@marimo-team/frontend 0.25.3-dev125 → 0.25.3-dev127

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 (96) hide show
  1. package/dist/assets/{CellStatus-_Aw9_foI.js → CellStatus-FhctFTd5.js} +1 -1
  2. package/dist/assets/{ErrorBoundary-DxSzjvbx.js → ErrorBoundary-D8cNDEWs.js} +2 -2
  3. package/dist/assets/{JsonOutput-B7pGj79O.js → JsonOutput-CKF7zS56.js} +1 -1
  4. package/dist/assets/{MarimoErrorOutput-Bzo6Bkp5.js → MarimoErrorOutput-BzRg-_e8.js} +1 -1
  5. package/dist/assets/{RenderHTML-D6AC0IhC.js → RenderHTML-BWp2DyZX.js} +1 -1
  6. package/dist/assets/{RunButton-BjYsPiKa.js → RunButton-Bgk4RWmz.js} +1 -1
  7. package/dist/assets/{add-cell-with-ai-CFrR1iW4.js → add-cell-with-ai-DdZy8mLi.js} +1 -1
  8. package/dist/assets/{add-connection-dialog-CyNAB_W2.js → add-connection-dialog-C8jZYKdn.js} +1 -1
  9. package/dist/assets/{agent-panel-VOrccb5q.js → agent-panel-Ds9Pb9Dq.js} +1 -1
  10. package/dist/assets/{ai-model-dropdown-Bfxv_zvu.js → ai-model-dropdown-CBDzZx1M.js} +1 -1
  11. package/dist/assets/{app-config-button-BRcjv8A_.js → app-config-button-D5D_EmY9.js} +1 -1
  12. package/dist/assets/{blob-DTYOX-m5.js → blob-CJNyvsia.js} +1 -1
  13. package/dist/assets/{cell-editor-eKgYK8Bd.js → cell-editor-BTr9z5Wp.js} +1 -1
  14. package/dist/assets/{cell-link-D3rkqgbU.js → cell-link-I5T63SlT.js} +1 -1
  15. package/dist/assets/{cells-2HETnlvE.js → cells-B3LEgMh1.js} +1 -1
  16. package/dist/assets/{chat-display-BrT4VJJK.js → chat-display-H16VjlZr.js} +1 -1
  17. package/dist/assets/{chat-panel-qpPNEwxV.js → chat-panel-DqrzqlCD.js} +1 -1
  18. package/dist/assets/{chat-ui-SAdJxg-k.js → chat-ui-DySzMqSB.js} +1 -1
  19. package/dist/assets/{code-visibility-DYDagVy7.js → code-visibility-E6qbtstz.js} +1 -1
  20. package/dist/assets/{column-preview-yI7-INkZ.js → column-preview-BdBJaVZ4.js} +1 -1
  21. package/dist/assets/{command-palette-DF-B_YpW.js → command-palette-Dc3C7NM6.js} +1 -1
  22. package/dist/assets/{common-DgXKwblm.js → common-Cqs8TPV5.js} +1 -1
  23. package/dist/assets/{components-CuMhY4Sf.js → components-Cwi1jZWr.js} +1 -1
  24. package/dist/assets/{config-CD1IuZFJ.js → config-BTFDx3Zj.js} +1 -1
  25. package/dist/assets/{config-DMz7oN0r.js → config-CqfGrErg.js} +1 -1
  26. package/dist/assets/{datasource-D9JMcEAP.js → datasource-D1_5m7Yd.js} +1 -1
  27. package/dist/assets/{dependency-graph-panel-BVJWPCvw.js → dependency-graph-panel-C4zXeWSh.js} +1 -1
  28. package/dist/assets/{documentation-panel--wI4XHso.js → documentation-panel-mAZeRrD1.js} +1 -1
  29. package/dist/assets/{download-Dod42wfD.js → download-CE9fT9D_.js} +1 -1
  30. package/dist/assets/{edit-page-Uj9YSRMX.js → edit-page-B85w4NTO.js} +4 -4
  31. package/dist/assets/{error-entries-D00nWhWE.js → error-entries-Dx8Rtti7.js} +1 -1
  32. package/dist/assets/{error-panel-CcN_1PWf.js → error-panel-DAXHR0Ch.js} +1 -1
  33. package/dist/assets/feedback-button-BPkAz7n4.js +1 -0
  34. package/dist/assets/{feedback-button-ByGgqUsX.js → feedback-button-C62fC5qU.js} +1 -1
  35. package/dist/assets/{file-explorer-panel-eTEqtMPW.js → file-explorer-panel-BwZcEQr-.js} +1 -1
  36. package/dist/assets/{file-name-input-D5SfTNWh.js → file-name-input-CmwUD7Hx.js} +1 -1
  37. package/dist/assets/{floating-outline-B-k3P_AO.js → floating-outline-PAiDriV4.js} +1 -1
  38. package/dist/assets/{gallery-page-BzbMhDHi.js → gallery-page-C6ayh2RI.js} +1 -1
  39. package/dist/assets/{glide-data-editor-BMqhUrHI.js → glide-data-editor-C4RmQotP.js} +1 -1
  40. package/dist/assets/{home-page-DJcYWiga.js → home-page-DKgFJ5fQ.js} +1 -1
  41. package/dist/assets/{hooks-CGLb_CCz.js → hooks-B3z6BXDe.js} +1 -1
  42. package/dist/assets/{index-bSIORW11.js → index-Cu7PYFi7.js} +6 -6
  43. package/dist/assets/{layout-C2XnLAfO.js → layout-BD9wfU32.js} +3 -3
  44. package/dist/assets/{logs-panel-B3T1GFBk.js → logs-panel-CTdAN6rZ.js} +1 -1
  45. package/dist/assets/{markdown-renderer-BhiTvxtL.js → markdown-renderer-BbXJkH92.js} +1 -1
  46. package/dist/assets/{name-cell-input-CgAObR6N.js → name-cell-input-CmZvZAsE.js} +1 -1
  47. package/dist/assets/{outline-panel-BhBb7Vqw.js → outline-panel-D8aMHyb1.js} +1 -1
  48. package/dist/assets/{packages-panel-Bt0xNpFl.js → packages-panel-_-hESZFB.js} +1 -1
  49. package/dist/assets/{panel-accordion-state-ZsUdpAYn.js → panel-accordion-state-DXo4a0Uu.js} +1 -1
  50. package/dist/assets/panels-RQ6Xn9SS.js +1 -0
  51. package/dist/assets/{process-output-CeOMwE17.js → process-output-BIrwpJB4.js} +1 -1
  52. package/dist/assets/{readonly-code-display-TvOC7ESE.js → readonly-code-display-yuks_SYy.js} +1 -1
  53. package/dist/assets/{readonly-python-code-Cqkfdeyo.js → readonly-python-code-BhBEAP6F.js} +1 -1
  54. package/dist/assets/{reveal-component-CwE6U9oJ.js → reveal-component-rMF_Gs2J.js} +1 -1
  55. package/dist/assets/{run-page-CtonWTtJ.js → run-page-BiotN_kV.js} +1 -1
  56. package/dist/assets/{runtime-details-state-CKqJSfSR.js → runtime-details-state-Bv77N7ch.js} +1 -1
  57. package/dist/assets/{scratchpad-panel-CwVBedfZ.js → scratchpad-panel-DRp6uxVD.js} +1 -1
  58. package/dist/assets/{session-panel-CdHdKUCF.js → session-panel-D_AV0U6M.js} +1 -1
  59. package/dist/assets/{snippets-panel-DYLWOLYw.js → snippets-panel-BPrNsfAG.js} +1 -1
  60. package/dist/assets/{state-DgECPVFs.js → state-Bvy6oc4o.js} +3 -3
  61. package/dist/assets/{state-DZN9vZ6z.js → state-DMO2unyy.js} +1 -1
  62. package/dist/assets/{terminal-Ca-kubKb.js → terminal-B-foRg1j.js} +1 -1
  63. package/dist/assets/{tracing-B0J2ctTm.js → tracing-DglCQA_A.js} +1 -1
  64. package/dist/assets/{tracing-panel-C1OCpoeE.js → tracing-panel-Dig-XuOl.js} +2 -2
  65. package/dist/assets/{tree-actions-sjBxIglc.js → tree-actions-BASXwJd1.js} +1 -1
  66. package/dist/assets/{useAddCell-CaXnFGki.js → useAddCell-bvRpB5dY.js} +1 -1
  67. package/dist/assets/{useBoolean-Dd2nWXFJ.js → useBoolean-rA1CzmYl.js} +1 -1
  68. package/dist/assets/{useCellActionButton-CJ90CMEj.js → useCellActionButton-Cv2-KLlH.js} +1 -1
  69. package/dist/assets/{useDeleteCell-D9N85822.js → useDeleteCell-B2rRUNeJ.js} +1 -1
  70. package/dist/assets/{useDependencyPanelTab-CzAE0cm-.js → useDependencyPanelTab-B8jk4N46.js} +1 -1
  71. package/dist/assets/{useInstallPackage-wcDq9hYT.js → useInstallPackage-DWxYtxn-.js} +1 -1
  72. package/dist/assets/{useNotebookActions-CAMEQ38y.js → useNotebookActions-HhHejFpc.js} +1 -1
  73. package/dist/assets/{useRunCells-DGakx8hj.js → useRunCells-Bz-vP8K6.js} +1 -1
  74. package/dist/assets/{useSplitCell-AK5BKPGM.js → useSplitCell-4bnvSMAx.js} +1 -1
  75. package/dist/assets/{vega-component-BeyxAJad.js → vega-component-D3px3WTM.js} +1 -1
  76. package/dist/index.html +24 -24
  77. package/package.json +1 -1
  78. package/src/core/host/__tests__/notebook-client.test.ts +18 -6
  79. package/src/core/host/__tests__/static.test.ts +4 -2
  80. package/src/core/host/__tests__/wasm.test.ts +12 -10
  81. package/src/core/host/backend.ts +8 -3
  82. package/src/core/host/notebook-client.ts +15 -15
  83. package/src/core/host/static.ts +2 -2
  84. package/src/core/host/wasm.ts +4 -3
  85. package/src/core/runtime/__tests__/runtime.test.ts +17 -0
  86. package/src/core/runtime/runtime.ts +13 -0
  87. package/src/core/websocket/__tests__/backend.test.ts +111 -0
  88. package/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx +32 -27
  89. package/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx +7 -4
  90. package/src/core/websocket/backend.ts +68 -0
  91. package/src/core/websocket/transports/__tests__/notebook.test.ts +9 -56
  92. package/src/core/websocket/transports/notebook.ts +15 -38
  93. package/src/core/websocket/useNotebookClient.ts +6 -6
  94. package/src/core/websocket/useNotebookSession.tsx +3 -2
  95. package/dist/assets/feedback-button-tbWwJ_t6.js +0 -1
  96. package/dist/assets/panels-DJghvIKo.js +0 -1
@@ -1,4 +1,4 @@
1
- import{r as e}from"./useEvent-BDjgaBtz.js";import{$n as t,La as n,Pa as r,Qn as i,_o as a,oi as o,vo as s,x as c,za as l}from"./cells-2HETnlvE.js";import{C as u,E as d,F as f,I as p,K as m,M as h,N as g,O as _,R as v,S as y,b,c as ee,v as x,z as S}from"./schemas-ChRqMOTL.js";import{t as te}from"./get-DjNf4SIX.js";import{t as ne}from"./debounce-aFmHgJZY.js";import{E as re}from"./config-DpY86_Yq.js";import{t as ie}from"./_baseSet-Bpdo9AvU.js";import{g as C,v as w}from"./useEventListener-CjDeLqFC.js";import{t as ae}from"./invariant-Ci2dTZ72.js";import{s as oe}from"./config-DMz7oN0r.js";import{d as se,v as ce}from"./session-CMLIzZKw.js";import{D as le,M as ue,c as T,l as de,n as fe}from"./config-CD1IuZFJ.js";import{c as pe,o as E}from"./state-C5WAeuTu.js";import{c as me,o as he}from"./markdown-renderer-BhiTvxtL.js";import{w as ge}from"./write-secret-modal-BEx-EUlh.js";import{t as _e}from"./use-toast-Wu434mLr.js";import{t as ve}from"./preload-helper-uBIymjUX.js";import{r as ye}from"./strings-C25fhMR_.js";import{t as D}from"./requests-BIFR-h4M.js";import{t as be}from"./Deferred-CrTnjj37.js";import{t as xe}from"./uuid-k9DpjH68.js";import{n as Se}from"./RenderHTML-D6AC0IhC.js";import{t as Ce}from"./useRunCells-DGakx8hj.js";import{r as we,t as Te}from"./blob-DTYOX-m5.js";import{f as Ee}from"./useInstallPackage-wcDq9hYT.js";import{n as De,t as Oe}from"./share-BZW3tzEX.js";import{i as ke,r as Ae,t as je}from"./events-CbeVJ6OD.js";function O(e){return m(ee,e)}function k(e,t,n){return e==null?e:ie(e,t,n)}function Me(e,t){if(e.origin===globalThis.origin)return new Worker(e.href,{...t,type:`module`});let n=`import ${JSON.stringify(e.href)}`,r=globalThis.origin===`null`?`data:application/javascript,${encodeURIComponent(n)}`:URL.createObjectURL(new Blob([n],{type:`application/javascript`}));try{return new Worker(r,{...t,type:`module`})}finally{r.startsWith(`blob:`)&&URL.revokeObjectURL(r)}}var A=p().min(1).describe(`Identifies a project. Unique within the host and unchanged while the project exists.`),j=p().min(1).describe(`Identifies a notebook. Unique within the host and unchanged while the notebook exists.`),Ne=p().min(1).describe(`Identifies a runtime. Unique within the host; every start and restart creates a new id.`),Pe=p().min(1).describe(`Identifies an attachment. Unique within the host.`),Fe=p().min(1).describe("Identifies a run independently of the request's `Idempotency-Key`. Events carry the key in `request_id`."),M=p().min(1).describe(`Identifies an execution. Unique within the host.`),N=p().min(1).describe(`Identifies a console, display, or variable item. Unique within the host; sending an item again with the same id replaces it.`),P=p().min(1).describe("Identifies a cell within its notebook. Stable while the host serves the notebook; whether it survives a reload of the store depends on the format. `setup` is the setup cell."),Ie=g({pid:d().min(1).describe(`The process id.`),started_at:O({offset:!0}).describe(`When the process started.`)}).describe("The process that wrote a record. A client checks that a process\nwith this `pid` that started at `started_at` still exists. If it\ndoes not, the record is stale and may be removed.\n");g({version:_(1).describe(`The version of this record's format. This document describes version 1.`),process:Ie,name:p().describe("A label for the host to show people, such as `VS Code` or `marimo`. Two hosts can share a name; the filename is the identity."),url:p().describe("Where the host's API is. The scheme is `http`, and the host part is `127.0.0.1` or `[::1]`, written exactly that way."),token:p().min(1).describe(`The secret a client sends to prove it read the record.`)}).describe(`A host record is the file a host writes so that clients can find
1
+ import{r as e}from"./useEvent-BDjgaBtz.js";import{$n as t,La as n,Pa as r,Qn as i,_o as a,oi as o,vo as s,x as c,za as l}from"./cells-B3LEgMh1.js";import{C as u,E as d,F as f,I as p,K as m,M as h,N as g,O as _,R as v,S as y,b,c as ee,v as x,z as S}from"./schemas-ChRqMOTL.js";import{t as te}from"./get-DjNf4SIX.js";import{t as ne}from"./debounce-aFmHgJZY.js";import{E as re}from"./config-DpY86_Yq.js";import{t as ie}from"./_baseSet-Bpdo9AvU.js";import{g as C,v as w}from"./useEventListener-CjDeLqFC.js";import{t as ae}from"./invariant-Ci2dTZ72.js";import{s as oe}from"./config-CqfGrErg.js";import{d as se,v as ce}from"./session-CMLIzZKw.js";import{D as le,M as ue,c as T,l as de,n as fe}from"./config-BTFDx3Zj.js";import{c as pe,o as E}from"./state-C5WAeuTu.js";import{c as me,o as he}from"./markdown-renderer-BbXJkH92.js";import{w as ge}from"./write-secret-modal-BEx-EUlh.js";import{t as _e}from"./use-toast-Wu434mLr.js";import{t as ve}from"./preload-helper-uBIymjUX.js";import{r as ye}from"./strings-C25fhMR_.js";import{t as D}from"./requests-BIFR-h4M.js";import{t as be}from"./Deferred-CrTnjj37.js";import{t as xe}from"./uuid-k9DpjH68.js";import{n as Se}from"./RenderHTML-BWp2DyZX.js";import{t as Ce}from"./useRunCells-Bz-vP8K6.js";import{r as we,t as Te}from"./blob-CJNyvsia.js";import{f as Ee}from"./useInstallPackage-DWxYtxn-.js";import{n as De,t as Oe}from"./share-BZW3tzEX.js";import{i as ke,r as Ae,t as je}from"./events-CbeVJ6OD.js";function O(e){return m(ee,e)}function k(e,t,n){return e==null?e:ie(e,t,n)}function Me(e,t){if(e.origin===globalThis.origin)return new Worker(e.href,{...t,type:`module`});let n=`import ${JSON.stringify(e.href)}`,r=globalThis.origin===`null`?`data:application/javascript,${encodeURIComponent(n)}`:URL.createObjectURL(new Blob([n],{type:`application/javascript`}));try{return new Worker(r,{...t,type:`module`})}finally{r.startsWith(`blob:`)&&URL.revokeObjectURL(r)}}var A=p().min(1).describe(`Identifies a project. Unique within the host and unchanged while the project exists.`),j=p().min(1).describe(`Identifies a notebook. Unique within the host and unchanged while the notebook exists.`),Ne=p().min(1).describe(`Identifies a runtime. Unique within the host; every start and restart creates a new id.`),Pe=p().min(1).describe(`Identifies an attachment. Unique within the host.`),Fe=p().min(1).describe("Identifies a run independently of the request's `Idempotency-Key`. Events carry the key in `request_id`."),M=p().min(1).describe(`Identifies an execution. Unique within the host.`),N=p().min(1).describe(`Identifies a console, display, or variable item. Unique within the host; sending an item again with the same id replaces it.`),P=p().min(1).describe("Identifies a cell within its notebook. Stable while the host serves the notebook; whether it survives a reload of the store depends on the format. `setup` is the setup cell."),Ie=g({pid:d().min(1).describe(`The process id.`),started_at:O({offset:!0}).describe(`When the process started.`)}).describe("The process that wrote a record. A client checks that a process\nwith this `pid` that started at `started_at` still exists. If it\ndoes not, the record is stale and may be removed.\n");g({version:_(1).describe(`The version of this record's format. This document describes version 1.`),process:Ie,name:p().describe("A label for the host to show people, such as `VS Code` or `marimo`. Two hosts can share a name; the filename is the identity."),url:p().describe("Where the host's API is. The scheme is `http`, and the host part is `127.0.0.1` or `[::1]`, written exactly that way."),token:p().min(1).describe(`The secret a client sends to prove it read the record.`)}).describe(`A host record is the file a host writes so that clients can find
2
2
  it. A host writes \`<marimo-state-dir>/hosts-v1/<id>.json\` once its API
3
3
  is serving at \`url\`, where \`<id>\` is an identifier the host makes
4
4
  up each time it starts. The record does not change while the host
@@ -102,6 +102,6 @@ The data is decoded JSON. Snapshot records and reset events omit
102
102
  the cursor; ready and live events carry it. Unknown event names
103
103
  belong to later versions or host extensions.
104
104
  `),$t=g({id:p().describe(`Identifies this answer.`),label:p().describe(`Text to show a person.`)}).describe(`One possible answer to a decision.`),en=g({id:p().describe(`Identifies the question when the client answers it.`),prompt:p().describe(`The question, worded for a person.`),options:y($t).describe(`The possible answers.`)}).describe("A question the host needs answered before it can carry out a\nrequest. The client answers by repeating the request with\n`decisions` in the body, mapping this `id` to the `id` of an\noption.\n"),tn=g({change:d().min(0).describe("The index of the stale change in the request's `changes`, or of the stale cell in a run's `cells`. `0` for a save with a stale `If-Match`."),cell:v([lt,b()]).describe(`The cell the change named, as it now is. Null when the document does not have it, or when the change named the order.`),document:z}).describe(`The first stale change of an edit or run, and the state the host holds.`),nn=g({type:p().describe("What kind of problem this is, as a URI. The kinds this\nprotocol defines all start with `tag:marimo.io,2026:host/` and\nend with one of `invalid-request` (400), `unauthorized` (401),\n`forbidden` (403), `not-found` (404), `method-not-allowed`\n(405), `not-acceptable` (406), `conflict` (409), `no-runtime`\n(409), `decision-required` (409), `internal` (500), or\n`unsupported-operation` (501). A client that sees a kind it\ndoes not recognize falls back to `status`.\n"),title:p().describe(`A short, human-readable name for the kind of problem.`),status:d().min(400).max(599).describe(`The HTTP status code of the response.`),detail:p().optional().describe(`A human-readable explanation of what went wrong this time.`),decisions:y(en).optional().describe("The choices the client has to make before the host can carry out the request. Only present for `decision-required`."),edit:tn.optional().describe("Which change was stale and what the host holds instead. Only present for a `conflict` answering an edit, a save, or a run of cells.")}).describe("An error. Every error response has this one shape, following RFC\n9457, and is served as `application/problem+json`. `status`\nrepeats the HTTP status, and `type` says more precisely what went\nwrong. `decisions` appears only when `type` is\n`tag:marimo.io,2026:host/decision-required`. A client ignores\nmembers it does not recognize. An error never contains a token.\n"),rn=g({project_id:A,path:p().optional().describe(`Where to put the file, relative to the project root and written the way the host's operating system writes paths.`),name:p().optional().describe(`A label to show people. In a project with a root it defaults to the filename.`)}).describe("The notebook's own fields, minus what the host assigns. A project with a root requires `path`; one without requires `name`."),an=g({path:p().optional().describe(`The new location, relative to the project root and written the way the host's operating system writes paths.`),name:p().optional().describe(`The new label to show people.`)}).describe(`The fields to change. At least one is present.`),on=g({url:p().describe(`The URL the host used to show the notebook. It never contains the host's token.`)}),sn=g({decisions:f(p(),p()).optional().describe("Answers to the questions in a `decision-required` problem.\nEach key is a decision's `id` and each value is the `id` of\nthe chosen option. A client that already knows its choices can\nsend them the first time.\n")}),cn=g({column:d().nullish().default(null),disabled:u().default(!1),hide_code:u().default(!1),expand_output:u().default(!1)}).describe(`A cell's settings as a client writes them. A field left out takes its default.`),ln=g({id:P.describe(`The cell's id. A client chooses the id of a cell it creates.`),code:p().describe(`The cell's source code.`),name:p().default(`_`).describe("The cell's name. `_` for an anonymous cell."),config:cn.optional()}).describe(`A cell as a client writes it. Code must be a string, even when the host withholds source in cell records. Null is not an edit or a request to preserve existing source. The host derives the etags.`),un=g({kind:x([`put_cell`]),base_etag:p().nullable().describe("The cell's etag as last read, `*` to skip the check, or null to create the cell. Null when the cell exists, or an etag when it does not, is a `conflict`."),cell:ln,after:P.optional().describe(`The cell a created cell goes after. Ignored for an existing cell.`),before:P.optional().describe("The cell a created cell goes before. Ignored for an existing cell. With neither `after` nor `before`, a created cell goes at the end.")}).describe(`Replaces a whole cell, or creates one.`),dn=g({kind:x([`delete_cell`]),id:P.describe(`The cell to remove.`),base_etag:p().describe("The cell's etag as last read, or `*`.")}).describe(`Removes a cell.`),fn=g({kind:x([`set_order`]),base_etag:p().describe("The document's `order_etag` as last read, or `*`."),order:y(P).describe(`Every cell id exactly once, in the new order, counting cells this edit creates and leaving out cells it deletes.`)}).describe(`Replaces the cell order.`),pn=v([un,dn,fn]).describe("One change to the document, tagged on `kind`."),mn=g({changes:y(pn).describe(`The changes, applied in order as one unit.`)}),hn=g({etag:R,code_hash:R,version:d().min(1).describe(`The cell's version after the edit.`)}).describe(`A cell's etags and version after an edit.`),gn=g({document:z,cells:f(p(),v([hn,b()])).describe(`The version of each cell the request created or changed, by id, and null for each cell it deleted.`)}).describe(`The document as an edit or save left it, or at a later revision, and the cells it touched.`),_n=g({decisions:f(p(),p()).optional().describe("Answers to the questions in a `decision-required` problem, as for `runtime.start`.")}).describe("What a save needs from the client, which is nothing until the host asks a question. `{}` is the usual body."),vn=g({id:P,code_hash:R.optional().describe("The cell's `code_hash` as last read. A cell whose code differs is a `conflict`. Absent, the cell runs as it is.")}),yn=g({code:p().optional().describe(`Python code to run as scratch code.`),cells:y(vn).min(1).optional().describe(`Cells of the document to run, in no particular order. The runtime's execution configuration determines whether dependent cells run too.`)}).describe("What to run, exactly one of `code` and `cells`."),bn=Le.options.filter(e=>e!==`host`&&e!==`project`),V=class extends Error{name=`StreamStopped`},xn={events:{method:`GET`,path:`/events`,query:{types:!1},headers:{"Last-Event-ID":!1},body:null,responses:{200:`text/event-stream`},problems:[400,401,403,404,405,500]},"notebook.create":{method:`POST`,path:`/notebooks`,query:{},headers:{"Idempotency-Key":!0},body:rn,responses:{201:F},problems:[400,401,403,404,405,409,500,501]},"notebook.update":{method:`PATCH`,path:`/notebooks/{notebook_id}`,query:{},headers:{"Idempotency-Key":!0},body:an,responses:{200:F},problems:[400,401,403,404,405,409,500,501]},"notebook.delete":{method:`DELETE`,path:`/notebooks/{notebook_id}`,query:{},headers:{"Idempotency-Key":!0},body:null,responses:{204:null},problems:[400,401,403,404,405,409,500,501]},"notebook.events":{method:`GET`,path:`/notebooks/{notebook_id}/events`,query:{types:!1,run_id:!1},headers:{"Last-Event-ID":!1,"Marimo-Attachment-Identity":!1,"Marimo-Attachment-Kind":!1,"Marimo-Attachment-Name":!1},body:null,responses:{200:`text/event-stream`},problems:[400,401,403,404,405,500]},"notebook.edit":{method:`POST`,path:`/notebooks/{notebook_id}/edits`,query:{},headers:{"Idempotency-Key":!0},body:mn,responses:{200:gn},problems:[400,401,403,404,405,409,500,501]},"notebook.save":{method:`POST`,path:`/notebooks/{notebook_id}/save`,query:{},headers:{"Idempotency-Key":!0,"If-Match":!1},body:_n,responses:{200:gn},problems:[400,401,403,404,405,409,500,501]},"notebook.open":{method:`POST`,path:`/notebooks/{notebook_id}/open`,query:{},headers:{"Idempotency-Key":!0},body:null,responses:{200:on},problems:[400,401,403,404,405,409,500,501]},"runtime.start":{method:`PUT`,path:`/notebooks/{notebook_id}/runtime`,query:{},headers:{"Idempotency-Key":!0},body:sn,responses:{200:I,202:I},problems:[400,401,403,404,405,409,500,501]},"runtime.stop":{method:`DELETE`,path:`/notebooks/{notebook_id}/runtime`,query:{},headers:{"Idempotency-Key":!0},body:null,responses:{202:I},problems:[400,401,403,404,405,409,500,501]},"runtime.restart":{method:`POST`,path:`/notebooks/{notebook_id}/runtime/restart`,query:{},headers:{"Idempotency-Key":!0},body:null,responses:{202:I},problems:[400,401,403,404,405,409,500,501]},"runtime.run":{method:`POST`,path:`/notebooks/{notebook_id}/runtime/runs`,query:{},headers:{"Idempotency-Key":!0},body:yn,responses:{202:L},problems:[400,401,403,404,405,409,500,501]},"runtime.interrupt":{method:`DELETE`,path:`/notebooks/{notebook_id}/runtime/runs/{run_id}`,query:{},headers:{"Idempotency-Key":!0},body:null,responses:{202:L},problems:[400,401,403,404,405,409,500,501]}};function Sn(){if(typeof globalThis.crypto.randomUUID==`function`)return globalThis.crypto.randomUUID();let e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(e=>e.toString(16).padStart(2,`0`));return[t.slice(0,4),t.slice(4,6),t.slice(6,8),t.slice(8,10),t.slice(10)].map(e=>e.join(``)).join(`-`)}function Cn(e,t){return e?.split(`;`,1)[0].trim().toLowerCase()===t}function wn(e,t){let n=new URL(e);return n.pathname=e.pathname.replace(/\/$/,``)+t,n}function Tn(e,t,n){let r=t.slice(e.prefix.length).replace(/\{(\w+)\}/g,(e,r)=>{let i=n[r];if(i===void 0||i===``||i===`.`||i===`..`)throw Error(`${t} needs a valid ${r}`);return encodeURIComponent(i)});return wn(e.url,r)}var En=g({status:h().int(),body:S()});async function Dn(e,t,{params:n={},body:r,headers:i={},options:a={}}){let o=xn[t],s={};`Idempotency-Key`in o.headers&&(s[`Idempotency-Key`]=a.idempotencyKey??Sn());for(let[e,t]of Object.entries(i))t!==void 0&&(s[e]=t);let c=o.body===null?void 0:o.body.parse(r),l=`send`in e?await kn(e,{operation:t,params:{...e.params,...n},headers:Object.fromEntries(Object.entries(s).map(([e,t])=>[e.toLowerCase(),t])),body:c},a.signal):await On(e,o,n,s,c,a.signal),u=l.status,d=o.responses[u];if(d===null)return{ok:!0,status:u,data:void 0};if(d!==void 0&&d!==`text/event-stream`)return{ok:!0,status:u,data:d.parse(await l.json())};if((u<200||u>=300)&&l.problem)return{ok:!1,status:u,problem:nn.parse(await l.json())};throw Error(`Unexpected ${u} response to ${t}`)}async function On(e,t,n,r,i,a){let o=new Headers(r);o.set(`Accept`,`application/json, application/problem+json`),e.client.token!==void 0&&o.set(`Authorization`,`Bearer ${e.client.token}`),i!==void 0&&o.set(`Content-Type`,`application/json`);let s=await(e.client.fetch??globalThis.fetch)(Tn(e,t.path,n),{method:t.method,headers:o,body:i===void 0?void 0:JSON.stringify(i),signal:a});return{status:s.status,problem:Cn(s.headers.get(`Content-Type`),`application/problem+json`),json:()=>s.json()}}async function kn(e,t,n){n?.throwIfAborted();let r=e.send(t),i=En.parse(n===void 0?await r:await new Promise((e,t)=>{let i=()=>t(n.reason);n.addEventListener(`abort`,i,{once:!0}),r.then(e,t).finally(()=>n.removeEventListener(`abort`,i))}));return{status:i.status,problem:!0,json:async()=>i.body}}var An=45e3,jn=class extends TransformStream{constructor(e=JSON.parse){let t=``,n=``,r=[],i,a=t=>{if(r.length>0){let a=r.join(`
105
- `),o=a;try{o=e(a)}catch{}t.enqueue({event:n||`message`,data:o,...i===void 0?{}:{id:i}})}n=``,r=[],i=void 0};super({transform(e,o){t+=e;let s=t.endsWith(`\r`)?`\r`:``,c=t.slice(0,t.length-s.length).split(/\r\n|\r|\n/);t=(c.pop()??``)+s;for(let e of c){if(e===``){a(o);continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`),s=t===-1?e:e.slice(0,t),c=t===-1?``:e.slice(t+1);c.startsWith(` `)&&(c=c.slice(1)),s===`event`?n=c:s===`data`?r.push(c):s===`id`&&!c.includes(`\0`)&&(i=c)}}})}},Mn=new Set([408,429]);function Nn(e,t={}){return async({cursor:n,signal:r},{open:i,message:a})=>{let o=new Headers;o.set(`Accept`,`text/event-stream`),t.token!==void 0&&o.set(`Authorization`,`Bearer ${t.token}`),n!==null&&o.set(`Last-Event-ID`,n);let s=new AbortController,c=()=>s.abort();r.addEventListener(`abort`,c,{once:!0});let l,u,d=()=>{clearTimeout(l),l=setTimeout(c,An)};try{let n=new URL(typeof e==`function`?await e():e),r=t.fetch??globalThis.fetch;d();let c=await r(n,{headers:o,signal:s.signal}),{status:l}=c;if(l>=400&&l<500&&!Mn.has(l)){let e=nn.safeParse(await c.json().catch(()=>void 0));throw new V(`The host refused the stream (${l})`,{cause:e.success?e.data:void 0})}if(!c.ok||c.body===null){await c.body?.cancel();return}if(!Cn(c.headers.get(`Content-Type`),`text/event-stream`))throw await c.body.cancel(),new V(`The host did not answer with an event stream`);i();let f=new TransformStream({transform(e,t){d(),t.enqueue(e)}}),p=c.body.pipeThrough(f).pipeThrough(new TextDecoderStream).pipeThrough(new jn(t.parseData)).getReader();for(s.signal.addEventListener(`abort`,()=>void p.cancel(),{once:!0});;){let{done:e,value:n}=await p.read();if(e)return;if(u=t.stop?.(n),u!==void 0)throw u;a(n)}}catch(e){if(e instanceof V||e===u)throw e}finally{clearTimeout(l),r.removeEventListener(`abort`,c)}}}var Pn=new Set(Qt.options.flatMap(e=>e.shape.event.options)),Fn=g({event:p().min(1),data:S(),id:p().optional()});function H(e){queueMicrotask(()=>{throw e})}var In=class{#e;#t=!1;#n;#r=new Set;constructor(e,t){this.#e=e.cursor??null,this.#n=new Set([`ready`,`reset`,...(e.types??t).flatMap(e=>{let t=`${e}.removed`;return Pn.has(t)?[e,t]:[e]})])}get cursor(){return this.#e}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}resume(){return this.#e===null&&this.#t&&this.#i({event:`reset`,data:{}}),this.#e}receive(e){let t=Fn.safeParse(e);if(!t.success)throw new V(`The host sent a message that is not an event`,{cause:t.error});this.#i(t.data)}#i(e){let t;if(Pn.has(e.event)){let n=Qt.safeParse(e);if(!n.success)throw new V(`The host sent an invalid ${e.event} event`,{cause:n.error});t=n.data}else t=e;if(e.id!==void 0&&(this.#e=e.id),t.event===`reset`?(this.#e=null,this.#t=!1):this.#e===null&&(this.#t=!0),this.#n.has(t.event))for(let e of this.#r)try{e(t)}catch(e){H(e)}}},Ln=10,Rn=5e3;function zn(e){return Math.min(1e3*1.5**(e-1),15e3)*(.75+Math.random()/2)}function Bn(e,t){return new Promise(n=>{let r=setTimeout(i,e);t.addEventListener(`abort`,i,{once:!0});function i(){clearTimeout(r),t.removeEventListener(`abort`,i),n()}})}var Vn=class{closed;#e;#t=`connecting`;#n=new AbortController;#r;#i;#a;#o=new Set;constructor(e,t,n){let r;if(typeof e==`function`)r=e;else{let n=new URL(e);t.types!==void 0&&n.searchParams.set(`types`,t.types.join(`,`)),r=Nn(n,t)}if(this.#e=new In({types:t.types,cursor:t.cursor},n),this.#r=t.onStatus,this.closed=new Promise((e,t)=>{this.#i={resolve:e,reject:t}}),this.closed.catch(()=>void 0),t.signal?.aborted){this.close();return}let i=t.signal;if(i!==void 0){let e=()=>this.close();i.addEventListener(`abort`,e,{once:!0}),this.#a=()=>i.removeEventListener(`abort`,e)}this.#s(r)}get status(){return this.#t}get cursor(){return this.#e.cursor}subscribe(e,t){let n=!0,r=this.#e.subscribe(t=>{n&&e(t)}),i=e=>{n&&t?.(e)};return t!==void 0&&this.#i!==void 0&&this.#o.add(i),()=>{n=!1,this.#o.delete(i),r()}}close(){this.#l()?.resolve()}[Symbol.asyncIterator](){let e=[],t=[],n=()=>t.splice(0).forEach(e=>e()),r,i=this.subscribe(t=>{e.push(t),n()});this.closed.then(()=>{r={},n()},e=>{r={error:e},n()});let a=()=>(i(),this.close(),{done:!0,value:void 0});return{next:async()=>{for(;;){let n=e.shift();if(n!==void 0)return{done:!1,value:n};if(r!==void 0){if(r.error!==void 0)throw i(),r.error;return a()}await new Promise(e=>t.push(e))}},return:async()=>a()}}async#s(e){await Promise.resolve();let{signal:t}=this.#n,n=0;for(;!t.aborted;){let r=!0,i=!1,a;try{await e({cursor:this.#e.resume(),signal:t},{open:()=>{r&&this.#i!==void 0&&this.#c(`connected`)},message:e=>{if(!(!r||this.#i===void 0)){a??=setTimeout(()=>{i=!0},Rn);try{this.#e.receive(e)}catch(e){this.#l()?.reject(e)}}}})}catch(e){this.#l()?.reject(e);return}finally{r=!1,clearTimeout(a)}if(t.aborted)return;if(this.#c(`connecting`),n=i?1:n+1,n>Ln){this.#l()?.reject(new V(`The host could not be reached`));return}await Bn(zn(n),t)}}#c(e){if(this.#t!==e){this.#t=e;try{this.#r?.(e)}catch(e){H(e)}}}#l(){let e=this.#i;if(e===void 0)return;this.#i=void 0;let t=[...this.#o];return this.#o.clear(),this.#a?.(),this.#n.abort(),this.#c(`closed`),{resolve:e.resolve,reject:n=>{e.reject(n);for(let e of t)try{e(n)}catch(e){H(e)}}}}},Hn=class extends Vn{constructor(e,t={}){typeof e!=`function`&&t.runId!==void 0&&(e=new URL(e),e.searchParams.set(`run_id`,t.runId)),super(e,t,bn)}},Un=class{#e;constructor(e){this.#e=e}update(e,t){return this.#t(`notebook.update`,{body:e,options:t})}delete(e){return this.#t(`notebook.delete`,{options:e})}open(e){return this.#t(`notebook.open`,{options:e})}edit(e,t){return this.#t(`notebook.edit`,{body:{changes:[...e]},options:t})}save(e){return this.#t(`notebook.save`,{body:{decisions:e?.decisions},headers:{"If-Match":e?.ifMatch},options:e})}start(e){return this.#t(`runtime.start`,{body:{decisions:e?.decisions},options:e})}stop(e){return this.#t(`runtime.stop`,{options:e})}restart(e){return this.#t(`runtime.restart`,{options:e})}run(e,t){return this.#t(`runtime.run`,{body:e,options:t})}interrupt(e,t){return this.#t(`runtime.interrupt`,{params:{run_id:e},options:t})}#t(e,t){return Dn(this.#e,e,t)}},Wn=class extends Un{#e;#t;constructor(e,t={}){let n=new URL(e);super({url:n,prefix:`/notebooks/{notebook_id}`,client:t}),this.#e=n,this.#t=t}static unstable_over(e,{notebookId:t}){return new Un({send:t=>e(t),prefix:`/notebooks/{notebook_id}`,params:{notebook_id:t}})}get url(){return new URL(this.#e)}events(e={}){return new Hn(wn(this.#e,`/events`),{...this.#t,...e})}};function Gn(e,t){return t?(t.throwIfAborted(),new Promise((n,r)=>{let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e().then(n,r).finally(()=>t.removeEventListener(`abort`,i))})):e()}function Kn(e){return{transport:async({cursor:t,signal:n},{open:r,message:i})=>{if(n.aborted)return;let a,o,s=new Promise(e=>{o=e}),c=()=>{a?.(),o()};n.addEventListener(`abort`,c,{once:!0});try{r(),await Gn(()=>e.subscribe(t,e=>{n.aborted||i(e)}).then(e=>{a=e,n.aborted&&e()}),n),await s}catch(e){if(!n.aborted)throw a?.(),new V(`Could not follow the WASM notebook`,{cause:e})}finally{n.removeEventListener(`abort`,c)}},client:Wn.unstable_over(t=>e.call(t),{notebookId:e.notebookId})}}function qn(e){return e.assetUrl,e}var Jn=1e10,Yn=1e3;function U(e,t){let n=e.map(e=>`"${e}"`).join(`, `);return Error(`This RPC instance cannot ${t} because the transport did not provide one or more of these methods: ${n}`)}function Xn(e={}){let t={};function n(e){t=e}let r={};function i(e){r.unregisterHandler&&r.unregisterHandler(),r=e,r.registerHandler?.(x)}let a;function o(e){if(typeof e==`function`){a=e;return}a=(t,n)=>{let r=e[t];if(r)return r(n);let i=e._;if(!i)throw Error(`The requested method has no handler: ${t}`);return i(t,n)}}let{maxRequestTime:s=Yn}=e;e.transport&&i(e.transport),e.requestHandler&&o(e.requestHandler),e._debugHooks&&n(e._debugHooks);let c=0;function l(){return c<=Jn?++c:c=0}let u=new Map,d=new Map;function f(e,...n){let i=n[0];return new Promise((n,a)=>{if(!r.send)throw U([`send`],`make requests`);let o=l(),c={type:`request`,id:o,method:e,params:i};u.set(o,{resolve:n,reject:a}),s!==1/0&&d.set(o,setTimeout(()=>{d.delete(o),a(Error(`RPC request timed out.`))},s)),t.onSend?.(c),r.send(c)})}let p=new Proxy(f,{get:(e,t,n)=>t in e?Reflect.get(e,t,n):e=>f(t,e)}),m=p;function h(e,...n){let i=n[0];if(!r.send)throw U([`send`],`send messages`);let a={type:`message`,id:e,payload:i};t.onSend?.(a),r.send(a)}let g=new Proxy(h,{get:(e,t,n)=>t in e?Reflect.get(e,t,n):e=>h(t,e)}),_=g,v=new Map,y=new Set;function b(e,t){if(!r.registerHandler)throw U([`registerHandler`],`register message listeners`);if(e===`*`){y.add(t);return}v.has(e)||v.set(e,new Set),v.get(e)?.add(t)}function ee(e,t){if(e===`*`){y.delete(t);return}v.get(e)?.delete(t),v.get(e)?.size===0&&v.delete(e)}async function x(e){if(t.onReceive?.(e),!(`type`in e))throw Error(`Message does not contain a type.`);if(e.type===`request`){if(!r.send||!a)throw U([`send`,`requestHandler`],`handle requests`);let{id:n,method:i,params:o}=e,s;try{s={type:`response`,id:n,success:!0,payload:await a(i,o)}}catch(e){if(!(e instanceof Error))throw e;s={type:`response`,id:n,success:!1,error:e.message}}t.onSend?.(s),r.send(s);return}if(e.type===`response`){let t=d.get(e.id);t!=null&&clearTimeout(t);let{resolve:n,reject:r}=u.get(e.id)??{};e.success?n?.(e.payload):r?.(Error(e.error));return}if(e.type===`message`){for(let t of y)t(e.id,e.payload);let t=v.get(e.id);if(!t)return;for(let n of t)n(e.payload);return}throw Error(`Unexpected RPC message type: ${e.type}`)}return{setTransport:i,setRequestHandler:o,request:p,requestProxy:m,send:g,sendProxy:_,addMessageListener:b,removeMessageListener:ee,proxy:{send:_,request:m},_setDebugHooks:n}}function Zn(e){return Xn(e)}var Qn=`[transport-id]`;function $n(e,t){let{transportId:n}=t;return n==null?e:{[Qn]:n,data:e}}function er(e,t){let{transportId:n,filter:r}=t,i=r?.();if(n!=null&&i!=null)throw Error("Cannot use both `transportId` and `filter` at the same time");let a=e;if(n){if(e[Qn]!==n)return[!0];a=e.data}return i===!1?[!0]:[!1,a]}function tr(e,t={}){let{transportId:n,filter:r,remotePort:i}=t,a=e,o=i??e,s;return{send(e){o.postMessage($n(e,{transportId:n}))},registerHandler(e){s=t=>{let i=t.data,[a,o]=er(i,{transportId:n,filter:()=>r?.(t)});a||e(o)},a.addEventListener(`message`,s)},unregisterHandler(){s&&a.removeEventListener(`message`,s)}}}function nr(e,t){return tr(e,t)}var rr=`::controller`,ir=`marimo-transport`;function ar(e){return Zn({transport:nr(e,{transportId:ir}),maxRequestTime:2e4,_debugHooks:{onSend:e=>{C.debug(`[rpc] Parent -> Worker`,e)},onReceive:e=>{C.debug(`[rpc] Worker -> Parent`,e)}}})}function or(){let e=document.querySelector(`marimo-wasm`),t=e=>{try{return e?new URL(e,document.baseURI).href:void 0}catch{return}};return{version:pe(),pyodideIndexUrl:t(e?.dataset.pyodideIndexUrl),pyodideLockfileUrl:t(e?.dataset.pyodideLockfileUrl),pypiIndexUrl:t(e?.dataset.pypiIndexUrl)?.replaceAll(`%7Bpackage_name%7D`,`{package_name}`)}}var sr=De(),cr=`marimo:file`,lr=new r(null),ur={saveFile(e){lr.set(cr,e)},readFile(){return lr.get(cr)}},dr={saveFile(e){s.setCodeForHash((0,sr.compressToEncodedURIComponent)(e))},readFile(){let e=s.getCodeFromHash()||s.getCodeFromSearchParam();return e?(0,sr.decompressFromEncodedURIComponent)(e):null}},fr={saveFile(e){},readFile(){let e=document.querySelector(`marimo-code`);return e?decodeURIComponent(e.textContent||``).trim():null}},pr={saveFile(e){},readFile(){if(window.location.hostname!==`marimo.app`)return null;let e=new URL(`export_demos/wasm-intro.py`,document.baseURI);return fetch(e.toString()).then(e=>e.ok?e.text():null).catch(()=>null)}},mr={saveFile(e){},readFile(){return e.get(n)??null}},hr={saveFile(e){},readFile(){return[`import marimo`,`app = marimo.App()`,``,`@app.cell`,`def __():`,` return`,``,`if __name__ == "__main__":`,` app.run()`].join(`
105
+ `),o=a;try{o=e(a)}catch{}t.enqueue({event:n||`message`,data:o,...i===void 0?{}:{id:i}})}n=``,r=[],i=void 0};super({transform(e,o){t+=e;let s=t.endsWith(`\r`)?`\r`:``,c=t.slice(0,t.length-s.length).split(/\r\n|\r|\n/);t=(c.pop()??``)+s;for(let e of c){if(e===``){a(o);continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`),s=t===-1?e:e.slice(0,t),c=t===-1?``:e.slice(t+1);c.startsWith(` `)&&(c=c.slice(1)),s===`event`?n=c:s===`data`?r.push(c):s===`id`&&!c.includes(`\0`)&&(i=c)}}})}},Mn=new Set([408,429]);function Nn(e,t={}){return async({cursor:n,signal:r},{open:i,message:a})=>{let o=new Headers;o.set(`Accept`,`text/event-stream`),t.token!==void 0&&o.set(`Authorization`,`Bearer ${t.token}`),n!==null&&o.set(`Last-Event-ID`,n);let s=new AbortController,c=()=>s.abort();r.addEventListener(`abort`,c,{once:!0});let l,u,d=()=>{clearTimeout(l),l=setTimeout(c,An)};try{let n=new URL(typeof e==`function`?await e():e),r=t.fetch??globalThis.fetch;d();let c=await r(n,{headers:o,signal:s.signal}),{status:l}=c;if(l>=400&&l<500&&!Mn.has(l)){let e=nn.safeParse(await c.json().catch(()=>void 0));throw new V(`The host refused the stream (${l})`,{cause:e.success?e.data:void 0})}if(!c.ok||c.body===null){await c.body?.cancel();return}if(!Cn(c.headers.get(`Content-Type`),`text/event-stream`))throw await c.body.cancel(),new V(`The host did not answer with an event stream`);i();let f=new TransformStream({transform(e,t){d(),t.enqueue(e)}}),p=c.body.pipeThrough(f).pipeThrough(new TextDecoderStream).pipeThrough(new jn(t.parseData)).getReader();for(s.signal.addEventListener(`abort`,()=>void p.cancel(),{once:!0});;){let{done:e,value:n}=await p.read();if(e)return;if(u=t.stop?.(n),u!==void 0)throw u;a(n)}}catch(e){if(e instanceof V||e===u)throw e}finally{clearTimeout(l),r.removeEventListener(`abort`,c)}}}var Pn=new Set(Qt.options.flatMap(e=>e.shape.event.options)),Fn=g({event:p().min(1),data:S(),id:p().optional()});function H(e){queueMicrotask(()=>{throw e})}var In=class{#e;#t=!1;#n;#r=new Set;constructor(e,t){this.#e=e.cursor??null,this.#n=new Set([`ready`,`reset`,...(e.types??t).flatMap(e=>{let t=`${e}.removed`;return Pn.has(t)?[e,t]:[e]})])}get cursor(){return this.#e}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}resume(){return this.#e===null&&this.#t&&this.#i({event:`reset`,data:{}}),this.#e}receive(e){let t=Fn.safeParse(e);if(!t.success)throw new V(`The host sent a message that is not an event`,{cause:t.error});this.#i(t.data)}#i(e){let t;if(Pn.has(e.event)){let n=Qt.safeParse(e);if(!n.success)throw new V(`The host sent an invalid ${e.event} event`,{cause:n.error});t=n.data}else t=e;if(e.id!==void 0&&(this.#e=e.id),t.event===`reset`?(this.#e=null,this.#t=!1):this.#e===null&&(this.#t=!0),this.#n.has(t.event))for(let e of this.#r)try{e(t)}catch(e){H(e)}}},Ln=10,Rn=5e3;function zn(e){return Math.min(1e3*1.5**(e-1),15e3)*(.75+Math.random()/2)}function Bn(e,t){return new Promise(n=>{let r=setTimeout(i,e);t.addEventListener(`abort`,i,{once:!0});function i(){clearTimeout(r),t.removeEventListener(`abort`,i),n()}})}var Vn=class{closed;#e;#t=`connecting`;#n=new AbortController;#r;#i;#a;#o=new Set;constructor(e,t,n){let r;if(typeof e==`function`)r=e;else{let n=new URL(e);t.types!==void 0&&n.searchParams.set(`types`,t.types.join(`,`)),r=Nn(n,t)}if(this.#e=new In({types:t.types,cursor:t.cursor},n),this.#r=t.onStatus,this.closed=new Promise((e,t)=>{this.#i={resolve:e,reject:t}}),this.closed.catch(()=>void 0),t.signal?.aborted){this.close();return}let i=t.signal;if(i!==void 0){let e=()=>this.close();i.addEventListener(`abort`,e,{once:!0}),this.#a=()=>i.removeEventListener(`abort`,e)}this.#s(r)}get status(){return this.#t}get cursor(){return this.#e.cursor}subscribe(e,t){let n=!0,r=this.#e.subscribe(t=>{n&&e(t)}),i=e=>{n&&t?.(e)};return t!==void 0&&this.#i!==void 0&&this.#o.add(i),()=>{n=!1,this.#o.delete(i),r()}}close(){this.#l()?.resolve()}[Symbol.asyncIterator](){let e=[],t=[],n=()=>t.splice(0).forEach(e=>e()),r,i=this.subscribe(t=>{e.push(t),n()});this.closed.then(()=>{r={},n()},e=>{r={error:e},n()});let a=()=>(i(),this.close(),{done:!0,value:void 0});return{next:async()=>{for(;;){let n=e.shift();if(n!==void 0)return{done:!1,value:n};if(r!==void 0){if(r.error!==void 0)throw i(),r.error;return a()}await new Promise(e=>t.push(e))}},return:async()=>a()}}async#s(e){await Promise.resolve();let{signal:t}=this.#n,n=0;for(;!t.aborted;){let r=!0,i=!1,a;try{await e({cursor:this.#e.resume(),signal:t},{open:()=>{r&&this.#i!==void 0&&this.#c(`connected`)},message:e=>{if(!(!r||this.#i===void 0)){a??=setTimeout(()=>{i=!0},Rn);try{this.#e.receive(e)}catch(e){this.#l()?.reject(e)}}}})}catch(e){this.#l()?.reject(e);return}finally{r=!1,clearTimeout(a)}if(t.aborted)return;if(this.#c(`connecting`),n=i?1:n+1,n>Ln){this.#l()?.reject(new V(`The host could not be reached`));return}await Bn(zn(n),t)}}#c(e){if(this.#t!==e){this.#t=e;try{this.#r?.(e)}catch(e){H(e)}}}#l(){let e=this.#i;if(e===void 0)return;this.#i=void 0;let t=[...this.#o];return this.#o.clear(),this.#a?.(),this.#n.abort(),this.#c(`closed`),{resolve:e.resolve,reject:n=>{e.reject(n);for(let e of t)try{e(n)}catch(e){H(e)}}}}},Hn=class extends Vn{constructor(e,t={}){typeof e!=`function`&&t.runId!==void 0&&(e=new URL(e),e.searchParams.set(`run_id`,t.runId)),super(e,t,bn)}},Un=class{#e;constructor(e){this.#e=e}update(e,t){return this.#t(`notebook.update`,{body:e,options:t})}delete(e){return this.#t(`notebook.delete`,{options:e})}open(e){return this.#t(`notebook.open`,{options:e})}edit(e,t){return this.#t(`notebook.edit`,{body:{changes:[...e]},options:t})}save(e){return this.#t(`notebook.save`,{body:{decisions:e?.decisions},headers:{"If-Match":e?.ifMatch},options:e})}start(e){return this.#t(`runtime.start`,{body:{decisions:e?.decisions},options:e})}stop(e){return this.#t(`runtime.stop`,{options:e})}restart(e){return this.#t(`runtime.restart`,{options:e})}run(e,t){return this.#t(`runtime.run`,{body:e,options:t})}interrupt(e,t){return this.#t(`runtime.interrupt`,{params:{run_id:e},options:t})}#t(e,t){return Dn(this.#e,e,t)}},Wn=class extends Un{#e;#t;constructor(e,t={}){let n=new URL(e);super({url:n,prefix:`/notebooks/{notebook_id}`,client:t}),this.#e=n,this.#t=t}static unstable_over(e,{notebookId:t}){return new Un({send:t=>e(t),prefix:`/notebooks/{notebook_id}`,params:{notebook_id:t}})}get url(){return new URL(this.#e)}events(e={}){return new Hn(wn(this.#e,`/events`),{...this.#t,...e})}};function Gn(e,t){return t?(t.throwIfAborted(),new Promise((n,r)=>{let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e().then(n,r).finally(()=>t.removeEventListener(`abort`,i))})):e()}function Kn(e){let t=Wn.unstable_over(t=>e.call(t),{notebookId:e.notebookId});return{transport:async({cursor:t,signal:n},{open:r,message:i})=>{if(n.aborted)return;let a,o,s=new Promise(e=>{o=e}),c=()=>{a?.(),o()};n.addEventListener(`abort`,c,{once:!0});try{r(),await Gn(()=>e.subscribe(t,e=>{n.aborted||i(e)}).then(e=>{a=e,n.aborted&&e()}),n),await s}catch(e){if(!n.aborted)throw a?.(),new V(`Could not follow the WASM notebook`,{cause:e})}finally{n.removeEventListener(`abort`,c)}},notebook:()=>t}}function qn(e){return e.assetUrl,e}var Jn=1e10,Yn=1e3;function U(e,t){let n=e.map(e=>`"${e}"`).join(`, `);return Error(`This RPC instance cannot ${t} because the transport did not provide one or more of these methods: ${n}`)}function Xn(e={}){let t={};function n(e){t=e}let r={};function i(e){r.unregisterHandler&&r.unregisterHandler(),r=e,r.registerHandler?.(x)}let a;function o(e){if(typeof e==`function`){a=e;return}a=(t,n)=>{let r=e[t];if(r)return r(n);let i=e._;if(!i)throw Error(`The requested method has no handler: ${t}`);return i(t,n)}}let{maxRequestTime:s=Yn}=e;e.transport&&i(e.transport),e.requestHandler&&o(e.requestHandler),e._debugHooks&&n(e._debugHooks);let c=0;function l(){return c<=Jn?++c:c=0}let u=new Map,d=new Map;function f(e,...n){let i=n[0];return new Promise((n,a)=>{if(!r.send)throw U([`send`],`make requests`);let o=l(),c={type:`request`,id:o,method:e,params:i};u.set(o,{resolve:n,reject:a}),s!==1/0&&d.set(o,setTimeout(()=>{d.delete(o),a(Error(`RPC request timed out.`))},s)),t.onSend?.(c),r.send(c)})}let p=new Proxy(f,{get:(e,t,n)=>t in e?Reflect.get(e,t,n):e=>f(t,e)}),m=p;function h(e,...n){let i=n[0];if(!r.send)throw U([`send`],`send messages`);let a={type:`message`,id:e,payload:i};t.onSend?.(a),r.send(a)}let g=new Proxy(h,{get:(e,t,n)=>t in e?Reflect.get(e,t,n):e=>h(t,e)}),_=g,v=new Map,y=new Set;function b(e,t){if(!r.registerHandler)throw U([`registerHandler`],`register message listeners`);if(e===`*`){y.add(t);return}v.has(e)||v.set(e,new Set),v.get(e)?.add(t)}function ee(e,t){if(e===`*`){y.delete(t);return}v.get(e)?.delete(t),v.get(e)?.size===0&&v.delete(e)}async function x(e){if(t.onReceive?.(e),!(`type`in e))throw Error(`Message does not contain a type.`);if(e.type===`request`){if(!r.send||!a)throw U([`send`,`requestHandler`],`handle requests`);let{id:n,method:i,params:o}=e,s;try{s={type:`response`,id:n,success:!0,payload:await a(i,o)}}catch(e){if(!(e instanceof Error))throw e;s={type:`response`,id:n,success:!1,error:e.message}}t.onSend?.(s),r.send(s);return}if(e.type===`response`){let t=d.get(e.id);t!=null&&clearTimeout(t);let{resolve:n,reject:r}=u.get(e.id)??{};e.success?n?.(e.payload):r?.(Error(e.error));return}if(e.type===`message`){for(let t of y)t(e.id,e.payload);let t=v.get(e.id);if(!t)return;for(let n of t)n(e.payload);return}throw Error(`Unexpected RPC message type: ${e.type}`)}return{setTransport:i,setRequestHandler:o,request:p,requestProxy:m,send:g,sendProxy:_,addMessageListener:b,removeMessageListener:ee,proxy:{send:_,request:m},_setDebugHooks:n}}function Zn(e){return Xn(e)}var Qn=`[transport-id]`;function $n(e,t){let{transportId:n}=t;return n==null?e:{[Qn]:n,data:e}}function er(e,t){let{transportId:n,filter:r}=t,i=r?.();if(n!=null&&i!=null)throw Error("Cannot use both `transportId` and `filter` at the same time");let a=e;if(n){if(e[Qn]!==n)return[!0];a=e.data}return i===!1?[!0]:[!1,a]}function tr(e,t={}){let{transportId:n,filter:r,remotePort:i}=t,a=e,o=i??e,s;return{send(e){o.postMessage($n(e,{transportId:n}))},registerHandler(e){s=t=>{let i=t.data,[a,o]=er(i,{transportId:n,filter:()=>r?.(t)});a||e(o)},a.addEventListener(`message`,s)},unregisterHandler(){s&&a.removeEventListener(`message`,s)}}}function nr(e,t){return tr(e,t)}var rr=`::controller`,ir=`marimo-transport`;function ar(e){return Zn({transport:nr(e,{transportId:ir}),maxRequestTime:2e4,_debugHooks:{onSend:e=>{C.debug(`[rpc] Parent -> Worker`,e)},onReceive:e=>{C.debug(`[rpc] Worker -> Parent`,e)}}})}function or(){let e=document.querySelector(`marimo-wasm`),t=e=>{try{return e?new URL(e,document.baseURI).href:void 0}catch{return}};return{version:pe(),pyodideIndexUrl:t(e?.dataset.pyodideIndexUrl),pyodideLockfileUrl:t(e?.dataset.pyodideLockfileUrl),pypiIndexUrl:t(e?.dataset.pypiIndexUrl)?.replaceAll(`%7Bpackage_name%7D`,`{package_name}`)}}var sr=De(),cr=`marimo:file`,lr=new r(null),ur={saveFile(e){lr.set(cr,e)},readFile(){return lr.get(cr)}},dr={saveFile(e){s.setCodeForHash((0,sr.compressToEncodedURIComponent)(e))},readFile(){let e=s.getCodeFromHash()||s.getCodeFromSearchParam();return e?(0,sr.decompressFromEncodedURIComponent)(e):null}},fr={saveFile(e){},readFile(){let e=document.querySelector(`marimo-code`);return e?decodeURIComponent(e.textContent||``).trim():null}},pr={saveFile(e){},readFile(){if(window.location.hostname!==`marimo.app`)return null;let e=new URL(`export_demos/wasm-intro.py`,document.baseURI);return fetch(e.toString()).then(e=>e.ok?e.text():null).catch(()=>null)}},mr={saveFile(e){},readFile(){return e.get(n)??null}},hr={saveFile(e){},readFile(){return[`import marimo`,`app = marimo.App()`,``,`@app.cell`,`def __():`,` return`,``,`if __name__ == "__main__":`,` app.run()`].join(`
106
106
  `)}},gr=class{stores;constructor(e){this.stores=e}insert(e,t){this.stores.splice(e,0,t)}saveFile(e){this.stores.forEach(t=>t.saveFile(e))}readFile(){for(let e of this.stores){let t=e.readFile();if(t)return t}return null}},W=new gr([mr,fr,dr]),G=new gr([ur,pr,hr]),_r=new URL(`save-worker-UwdGcNK5.js`,import.meta.url).href,vr=new URL(`worker-jm2VC7pS.js`,import.meta.url).href,yr=class t{static get INSTANCE(){let e=`_marimo_private_PyodideBridge`;return window[e]||(window[e]=new t),window[e]}rpc;saveRpc;pendingSessionSave=Promise.resolve();notebookConsumers=new Map;interruptBuffer;messageConsumer;initialized=new be;getSaveWorker(){if(se()===`read`)return C.debug(`Using partially disabled SaveWorker in read-mode`),{readFile:w,readNotebook:async()=>await W.readFile()??``,saveNotebook:w};let e=or(),t=ar(Me(new URL(_r,import.meta.url),{name:br()}));return t.send.bootstrap(e),t.proxy.request}constructor(){if(!ue())return;let t=or(),n=Me(new URL(vr,import.meta.url),{name:br()});this.rpc=ar(n),this.rpc.send.bootstrap(t),this.rpc.addMessageListener(`notebookEvent`,({id:e,event:t})=>{this.notebookConsumers.get(e)?.(JSON.parse(t))}),this.rpc.addMessageListener(`ready`,()=>{this.startSession()}),this.rpc.addMessageListener(`initialized`,()=>{this.saveRpc=this.getSaveWorker(),this.setInterruptBuffer(),e.set(E,{kind:`ready`}),this.initialized.resolve()}),this.rpc.addMessageListener(`initializingMessage`,({message:t})=>{e.get(E).kind===`loading`&&e.set(E,{kind:`loading`,message:t})}),this.rpc.addMessageListener(`initializedError`,({error:t})=>{if(this.initialized.status===`resolved`){C.error(t),_e({title:`Error initializing`,description:t,variant:`danger`});return}e.set(E,{kind:`error`,message:t}),this.initialized.reject(Error(t))}),this.rpc.addMessageListener(`kernelMessage`,({message:e})=>{this.messageConsumer?.(new MessageEvent(`message`,{data:e}))})}async startSession(){let t=await W.readFile(),n=await G.readFile(),r=e.get(l)??s.getFilename(),i=e.get(re),a={},o=new URLSearchParams(window.location.search);for(let e of o.keys()){let t=o.getAll(e);a[e]=t.length===1?t[0]:t}await this.rpc.proxy.request.startSession({queryParameters:a,code:t||n||``,filename:r,userConfig:{...i,runtime:{...i.runtime,auto_instantiate:se()===`read`||i.runtime.auto_instantiate}}})}setInterruptBuffer(){crossOriginIsolated?(this.interruptBuffer=new Uint8Array(new SharedArrayBuffer(1)),this.rpc.proxy.request.setInterruptBuffer(this.interruptBuffer)):C.warn(`Not running in a secure context; interrupts are not available.`)}attachMessageConsumer(e){this.messageConsumer=e,this.rpc.proxy.send.consumerReady({})}async createNotebookBackend(){await this.initialized.promise;let{id:e}=await this.rpc.proxy.request.notebookInfo();return Kn({notebookId:e,subscribe:async(e,t)=>{await this.initialized.promise;let n=xe();this.notebookConsumers.set(n,t);let r=()=>{this.notebookConsumers.delete(n),this.rpc.proxy.request.notebookUnsubscribe(n).catch(C.error)};try{return await this.rpc.proxy.request.notebookSubscribe({id:n,cursor:e}),r}catch(e){throw r(),e}},call:async e=>(await this.initialized.promise,this.rpc.proxy.request.notebookCall(e))})}sendRename=async({filename:e})=>e===null?null:(s.setFilename(e),await this.rpc.proxy.request.bridge({functionName:`rename_file`,payload:e}),null);sendSave=async e=>{if(!this.saveRpc)return C.warn(`Save RPC not initialized`),null;let t=this.saveRpc.saveNotebook(e);this.pendingSessionSave=this.pendingSessionSave.catch(()=>void 0).then(async()=>{await t,await this.rpc.proxy.request.saveNotebook(e)}),this.pendingSessionSave.catch(e=>{C.error(e)}),await t;let n=await this.readCode();return n.contents&&(W.saveFile(n.contents),G.saveFile(n.contents)),null};sendCopy=async()=>{w()};sendStdin=async e=>(await this.rpc.proxy.request.bridge({functionName:`put_input`,payload:e.text}),null);sendPdb=async()=>{w()};sendSetBreakpoints=async()=>{w()};sendRun=async e=>(await this.rpc.proxy.request.loadPackages(e.codes.join(`
107
- `)),await this.putControlRequest({type:`execute-cells`,...e}),null);sendRunScratchpad=async e=>(await this.rpc.proxy.request.loadPackages(e.code),await this.putControlRequest({type:`execute-scratchpad`,...e}),null);sendInterrupt=async()=>(this.interruptBuffer!==void 0&&(this.interruptBuffer[0]=2),null);sendShutdown=async()=>(window.close(),null);sendFormat=async e=>await this.rpc.proxy.request.bridge({functionName:`format`,payload:e});sendDeleteCell=async e=>(await this.putControlRequest({type:`delete-cell`,...e}),null);sendInstallMissingPackages=async e=>(this.putControlRequest({type:`install-packages`,...e}),null);sendCodeCompletionRequest=async t=>(e.get(c)||await this.rpc.proxy.request.bridge({functionName:`code_complete`,payload:t}),null);saveUserConfig=async e=>(await this.rpc.proxy.request.bridge({functionName:`save_user_config`,payload:e}),oe.post(`/kernel/save_user_config`,e,{baseUrl:`/`}).catch(e=>(C.error(e),null)));saveAppConfig=async e=>(await this.rpc.proxy.request.bridge({functionName:`save_app_config`,payload:e}),null);saveCellConfig=async e=>(await this.putControlRequest({type:`update-cell-config`,...e}),null);sendRestart=async()=>{let e=await this.readCode();return e.contents&&(W.saveFile(e.contents),G.saveFile(e.contents)),Ee(),null};readCode=async()=>this.saveRpc?{contents:await this.saveRpc.readNotebook()}:(C.warn(`Save RPC not initialized`),{contents:``});readSnippets=async()=>await this.rpc.proxy.request.bridge({functionName:`read_snippets`,payload:void 0});openFile=async()=>{let e=Oe({code:null,baseUrl:window.location.origin});return window.open(e,`_blank`),null};sendListFiles=async e=>await this.rpc.proxy.request.bridge({functionName:`list_files`,payload:e});getFileRoots=async()=>await this.rpc.proxy.request.bridge({functionName:`file_roots`,payload:void 0});sendSearchFiles=async e=>await this.rpc.proxy.request.bridge({functionName:`search_files`,payload:e});sendComponentValues=async e=>(await this.putControlRequest({type:`update-ui-element`,...e,token:xe()}),null);sendInstantiate=async()=>null;sendFunctionRequest=async e=>(await this.putControlRequest({type:`invoke-function`,...e}),null);sendCreateFileOrFolder=async e=>{let t=null;return e.file&&(t=(await we(e.file)).split(`,`)[1]??``),await this.rpc.proxy.request.bridge({functionName:`create_file_or_directory`,payload:{path:e.path,type:e.type,name:e.name,contents:t}})};sendDeleteFileOrFolder=async e=>await this.rpc.proxy.request.bridge({functionName:`delete_file_or_directory`,payload:e});sendCopyFileOrFolder=async e=>await this.rpc.proxy.request.bridge({functionName:`copy_file_or_directory`,payload:e});sendRenameFileOrFolder=async e=>await this.rpc.proxy.request.bridge({functionName:`move_file_or_directory`,payload:e});sendUpdateFile=async e=>await this.rpc.proxy.request.bridge({functionName:`update_file`,payload:e});sendFileDetails=async e=>await this.rpc.proxy.request.bridge({functionName:`file_details`,payload:e});exportAsHTML=async e=>(await this.pendingSessionSave,await this.rpc.proxy.request.bridge({functionName:`export_html`,payload:qn(e)}));exportAsMarkdown=async e=>(await this.pendingSessionSave,await this.rpc.proxy.request.bridge({functionName:`export_markdown`,payload:e}));exportAsScript=async e=>(await this.pendingSessionSave,await this.rpc.proxy.request.bridge({functionName:`export_script`,payload:e}));previewDatasetColumn=async e=>(await this.putControlRequest({type:`preview-dataset-column`,...e}),null);previewSQLTable=async e=>(await this.putControlRequest({type:`preview-sql-table`,...e}),null);previewSQLTableList=async e=>(await this.putControlRequest({type:`list-sql-tables`,...e}),null);previewSQLSchemaList=async e=>(await this.putControlRequest({type:`list-sql-schemas`,...e}),null);previewDataSourceConnection=async e=>(await this.putControlRequest({type:`list-data-source-connection`,...e}),null);validateSQL=async e=>(await this.putControlRequest({type:`validate-sql`,...e}),null);sendModelValue=async e=>(await this.putControlRequest({type:`model`,...e}),null);sendDocumentTransaction=()=>Promise.resolve(null);addPackage=async e=>this.rpc.proxy.request.addPackage(e);removePackage=async e=>this.rpc.proxy.request.removePackage(e);getPackageList=async()=>await this.rpc.proxy.request.listPackages();getSandbox=async()=>({backend:null,manifest:null,filename:null});updateManifest=async()=>{throw Error(`Sandboxes are not supported in WebAssembly`)};syncSandbox=async()=>{throw Error(`Sandboxes are not supported in WebAssembly`)};getDependencyTree=async()=>({tree:{dependencies:[],name:``,tags:[],version:null},context:{kind:`package-manager`,name:`micropip`}});listSecretKeys=async e=>(await this.putControlRequest({type:`list-secret-keys`,...e}),null);discoverDataSources=async e=>(await this.putControlRequest({type:`discover-data-sources`,...e}),null);getUsageStats=w;getEnvironmentInfo=async()=>await this.rpc.proxy.request.bridge({functionName:`get_environment_info`,payload:void 0});openTutorial=w;getRecentFiles=w;getWorkspaceFiles=w;getRunningNotebooks=w;shutdownSession=w;getExportAvailability=w;installExportRequirements=w;exportAsIPYNB=w;exportAsPDF=w;autoExportAsHTML=w;autoExportAsMarkdown=w;autoExportAsIPYNB=w;updateCellOutputs=w;writeSecret=w;invokeAiTool=w;clearCache=w;getCacheInfo=w;listStorageEntries=w;downloadStorage=w;async putControlRequest(e){await this.rpc.proxy.request.bridge({functionName:`put_control_request`,payload:e})}};function br(){return`marimo${typeof window<`u`&&window.__MARIMO_HAS_WASM_CONTROLLER__===!0?rr:``}`}function xr(e=T()){let t=window.fetch;return window.fetch=async(n,r)=>{let i=n instanceof Request?n.url:n.toString();if(i.startsWith(`data:`))return t(n,r);try{let a=K(i,e);if(a){let e=await(await t(a)).arrayBuffer();return new Response(e,{headers:{"Content-Type":Sr(i)}})}return t(n,r)}catch(e){return C.error(`Error parsing URL`,e),t(n,r)}},()=>{window.fetch=t}}function Sr(e){return e.endsWith(`.csv`)?`text/csv`:e.endsWith(`.json`)?`application/json`:e.endsWith(`.txt`)?`text/plain`:`application/octet-stream`}function Cr(e,t=T()){let n=e.http.bind(e),r=e.load.bind(e);return e.http=async e=>{let r=K(e,t);if(r)return await window.fetch(r).then(e=>e.text());try{return await n(e)}catch(t){if(e.startsWith(`data:`))return await window.fetch(e).then(e=>e.text());throw t}},e.load=async e=>{let n=K(e,t);if(n)return await window.fetch(n).then(e=>e.text());try{return await r(e)}catch(t){if(e.startsWith(`data:`))return await window.fetch(e).then(e=>e.text());throw t}},()=>{e.http=n,e.load=r}}function wr(e){return e.startsWith(`.`)?e.slice(1):e}function Tr(e,t=T()){let n=K(e,t);if(!n)return e;let r=Te(n);return URL.createObjectURL(r)}function K(e,t){let n=document.baseURI;n.startsWith(`blob:`)&&(n=n.replace(`blob:`,``));let r=new URL(e,n).pathname,i=Er(e),a=Er(r);return t[e]||t[wr(e)]||t[r]||t[wr(r)]||i&&t[i]||a&&t[a]}function Er(e){let t=e.indexOf(`/@file/`);return t===-1?null:e.slice(t)}function q(e,t){return{get(t){return e.get(t)},set(t,n){e.set(t,n)},save_changes(){e.save_changes()},send:e.send.bind(e),on(n,r){t.aborted||(e.on(n,r),t.addEventListener(`abort`,()=>e.off(n,r),{once:!0}))},off(t,n){e.off(t??null,n??null)},widget_manager:{async get_model(n){return q(await e.widget_manager.get_model(n),t)}}}}function J(e){return typeof e==`string`&&e.length>0}function Dr(e){if(typeof e==`string`&&e.startsWith(`anywidget:`)){let t=e.slice(10);if(J(t))return t}throw Error(`[anywidget] Invalid widget reference: ${JSON.stringify(e)}`)}function Or(e,t){return{async getModel(n){let r=Dr(n);return q(await e.getModel(r),t)},async getWidget(n){let r=Dr(n),i=await e.getWidget(r);return{exports:i.exports,async render({el:e,signal:n}){await i.render({el:e,signal:n??t})}}}}}var kr=Symbol(`marimo`);function Y(e){return e[kr]}var Ar=class e{#e=`change`;#t;#n;#r;#i={};static _modelManager;constructor(e,t,n){this.#n=e,this.#r=t,this.#t=new Set,n&&n.addEventListener(`abort`,()=>{C.debug(`[Model] Signal aborted, clearing all listeners`),this.#i={}})}[kr]={updateAndEmitDiffs:e=>this.#o(e),emitCustomMessage:(e,t)=>this.#s(e,t)};off(e,t){if(!e){this.#i={};return}if(!t){this.#i[e]=new Set;return}this.#i[e]?.delete(t)}send(e,t,n){let r=(n??[]).map(e=>e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength));return this.#r.sendCustomMessage(e,r).then(()=>t?.())}widget_manager={async get_model(t){let n=await e._modelManager.getModel(t);if(!n)throw Error(`Model not found with id: ${t}. This is likely because the model was not registered.`);return n}};get(e){return this.#n[e]}set(e,t){this.#n={...this.#n,[e]:t},this.#t.add(e),this.#a(`change:${e}`,t),this.#c()}save_changes(){if(this.#t.size===0)return;let e=Object.fromEntries([...this.#t].map(e=>[e,this.#n[e]]));this.#t.clear(),this.#r.sendUpdate(e)}on(e,t,n){let r=n?.signal;r?.aborted||(this.#i[e]||(this.#i[e]=new Set),this.#i[e].add(t),r?.addEventListener(`abort`,()=>this.off(e,t),{once:!0}))}#a(e,t){let n=this.#i[e];if(n)for(let e of[...n])try{e(t)}catch(e){C.error(`Error emitting event`,e)}}#o(e){e!=null&&Object.keys(e).forEach(t=>{let n=t;this.#t.delete(n),this.#n[n]!==e[n]&&(this.#n={...this.#n,[n]:e[n]},this.#a(`change:${n}`,e[n]),this.#c())})}#s(e,t=[]){let n=this.#i[`msg:custom`];if(n)for(let r of[...n])try{r(e.content,t)}catch(e){C.error(`Error emitting event`,e)}}#c=ne(()=>{let e=this.#i[this.#e];if(e)for(let t of[...e])try{t()}catch(e){C.error(`Error emitting event`,e)}},0)};function jr(e){return typeof e==`function`}function Mr(e){return typeof e==`function`}function Nr(e){return t(e)&&(jr(e.render)||Mr(e.initialize))}function Pr(e){return typeof e==`function`||Nr(e)}function Fr(e){return t(e)&&Pr(e.default)}var Ir=new Set,Lr=new WeakMap;function Rr(e,n){if(Fr(e))return e.default;if(!t(e)||e.default!==void 0)return null;let r=jr(e.render)?e.render:void 0,i=Mr(e.initialize)?e.initialize:void 0;if(r===void 0&&i===void 0)return null;let a=Lr.get(e);if(a)return a;Ir.has(n)||(Ir.add(n),C.warn(`Anywidget module at ${n} uses deprecated top-level named exports (\`render\`/\`initialize\`). Per the AFM spec, use a default export instead: \`export default { render }\`. See https://anywidget.dev/en/afm/`));let o={render:r,initialize:i};return Lr.set(e,o),o}function zr(e,n){let r=`https://anywidget.dev/en/afm/`,a=t(e)&&i(e,`render`),o=t(e)&&i(e,`initialize`);if(t(e)&&e.default!==void 0)return Error(`Anywidget module at ${n} has an invalid default export. Expected a factory function or an object with \`render\` or \`initialize\`. See ${r}`);if(a||o){let e=[a?"`render`":null,o?"`initialize`":null].filter(Boolean).join(` and `),t=[a?`render`:null,o?`initialize`:null].filter(e=>e!==null),i=`export default { ${t.join(`, `)} }`,s=t.length===1?`export function ${t[0]}`:`named export function ...`;return Error(`Anywidget module at ${n} uses named exports (${e}). Per the AFM spec, use a default export instead: \`${i}\` (not \`${s}\`). See ${r}`)}return Error(`Anywidget module at ${n} is missing a default export. Per the AFM spec, use \`export default { render }\` or \`export default async () => ({ render })\`. See ${r}`)}function Br(e){return typeof e!=`string`||e.length===0?!1:!!(/^(\.?\/)?@file\/[^?#]+$/.test(e)||Hr(e))}function Vr(){return e.get(Ce)||Se()}function Hr(e){return e.startsWith(`data:text/javascript;base64,`)||e.startsWith(`data:application/javascript;base64,`)||e.startsWith(`data:text/css;base64,`)?Vr():!1}var Ur={invoke:async()=>{let e=`anywidget.invoke not supported in marimo. Please file an issue at https://github.com/marimo-team/marimo/issues`;throw C.warn(e),Error(e)}};function Wr(e){if(typeof AbortSignal.any==`function`)return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted)return t.abort(n.reason),t.signal;n.addEventListener(`abort`,()=>t.abort(n.reason),{once:!0})}return t.signal}var Gr=class{#e=new Map;getModule(e){let{jsUrl:t,jsHash:n,kernelAuthored:r=!1,lifetime:i}=e,a=this.#e.get(n);if(!a){let e={references:0,dispose:()=>void 0,promise:this.#t(t,{kernelAuthored:r}).then(({module:t,dispose:n})=>(e.dispose=n,t),t=>{throw this.#e.get(n)===e&&this.#e.delete(n),t})};this.#e.set(n,e),a=e}let o=a;o.references+=1;let s=()=>{--o.references,o.references===0&&o.promise.then(()=>{o.dispose(),o.dispose=()=>void 0},()=>void 0)};return i?.aborted?s():i?.addEventListener(`abort`,s,{once:!0}),o.promise}invalidate(e){this.#e.delete(e)}async#t(e,t={}){if(!(Br(e)||t.kernelAuthored===!0&&/^(https?:|data:)/.test(e)))throw Error(`Refusing to load anywidget module from untrusted URL: ${String(e)}`);let n=fe(e).toString(),r=de()?Tr(n):n,i=()=>{r!==n&&URL.revokeObjectURL(r)};try{return{module:await ve(()=>import(r),[],import.meta.url),dispose:i}}catch(e){throw i(),e}}};function X(e){return typeof e==`function`}async function Kr(e,t){try{await e()}catch(e){C.warn(`[WidgetBinding] ${t} cleanup failed`,e)}}var qr=class e{#e;#t;#n;#r;#i;#a=new Set;#o=new Set;#s;constructor(e){this.#t=e.widget,this.#n=e.model,this.#r=e.exports,this.#e=e.controller,this.#i=e.createHost,this.#s=e.onDestroy}static async create({widgetDef:t,model:n,createHost:r,controller:i=new AbortController,onDestroy:a}){let o=i.signal,s;try{let c=typeof t==`function`?await t():t;if(o.aborted)throw Error(`[anywidget] binding destroyed`);let l=Promise.resolve(c.initialize?.({model:q(n,o),experimental:Ur,signal:o}));s=l.then(async e=>{o.aborted&&X(e)&&await Kr(e,`late initialize`)}).catch(()=>void 0);let u=await Promise.race([l,new Promise((e,t)=>{let n=()=>t(Error(`[anywidget] binding destroyed`));if(o.aborted){n();return}o.addEventListener(`abort`,n,{once:!0})})]);if(o.aborted)throw Error(`[anywidget] binding destroyed`);let d,f;X(u)?(f=u,d=void 0):d=typeof u==`object`&&u?u:void 0;let p=new e({widget:c,model:n,exports:d,controller:i,createHost:r,onDestroy:a});return f&&o.addEventListener(`abort`,()=>void p.#l(f,`initialize`),{once:!0}),p}catch(e){throw s?s.then(()=>a?.()):a?.(),e}}get exports(){return this.#r}async createView(e,t){let n=this.#c(e,t);this.#o.add(n);try{await n}finally{this.#o.delete(n)}}async#c(e,t){let n=this.#t;if(!n.render)return;let r=Wr([t.signal,this.#e.signal]);if(r.aborted)return;e.el.innerHTML=``;let i=this.#i(r),a=await n.render({model:q(this.#n,r),el:e.el,experimental:Ur,signal:r,host:i});if(X(a)){let e=()=>{let e=t.signal.aborted?`view unmount`:`binding destroyed`;return C.debug(`[WidgetBinding] Render cleanup triggered (reason: ${e})`),this.#l(a,`render`)};if(r.aborted){await e();return}r.addEventListener(`abort`,()=>void e(),{once:!0})}}#l(e,t){let n=Kr(e,t);return this.#a.add(n),n.finally(()=>this.#a.delete(n)),n}async destroy(){for(C.debug(`[WidgetBinding] Destroying binding generation`),this.#e.abort(),await Promise.allSettled(this.#o);this.#a.size>0;)await Promise.all(this.#a);this.#s?.(),this.#s=void 0}},Jr=new Gr,Yr=class{#e;#t;#n;#r;#i;#a=new AbortController;#o=new be;#s=new Set;#c=new Map;#l;#u;#d;#f=Promise.resolve();#p=``;constructor(e,t){this.#e=e,this.#t=t.timeout,this.#n=t.isEditMode,this.#r=t.createHost,this.#i=t.onModelTimeout}getModel(){return this.#o.status===`pending`&&!this.#l&&(this.#l=setTimeout(()=>{this.#o.status===`pending`&&(this.#l=void 0,this.#o.reject(Error(`Model not found for key: ${this.#e}`)),this.#i())},this.#t)),this.#o.promise}getModelSync(){return this.#o.status===`resolved`?this.#o.value:void 0}createModel(e){this.#o.status===`pending`&&this.#m(e(this.#a.signal))}setModel(e){this.#o.status===`pending`&&this.#m(e)}#m(e){this.#l&&=(clearTimeout(this.#l),void 0),this.#o.resolve(e);let t=e.get(`_css`);this.#p=typeof t==`string`?t:``,e.on(`change:_css`,e=>{this.#p=typeof e==`string`?e:``;for(let e of this.#c.values())e.update(this.#p)},{signal:this.#a.signal})}setSpec(e){if(!this.#u){this.#u=e;return}this.#n()&&(this.#u=e,this.#d&&this.#d.hash!==e.hash&&this.#v(e))}async getWidget(){return{exports:(await this.#h()).exports,render:async({el:e,signal:t})=>{await this.createView({el:e,signal:t??this.#a.signal})}}}async createView(e){if(e.signal.aborted||this.#a.signal.aborted)return;let t={el:e.el,signal:e.signal};this.#s.add(t),this.#x(t),e.signal.addEventListener(`abort`,()=>this.#s.delete(t),{once:!0}),await this.#b(t)}async#h(){for(;!this.#a.signal.aborted;){let e=await this.getModel(),t=this.#d;if(!t){let n=this.#u;if(!n)throw Error(`[anywidget] No ESM spec for model ${this.#e}: nothing ever provided this widget's code`);t=this.#_(n,e)}try{let e=await t.promise;if(t===this.#d)return e}catch(e){if(!this.#d||t===this.#d)throw e}}throw Error(`[anywidget] widget runtime destroyed`)}async#g(e){let{spec:t,model:n,controller:r}=e,i=new AbortController,a;try{let e=await Jr.getModule({jsUrl:t.url,jsHash:t.hash,kernelAuthored:!0,lifetime:i.signal}),n=Rr(e,t.url);if(!n)throw Jr.invalidate(t.hash),zr(e,t.url);a=n}catch(e){throw i.abort(),e}return qr.create({widgetDef:a,model:n,createHost:this.#r,controller:r,onDestroy:()=>i.abort()})}#_(e,t){let n=new AbortController,r={hash:e.hash,controller:n,promise:this.#g({spec:e,model:t,controller:n})};return r.promise.catch(()=>{this.#d===r&&(this.#d=void 0)}),this.#d=r,r}#v(e){let t=this.#d;if(!t)return;C.debug(`[WidgetRuntime] Hot-swapping generation for model=${this.#e}`);let n=this.#y(t),r=this.getModelSync();if(!r)return;let i=this.#_(e,r);for(let e of this.#s)e.generation=void 0,n.then(()=>this.#b(e,i)).catch(e=>{C.error(`[WidgetRuntime] Error replacing widget view`,e)})}#y(e){e.controller.abort();let t=this.#f.then(async()=>{try{await(await e.promise).destroy()}catch{}});return this.#f=t,t}async#b(e,t){if(e.signal.aborted||this.#a.signal.aborted)return;let n=t??this.#d,r=n?await n.promise:await this.#h(),i=this.#d;if(!(!i||i!==(n??i))&&e.generation!==i){e.generation=i;try{await r.createView({el:e.el},{signal:e.signal})}catch(t){if(i!==this.#d){e.generation=void 0;return}throw t}}}#x(e){let t=e.el.getRootNode();if(!Z(t)&&!Xr(t))return;let n=this.#c.get(t);n||(n=Zr(t,this.#p),this.#c.set(t,n)),n.references+=1;let r=!1;e.signal.addEventListener(`abort`,()=>{if(r)return;r=!0;let e=this.#c.get(t);e&&(--e.references,e.references===0&&(e.dispose(),this.#c.delete(t)))},{once:!0})}dispose(){if(!this.#a.signal.aborted){C.debug(`[WidgetRuntime] Disposing model=${this.#e}`),this.#l&&=(clearTimeout(this.#l),void 0),this.#o.status===`pending`&&(this.#o.promise.catch(()=>void 0),this.#o.reject(Error(`[anywidget] widget runtime destroyed`))),this.#d&&this.#y(this.#d),this.#a.abort(),this.#s.clear();for(let e of this.#c.values())e.dispose();this.#c.clear()}}};function Z(e){return e.nodeType===Node.DOCUMENT_NODE}function Xr(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e}function Zr(e,t){let n=Z(e)?e:e.ownerDocument??document,r=n.defaultView??window;if(`adoptedStyleSheets`in e&&r.CSSStyleSheet!==void 0&&typeof r.CSSStyleSheet.prototype.replaceSync==`function`)try{let n=new r.CSSStyleSheet;return n.replaceSync(t),e.adoptedStyleSheets=[...e.adoptedStyleSheets,n],{references:0,update(e){n.replaceSync(e)},dispose(){e.adoptedStyleSheets=e.adoptedStyleSheets.filter(e=>e!==n)}}}catch{}let i=n.createElement(`style`);return i.textContent=t,Z(e)?n.head.append(i):e.append(i),{references:0,update(e){i.textContent=e},dispose(){i.remove()}}}function Q(e,t=[]){let n=[];if(e instanceof DataView)n.push(t);else if(Array.isArray(e))for(let[r,i]of e.entries())n.push(...Q(i,[...t,r]));else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))n.push(...Q(i,[...t,r]));return n}function Qr(e){let t=Q(e);if(t.length===0)return{state:e,buffers:[],bufferPaths:[]};let n=structuredClone(e),r=[],i=[];for(let a of t){let t=te(e,a);if(t instanceof DataView){let e=me(t);r.push(e),i.push(a),k(n,a,e)}}return{state:n,buffers:r,bufferPaths:i}}function $r(e){let{state:t,bufferPaths:n,buffers:r}=e;if(!n||n.length===0)return t;r&&ae(r.length===n.length,`Buffers and buffer paths not the same length`);let i=t;for(let[e,t]of n.entries()){let n=r?.[e];if(n==null){C.warn(`[anywidget] Could not find buffer at path`,t);continue}typeof n==`string`?k(i,t,he(n)):k(i,t,n)}return i}function ei(){let t=e.get(ce).mode;return t===`edit`||t===`present`}var $=new class{#e=new Map;#t;#n;constructor(e=1e4,t=ei){this.#t=e,this.#n=t}#r(e){let t=this.#e.get(e);if(!t){let n=new Yr(e,{timeout:this.#t,isEditMode:this.#n,createHost:e=>Or(this,e),onModelTimeout:()=>{this.#e.get(e)===n&&(n.dispose(),this.#e.delete(e))}});t=n,this.#e.set(e,t)}return t}getModel(e){return this.#r(e).getModel()}getModelSync(e){return this.#e.get(e)?.getModelSync()}createModel(e,t){this.#r(e).createModel(t)}setModel(e,t){this.#r(e).setModel(t)}setSpec(e,t){this.#r(e).setSpec(t)}getWidget(e){return this.#r(e).getWidget()}createView(e){return this.#r(e.modelId).createView(e)}delete(e){let t=this.#e.get(e);t&&(t.dispose(),this.#e.delete(e))}};Ar._modelManager=$;async function ti(e,t){let n=t.model_id;if(!J(n))throw Error(`[anywidget] Invalid model id: ${String(n)}`);let r=t.message,i=(`buffers`in r?r.buffers:[]).map(he);switch(r.method){case`open`:{let{state:t,buffer_paths:a=[]}=r;r.esm_spec&&e.setSpec(n,r.esm_spec);let o=$r({state:t,bufferPaths:a,buffers:i}),s=e.getModelSync(n);if(s){Y(s).updateAndEmitDiffs(o);return}e.createModel(n,e=>{let t=de()?{sendUpdate:async()=>void 0,sendCustomMessage:async()=>void 0}:{async sendUpdate(t){if(e.aborted){C.debug(`[Model] sendUpdate suppressed for model=${n} (signal aborted)`);return}let{state:r,buffers:i,bufferPaths:a}=Qr(t);await D().sendModelValue({modelId:n,message:{method:`update`,state:r,bufferPaths:a},buffers:i})},async sendCustomMessage(t,r){if(e.aborted){C.debug(`[Model] sendCustomMessage suppressed for model=${n} (signal aborted)`);return}await D().sendModelValue({modelId:n,message:{method:`custom`,content:t},buffers:r.map(me)})}};return new Ar(o,t,e)});return}case`custom`:Y(await e.getModel(n)).emitCustomMessage({method:`custom`,content:r.content},i);return;case`close`:e.delete(n);return;case`update`:{let{state:t,buffer_paths:a=[]}=r;r.esm_spec&&e.setSpec(n,r.esm_spec);let o=$r({state:t,bufferPaths:a,buffers:i});Y(await e.getModel(n)).updateAndEmitDiffs(o);return}default:ye(r)}}o($,`WIDGET_REGISTRY`);function ni(e){return typeof e!=`object`||!e?!1:`type`in e&&e.type===`marimo-ui-value-update`}var ri=class e{entries;static get INSTANCE(){let t=`_marimo_private_UIElementRegistry`;return window[t]||(window[t]=new e),window[t]}constructor(){this.entries=new Map}has(e){return this.entries.has(e)}set(e,t){this.entries.has(e)&&C.debug(`UIElementRegistry overwriting entry for objectId.`,e),this.entries.set(e,{objectId:e,value:t,elements:new Set})}registerInstance(e,t){let n=this.entries.get(e);n===void 0?this.entries.set(e,{objectId:e,value:a(t,this),elements:new Set([t])}):n.elements.add(t)}removeInstance(e,t){let n=this.entries.get(e);n?.elements.has(t)&&n.elements.delete(t)}removeElementsByCell(e){[...this.entries.keys()].filter(t=>t.startsWith(`${e}-`)).forEach(e=>{this.entries.delete(e)})}lookupValue(e){let t=this.entries.get(e);return t===void 0?void 0:t.value}broadcastMessage(e,t,n){let r=this.entries.get(e);if(r===void 0){C.warn(`UIElementRegistry missing entry`,e);return}if(ni(t)){r.value=t.value,r.elements.forEach(e=>{e.dispatchEvent(ke.create({bubbles:!1,composed:!0,detail:{value:t.value,element:e}}))});return}r.elements.forEach(r=>{r.dispatchEvent(je.create({bubbles:!1,composed:!0,detail:{objectId:e,message:t,buffers:n}}))})}broadcastValueUpdate(e,t,n){let r=this.entries.get(t);r===void 0?C.warn(`UIElementRegistry missing entry`,t):(r.value=n,r.elements.forEach(t=>{t!==e&&t.dispatchEvent(ke.create({bubbles:!1,composed:!0,detail:{value:n,element:t}}))}),document.dispatchEvent(Ae.create({bubbles:!0,composed:!0,detail:{objectId:t}})))}},ii=ri.INSTANCE,ai=new ge(`function-call-result`,async(e,t)=>{await D().sendFunctionRequest({functionCallId:e,...t})}),oi=`68px`,si=`288px`,ci=e=>e?/^\d+$/.test(e)?`${e}px`:e:si,li=le({isOpen:!0},(e,t)=>{if(!t)return e;switch(t.type){case`toggle`:return{...e,isOpen:t.isOpen??e.isOpen};case`setWidth`:return{...e,width:t.width};default:return e}});export{Nn as _,ri as a,ti as c,xr as d,Cr as f,Hn as g,qn as h,ai as i,Br as l,W as m,ci as n,ii as o,yr as p,li as r,$ as s,oi as t,J as u,V as v,k as y};
107
+ `)),await this.putControlRequest({type:`execute-cells`,...e}),null);sendRunScratchpad=async e=>(await this.rpc.proxy.request.loadPackages(e.code),await this.putControlRequest({type:`execute-scratchpad`,...e}),null);sendInterrupt=async()=>(this.interruptBuffer!==void 0&&(this.interruptBuffer[0]=2),null);sendShutdown=async()=>(window.close(),null);sendFormat=async e=>await this.rpc.proxy.request.bridge({functionName:`format`,payload:e});sendDeleteCell=async e=>(await this.putControlRequest({type:`delete-cell`,...e}),null);sendInstallMissingPackages=async e=>(this.putControlRequest({type:`install-packages`,...e}),null);sendCodeCompletionRequest=async t=>(e.get(c)||await this.rpc.proxy.request.bridge({functionName:`code_complete`,payload:t}),null);saveUserConfig=async e=>(await this.rpc.proxy.request.bridge({functionName:`save_user_config`,payload:e}),oe.post(`/kernel/save_user_config`,e,{baseUrl:`/`}).catch(e=>(C.error(e),null)));saveAppConfig=async e=>(await this.rpc.proxy.request.bridge({functionName:`save_app_config`,payload:e}),null);saveCellConfig=async e=>(await this.putControlRequest({type:`update-cell-config`,...e}),null);sendRestart=async()=>{let e=await this.readCode();return e.contents&&(W.saveFile(e.contents),G.saveFile(e.contents)),Ee(),null};readCode=async()=>this.saveRpc?{contents:await this.saveRpc.readNotebook()}:(C.warn(`Save RPC not initialized`),{contents:``});readSnippets=async()=>await this.rpc.proxy.request.bridge({functionName:`read_snippets`,payload:void 0});openFile=async()=>{let e=Oe({code:null,baseUrl:window.location.origin});return window.open(e,`_blank`),null};sendListFiles=async e=>await this.rpc.proxy.request.bridge({functionName:`list_files`,payload:e});getFileRoots=async()=>await this.rpc.proxy.request.bridge({functionName:`file_roots`,payload:void 0});sendSearchFiles=async e=>await this.rpc.proxy.request.bridge({functionName:`search_files`,payload:e});sendComponentValues=async e=>(await this.putControlRequest({type:`update-ui-element`,...e,token:xe()}),null);sendInstantiate=async()=>null;sendFunctionRequest=async e=>(await this.putControlRequest({type:`invoke-function`,...e}),null);sendCreateFileOrFolder=async e=>{let t=null;return e.file&&(t=(await we(e.file)).split(`,`)[1]??``),await this.rpc.proxy.request.bridge({functionName:`create_file_or_directory`,payload:{path:e.path,type:e.type,name:e.name,contents:t}})};sendDeleteFileOrFolder=async e=>await this.rpc.proxy.request.bridge({functionName:`delete_file_or_directory`,payload:e});sendCopyFileOrFolder=async e=>await this.rpc.proxy.request.bridge({functionName:`copy_file_or_directory`,payload:e});sendRenameFileOrFolder=async e=>await this.rpc.proxy.request.bridge({functionName:`move_file_or_directory`,payload:e});sendUpdateFile=async e=>await this.rpc.proxy.request.bridge({functionName:`update_file`,payload:e});sendFileDetails=async e=>await this.rpc.proxy.request.bridge({functionName:`file_details`,payload:e});exportAsHTML=async e=>(await this.pendingSessionSave,await this.rpc.proxy.request.bridge({functionName:`export_html`,payload:qn(e)}));exportAsMarkdown=async e=>(await this.pendingSessionSave,await this.rpc.proxy.request.bridge({functionName:`export_markdown`,payload:e}));exportAsScript=async e=>(await this.pendingSessionSave,await this.rpc.proxy.request.bridge({functionName:`export_script`,payload:e}));previewDatasetColumn=async e=>(await this.putControlRequest({type:`preview-dataset-column`,...e}),null);previewSQLTable=async e=>(await this.putControlRequest({type:`preview-sql-table`,...e}),null);previewSQLTableList=async e=>(await this.putControlRequest({type:`list-sql-tables`,...e}),null);previewSQLSchemaList=async e=>(await this.putControlRequest({type:`list-sql-schemas`,...e}),null);previewDataSourceConnection=async e=>(await this.putControlRequest({type:`list-data-source-connection`,...e}),null);validateSQL=async e=>(await this.putControlRequest({type:`validate-sql`,...e}),null);sendModelValue=async e=>(await this.putControlRequest({type:`model`,...e}),null);sendDocumentTransaction=()=>Promise.resolve(null);addPackage=async e=>this.rpc.proxy.request.addPackage(e);removePackage=async e=>this.rpc.proxy.request.removePackage(e);getPackageList=async()=>await this.rpc.proxy.request.listPackages();getSandbox=async()=>({backend:null,manifest:null,filename:null});updateManifest=async()=>{throw Error(`Sandboxes are not supported in WebAssembly`)};syncSandbox=async()=>{throw Error(`Sandboxes are not supported in WebAssembly`)};getDependencyTree=async()=>({tree:{dependencies:[],name:``,tags:[],version:null},context:{kind:`package-manager`,name:`micropip`}});listSecretKeys=async e=>(await this.putControlRequest({type:`list-secret-keys`,...e}),null);discoverDataSources=async e=>(await this.putControlRequest({type:`discover-data-sources`,...e}),null);getUsageStats=w;getEnvironmentInfo=async()=>await this.rpc.proxy.request.bridge({functionName:`get_environment_info`,payload:void 0});openTutorial=w;getRecentFiles=w;getWorkspaceFiles=w;getRunningNotebooks=w;shutdownSession=w;getExportAvailability=w;installExportRequirements=w;exportAsIPYNB=w;exportAsPDF=w;autoExportAsHTML=w;autoExportAsMarkdown=w;autoExportAsIPYNB=w;updateCellOutputs=w;writeSecret=w;invokeAiTool=w;clearCache=w;getCacheInfo=w;listStorageEntries=w;downloadStorage=w;async putControlRequest(e){await this.rpc.proxy.request.bridge({functionName:`put_control_request`,payload:e})}};function br(){return`marimo${typeof window<`u`&&window.__MARIMO_HAS_WASM_CONTROLLER__===!0?rr:``}`}function xr(e=T()){let t=window.fetch;return window.fetch=async(n,r)=>{let i=n instanceof Request?n.url:n.toString();if(i.startsWith(`data:`))return t(n,r);try{let a=K(i,e);if(a){let e=await(await t(a)).arrayBuffer();return new Response(e,{headers:{"Content-Type":Sr(i)}})}return t(n,r)}catch(e){return C.error(`Error parsing URL`,e),t(n,r)}},()=>{window.fetch=t}}function Sr(e){return e.endsWith(`.csv`)?`text/csv`:e.endsWith(`.json`)?`application/json`:e.endsWith(`.txt`)?`text/plain`:`application/octet-stream`}function Cr(e,t=T()){let n=e.http.bind(e),r=e.load.bind(e);return e.http=async e=>{let r=K(e,t);if(r)return await window.fetch(r).then(e=>e.text());try{return await n(e)}catch(t){if(e.startsWith(`data:`))return await window.fetch(e).then(e=>e.text());throw t}},e.load=async e=>{let n=K(e,t);if(n)return await window.fetch(n).then(e=>e.text());try{return await r(e)}catch(t){if(e.startsWith(`data:`))return await window.fetch(e).then(e=>e.text());throw t}},()=>{e.http=n,e.load=r}}function wr(e){return e.startsWith(`.`)?e.slice(1):e}function Tr(e,t=T()){let n=K(e,t);if(!n)return e;let r=Te(n);return URL.createObjectURL(r)}function K(e,t){let n=document.baseURI;n.startsWith(`blob:`)&&(n=n.replace(`blob:`,``));let r=new URL(e,n).pathname,i=Er(e),a=Er(r);return t[e]||t[wr(e)]||t[r]||t[wr(r)]||i&&t[i]||a&&t[a]}function Er(e){let t=e.indexOf(`/@file/`);return t===-1?null:e.slice(t)}function q(e,t){return{get(t){return e.get(t)},set(t,n){e.set(t,n)},save_changes(){e.save_changes()},send:e.send.bind(e),on(n,r){t.aborted||(e.on(n,r),t.addEventListener(`abort`,()=>e.off(n,r),{once:!0}))},off(t,n){e.off(t??null,n??null)},widget_manager:{async get_model(n){return q(await e.widget_manager.get_model(n),t)}}}}function J(e){return typeof e==`string`&&e.length>0}function Dr(e){if(typeof e==`string`&&e.startsWith(`anywidget:`)){let t=e.slice(10);if(J(t))return t}throw Error(`[anywidget] Invalid widget reference: ${JSON.stringify(e)}`)}function Or(e,t){return{async getModel(n){let r=Dr(n);return q(await e.getModel(r),t)},async getWidget(n){let r=Dr(n),i=await e.getWidget(r);return{exports:i.exports,async render({el:e,signal:n}){await i.render({el:e,signal:n??t})}}}}}var kr=Symbol(`marimo`);function Y(e){return e[kr]}var Ar=class e{#e=`change`;#t;#n;#r;#i={};static _modelManager;constructor(e,t,n){this.#n=e,this.#r=t,this.#t=new Set,n&&n.addEventListener(`abort`,()=>{C.debug(`[Model] Signal aborted, clearing all listeners`),this.#i={}})}[kr]={updateAndEmitDiffs:e=>this.#o(e),emitCustomMessage:(e,t)=>this.#s(e,t)};off(e,t){if(!e){this.#i={};return}if(!t){this.#i[e]=new Set;return}this.#i[e]?.delete(t)}send(e,t,n){let r=(n??[]).map(e=>e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength));return this.#r.sendCustomMessage(e,r).then(()=>t?.())}widget_manager={async get_model(t){let n=await e._modelManager.getModel(t);if(!n)throw Error(`Model not found with id: ${t}. This is likely because the model was not registered.`);return n}};get(e){return this.#n[e]}set(e,t){this.#n={...this.#n,[e]:t},this.#t.add(e),this.#a(`change:${e}`,t),this.#c()}save_changes(){if(this.#t.size===0)return;let e=Object.fromEntries([...this.#t].map(e=>[e,this.#n[e]]));this.#t.clear(),this.#r.sendUpdate(e)}on(e,t,n){let r=n?.signal;r?.aborted||(this.#i[e]||(this.#i[e]=new Set),this.#i[e].add(t),r?.addEventListener(`abort`,()=>this.off(e,t),{once:!0}))}#a(e,t){let n=this.#i[e];if(n)for(let e of[...n])try{e(t)}catch(e){C.error(`Error emitting event`,e)}}#o(e){e!=null&&Object.keys(e).forEach(t=>{let n=t;this.#t.delete(n),this.#n[n]!==e[n]&&(this.#n={...this.#n,[n]:e[n]},this.#a(`change:${n}`,e[n]),this.#c())})}#s(e,t=[]){let n=this.#i[`msg:custom`];if(n)for(let r of[...n])try{r(e.content,t)}catch(e){C.error(`Error emitting event`,e)}}#c=ne(()=>{let e=this.#i[this.#e];if(e)for(let t of[...e])try{t()}catch(e){C.error(`Error emitting event`,e)}},0)};function jr(e){return typeof e==`function`}function Mr(e){return typeof e==`function`}function Nr(e){return t(e)&&(jr(e.render)||Mr(e.initialize))}function Pr(e){return typeof e==`function`||Nr(e)}function Fr(e){return t(e)&&Pr(e.default)}var Ir=new Set,Lr=new WeakMap;function Rr(e,n){if(Fr(e))return e.default;if(!t(e)||e.default!==void 0)return null;let r=jr(e.render)?e.render:void 0,i=Mr(e.initialize)?e.initialize:void 0;if(r===void 0&&i===void 0)return null;let a=Lr.get(e);if(a)return a;Ir.has(n)||(Ir.add(n),C.warn(`Anywidget module at ${n} uses deprecated top-level named exports (\`render\`/\`initialize\`). Per the AFM spec, use a default export instead: \`export default { render }\`. See https://anywidget.dev/en/afm/`));let o={render:r,initialize:i};return Lr.set(e,o),o}function zr(e,n){let r=`https://anywidget.dev/en/afm/`,a=t(e)&&i(e,`render`),o=t(e)&&i(e,`initialize`);if(t(e)&&e.default!==void 0)return Error(`Anywidget module at ${n} has an invalid default export. Expected a factory function or an object with \`render\` or \`initialize\`. See ${r}`);if(a||o){let e=[a?"`render`":null,o?"`initialize`":null].filter(Boolean).join(` and `),t=[a?`render`:null,o?`initialize`:null].filter(e=>e!==null),i=`export default { ${t.join(`, `)} }`,s=t.length===1?`export function ${t[0]}`:`named export function ...`;return Error(`Anywidget module at ${n} uses named exports (${e}). Per the AFM spec, use a default export instead: \`${i}\` (not \`${s}\`). See ${r}`)}return Error(`Anywidget module at ${n} is missing a default export. Per the AFM spec, use \`export default { render }\` or \`export default async () => ({ render })\`. See ${r}`)}function Br(e){return typeof e!=`string`||e.length===0?!1:!!(/^(\.?\/)?@file\/[^?#]+$/.test(e)||Hr(e))}function Vr(){return e.get(Ce)||Se()}function Hr(e){return e.startsWith(`data:text/javascript;base64,`)||e.startsWith(`data:application/javascript;base64,`)||e.startsWith(`data:text/css;base64,`)?Vr():!1}var Ur={invoke:async()=>{let e=`anywidget.invoke not supported in marimo. Please file an issue at https://github.com/marimo-team/marimo/issues`;throw C.warn(e),Error(e)}};function Wr(e){if(typeof AbortSignal.any==`function`)return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted)return t.abort(n.reason),t.signal;n.addEventListener(`abort`,()=>t.abort(n.reason),{once:!0})}return t.signal}var Gr=class{#e=new Map;getModule(e){let{jsUrl:t,jsHash:n,kernelAuthored:r=!1,lifetime:i}=e,a=this.#e.get(n);if(!a){let e={references:0,dispose:()=>void 0,promise:this.#t(t,{kernelAuthored:r}).then(({module:t,dispose:n})=>(e.dispose=n,t),t=>{throw this.#e.get(n)===e&&this.#e.delete(n),t})};this.#e.set(n,e),a=e}let o=a;o.references+=1;let s=()=>{--o.references,o.references===0&&o.promise.then(()=>{o.dispose(),o.dispose=()=>void 0},()=>void 0)};return i?.aborted?s():i?.addEventListener(`abort`,s,{once:!0}),o.promise}invalidate(e){this.#e.delete(e)}async#t(e,t={}){if(!(Br(e)||t.kernelAuthored===!0&&/^(https?:|data:)/.test(e)))throw Error(`Refusing to load anywidget module from untrusted URL: ${String(e)}`);let n=fe(e).toString(),r=de()?Tr(n):n,i=()=>{r!==n&&URL.revokeObjectURL(r)};try{return{module:await ve(()=>import(r),[],import.meta.url),dispose:i}}catch(e){throw i(),e}}};function X(e){return typeof e==`function`}async function Kr(e,t){try{await e()}catch(e){C.warn(`[WidgetBinding] ${t} cleanup failed`,e)}}var qr=class e{#e;#t;#n;#r;#i;#a=new Set;#o=new Set;#s;constructor(e){this.#t=e.widget,this.#n=e.model,this.#r=e.exports,this.#e=e.controller,this.#i=e.createHost,this.#s=e.onDestroy}static async create({widgetDef:t,model:n,createHost:r,controller:i=new AbortController,onDestroy:a}){let o=i.signal,s;try{let c=typeof t==`function`?await t():t;if(o.aborted)throw Error(`[anywidget] binding destroyed`);let l=Promise.resolve(c.initialize?.({model:q(n,o),experimental:Ur,signal:o}));s=l.then(async e=>{o.aborted&&X(e)&&await Kr(e,`late initialize`)}).catch(()=>void 0);let u=await Promise.race([l,new Promise((e,t)=>{let n=()=>t(Error(`[anywidget] binding destroyed`));if(o.aborted){n();return}o.addEventListener(`abort`,n,{once:!0})})]);if(o.aborted)throw Error(`[anywidget] binding destroyed`);let d,f;X(u)?(f=u,d=void 0):d=typeof u==`object`&&u?u:void 0;let p=new e({widget:c,model:n,exports:d,controller:i,createHost:r,onDestroy:a});return f&&o.addEventListener(`abort`,()=>void p.#l(f,`initialize`),{once:!0}),p}catch(e){throw s?s.then(()=>a?.()):a?.(),e}}get exports(){return this.#r}async createView(e,t){let n=this.#c(e,t);this.#o.add(n);try{await n}finally{this.#o.delete(n)}}async#c(e,t){let n=this.#t;if(!n.render)return;let r=Wr([t.signal,this.#e.signal]);if(r.aborted)return;e.el.innerHTML=``;let i=this.#i(r),a=await n.render({model:q(this.#n,r),el:e.el,experimental:Ur,signal:r,host:i});if(X(a)){let e=()=>{let e=t.signal.aborted?`view unmount`:`binding destroyed`;return C.debug(`[WidgetBinding] Render cleanup triggered (reason: ${e})`),this.#l(a,`render`)};if(r.aborted){await e();return}r.addEventListener(`abort`,()=>void e(),{once:!0})}}#l(e,t){let n=Kr(e,t);return this.#a.add(n),n.finally(()=>this.#a.delete(n)),n}async destroy(){for(C.debug(`[WidgetBinding] Destroying binding generation`),this.#e.abort(),await Promise.allSettled(this.#o);this.#a.size>0;)await Promise.all(this.#a);this.#s?.(),this.#s=void 0}},Jr=new Gr,Yr=class{#e;#t;#n;#r;#i;#a=new AbortController;#o=new be;#s=new Set;#c=new Map;#l;#u;#d;#f=Promise.resolve();#p=``;constructor(e,t){this.#e=e,this.#t=t.timeout,this.#n=t.isEditMode,this.#r=t.createHost,this.#i=t.onModelTimeout}getModel(){return this.#o.status===`pending`&&!this.#l&&(this.#l=setTimeout(()=>{this.#o.status===`pending`&&(this.#l=void 0,this.#o.reject(Error(`Model not found for key: ${this.#e}`)),this.#i())},this.#t)),this.#o.promise}getModelSync(){return this.#o.status===`resolved`?this.#o.value:void 0}createModel(e){this.#o.status===`pending`&&this.#m(e(this.#a.signal))}setModel(e){this.#o.status===`pending`&&this.#m(e)}#m(e){this.#l&&=(clearTimeout(this.#l),void 0),this.#o.resolve(e);let t=e.get(`_css`);this.#p=typeof t==`string`?t:``,e.on(`change:_css`,e=>{this.#p=typeof e==`string`?e:``;for(let e of this.#c.values())e.update(this.#p)},{signal:this.#a.signal})}setSpec(e){if(!this.#u){this.#u=e;return}this.#n()&&(this.#u=e,this.#d&&this.#d.hash!==e.hash&&this.#v(e))}async getWidget(){return{exports:(await this.#h()).exports,render:async({el:e,signal:t})=>{await this.createView({el:e,signal:t??this.#a.signal})}}}async createView(e){if(e.signal.aborted||this.#a.signal.aborted)return;let t={el:e.el,signal:e.signal};this.#s.add(t),this.#x(t),e.signal.addEventListener(`abort`,()=>this.#s.delete(t),{once:!0}),await this.#b(t)}async#h(){for(;!this.#a.signal.aborted;){let e=await this.getModel(),t=this.#d;if(!t){let n=this.#u;if(!n)throw Error(`[anywidget] No ESM spec for model ${this.#e}: nothing ever provided this widget's code`);t=this.#_(n,e)}try{let e=await t.promise;if(t===this.#d)return e}catch(e){if(!this.#d||t===this.#d)throw e}}throw Error(`[anywidget] widget runtime destroyed`)}async#g(e){let{spec:t,model:n,controller:r}=e,i=new AbortController,a;try{let e=await Jr.getModule({jsUrl:t.url,jsHash:t.hash,kernelAuthored:!0,lifetime:i.signal}),n=Rr(e,t.url);if(!n)throw Jr.invalidate(t.hash),zr(e,t.url);a=n}catch(e){throw i.abort(),e}return qr.create({widgetDef:a,model:n,createHost:this.#r,controller:r,onDestroy:()=>i.abort()})}#_(e,t){let n=new AbortController,r={hash:e.hash,controller:n,promise:this.#g({spec:e,model:t,controller:n})};return r.promise.catch(()=>{this.#d===r&&(this.#d=void 0)}),this.#d=r,r}#v(e){let t=this.#d;if(!t)return;C.debug(`[WidgetRuntime] Hot-swapping generation for model=${this.#e}`);let n=this.#y(t),r=this.getModelSync();if(!r)return;let i=this.#_(e,r);for(let e of this.#s)e.generation=void 0,n.then(()=>this.#b(e,i)).catch(e=>{C.error(`[WidgetRuntime] Error replacing widget view`,e)})}#y(e){e.controller.abort();let t=this.#f.then(async()=>{try{await(await e.promise).destroy()}catch{}});return this.#f=t,t}async#b(e,t){if(e.signal.aborted||this.#a.signal.aborted)return;let n=t??this.#d,r=n?await n.promise:await this.#h(),i=this.#d;if(!(!i||i!==(n??i))&&e.generation!==i){e.generation=i;try{await r.createView({el:e.el},{signal:e.signal})}catch(t){if(i!==this.#d){e.generation=void 0;return}throw t}}}#x(e){let t=e.el.getRootNode();if(!Z(t)&&!Xr(t))return;let n=this.#c.get(t);n||(n=Zr(t,this.#p),this.#c.set(t,n)),n.references+=1;let r=!1;e.signal.addEventListener(`abort`,()=>{if(r)return;r=!0;let e=this.#c.get(t);e&&(--e.references,e.references===0&&(e.dispose(),this.#c.delete(t)))},{once:!0})}dispose(){if(!this.#a.signal.aborted){C.debug(`[WidgetRuntime] Disposing model=${this.#e}`),this.#l&&=(clearTimeout(this.#l),void 0),this.#o.status===`pending`&&(this.#o.promise.catch(()=>void 0),this.#o.reject(Error(`[anywidget] widget runtime destroyed`))),this.#d&&this.#y(this.#d),this.#a.abort(),this.#s.clear();for(let e of this.#c.values())e.dispose();this.#c.clear()}}};function Z(e){return e.nodeType===Node.DOCUMENT_NODE}function Xr(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e}function Zr(e,t){let n=Z(e)?e:e.ownerDocument??document,r=n.defaultView??window;if(`adoptedStyleSheets`in e&&r.CSSStyleSheet!==void 0&&typeof r.CSSStyleSheet.prototype.replaceSync==`function`)try{let n=new r.CSSStyleSheet;return n.replaceSync(t),e.adoptedStyleSheets=[...e.adoptedStyleSheets,n],{references:0,update(e){n.replaceSync(e)},dispose(){e.adoptedStyleSheets=e.adoptedStyleSheets.filter(e=>e!==n)}}}catch{}let i=n.createElement(`style`);return i.textContent=t,Z(e)?n.head.append(i):e.append(i),{references:0,update(e){i.textContent=e},dispose(){i.remove()}}}function Q(e,t=[]){let n=[];if(e instanceof DataView)n.push(t);else if(Array.isArray(e))for(let[r,i]of e.entries())n.push(...Q(i,[...t,r]));else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))n.push(...Q(i,[...t,r]));return n}function Qr(e){let t=Q(e);if(t.length===0)return{state:e,buffers:[],bufferPaths:[]};let n=structuredClone(e),r=[],i=[];for(let a of t){let t=te(e,a);if(t instanceof DataView){let e=me(t);r.push(e),i.push(a),k(n,a,e)}}return{state:n,buffers:r,bufferPaths:i}}function $r(e){let{state:t,bufferPaths:n,buffers:r}=e;if(!n||n.length===0)return t;r&&ae(r.length===n.length,`Buffers and buffer paths not the same length`);let i=t;for(let[e,t]of n.entries()){let n=r?.[e];if(n==null){C.warn(`[anywidget] Could not find buffer at path`,t);continue}typeof n==`string`?k(i,t,he(n)):k(i,t,n)}return i}function ei(){let t=e.get(ce).mode;return t===`edit`||t===`present`}var $=new class{#e=new Map;#t;#n;constructor(e=1e4,t=ei){this.#t=e,this.#n=t}#r(e){let t=this.#e.get(e);if(!t){let n=new Yr(e,{timeout:this.#t,isEditMode:this.#n,createHost:e=>Or(this,e),onModelTimeout:()=>{this.#e.get(e)===n&&(n.dispose(),this.#e.delete(e))}});t=n,this.#e.set(e,t)}return t}getModel(e){return this.#r(e).getModel()}getModelSync(e){return this.#e.get(e)?.getModelSync()}createModel(e,t){this.#r(e).createModel(t)}setModel(e,t){this.#r(e).setModel(t)}setSpec(e,t){this.#r(e).setSpec(t)}getWidget(e){return this.#r(e).getWidget()}createView(e){return this.#r(e.modelId).createView(e)}delete(e){let t=this.#e.get(e);t&&(t.dispose(),this.#e.delete(e))}};Ar._modelManager=$;async function ti(e,t){let n=t.model_id;if(!J(n))throw Error(`[anywidget] Invalid model id: ${String(n)}`);let r=t.message,i=(`buffers`in r?r.buffers:[]).map(he);switch(r.method){case`open`:{let{state:t,buffer_paths:a=[]}=r;r.esm_spec&&e.setSpec(n,r.esm_spec);let o=$r({state:t,bufferPaths:a,buffers:i}),s=e.getModelSync(n);if(s){Y(s).updateAndEmitDiffs(o);return}e.createModel(n,e=>{let t=de()?{sendUpdate:async()=>void 0,sendCustomMessage:async()=>void 0}:{async sendUpdate(t){if(e.aborted){C.debug(`[Model] sendUpdate suppressed for model=${n} (signal aborted)`);return}let{state:r,buffers:i,bufferPaths:a}=Qr(t);await D().sendModelValue({modelId:n,message:{method:`update`,state:r,bufferPaths:a},buffers:i})},async sendCustomMessage(t,r){if(e.aborted){C.debug(`[Model] sendCustomMessage suppressed for model=${n} (signal aborted)`);return}await D().sendModelValue({modelId:n,message:{method:`custom`,content:t},buffers:r.map(me)})}};return new Ar(o,t,e)});return}case`custom`:Y(await e.getModel(n)).emitCustomMessage({method:`custom`,content:r.content},i);return;case`close`:e.delete(n);return;case`update`:{let{state:t,buffer_paths:a=[]}=r;r.esm_spec&&e.setSpec(n,r.esm_spec);let o=$r({state:t,bufferPaths:a,buffers:i});Y(await e.getModel(n)).updateAndEmitDiffs(o);return}default:ye(r)}}o($,`WIDGET_REGISTRY`);function ni(e){return typeof e!=`object`||!e?!1:`type`in e&&e.type===`marimo-ui-value-update`}var ri=class e{entries;static get INSTANCE(){let t=`_marimo_private_UIElementRegistry`;return window[t]||(window[t]=new e),window[t]}constructor(){this.entries=new Map}has(e){return this.entries.has(e)}set(e,t){this.entries.has(e)&&C.debug(`UIElementRegistry overwriting entry for objectId.`,e),this.entries.set(e,{objectId:e,value:t,elements:new Set})}registerInstance(e,t){let n=this.entries.get(e);n===void 0?this.entries.set(e,{objectId:e,value:a(t,this),elements:new Set([t])}):n.elements.add(t)}removeInstance(e,t){let n=this.entries.get(e);n?.elements.has(t)&&n.elements.delete(t)}removeElementsByCell(e){[...this.entries.keys()].filter(t=>t.startsWith(`${e}-`)).forEach(e=>{this.entries.delete(e)})}lookupValue(e){let t=this.entries.get(e);return t===void 0?void 0:t.value}broadcastMessage(e,t,n){let r=this.entries.get(e);if(r===void 0){C.warn(`UIElementRegistry missing entry`,e);return}if(ni(t)){r.value=t.value,r.elements.forEach(e=>{e.dispatchEvent(ke.create({bubbles:!1,composed:!0,detail:{value:t.value,element:e}}))});return}r.elements.forEach(r=>{r.dispatchEvent(je.create({bubbles:!1,composed:!0,detail:{objectId:e,message:t,buffers:n}}))})}broadcastValueUpdate(e,t,n){let r=this.entries.get(t);r===void 0?C.warn(`UIElementRegistry missing entry`,t):(r.value=n,r.elements.forEach(t=>{t!==e&&t.dispatchEvent(ke.create({bubbles:!1,composed:!0,detail:{value:n,element:t}}))}),document.dispatchEvent(Ae.create({bubbles:!0,composed:!0,detail:{objectId:t}})))}},ii=ri.INSTANCE,ai=new ge(`function-call-result`,async(e,t)=>{await D().sendFunctionRequest({functionCallId:e,...t})}),oi=`68px`,si=`288px`,ci=e=>e?/^\d+$/.test(e)?`${e}px`:e:si,li=le({isOpen:!0},(e,t)=>{if(!t)return e;switch(t.type){case`toggle`:return{...e,isOpen:t.isOpen??e.isOpen};case`setWidth`:return{...e,width:t.width};default:return e}});export{Hn as _,ri as a,k as b,ti as c,xr as d,Cr as f,Wn as g,qn as h,ai as i,Br as l,W as m,ci as n,ii as o,yr as p,li as r,$ as s,oi as t,J as u,Nn as v,V as y};
@@ -1 +1 @@
1
- import{f as e}from"./useEvent-BDjgaBtz.js";import{Qr as t,Zr as n}from"./cells-2HETnlvE.js";import{g as r}from"./useEventListener-CjDeLqFC.js";import{O as i}from"./config-CD1IuZFJ.js";import{t as a}from"./use-toast-Wu434mLr.js";import{d as o}from"./arrays-0R2reF2y.js";var s=`marimo:ai:chatState:v5`,c=e(null),l=e(null),u=i(`marimo:ai:chatOptions`,{webSearch:!1},t),d=i(`marimo:ai:includeOtherCells`,!0,t);function f(e){let t=new Map;for(let[n,r]of e.entries()){if(r.messages.length===0)continue;let e=o(r.messages,e=>e.id);t.set(n,{...r,messages:e})}return t}var p=n({toSerializable:e=>({chats:[...f(e.chats).entries()],activeChatId:e.activeChatId}),fromSerializable:e=>({chats:new Map(e.chats),activeChatId:e.activeChatId})}),m=i(s,{chats:new Map,activeChatId:null},{...p,setItem:(e,t)=>{try{f(t.chats).size===0?p.removeItem(e):p.setItem(e,t)}catch(e){r.warn(`Could not save chat history`,e),a({id:`chat-storage-error`,once:!0,title:`Chat history couldn't be saved`,description:`Try deleting old chats. New messages may be lost when you reload.`,variant:`danger`})}}}),h=e(e=>{let t=e(m);return t.activeChatId?t.chats.get(t.activeChatId):null},(e,t,n)=>{t(m,e=>({...e,activeChatId:n}))});export{d as a,m as i,c as n,l as o,u as r,h as t};
1
+ import{f as e}from"./useEvent-BDjgaBtz.js";import{Qr as t,Zr as n}from"./cells-B3LEgMh1.js";import{g as r}from"./useEventListener-CjDeLqFC.js";import{O as i}from"./config-BTFDx3Zj.js";import{t as a}from"./use-toast-Wu434mLr.js";import{d as o}from"./arrays-0R2reF2y.js";var s=`marimo:ai:chatState:v5`,c=e(null),l=e(null),u=i(`marimo:ai:chatOptions`,{webSearch:!1},t),d=i(`marimo:ai:includeOtherCells`,!0,t);function f(e){let t=new Map;for(let[n,r]of e.entries()){if(r.messages.length===0)continue;let e=o(r.messages,e=>e.id);t.set(n,{...r,messages:e})}return t}var p=n({toSerializable:e=>({chats:[...f(e.chats).entries()],activeChatId:e.activeChatId}),fromSerializable:e=>({chats:new Map(e.chats),activeChatId:e.activeChatId})}),m=i(s,{chats:new Map,activeChatId:null},{...p,setItem:(e,t)=>{try{f(t.chats).size===0?p.removeItem(e):p.setItem(e,t)}catch(e){r.warn(`Could not save chat history`,e),a({id:`chat-storage-error`,once:!0,title:`Chat history couldn't be saved`,description:`Try deleting old chats. New messages may be lost when you reload.`,variant:`danger`})}}}),h=e(e=>{let t=e(m);return t.activeChatId?t.chats.get(t.activeChatId):null},(e,t,n)=>{t(m,e=>({...e,activeChatId:n}))});export{d as a,m as i,c as n,l as o,u as r,h as t};