sparkforensics-cli 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/export-template/docs/404.html +1 -1
  2. package/export-template/docs/assets/{app.CndaAS6v.js → app.DQTZyGL1.js} +1 -1
  3. package/export-template/docs/assets/chunks/@localSearchIndexroot.DppnXnDE.js +1 -0
  4. package/export-template/docs/assets/chunks/{VPLocalSearchBox.yJbZbsEo.js → VPLocalSearchBox.BkBIPFs6.js} +1 -1
  5. package/export-template/docs/assets/chunks/theme.DP0u1AUq.js +2 -0
  6. package/export-template/docs/assets/contributor-guide_architecture_board-widgets.md.CWpj01WU.js +1 -0
  7. package/export-template/docs/assets/contributor-guide_architecture_board-widgets.md.CWpj01WU.lean.js +1 -0
  8. package/export-template/docs/assets/contributor-guide_architecture_detector-contract.md.CgzUsQ6W.js +1 -0
  9. package/export-template/docs/assets/{contributor-guide_architecture_impact-estimation.md.DYCDPgkh.js → contributor-guide_architecture_impact-estimation.md.CooslVJt.js} +1 -1
  10. package/export-template/docs/assets/contributor-guide_architecture_state-and-history.md.C-xxn0q7.js +1 -0
  11. package/export-template/docs/assets/contributor-guide_architecture_state-and-history.md.C-xxn0q7.lean.js +1 -0
  12. package/export-template/docs/assets/contributor-guide_architecture_widget-rendering.md.R27gQrgY.js +1 -0
  13. package/export-template/docs/assets/contributor-guide_architecture_worker-protocol.md.IbnfNrV3.js +6 -0
  14. package/export-template/docs/assets/{style.DXOMCXxn.css → style.DSixAiZE.css} +1 -1
  15. package/export-template/docs/assets/{user-guide_alternative-log-retrieval.md.sU3KGarf.js → user-guide_alternative-log-retrieval.md.B4tPGIal.js} +1 -1
  16. package/export-template/docs/assets/{user-guide_alternative-log-retrieval.md.sU3KGarf.lean.js → user-guide_alternative-log-retrieval.md.B4tPGIal.lean.js} +1 -1
  17. package/export-template/docs/assets/user-guide_getting-started.md.BJvwLEIM.js +3 -0
  18. package/export-template/docs/assets/user-guide_getting-started.md.BJvwLEIM.lean.js +1 -0
  19. package/export-template/docs/assets/{user-guide_mcp-tools.md.C8MiIu7F.js → user-guide_mcp-tools.md.Vi3RoflJ.js} +3 -3
  20. package/export-template/docs/assets/{user-guide_mcp-tools.md.C8MiIu7F.lean.js → user-guide_mcp-tools.md.Vi3RoflJ.lean.js} +1 -1
  21. package/export-template/docs/assets/user-guide_run-comparison.md.CQc1aoU8.js +1 -0
  22. package/export-template/docs/assets/user-guide_run-comparison.md.CQc1aoU8.lean.js +1 -0
  23. package/export-template/docs/assets/user-guide_understanding-findings.md.DL1UDhvR.js +1 -0
  24. package/export-template/docs/assets/user-guide_understanding-findings.md.DL1UDhvR.lean.js +1 -0
  25. package/export-template/docs/contributor-guide/architecture/board-widgets.html +2 -2
  26. package/export-template/docs/contributor-guide/architecture/detector-contract.html +2 -2
  27. package/export-template/docs/contributor-guide/architecture/drill-down.html +1 -1
  28. package/export-template/docs/contributor-guide/architecture/impact-estimation.html +2 -2
  29. package/export-template/docs/contributor-guide/architecture/index.html +1 -1
  30. package/export-template/docs/contributor-guide/architecture/overview.html +1 -1
  31. package/export-template/docs/contributor-guide/architecture/state-and-history.html +2 -2
  32. package/export-template/docs/contributor-guide/architecture/widget-rendering.html +2 -2
  33. package/export-template/docs/contributor-guide/architecture/worker-protocol.html +2 -2
  34. package/export-template/docs/contributor-guide/contributing.html +1 -1
  35. package/export-template/docs/contributor-guide/development-setup.html +1 -1
  36. package/export-template/docs/contributor-guide/testing.html +1 -1
  37. package/export-template/docs/index.html +1 -1
  38. package/export-template/docs/tuning-reference/anti-patterns.html +1 -1
  39. package/export-template/docs/tuning-reference/aqe.html +1 -1
  40. package/export-template/docs/tuning-reference/bottleneck-broadcast-sizing.html +1 -1
  41. package/export-template/docs/tuning-reference/bottleneck-cold-start.html +1 -1
  42. package/export-template/docs/tuning-reference/bottleneck-duplicate-plan-subtree.html +1 -1
  43. package/export-template/docs/tuning-reference/bottleneck-failures.html +1 -1
  44. package/export-template/docs/tuning-reference/bottleneck-gc.html +1 -1
  45. package/export-template/docs/tuning-reference/bottleneck-job-failure-rate.html +1 -1
  46. package/export-template/docs/tuning-reference/bottleneck-memory-utilization.html +1 -1
  47. package/export-template/docs/tuning-reference/bottleneck-retry-waste.html +1 -1
  48. package/export-template/docs/tuning-reference/bottleneck-shuffle.html +1 -1
  49. package/export-template/docs/tuning-reference/bottleneck-skew.html +1 -1
  50. package/export-template/docs/tuning-reference/bottleneck-slow-host.html +1 -1
  51. package/export-template/docs/tuning-reference/bottleneck-small-files.html +1 -1
  52. package/export-template/docs/tuning-reference/bottleneck-spill.html +1 -1
  53. package/export-template/docs/tuning-reference/bottleneck-straggler.html +1 -1
  54. package/export-template/docs/tuning-reference/bottleneck-tiny-tasks.html +1 -1
  55. package/export-template/docs/tuning-reference/bottleneck-utilization.html +1 -1
  56. package/export-template/docs/tuning-reference/caching.html +1 -1
  57. package/export-template/docs/tuning-reference/cluster-config.html +1 -1
  58. package/export-template/docs/tuning-reference/config.html +1 -1
  59. package/export-template/docs/tuning-reference/data-formats.html +1 -1
  60. package/export-template/docs/tuning-reference/index.html +1 -1
  61. package/export-template/docs/tuning-reference/intro.html +1 -1
  62. package/export-template/docs/tuning-reference/joins.html +1 -1
  63. package/export-template/docs/tuning-reference/memory-model.html +1 -1
  64. package/export-template/docs/tuning-reference/metrics.html +1 -1
  65. package/export-template/docs/tuning-reference/partitioning.html +1 -1
  66. package/export-template/docs/tuning-reference/pyspark.html +1 -1
  67. package/export-template/docs/tuning-reference/shuffle.html +1 -1
  68. package/export-template/docs/tuning-reference/spark-architecture.html +1 -1
  69. package/export-template/docs/tuning-reference/table-formats.html +1 -1
  70. package/export-template/docs/user-guide/alternative-log-retrieval.html +2 -2
  71. package/export-template/docs/user-guide/getting-started.html +3 -3
  72. package/export-template/docs/user-guide/mcp-tools.html +4 -4
  73. package/export-template/docs/user-guide/run-comparison.html +2 -2
  74. package/export-template/docs/user-guide/understanding-findings.html +2 -2
  75. package/export-template/index.html +75 -79
  76. package/export-template/parser-worker-DyjiQvfP.js +112 -0
  77. package/export-template/sample-runs/sample-run.ndjson.gz +0 -0
  78. package/package.json +5 -4
  79. package/vendor-core/detectors.js +149 -24
  80. package/vendor-core/docs-content/detection/cache.md +4 -3
  81. package/vendor-core/docs-content/detection/chrn.md +4 -2
  82. package/vendor-core/docs-content/detection/local.md +2 -3
  83. package/vendor-core/docs-content/detection/mem.md +3 -3
  84. package/vendor-core/docs-content/detection/spec.md +4 -3
  85. package/vendor-core/evidence-report.js +1 -1
  86. package/vendor-core/parser-worker.js +2 -2
  87. package/vendor-core/run-comparison.js +21 -2
  88. package/export-template/docs/assets/chunks/@localSearchIndexroot.DNY8bVcl.js +0 -1
  89. package/export-template/docs/assets/chunks/theme.Df2VAG9w.js +0 -2
  90. package/export-template/docs/assets/contributor-guide_architecture_board-widgets.md.B-OsL91z.js +0 -1
  91. package/export-template/docs/assets/contributor-guide_architecture_board-widgets.md.B-OsL91z.lean.js +0 -1
  92. package/export-template/docs/assets/contributor-guide_architecture_detector-contract.md.BOeH4d1J.js +0 -1
  93. package/export-template/docs/assets/contributor-guide_architecture_state-and-history.md.m3S3UdMk.js +0 -1
  94. package/export-template/docs/assets/contributor-guide_architecture_state-and-history.md.m3S3UdMk.lean.js +0 -1
  95. package/export-template/docs/assets/contributor-guide_architecture_widget-rendering.md.DbqPf2OT.js +0 -1
  96. package/export-template/docs/assets/contributor-guide_architecture_worker-protocol.md.B93qJ_tT.js +0 -6
  97. package/export-template/docs/assets/user-guide_getting-started.md.DtEM37MK.js +0 -3
  98. package/export-template/docs/assets/user-guide_getting-started.md.DtEM37MK.lean.js +0 -1
  99. package/export-template/docs/assets/user-guide_run-comparison.md.S0TWWmLY.js +0 -1
  100. package/export-template/docs/assets/user-guide_run-comparison.md.S0TWWmLY.lean.js +0 -1
  101. package/export-template/docs/assets/user-guide_understanding-findings.md.D0R_Y-R2.js +0 -1
  102. package/export-template/docs/assets/user-guide_understanding-findings.md.D0R_Y-R2.lean.js +0 -1
  103. package/export-template/parser-worker-QqyEE4m9.js +0 -64
  104. /package/export-template/docs/assets/{contributor-guide_architecture_detector-contract.md.BOeH4d1J.lean.js → contributor-guide_architecture_detector-contract.md.CgzUsQ6W.lean.js} +0 -0
  105. /package/export-template/docs/assets/{contributor-guide_architecture_impact-estimation.md.DYCDPgkh.lean.js → contributor-guide_architecture_impact-estimation.md.CooslVJt.lean.js} +0 -0
  106. /package/export-template/docs/assets/{contributor-guide_architecture_widget-rendering.md.DbqPf2OT.lean.js → contributor-guide_architecture_widget-rendering.md.R27gQrgY.lean.js} +0 -0
  107. /package/export-template/docs/assets/{contributor-guide_architecture_worker-protocol.md.B93qJ_tT.lean.js → contributor-guide_architecture_worker-protocol.md.IbnfNrV3.lean.js} +0 -0
@@ -1,6 +0,0 @@
1
- import{_ as o,o as t,c as d,a5 as a}from"./chunks/framework.DSg0KOwT.js";const u=JSON.parse('{"title":"Worker protocol","description":"","frontmatter":{},"headers":[],"relativePath":"contributor-guide/architecture/worker-protocol.md","filePath":"contributor-guide/architecture/worker-protocol.md"}'),c={name:"contributor-guide/architecture/worker-protocol.md"};function s(r,e,i,n,l,p){return t(),d("div",null,[...e[0]||(e[0]=[a(`<h1 id="worker-protocol" tabindex="-1">Worker protocol <a class="header-anchor" href="#worker-protocol" aria-label="Permalink to &quot;Worker protocol&quot;">​</a></h1><h2 id="message-protocol" tabindex="-1">Message protocol <a class="header-anchor" href="#message-protocol" aria-label="Permalink to &quot;Message protocol&quot;">​</a></h2><p>Worker to main:</p><ul><li><code>app</code>, <code>stage</code>, <code>sql</code>, <code>executor</code>, <code>job</code>, <code>progress</code>: progressive, posted as the parser reads.</li><li><code>sqlPlan</code> (<code>{ type: &#39;sqlPlan&#39;, data: { executionId, planTree } }</code>): posted by <code>endSqlExecution</code> once a SQL execution&#39;s plan tree resolves.</li><li><code>runAggregates</code>: one whole-run core-time-series summary (busy-core-ms, peak concurrency, per-stage task-duration sums), emitted just before <code>done</code>.</li><li><code>stageExecutorMetrics</code>: the post-completion re-post described in <a href="./overview.html#streaming">Streaming</a>, also emitted just before <code>done</code>.</li><li><code>done</code>, <code>taskData</code>, <code>error</code>.</li></ul><p>A History Server failure is always the typed, display-safe payload <code>{ type: &#39;error&#39;, source: &#39;shs&#39;, code }</code>, where <code>code</code> is one of <code>local-server-unavailable</code>, <code>upstream-unreachable</code>, <code>application-not-found</code>, <code>access-or-upstream-failure</code>, or <code>invalid-event-log</code>. It never carries an upstream message, URL, status, or response body.</p><p>Evidence availability has no dedicated worker message: the final <code>app</code> message carries a compact <code>evidenceInputs</code> counter summary, and <code>done.skippedLines</code> supplies its parse-integrity input.</p><p>Main to worker: <code>parse</code>, <code>parseFiles(files)</code> (rolling <code>eventlog_v2_*</code> directories, one continuous stream across files), <code>parseFromUrl({ baseUrl, appId, attemptId })</code>, and <code>getTaskData(stageId)</code>. The SHS request object is normalized before it reaches the worker: <code>{ baseUrl: string, appId: string, attemptId: string | null }</code>.</p><p><code>taskData</code> uses structured-clone (<code>.slice()</code>) so the worker retains its own <code>Float64Array</code> for re-renders.</p><p>Post-parse prefetch: after <code>done</code>, main runs <code>analyzer.ts</code> to build the bottleneck catalog, then fires parallel <code>getTaskData</code> for every flagged stage so their widgets render immediately. Unflagged stages are on-demand.</p><h3 id="evidence-availability-worker-input" tabindex="-1">Evidence-availability worker input <a class="header-anchor" href="#evidence-availability-worker-input" aria-label="Permalink to &quot;Evidence-availability worker input&quot;">​</a></h3><p><code>packages/core/src/event-handlers.ts</code>&#39;s <code>createState()</code>/per-event handlers start and increment this fixed <code>evidenceInputs</code> shape on the normalized app model:</p><div class="language-text vp-adaptive-theme"><button title="Copy Code" class="copy"></button><span class="lang">text</span><pre class="shiki shiki-themes github-light github-dark vp-code" tabindex="0"><code><span class="line"><span>environmentUpdates, applicationEnds, stageSubmissions, rddStorageSnapshots,</span></span>
2
- <span class="line"><span>sqlExecutions, resolvedSqlPlans, executorMetricRows, taskRecords</span></span></code></pre></div><p>The counters are a structured-clone-safe summary: they contain counts, not raw events, task records, host names, SQL text, paths, or Spark-property values. The final <code>app</code> message snapshots the counters after all input is processed, immediately before <code>done</code>; a consumer must not add a second worker message just for the ledger. <code>app</code> messages are also emitted mid-parse from <code>SparkListenerApplicationStart</code> and <code>SparkListenerEnvironmentUpdate</code>; those snapshots are partial and non-authoritative. Only the terminal <code>app</code> message emitted by <code>emitParseCompletion</code> (the one immediately before <code>done</code>) should be used for evidence-availability conclusions. On the main thread, <code>useIngest</code> combines the normalized <code>AppModel</code> with <code>done.skippedLines</code>, derives the ledger before calling <code>analyze()</code>, and stores it as <code>appModel.evidenceAvailability</code>.</p><h3 id="evidence-availability-contract-v1" tabindex="-1">Evidence-availability contract (V1) <a class="header-anchor" href="#evidence-availability-contract-v1" aria-label="Permalink to &quot;Evidence-availability contract (V1)&quot;">​</a></h3><p><code>packages/core/src/evidence-availability.ts</code> is the single reusable taxonomy for the browser, future report output, and future headless consumers. Its serialized ledger shape is <code>{ schemaVersion: 1, entries: EvidenceAvailabilityEntry[] }</code>. Entries are ordered by the following fixed eight-key enum:</p><div class="language-text vp-adaptive-theme"><button title="Copy Code" class="copy"></button><span class="lang">text</span><pre class="shiki shiki-themes github-light github-dark vp-code" tabindex="0"><code><span class="line"><span>executorMetrics, rddStorageSnapshots, sqlPlan, sparkConfiguration,</span></span>
3
- <span class="line"><span>taskCoreTime, infrastructureContext, sourceContext, costContext</span></span></code></pre></div><p>Each entry has the stable fields <code>key</code>, <code>state</code>, <code>reasonCode</code>, <code>summary</code>, and optional <code>evidence</code>. The closed V1 state enum is:</p><div class="language-text vp-adaptive-theme"><button title="Copy Code" class="copy"></button><span class="lang">text</span><pre class="shiki shiki-themes github-light github-dark vp-code" tabindex="0"><code><span class="line"><span>present, disabled, notEmitted, notApplicable, outsideEventLog, unknown</span></span></code></pre></div><p>The closed V1 reason-code enum is:</p><div class="language-text vp-adaptive-theme"><button title="Copy Code" class="copy"></button><span class="lang">text</span><pre class="shiki shiki-themes github-light github-dark vp-code" tabindex="0"><code><span class="line"><span>observed, explicitlyDisabled, noObservedExecutorMetrics,</span></span>
4
- <span class="line"><span>noObservedStageSubmission, noRddStorageSnapshot, noResolvedSqlPlan,</span></span>
5
- <span class="line"><span>noSqlExecution, noEnvironmentUpdate, noTaskRecords, noUsableCoreTimeAggregate,</span></span>
6
- <span class="line"><span>outsideEventLogScope, parseIncomplete</span></span></code></pre></div><p><code>summary</code> is domain-agnostic presentation copy derived from the reason code; the enum values, not labels, are the machine contract. Optional <code>evidence</code> is limited to safe compact provenance of the exact <code>{ eventType, count }</code> shape. <code>eventType</code> values are pinned to the exact <code>evidenceInputs</code> counter keys; they are not shortened or aliased. It must never include raw Spark-property values, host names, paths, SQL text, task records, raw-event identifiers, or other event payloads.</p><table tabindex="0"><thead><tr><th>Key</th><th>Proven <code>present</code> evidence</th><th>Trustworthy absence / boundary result</th></tr></thead><tbody><tr><td><code>executorMetrics</code></td><td><code>executorMetricRows &gt; 0</code></td><td>Explicit observed <code>spark.eventLog.logStageExecutorMetrics=false</code> is <code>disabled</code> / <code>explicitlyDisabled</code>; otherwise <code>notEmitted</code> / <code>noObservedExecutorMetrics</code>. Observed metrics win over the explicit setting.</td></tr><tr><td><code>rddStorageSnapshots</code></td><td><code>rddStorageSnapshots &gt; 0</code> from <code>SparkListenerStageSubmitted</code></td><td>No stage submissions is <code>notEmitted</code> / <code>noObservedStageSubmission</code>; stages submitted without any <code>RDD Info</code> rows is <code>notEmitted</code> / <code>noRddStorageSnapshot</code>. This is RDD snapshot evidence, not block-update telemetry.</td></tr><tr><td><code>sqlPlan</code></td><td><code>resolvedSqlPlans &gt; 0</code></td><td>A SQL execution without a resolved plan is <code>notEmitted</code> / <code>noResolvedSqlPlan</code>; no SQL execution is <code>notApplicable</code> / <code>noSqlExecution</code>.</td></tr><tr><td><code>sparkConfiguration</code></td><td><code>environmentUpdates &gt; 0</code></td><td><code>notEmitted</code> / <code>noEnvironmentUpdate</code>; a normalized empty config object alone is not evidence.</td></tr><tr><td><code>taskCoreTime</code></td><td><code>taskRecords &gt; 0</code> and a usable <code>runAggregates.perStage</code> task count</td><td>No task records is <code>notEmitted</code> / <code>noTaskRecords</code>; task records with no usable aggregate are <code>notEmitted</code> / <code>noUsableCoreTimeAggregate</code>. An empty aggregate object is not usable evidence.</td></tr><tr><td><code>infrastructureContext</code></td><td>none</td><td>Always <code>outsideEventLog</code> / <code>outsideEventLogScope</code>.</td></tr><tr><td><code>sourceContext</code></td><td>none</td><td>Always <code>outsideEventLog</code> / <code>outsideEventLogScope</code>.</td></tr><tr><td><code>costContext</code></td><td>none</td><td>Always <code>outsideEventLog</code> / <code>outsideEventLogScope</code>.</td></tr></tbody></table><p>Parse integrity is fail-closed. A parse is trustworthy only when it skipped no malformed lines and observed an application-end event. For an untrustworthy parse, proof already observed remains <code>present</code>, and an explicitly observed executor-metrics disablement remains <code>disabled</code>; every conclusion based on absence or irrelevance becomes <code>unknown</code> / <code>parseIncomplete</code>. The three outside-event-log product boundaries remain <code>outsideEventLog</code>. In particular, <code>notEmitted</code> and <code>notApplicable</code> are never favorable measurements inferred from an incomplete parse.</p><p>Availability is model metadata, not a detector or finding: it never changes detector thresholds or ordering, impact band, catalog/scorecard counts, no-bottleneck behavior, or detector suppression. <code>session-snapshot.ts</code> captures and restores <code>evidenceAvailability</code> with the normalized model, so a recent-file switch retains the same ledger without reparsing.</p><h3 id="portable-evidence-report-v1" tabindex="-1">Portable evidence report (V1) <a class="header-anchor" href="#portable-evidence-report-v1" aria-label="Permalink to &quot;Portable evidence report (V1)&quot;">​</a></h3><p><code>packages/core/src/evidence-report.ts</code>&#39;s <code>buildEvidenceReport(appModel, { redact })</code> returns <code>{ markdown, json }</code>: a self-contained, byte-stable document that runs the detectors over an <code>appModel</code> and serializes the result for sharing outside the tool. Raw task records are never included; identifier redaction (app id + host names → <code>app-1</code>/<code>host-1</code> pseudonyms via <code>packages/core/src/redact.ts</code>) is opt-in with <code>{ redact: true }</code>. The JSON is pinned by <code>EVIDENCE_SCHEMA_VERSION</code> (currently <code>3</code>, surfaced as <code>json.schemaVersion</code>) and has this fixed top-level key order:</p><div class="language-text vp-adaptive-theme"><button title="Copy Code" class="copy"></button><span class="lang">text</span><pre class="shiki shiki-themes github-light github-dark vp-code" tabindex="0"><code><span class="line"><span>schemaVersion, summary, evidenceAvailability, detectors, findings, recommendations, cleanChecks</span></span></code></pre></div><ul><li><code>summary</code> is the run header: <code>{ app: { id, name, sparkVersion }, stageCount, jobCount, sqlExecutionCount, findingCount, impactBandCounts }</code>.</li><li><code>evidenceAvailability</code> is the ledger above (or <code>null</code> when absent).</li><li><code>detectors</code> is <code>detectorCatalog()</code> output: one <code>{ type, version, scope, thresholds, docAnchor }</code> per detector, in <code>DETECTORS</code> order, so the exact threshold set that produced each finding travels with the evidence.</li><li><code>findings</code> are deterministically sorted rows (impact band → type → stage → id), each with a stable <code>id</code>, <code>tag</code>, core columns, an always-present <code>actionLabel</code>, and an <code>evidence</code> sub-object for non-core fields; <code>confidence</code>/ <code>validationRequired</code>/<code>docAnchor</code> appear only when the detector emitted them.</li><li><code>recommendations</code> is the impact-ranked <code>buildRecommendationRollup</code> output (<code>packages/core/src/recommendation-rollup.ts</code>), and <code>cleanChecks</code> lists every detector type that fired zero findings this run: see the 2026-09-03 update below.</li></ul><p>Determinism holds because detector order, finding sort, and object key order are all fixed, so a given <code>appModel</code> serializes identically across calls.</p><p>Redaction enumerates hosts two ways: by walking the findings tree for every string value under a key literally named <code>host</code> (<code>evidence.host</code>, <code>evidence.failedTaskDetails[].host</code>, <code>evidence.retriedTaskDetails[].host</code>, and any future nested <code>host</code> field, all covered without enumerating paths), and by scanning every string value for EC2-style hostnames / bare IPv4 tokens. So identifiers that surface only in free text (recommendation copy, a <code>stageFailed</code> failure-reason value) are pseudonymized too. Pseudonym numbering uses a numeric-aware sort, so re-redacting an already-redacted report is a no-op even past <code>host-10</code>.</p><p>The Markdown rendering mirrors the JSON&#39;s AC3 field set: each finding block prints its <code>detector version</code>, its sorted <code>evidence</code> entries (byte-magnitude keys humanized), and the report ends with a <code>## Detectors</code> catalog carrying the version + threshold set. A finding&#39;s <code>impactEstimate</code> (when its <code>basis</code> isn&#39;t <code>&#39;informational&#39;</code>) prints as its own <code>- impact: </code> line (<code>Est. &lt;low&gt;-&lt;high&gt;</code> and/or the raw-waste figure, plus <code>estimateMethod</code>), via <code>renderImpactEstimate</code>/<code>formatWallClockRange</code>/<code>formatRawWaste</code> in <code>packages/core/src/evidence-report.ts</code>. <code>EvidenceExport</code> names downloads <code>evidence-&lt;appId&gt;[-redacted].&lt;md|json&gt;</code>, taking the app id from the (already pseudonymized when redacting) report so a redacted file never leaks the real id and is never name-identical to a raw export.</p><p>Decision 9 (design spec): <code>Finding</code>&#39;s <code>impactEstimate</code> field, plus the <code>utilizationFraction</code>/<code>memorySize</code>/<code>diskSize</code>/<code>numCachedPartitions</code>/<code>numPartitions</code> instrumentation fields the impact estimator reads, were added without bumping <code>EVIDENCE_SCHEMA_VERSION</code> past <code>1</code>. Both additions are purely optional and ride <code>Finding</code>&#39;s existing optional-field-plus-catch-all convention, so an evidence report built before these fields existed still deserializes and compares byte-for-byte against one built after: nothing about the schema&#39;s stability guarantee changed, only its surface grew. A future reader who notices <code>impactEstimate</code> in the JSON without a schema bump is looking at this deliberate call, not an oversight.</p><p>2026-08-30 update: <code>EVIDENCE_SCHEMA_VERSION</code> was bumped to <code>2</code> for the occupancy-weighted attribution redesign (see <a href="./impact-estimation.html#occupancy-weighted-attribution">Occupancy-weighted attribution</a>): <code>ImpactEstimate</code>&#39;s shape changed from <code>{low, high}</code> to <code>{basis, wallClock, estimateMethod, rawWaste?}</code>, a real, non-additive breaking change to a field this same Decision 9 previously shipped without a bump. <code>impactEstimate</code> had zero consumers outside <code>packages/core/src/impact-estimator.ts</code> and its own tests at the time of this bump (confirmed by grep across <code>src/view/*</code> and <code>packages/core/src/evidence-report.ts</code>), so no other code needed migrating alongside it.</p><p><code>FindingRow</code>&#39;s schema was extended to surface <code>impactEstimate</code> as a first-class column without further bumping <code>EVIDENCE_SCHEMA_VERSION</code> past <code>2</code>, consistent with <code>Finding</code>&#39;s existing optional-field-plus-catch-all convention. It appears after the pinned core columns (<code>id</code>, <code>type</code>, <code>impactBand</code>, <code>stageId</code>, <code>metric</code>, <code>value</code>, <code>recommendation</code>, <code>detectorVersion</code>, plus optional but pinned <code>confidence</code>, <code>validationRequired</code>, <code>docAnchor</code>) without displacing any of them; byte-for-byte deserializability of existing reports is preserved. <code>FindingRow.impactEstimate</code> carries the full contract documented in <a href="./impact-estimation.html#occupancy-weighted-attribution">Impact estimation</a> (basis, wallClock, estimateMethod, rawWaste).</p><p>2026-09-03 update: the &quot;Fix These First&quot; dashboard redesign (impact-ranked recommendation rollup, short per-finding action labels, a clean-checks table) was UI-only when it shipped; this update ports the underlying data into <code>buildEvidenceReport()</code> so the CLI (<code>packages/cli/bin/sparkforensics-analyze.mjs</code>) and the MCP tool (<code>diagnoseRun</code> in <code>packages/core/src/mcp-tools.ts</code>) get it too, not just the web markdown/JSON download. Three additions, all purely additive, so this does not bump <code>EVIDENCE_SCHEMA_VERSION</code> past <code>2</code>, the same rationale as the <code>impactEstimate</code> addition immediately above: <code>FindingRow.actionLabel</code> is now always present (a short imperative label like &quot;Reduce shuffle size&quot;), sourced from a new core module, <code>packages/core/src/finding-action-label.ts</code>&#39;s <code>coreFindingActionLabel</code>, extracted from the (type, discriminant) switch statement that used to live only in the view layer (<code>src/view/finding-action-label.ts</code>, which now wraps the core function and layers its own <code>REGISTRY</code> fallback on top). <code>EvidenceReportJson.recommendations</code> is the same impact-ranked <code>buildRecommendationRollup</code> grouping (<code>packages/core/src/recommendation-rollup.ts</code>) that <code>FixTheseFirst.tsx</code> renders, so CLI/MCP/download consumers get the same &quot;what&#39;s the highest-impact fix&quot; ranking the dashboard shows, without changing the existing <code>findings</code> array&#39;s own impact-band-sorted order at all. <code>EvidenceReportJson.cleanChecks</code> lists every detector type that fired zero findings this run, each with <code>getThresholdSummary</code>&#39;s one-line &quot;what would have tripped it&quot; sentence; unlike the dashboard&#39;s <code>Alerts.tsx</code> clean-checks table, it deliberately includes the one &quot;always-mounted&quot; reference type (<code>coreLocality</code>) even when it has no findings, since a flat evidence report has no separate always-visible surface for it to already appear on the way that widget does on the board.</p><h3 id="finding-identity" tabindex="-1">Finding identity <a class="header-anchor" href="#finding-identity" aria-label="Permalink to &quot;Finding identity&quot;">​</a></h3><p>Every finding <code>analyzer.ts</code> emits carries a stable <code>id</code> (<code>push()</code>&#39;s <code>findingId()</code> choke point, FNV-1a hash over <code>type | location | metric | value | discriminators</code>) and a <code>detectorVersion</code> (from the emitting <code>DETECTORS</code> entry). The two are deliberately decoupled: <code>id</code> is derived only from a finding&#39;s evidence tuple, never from <code>detectorVersion</code>, so a threshold or logic tweak that bumps a detector&#39;s <code>version</code> does not change the <code>id</code> of findings it still emits at the same location/metric. A saved reference (dashboard bookmark, exported report row, future URL-restored filter) keeps pointing at the same logical finding across detector revisions; <code>detectorVersion</code> is separate provenance metadata for &quot;which ruleset produced this,&quot; not part of identity. See <code>packages/core/test/analyzer-finding-identity.test.js</code> for the decoupling proof.</p><p><code>id</code> stability holds for equivalent reruns of the same schema/analyzer version on the same input. Changing the id-derivation rule itself (the hash algorithm, or which fields feed the location key/discriminators) is an intentional breaking change and must bump <code>EVIDENCE_SCHEMA_VERSION</code> (<code>packages/core/src/evidence-report.ts</code>); there is no separate id-scheme version.</p><h3 id="headless-analysis-cli-v1" tabindex="-1">Headless analysis CLI (V1) <a class="header-anchor" href="#headless-analysis-cli-v1" aria-label="Permalink to &quot;Headless analysis CLI (V1)&quot;">​</a></h3><p><code>packages/cli/bin/sparkforensics-analyze.mjs</code> runs the same parser + detector contracts outside the browser, for CI. It accepts a single event-log file or a rolling-log directory, drives <code>runParse</code>/<code>runParseFiles</code> (<code>packages/core/src/parser-worker.ts</code>) with a Node-only File-like shim (<code>packages/core/src/cli/collect-run.ts</code>), and writes the exact <code>buildEvidenceReport</code> JSON schema described above: one format, not a second. Alternatively, <code>--shs-base-url &lt;url&gt; --app-id &lt;id&gt; [--attempt-id &lt;id&gt;]</code> fetches the run from a Spark History Server instead (mutually exclusive with the positional file/directory argument), calling <code>resolveFromShs</code> (<code>packages/core/src/shs-load.ts</code>, shared with the MCP server&#39;s SHS source path below) directly; no dependency on the <code>packages/server</code> package. A failed SHS fetch reports its message to <code>stderr</code> and exits <code>2</code>, same as a local file that can&#39;t be parsed.</p><p>Optional CLI-flag budgets (<code>--max-runtime &lt;ms&gt;</code>, <code>--max-spill &lt;gb&gt;</code>, <code>--max-skew &lt;ratio&gt;</code>, <code>--max-failed-task-rate &lt;pct&gt;</code>, <code>--min-efficiency &lt;pct&gt;</code>) are evaluated in <code>packages/core/src/cli/budgets.ts</code> against the existing finding catalog (<code>analyze()</code>) and <code>computeEfficiencyModel</code>; there is no second rule engine. A budget whose required evidence is missing (e.g. the run never emitted <code>ApplicationEnd</code>, or has no usable per-task <code>runAggregates</code>) is reported as inconclusive (<code>stderr</code> warning) rather than silently passing, and gets its own exit code distinct from both pass and violation. Exit codes: <code>0</code> pass, <code>1</code> a configured budget was violated, <code>2</code> the input could not be parsed at all, <code>3</code> no violations but at least one budget was inconclusive. A violation always wins over an inconclusive result in the same run (exit <code>1</code>, not <code>3</code>).</p><h3 id="mcp-server-v1" tabindex="-1">MCP server (V1) <a class="header-anchor" href="#mcp-server-v1" aria-label="Permalink to &quot;MCP server (V1)&quot;">​</a></h3><p><code>packages/core/src/mcp-server-factory.ts</code>&#39;s <code>createMcpServer()</code> registers 6 tools: <code>diagnose_run</code> (thresholded findings + remediation text), <code>get_run_summary</code> (app/stage/job/sql counts and duration, no findings), <code>compare_runs</code> (categorized findings delta + metric deltas between two runs), <code>evaluate_budgets</code> (pass/fail budget thresholds against one run, optionally with a second run for regression/fail-on-introduced budgets: the MCP side of the CLI&#39;s <code>evaluateBudgets()</code> gating), <code>get_finding_evidence</code> (raw evidence bundle for one finding, for drill-down after <code>diagnose_run</code>), and <code>get_finding_documentation</code> (detection/tuning reference docs for one finding type, independent of any run). None re-implement detector logic; all repackage <code>analyze</code>/<code>buildEvidenceReport</code>/<code>compareRuns</code>/<code>captureSnapshot</code>/<code>evaluateBudgets</code> from <code>packages/core/src/mcp-tools.ts</code>, which resolves a <code>source</code> (event-log <code>path</code>, or an SHS <code>shsBaseUrl</code>/<code>appId</code>/<code>attemptId</code> triple) into a cached <code>AppModel</code>. The SHS source path calls <code>resolveFromShs</code> (<code>packages/core/src/shs-load.ts</code>, also used directly by the CLI&#39;s <code>--shs-base-url</code> mode above), which reuses two extractions shared with the browser ingestion flow: <code>fetchShsEventLog</code> (<code>packages/core/src/proxy.js</code>) fetches the zip, and <code>decodeShsArchive</code> (<code>packages/core/src/shs-fetch.ts</code>, re-exported from <code>parser-worker.ts</code>&#39;s barrel) decodes it into a parsed <code>AppModel</code>, the same split <code>runParseFromUrl</code> itself calls into.</p><p>Two transports connect to that one factory: <code>packages/mcp/bin/sparkforensics-mcp.mjs</code> (stdio, for local MCP clients) and <code>packages/server/index.js</code>&#39;s <code>/mcp</code> route (streamable HTTP, for the local server). The run cache (<code>packages/core/src/mcp-tools.ts</code>) is a module-level LRU (cap 8 and 15-minute idle TTL by default, overridable via <code>SPARKFORENSICS_MCP_CACHE_CAP</code> and <code>SPARKFORENSICS_MCP_CACHE_TTL_MS</code>, lazily swept on access) keyed by resolved source (path mtime, or SHS baseUrl+appId+attemptId), so a client mints a <code>runId</code> once via <code>resolveOrCreateRun</code> and reuses it across subsequent tool calls instead of re-parsing.</p><p>Every tool failure comes back as <code>{isError: true, content: [...], structuredContent: {code}}</code>, never an HTTP-status-shaped error; <code>code</code> is one of the 5 existing SHS codes (<code>SHS_ERROR_CODES</code>, <code>packages/core/src/shs-request.js</code>) plus <code>run-not-found</code>, <code>finding-not-found</code>, <code>invalid-event-log</code> (also covers a nonexistent <code>path</code> source), and <code>archive-too-large</code> (SHS archive over the <code>SPARKFORENSICS_MAX_ARCHIVE_BYTES</code> byte cap, default 1 GiB, because the MCP path buffers the whole archive in memory, unlike the streaming <code>/shs-proxy</code> route).</p><p><code>scripts/vendor-core.mjs</code> (shared by <code>packages/cli</code>, <code>packages/mcp</code>, and <code>packages/server</code>&#39;s <code>prepack</code> scripts) vendors <code>packages/core/src/</code> wholesale into each package&#39;s own <code>vendor-core/</code> at pack time, pre-stripping TypeScript to plain <code>.js</code> (Node&#39;s native TS stripping refuses to run on <code>.ts</code> files under <code>node_modules</code>, which is exactly where a published <code>vendor-core/</code> lands). Each package&#39;s bin/entry point resolves its needed module from <code>vendor-core/</code> if present, else falls back to the real <code>packages/core/src/</code> sibling loaded as <code>.ts</code> directly (<code>packages/server/index.js</code> mirrors <code>resolveStaticRoot</code>&#39;s <code>public/</code>-vs-<code>../dist</code> pattern for this same fallback).</p><h2 id="typescript-core-and-runtime-event-validation" tabindex="-1">TypeScript core and runtime event validation <a class="header-anchor" href="#typescript-core-and-runtime-event-validation" aria-label="Permalink to &quot;TypeScript core and runtime event validation&quot;">​</a></h2><p>All of <code>src/</code> (browser SPA) and <code>packages/core/src/</code> (shared analysis logic) is strict TypeScript; the only plain-<code>.js</code> holdouts are the two vendored third-party decompressors, <code>packages/core/src/vendor/fflate.js</code> and <code>packages/core/src/vendor/fzstd.js</code> (left untouched deliberately: vendored code, not project code). Every remaining import of a same-repo module uses a <code>.ts</code> specifier (e.g. <code>import { dispatchLine } from &#39;./event-handlers.ts&#39;</code>), not <code>.js</code>: the CLI and MCP entrypoints (<code>packages/cli/bin/sparkforensics-analyze.mjs</code>, <code>packages/mcp/bin/sparkforensics-mcp.mjs</code>) run under plain Node&#39;s ESM resolver, which cannot remap a <code>.js</code> specifier to a same-named <code>.ts</code> file the way Vite/Vitest&#39;s bundler-style resolver can. <code>tsconfig.json</code> sets <code>&quot;allowImportingTsExtensions&quot;: true</code> to make this legal.</p><p>Event schema validation lives in <code>packages/core/src/event-schemas.ts</code>: one zod schema per <code>SparkListener*</code> event variant the parser understands (15 total: <code>LogStart</code>, <code>ApplicationStart</code>, <code>EnvironmentUpdate</code>, <code>ApplicationEnd</code>, <code>JobStart</code>, <code>JobEnd</code>, <code>StageSubmitted</code>, <code>StageCompleted</code>, <code>StageExecutorMetrics</code>, <code>TaskEnd</code>, the three SQL-execution-UI listener events, <code>ExecutorAdded</code>, <code>ExecutorRemoved</code>), combined into <code>SparkEventSchema = z.discriminatedUnion(&#39;Event&#39;, [...])</code>. <code>processEvent</code>&#39;s switch (<code>event-handlers.ts</code>) consumes the resulting <code>SparkEvent</code> union type directly, so a schema change and a handler&#39;s expectations can&#39;t silently drift apart.</p><p>The recursive <code>sparkPlanInfo.children</code> tree carried on SQL-execution-start events is validated by <code>parseSparkPlanInfoTree</code>, an iterative, explicit heap-allocated-stack parser, deliberately not <code>z.lazy()</code>. A real plan tree&#39;s depth is unbounded, and attacker-uncontrolled input should never hand zod&#39;s own recursive schema resolution an arbitrarily deep structure to walk. The iterative parser shallow-validates one node at a time via <code>z.object(...)</code> and builds the tree itself, capping at <code>MAX_PLAN_DEPTH = 500</code> (throws past that). This mirrors <code>packages/core/src/plan-tree-walk.ts</code>&#39;s <code>walkPlanTree</code>, which uses the same iterative-over-recursive approach for the <em>resolved</em> tree; <code>event-schemas.ts</code> applies it one layer earlier, to the raw JSON before it becomes a tree at all.</p><p>There are two external-data boundaries, the two places this codebase parses data it does not control. Both now run that data through a schema, and both treat a validation failure the same way: a silent skip, not a distinct error.</p><ul><li><code>dispatchLine</code> (<code>event-handlers.ts</code>): after <code>JSON.parse</code> succeeds, a line whose <code>Event</code> value is one of the 15 modeled types but fails that type&#39;s own schema now increments <code>skippedLines</code> (previously: no shape validation existed at all, and a malformed event silently corrupted downstream state with no signal anywhere). An <code>Event</code> value outside the 15 modeled types is still silently ignored without incrementing <code>skippedLines</code>, unchanged from before migration (see the note below on why the broader design was rejected).</li><li><code>shs-fetch.ts</code>: on a non-OK response from the local SHS proxy, the JSON error envelope is validated against <code>ShsProxyErrorBodySchema</code> (<code>packages/core/src/shs-schemas.ts</code>, <code>{ code: string }</code>, <code>.passthrough()</code>). A body that isn&#39;t valid JSON, or is JSON but fails that schema, falls back to the generic <code>access-or-upstream-failure</code> code: the same silent-skip treatment as a malformed log line, collapsing what could have been a separate &quot;malformed SHS response&quot; error code into the existing generic one.</li></ul><p>Neither boundary distinguishes &quot;malformed JSON&quot; from &quot;wrong shape&quot; from &quot;unrecognized variant&quot; in what it reports outward: all three collapse into the same skip/fallback path. That was a deliberate scope decision. The correction below says why the <em>line</em> boundary stops there rather than flagging every unrecognized event type.</p><blockquote><p>Correction made during migration, not part of the original design: an earlier draft counted <em>any</em> <code>Event</code> value outside the 15 modeled types toward <code>skippedLines</code>, not just ones that fail their own schema. Running that design against real Spark event logs (which always contain plenty of ordinary event types this tool has never modeled: <code>TaskStart</code>, <code>BlockManagerAdded</code>, <code>ExecutorMetricsUpdate</code>, and others, always silently ignored pre-migration) pushed <code>skippedLines</code> from 0 to the tens of thousands on completely healthy logs. That would have tripped <code>evidence-availability.ts</code>&#39;s fail-closed <code>trustworthy</code> gate and shown a false &quot;malformed JSON&quot; warning on every real file. Caught in review against real fixtures, not synthetic ones; fixed to the narrower rule described above before merging. <code>evidence-availability.ts</code>&#39;s gate itself (<code>trustworthy = skippedLines === 0 &amp;&amp; applicationEnds &gt; 0</code>) needed no code change once this was fixed: it was already correct, the input feeding it was not.</p></blockquote><p>The exhaustiveness convention is <code>packages/core/src/assert-never.ts</code>. <code>assertNever(x: never): never</code> throws at runtime and, more importantly, fails <code>tsc</code> at compile time if <code>x</code> is not actually <code>never</code>, i.e. if some case of a union type isn&#39;t handled. Used today at the <code>default</code> arm of <code>event-handlers.ts</code>&#39;s <code>processEvent</code> switch (over <code>SparkEvent</code>) and <code>analyzer.ts</code>&#39;s scope-dispatch switch (over a detector&#39;s <code>scope: &#39;stage&#39; | &#39;sql&#39; | &#39;app&#39; | &#39;config&#39;</code>). It is the project&#39;s standard pattern for any future exhaustive switch or dispatch over a closed union: add <code>default: return assertNever(x);</code> (or the closest non-returning equivalent) so that adding a new union member without updating every consumer becomes a compile error instead of a silent runtime gap.</p>`,55)])])}const m=o(c,[["render",s]]);export{u as __pageData,m as default};
@@ -1,3 +0,0 @@
1
- import{_ as a,o as t,c as i,a5 as o}from"./chunks/framework.DSg0KOwT.js";const g=JSON.parse('{"title":"Getting started","description":"","frontmatter":{},"headers":[],"relativePath":"user-guide/getting-started.md","filePath":"user-guide/getting-started.md"}'),s={name:"user-guide/getting-started.md"};function n(r,e,d,l,h,c){return t(),i("div",null,[...e[0]||(e[0]=[o(`<h1 id="getting-started" tabindex="-1">Getting started <a class="header-anchor" href="#getting-started" aria-label="Permalink to &quot;Getting started&quot;">​</a></h1><p>SparkForensics reads a Spark History Server event log and turns it into a dashboard of flagged bottlenecks. No server or account required.</p><h2 id="load-a-run" tabindex="-1">Load a run <a class="header-anchor" href="#load-a-run" aria-label="Permalink to &quot;Load a run&quot;">​</a></h2><p>Drop a log file onto the landing page, or click <strong>Choose file</strong> to pick one. Parsing runs in a background worker, off the browser&#39;s main thread, so a multi-hundred-megabyte event stream doesn&#39;t freeze the tab.</p><p>The app takes a newline-delimited JSON event log (one JSON event per line, the format Spark writes to <code>spark.eventLog.dir</code>), either plain or gzip/Zstandard/LZ4/Snappy-compressed.</p><p>The same landing page has two other ways in: <strong>Choose rolling-log folder</strong> for an <code>eventlog_v2_*</code> rolling directory, and <strong>Fetch from Spark History Server</strong> to pull an application from a reachable History Server (local-server mode only).</p><p>Can&#39;t reach the History Server directly (it&#39;s only reachable through an SSH bastion)? See <a href="./alternative-log-retrieval.html">Alternative ways to get the logs</a>.</p><p>A History Server export needs one manual step. <code>GET /api/v1/applications/&lt;appId&gt;/logs</code> hands back a zip, and the drop zone does not unwrap zip containers. Extract the <code>.zstd</code> event log from that zip yourself and drop the extracted file in. It needs no further decompressing.</p><p>Files you have already loaded stay listed under <strong>Recent files</strong> on the landing page.</p><h2 id="reading-the-dashboard" tabindex="-1">Reading the dashboard <a class="header-anchor" href="#reading-the-dashboard" aria-label="Permalink to &quot;Reading the dashboard&quot;">​</a></h2><p>When parsing finishes, the dashboard shows a board of widgets, each in its own card with a title. Every widget that flags a problem uses the same convention: a colored impact dot (critical / warning / info) and an ALL-CAPS tag for the bottleneck category (<code>SKEW</code>, <code>SPILL</code>, <code>GC</code>, and so on: see <a href="./understanding-findings.html">Understanding findings</a>). Widgets list every affected stage, not just the worst one. The dot&#39;s color tracks how much run time the finding could save you rather than how unusual the metric looks, so a small-looking anomaly with a big payoff can outrank a dramatic one that would barely move your run time.</p><p>A run scorecard (wall-clock, efficiency, wastage) always shows at the top. Below it, two tabs split the rest of the board:</p><ol><li><strong>Findings</strong>: every flagged finding and its detail widget, grouped by impact band (Critical, Warning, Info). Within a band, a recommendation row for a bottleneck type collapses into a summary row when it fires more than once; clicking the summary row expands its full list, and clicking any single row or widget jumps straight to that finding. Below the impact-band groups, memory and core-usage utilization always show, even on a clean run, and widgets that found nothing fold away into a &quot;Clean checks&quot; disclosure. This is the tab you land on.</li><li><strong>Full app report</strong>: the wall-clock and executor timelines, the stage table, and the reference-only cards.</li></ol><h3 id="advanced-view" tabindex="-1">Advanced view <a class="header-anchor" href="#advanced-view" aria-label="Permalink to &quot;Advanced view&quot;">​</a></h3><p>The topbar has an <strong>Advanced view</strong> toggle. It&#39;s off by default, which keeps each widget to the finding itself and what to do about it. Turn it on to also show confidence levels, supporting evidence, and documentation links for each finding, plus a few extra table columns. Your choice is remembered across runs.</p><h2 id="compare-two-runs" tabindex="-1">Compare two runs <a class="header-anchor" href="#compare-two-runs" aria-label="Permalink to &quot;Compare two runs&quot;">​</a></h2><p>To compare a baseline run against a candidate, say to check whether a tuning change helped, see <a href="./run-comparison.html">Run comparison mode</a>.</p><h2 id="ci-and-automation" tabindex="-1">CI and automation <a class="header-anchor" href="#ci-and-automation" aria-label="Permalink to &quot;CI and automation&quot;">​</a></h2><p>In a pipeline or a script, use the <code>analyze</code> CLI instead of the browser dashboard. It parses the same event logs and exits non-zero when a run crosses a threshold you set, so it can gate a build:</p><div class="language-sh vp-adaptive-theme"><button title="Copy Code" class="copy"></button><span class="lang">sh</span><pre class="shiki shiki-themes github-light github-dark vp-code" tabindex="0"><code><span class="line"><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;">npx</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;"> sparkforensics-analyze</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> &lt;</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">file</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">|</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;">dir</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">&gt; [--max-runtime </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">ms]</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> [--max-skew </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">ratio]</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> \\</span></span>
2
- <span class="line"><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> [--max-spill </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">gb]</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> [--max-failed-task-rate </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">pct]</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> [--min-efficiency </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">pct]</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> \\</span></span>
3
- <span class="line"><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> [--out </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">path]</span></span></code></pre></div><p>Point it at a single event log or a directory of them. Pass <code>--out</code> to also write the findings to a file.</p><p>Pass <code>--export-html &lt;dir&gt;</code> to write a self-contained HTML dashboard for the run into <code>&lt;dir&gt;</code> (which must not already exist or must be empty). Open <code>&lt;dir&gt;/index.html</code> directly in a browser over <code>file://</code>, with no server, to get the same interactive dashboard offline. This makes it easy to archive or share a run. <code>--redact</code> applies to the exported report too.</p><p>The CLI also supports fetching a run directly from a reachable Spark History Server (<code>--shs-base-url</code>/<code>--app-id</code>/<code>--attempt-id</code>) instead of a local file, comparing a candidate run against a baseline with regression gating (<code>--baseline</code>/<code>--max-regression-pct</code>/<code>--regression-metric</code>/ <code>--fail-on-introduced</code>), redacting the app id and any host/IP tokens before sharing output (<code>--redact</code>), and narrowing the findings to certain impact bands, types, or a stage (<code>--impact</code>/<code>--type</code>/<code>--stage</code>). Run it with <code>--help</code> for the full flag list.</p><p>Same caveat as above: if the History Server is only reachable through an SSH bastion, <code>--shs-base-url</code> can&#39;t reach it either: see <a href="./alternative-log-retrieval.html">Alternative ways to get the logs</a>.</p><p>Running in Airflow instead of a plain CI pipeline? See <a href="https://github.com/shuffle-works/sparkforensics-operator" target="_blank" rel="noreferrer">sparkforensics-operator</a>, an Airflow operator that wraps the CLI and acts on the result after each Spark job, so you don&#39;t have to wire up the call yourself.</p>`,25)])])}const u=a(s,[["render",n]]);export{g as __pageData,u as default};
@@ -1 +0,0 @@
1
- import{_ as a,o as t,c as i,a5 as o}from"./chunks/framework.DSg0KOwT.js";const g=JSON.parse('{"title":"Getting started","description":"","frontmatter":{},"headers":[],"relativePath":"user-guide/getting-started.md","filePath":"user-guide/getting-started.md"}'),s={name:"user-guide/getting-started.md"};function n(r,e,d,l,h,c){return t(),i("div",null,[...e[0]||(e[0]=[o("",25)])])}const u=a(s,[["render",n]]);export{g as __pageData,u as default};
@@ -1 +0,0 @@
1
- import{_ as a,o as r,c as e,a5 as n}from"./chunks/framework.DSg0KOwT.js";const l=JSON.parse('{"title":"Run comparison mode","description":"","frontmatter":{},"headers":[],"relativePath":"user-guide/run-comparison.md","filePath":"user-guide/run-comparison.md"}'),t={name:"user-guide/run-comparison.md"};function s(i,o,d,p,c,h){return r(),e("div",null,[...o[0]||(o[0]=[n('<h1 id="run-comparison-mode" tabindex="-1">Run comparison mode <a class="header-anchor" href="#run-comparison-mode" aria-label="Permalink to &quot;Run comparison mode&quot;">​</a></h1><p>Put two runs side by side to see whether a tuning change helped.</p><h2 id="starting-a-comparison" tabindex="-1">Starting a comparison <a class="header-anchor" href="#starting-a-comparison" aria-label="Permalink to &quot;Starting a comparison&quot;">​</a></h2><p>From the landing page, click <strong>Compare two runs</strong>. Two slots appear, <strong>Run A</strong> and <strong>Run B</strong>.</p><ol><li>Load a file into each slot the same way you&#39;d load a single run (drag and drop, or <strong>Choose file</strong>).</li><li>Click <strong>Compare</strong>.</li></ol><p>The runs parse one after the other through the same background worker. When both finish, the comparison view opens.</p><h2 id="reading-the-comparison" tabindex="-1">Reading the comparison <a class="header-anchor" href="#reading-the-comparison" aria-label="Permalink to &quot;Reading the comparison&quot;">​</a></h2><p>The comparison page shows what changed between the two runs: findings that appeared or disappeared, plus metric deltas for duration, spill, GC time and so on.</p><p>For either run&#39;s full dashboard, click <strong>View run A dashboard</strong> or <strong>View run B dashboard</strong>. <strong>← Back to comparison</strong> takes you back.</p>',9)])])}const m=a(t,[["render",s]]);export{l as __pageData,m as default};
@@ -1 +0,0 @@
1
- import{_ as a,o as r,c as e,a5 as n}from"./chunks/framework.DSg0KOwT.js";const l=JSON.parse('{"title":"Run comparison mode","description":"","frontmatter":{},"headers":[],"relativePath":"user-guide/run-comparison.md","filePath":"user-guide/run-comparison.md"}'),t={name:"user-guide/run-comparison.md"};function s(i,o,d,p,c,h){return r(),e("div",null,[...o[0]||(o[0]=[n("",9)])])}const m=a(t,[["render",s]]);export{l as __pageData,m as default};
@@ -1 +0,0 @@
1
- import{_ as a,o,c as t,a5 as r}from"./chunks/framework.DSg0KOwT.js";const p=JSON.parse('{"title":"Understanding findings","description":"","frontmatter":{},"headers":[],"relativePath":"user-guide/understanding-findings.md","filePath":"user-guide/understanding-findings.md"}'),i={name:"user-guide/understanding-findings.md"};function s(n,e,l,d,c,h){return o(),t("div",null,[...e[0]||(e[0]=[r('<h1 id="understanding-findings" tabindex="-1">Understanding findings <a class="header-anchor" href="#understanding-findings" aria-label="Permalink to &quot;Understanding findings&quot;">​</a></h1><p>Every flagged problem carries a short ALL-CAPS tag. This page has one entry per tag: what it means, and what to do about it.</p><p>A few tags share their in-app &quot;Reference panel&quot; background reading with another tag, because the underlying Spark-tuning material overlaps: <code>SFAIL</code> with <code>FAIL</code>, <code>PART</code> with <code>SHFL</code>, <code>SPEC</code> with <code>STRAG</code>, and <code>CACHE</code>/<code>LOCAL</code> with <code>UTIL</code>.</p><h2 id="per-stage" tabindex="-1">Per-stage <a class="header-anchor" href="#per-stage" aria-label="Permalink to &quot;Per-stage&quot;">​</a></h2><h3 id="skew" tabindex="-1"><code>SKEW</code>: Task skew <a class="header-anchor" href="#skew" aria-label="Permalink to &quot;`SKEW`: Task skew {#skew}&quot;">​</a></h3><p>A small number of tasks take much longer than their peers in the same stage. For join-driven skew, enable AQE skew-join handling (<code>spark.sql.adaptive.skewJoin.enabled</code>); otherwise salt the key or repartition on a better key.</p><h3 id="shfl" tabindex="-1"><code>SHFL</code>: Shuffle I/O <a class="header-anchor" href="#shfl" aria-label="Permalink to &quot;`SHFL`: Shuffle I/O {#shfl}&quot;">​</a></h3><p>Tasks move a large amount of intermediate data between stages. Raise <code>spark.sql.shuffle.partitions</code>, or add a broadcast join.</p><h3 id="spill" tabindex="-1"><code>SPILL</code>: Memory and disk spill <a class="header-anchor" href="#spill" aria-label="Permalink to &quot;`SPILL`: Memory and disk spill {#spill}&quot;">​</a></h3><p>Tasks are writing data out of memory, which slows execution. Two spill patterns get flagged differently: skew spill, where a few heavy tasks spill while most don&#39;t (rebalance partitioning), and volume spill, where most tasks spill because the data genuinely exceeds available memory (add partitions).</p><h3 id="gc" tabindex="-1"><code>GC</code>: Garbage collection pressure <a class="header-anchor" href="#gc" aria-label="Permalink to &quot;`GC`: Garbage collection pressure {#gc}&quot;">​</a></h3><p>Tasks spend an unusually large share of time reclaiming memory. Reduce object creation: use primitive types, avoid UDFs, or raise executor memory.</p><h3 id="fail" tabindex="-1"><code>FAIL</code>: Failed tasks <a class="header-anchor" href="#fail" aria-label="Permalink to &quot;`FAIL`: Failed tasks {#fail}&quot;">​</a></h3><p>Tasks fail often enough to affect the stage. Failed tasks point to executor instability or data-driven errors: check driver logs for the dominant failure reason.</p><h3 id="sfail" tabindex="-1"><code>SFAIL</code>: Failed stage <a class="header-anchor" href="#sfail" aria-label="Permalink to &quot;`SFAIL`: Failed stage {#sfail}&quot;">​</a></h3><p>A stage attempt failed outright rather than losing individual tasks within it. Inspect the driver log for the failure reason and the job that triggered it.</p><h3 id="strag" tabindex="-1"><code>STRAG</code>: Straggler tasks <a class="header-anchor" href="#strag" aria-label="Permalink to &quot;`STRAG`: Straggler tasks {#strag}&quot;">​</a></h3><p>A few tasks run much slower than the rest of their stage. Rule out a GC pause or a slow shuffle fetch before assuming a hardware issue; if a skewed key is the real cause, that&#39;s a candidate for AQE&#39;s skew-join handling.</p><h3 id="spec" tabindex="-1"><code>SPEC</code>: Speculation waste <a class="header-anchor" href="#spec" aria-label="Permalink to &quot;`SPEC`: Speculation waste {#spec}&quot;">​</a></h3><p>Speculative task attempts used a lot of executor time without confirming a genuine straggler. Self-flagged low-confidence: a design spike, not yet validated against real-world runs. If task durations are just naturally variable rather than genuine stragglers, tune <code>spark.speculation.multiplier</code>/<code>spark.speculation.quantile</code>.</p><h3 id="retry" tabindex="-1"><code>RETRY</code>: Retry waste <a class="header-anchor" href="#retry" aria-label="Permalink to &quot;`RETRY`: Retry waste {#retry}&quot;">​</a></h3><p>Repeated task attempts ate into execution time even though the stage completed. Investigate executor loss or fetch failures.</p><h3 id="tiny" tabindex="-1"><code>TINY</code>: Tiny tasks <a class="header-anchor" href="#tiny" aria-label="Permalink to &quot;`TINY`: Tiny tasks {#tiny}&quot;">​</a></h3><p>Many very short tasks add scheduling overhead out of proportion to the work each one does. Repartition to fewer, larger tasks.</p><h3 id="part" tabindex="-1"><code>PART</code>: Partition sizing <a class="header-anchor" href="#part" aria-label="Permalink to &quot;`PART`: Partition sizing {#part}&quot;">​</a></h3><p>Shuffle partitions are too large, too uneven, or too few for the work. A single shuffle partition over 5 GB, for example, will OOM or spill heavily: repartition to break it up before the stage runs.</p><h3 id="slow" tabindex="-1"><code>SLOW</code>: Stage slowness <a class="header-anchor" href="#slow" aria-label="Permalink to &quot;`SLOW`: Stage slowness {#slow}&quot;">​</a></h3><p>A stage ran long overall without a more specific cause getting flagged. Often a partition-count problem: raise parallelism via <code>spark.sql.shuffle.partitions</code> or <code>spark.default.parallelism</code>, or check for a large per-task data volume driving heavy shuffle and spill.</p><h3 id="shape" tabindex="-1"><code>SHAPE</code>: Stage shape <a class="header-anchor" href="#shape" aria-label="Permalink to &quot;`SHAPE`: Stage shape {#shape}&quot;">​</a></h3><p>The stage has an inefficient task count, output shape, or task-to-stage balance: for example, one straggler task taking a large fraction of the stage&#39;s wall-clock time.</p><h3 id="host" tabindex="-1"><code>HOST</code>: Slow host <a class="header-anchor" href="#host" aria-label="Permalink to &quot;`HOST`: Slow host {#host}&quot;">​</a></h3><p>One executor is much slower than its peers. It may just hold data locality for its tasks or carry one heavy stage, rather than a hardware fault. Enable <code>spark.speculation</code> to relaunch a lagging task automatically.</p><h2 id="app-level" tabindex="-1">App-level <a class="header-anchor" href="#app-level" aria-label="Permalink to &quot;App-level&quot;">​</a></h2><h3 id="cold" tabindex="-1"><code>COLD</code>: Executor cold start <a class="header-anchor" href="#cold" aria-label="Permalink to &quot;`COLD`: Executor cold start {#cold}&quot;">​</a></h3><p>New executors take time to become available for work. Pre-warm the cluster, or use dynamic allocation.</p><h3 id="util" tabindex="-1"><code>UTIL</code>: Low utilization <a class="header-anchor" href="#util" aria-label="Permalink to &quot;`UTIL`: Low utilization {#util}&quot;">​</a></h3><p>Allocated executors sit idle for a large share of the application run. Consider a smaller cluster, or enable dynamic allocation.</p><h3 id="mem" tabindex="-1"><code>MEM</code>: Memory utilization <a class="header-anchor" href="#mem" aria-label="Permalink to &quot;`MEM`: Memory utilization {#mem}&quot;">​</a></h3><p>Executor memory or core capacity may be over- or under-provisioned. Some detail here needs <code>spark.eventLog.logStageExecutorMetrics=true</code> on the run being analyzed; without it, per-executor memory usage can&#39;t be broken down. Review <code>spark.executor.memory</code> and executor count if allocated memory sat largely idle over the run. That idle-memory variant is self-flagged low-confidence: it estimates waste from allocated-versus-used memory-time against an unverified 1.5x buffer. Check it against the Spark UI before resizing anything.</p><h3 id="cache" tabindex="-1"><code>CACHE</code>: Caching opportunity <a class="header-anchor" href="#cache" aria-label="Permalink to &quot;`CACHE`: Caching opportunity {#cache}&quot;">​</a></h3><p>A reusable dataset (re-read via the same SQL relation more than once) may be worth persisting between stages. Self-flagged low-confidence: reuse is only inferred, from plan-scan identity across SQL executions, so confirm the reads really do hit the same data before you cache anything.</p><h3 id="cstor" tabindex="-1"><code>CSTOR</code>: Cache storage <a class="header-anchor" href="#cstor" aria-label="Permalink to &quot;`CSTOR`: Cache storage {#cstor}&quot;">​</a></h3><p>A persisted dataset is not fully cached in memory, or is spilling to disk. Raise executor memory, or shrink the cached dataset.</p><h3 id="local" tabindex="-1"><code>LOCAL</code>: Core usage locality <a class="header-anchor" href="#local" aria-label="Permalink to &quot;`LOCAL`: Core usage locality {#local}&quot;">​</a></h3><p>Tasks run without process- or node-local data placement more often than expected. Check <code>spark.locality.wait</code> settings and executor/data colocation. Self-flagged low-confidence: the non-local-ratio thresholds are unvalidated design-spike values, and no external tool publishes an equivalent metric to calibrate them against.</p><h3 id="chrn" tabindex="-1"><code>CHRN</code>: Autoscaling churn <a class="header-anchor" href="#chrn" aria-label="Permalink to &quot;`CHRN`: Autoscaling churn {#chrn}&quot;">​</a></h3><p>Executors are stood up and torn down again before they can do useful work: re-provisioning churn rather than normal scale-down. Raise <code>spark.dynamicAllocation.executorIdleTimeout</code>, or widen the <code>minExecutors</code>/<code>maxExecutors</code> bounds to reduce flapping. Self-flagged low-confidence: a design spike, not yet validated against real-world runs.</p><h3 id="jobs" tabindex="-1"><code>JOBS</code>: Job failure rate <a class="header-anchor" href="#jobs" aria-label="Permalink to &quot;`JOBS`: Job failure rate {#jobs}&quot;">​</a></h3><p>A large share of completed jobs did not succeed. Inspect the driver log for the failed job(s) and the stage failures that triggered them.</p><h3 id="incmp" tabindex="-1"><code>INCMP</code>: Incomplete run <a class="header-anchor" href="#incmp" aria-label="Permalink to &quot;`INCMP`: Incomplete run {#incmp}&quot;">​</a></h3><p>This event log never recorded an <code>ApplicationEnd</code> event: capture stopped before the run finished (an in-flight job, a rotated-away log, or a cut-short capture). Every other finding and metric on the board reflects only what was captured up to that point, not the full run.</p><h2 id="configuration-scope" tabindex="-1">Configuration scope <a class="header-anchor" href="#configuration-scope" aria-label="Permalink to &quot;Configuration scope&quot;">​</a></h2><h3 id="cfg" tabindex="-1"><code>CFG</code>: Configuration audit <a class="header-anchor" href="#cfg" aria-label="Permalink to &quot;`CFG`: Configuration audit {#cfg}&quot;">​</a></h3><p>Flags configuration settings that may cause reliability or efficiency problems, independent of any one stage&#39;s behavior. Four properties are audited today:</p><ul><li><code>spark.shuffle.service.enabled</code>: flagged when dynamic allocation is on but the external shuffle service is off, since shuffle data won&#39;t survive executor removal.</li><li><code>spark.dynamicAllocation.maxExecutors</code>: flagged for inverted bounds or a missing upper bound.</li><li><code>spark.serializer</code>: flagged when still on the default Java serializer; <code>org.apache.spark.serializer.KryoSerializer</code> is faster and produces smaller buffers.</li><li><code>spark.executor.memoryOverhead</code>: flagged when set below a safe floor.</li></ul><h2 id="sql-scope" tabindex="-1">SQL scope <a class="header-anchor" href="#sql-scope" aria-label="Permalink to &quot;SQL scope&quot;">​</a></h2><h3 id="plan" tabindex="-1"><code>PLAN</code>: Plan advisor <a class="header-anchor" href="#plan" aria-label="Permalink to &quot;`PLAN`: Plan advisor {#plan}&quot;">​</a></h3><p>Flags patterns in the SQL execution plan worth reviewing. Four checks share this tag:</p><ul><li>Duplicate plan subtree: the same subtree recomputed more than once in the plan.</li><li>Small files: reading an excessive number of small files.</li><li>Under-broadcast: the smaller side of a Sort Merge Join looks well under the broadcast threshold; consider a <code>broadcast()</code> hint or raising <code>spark.sql.autoBroadcastJoinThreshold</code>.</li><li>Over-broadcast: a broadcast exceeds the 1 GB threshold; check for a misapplied broadcast hint or a misconfigured <code>spark.sql.autoBroadcastJoinThreshold</code>.</li></ul>',59)])])}const f=a(i,[["render",s]]);export{p as __pageData,f as default};
@@ -1 +0,0 @@
1
- import{_ as a,o,c as t,a5 as r}from"./chunks/framework.DSg0KOwT.js";const p=JSON.parse('{"title":"Understanding findings","description":"","frontmatter":{},"headers":[],"relativePath":"user-guide/understanding-findings.md","filePath":"user-guide/understanding-findings.md"}'),i={name:"user-guide/understanding-findings.md"};function s(n,e,l,d,c,h){return o(),t("div",null,[...e[0]||(e[0]=[r("",59)])])}const f=a(i,[["render",s]]);export{p as __pageData,f as default};
@@ -1,64 +0,0 @@
1
- (function(){"use strict";var V=Uint8Array,$e=Uint16Array,Sr=Int32Array,Dt=new V([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ct=new V([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),kr=new V([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Lt=function(e,t){for(var n=new $e(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var o=new Sr(n[30]),r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)o[i]=i-n[r]<<5|r;return{b:n,r:o}},jt=Lt(Dt,2),Ut=jt.b,wr=jt.r;Ut[28]=258,wr[258]=28;for(var zr=Lt(Ct,0),br=zr.b,ht=new $e(32768),M=0;M<32768;++M){var de=(M&43690)>>1|(M&21845)<<1;de=(de&52428)>>2|(de&13107)<<2,de=(de&61680)>>4|(de&3855)<<4,ht[M]=((de&65280)>>8|(de&255)<<8)>>1}for(var Ce=(function(e,t,n){for(var r=e.length,o=0,i=new $e(t);o<r;++o)e[o]&&++i[e[o]-1];var s=new $e(t);for(o=1;o<t;++o)s[o]=s[o-1]+i[o-1]<<1;var a;if(n){a=new $e(1<<t);var u=15-t;for(o=0;o<r;++o)if(e[o])for(var c=o<<4|e[o],l=t-e[o],f=s[e[o]-1]++<<l,p=f|(1<<l)-1;f<=p;++f)a[ht[f]>>u]=c}else for(a=new $e(r),o=0;o<r;++o)e[o]&&(a[o]=ht[s[e[o]-1]++]>>15-e[o]);return a}),Le=new V(288),M=0;M<144;++M)Le[M]=8;for(var M=144;M<256;++M)Le[M]=9;for(var M=256;M<280;++M)Le[M]=7;for(var M=280;M<288;++M)Le[M]=8;for(var Ft=new V(32),M=0;M<32;++M)Ft[M]=5;var Er=Ce(Le,9,1),Ir=Ce(Ft,5,1),dt=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},oe=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},mt=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Bt=function(e){return(e+7)/8|0},Pe=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new V(e.subarray(t,n))},Tr=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],K=function(e,t,n){var r=new Error(t||Tr[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,K),!n)throw r;return r},Jt=function(e,t,n,r){var o=e.length,i=r?r.length:0;if(!o||t.f&&!t.l)return n||new V(0);var s=!n,a=s||t.i!=2,u=t.i;s&&(n=new V(o*3));var c=function(Se){var ke=n.length;if(Se>ke){var pt=new V(Math.max(ke*2,Se));pt.set(n),n=pt}},l=t.f||0,f=t.p||0,p=t.b||0,h=t.l,m=t.d,g=t.m,v=t.n,b=o*8;do{if(!h){l=oe(e,f,1);var w=oe(e,f+1,3);if(f+=3,w)if(w==1)h=Er,m=Ir,g=9,v=5;else if(w==2){var z=oe(e,f,31)+257,F=oe(e,f+10,15)+4,W=z+oe(e,f+5,31)+1;f+=14;for(var q=new V(W),J=new V(19),N=0;N<F;++N)J[kr[N]]=oe(e,f+N*3,7);f+=F*3;for(var ee=dt(J),X=(1<<ee)-1,x=Ce(J,ee,1),N=0;N<W;){var I=x[oe(e,f,X)];f+=I&15;var k=I>>4;if(k<16)q[N++]=k;else{var B=0,se=0;for(k==16?(se=3+oe(e,f,3),f+=2,B=q[N-1]):k==17?(se=3+oe(e,f,7),f+=3):k==18&&(se=11+oe(e,f,127),f+=7);se--;)q[N++]=B}}var pe=q.subarray(0,z),Y=q.subarray(z);g=dt(pe),v=dt(Y),h=Ce(pe,g,1),m=Ce(Y,v,1)}else K(1);else{var k=Bt(f)+4,$=e[k-4]|e[k-3]<<8,E=k+$;if(E>o){u&&K(0);break}a&&c(p+$),n.set(e.subarray(k,E),p),t.b=p+=$,t.p=f=E*8,t.f=l;continue}if(f>b){u&&K(0);break}}a&&c(p+131072);for(var S=(1<<g)-1,P=(1<<v)-1,Ie=f;;Ie=f){var B=h[mt(e,f)&S],he=B>>4;if(f+=B&15,f>b){u&&K(0);break}if(B||K(2),he<256)n[p++]=he;else if(he==256){Ie=f,h=null;break}else{var qe=he-254;if(he>264){var N=he-257,_e=Dt[N];qe=oe(e,f,(1<<_e)-1)+Ut[N],f+=_e}var Ne=m[mt(e,f)&P],ae=Ne>>4;Ne||K(3),f+=Ne&15;var Y=br[ae];if(ae>3){var _e=Ct[ae];Y+=mt(e,f)&(1<<_e)-1,f+=_e}if(f>b){u&&K(0);break}a&&c(p+131072);var ye=p+qe;if(p<Y){var Te=i-Y,De=Math.min(Y,ye);for(Te+p<0&&K(3);p<De;++p)n[p]=r[Te+p]}for(;p<ye;++p)n[p]=n[p-Y]}}t.l=h,t.p=Ie,t.b=p,t.f=l,h&&(l=1,t.m=g,t.d=m,t.n=v)}while(!l);return p!=n.length&&s?Pe(n,0,p):n.subarray(0,p)},$r=new V(0),ce=function(e,t){return e[t]|e[t+1]<<8},ne=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},gt=function(e,t){return ne(e,t)+ne(e,t+4)*4294967296},Pr=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&K(6,"invalid gzip data");var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},Ge=(function(){function e(t,n){typeof t=="function"&&(n=t,t={}),this.ondata=n;var r=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new V(32768),this.p=new V(0),r&&this.o.set(r)}return e.prototype.e=function(t){if(this.ondata||K(5),this.d&&K(4),!this.p.length)this.p=t;else if(t.length){var n=new V(this.p.length+t.length);n.set(this.p),n.set(t,this.p.length),this.p=n}},e.prototype.c=function(t){this.s.i=+(this.d=t||!1);var n=this.s.b,r=Jt(this.p,this.s,this.o);this.ondata(Pe(r,n,this.s.b),this.d),this.o=Pe(r,this.s.b-32768),this.s.b=this.o.length,this.p=Pe(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(t,n){this.e(t),this.c(n)},e})();function Zr(e,t){return Jt(e,{i:2},t&&t.out,t&&t.dictionary)}var Wt=(function(){function e(t,n){this.v=1,this.r=0,Ge.call(this,t,n)}return e.prototype.push=function(t,n){if(Ge.prototype.e.call(this,t),this.r+=t.length,this.v){var r=this.p.subarray(this.v-1),o=r.length>3?Pr(r):4;if(o>r.length){if(!n)return}else this.v>1&&this.onmember&&this.onmember(this.r-r.length);this.p=r.subarray(o),this.v=0}Ge.prototype.c.call(this,0),this.s.f&&!this.s.l?(this.v=Bt(this.s.p)+9,this.s={i:0},this.o=new V(0),this.push(new V(0),n)):n&&Ge.prototype.c.call(this,n)},e})(),vt=typeof TextDecoder<"u"&&new TextDecoder,xr=0;try{vt.decode($r,{stream:!0}),xr=1}catch{}var Or=function(e){for(var t="",n=0;;){var r=e[n++],o=(r>127)+(r>223)+(r>239);if(n+o>e.length)return{s:t,r:Pe(e,n-1)};o?o==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):o&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function Ar(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}else{if(vt)return vt.decode(e);var o=Or(e),i=o.s,n=o.r;return n.length&&K(8),i}}var Mr=function(e,t){return t+30+ce(e,t+26)+ce(e,t+28)},Rr=function(e,t,n){var r=ce(e,t+28),o=ce(e,t+30),i=Ar(e.subarray(t+46,t+46+r),!(ce(e,t+8)&2048)),s=t+46+r,a=Nr(e,s,o,n,ne(e,t+20),ne(e,t+24),ne(e,t+42)),u=a[0],c=a[1],l=a[2];return[ce(e,t+10),u,c,i,s+o+ce(e,t+32),l]},Nr=function(e,t,n,r,o,i,s){var a=o==4294967295,u=i==4294967295,c=s==4294967295,l=t+n,f=a+u+c;if(r&&f){for(;t+4<l;t+=4+ce(e,t+2))if(ce(e,t)==1)return[a?gt(e,t+4+8*u):o,u?gt(e,t+4):i,c?gt(e,t+4+8*(u+a)):s,1];r<2&&K(13)}return[o,i,s,0]};function Dr(e,t){for(var n={},r=e.length-22;ne(e,r)!=101010256;--r)(!r||e.length-r>65558)&&K(13);var o=ce(e,r+8);if(!o)return{};var i=ne(e,r+16),s=ne(e,r-20)==117853008;if(s){var a=ne(e,r-12);s=ne(e,a)==101075792,s&&(o=ne(e,a+32),i=ne(e,a+48))}for(var u=0;u<o;++u){var c=Rr(e,i,s),l=c[0],f=c[1],p=c[2],h=c[3],m=c[4],g=c[5],v=Mr(e,g);i=m,l?l==8?n[h]=Zr(e.subarray(v,v+f),{out:new V(p)}):K(14,"unknown compression type "+l):n[h]=Pe(e,v,v+f)}return n}const Cr=[76,90,52,66,108,111,99,107];function Vt(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Lr(e,t){const n=new Uint8Array(t);let r=0,o=0;const i=e.length;for(;r<i;){const s=e[r++];let a=s>>4;if(a===15){let f;do f=e[r++],a+=f;while(f===255)}if(n.set(e.subarray(r,r+a),o),r+=a,o+=a,r>=i)break;const u=e[r]|e[r+1]<<8;r+=2;let c=s&15;if(c===15){let f;do f=e[r++],c+=f;while(f===255)}c+=4;let l=o-u;for(let f=0;f<c;f++)n[o++]=n[l++]}return n}function qt(e){let t=new Uint8Array(0);return{push(n){if(t.length===0)t=n;else if(n.length){const o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o}let r=0;for(;t.length-r>=21;){for(let l=0;l<8;l++)if(t[r+l]!==Cr[l])throw new Error(`Not a Spark LZ4Block stream: bad magic at offset ${r}.`);const o=t[r+8]&240,i=Vt(t,r+9),s=Vt(t,r+13),a=r+21;if(t.length-a<i)break;const u=t.subarray(a,a+i);let c;if(o===16)c=u;else if(o===32)c=Lr(u,s);else throw new Error(`Unknown LZ4Block method 0x${o.toString(16)} at offset ${r}.`);if(c.length!==s)throw new Error(`LZ4Block length mismatch at offset ${r}: expected ${s}, got ${c.length}.`);e(c),r=a+i}t=r>0?t.slice(r):t},end(){if(t.length!==0)throw new Error(`Trailing ${t.length} undecoded bytes in LZ4Block stream.`)}}}var jr=ArrayBuffer,j=Uint8Array,Ke=Uint16Array,Ur=Int16Array,He=Int32Array,_t=function(e,t,n){if(j.prototype.slice)return j.prototype.slice.call(e,t,n);(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length);var r=new j(n-t);return r.set(e.subarray(t,n)),r},Xe=function(e,t,n,r){if(j.prototype.fill)return j.prototype.fill.call(e,t,n,r);for((n==null||n<0)&&(n=0),(r==null||r>e.length)&&(r=e.length);n<r;++n)e[n]=t;return e},Fr=function(e,t,n,r){if(j.prototype.copyWithin)return j.prototype.copyWithin.call(e,t,n,r);for((n==null||n<0)&&(n=0),(r==null||r>e.length)&&(r=e.length);n<r;)e[t++]=e[n++]},Br=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],D=function(e,t,n){var r=new Error(t||Br[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,D),!n)throw r;return r},Gt=function(e,t,n){for(var r=0,o=0;r<n;++r)o|=e[t++]<<(r<<3);return o},Jr=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Wr=function(e,t){var n=e[0]|e[1]<<8|e[2]<<16;if(n==3126568&&e[3]==253){var r=e[4],o=r>>5&1,i=r>>2&1,s=r&3,a=r>>6;r&8&&D(0);var u=6-o,c=s==3?4:s,l=Gt(e,u,c);u+=c;var f=a?1<<a:o,p=Gt(e,u,f)+(a==1&&256),h=p;if(!o){var m=1<<10+(e[5]>>3);h=m+(m>>3)*(e[5]&7)}h>2145386496&&D(1);var g=new j(h+12);return g[0]=1,g[4]=4,g[8]=8,{b:u+f,y:0,l:0,d:l,w:t&&t!=1?t:g.subarray(12),e:h,o:new He(g.buffer,0,3),u:p,c:i,m:Math.min(131072,h)}}else if((n>>4|e[3]<<20)==25481893)return Jr(e,4)+8;D(0)},we=function(e){for(var t=0;1<<t<=e;++t);return t-1},je=function(e,t,n){var r=(t<<3)+4,o=(e[t]&15)+5;o>n&&D(3);for(var i=1<<o,s=i,a=-1,u=-1,c=-1,l=i,f=new jr(512+(i<<2)),p=new Ur(f,0,256),h=new Ke(f,0,256),m=new Ke(f,512,i),g=512+(i<<1),v=new j(f,g,i),b=new j(f,g+i);a<255&&s>0;){var w=we(s+1),k=r>>3,$=(1<<w+1)-1,E=(e[k]|e[k+1]<<8|e[k+2]<<16)>>(r&7)&$,z=(1<<w)-1,F=$-s-1,W=E&z;if(W<F?(r+=w,E=W):(r+=w+1,E>z&&(E-=F)),p[++a]=--E,E==-1?(s+=E,v[--l]=a):s-=E,!E)do{var q=r>>3;u=(e[q]|e[q+1]<<8)>>(r&7)&3,r+=2,a+=u}while(u==3)}(a>255||s)&&D(0);for(var J=0,N=(i>>1)+(i>>3)+3,ee=i-1,X=0;X<=a;++X){var x=p[X];if(x<1){h[X]=-x;continue}for(c=0;c<x;++c){v[J]=X;do J=J+N&ee;while(J>=l)}}for(J&&D(0),c=0;c<i;++c){var I=h[v[c]]++,B=b[c]=o-we(I);m[c]=(I<<B)-i}return[r+7>>3,{b:o,s:v,n:b,t:m}]},Vr=function(e,t){var n=0,r=-1,o=new j(292),i=e[t],s=o.subarray(0,256),a=o.subarray(256,268),u=new Ke(o.buffer,268);if(i<128){var c=je(e,t+1,6),l=c[0],f=c[1];t+=i;var p=l<<3,h=e[t];h||D(0);for(var m=0,g=0,v=f.b,b=v,w=(++t<<3)-8+we(h);w-=v,!(w<p);){var k=w>>3;if(m+=(e[k]|e[k+1]<<8)>>(w&7)&(1<<v)-1,s[++r]=f.s[m],w-=b,w<p)break;k=w>>3,g+=(e[k]|e[k+1]<<8)>>(w&7)&(1<<b)-1,s[++r]=f.s[g],v=f.n[m],m=f.t[m],b=f.n[g],g=f.t[g]}++r>255&&D(0)}else{for(r=i-127;n<r;n+=2){var $=e[++t];s[n]=$>>4,s[n+1]=$&15}++t}var E=0;for(n=0;n<r;++n){var z=s[n];z>11&&D(0),E+=z&&1<<z-1}var F=we(E)+1,W=1<<F,q=W-E;for(q&q-1&&D(0),s[r++]=we(q)+1,n=0;n<r;++n){var z=s[n];++a[s[n]=z&&F+1-z]}var J=new j(W<<1),N=J.subarray(0,W),ee=J.subarray(W);for(u[F]=0,n=F;n>0;--n){var X=u[n];Xe(ee,n,X,u[n-1]=X+a[n]*(1<<F-n))}for(u[0]!=W&&D(0),n=0;n<r;++n){var x=s[n];if(x){var I=u[x];Xe(N,n,I,u[x]=I+(1<<F-x))}}return[t,{n:ee,b:F,s:N}]},qr=je(new j([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],Gr=je(new j([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],Kr=je(new j([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],Kt=function(e,t){for(var n=e.length,r=new He(n),o=0;o<n;++o)r[o]=t,t+=1<<e[o];return r},yt=new j(new He([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),Hr=Kt(yt,0),St=new j(new He([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),Xr=Kt(St,3),Ue=function(e,t,n){var r=e.length,o=t.length,i=e[r-1],s=(1<<n.b)-1,a=-n.b;i||D(0);for(var u=0,c=n.b,l=(r<<3)-8+we(i)-c,f=-1;l>a&&f<o;){var p=l>>3,h=(e[p]|e[p+1]<<8|e[p+2]<<16)>>(l&7);u=(u<<c|h)&s,t[++f]=n.s[u],l-=c=n.n[u]}(l!=a||f+1!=o)&&D(0)},Yr=function(e,t,n){var r=6,o=t.length,i=o+3>>2,s=i<<1,a=i+s;Ue(e.subarray(r,r+=e[0]|e[1]<<8),t.subarray(0,i),n),Ue(e.subarray(r,r+=e[2]|e[3]<<8),t.subarray(i,s),n),Ue(e.subarray(r,r+=e[4]|e[5]<<8),t.subarray(s,a),n),Ue(e.subarray(r),t.subarray(a),n)},Qr=function(e,t,n){var r,o=t.b,i=e[o],s=i>>1&3;t.l=i&1;var a=i>>3|e[o+1]<<5|e[o+2]<<13,u=(o+=3)+a;if(s==1)return o>=e.length?void 0:(t.b=o+1,Xe(new j(a),e[o]));if(!(u>e.length)){if(s==0)return t.b=u,_t(e,o,u);if(s==2){var c=e[o],l=c&3,f=c>>2&3,p=c>>4,h=0,m=0;l<2?f&1?p|=e[++o]<<4|(f&2&&e[++o]<<12):p=c>>3:(m=f,f<2?(p|=(e[++o]&63)<<4,h=e[o]>>6|e[++o]<<2):f==2?(p|=e[++o]<<4|(e[++o]&3)<<12,h=e[o]>>2|e[++o]<<6):(p|=e[++o]<<4|(e[++o]&63)<<12,h=e[o]>>6|e[++o]<<2|e[++o]<<10)),++o;var g=new j(t.m),v=g.length-p;if(l==0)g.set(e.subarray(o,o+=p),v);else if(l==1)Xe(g,e[o++],v);else{var b=t.h;if(l==2){var w=Vr(e,o);h+=o-(o=w[0]),t.h=b=w[1]}else b||D(0);(m?Yr:Ue)(e.subarray(o,o+=h),g.subarray(v),b)}var k=e[o++];if(k){k==255?k=(e[o++]|e[o++]<<8)+32512:k>127&&(k=k-128<<8|e[o++]);var $=e[o++];$&3&&D(0);for(var E=[Gr,Kr,qr],z=2;z>-1;--z){var F=$>>(z<<1)+2&3;if(F==1){var W=new j([0,0,e[o++]]);E[z]={s:W.subarray(2,3),n:W.subarray(0,1),t:new Ke(W.buffer,0,1),b:0}}else F==2?(r=je(e,o,9-(z&1)),o=r[0],E[z]=r[1]):F==3&&(t.t||D(0),E[z]=t.t[z])}var q=t.t=E,J=q[0],N=q[1],ee=q[2],X=e[u-1];X||D(0);var x=(u<<3)-8+we(X)-ee.b,I=x>>3,B=0,se=(e[I]|e[I+1]<<8)>>(x&7)&(1<<ee.b)-1;I=(x-=N.b)>>3;var pe=(e[I]|e[I+1]<<8)>>(x&7)&(1<<N.b)-1;I=(x-=J.b)>>3;var Y=(e[I]|e[I+1]<<8)>>(x&7)&(1<<J.b)-1;for(++k;--k;){var S=ee.s[se],P=ee.n[se],Ie=J.s[Y],he=J.n[Y],qe=N.s[pe],_e=N.n[pe];I=(x-=qe)>>3;var Ne=1<<qe,ae=Ne+((e[I]|e[I+1]<<8|e[I+2]<<16|e[I+3]<<24)>>>(x&7)&Ne-1);I=(x-=St[Ie])>>3;var ye=Xr[Ie]+((e[I]|e[I+1]<<8|e[I+2]<<16)>>(x&7)&(1<<St[Ie])-1);I=(x-=yt[S])>>3;var Te=Hr[S]+((e[I]|e[I+1]<<8|e[I+2]<<16)>>(x&7)&(1<<yt[S])-1);if(I=(x-=P)>>3,se=ee.t[se]+((e[I]|e[I+1]<<8)>>(x&7)&(1<<P)-1),I=(x-=he)>>3,Y=J.t[Y]+((e[I]|e[I+1]<<8)>>(x&7)&(1<<he)-1),I=(x-=_e)>>3,pe=N.t[pe]+((e[I]|e[I+1]<<8)>>(x&7)&(1<<_e)-1),ae>3)t.o[2]=t.o[1],t.o[1]=t.o[0],t.o[0]=ae-=3;else{var De=ae-(Te!=0);De?(ae=De==3?t.o[0]-1:t.o[De],De>1&&(t.o[2]=t.o[1]),t.o[1]=t.o[0],t.o[0]=ae):ae=t.o[0]}for(var z=0;z<Te;++z)g[B+z]=g[v+z];B+=Te,v+=Te;var Se=B-ae;if(Se<0){var ke=-Se,pt=t.e+Se;ke>ye&&(ke=ye);for(var z=0;z<ke;++z)g[B+z]=t.w[pt+z];B+=ke,ye-=ke,Se=0}for(var z=0;z<ye;++z)g[B+z]=g[Se+z];B+=ye}if(B!=v)for(;v<g.length;)g[B++]=g[v++];else B=g.length;g=_t(g,0,B)}else{var z;v&&(g=_t(g,v))}return t.b=u,g}D(2)}},Ht=function(e,t){if(e.length==1)return e[0];for(var n=new j(t),r=0,o=0;r<e.length;++r){var i=e[r];n.set(i,o),o+=i.length}return n},Xt=(function(){function e(t){this.ondata=t,this.c=[],this.l=0,this.z=0}return e.prototype.push=function(t,n){e:for(;;){if(typeof this.s=="number"){var r=Math.min(t.length,this.s);t=t.subarray(r),this.s-=r}var o=t.length,i=o+this.l;if(!this.s){if(n){if(!i){this.ondata(new j(0),!0);return}i<5&&D(5)}else if(i<18){this.c.push(t),this.l=i;return}if(this.l&&(this.c.push(t),t=Ht(this.c,i),this.c=[],this.l=0),typeof(this.s=Wr(t))=="number")continue e}if(typeof this.s!="number"){if(i<(this.z||3)){n&&D(5),this.c.push(t),this.l=i;return}if(this.l&&(this.c.push(t),t=Ht(this.c,i),this.c=[],this.l=0),!this.z&&i<(this.z=t[this.s.b]&2?4:3+(t[this.s.b]>>3|t[this.s.b+1]<<5|t[this.s.b+2]<<13))){n&&D(5),this.c.push(t),this.l=i;return}else this.z=0;for(;;){var s=Qr(t,this.s);if(s)this.ondata(s,!1),Fr(this.s.w,0,s.length),this.s.w.set(s,this.s.w.length-s.length);else{n&&D(5);var a=t.subarray(this.s.b);this.s.b=0,this.c.push(a),this.l+=a.length;return}if(this.s.l){t=t.subarray(this.s.b),this.s=this.s.c*4;continue e}}}else n&&D(5);return}},e})();const eo=[130,83,78,65,80,80,89,0],Yt=16;function to(e,t){let n=0,r=0,o=t;for(;;){const i=e[o++];if(n|=(i&127)<<r,(i&128)===0)break;r+=7}return{value:n>>>0,next:o}}function no(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function ro(e,t){for(let n=0;n<8;n++)if(e[t+n]!==eo[n])throw new Error(`Not a Spark SnappyCodec stream: bad magic at offset ${t}.`)}function oo(e){const{value:t,next:n}=to(e,0),r=new Uint8Array(t);let o=n,i=0;const s=e.length;for(;o<s;){const a=e[o],u=a&3;if(u===0){const c=a>>2;let l,f;if(c<60)l=c+1,f=1;else{const p=c-59;let h=0;for(let m=0;m<p;m++)h|=e[o+1+m]<<8*m;l=(h>>>0)+1,f=1+p}r.set(e.subarray(o+f,o+f+l),i),o+=f+l,i+=l}else if(u===1){const c=(a>>2&7)+4,l=(a&224)<<3|e[o+1];let f=i-l;for(let p=0;p<c;p++)r[i++]=r[f++];o+=2}else if(u===2){const c=(a>>2)+1,l=e[o+1]|e[o+2]<<8;let f=i-l;for(let p=0;p<c;p++)r[i++]=r[f++];o+=3}else{const c=(a>>2)+1,l=(e[o+1]|e[o+2]<<8|e[o+3]<<16|e[o+4]<<24)>>>0;let f=i-l;for(let p=0;p<c;p++)r[i++]=r[f++];o+=5}}return r}function Qt(e){let t=new Uint8Array(0),n=!1;return{push(r){if(t.length===0)t=r;else if(r.length){const i=new Uint8Array(t.length+r.length);i.set(t),i.set(r,t.length),t=i}let o=0;if(!n){if(t.length<Yt)return;ro(t,0),o=Yt,n=!0}for(;t.length-o>=4;){const i=no(t,o),s=o+4;if(t.length-s<i)break;const a=t.subarray(s,s+i);e(oo(a)),o=s+i}t=o>0?t.slice(o):t},end(){if(t.length!==0)throw new Error(`Trailing ${t.length} undecoded bytes in Snappy stream.`)}}}var en;const io=Object.freeze({status:"aborted"});function d(e,t,n){function r(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,u);const c=s.prototype,l=Object.keys(c);for(let f=0;f<l.length;f++){const p=l[f];p in a||(a[p]=c[p].bind(a))}}const o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var u;const c=n?.Parent?new i:this;r(c,a),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Ze extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class tn extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(en=globalThis).__zod_globalConfig??(en.__zod_globalConfig={});const kt=globalThis.__zod_globalConfig;function ue(e){return kt}function nn(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function wt(e,t){return typeof t=="bigint"?t.toString():t}function Ye(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function zt(e){return e==null}function bt(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function so(e,t){const n=e/t,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}const rn=Symbol("evaluating");function O(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==rn)return r===void 0&&(r=rn,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ze(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function me(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function on(e){return JSON.stringify(e)}function ao(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const sn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const co=Ye(()=>{if(kt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function xe(e){if(Fe(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Fe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function an(e){return xe(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const uo=new Set(["string","number","symbol"]);function Oe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ge(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function _(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function lo(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const fo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function po(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=me(e._zod.def,{get shape(){const s={};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return ze(this,"shape",s),s},checks:[]});return ge(e,i)}function ho(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=me(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return ze(this,"shape",s),s},checks:[]});return ge(e,i)}function mo(e,t){if(!xe(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=me(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return ze(this,"shape",i),i}});return ge(e,o)}function go(e,t){if(!xe(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=me(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ze(this,"shape",r),r}});return ge(e,n)}function vo(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=me(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ze(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ge(e,n)}function _o(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=me(t._zod.def,{get shape(){const a=t._zod.def.shape,u={...a};if(n)for(const c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(u[c]=e?new e({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)u[c]=e?new e({type:"optional",innerType:a[c]}):a[c];return ze(this,"shape",u),u},checks:[]});return ge(t,s)}function yo(e,t,n){const r=me(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return ze(this,"shape",i),i}});return ge(t,r)}function Ae(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function So(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ve(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Qe(e){return typeof e=="string"?e:e?.message}function le(e,t,n){const r=e.message?e.message:Qe(e.inst?._zod.def?.error?.(e))??Qe(t?.error?.(e))??Qe(n.customError?.(e))??Qe(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function Et(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Be(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const cn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,wt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},un=d("$ZodError",cn),ln=d("$ZodError",cn,{Parent:Error});function ko(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function wo(e,t=n=>n.message){const n={_errors:[]},r=(o,i=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>r({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...i,...s.path]);else{const a=[...i,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,c=0;for(;c<a.length;){const l=a[c];c===a.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(t(s))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}}};return r(e),n}const It=e=>(t,n,r,o)=>{const i=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Ze;if(s.issues.length){const a=new(o?.Err??e)(s.issues.map(u=>le(u,i,ue())));throw sn(a,o?.callee),a}return s.value},Tt=e=>async(t,n,r,o)=>{const i=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(o?.Err??e)(s.issues.map(u=>le(u,i,ue())));throw sn(a,o?.callee),a}return s.value},et=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ze;return i.issues.length?{success:!1,error:new(e??un)(i.issues.map(s=>le(s,o,ue())))}:{success:!0,data:i.value}},zo=et(ln),tt=e=>async(t,n,r)=>{const o=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>le(s,o,ue())))}:{success:!0,data:i.value}},bo=tt(ln),Eo=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return It(e)(t,n,o)},Io=e=>(t,n,r)=>It(e)(t,n,r),To=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return Tt(e)(t,n,o)},$o=e=>async(t,n,r)=>Tt(e)(t,n,r),Po=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return et(e)(t,n,o)},Zo=e=>(t,n,r)=>et(e)(t,n,r),xo=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return tt(e)(t,n,o)},Oo=e=>async(t,n,r)=>tt(e)(t,n,r),Ao=/^[cC][0-9a-z]{6,}$/,Mo=/^[0-9a-z]+$/,Ro=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,No=/^[0-9a-vA-V]{20}$/,Do=/^[A-Za-z0-9]{27}$/,Co=/^[a-zA-Z0-9_-]{21}$/,Lo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fn=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Uo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Fo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Bo(){return new RegExp(Fo,"u")}const Jo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Vo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,qo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Go=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pn=/^[A-Za-z0-9_-]*$/,Ko=/^https?$/,Ho=/^\+[1-9]\d{6,14}$/,hn="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Xo=new RegExp(`^${hn}$`);function dn(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Yo(e){return new RegExp(`^${dn(e)}$`)}function Qo(e){const t=dn({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${hn}T(?:${r})$`)}const ei=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},ti=/^-?\d+$/,mn=/^-?\d+(?:\.\d+)?$/,ni=/^(?:true|false)$/i,ri=/^null$/i,oi=/^[^A-Z]*$/,ii=/^[^a-z]*$/,te=d("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gn={number:"number",bigint:"bigint",object:"date"},vn=d("$ZodCheckLessThan",(e,t)=>{te.init(e,t);const n=gn[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_n=d("$ZodCheckGreaterThan",(e,t)=>{te.init(e,t);const n=gn[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),si=d("$ZodCheckMultipleOf",(e,t)=>{te.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):so(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ai=d("$ZodCheckNumberFormat",(e,t)=>{te.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=fo[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,n&&(a.pattern=ti)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),ci=d("$ZodCheckMaxLength",(e,t)=>{var n;te.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!zt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const s=Et(o);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ui=d("$ZodCheckMinLength",(e,t)=>{var n;te.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!zt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const s=Et(o);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),li=d("$ZodCheckLengthEquals",(e,t)=>{var n;te.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!zt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,i=o.length;if(i===t.length)return;const s=Et(o),a=i>t.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),nt=d("$ZodCheckStringFormat",(e,t)=>{var n,r;te.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),fi=d("$ZodCheckRegex",(e,t)=>{nt.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),pi=d("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=oi),nt.init(e,t)}),hi=d("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ii),nt.init(e,t)}),di=d("$ZodCheckIncludes",(e,t)=>{te.init(e,t);const n=Oe(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),mi=d("$ZodCheckStartsWith",(e,t)=>{te.init(e,t);const n=new RegExp(`^${Oe(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),gi=d("$ZodCheckEndsWith",(e,t)=>{te.init(e,t);const n=new RegExp(`.*${Oe(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),vi=d("$ZodCheckOverwrite",(e,t)=>{te.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class _i{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
2
- `).filter(s=>s),o=Math.min(...r.map(s=>s.length-s.trimStart().length)),i=r.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,o.join(`
3
- `))}}const yi={major:4,minor:4,patch:3},A=d("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yi;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const i of o._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,u)=>{let c=Ae(s),l;for(const f of a){if(f._zod.def.when){if(So(s)||!f._zod.def.when(s))continue}else if(c)continue;const p=s.issues.length,h=f._zod.check(s);if(h instanceof Promise&&u?.async===!1)throw new Ze;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await h,s.issues.length!==p&&(c||(c=Ae(s,p)))});else{if(s.issues.length===p)continue;c||(c=Ae(s,p))}}return l?l.then(()=>s):s},i=(s,a,u)=>{if(Ae(s))return s.aborted=!0,s;const c=o(a,r,u);if(c instanceof Promise){if(u.async===!1)throw new Ze;return c.then(l=>e._zod.parse(l,u))}return e._zod.parse(c,u)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(l=>i(l,s,a)):i(c,s,a)}const u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new Ze;return u.then(c=>o(c,r,a))}return o(u,r,a)}}O(e,"~standard",()=>({validate:o=>{try{const i=zo(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return bo(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),$t=d("$ZodString",(e,t)=>{A.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ei(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),C=d("$ZodStringFormat",(e,t)=>{nt.init(e,t),$t.init(e,t)}),Si=d("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jo),C.init(e,t)}),ki=d("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=fn(r))}else t.pattern??(t.pattern=fn());C.init(e,t)}),wi=d("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Uo),C.init(e,t)}),zi=d("$ZodURL",(e,t)=>{C.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===Ko.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),bi=d("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Bo()),C.init(e,t)}),Ei=d("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Co),C.init(e,t)}),Ii=d("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ao),C.init(e,t)}),Ti=d("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Mo),C.init(e,t)}),$i=d("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ro),C.init(e,t)}),Pi=d("$ZodXID",(e,t)=>{t.pattern??(t.pattern=No),C.init(e,t)}),Zi=d("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Do),C.init(e,t)}),xi=d("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Qo(t)),C.init(e,t)}),Oi=d("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Xo),C.init(e,t)}),Ai=d("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Yo(t)),C.init(e,t)}),Mi=d("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Lo),C.init(e,t)}),Ri=d("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Jo),C.init(e,t),e._zod.bag.format="ipv4"}),Ni=d("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Wo),C.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Di=d("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Vo),C.init(e,t)}),Ci=d("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=qo),C.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,i]=r;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function yn(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Li=d("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Go),C.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{yn(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function ji(e){if(!pn.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return yn(n)}const Ui=d("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=pn),C.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{ji(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Fi=d("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ho),C.init(e,t)});function Bi(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Ji=d("$ZodJWT",(e,t)=>{C.init(e,t),e._zod.check=n=>{Bi(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Sn=d("$ZodNumber",(e,t)=>{A.init(e,t),e._zod.pattern=e._zod.bag.pattern??mn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Wi=d("$ZodNumberFormat",(e,t)=>{ai.init(e,t),Sn.init(e,t)}),Vi=d("$ZodBoolean",(e,t)=>{A.init(e,t),e._zod.pattern=ni,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),qi=d("$ZodNull",(e,t)=>{A.init(e,t),e._zod.pattern=ri,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Gi=d("$ZodUnknown",(e,t)=>{A.init(e,t),e._zod.parse=n=>n}),Ki=d("$ZodNever",(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function kn(e,t,n){e.issues.length&&t.issues.push(...ve(n,e.issues)),t.value[n]=e.value}const Hi=d("$ZodArray",(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const a=o[s],u=t.element._zod.run({value:a,issues:[]},r);u instanceof Promise?i.push(u.then(c=>kn(c,n,s))):kn(u,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function rt(e,t,n,r,o,i){const s=n in r;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...ve(n,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function wn(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=lo(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function zn(e,t,n,r,o,i){const s=[],a=o.keySet,u=o.catchall._zod,c=u.def.type,l=u.optin==="optional",f=u.optout==="optional";for(const p in t){if(p==="__proto__"||a.has(p))continue;if(c==="never"){s.push(p);continue}const h=u.run({value:t[p],issues:[]},r);h instanceof Promise?e.push(h.then(m=>rt(m,n,p,t,l,f))):rt(h,n,p,t,l,f)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Xi=d("$ZodObject",(e,t)=>{if(A.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...a};return Object.defineProperty(t,"shape",{value:u}),u}})}const r=Ye(()=>wn(t));O(e._zod,"propValues",()=>{const a=t.shape,u={};for(const c in a){const l=a[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(const f of l.values)u[c].add(f)}}return u});const o=Fe,i=t.catchall;let s;e._zod.parse=(a,u)=>{s??(s=r.value);const c=a.value;if(!o(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),a;a.value={};const l=[],f=s.shape;for(const p of s.keys){const h=f[p],m=h._zod.optin==="optional",g=h._zod.optout==="optional",v=h._zod.run({value:c[p],issues:[]},u);v instanceof Promise?l.push(v.then(b=>rt(b,a,p,c,m,g))):rt(v,a,p,c,m,g)}return i?zn(l,c,a,u,r.value,e):l.length?Promise.all(l).then(()=>a):a}}),Yi=d("$ZodObjectJIT",(e,t)=>{Xi.init(e,t);const n=e._zod.parse,r=Ye(()=>wn(t)),o=p=>{const h=new _i(["shape","payload","ctx"]),m=r.value,g=k=>{const $=on(k);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};h.write("const input = payload.value;");const v=Object.create(null);let b=0;for(const k of m.keys)v[k]=`key_${b++}`;h.write("const newResult = {};");for(const k of m.keys){const $=v[k],E=on(k),z=p[k],F=z?._zod?.optin==="optional",W=z?._zod?.optout==="optional";h.write(`const ${$} = ${g(k)};`),F&&W?h.write(`
4
- if (${$}.issues.length) {
5
- if (${E} in input) {
6
- payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${E}, ...iss.path] : [${E}]
9
- })));
10
- }
11
- }
12
-
13
- if (${$}.value === undefined) {
14
- if (${E} in input) {
15
- newResult[${E}] = undefined;
16
- }
17
- } else {
18
- newResult[${E}] = ${$}.value;
19
- }
20
-
21
- `):F?h.write(`
22
- if (${$}.issues.length) {
23
- payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
24
- ...iss,
25
- path: iss.path ? [${E}, ...iss.path] : [${E}]
26
- })));
27
- }
28
-
29
- if (${$}.value === undefined) {
30
- if (${E} in input) {
31
- newResult[${E}] = undefined;
32
- }
33
- } else {
34
- newResult[${E}] = ${$}.value;
35
- }
36
-
37
- `):h.write(`
38
- const ${$}_present = ${E} in input;
39
- if (${$}.issues.length) {
40
- payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
41
- ...iss,
42
- path: iss.path ? [${E}, ...iss.path] : [${E}]
43
- })));
44
- }
45
- if (!${$}_present && !${$}.issues.length) {
46
- payload.issues.push({
47
- code: "invalid_type",
48
- expected: "nonoptional",
49
- input: undefined,
50
- path: [${E}]
51
- });
52
- }
53
-
54
- if (${$}_present) {
55
- if (${$}.value === undefined) {
56
- newResult[${E}] = undefined;
57
- } else {
58
- newResult[${E}] = ${$}.value;
59
- }
60
- }
61
-
62
- `)}h.write("payload.value = newResult;"),h.write("return payload;");const w=h.compile();return(k,$)=>w(p,k,$)};let i;const s=Fe,a=!kt.jitless,c=a&&co.value,l=t.catchall;let f;e._zod.parse=(p,h)=>{f??(f=r.value);const m=p.value;return s(m)?a&&c&&h?.async===!1&&h.jitless!==!0?(i||(i=o(t.shape)),p=i(p,h),l?zn([],m,p,h,f,e):p):n(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),p)}});function bn(e,t,n,r){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const o=e.filter(i=>!Ae(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>le(s,r,ue())))}),t)}const En=d("$ZodUnion",(e,t)=>{A.init(e,t),O(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),O(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),O(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),O(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>bt(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:r.value,issues:[]},o);if(u instanceof Promise)s.push(u),i=!0;else{if(u.issues.length===0)return u;s.push(u)}}return i?Promise.all(s).then(a=>bn(a,r,e,o)):bn(s,r,e,o)}}),Qi=d("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,En.init(e,t);const n=e._zod.parse;O(e._zod,"propValues",()=>{const o={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[a,u]of Object.entries(s)){o[a]||(o[a]=new Set);for(const c of u)o[a].add(c)}}return o});const r=Ye(()=>{const o=t.options,i=new Map;for(const s of o){const a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const u of a){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,s)}}return i});e._zod.parse=(o,i)=>{const s=o.value;if(!Fe(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const a=r.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback||i.direction==="backward"?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:s,path:[t.discriminator],inst:e}),o)}}),es=d("$ZodIntersection",(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},r),s=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([u,c])=>In(n,u,c)):In(n,i,s)}});function Pt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xe(e)&&xe(t)){const n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of r){const s=Pt(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],i=t[r],s=Pt(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function In(e,t,n){const r=new Map;let o;for(const a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(const u of a.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else e.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const u of a.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else e.issues.push(a);const i=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),Ae(e))return e;const s=Pt(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const ts=d("$ZodTuple",(e,t)=>{A.init(e,t);const n=t.items;e._zod.parse=(r,o)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];const s=[],a=Tn(n,"optin"),u=Tn(n,"optout");if(!t.rest){if(i.length<a)return r.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:e,origin:"array"}),r;i.length>n.length&&r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:e,origin:"array"})}const c=new Array(n.length);for(let l=0;l<n.length;l++){const f=n[l]._zod.run({value:i[l],issues:[]},o);f instanceof Promise?s.push(f.then(p=>{c[l]=p})):c[l]=f}if(t.rest){let l=n.length-1;const f=i.slice(n.length);for(const p of f){l++;const h=t.rest._zod.run({value:p,issues:[]},o);h instanceof Promise?s.push(h.then(m=>$n(m,r,l))):$n(h,r,l)}}return s.length?Promise.all(s).then(()=>Pn(c,r,n,i,u)):Pn(c,r,n,i,u)}});function Tn(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!=="optional")return n+1;return 0}function $n(e,t,n){e.issues.length&&t.issues.push(...ve(n,e.issues)),t.value[n]=e.value}function Pn(e,t,n,r,o){for(let i=0;i<n.length;i++){const s=e[i],a=i<r.length;if(s.issues.length){if(!a&&i>=o){t.value.length=i;break}t.issues.push(...ve(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=r.length&&(n[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}const ns=d("$ZodRecord",(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!xe(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[],s=t.keyType._zod.values;if(s){n.value={};const a=new Set;for(const c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);const l=t.keyType._zod.run({value:c,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(h=>le(h,r,ue())),input:c,path:[c],inst:e});continue}const f=l.value,p=t.valueType._zod.run({value:o[c],issues:[]},r);p instanceof Promise?i.push(p.then(h=>{h.issues.length&&n.issues.push(...ve(c,h.issues)),n.value[f]=h.value})):(p.issues.length&&n.issues.push(...ve(c,p.issues)),n.value[f]=p.value)}let u;for(const c in o)a.has(c)||(u=u??[],u.push(c));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let u=t.keyType._zod.run({value:a,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&mn.test(a)&&u.issues.length){const f=t.keyType._zod.run({value:Number(a),issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(u=f)}if(u.issues.length){t.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(f=>le(f,r,ue())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?i.push(l.then(f=>{f.issues.length&&n.issues.push(...ve(a,f.issues)),n.value[u.value]=f.value})):(l.issues.length&&n.issues.push(...ve(a,l.issues)),n.value[u.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),rs=d("$ZodEnum",(e,t)=>{A.init(e,t);const n=nn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>uo.has(typeof o)).map(o=>typeof o=="string"?Oe(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{const s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),os=d("$ZodLiteral",(e,t)=>{if(A.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Oe(r):r?Oe(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,o)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),is=d("$ZodTransform",(e,t)=>{A.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new tn(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new Ze;return n.value=o,n.fallback=!0,n}});function Zn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const xn=d("$ZodOptional",(e,t)=>{A.init(e,t),e._zod.optin="optional",e._zod.optout="optional",O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),O(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${bt(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>Zn(s,o)):Zn(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),ss=d("$ZodExactOptional",(e,t)=>{xn.init(e,t),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),as=d("$ZodNullable",(e,t)=>{A.init(e,t),O(e._zod,"optin",()=>t.innerType._zod.optin),O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${bt(n.source)}|null)$`):void 0}),O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),cs=d("$ZodDefault",(e,t)=>{A.init(e,t),e._zod.optin="optional",O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>On(i,t)):On(o,t)}});function On(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const us=d("$ZodPrefault",(e,t)=>{A.init(e,t),e._zod.optin="optional",O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),ls=d("$ZodNonOptional",(e,t)=>{A.init(e,t),O(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>An(i,e)):An(o,e)}});function An(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const fs=d("$ZodCatch",(e,t)=>{A.init(e,t),e._zod.optin="optional",O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>le(s,r,ue()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>le(i,r,ue()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),ps=d("$ZodPipe",(e,t)=>{A.init(e,t),O(e._zod,"values",()=>t.in._zod.values),O(e._zod,"optin",()=>t.in._zod.optin),O(e._zod,"optout",()=>t.out._zod.optout),O(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=t.out._zod.run(n,r);return i instanceof Promise?i.then(s=>ot(s,t.in,r)):ot(i,t.in,r)}const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(i=>ot(i,t.out,r)):ot(o,t.out,r)}});function ot(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const hs=d("$ZodReadonly",(e,t)=>{A.init(e,t),O(e._zod,"propValues",()=>t.innerType._zod.propValues),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"optin",()=>t.innerType?._zod?.optin),O(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Mn):Mn(o)}});function Mn(e){return e.value=Object.freeze(e.value),e}const ds=d("$ZodCustom",(e,t)=>{te.init(e,t),A.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>Rn(i,n,r,e));Rn(o,n,r,e)}});function Rn(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(Be(o))}}var Nn;class ms{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function gs(){return new ms}(Nn=globalThis).__zod_globalRegistry??(Nn.__zod_globalRegistry=gs());const Je=globalThis.__zod_globalRegistry;function vs(e,t){return new e({type:"string",..._(t)})}function _s(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,..._(t)})}function Dn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,..._(t)})}function ys(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,..._(t)})}function Ss(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(t)})}function ks(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(t)})}function ws(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(t)})}function zs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,..._(t)})}function bs(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,..._(t)})}function Es(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(t)})}function Is(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,..._(t)})}function Ts(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(t)})}function $s(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,..._(t)})}function Ps(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,..._(t)})}function Zs(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(t)})}function xs(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(t)})}function Os(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(t)})}function As(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(t)})}function Ms(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(t)})}function Rs(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,..._(t)})}function Ns(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,..._(t)})}function Ds(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,..._(t)})}function Cs(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,..._(t)})}function Ls(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(t)})}function js(e,t){return new e({type:"string",format:"date",check:"string_format",..._(t)})}function Us(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,..._(t)})}function Fs(e,t){return new e({type:"string",format:"duration",check:"string_format",..._(t)})}function Bs(e,t){return new e({type:"number",checks:[],..._(t)})}function Js(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",..._(t)})}function Ws(e,t){return new e({type:"boolean",..._(t)})}function Vs(e,t){return new e({type:"null",..._(t)})}function qs(e){return new e({type:"unknown"})}function Gs(e,t){return new e({type:"never",..._(t)})}function Cn(e,t){return new vn({check:"less_than",..._(t),value:e,inclusive:!1})}function Zt(e,t){return new vn({check:"less_than",..._(t),value:e,inclusive:!0})}function Ln(e,t){return new _n({check:"greater_than",..._(t),value:e,inclusive:!1})}function xt(e,t){return new _n({check:"greater_than",..._(t),value:e,inclusive:!0})}function jn(e,t){return new si({check:"multiple_of",..._(t),value:e})}function Un(e,t){return new ci({check:"max_length",..._(t),maximum:e})}function it(e,t){return new ui({check:"min_length",..._(t),minimum:e})}function Fn(e,t){return new li({check:"length_equals",..._(t),length:e})}function Ks(e,t){return new fi({check:"string_format",format:"regex",..._(t),pattern:e})}function Hs(e){return new pi({check:"string_format",format:"lowercase",..._(e)})}function Xs(e){return new hi({check:"string_format",format:"uppercase",..._(e)})}function Ys(e,t){return new di({check:"string_format",format:"includes",..._(t),includes:e})}function Qs(e,t){return new mi({check:"string_format",format:"starts_with",..._(t),prefix:e})}function ea(e,t){return new gi({check:"string_format",format:"ends_with",..._(t),suffix:e})}function Me(e){return new vi({check:"overwrite",tx:e})}function ta(e){return Me(t=>t.normalize(e))}function na(){return Me(e=>e.trim())}function ra(){return Me(e=>e.toLowerCase())}function oa(){return Me(e=>e.toUpperCase())}function ia(){return Me(e=>ao(e))}function sa(e,t,n){return new e({type:"array",element:t,..._(n)})}function aa(e,t,n){return new e({type:"custom",check:"custom",fn:t,..._(n)})}function ca(e,t){const n=ua(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Be(o,r.value,n._zod.def));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(Be(i))}},e(r.value,r)),t);return n}function ua(e,t){const n=new te({check:"custom",..._(t)});return n._zod.check=e,n}function Bn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Je,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function U(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{const p=s.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,p,l)}const f=e._zod.parent;f&&(s.ref||(s.ref=f),U(f,t,l),t.seen.get(f).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&Object.assign(s.schema,u),t.io==="input"&&Q(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Jn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const u=r.get(a);if(u&&u!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}const o=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const f=e.external.registry.get(s[0])?.id,p=e.external.uri??(m=>m);if(f)return{ref:p(f)};const h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${p("__shared")}#/${a}/${h}`}}if(s[1]===n)return{ref:"#"};const c=`#/${a}/`,l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},i=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:u,defId:c}=o(s);a.def={...a.schema},c&&(a.defId=c);const l=a.schema;for(const f in l)delete l[f];l.$ref=u};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
-
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){i(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&e.reused==="ref"){i(s);continue}}}function Wn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=a=>{const u=e.seen.get(a);if(u.ref===null)return;const c=u.def??u.schema,l={...c},f=u.ref;if(u.ref=null,f){r(f);const h=e.seen.get(f),m=h.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(m)):Object.assign(c,m),Object.assign(c,l),a._zod.parent===f)for(const v in c)v==="$ref"||v==="allOf"||v in l||delete c[v];if(m.$ref&&h.def)for(const v in c)v==="$ref"||v==="allOf"||v in h.def&&JSON.stringify(c[v])===JSON.stringify(h.def[v])&&delete c[v]}const p=a._zod.parent;if(p&&p!==f){r(p);const h=e.seen.get(p);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const m in c)m==="$ref"||m==="allOf"||m in h.def&&JSON.stringify(c[m])===JSON.stringify(h.def[m])&&delete c[m]}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};for(const a of[...e.seen.entries()].reverse())r(a[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const a of e.seen.entries()){const u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,s[u.defId]=u.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:st(t,"input",e.processors),output:st(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Q(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Q(r.element,n);if(r.type==="set")return Q(r.valueType,n);if(r.type==="lazy")return Q(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Q(r.innerType,n);if(r.type==="intersection")return Q(r.left,n)||Q(r.right,n);if(r.type==="record"||r.type==="map")return Q(r.keyType,n)||Q(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Q(r.in,n)||Q(r.out,n);if(r.type==="object"){for(const o in r.shape)if(Q(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if(Q(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if(Q(o,n))return!0;return!!(r.rest&&Q(r.rest,n))}return!1}const la=(e,t={})=>n=>{const r=Bn({...n,processors:t});return U(e,r),Jn(r,e),Wn(r,e)},st=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},s=Bn({...o??{},target:i,io:t,processors:n});return U(e,s),Jn(s,e),Wn(s,e)},fa={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pa=(e,t,n,r)=>{const o=n;o.type="string";const{minimum:i,maximum:s,format:a,patterns:u,contentEncoding:c}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=fa[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),c&&(o.contentEncoding=c),u&&u.size>0){const l=[...u];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},ha=(e,t,n,r)=>{const o=n,{minimum:i,maximum:s,format:a,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";const f=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";f?h?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof i=="number"&&(o.minimum=i),p?h?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c:typeof s=="number"&&(o.maximum=s),typeof u=="number"&&(o.multipleOf=u)},da=(e,t,n,r)=>{n.type="boolean"},ma=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},ga=(e,t,n,r)=>{n.not={}},va=(e,t,n,r)=>{},_a=(e,t,n,r)=>{const o=e._zod.def,i=nn(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},ya=(e,t,n,r)=>{const o=e._zod.def,i=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},Sa=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},ka=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},wa=(e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=U(i.element,t,{...r,path:[...r.path,"items"]})},za=(e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const c in s)o.properties[c]=U(s[c],t,{...r,path:[...r.path,"properties",c]});const a=new Set(Object.keys(s)),u=new Set([...a].filter(c=>{const l=i.shape[c]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));u.size>0&&(o.required=Array.from(u)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=U(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ba=(e,t,n,r)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,u)=>U(a,t,{...r,path:[...r.path,i?"oneOf":"anyOf",u]}));i?n.oneOf=s:n.anyOf=s},Ea=(e,t,n,r)=>{const o=e._zod.def,i=U(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=U(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=u},Ia=(e,t,n,r)=>{const o=n,i=e._zod.def;o.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((p,h)=>U(p,t,{...r,path:[...r.path,s,h]})),c=i.rest?U(i.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=u,c&&(o.items=c)):t.target==="openapi-3.0"?(o.items={anyOf:u},c&&o.items.anyOf.push(c),o.minItems=u.length,c||(o.maxItems=u.length)):(o.items=u,c&&(o.additionalItems=c));const{minimum:l,maximum:f}=e._zod.bag;typeof l=="number"&&(o.minItems=l),typeof f=="number"&&(o.maxItems=f)},Ta=(e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const s=i.keyType,u=s._zod.bag?.patterns;if(i.mode==="loose"&&u&&u.size>0){const l=U(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const f of u)o.patternProperties[f.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=U(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=U(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=s._zod.values;if(c){const l=[...c].filter(f=>typeof f=="string"||typeof f=="number");l.length>0&&(o.required=l)}},$a=(e,t,n,r)=>{const o=e._zod.def,i=U(o.innerType,t,r),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},Pa=(e,t,n,r)=>{const o=e._zod.def;U(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType},Za=(e,t,n,r)=>{const o=e._zod.def;U(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},xa=(e,t,n,r)=>{const o=e._zod.def;U(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Oa=(e,t,n,r)=>{const o=e._zod.def;U(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Aa=(e,t,n,r)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;U(s,t,r);const a=t.seen.get(e);a.ref=s},Ma=(e,t,n,r)=>{const o=e._zod.def;U(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Vn=(e,t,n,r)=>{const o=e._zod.def;U(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType},Ra=d("ZodISODateTime",(e,t)=>{xi.init(e,t),L.init(e,t)});function Na(e){return Ls(Ra,e)}const Da=d("ZodISODate",(e,t)=>{Oi.init(e,t),L.init(e,t)});function Ca(e){return js(Da,e)}const La=d("ZodISOTime",(e,t)=>{Ai.init(e,t),L.init(e,t)});function ja(e){return Us(La,e)}const Ua=d("ZodISODuration",(e,t)=>{Mi.init(e,t),L.init(e,t)});function Fa(e){return Fs(Ua,e)}const re=d("ZodError",(e,t)=>{un.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>wo(e,n)},flatten:{value:n=>ko(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,wt,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,wt,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Ba=It(re),Ja=Tt(re),Wa=et(re),Va=tt(re),qa=Eo(re),Ga=Io(re),Ka=To(re),Ha=$o(re),Xa=Po(re),Ya=Zo(re),Qa=xo(re),ec=Oo(re),qn=new WeakMap;function We(e,t,n){const r=Object.getPrototypeOf(e);let o=qn.get(r);if(o||(o=new Set,qn.set(r,o)),!o.has(t)){o.add(t);for(const i in n){const s=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const R=d("ZodType",(e,t)=>(A.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:st(e,"input"),output:st(e,"output")}}),e.toJSONSchema=la(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Ba(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Wa(e,n,r),e.parseAsync=async(n,r)=>Ja(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Va(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>qa(e,n,r),e.decode=(n,r)=>Ga(e,n,r),e.encodeAsync=async(n,r)=>Ka(e,n,r),e.decodeAsync=async(n,r)=>Ha(e,n,r),e.safeEncode=(n,r)=>Xa(e,n,r),e.safeDecode=(n,r)=>Ya(e,n,r),e.safeEncodeAsync=async(n,r)=>Qa(e,n,r),e.safeDecodeAsync=async(n,r)=>ec(e,n,r),We(e,"ZodType",{check(...n){const r=this.def;return this.clone(me(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return ge(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Xc(n,r))},superRefine(n,r){return this.check(Yc(n,r))},overwrite(n){return this.check(Me(n))},optional(){return nr(this)},exactOptional(){return Cc(this)},nullable(){return rr(this)},nullish(){return nr(rr(this))},nonoptional(n){return Jc(this,n)},array(){return fe(this)},or(n){return Ee([this,n])},and(n){return xc(this,n)},transform(n){return ir(this,Nc(n))},default(n){return Uc(this,n)},prefault(n){return Bc(this,n)},catch(n){return Vc(this,n)},pipe(n){return ir(this,n)},readonly(){return Kc(this)},describe(n){const r=this.clone();return Je.add(r,{description:n}),r},meta(...n){if(n.length===0)return Je.get(this);const r=this.clone();return Je.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Je.get(e)?.description},configurable:!0}),e)),Gn=d("_ZodString",(e,t)=>{$t.init(e,t),R.init(e,t),e._zod.processJSONSchema=(r,o,i)=>pa(e,r,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,We(e,"_ZodString",{regex(...r){return this.check(Ks(...r))},includes(...r){return this.check(Ys(...r))},startsWith(...r){return this.check(Qs(...r))},endsWith(...r){return this.check(ea(...r))},min(...r){return this.check(it(...r))},max(...r){return this.check(Un(...r))},length(...r){return this.check(Fn(...r))},nonempty(...r){return this.check(it(1,...r))},lowercase(r){return this.check(Hs(r))},uppercase(r){return this.check(Xs(r))},trim(){return this.check(na())},normalize(...r){return this.check(ta(...r))},toLowerCase(){return this.check(ra())},toUpperCase(){return this.check(oa())},slugify(){return this.check(ia())}})}),tc=d("ZodString",(e,t)=>{$t.init(e,t),Gn.init(e,t),e.email=n=>e.check(_s(nc,n)),e.url=n=>e.check(zs(rc,n)),e.jwt=n=>e.check(Cs(_c,n)),e.emoji=n=>e.check(bs(oc,n)),e.guid=n=>e.check(Dn(Kn,n)),e.uuid=n=>e.check(ys(at,n)),e.uuidv4=n=>e.check(Ss(at,n)),e.uuidv6=n=>e.check(ks(at,n)),e.uuidv7=n=>e.check(ws(at,n)),e.nanoid=n=>e.check(Es(ic,n)),e.guid=n=>e.check(Dn(Kn,n)),e.cuid=n=>e.check(Is(sc,n)),e.cuid2=n=>e.check(Ts(ac,n)),e.ulid=n=>e.check($s(cc,n)),e.base64=n=>e.check(Rs(mc,n)),e.base64url=n=>e.check(Ns(gc,n)),e.xid=n=>e.check(Ps(uc,n)),e.ksuid=n=>e.check(Zs(lc,n)),e.ipv4=n=>e.check(xs(fc,n)),e.ipv6=n=>e.check(Os(pc,n)),e.cidrv4=n=>e.check(As(hc,n)),e.cidrv6=n=>e.check(Ms(dc,n)),e.e164=n=>e.check(Ds(vc,n)),e.datetime=n=>e.check(Na(n)),e.date=n=>e.check(Ca(n)),e.time=n=>e.check(ja(n)),e.duration=n=>e.check(Fa(n))});function T(e){return vs(tc,e)}const L=d("ZodStringFormat",(e,t)=>{C.init(e,t),Gn.init(e,t)}),nc=d("ZodEmail",(e,t)=>{wi.init(e,t),L.init(e,t)}),Kn=d("ZodGUID",(e,t)=>{Si.init(e,t),L.init(e,t)}),at=d("ZodUUID",(e,t)=>{ki.init(e,t),L.init(e,t)}),rc=d("ZodURL",(e,t)=>{zi.init(e,t),L.init(e,t)}),oc=d("ZodEmoji",(e,t)=>{bi.init(e,t),L.init(e,t)}),ic=d("ZodNanoID",(e,t)=>{Ei.init(e,t),L.init(e,t)}),sc=d("ZodCUID",(e,t)=>{Ii.init(e,t),L.init(e,t)}),ac=d("ZodCUID2",(e,t)=>{Ti.init(e,t),L.init(e,t)}),cc=d("ZodULID",(e,t)=>{$i.init(e,t),L.init(e,t)}),uc=d("ZodXID",(e,t)=>{Pi.init(e,t),L.init(e,t)}),lc=d("ZodKSUID",(e,t)=>{Zi.init(e,t),L.init(e,t)}),fc=d("ZodIPv4",(e,t)=>{Ri.init(e,t),L.init(e,t)}),pc=d("ZodIPv6",(e,t)=>{Ni.init(e,t),L.init(e,t)}),hc=d("ZodCIDRv4",(e,t)=>{Di.init(e,t),L.init(e,t)}),dc=d("ZodCIDRv6",(e,t)=>{Ci.init(e,t),L.init(e,t)}),mc=d("ZodBase64",(e,t)=>{Li.init(e,t),L.init(e,t)}),gc=d("ZodBase64URL",(e,t)=>{Ui.init(e,t),L.init(e,t)}),vc=d("ZodE164",(e,t)=>{Fi.init(e,t),L.init(e,t)}),_c=d("ZodJWT",(e,t)=>{Ji.init(e,t),L.init(e,t)}),Hn=d("ZodNumber",(e,t)=>{Sn.init(e,t),R.init(e,t),e._zod.processJSONSchema=(r,o,i)=>ha(e,r,o),We(e,"ZodNumber",{gt(r,o){return this.check(Ln(r,o))},gte(r,o){return this.check(xt(r,o))},min(r,o){return this.check(xt(r,o))},lt(r,o){return this.check(Cn(r,o))},lte(r,o){return this.check(Zt(r,o))},max(r,o){return this.check(Zt(r,o))},int(r){return this.check(Xn(r))},safe(r){return this.check(Xn(r))},positive(r){return this.check(Ln(0,r))},nonnegative(r){return this.check(xt(0,r))},negative(r){return this.check(Cn(0,r))},nonpositive(r){return this.check(Zt(0,r))},multipleOf(r,o){return this.check(jn(r,o))},step(r,o){return this.check(jn(r,o))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function y(e){return Bs(Hn,e)}const yc=d("ZodNumberFormat",(e,t)=>{Wi.init(e,t),Hn.init(e,t)});function Xn(e){return Js(yc,e)}const Sc=d("ZodBoolean",(e,t)=>{Vi.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>da(e,n,r)});function be(e){return Ws(Sc,e)}const kc=d("ZodNull",(e,t)=>{qi.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ma(e,n,r)});function wc(e){return Vs(kc,e)}const zc=d("ZodUnknown",(e,t)=>{Gi.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>va()});function Ve(){return qs(zc)}const bc=d("ZodNever",(e,t)=>{Ki.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ga(e,n,r)});function Ec(e){return Gs(bc,e)}const Ic=d("ZodArray",(e,t)=>{Hi.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wa(e,n,r,o),e.element=t.element,We(e,"ZodArray",{min(n,r){return this.check(it(n,r))},nonempty(n){return this.check(it(1,n))},max(n,r){return this.check(Un(n,r))},length(n,r){return this.check(Fn(n,r))},unwrap(){return this.element}})});function fe(e,t){return sa(Ic,e,t)}const Tc=d("ZodObject",(e,t)=>{Yi.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>za(e,n,r,o),O(e,"shape",()=>t.shape),We(e,"ZodObject",{keyof(){return Ac(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ve()})},loose(){return this.clone({...this._zod.def,catchall:Ve()})},strict(){return this.clone({...this._zod.def,catchall:Ec()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return mo(this,n)},safeExtend(n){return go(this,n)},merge(n){return vo(this,n)},pick(n){return po(this,n)},omit(n){return ho(this,n)},partial(...n){return _o(tr,this,n[0])},required(...n){return yo(or,this,n[0])}})});function Z(e,t){const n={type:"object",shape:e??{},..._(t)};return new Tc(n)}const Yn=d("ZodUnion",(e,t)=>{En.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ba(e,n,r,o),e.options=t.options});function Ee(e,t){return new Yn({type:"union",options:e,..._(t)})}const $c=d("ZodDiscriminatedUnion",(e,t)=>{Yn.init(e,t),Qi.init(e,t)});function Pc(e,t,n){return new $c({type:"union",options:t,discriminator:e,..._(n)})}const Zc=d("ZodIntersection",(e,t)=>{es.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ea(e,n,r,o)});function xc(e,t){return new Zc({type:"intersection",left:e,right:t})}const Oc=d("ZodTuple",(e,t)=>{ts.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ia(e,n,r,o),e.rest=n=>e.clone({...e._zod.def,rest:n})});function Qn(e,t,n){const r=t instanceof A,o=r?n:t,i=r?t:null;return new Oc({type:"tuple",items:e,rest:i,..._(o)})}const er=d("ZodRecord",(e,t)=>{ns.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ta(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ot(e,t,n){return!t||!t._zod?new er({type:"record",keyType:T(),valueType:e,..._(t)}):new er({type:"record",keyType:e,valueType:t,..._(n)})}const At=d("ZodEnum",(e,t)=>{rs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(r,o,i)=>_a(e,r,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const i={};for(const s of r)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new At({...t,checks:[],..._(o),entries:i})},e.exclude=(r,o)=>{const i={...t.entries};for(const s of r)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new At({...t,checks:[],..._(o),entries:i})}});function Ac(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new At({type:"enum",entries:n,..._(t)})}const Mc=d("ZodLiteral",(e,t)=>{os.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ya(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function H(e,t){return new Mc({type:"literal",values:Array.isArray(e)?e:[e],..._(t)})}const Rc=d("ZodTransform",(e,t)=>{is.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ka(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new tn(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(Be(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Be(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Nc(e){return new Rc({type:"transform",transform:e})}const tr=d("ZodOptional",(e,t)=>{xn.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vn(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function nr(e){return new tr({type:"optional",innerType:e})}const Dc=d("ZodExactOptional",(e,t)=>{ss.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vn(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Cc(e){return new Dc({type:"optional",innerType:e})}const Lc=d("ZodNullable",(e,t)=>{as.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$a(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function rr(e){return new Lc({type:"nullable",innerType:e})}const jc=d("ZodDefault",(e,t)=>{cs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Za(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Uc(e,t){return new jc({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():an(t)}})}const Fc=d("ZodPrefault",(e,t)=>{us.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xa(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Bc(e,t){return new Fc({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():an(t)}})}const or=d("ZodNonOptional",(e,t)=>{ls.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pa(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Jc(e,t){return new or({type:"nonoptional",innerType:e,..._(t)})}const Wc=d("ZodCatch",(e,t)=>{fs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oa(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Vc(e,t){return new Wc({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const qc=d("ZodPipe",(e,t)=>{ps.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Aa(e,n,r,o),e.in=t.in,e.out=t.out});function ir(e,t){return new qc({type:"pipe",in:e,out:t})}const Gc=d("ZodReadonly",(e,t)=>{hs.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ma(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Kc(e){return new Gc({type:"readonly",innerType:e})}const Hc=d("ZodCustom",(e,t)=>{ds.init(e,t),R.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sa(e,n)});function Xc(e,t={}){return aa(Hc,e,t)}function Yc(e,t){return ca(e,t)}const Qc={custom:"custom"},eu=Z({name:T(),accumulatorId:y().optional(),value:Ee([T(),y()]).optional(),metricType:T().optional()}),sr=Z({nodeName:T(),simpleString:T().optional(),metrics:fe(eu).optional(),metadata:Ot(T(),Ve()).optional(),children:fe(Ve())}),ar=500;function tu(e){const t=sr.parse(e),r=[{shallow:t,children:[],pendingRaw:[...t.children],depth:0}],o=new Map;for(;r.length>0;){const i=r[r.length-1];if(i.pendingRaw.length===0){r.pop();const c={...i.shallow,children:i.children},l=o.get(i);if(l){l.children.push(c);continue}return c}if(i.depth>ar)throw new Error(`sparkPlanInfo tree exceeds max depth of ${ar}`);const s=i.pendingRaw.shift(),a=sr.parse(s),u={shallow:a,children:[],pendingRaw:[...a.children],depth:i.depth+1};o.set(u,i),r.push(u)}throw new Error("unreachable: sparkPlanInfo tree stack exhausted without resolving root")}const cr=Ve().nullable().optional().transform((e,t)=>{if(e==null)return null;try{return tu(e)}catch(n){return t.addIssue({code:Qc.custom,message:n instanceof Error?n.message:String(n)}),io}}),nu=Z({Event:H("SparkListenerLogStart"),"Spark Version":T().optional()}),ru=Z({Event:H("SparkListenerApplicationStart"),"App ID":T().optional(),"App Name":T().optional(),Timestamp:y().optional(),"Spark Version":T().optional()}),ur=Ee([T(),y(),be()]),ou=Z({Event:H("SparkListenerEnvironmentUpdate"),"Spark Properties":Ee([Ot(T(),ur),fe(Qn([T(),ur])),wc()]).optional()}),iu=Z({Event:H("SparkListenerApplicationEnd"),Timestamp:y().optional()}),su=Z({Event:H("SparkListenerExecutorAdded"),Timestamp:y(),"Executor ID":T(),"Executor Info":Z({Host:T().optional(),"Total Cores":y().optional(),"Resource Profile Id":y().optional()}).optional(),"Resource Profile Id":y().optional()}),au=Z({Event:H("SparkListenerExecutorRemoved"),Timestamp:y(),"Executor ID":T(),"Removed Reason":T().optional()}),cu=Z({Event:H("SparkListenerJobStart"),"Job ID":y().optional(),"Submission Time":y().optional(),"Stage IDs":fe(y()).optional(),Properties:Z({"spark.sql.execution.id":Ee([T(),y()]).optional()}).optional()}),uu=Z({Event:H("SparkListenerJobEnd"),"Job ID":y(),"Completion Time":y().optional(),"Job Result":Z({Result:T().optional(),Exception:Z({Message:T().optional()}).optional()}).optional()}),lu=Z({"RDD ID":y().optional(),Name:T().optional(),Callsite:T().optional(),"Storage Level":Z({"Use Disk":be().optional(),"Use Memory":be().optional(),Deserialized:be().optional(),Replication:y().optional()}).optional(),"Number of Partitions":y().optional(),"Number of Cached Partitions":y().optional(),"Memory Size":y().optional(),"Disk Size":y().optional()}),fu=Z({Event:H("SparkListenerStageSubmitted"),"Stage Info":Z({"Stage ID":y(),"Stage Name":T().optional(),Details:T().optional(),"Submission Time":y().optional(),"Parent IDs":fe(y()).optional(),"RDD Info":fe(lu).optional()})}),pu=Z({Event:H("SparkListenerStageCompleted"),"Stage Info":Z({"Stage ID":y(),"Completion Time":y().optional(),"Failure Reason":T().optional()})}),hu=Z({Event:H("SparkListenerStageExecutorMetrics"),"Stage ID":y(),"Executor ID":T(),"Executor Metrics":Ot(T(),y()).optional()}),du=Z({Event:H("SparkListenerTaskEnd"),"Stage ID":y(),"Stage Attempt ID":y().optional(),"Task End Reason":Z({Reason:T().optional()}).optional(),"Task Info":Z({"Launch Time":y().optional(),"Finish Time":y().optional(),Failed:be().optional(),Killed:be().optional(),Speculative:be().optional(),Host:T().optional(),"Executor ID":T().optional(),Locality:T().optional(),Index:y().optional(),"Task ID":y().optional(),"Attempt Number":y().optional(),Accumulables:fe(Z({ID:y(),Update:Ee([T(),y()]).optional(),Value:Ee([T(),y()]).optional()})).max(1e4).optional()}).optional(),"Task Metrics":Z({"Peak Execution Memory":y().optional(),"JVM GC Time":y().optional(),"Memory Bytes Spilled":y().optional(),"Disk Bytes Spilled":y().optional(),"Executor Run Time":y().optional(),"Executor CPU Time":y().optional(),"Shuffle Read Metrics":Z({"Remote Bytes Read":y().optional(),"Local Bytes Read":y().optional(),"Fetch Wait Time":y().optional()}).optional(),"Shuffle Write Metrics":Z({"Shuffle Bytes Written":y().optional()}).optional(),"Input Metrics":Z({"Bytes Read":y().optional()}).optional(),"Output Metrics":Z({"Bytes Written":y().optional()}).optional()}).optional()}),mu=Z({Event:H("org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionStart"),executionId:y(),description:T().optional(),time:y(),physicalPlanDescription:T().optional(),sparkPlanInfo:cr}),gu=Z({Event:H("org.apache.spark.sql.execution.ui.SparkListenerSQLAdaptiveExecutionUpdate"),executionId:y(),physicalPlanDescription:T().optional(),sparkPlanInfo:cr}),vu=Z({Event:H("org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionEnd"),executionId:y(),time:y()}),_u=Z({Event:H("org.apache.spark.sql.execution.ui.SparkListenerDriverAccumUpdates"),executionId:y(),accumUpdates:fe(Qn([y(),y()]))}),lr=Pc("Event",[nu,ru,ou,iu,cu,uu,fu,pu,hu,du,mu,gu,vu,_u,su,au]);function yu(e){throw new Error(`Unreachable case: ${JSON.stringify(e)}`)}const ct=[{key:"DURATION",name:"duration",prop:"duration"},{key:"GC_TIME",name:"gcTime",prop:"gcTime"},{key:"MEM_SPILLED",name:"memorySpilled",prop:"memSpilled"},{key:"DISK_SPILLED",name:"diskSpilled",prop:"diskSpilled"},{key:"SHUFFLE_READ",name:"shuffleRead",prop:"shuffleRead"},{key:"SHUFFLE_WRITE",name:"shuffleWrite",prop:"shuffleWrite"},{key:"LAUNCH_TIME",name:"launchTime",prop:"launchTime"},{key:"FINISH_TIME",name:"finishTime",prop:"finishTime"}],Su=ct.length,ku=20,G=Object.freeze({...Object.fromEntries(ct.map((e,t)=>[e.key,t])),STRIDE:Su}),wu=ct.map(e=>e.name),fr=ct.map(e=>e.prop);function zu(e,t,n){if(t.taskAttempts===null)return null;const r=t,o=[];let i=0,s=0,a=0;const u=new Map,c=new Map,l=new Map,f=[],p=new Map;let h=0;for(const S of t.taskAttempts.values()){if(i++,S.failed&&(s++,S.reason&&l.set(S.reason,(l.get(S.reason)??0)+1),f.length<ku&&f.push({taskId:S.taskId,attemptNumber:S.attemptNumber,host:S.host,executorId:S.executorId,reason:S.reason,peakExecMem:S.peakExecMem,memSpilled:S.memSpilled,shuffleWrite:S.shuffleWrite})),S.speculative&&a++,S.host){let P=u.get(S.host);P||(P={taskCount:0,totalDuration:0},u.set(S.host,P)),P.taskCount++,P.totalDuration+=S.duration}if(S.executorId){let P=c.get(S.executorId);P||(P={taskCount:0,totalDuration:0,inputBytes:0,shuffleReadBytes:0,shuffleWriteBytes:0},c.set(S.executorId,P)),P.taskCount++,P.totalDuration+=S.duration,P.inputBytes+=S.inputBytes,P.shuffleReadBytes+=S.shuffleRead,P.shuffleWriteBytes+=S.shuffleWrite}S.locality&&p.set(S.locality,(p.get(S.locality)??0)+1),S.peakExecMem>h&&(h=S.peakExecMem),r.shuffleReadBytes+=S.shuffleRead,r.shuffleWriteBytes+=S.shuffleWrite,r.fetchWaitTime+=S.fetchWaitTime,r.memoryBytesSpilled+=S.memSpilled,r.diskBytesSpilled+=S.diskSpilled,r.jvmGCTime+=S.gcTime,r.executorRunTime+=S.executorRunTime,r.executorCpuTime+=S.executorCpuTime,r.inputBytes+=S.inputBytes,r.outputBytes+=S.outputBytes;for(let P=0;P<fr.length;P++)o.push(S[fr[P]])}t.taskCount=i,t.failedTasks=s,t.speculativeTasks=a,t.taskAttempts=null;const m=new Float64Array(o);n.taskStore.set(e,m);const{p50:g,p95:v,max:b}=bu(m),w=r.memoryBytesSpilled>0?Eu(m):"unclassified",{p50:k,p95:$,max:E}=ut(m,G.SHUFFLE_READ),{p50:z,p95:F,max:W}=ut(m,G.MEM_SPILLED),{p50:q,p95:J,max:N}=ut(m,G.DISK_SPILLED),ee=4*g;let X=0;const x=m.length/G.STRIDE;if(g>0)for(let S=0;S<x;S++)m[S*G.STRIDE+G.DURATION]>ee&&X++;const I=[...u.entries()].map(([S,P])=>({host:S,taskCount:P.taskCount,totalDuration:P.totalDuration})),B=[...c.entries()].map(([S,P])=>({executorId:S,taskCount:P.taskCount,totalDuration:P.totalDuration,inputBytes:P.inputBytes,shuffleReadBytes:P.shuffleReadBytes,shuffleWriteBytes:P.shuffleWriteBytes})),se=[...l.entries()].map(([S,P])=>({reason:S,count:P})),pe=[...p.entries()].map(([S,P])=>({locality:S,count:P})),Y={...t,hostStats:I,executorStats:B,failureReasons:se,localityStats:pe,stragglerCount:X,failedTaskSamples:f,peakExecutionMemoryMax:h,taskDurationP50:g,taskDurationP95:v,taskDurationMax:b,shuffleReadP50:k,shuffleReadP95:$,shuffleReadMax:E,spillMemP50:z,spillMemP95:F,spillMemMax:W,spillDiskP50:q,spillDiskP95:J,spillDiskMax:N,gcPct:r.executorRunTime>0?r.jvmGCTime/r.executorRunTime*100:0,spillClassification:w,stageType:r.shuffleReadBytes>0?"REDUCE":"MAP"};return delete Y.taskAttempts,{type:"stage",data:Y}}function ut(e,t){const n=e.length/G.STRIDE;if(n===0)return{p50:0,p95:0,max:0};const r=new Float64Array(n);for(let o=0;o<n;o++)r[o]=e[o*G.STRIDE+t];return r.sort(),{p50:r[Math.ceil(n*.5)-1],p95:r[Math.ceil(n*.95)-1],max:r[n-1]}}function bu(e){return ut(e,G.DURATION)}function Eu(e){const t=e.length/G.STRIDE;if(t===0)return"unclassified";let n=0;for(let o=0;o<t;o++)e[o*G.STRIDE+G.MEM_SPILLED]===0&&n++;const r=n/t;return r>=.8?"skew":r<.2?"volume":"unclassified"}function Iu(e,t){const n=[];for(const{launch:i,finish:s}of e)s>i&&(n.push({t:i,delta:1}),n.push({t:s,delta:-1}));n.sort((i,s)=>i.t-s.t||i.delta-s.delta);const r=[];let o=0;for(let i=0;i<n.length;i++){const s=n[i];o+=s.delta;const a=n[i+1];if(!a||a.t===s.t)continue;const u=t!=null?Math.min(o,t):o;r.push({tStart:s.t,tEnd:a.t,busy:u})}return r}function Tu(e,{bucketBy:t="time",bucketWidthMs:n=1e3,hypotheticalCores:r=null}={}){const o=Iu(e,r);if(t==="coreCount"){const u=[];for(const c of o)u[c.busy]=(u[c.busy]??0)+(c.tEnd-c.tStart);for(let c=0;c<u.length;c++)u[c]===void 0&&(u[c]=0);return{mode:"coreCount",histogram:u}}if(o.length===0)return{mode:"time",bucketWidthMs:n,startTime:null,endTime:null,buckets:[]};const i=o[0].tStart,s=o[o.length-1].tEnd,a=[];for(let u=i;u<s;u+=n){const c=u+n;let l=0;for(const f of o){const p=Math.max(f.tStart,u),h=Math.min(f.tEnd,c);h>p&&(l+=f.busy*(h-p))}a.push({tStart:u,tEnd:c,busyCoreMs:l,avgBusyCores:l/n})}return{mode:"time",bucketWidthMs:n,startTime:i,endTime:s,buckets:a}}function $u(e){const t=[],n={};for(const[s,a]of e){const u=a.length/G.STRIDE;let c=0;for(let l=0;l<u;l++){const f=l*G.STRIDE,p=a[f+G.LAUNCH_TIME],h=a[f+G.FINISH_TIME];c+=a[f+G.DURATION],h>p&&t.push({launch:p,finish:h})}n[s]={totalTaskDurationSum:c,taskCount:u}}const{histogram:r}=Tu(t,{bucketBy:"coreCount"});let o=0;for(let s=0;s<r.length;s++)o+=s*r[s];const i=r.length>0?r.length-1:0;return{coreHistogram:r,busyCoreMs:o,peakConcurrentCores:i,perStage:n}}const pr=20,lt=10;function Mt(){const e=new TextDecoder("utf-8");let t="";return{decode(n){const r=[],o=e.decode(n,{stream:!0}),i=t===""?o:t+o,s=t.length,a=n.length;let u=0;if(o.length===a){let c=n.indexOf(lt,0);for(;c!==-1;){const l=s+c;l>u&&r.push(i.substring(u,l)),u=l+1,c=n.indexOf(lt,c+1)}}else{let c=s,l=0;if(a>0&&(n[0]&192)===128){const p=o.charCodeAt(0);for(c+=p>=55296&&p<=56319?2:1;l<a&&(n[l]&192)===128;)l++}let f=n.indexOf(lt,l);for(;f!==-1;){for(let p=l;p<f;p++){const h=n[p];h<128?c++:h>=240?c+=2:h>=192&&c++}c>u&&r.push(i.substring(u,c)),c++,u=c,l=f+1,f=n.indexOf(lt,l)}}return t=u<i.length?i.substring(u):"",r},flush(){const n=(t+e.decode()).trim();return t="",n?[n]:[]}}}function Rt(){return{app:null,pendingSparkVersion:null,pendingConfig:null,pendingResources:null,stages:new Map,taskStore:new Map,sqlExecutions:new Map,stageToSqlExec:new Map,sqlExecStages:new Map,jobs:new Map,executors:{added:[],removed:[]},skippedLines:0,accumState:new Map,rddInfo:new Map,taskAccumStages:new Map,evidenceInputs:{environmentUpdates:0,applicationEnds:0,stageSubmissions:0,rddStorageSnapshots:0,sqlExecutions:0,resolvedSqlPlans:0,executorMetricRows:0,taskRecords:0}}}function Pu(e){if(Array.isArray(e)){const n={};for(const r of e)Array.isArray(r)&&r.length>=2&&(n[r[0]]=String(r[1]));return n}const t={};for(const[n,r]of Object.entries(e??{}))t[n]=String(r);return t}function Zu(e){if(e==null)return null;const t=String(e).trim().toLowerCase().match(/^([\d.]+)\s*([kmgt]?)(b?)$/);if(!t)return null;const n=parseFloat(t[1]);if(!Number.isFinite(n))return null;switch(t[2]){case"k":return Math.round(n/1024);case"g":return Math.round(n*1024);case"t":return Math.round(n*1024*1024);case"m":return Math.round(n);default:return t[3]==="b"?Math.round(n/(1024*1024)):Math.round(n)}}function hr(e){const t=e??{},n=i=>{if(t[i]==null)return null;const s=parseInt(t[i],10);return Number.isFinite(s)?s:null},r=i=>t[i]!=null?Zu(t[i]):null,o=i=>t[i]!=null?String(t[i]).toLowerCase()==="true":null;return{executor:{memory:t["spark.executor.memory"]??null,memoryMB:r("spark.executor.memory"),memoryOverhead:t["spark.executor.memoryOverhead"]??null,memoryOverheadMB:r("spark.executor.memoryOverhead"),cores:n("spark.executor.cores"),instances:n("spark.executor.instances")},driver:{memory:t["spark.driver.memory"]??null,memoryMB:r("spark.driver.memory"),memoryOverhead:t["spark.driver.memoryOverhead"]??null,memoryOverheadMB:r("spark.driver.memoryOverhead"),cores:n("spark.driver.cores")},dynamicAllocationEnabled:o("spark.dynamicAllocation.enabled"),shuffleServiceEnabled:o("spark.shuffle.service.enabled"),serializer:t["spark.serializer"]??null}}function xu(e){const t=new Map;for(const[n,r]of e)t.set(n,{...r,stageIds:[...r.stageIds].sort((o,i)=>o-i)});return t}function Ou(e){return{...e.evidenceInputs}}function ft(e){const t=Ou(e);return e.app.evidenceInputs=t,{type:"app",data:{...e.app,rddInfo:xu(e.rddInfo)}}}function dr(e){return{taskId:e.taskId,attemptNumber:e.attemptNumber,host:e.host,executorId:e.executorId,reason:e.reason,peakExecMem:e.peakExecMem,memSpilled:e.memSpilled,shuffleWrite:e.shuffleWrite}}function Au(e,t){const n=e["Stage ID"],r=t.stages.get(n);if(!r||r.taskAttempts===null)return null;t.evidenceInputs.taskRecords++;const o=e["Task Info"]?.Accumulables??[];for(const b of o)t.taskAccumStages.has(b.ID)||t.taskAccumStages.set(b.ID,new Set),t.taskAccumStages.get(b.ID).add(n);const i=e["Task Info"]??{},s=e["Task Metrics"]??{},a=s["Shuffle Read Metrics"]??{},u=s["Shuffle Write Metrics"]??{},c=s["Input Metrics"]??{},l=s["Output Metrics"]??{},f=(i["Finish Time"]??0)-(i["Launch Time"]??0),p=!!(i.Failed||i.Killed),h={duration:f,failed:p,taskId:i["Task ID"]??null,attemptNumber:i["Attempt Number"]??0,launchTime:i["Launch Time"]??0,finishTime:i["Finish Time"]??0,reason:e["Task End Reason"]?.Reason??null,speculative:i.Speculative===!0,host:i.Host??"",executorId:i["Executor ID"]??"",locality:i.Locality??null,peakExecMem:s["Peak Execution Memory"]??0,gcTime:s["JVM GC Time"]??0,memSpilled:s["Memory Bytes Spilled"]??0,diskSpilled:s["Disk Bytes Spilled"]??0,shuffleRead:(a["Remote Bytes Read"]??0)+(a["Local Bytes Read"]??0),shuffleWrite:u["Shuffle Bytes Written"]??0,fetchWaitTime:a["Fetch Wait Time"]??0,executorRunTime:s["Executor Run Time"]??0,executorCpuTime:s["Executor CPU Time"]??0,inputBytes:c["Bytes Read"]??0,outputBytes:l["Bytes Written"]??0},m=i.Index,g=m!=null?`${e["Stage Attempt ID"]??0}:${m}`:Symbol("no-index"),v=r.taskAttempts.get(g);return v?v.failed&&!h.failed?(v.speculative||h.speculative?(r.speculationWasteMs+=v.duration,r.speculationWastedAttempts++):(r.retryWasteMs+=v.duration,r.wastedAttempts++,r.retryTaskSamples.length<pr&&r.retryTaskSamples.push(dr(v))),r.taskAttempts.set(g,h)):v.speculative||h.speculative?(r.speculationWasteMs+=h.duration,r.speculationWastedAttempts++):(r.retryWasteMs+=h.duration,r.wastedAttempts++,r.retryTaskSamples.length<pr&&r.retryTaskSamples.push(dr(h))):r.taskAttempts.set(g,h),null}function Mu(e,t,n,r,o){const i=new WeakSet,s=new WeakMap;let a=0;const u=o!=null?`e${o}:`:"";function c(m){const g=(m.metrics??[]).reduce((b,w)=>(w.accumulatorId!==void 0&&t.has(w.accumulatorId)&&b.push({name:w.name,value:t.get(w.accumulatorId),metricType:w.metricType}),b),[]),v=new Set;for(const b of m.metrics??[]){if(b.accumulatorId===void 0)continue;const w=n.get(b.accumulatorId);if(w)for(const k of w)r&&r.has(k)&&v.add(k)}return v.size>0?{metrics:g,stageIds:[...v].sort((b,w)=>b-w)}:{metrics:g}}function l(m,g){const{metrics:v,stageIds:b}=c(m),w={id:`${u}n${a++}`,name:m.nodeName,detail:m.simpleString??"",metrics:v,children:g};return b&&(w.stageIds=b),w}function f(m,g){const{metrics:v,stageIds:b}=c(m),w={id:`${u}n${a++}`,name:m.nodeName,detail:"",metrics:v,children:g,exchangeRole:"write"};b&&(w.stageIds=b);const k={id:`${u}n${a++}`,name:m.nodeName,detail:m.simpleString??"",metrics:[],children:[w],exchangeRole:"read"};return b&&(k.stageIds=b),k}const p=[e],h=[];for(;p.length>0;){const m=p.pop();if(!i.has(m)){i.add(m),h.push(m);for(const g of m.children??[])i.has(g)||p.push(g)}}for(let m=h.length-1;m>=0;m--){const g=h[m],v=[];for(const w of g.children??[]){const k=s.get(w);k&&v.push(k)}const b=g.nodeName==="Exchange"||g.nodeName==="BroadcastExchange"?f(g,v):l(g,v);s.set(g,b)}return s.get(e)}const Ru={JVMHeapMemory:"jvmHeapMemory",JVMOffHeapMemory:"jvmOffHeapMemory",OnHeapExecutionMemory:"onHeapExecutionMemory",OffHeapExecutionMemory:"offHeapExecutionMemory",OnHeapStorageMemory:"onHeapStorageMemory",OffHeapStorageMemory:"offHeapStorageMemory",OnHeapUnifiedMemory:"onHeapUnifiedMemory",OffHeapUnifiedMemory:"offHeapUnifiedMemory",DirectPoolMemory:"directPoolMemory",MappedPoolMemory:"mappedPoolMemory",ProcessTreeJVMVMemory:"processTreeJVMVMemory",ProcessTreeJVMRSSMemory:"processTreeJVMRSSMemory",ProcessTreePythonVMemory:"processTreePythonVMemory",ProcessTreePythonRSSMemory:"processTreePythonRSSMemory",ProcessTreeOtherVMemory:"processTreeOtherVMemory",ProcessTreeOtherRSSMemory:"processTreeOtherRSSMemory",MinorGCCount:"minorGCCount",MinorGCTime:"minorGCTime",MajorGCCount:"majorGCCount",MajorGCTime:"majorGCTime",TotalGCTime:"totalGCTime",ConcurrentGCCount:"concurrentGCCount",ConcurrentGCTime:"concurrentGCTime"};function Nu(e,t){const n=t.pendingConfig??{};return t.app={id:e["App ID"],name:e["App Name"],startTime:e.Timestamp,endTime:null,sparkVersion:t.pendingSparkVersion??e["Spark Version"]??null,config:n,resources:t.pendingResources??hr(n),rddInfo:t.rddInfo},ft(t)}function Du(e,t){t.evidenceInputs.environmentUpdates++;const n=Pu(e["Spark Properties"]),r=hr(n);return t.app?(t.app.config=n,t.app.resources=r,ft(t)):(t.pendingConfig=n,t.pendingResources=r,null)}function Cu(e,t){const n=e["Stage IDs"]??[],r=e.Properties?.["spark.sql.execution.id"],o=r!=null?parseInt(String(r),10):null;if(o!=null){t.sqlExecStages.has(o)||t.sqlExecStages.set(o,new Set);const s=t.sqlExecStages.get(o);for(const a of n)t.stageToSqlExec.set(a,o),s.add(a)}const i=e["Job ID"];return i!=null&&t.jobs.set(i,{id:i,submissionTime:e["Submission Time"]??null,stageIds:n,sqlExecutionId:o,result:null,succeeded:null,exception:null,completionTime:null}),null}function Lu(e,t){const n=e["Job ID"],r=e["Job Result"]?.Result??null,o=e["Job Result"]?.Exception?.Message??null,i=t.jobs.get(n)??{id:n,submissionTime:null,stageIds:[],sqlExecutionId:null,result:null,succeeded:null,exception:null,completionTime:null};return i.result=r,i.succeeded=r==="JobSucceeded",i.exception=o,i.completionTime=e["Completion Time"]??null,t.jobs.set(n,i),{type:"job",data:{...i}}}function ju(e,t){t.evidenceInputs.stageSubmissions++;const n=e["Stage Info"],r=n["Stage ID"];return t.stages.set(r,{id:r,name:n["Stage Name"]??"",details:n.Details??"",submittedAt:n["Submission Time"]??0,completedAt:0,taskCount:0,failedTasks:0,shuffleReadBytes:0,shuffleWriteBytes:0,fetchWaitTime:0,memoryBytesSpilled:0,diskBytesSpilled:0,jvmGCTime:0,executorRunTime:0,executorCpuTime:0,inputBytes:0,outputBytes:0,sqlExecutionId:t.stageToSqlExec.get(r)??null,parentIds:n["Parent IDs"]??[],hostStats:new Map,speculativeTasks:0,failureReasons:new Map,stageFailureReason:null,taskAttempts:new Map,retryTaskSamples:[],retryWasteMs:0,wastedAttempts:0,speculationWasteMs:0,speculationWastedAttempts:0,executorMetrics:new Map}),Uu(n,r,t),null}function Uu(e,t,n){for(const r of e["RDD Info"]??[]){const o=r["RDD ID"];if(o==null)continue;n.evidenceInputs.rddStorageSnapshots++;const i=r["Storage Level"]??{},s=n.rddInfo.get(o),a=s?.stageIds??new Set;a.add(t),n.rddInfo.set(o,{id:o,name:r.Name??"",callsite:r.Callsite??"",storageLevel:{useDisk:i["Use Disk"]??!1,useMemory:i["Use Memory"]??!1,deserialized:i.Deserialized??!1,replication:i.Replication??1},numPartitions:r["Number of Partitions"]??0,numCachedPartitions:r["Number of Cached Partitions"]||s?.numCachedPartitions||0,memorySize:r["Memory Size"]||s?.memorySize||0,diskSize:r["Disk Size"]||s?.diskSize||0,stageIds:a})}}function Fu(e,t){const n=t.stages.get(e["Stage ID"]);if(!n)return null;const r=e["Executor Metrics"]??{},o={};for(const[i,s]of Object.entries(Ru))r[i]!=null&&(o[s]=r[i]);return Object.keys(o).length>0&&t.evidenceInputs.executorMetricRows++,n.executorMetrics.set(e["Executor ID"],o),null}function Bu(e,t){t.evidenceInputs.sqlExecutions++;const n=e.sparkPlanInfo??null,r={id:e.executionId,description:e.description??"",startTime:e.time,endTime:null,stageIds:[],physicalPlanDescription:e.physicalPlanDescription??"",sparkPlanInfo:n,hadAdaptiveUpdate:!1};return t.sqlExecutions.set(r.id,r),n!==null&&t.accumState.set(r.id,new Map),{type:"sql",data:r}}function Ju(e,t){const n=t.sqlExecutions.get(e.executionId);n&&(n.endTime=e.time);const r=n?.sparkPlanInfo??null;if(!r||!r.nodeName)return t.accumState.delete(e.executionId),n?{type:"sql",data:{...n}}:null;const o=t.accumState.get(e.executionId)??new Map,i=Mu(r,o,t.taskAccumStages,t.sqlExecStages.get(e.executionId),e.executionId);return t.accumState.delete(e.executionId),t.evidenceInputs.resolvedSqlPlans++,{type:"sqlPlan",data:{executionId:e.executionId,planTree:i}}}function Wu(e,t){const{executionId:n,accumUpdates:r}=e;if(!t.accumState.has(n))return null;const o=t.accumState.get(n);for(const[i,s]of r)o.set(i,(o.get(i)??0)+s);return null}function Vu(e,t){const n=t.sqlExecutions.get(e.executionId);return n?(e.sparkPlanInfo!=null&&(n.sparkPlanInfo=e.sparkPlanInfo),e.physicalPlanDescription!=null&&(n.physicalPlanDescription=e.physicalPlanDescription),n.hadAdaptiveUpdate=!0,{type:"sql",data:{...n}}):null}function qu(e,t){const n={kind:"added",timestamp:e.Timestamp,executorId:e["Executor ID"],host:e["Executor Info"]?.Host??"",totalCores:e["Executor Info"]?.["Total Cores"]??0,resourceProfileId:e["Executor Info"]?.["Resource Profile Id"]??e["Resource Profile Id"]??null};return t.executors.added.push(n),{type:"executor",data:n}}function Gu(e,t){const n={kind:"removed",timestamp:e.Timestamp,executorId:e["Executor ID"],reason:e["Removed Reason"]??""};return t.executors.removed.push(n),{type:"executor",data:n}}function Ku(e,t){switch(e.Event){case"SparkListenerLogStart":return t.pendingSparkVersion=e["Spark Version"]??null,null;case"SparkListenerApplicationStart":return Nu(e,t);case"SparkListenerEnvironmentUpdate":return Du(e,t);case"SparkListenerApplicationEnd":return t.evidenceInputs.applicationEnds++,t.app?(t.app.endTime=e.Timestamp,ft(t)):null;case"SparkListenerJobStart":return Cu(e,t);case"SparkListenerJobEnd":return Lu(e,t);case"SparkListenerStageSubmitted":return ju(e,t);case"SparkListenerStageCompleted":{const n=e["Stage Info"],r=n["Stage ID"],o=t.stages.get(r);return o?(o.completedAt=n["Completion Time"]??0,o.stageFailureReason=n["Failure Reason"]??null,zu(r,o,t)):null}case"SparkListenerStageExecutorMetrics":return Fu(e,t);case"SparkListenerTaskEnd":return Au(e,t);case"org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionStart":return Bu(e,t);case"org.apache.spark.sql.execution.ui.SparkListenerSQLAdaptiveExecutionUpdate":return Vu(e,t);case"org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionEnd":return Ju(e,t);case"org.apache.spark.sql.execution.ui.SparkListenerDriverAccumUpdates":return Wu(e,t);case"SparkListenerExecutorAdded":return qu(e,t);case"SparkListenerExecutorRemoved":return Gu(e,t);default:return yu(e)}}const Hu=new Set(lr.options.map(e=>e.shape.Event.value));function Re(e,t,n){let r;try{r=JSON.parse(e)}catch{t.skippedLines++;return}const o=r?.Event;if(typeof o!="string"||!Hu.has(o))return;const i=lr.safeParse(r);if(!i.success){t.skippedLines++;return}let s;try{s=Ku(i.data,t)}catch(a){console.error("processEvent threw for an already-validated event:",a),t.skippedLines++;return}s&&n(s)}function Xu(e){const t=new Map;for(const[n,r]of e.stages)r.executorMetrics instanceof Map&&r.executorMetrics.size>0&&t.set(n,r.executorMetrics);return t}function Nt(e,t,n){t({type:"progress",pct:1,linesProcessed:n}),t({type:"runAggregates",data:$u(e.taskStore)}),t({type:"stageExecutorMetrics",data:Xu(e)}),t(ft(e)),t({type:"done",skippedLines:e.skippedLines}),e.accumState.clear()}const Yu=new Set(["local-server-unavailable","upstream-unreachable","application-not-found","access-or-upstream-failure","invalid-event-log"]);function Qu({baseUrl:e,appId:t,attemptId:n}){const r=[["baseUrl",e],["appId",t]];return n!==null&&r.push(["attemptId",n]),`/shs-proxy?${r.map(([o,i])=>`${o}=${encodeURIComponent(i)}`).join("&")}`}function el(e){return typeof e=="string"&&Yu.has(e)}const tl=Z({code:T()}).passthrough();function mr(e,t){const n=s=>s.match(/(\d+)|(\D+)/g)??[s],r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){const a=r[s]??"",u=o[s]??"";if(a===u)continue;const c=Number(a),l=Number(u);return!Number.isNaN(c)&&!Number.isNaN(l)?c-l:a<u?-1:1}return 0}function nl(e){const n=e.filter(c=>!c.toLowerCase().startsWith("appstatus")).filter(c=>/^events_\d+_/.test(c)),r=c=>parseInt(c.match(/^events_(\d+)_/)[1],10),o=n.filter(c=>c.endsWith(".compact")).map(r),i=o.length>0?Math.max(...o):-1,a=n.filter(c=>{const l=r(c);return c.endsWith(".compact")?l===i:l>i}).sort(mr),u=a.map(r);for(let c=1;c<u.length;c++)if(u[c]!==u[c-1]+1)throw new Error(`Rolling event-log directory is missing file(s) between index ${u[c-1]} and ${u[c]}.`);return a}function gr(e){if(e.length>=2&&e[0]===31&&e[1]===139)return"gz";if(e.length>=4&&e[0]===40&&e[1]===181&&e[2]===47&&e[3]===253)return"zstd";const t=[76,90,52,66,108,111,99,107];if(e.length>=8&&t.every((r,o)=>e[o]===r))return"lz4";const n=[130,83,78,65,80,80,89,0];return e.length>=8&&n.every((r,o)=>e[o]===r)?"snappy":null}function rl(e,t,n){const r=gr(t);if(r==="lz4"||e.endsWith(".lz4")){const o=qt(n);o.push(t),o.end()}else if(r==="gz"||e.endsWith(".gz"))new Wt(n).push(t,!0);else if(r==="zstd"||e.endsWith(".zstd")||e.endsWith(".zst"))new Xt(n).push(t,!0);else if(r==="snappy"||e.endsWith(".snappy")){const o=Qt(n);o.push(t),o.end()}else n(t)}function ie(e,t){e({type:"error",source:"shs",code:t})}async function ol(e,t,{fetchImpl:n=fetch,emit:r=o=>self.postMessage(o)}={}){const o=Qu(e);let i;try{i=await n(o)}catch{ie(r,"local-server-unavailable");return}if(i.status===404){ie(r,"local-server-unavailable");return}if(!i.ok){let c="access-or-upstream-failure";try{const l=tl.parse(await i.json());el(l.code)&&(c=l.code)}catch{}ie(r,c);return}if(!i.body){ie(r,"invalid-event-log");return}let s,a;try{a=Number(i.headers.get("content-length"))||null;const c=i.body.getReader(),l=[];let f=0;for(;;){const{done:h,value:m}=await c.read();if(h)break;l.push(m),f+=m.length,(!a||f<a)&&r({type:"progress",pct:a?f/a*.5:null,linesProcessed:0})}s=new Uint8Array(f);let p=0;for(const h of l)s.set(h,p),p+=h.length}catch{ie(r,"local-server-unavailable");return}if((i.headers.get("content-type")||"").startsWith("text/html")){ie(r,"local-server-unavailable");return}a&&r({type:"progress",pct:.5,linesProcessed:0}),il(s,t,r)}function il(e,t,n){let r;try{r=Dr(e)}catch{ie(n,"invalid-event-log");return}const o=Object.keys(r),i=o.some(c=>/^events_\d+_/.test(c));let s;if(i)try{s=nl(o)}catch{ie(n,"invalid-event-log");return}else s=o.filter(c=>c.toLowerCase()!=="appstatus").sort(mr);if(s.length===0){ie(n,"invalid-event-log");return}const a=Mt();let u=0;for(const c of s)try{rl(c,r[c],l=>{for(const f of a.decode(l))Re(f,t,n),u++,u%2e3===0&&n({type:"progress",pct:null,linesProcessed:u})})}catch{ie(n,"invalid-event-log");return}for(const c of a.flush())Re(c,t,n);if(!t.app){ie(n,"invalid-event-log");return}Nt(t,n,u)}const vr=512*1024,sl=100,_r=300;async function yr(e,t,n){const r=new Uint8Array(await e.slice(0,Math.min(8,e.size)).arrayBuffer()),o=gr(r);let i=0;const s=o==="gz"?new Wt(p=>t(p,i)):null,a=o==="lz4"?qt(p=>t(p,i)):null,u=o==="zstd"?new Xt(p=>t(p,i)):null,c=o==="snappy"?Qt(p=>t(p,i)):null,l=Math.max(1,Math.min(n,Math.ceil(e.size/sl)));let f=0;for(;f<e.size;){const p=f,h=new Uint8Array(await e.slice(p,p+l).arrayBuffer());f+=l;const m=f>=e.size;i=p/e.size,s?s.push(h,m):a?a.push(h):u?u.push(h,m):c?c.push(h):t(h,i)}a&&a.end(),c&&c.end()}async function al(e,t,{emit:n=o=>self.postMessage(o),chunkSize:r=vr}={}){if(e.size===0){n({type:"error",message:"File is empty."});return}const o=Mt();let i=0;const s=(a,u)=>{for(const c of o.decode(a))Re(c,t,n),i++,i%_r===0&&n({type:"progress",pct:u??null,linesProcessed:i})};try{await yr(e,s,r)}catch(a){const u=a instanceof Error?a.message:String(a);n({type:"error",message:`Could not decompress "${e.name}": ${u}`});return}for(const a of o.flush())Re(a,t,n);if(!t.app){n({type:"error",message:"Not a Spark event log: SparkListenerApplicationStart not found."});return}Nt(t,n,i)}async function cl(e,t,{emit:n=o=>self.postMessage(o),chunkSize:r=vr}={}){if(e.length===0){n({type:"error",message:"Rolling event-log directory contained no event files."});return}const o=Mt();let i=0;const s=e.reduce((l,f)=>l+f.size,0);let a=0,u=0;const c=(l,f)=>{for(const p of o.decode(l))if(Re(p,t,n),i++,i%_r===0){const h=s>0?(a+(f??0)*u)/s:null;n({type:"progress",pct:h,linesProcessed:i})}};for(const l of e){u=l.size;try{await yr(l,c,r)}catch(f){const p=f instanceof Error?f.message:String(f);n({type:"error",message:`Could not decompress "${l.name}": ${p}`});return}a+=l.size}for(const l of o.flush())Re(l,t,n);if(!t.app){n({type:"error",message:"Not a Spark event log: SparkListenerApplicationStart not found."});return}Nt(t,n,i)}if(typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope){let e=null;self.onmessage=async({data:t})=>{if(t.type==="parse")e=Rt(),await al(t.file,e);else if(t.type==="parseFromUrl")e=Rt(),await ol(t.request,e);else if(t.type==="parseFiles")e=Rt(),await cl(t.files,e);else if(t.type==="getTaskData"){const{stageId:n,reqId:r}=t,o=e?.taskStore.get(n)??new Float64Array(0);self.postMessage({type:"taskData",stageId:n,reqId:r,metrics:o.slice(),fieldNames:wu})}}}})();