@spencerboucher/switchyard 0.19.0 → 0.20.0
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.
- package/README.md +8 -5
- package/dist/bridge/enroll.js +36 -6
- package/dist/bridge/switchyard-terminal.js +2 -1
- package/dist/policies/worker.js +47 -12
- package/dist/switchyard.mjs +1421 -585
- package/package.json +1 -1
- package/web-dist/assets/AutomationView-B4O_teaB.js +2 -0
- package/web-dist/assets/{AutomationView-X-U6Fpm7.js.map → AutomationView-B4O_teaB.js.map} +1 -1
- package/web-dist/assets/Button-C7TQGuSX.js +2 -0
- package/web-dist/assets/Button-C7TQGuSX.js.map +1 -0
- package/web-dist/assets/{Card-WONLvqGM.js → Card-DzHrwFrv.js} +2 -2
- package/web-dist/assets/{Card-WONLvqGM.js.map → Card-DzHrwFrv.js.map} +1 -1
- package/web-dist/assets/{Checkbox-BmiLcC-z.js → Checkbox-BnRsg6ki.js} +2 -2
- package/web-dist/assets/{Checkbox-BmiLcC-z.js.map → Checkbox-BnRsg6ki.js.map} +1 -1
- package/web-dist/assets/{DangerZone-Ch2KNmob.js → DangerZone-BicyqXv8.js} +2 -2
- package/web-dist/assets/{DangerZone-Ch2KNmob.js.map → DangerZone-BicyqXv8.js.map} +1 -1
- package/web-dist/assets/Field-Cp-08kpe.js +2 -0
- package/web-dist/assets/Field-Cp-08kpe.js.map +1 -0
- package/web-dist/assets/{Markdown-BKOAPNDn.js → Markdown-BPWc6K6m.js} +2 -2
- package/web-dist/assets/{Markdown-BKOAPNDn.js.map → Markdown-BPWc6K6m.js.map} +1 -1
- package/web-dist/assets/{Priority-DTBkp1nb.js → Priority-ZGpTH645.js} +2 -2
- package/web-dist/assets/{Priority-DTBkp1nb.js.map → Priority-ZGpTH645.js.map} +1 -1
- package/web-dist/assets/{SegmentedControl-Ca8Fsw-g.js → SegmentedControl-Cvkz7C_A.js} +2 -2
- package/web-dist/assets/{SegmentedControl-Ca8Fsw-g.js.map → SegmentedControl-Cvkz7C_A.js.map} +1 -1
- package/web-dist/assets/Select-DHRR7IAK.js +2 -0
- package/web-dist/assets/{Select-YFnt2Br2.js.map → Select-DHRR7IAK.js.map} +1 -1
- package/web-dist/assets/{Switch-DHX-YYPr.js → Switch-D5pVfZgf.js} +2 -2
- package/web-dist/assets/{Switch-DHX-YYPr.js.map → Switch-D5pVfZgf.js.map} +1 -1
- package/web-dist/assets/Tabs-2GilVMsH.js +2 -0
- package/web-dist/assets/{Tabs-DrFCe494.js.map → Tabs-2GilVMsH.js.map} +1 -1
- package/web-dist/assets/{TextLink-CCc3WEdm.js → TextLink-BGtYWCW9.js} +2 -2
- package/web-dist/assets/{TextLink-CCc3WEdm.js.map → TextLink-BGtYWCW9.js.map} +1 -1
- package/web-dist/assets/{UINodeRenderer-BdvzPTz0.js → UINodeRenderer-BaANWHvJ.js} +3 -3
- package/web-dist/assets/{UINodeRenderer-BdvzPTz0.js.map → UINodeRenderer-BaANWHvJ.js.map} +1 -1
- package/web-dist/assets/UnfilteredNote-zVO8ajSi.js +2 -0
- package/web-dist/assets/{UnfilteredNote-C44Gi9gP.js.map → UnfilteredNote-zVO8ajSi.js.map} +1 -1
- package/web-dist/assets/ViewSelect-C9gNftWK.js +2 -0
- package/web-dist/assets/ViewSelect-C9gNftWK.js.map +1 -0
- package/web-dist/assets/api-DMrk4xwq.js +2 -0
- package/web-dist/assets/api-DMrk4xwq.js.map +1 -0
- package/web-dist/assets/{arrow-down-YwTzxo-r.js → arrow-down-Dn3KG_JI.js} +2 -2
- package/web-dist/assets/{arrow-down-YwTzxo-r.js.map → arrow-down-Dn3KG_JI.js.map} +1 -1
- package/web-dist/assets/{arrow-up-Bzh112dp.js → arrow-up-BiPtOqqy.js} +2 -2
- package/web-dist/assets/{arrow-up-Bzh112dp.js.map → arrow-up-BiPtOqqy.js.map} +1 -1
- package/web-dist/assets/attention-B9uawu1d.js +2 -0
- package/web-dist/assets/attention-B9uawu1d.js.map +1 -0
- package/web-dist/assets/automations-IX9DQNk8.js +2 -0
- package/web-dist/assets/{automations-CkbEL-3K.js.map → automations-IX9DQNk8.js.map} +1 -1
- package/web-dist/assets/board-BUAI4L7M.js +6 -0
- package/web-dist/assets/{board-DRNTDqMF.js.map → board-BUAI4L7M.js.map} +1 -1
- package/web-dist/assets/{calendar-clock-CwOgyN2z.js → calendar-clock-DVlat602.js} +2 -2
- package/web-dist/assets/{calendar-clock-CwOgyN2z.js.map → calendar-clock-DVlat602.js.map} +1 -1
- package/web-dist/assets/check-CEnbWw4D.js +2 -0
- package/web-dist/assets/{check-DTN2VHtE.js.map → check-CEnbWw4D.js.map} +1 -1
- package/web-dist/assets/chevron-right-BM1IJI2z.js +2 -0
- package/web-dist/assets/{chevron-right-aaHL5Igi.js.map → chevron-right-BM1IJI2z.js.map} +1 -1
- package/web-dist/assets/code-Dav4E15n.js +25 -0
- package/web-dist/assets/code-Dav4E15n.js.map +1 -0
- package/web-dist/assets/{core.esm-C84Qlq9d.js → core.esm-C4dCvG0s.js} +2 -2
- package/web-dist/assets/{core.esm-C84Qlq9d.js.map → core.esm-C4dCvG0s.js.map} +1 -1
- package/web-dist/assets/describe-B66LJTqU.js +2 -0
- package/web-dist/assets/describe-B66LJTqU.js.map +1 -0
- package/web-dist/assets/{describe-Bt36Y0d7.js → describe-BeFxHr2Y.js} +3 -3
- package/web-dist/assets/{describe-Bt36Y0d7.js.map → describe-BeFxHr2Y.js.map} +1 -1
- package/web-dist/assets/enroll-GUEF5Uxu.js +2 -0
- package/web-dist/assets/{enroll--c9VSPgK.js.map → enroll-GUEF5Uxu.js.map} +1 -1
- package/web-dist/assets/{external-link-CI-Uzhfh.js → external-link-B3hnazCa.js} +2 -2
- package/web-dist/assets/{external-link-CI-Uzhfh.js.map → external-link-B3hnazCa.js.map} +1 -1
- package/web-dist/assets/{hand-HCdmhGph.js → hand-B6lvj014.js} +2 -2
- package/web-dist/assets/{hand-HCdmhGph.js.map → hand-B6lvj014.js.map} +1 -1
- package/web-dist/assets/index-BUZpNu-R.js +22 -0
- package/web-dist/assets/index-BUZpNu-R.js.map +1 -0
- package/web-dist/assets/index-C9iuCGwg.css +2 -0
- package/web-dist/assets/{keyboardLayers-DKHA_Gcs.js → keyboardLayers-BZOygMAH.js} +2 -2
- package/web-dist/assets/{keyboardLayers-DKHA_Gcs.js.map → keyboardLayers-BZOygMAH.js.map} +1 -1
- package/web-dist/assets/{link-2-D6l0YZ-8.js → link-2-CCq9WzMy.js} +2 -2
- package/web-dist/assets/{link-2-D6l0YZ-8.js.map → link-2-CCq9WzMy.js.map} +1 -1
- package/web-dist/assets/logic-BBQ4d1GC.js +4 -0
- package/web-dist/assets/logic-BBQ4d1GC.js.map +1 -0
- package/web-dist/assets/{logic-CzU-NdeO.js → logic-BnSIy9_P.js} +2 -2
- package/web-dist/assets/{logic-CzU-NdeO.js.map → logic-BnSIy9_P.js.map} +1 -1
- package/web-dist/assets/more-C1oPXLVM.js +2 -0
- package/web-dist/assets/{more-Dca-1nh1.js.map → more-C1oPXLVM.js.map} +1 -1
- package/web-dist/assets/{pencil-BtK08_f_.js → pencil-DeML-0z2.js} +2 -2
- package/web-dist/assets/{pencil-BtK08_f_.js.map → pencil-DeML-0z2.js.map} +1 -1
- package/web-dist/assets/{play-j138GLHB.js → play-NHO6U6cY.js} +2 -2
- package/web-dist/assets/{play-j138GLHB.js.map → play-NHO6U6cY.js.map} +1 -1
- package/web-dist/assets/{plus-D935l0Os.js → plus-C83uJhbf.js} +2 -2
- package/web-dist/assets/{plus-D935l0Os.js.map → plus-C83uJhbf.js.map} +1 -1
- package/web-dist/assets/policyLogic-DqKyFQEW.js +2 -0
- package/web-dist/assets/policyLogic-DqKyFQEW.js.map +1 -0
- package/web-dist/assets/{queue-CbFYHdtZ.js → queue-DWSd1kia.js} +2 -2
- package/web-dist/assets/{queue-CbFYHdtZ.js.map → queue-DWSd1kia.js.map} +1 -1
- package/web-dist/assets/repo-DRwGWCut.js +2 -0
- package/web-dist/assets/repo-DRwGWCut.js.map +1 -0
- package/web-dist/assets/{rotate-ccw-mfO3Crkq.js → rotate-ccw-BRrlVEAQ.js} +2 -2
- package/web-dist/assets/{rotate-ccw-mfO3Crkq.js.map → rotate-ccw-BRrlVEAQ.js.map} +1 -1
- package/web-dist/assets/{search-DdgUAUi7.js → search-C5H14z0D.js} +2 -2
- package/web-dist/assets/{search-DdgUAUi7.js.map → search-C5H14z0D.js.map} +1 -1
- package/web-dist/assets/settings-B0IbaTOd.js +12 -0
- package/web-dist/assets/settings-B0IbaTOd.js.map +1 -0
- package/web-dist/assets/{states-DM6omTC-.js → states-hyf_ATdQ.js} +4 -4
- package/web-dist/assets/states-hyf_ATdQ.js.map +1 -0
- package/web-dist/assets/{terminal-DKqo1lis.js → terminal-CATQN_17.js} +2 -2
- package/web-dist/assets/{terminal-DKqo1lis.js.map → terminal-CATQN_17.js.map} +1 -1
- package/web-dist/assets/terminal-login-BdkmJdOO.js +2 -0
- package/web-dist/assets/{terminal-login-CK1PXQq9.js.map → terminal-login-BdkmJdOO.js.map} +1 -1
- package/web-dist/assets/{timer-CDGYPIoD.js → timer-DFrvOKOy.js} +2 -2
- package/web-dist/assets/{timer-CDGYPIoD.js.map → timer-DFrvOKOy.js.map} +1 -1
- package/web-dist/assets/{useBreakpoint-kT0J1Dnk.js → useBreakpoint-BYCN9s8X.js} +2 -2
- package/web-dist/assets/{useBreakpoint-kT0J1Dnk.js.map → useBreakpoint-BYCN9s8X.js.map} +1 -1
- package/web-dist/assets/useNow-DXyC-YfE.js +2 -0
- package/web-dist/assets/{useNow-DOQOgv7k.js.map → useNow-DXyC-YfE.js.map} +1 -1
- package/web-dist/assets/{useResource-OCKiw9Xe.js → useResource-DYNGG9XS.js} +2 -2
- package/web-dist/assets/{useResource-OCKiw9Xe.js.map → useResource-DYNGG9XS.js.map} +1 -1
- package/web-dist/assets/workboard-BJCZsLp5.js +3 -0
- package/web-dist/assets/workboard-BJCZsLp5.js.map +1 -0
- package/web-dist/index.html +7 -8
- package/web-dist/sw.js +1 -1
- package/web-dist/sw.js.map +1 -1
- package/web-dist/assets/AutomationView-X-U6Fpm7.js +0 -2
- package/web-dist/assets/Button-BKQW9doW.js +0 -2
- package/web-dist/assets/Button-BKQW9doW.js.map +0 -1
- package/web-dist/assets/Copy-CdlOSzns.js +0 -2
- package/web-dist/assets/Copy-CdlOSzns.js.map +0 -1
- package/web-dist/assets/InteractionCard-CMLAH54x.js +0 -4
- package/web-dist/assets/InteractionCard-CMLAH54x.js.map +0 -1
- package/web-dist/assets/Select-YFnt2Br2.js +0 -2
- package/web-dist/assets/Tabs-DrFCe494.js +0 -2
- package/web-dist/assets/UnfilteredNote-C44Gi9gP.js +0 -2
- package/web-dist/assets/ViewSelect-Dr9Akgak.js +0 -2
- package/web-dist/assets/ViewSelect-Dr9Akgak.js.map +0 -1
- package/web-dist/assets/api-Dbc6zmlY.js +0 -2
- package/web-dist/assets/api-Dbc6zmlY.js.map +0 -1
- package/web-dist/assets/attention-BWVl_pfs.js +0 -2
- package/web-dist/assets/attention-BWVl_pfs.js.map +0 -1
- package/web-dist/assets/automations-CkbEL-3K.js +0 -2
- package/web-dist/assets/board-DRNTDqMF.js +0 -6
- package/web-dist/assets/check-DTN2VHtE.js +0 -2
- package/web-dist/assets/chevron-right-aaHL5Igi.js +0 -2
- package/web-dist/assets/code-0I1wn1N7.js +0 -25
- package/web-dist/assets/code-0I1wn1N7.js.map +0 -1
- package/web-dist/assets/enroll--c9VSPgK.js +0 -2
- package/web-dist/assets/index-9TW72kVM.css +0 -2
- package/web-dist/assets/index-C6YuwL8H.js +0 -17
- package/web-dist/assets/index-C6YuwL8H.js.map +0 -1
- package/web-dist/assets/more-Dca-1nh1.js +0 -2
- package/web-dist/assets/policyLogic-Bs-3OIqh.js +0 -2
- package/web-dist/assets/policyLogic-Bs-3OIqh.js.map +0 -1
- package/web-dist/assets/repo-BB50Kdri.js +0 -2
- package/web-dist/assets/repo-BB50Kdri.js.map +0 -1
- package/web-dist/assets/selection-QGVHfoxz.js +0 -7
- package/web-dist/assets/selection-QGVHfoxz.js.map +0 -1
- package/web-dist/assets/settings-BvUmCxtY.js +0 -12
- package/web-dist/assets/settings-BvUmCxtY.js.map +0 -1
- package/web-dist/assets/states-DM6omTC-.js.map +0 -1
- package/web-dist/assets/terminal-login-CK1PXQq9.js +0 -2
- package/web-dist/assets/trackers-BIhLByAc.js +0 -2
- package/web-dist/assets/trackers-BIhLByAc.js.map +0 -1
- package/web-dist/assets/useNow-DOQOgv7k.js +0 -2
- package/web-dist/assets/workboard-C0XpNo0s.js +0 -3
- package/web-dist/assets/workboard-C0XpNo0s.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logic-BBQ4d1GC.js","names":["useState","_Fragment","useRef","useMemo","useState","useState","useMemo","useRef","useCallback","_Fragment","useState","useMemo","_Fragment","__toESM","useNavigate","cn","require_jsx_runtime","Button","require_react","StatusChip","useSyncStore","isInputAttentionReason","errorMessage","issueLinkProblem","apiDelete","primarySession","ErrorState","isApiError","issueLookup","formatTime","apiPost","compareIssues","issueUnlinkProblem","ArrowUp","toast","useBreakpoint","Field","UINodeRenderer","automationControl","runForSession","TextInput","IconButton","hostLink","isLive","isBusy","TextArea","Sheet","ConfirmDialog","contextMeter","Dialog","TextLink","headingSlug","Markdown","unlinkIssue","linkIssue","codeApi","import_react","UNSUPPORTED_COPY","DEFAULT_ACTIONS","findActions","node","c","found","isUnsupported","i","unsupportedView","offered","a","messageMode","runtime","import_jsx_runtime","hasInteractive","t","byLabel","by","InteractionCard","fromProps","upsert","s","busy","setBusy","error","setError","alreadyAnswered","setAlreadyAnswered","lastResponse","setLastResponse","acked","setAcked","interaction","pending","unsupported","sessionRuntime","composing","setComposing","message","setMessage","respond","response","res","onAnswered","other","sendMessage","text","bp","isDocumentPresentation","DocumentInteraction","r","readOnlyReason","sticky","flush","className","UnsupportedBody","actionId","formatRelative","view","answered","onSend","onCancelMessage","onAction","splitPresentation","last","rest","scrollTo","calm","el","useOnScreen","visible","setVisible","ref","io","firstMarkdown","m","md","leadingHeading","documentSections","out","fence","line","useActiveSection","active","setActive","pinned","setPinned","key","ids","els","root","e","entries","release","shown","h","bodyRef","startRef","optionsRef","optionsVisible","sheet","setSheet","split","heading","sections","pinSection","options","changes","question","title","answer","onRespond","variant","tone","showBar","disabled","wrapBtn","jump","mobile","o","useIssueLink","issues","list","linked","workspace","LinkIssueDialog","close","onClose","pick","issue","candidates","NO_ADAPTERS","useSessionLookup","absent","hydrated","sessionId","session","result","setResult","ctrl","useSessionContext","host","project","runs","tasks","adapters","run","taskId","useMutation","fnRef","fn","optsRef","opts","mounted","args","msg","success","useNow","now","setNow","ms","useElementWidth","width","setWidth","ro","entry","InfoRow","label","value","SessionInfoDialog","meter","stats","hostLabel","useSessionActions","ctx","navigate","dialog","setDialog","setTitle","link","attention","st","inputAttention","isPrimary","peers","x","takeover","ret","stop","resume","rename","cacheAlert","archive","unarchive","connected","archiveBlocked","dialogs","ok","control","dismissAttentionItem","path","viewId","primary","item","next","ATTENTION_GROUPS","groupAttention","items","ATTENTION_ACTION_HELP","normalizeShow","v","visibleAttention","show","all","attentionMeta","task"],"sources":["../../src/components/intent/unsupported.ts","../../src/components/intent/InteractionCard.tsx","../../src/features/workboard/LinkIssue.tsx","../../src/features/code/hooks.ts","../../src/features/code/SessionInfoDialog.tsx","../../src/features/code/SessionActions.tsx","../../src/features/attention/logic.ts"],"sourcesContent":["import type { Interaction, UINode } from \"@switchyard/protocol\";\n\n/** What actually happened when an extension opened a terminal-only `ctx.ui.custom()` dialog. */\nexport const UNSUPPORTED_COPY =\n \"An extension opened a terminal-only dialog. In RPC mode Pi gave it no answer, so the extension continued without one.\";\n\nexport interface UnsupportedAction {\n id: \"abort\" | \"message\";\n label: string;\n tone: \"primary\" | \"secondary\" | \"danger\";\n}\n\nconst DEFAULT_ACTIONS: UnsupportedAction[] = [\n { id: \"abort\", label: \"Stop the run\", tone: \"danger\" },\n { id: \"message\", label: \"Send a message to Pi\", tone: \"primary\" },\n];\n\nfunction findActions(node: UINode): Extract<UINode, { t: \"actions\" }> | null {\n if (node.t === \"actions\") return node;\n if (node.t === \"section\") {\n for (const c of node.children) {\n const found = findActions(c);\n if (found) return found;\n }\n }\n return null;\n}\n\nexport interface UnsupportedView {\n /** True until a person chose one of the alternatives. */\n answerable: boolean;\n actions: UnsupportedAction[];\n copy: string;\n}\n\nexport function isUnsupported(i: Interaction): boolean {\n return i.state === \"unsupported\" || i.source.kind === \"unsupported_custom\";\n}\n\n/** The alternatives the host offers for an unsupported dialog (stop the run, message). */\nexport function unsupportedView(i: Interaction): UnsupportedView {\n const node = findActions(i.presentation);\n const offered = (node?.actions ?? [])\n .filter(\n (a): a is typeof a & { id: \"abort\" | \"message\" } => a.id === \"abort\" || a.id === \"message\",\n )\n .map((a) => ({\n id: a.id,\n label: a.label,\n tone: (a.tone === \"default\"\n ? \"secondary\"\n : (a.tone ?? (a.id === \"abort\" ? \"danger\" : \"primary\"))) as UnsupportedAction[\"tone\"],\n }));\n return {\n answerable: i.state === \"unsupported\" && i.resolution === null,\n actions: offered.length > 0 ? offered : DEFAULT_ACTIONS,\n copy: UNSUPPORTED_COPY,\n };\n}\n\n/** A follow-up while Pi is still working queues behind the current turn. */\nexport function messageMode(runtime: string | undefined): \"prompt\" | \"followUp\" {\n return runtime === \"running\" || runtime === \"waiting_input\" ? \"followUp\" : \"prompt\";\n}\n","import type { Interaction, InteractionResponse, UINode } from \"@switchyard/protocol\";\nimport { ArrowUp } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useBreakpoint } from \"../../app/useBreakpoint\";\nimport { cn } from \"../../lib/cn\";\nimport { formatRelative } from \"../../lib/time\";\nimport { apiPost, errorMessage, isApiError } from \"../../sync/api\";\nimport { useSyncStore } from \"../../sync/store\";\nimport { Button } from \"../ui/Button\";\nimport { IconButton } from \"../ui/IconButton\";\nimport { Sheet } from \"../ui/Overlay\";\nimport { StatusChip } from \"../ui/StatusChip\";\nimport { ErrorState } from \"../ui/states\";\nimport { TextArea } from \"../ui/TextArea\";\nimport { TextLink } from \"../ui/TextLink\";\nimport { headingSlug, Markdown } from \"./Markdown\";\nimport { UINodeRenderer } from \"./UINodeRenderer\";\nimport { isUnsupported, messageMode, unsupportedView } from \"./unsupported\";\n\nexport interface InteractionCardProps {\n interaction: Interaction;\n /** Read-only session or host offline: show the question without answer controls. */\n readOnlyReason?: string | null;\n className?: string;\n /** Called after the coordinator acknowledged an answer. */\n onAnswered?: (interaction: Interaction) => void;\n /** DOM id (the \"Needs input\" strip scrolls to it). */\n id?: string;\n /** Stick the document header to the top of its scroller (false when the page scrolls). */\n sticky?: boolean;\n /** The page itself scrolls (no padded scroller): pin the header and bar flush. */\n flush?: boolean;\n}\n\nfunction hasInteractive(node: UINode): boolean {\n switch (node.t) {\n case \"form\":\n case \"confirm\":\n case \"actions\":\n return true;\n case \"list\":\n return node.items.some(hasInteractive);\n case \"section\":\n return node.children.some(hasInteractive);\n case \"tabs\":\n return node.tabs.some((t) => t.children.some(hasInteractive));\n default:\n return false;\n }\n}\n\nfunction byLabel(by: string): string {\n if (by === \"host\") return \"the host\";\n if (by === \"pi\") return \"Pi\";\n return \"a device\";\n}\n\n/**\n * A runtime interaction (extension dialog). Posts the answer with the\n * interaction revision and waits for the acknowledgement; there is no\n * optimistic resolution. A 409 shows \"Already answered: <summary>\".\n */\nexport function InteractionCard({\n interaction: fromProps,\n readOnlyReason,\n className,\n onAnswered,\n id,\n sticky,\n flush,\n}: InteractionCardProps) {\n const upsert = useSyncStore((s) => s.upsertInteraction);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<unknown>(null);\n const [alreadyAnswered, setAlreadyAnswered] = useState<string | null>(null);\n const [lastResponse, setLastResponse] = useState<InteractionResponse | null>(null);\n // The acknowledged interaction from the answer/409 response, until the prop catches up.\n const [acked, setAcked] = useState<Interaction | null>(null);\n const interaction =\n acked && acked.id === fromProps.id && acked.revision > fromProps.revision ? acked : fromProps;\n\n const pending = interaction.state === \"pending\";\n const unsupported = isUnsupported(interaction);\n const sessionRuntime = useSyncStore((s) => s.sessions[interaction.sessionId]?.runtime);\n const [composing, setComposing] = useState(false);\n const [message, setMessage] = useState(\"\");\n\n const respond = async (response: InteractionResponse): Promise<boolean> => {\n setBusy(true);\n setError(null);\n setLastResponse(response);\n try {\n const res = await apiPost<{ status: string; interaction: Interaction }>(\n `/api/interactions/${encodeURIComponent(interaction.id)}/answer`,\n { revision: interaction.revision, response },\n );\n if (res?.interaction) {\n upsert(res.interaction);\n setAcked(res.interaction);\n onAnswered?.(res.interaction);\n }\n return true;\n } catch (e) {\n if (isApiError(e, \"already_answered\")) {\n const other = (e.details as { interaction?: Interaction } | undefined)?.interaction;\n if (other) {\n upsert(other);\n setAcked(other);\n }\n setAlreadyAnswered(other?.resolution?.summary ?? \"answered on another device\");\n } else {\n setError(e);\n }\n return false;\n } finally {\n setBusy(false);\n }\n };\n\n /** \"Send a message to Pi\": deliver the message first, then record the choice. */\n const sendMessage = async () => {\n const text = message.trim();\n if (!text) return;\n setBusy(true);\n setError(null);\n try {\n await apiPost(`/api/sessions/${encodeURIComponent(interaction.sessionId)}/prompt`, {\n text,\n mode: messageMode(sessionRuntime),\n });\n } catch (e) {\n setError(e);\n setBusy(false);\n return;\n }\n setBusy(false);\n if (await respond({ kind: \"action\", actionId: \"message\" })) {\n setComposing(false);\n setMessage(\"\");\n }\n };\n\n const bp = useBreakpoint();\n if (\n pending &&\n !alreadyAnswered &&\n !unsupported &&\n isDocumentPresentation(interaction.presentation)\n ) {\n return (\n <DocumentInteraction\n id={id}\n interaction={interaction}\n node={interaction.presentation}\n onRespond={(r) => void respond(r)}\n busy={busy}\n disabled={!!readOnlyReason}\n mobile={bp === \"mobile\"}\n sticky={sticky ?? true}\n flush={flush ?? false}\n className={className}\n />\n );\n }\n\n return (\n <article\n id={id}\n aria-label={`Question: ${interaction.title}`}\n className={cn(\n \"flex min-w-0 flex-col gap-3 border-l-2 py-1 pl-3\",\n pending ? \"border-warning\" : \"border-border\",\n className,\n )}\n >\n <header className=\"flex min-w-0 flex-wrap items-start gap-2\">\n <h3 className=\"min-w-0 flex-1 text-sm font-semibold break-words\">{interaction.title}</h3>\n <StatusChip kind=\"interaction\" value={interaction.state} size=\"sm\" />\n </header>\n\n {alreadyAnswered && (\n <p role=\"status\" className=\"rounded-md bg-surface-2 px-3 py-2 text-sm\">\n Already answered: {alreadyAnswered}\n </p>\n )}\n\n {unsupported ? (\n <UnsupportedBody\n interaction={interaction}\n readOnlyReason={readOnlyReason ?? null}\n busy={busy}\n answered={alreadyAnswered !== null}\n composing={composing}\n message={message}\n setMessage={setMessage}\n onAction={(actionId) => {\n if (actionId === \"message\") setComposing(true);\n else void respond({ kind: \"action\", actionId });\n }}\n onSend={() => void sendMessage()}\n onCancelMessage={() => setComposing(false)}\n />\n ) : pending && !alreadyAnswered ? (\n <>\n {readOnlyReason && <p className=\"text-sm text-muted\">{readOnlyReason}</p>}\n <UINodeRenderer\n node={interaction.presentation}\n onRespond={(r) => void respond(r)}\n busy={busy}\n disabled={!!readOnlyReason}\n />\n {!readOnlyReason && !hasInteractive(interaction.presentation) && (\n <div>\n <Button busy={busy} onClick={() => void respond({ kind: \"cancel\" })}>\n Dismiss\n </Button>\n </div>\n )}\n {busy && (\n <p role=\"status\" className=\"text-sm text-muted\">\n Sending answer… waiting for the host to confirm.\n </p>\n )}\n </>\n ) : alreadyAnswered ? null : interaction.resolution ? (\n <p className=\"text-sm text-muted\">\n {interaction.state === \"resolved\" ? \"Answered\" : \"Closed\"} by{\" \"}\n {byLabel(interaction.resolution.by)} {formatRelative(interaction.resolution.at)}:{\" \"}\n <span className=\"text-text\">{interaction.resolution.summary}</span>\n </p>\n ) : (\n <p className=\"text-sm text-muted\">\n {interaction.state === \"expired\"\n ? \"This question expired before it was answered (Pi closed the dialog).\"\n : \"This question was canceled.\"}\n </p>\n )}\n\n {error !== null && (\n <ErrorState\n compact\n title=\"Answer not delivered\"\n error={errorMessage(error)}\n onRetry={lastResponse ? () => void respond(lastResponse) : undefined}\n />\n )}\n </article>\n );\n}\n\n/** A terminal-only dialog: what happened, and the alternatives the host offers until one is chosen. */\nfunction UnsupportedBody({\n interaction,\n readOnlyReason,\n busy,\n answered,\n composing,\n message,\n setMessage,\n onAction,\n onSend,\n onCancelMessage,\n}: {\n interaction: Interaction;\n readOnlyReason: string | null;\n busy: boolean;\n answered: boolean;\n composing: boolean;\n message: string;\n setMessage: (t: string) => void;\n onAction: (actionId: \"abort\" | \"message\") => void;\n onSend: () => void;\n onCancelMessage: () => void;\n}) {\n const view = unsupportedView(interaction);\n return (\n <div className=\"flex min-w-0 flex-col gap-2\">\n <p className=\"text-sm text-muted\">{view.copy}</p>\n {interaction.resolution ? (\n <p className=\"text-sm text-muted\">\n Chosen by {byLabel(interaction.resolution.by)} {formatRelative(interaction.resolution.at)}\n : <span className=\"text-text\">{interaction.resolution.summary}</span>\n </p>\n ) : !view.answerable || answered ? null : readOnlyReason ? (\n <p className=\"text-sm text-muted\">{readOnlyReason}</p>\n ) : composing ? (\n <div className=\"flex min-w-0 flex-col gap-2\">\n <TextArea\n aria-label=\"Message for Pi\"\n value={message}\n onChange={(e) => setMessage(e.target.value)}\n rows={3}\n autoFocus\n placeholder=\"Tell Pi what to do instead\"\n />\n <div className=\"flex flex-wrap gap-2\">\n <Button variant=\"primary\" busy={busy} disabled={!message.trim()} onClick={onSend}>\n Send message\n </Button>\n <Button disabled={busy} onClick={onCancelMessage}>\n Cancel\n </Button>\n </div>\n </div>\n ) : (\n <div className=\"flex flex-wrap gap-2\">\n {view.actions.map((a) => (\n <Button\n key={a.id}\n variant={a.tone}\n busy={busy && a.id === \"abort\"}\n disabled={busy}\n onClick={() => onAction(a.id)}\n >\n {a.label}\n </Button>\n ))}\n </div>\n )}\n </div>\n );\n}\n\n/** A content section that ends in a row of actions (a plan with its options), if `node` is one. */\nexport function splitPresentation(node: UINode): { body: UINode; actions: UINode } | null {\n if (node.t !== \"section\" || node.children.length < 2) return null;\n const last = node.children[node.children.length - 1];\n if (last?.t !== \"actions\") return null;\n const rest = node.children.slice(0, -1);\n if (rest.some(hasInteractive)) return null;\n return { body: { ...node, children: rest }, actions: last };\n}\n\nfunction scrollTo(el: HTMLElement | null, block: \"start\" | \"center\") {\n const calm = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches;\n el?.scrollIntoView({ behavior: calm ? \"auto\" : \"smooth\", block });\n}\n\n/** True while `el` is (at least partly) on screen; assumed visible without IntersectionObserver. */\nfunction useOnScreen(ref: React.RefObject<HTMLElement | null>): boolean {\n const [visible, setVisible] = useState(true);\n useEffect(() => {\n const el = ref.current;\n if (!el || typeof IntersectionObserver === \"undefined\") return;\n const io = new IntersectionObserver(([e]) => setVisible(!!e?.isIntersecting));\n io.observe(el);\n return () => io.disconnect();\n }, [ref]);\n return visible;\n}\n\nfunction firstMarkdown(node: UINode): string | null {\n if (node.t === \"markdown\") return node.text;\n if (node.t === \"section\") {\n for (const c of node.children) {\n const m = firstMarkdown(c);\n if (m !== null) return m;\n }\n }\n return null;\n}\n\n/** A long document with trailing options (a plan awaiting approval). */\nexport function isDocumentPresentation(node: UINode): boolean {\n if (!splitPresentation(node)) return false;\n const md = firstMarkdown(node);\n return md !== null && (md.length >= 400 || md.split(\"\\n\").length >= 12);\n}\n\n/** The first heading of a document, its text and the markdown without it. */\nexport function leadingHeading(md: string): { title: string | null; rest: string } {\n const m = /^\\s*#{1,6}\\s+(.+?)\\s*(?:\\n+|$)/.exec(md);\n return m?.[1] ? { title: m[1], rest: md.slice(m[0].length) } : { title: null, rest: md };\n}\n\n/** `##` headings of a document, for the outline. */\nexport function documentSections(md: string): { text: string; id: string }[] {\n const out: { text: string; id: string }[] = [];\n let fence = false;\n for (const line of md.split(\"\\n\")) {\n if (/^\\s*```/.test(line)) fence = !fence;\n const m = !fence ? /^##\\s+(.+?)\\s*$/.exec(line) : null;\n if (m?.[1]) out.push({ text: m[1], id: headingSlug(m[1]) });\n }\n return out;\n}\n\n/** Id of the outline entry whose heading is the last one scrolled past the top. */\nfunction useActiveSection(ids: string[], root: React.RefObject<HTMLElement | null>) {\n const [active, setActive] = useState<string | null>(null);\n const [pinned, setPinned] = useState<string | null>(null);\n const key = ids.join(\"|\");\n // biome-ignore lint/correctness/useExhaustiveDependencies: `key` stands for `ids`\n useEffect(() => {\n if (typeof IntersectionObserver === \"undefined\" || !ids.length) return;\n const els = ids\n .map((i) => root.current?.querySelector<HTMLElement>(`#${CSS.escape(i)}`))\n .filter((e): e is HTMLElement => !!e);\n const io = new IntersectionObserver(\n (entries) => {\n for (const e of entries) if (e.isIntersecting) setActive(e.target.id);\n },\n { rootMargin: \"-56px 0px -70% 0px\" },\n );\n for (const e of els) io.observe(e);\n // A click on an entry near the end cannot scroll it to the top: it stays selected until the\n // reader scrolls again.\n const release = () => setPinned(null);\n window.addEventListener(\"wheel\", release, { passive: true });\n window.addEventListener(\"touchmove\", release, { passive: true });\n window.addEventListener(\"keydown\", release);\n return () => {\n io.disconnect();\n window.removeEventListener(\"wheel\", release);\n window.removeEventListener(\"touchmove\", release);\n window.removeEventListener(\"keydown\", release);\n };\n }, [key, root]);\n const shown = pinned ?? active;\n // Mark the heading in the text that the outline highlights.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `key` stands for `ids`\n useEffect(() => {\n const r = root.current;\n if (!r) return;\n for (const h of r.querySelectorAll<HTMLElement>(\"h2[data-active]\")) delete h.dataset.active;\n if (shown) {\n const el = r.querySelector<HTMLElement>(`#${CSS.escape(shown)}`);\n if (el) el.dataset.active = \"true\";\n }\n }, [shown, key, root]);\n return [shown, setPinned] as const;\n}\n\n/**\n * Document question (a plan awaiting approval): no card of its own. The plan's own heading titles\n * it, the question labels the answers, revisions come first. Phone: compact header, prose, a bar\n * with the answers pinned to the bottom. Desktop: a section outline beside prose at a readable\n * measure, and a wrapping bar of answers. The bar hides while the inline options are on screen.\n */\nfunction DocumentInteraction({\n id,\n interaction,\n node,\n onRespond,\n busy,\n disabled,\n mobile,\n sticky,\n flush,\n className,\n}: {\n id?: string;\n interaction: Interaction;\n node: UINode;\n onRespond: (r: InteractionResponse) => void;\n busy: boolean;\n disabled: boolean;\n mobile: boolean;\n sticky: boolean;\n flush: boolean;\n className?: string;\n}) {\n const bodyRef = useRef<HTMLDivElement>(null);\n const startRef = useRef<HTMLDivElement>(null);\n const optionsRef = useRef<HTMLElement>(null);\n const optionsVisible = useOnScreen(optionsRef);\n const [sheet, setSheet] = useState(false);\n const split = splitPresentation(node);\n const md =\n split?.body.t === \"section\"\n ? (split.body.children.find((c) => c.t === \"markdown\") as\n | Extract<UINode, { t: \"markdown\" }>\n | undefined)\n : undefined;\n const { title: heading, rest } = leadingHeading(md?.text ?? \"\");\n const sections = documentSections(rest);\n const [active, pinSection] = useActiveSection(\n sections.map((s) => s.id),\n bodyRef,\n );\n if (split?.body.t !== \"section\") return null;\n const options = (split.actions as Extract<UINode, { t: \"actions\" }>).actions;\n const changes = split.body.children.find((c) => c.t === \"section\");\n const question = interaction.title;\n const title = heading ?? question;\n const answer = (actionId: string) => {\n setSheet(false);\n onRespond({ kind: \"action\", actionId });\n };\n const variant = (i: number, tone?: string) =>\n i === 0 || tone === \"primary\" ? \"primary\" : tone === \"danger\" ? \"danger\" : \"secondary\";\n const showBar = !disabled && !optionsVisible;\n const wrapBtn = \"h-auto! min-h-9 min-w-0 py-1.5 text-left leading-tight whitespace-normal!\";\n const jump = (el: HTMLElement | null) => scrollTo(el, \"start\");\n return (\n <article\n id={id}\n data-testid=\"document-interaction\"\n aria-label={`Question: ${question}`}\n className={cn(\n \"w-full min-w-0 self-stretch border-t border-border\",\n\n className,\n )}\n >\n <header\n className={cn(\n \"z-10 flex min-w-0 items-center gap-2 border-b border-border bg-bg px-4 py-2 md:px-6\",\n sticky && (flush ? \"md:sticky md:top-0\" : \"max-md:static md:sticky md:-top-3\"),\n )}\n >\n <h3 className=\"min-w-0 flex-1 truncate text-[15px] leading-snug font-semibold md:text-sm\">\n {title}\n </h3>\n {mobile && (\n <StatusChip\n kind=\"interaction\"\n value={interaction.state}\n size=\"sm\"\n className=\"[&>span]:sr-only\"\n />\n )}\n {!disabled && !optionsVisible && (\n <TextLink\n size=\"xs\"\n className=\"shrink-0\"\n onClick={() => scrollTo(optionsRef.current, \"center\")}\n >\n Jump to options ↓\n </TextLink>\n )}\n </header>\n {changes && (\n <aside className=\"mx-4 mt-3 rounded-md bg-warning-soft px-3 py-2 text-sm md:mx-6\">\n <UINodeRenderer node={changes} />\n </aside>\n )}\n <div className=\"px-4 py-4 md:grid md:grid-cols-[13rem_minmax(0,1fr)] 2xl:grid-cols-[15rem_minmax(0,1fr)] md:gap-8 md:px-6\">\n {sections.length > 0 && (\n <nav aria-label=\"Plan sections\" className=\"hidden md:block\">\n <ol className=\"sticky top-16 flex flex-col gap-0.5 border-l border-border text-sm\">\n <li>\n <button\n type=\"button\"\n className=\"-ml-px block w-full truncate border-l-2 border-transparent py-1 pl-3 text-left text-muted hover:text-text\"\n onClick={() => jump(startRef.current)}\n >\n Start\n </button>\n </li>\n {sections.map((s) => (\n <li key={s.id}>\n <button\n type=\"button\"\n aria-current={active === s.id}\n className=\"-ml-px block w-full truncate border-l-2 border-transparent py-1 pl-3 text-left text-muted hover:text-text aria-[current=true]:border-accent aria-[current=true]:text-text\"\n onClick={() => {\n pinSection(s.id);\n jump(\n bodyRef.current?.querySelector<HTMLElement>(`#${CSS.escape(s.id)}`) ?? null,\n );\n }}\n >\n {s.text}\n </button>\n </li>\n ))}\n </ol>\n </nav>\n )}\n <div ref={startRef} className=\"min-w-0 scroll-mt-14\">\n <div\n ref={bodyRef}\n className=\"sy-prose-compact max-w-[80ch] min-w-0 2xl:max-w-[100ch] min-[1800px]:text-base [&_h2]:scroll-mt-14\"\n >\n <Markdown text={rest} headingIds className=\"text-inherit\" />\n </div>\n </div>\n </div>\n <section\n ref={optionsRef}\n data-testid=\"plan-options\"\n aria-label={question}\n className=\"border-t border-border px-4 py-3 md:px-6\"\n >\n <p className=\"mb-2 text-sm font-medium\">{question}</p>\n {!disabled && (\n <div className=\"flex min-w-0 flex-col gap-2 md:flex-row md:flex-wrap\">\n {options.map((o, i) => (\n <Button\n key={o.id}\n variant={variant(i, o.tone)}\n size=\"md\"\n disabled={busy}\n className={cn(wrapBtn, \"md:text-center\")}\n onClick={() => answer(o.id)}\n >\n {o.label}\n </Button>\n ))}\n </div>\n )}\n <TextLink\n size=\"xs\"\n className=\"mt-2\"\n icon={<ArrowUp aria-hidden className=\"size-3.5\" />}\n onClick={() => jump(startRef.current)}\n >\n Back to the plan start\n </TextLink>\n </section>\n {showBar && (\n <div\n data-testid=\"answer-bar\"\n className={cn(\n \"z-10 flex min-w-0 items-center gap-2 border-t border-border bg-bg px-4 py-2 md:gap-3 md:px-6\",\n sticky && !flush ? \"sticky -bottom-3\" : \"sticky bottom-0\",\n )}\n >\n {mobile ? (\n <>\n <IconButton\n label=\"Plan start\"\n icon={<ArrowUp className=\"size-4\" />}\n variant=\"secondary\"\n onClick={() => jump(startRef.current)}\n />\n {options.length > 2 ? (\n <>\n <Button\n variant=\"primary\"\n disabled={busy}\n className={cn(wrapBtn, \"flex-1\")}\n onClick={() => answer(options[0]!.id)}\n >\n {options[0]!.label}\n </Button>\n <Button variant=\"secondary\" onClick={() => setSheet(true)}>\n More ({options.length - 1})\n </Button>\n </>\n ) : (\n options.map((o, i) => (\n <Button\n key={o.id}\n variant={variant(i, o.tone)}\n disabled={busy}\n className={cn(wrapBtn, \"flex-1\")}\n onClick={() => answer(o.id)}\n >\n {o.label}\n </Button>\n ))\n )}\n </>\n ) : (\n <>\n <span\n className=\"max-w-[16rem] min-w-0 shrink truncate text-sm font-medium\"\n title={question}\n >\n {question}\n </span>\n <div className=\"grid min-w-0 flex-1 grid-cols-[repeat(auto-fit,minmax(11rem,1fr))] gap-2\">\n {options.map((o, i) => (\n <Button\n key={o.id}\n variant={variant(i, o.tone)}\n disabled={busy}\n className={cn(wrapBtn, \"w-full md:text-center\")}\n onClick={() => answer(o.id)}\n >\n {o.label}\n </Button>\n ))}\n </div>\n <IconButton\n label=\"Plan start\"\n icon={<ArrowUp className=\"size-4\" />}\n variant=\"secondary\"\n size=\"sm\"\n onClick={() => jump(startRef.current)}\n />\n </>\n )}\n </div>\n )}\n <Sheet open={sheet} onClose={() => setSheet(false)} title={question}>\n <div className=\"flex flex-col gap-2\">\n {options.map((o, i) => (\n <Button\n key={o.id}\n block\n variant={variant(i, o.tone)}\n disabled={busy}\n className={wrapBtn}\n onClick={() => answer(o.id)}\n >\n {o.label}\n </Button>\n ))}\n </div>\n </Sheet>\n </article>\n );\n}\n","import {\n compareIssues,\n issueLinkProblem,\n issueLookup,\n issueUnlinkProblem,\n type TrackedIssue,\n type Workspace,\n} from \"@switchyard/protocol\";\nimport { useMemo, useState } from \"react\";\nimport { Button } from \"../../components/ui/Button\";\nimport { Dialog } from \"../../components/ui/Overlay\";\nimport { ErrorState } from \"../../components/ui/states\";\nimport { toast } from \"../../components/ui/Toast\";\nimport { errorMessage } from \"../../sync/api\";\nimport { useSyncStore } from \"../../sync/store\";\nimport { linkIssue } from \"./api\";\n\n/** A workspace's issue, the issues it could be linked to, and whether its link can be undone here. */\nexport function useIssueLink(workspace: Workspace | null | undefined): {\n linked: TrackedIssue | null;\n candidates: TrackedIssue[];\n canUnlink: boolean;\n} {\n const issues = useSyncStore((s) => s.issues);\n return useMemo(() => {\n const list = Object.values(issues);\n const linked = workspace ? issueLookup(list)(workspace) : null;\n const candidates =\n workspace && !linked\n ? list.filter((i) => issueLinkProblem(i, workspace, list) === null).sort(compareIssues)\n : [];\n return { linked, candidates, canUnlink: !!linked && issueUnlinkProblem(linked) === null };\n }, [issues, workspace]);\n}\n\n/** Pick a not-started issue to link a worktree's branch to. */\nexport function LinkIssueDialog({\n open,\n onClose,\n workspace,\n candidates,\n}: {\n open: boolean;\n onClose: () => void;\n workspace: Workspace;\n candidates: TrackedIssue[];\n}) {\n const [busy, setBusy] = useState<string | null>(null);\n const [error, setError] = useState<unknown>(null);\n const close = () => {\n setError(null);\n onClose();\n };\n const pick = async (issue: TrackedIssue) => {\n if (busy) return;\n setBusy(issue.id);\n setError(null);\n try {\n await linkIssue(issue.id, workspace.id);\n toast.success(`Linked to #${issue.number}`);\n close();\n } catch (e) {\n setError(e);\n } finally {\n setBusy(null);\n }\n };\n return (\n <Dialog\n open={open}\n onClose={close}\n title=\"Link to issue\"\n description={`Link ${workspace.branch} to an issue that has no branch yet. Its sessions then stay in the tracker's view.`}\n footer={<Button onClick={close}>Cancel</Button>}\n >\n <div className=\"flex min-w-0 flex-col gap-2\">\n {error !== null && (\n <ErrorState compact title=\"Could not link\" error={errorMessage(error)} />\n )}\n {candidates.length === 0 && (\n <p className=\"text-sm text-muted\">No issue without a branch in this project.</p>\n )}\n <ul className=\"flex min-w-0 flex-col gap-1\">\n {candidates.map((i) => (\n <li key={i.id} className=\"min-w-0\">\n <button\n type=\"button\"\n disabled={!!busy}\n aria-busy={busy === i.id}\n onClick={() => void pick(i)}\n className=\"tap flex w-full min-w-0 flex-col rounded-md px-2 py-1.5 text-left hover:bg-surface-2 disabled:opacity-55\"\n >\n <span className=\"truncate text-sm\">\n #{i.number} {i.title}\n </span>\n <span className=\"truncate text-xs text-muted\">\n {i.repository}\n {i.board?.priority ? ` · ${i.board.priority.name}` : \"\"}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </div>\n </Dialog>\n );\n}\n","import type {\n AdapterInfo,\n Host,\n Project,\n Run,\n Session,\n Task,\n Workspace,\n} from \"@switchyard/protocol\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport { toast } from \"../../components/ui/Toast\";\nimport { errorMessage, isApiError } from \"../../sync/api\";\nimport { useSyncStore } from \"../../sync/store\";\nimport { codeApi } from \"./api\";\nimport {\n type AutomationControl,\n automationControl,\n type HostLink,\n hostLink,\n runForSession,\n} from \"./model\";\n\nexport interface SessionContext {\n session: Session;\n host: Host | undefined;\n hostName: string;\n link: HostLink;\n project: Project | undefined;\n workspace: Workspace | undefined;\n run: Run | null;\n task: Task | undefined;\n control: AutomationControl;\n adapters: AdapterInfo[];\n}\n\nconst NO_ADAPTERS: AdapterInfo[] = [];\n\nexport type SessionLookup =\n | { state: \"idle\" }\n | { state: \"loading\" }\n | { state: \"missing\" }\n | { state: \"error\"; error: string };\n\n/**\n * A session the snapshot leaves out (archived) is fetched by id and kept in the sync store, so\n * its URL still opens after a reload and live events (Unarchive) update it.\n */\nexport function useSessionLookup(\n sessionId: string | null,\n session: Session | undefined,\n hydrated: boolean,\n): SessionLookup {\n const absent = hydrated && !!sessionId && !session;\n const [result, setResult] = useState<{ id: string; lookup: SessionLookup } | null>(null);\n useEffect(() => {\n if (!absent || !sessionId) return;\n const ctrl = new AbortController();\n setResult({ id: sessionId, lookup: { state: \"loading\" } });\n codeApi.get(sessionId, ctrl.signal).then(\n (s) => {\n useSyncStore.getState().upsertSessionIfMissing(s);\n setResult(null);\n },\n (e) => {\n if (ctrl.signal.aborted) return;\n setResult({\n id: sessionId,\n lookup: isApiError(e, \"not_found\")\n ? { state: \"missing\" }\n : { state: \"error\", error: errorMessage(e) },\n });\n },\n );\n return () => ctrl.abort();\n }, [absent, sessionId]);\n if (!absent) return { state: \"idle\" };\n return result?.id === sessionId ? result.lookup : { state: \"loading\" };\n}\n\n/** Everything the session views need about one session, from the store. */\nexport function useSessionContext(session: Session | undefined): SessionContext | null {\n const host = useSyncStore((s) => (session ? s.hosts[session.hostId] : undefined));\n const project = useSyncStore((s) =>\n session?.projectId ? s.projects[session.projectId] : undefined,\n );\n const workspace = useSyncStore((s) =>\n session?.workspaceId ? s.workspaces[session.workspaceId] : undefined,\n );\n const runs = useSyncStore((s) => s.runs);\n const tasks = useSyncStore((s) => s.tasks);\n const adapters = useSyncStore((s) =>\n session ? (s.adapters[session.hostId] ?? NO_ADAPTERS) : NO_ADAPTERS,\n );\n return useMemo(() => {\n if (!session) return null;\n const run = runForSession(runs, session);\n const taskId = session.taskId ?? run?.taskId ?? null;\n return {\n session,\n host,\n hostName: host?.name ?? \"Unknown host\",\n link: hostLink(host, session),\n project,\n workspace,\n run,\n task: taskId ? tasks[taskId] : undefined,\n control: automationControl(run),\n adapters,\n };\n }, [session, host, project, workspace, runs, tasks, adapters]);\n}\n\nexport interface Mutation<A extends unknown[]> {\n run: (...args: A) => Promise<boolean>;\n busy: boolean;\n error: unknown;\n reset: () => void;\n}\n\n/**\n * Wrap a REST mutation: busy state, error kept for inline display (with\n * retry), and a success toast only after the coordinator acknowledged.\n */\nexport function useMutation<A extends unknown[], R>(\n fn: (...args: A) => Promise<R>,\n opts: { success?: string | ((r: R) => string | null); errorToast?: boolean } = {},\n): Mutation<A> {\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<unknown>(null);\n const fnRef = useRef(fn);\n fnRef.current = fn;\n const optsRef = useRef(opts);\n optsRef.current = opts;\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n const run = useCallback(async (...args: A) => {\n setBusy(true);\n setError(null);\n try {\n const r = await fnRef.current(...args);\n const { success } = optsRef.current;\n const msg = typeof success === \"function\" ? success(r) : success;\n if (msg) toast.success(msg);\n return true;\n } catch (e) {\n if (mounted.current) setError(e);\n if (optsRef.current.errorToast) toast.error(errorMessage(e));\n return false;\n } finally {\n if (mounted.current) setBusy(false);\n }\n }, []);\n const reset = useCallback(() => setError(null), []);\n return { run, busy, error, reset };\n}\n\n/** Re-render every `ms` while `active` (elapsed timers). */\nexport function useNow(active: boolean, ms = 1000): number {\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (!active) return;\n setNow(Date.now());\n const t = setInterval(() => setNow(Date.now()), ms);\n return () => clearInterval(t);\n }, [active, ms]);\n return now;\n}\n\n/** Width of an element, kept current with a ResizeObserver. */\nexport function useElementWidth<T extends HTMLElement>() {\n const ref = useRef<T>(null);\n const [width, setWidth] = useState(0);\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n setWidth(el.clientWidth);\n const ro = new ResizeObserver(([entry]) => {\n if (entry) setWidth(entry.contentRect.width);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width] as const;\n}\n","import type { Session } from \"@switchyard/protocol\";\nimport { Dialog } from \"../../components/ui/Overlay\";\nimport { formatTime } from \"../../lib/time\";\nimport { contextMeter } from \"./model\";\n\nfunction InfoRow({ label, value }: { label: string; value: string }) {\n return (\n <>\n <dt className=\"text-muted\">{label}</dt>\n <dd className=\"min-w-0 font-mono text-xs break-all\">{value}</dd>\n </>\n );\n}\n\nexport interface SessionInfoDialogProps {\n session: Session;\n hostLabel: string;\n open: boolean;\n onClose: () => void;\n}\n\n/** Session ids, Pi session file, tokens, cost and context. */\nexport function SessionInfoDialog({ session, hostLabel, open, onClose }: SessionInfoDialogProps) {\n const meter = contextMeter(session);\n const stats = session.stats;\n return (\n <Dialog open={open} onClose={onClose} title=\"Session info\">\n <dl className=\"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-2 text-sm\">\n <InfoRow label=\"Switchyard session\" value={session.id} />\n <InfoRow label=\"Pi session id\" value={session.nativeHandle?.sessionId ?? \"Not started\"} />\n <InfoRow label=\"Session file\" value={session.nativeHandle?.sessionFile ?? \"None yet\"} />\n <InfoRow label=\"Host\" value={hostLabel} />\n <InfoRow label=\"Working directory\" value={session.cwd} />\n <InfoRow label=\"Origin\" value={session.provenance} />\n <InfoRow label=\"Profile\" value={session.profileSnapshot.name} />\n <InfoRow label=\"Created\" value={formatTime(session.createdAt)} />\n {stats?.tokens != null && (\n <InfoRow label=\"Tokens\" value={stats.tokens.toLocaleString(\"en-US\")} />\n )}\n {stats?.costUsd != null && <InfoRow label=\"Cost\" value={`$${stats.costUsd.toFixed(2)}`} />}\n {meter && <InfoRow label=\"Context\" value={`${meter.label} (${meter.detail})`} />}\n </dl>\n </Dialog>\n );\n}\n","import {\n type AttentionItem,\n isInputAttentionReason,\n primarySession,\n type TrackedIssue,\n} from \"@switchyard/protocol\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport { useNavigate } from \"react-router\";\nimport { Button } from \"../../components/ui/Button\";\nimport { Field } from \"../../components/ui/Field\";\nimport { ConfirmDialog, Dialog } from \"../../components/ui/Overlay\";\nimport { ErrorState } from \"../../components/ui/states\";\nimport { TextInput } from \"../../components/ui/TextArea\";\nimport { toast } from \"../../components/ui/Toast\";\nimport { apiDelete, apiPost, errorMessage } from \"../../sync/api\";\nimport { useSyncStore } from \"../../sync/store\";\nimport { unlinkIssue } from \"../workboard/api\";\nimport { LinkIssueDialog, useIssueLink } from \"../workboard/LinkIssue\";\nimport { codeApi } from \"./api\";\nimport type { SessionContext } from \"./hooks\";\nimport { useMutation } from \"./hooks\";\nimport { isBusy, isLive } from \"./model\";\nimport { SessionInfoDialog } from \"./SessionInfoDialog\";\n\nexport interface SessionActions {\n canTakeover: boolean;\n canReturn: boolean;\n canStop: boolean;\n canResume: boolean;\n /** Why archive is unavailable, or null. */\n archiveBlocked: string | null;\n takeover: () => void;\n returnToAutomation: () => void;\n requestStop: () => void;\n resume: () => void;\n openRename: () => void;\n requestArchive: () => void;\n openInfo: () => void;\n toggleCacheAlert: () => void;\n unarchive: () => void;\n /** Clear this session's \"Needs input\" flag (its open input attention), or null when it has none. */\n dismissAttention: (() => void) | null;\n /** Pin the session to a view, or unpin it. */\n setPinned: (viewId: string, pinned: boolean) => void;\n /** This session is its branch's primary session. */\n isPrimary: boolean;\n setPrimary: (primary: boolean) => void;\n /** Start another session in this session's workspace, or null when it has none. */\n newInBranch: (() => void) | null;\n /** Link this worktree's branch to an issue, or undo it; null without a worktree. */\n issueLink: {\n linked: TrackedIssue | null;\n candidates: TrackedIssue[];\n canUnlink: boolean;\n open: () => void;\n unlink: () => void;\n } | null;\n busy: { takeover: boolean; ret: boolean; stop: boolean; resume: boolean; unarchive: boolean };\n /** Confirmation and form dialogs; render once in the view. */\n dialogs: ReactNode;\n}\n\n/** Session control and menu actions with confirmation dialogs (no optimistic success). */\nexport function useSessionActions(ctx: SessionContext): SessionActions {\n const { session, run, control } = ctx;\n const navigate = useNavigate();\n const [dialog, setDialog] = useState<null | \"stop\" | \"rename\" | \"archive\" | \"info\" | \"link\">(\n null,\n );\n const [title, setTitle] = useState(session.title);\n const link = useIssueLink(session.provenance === \"subagent\" ? null : ctx.workspace);\n const attention = useSyncStore((st) => st.attention);\n const inputAttention = useMemo(\n () =>\n Object.values(attention).filter(\n (a) => a.sessionId === session.id && !a.resolvedAt && isInputAttentionReason(a.reason),\n ),\n [attention, session.id],\n );\n const isPrimary = useSyncStore((st) => {\n if (session.provenance === \"subagent\" || session.archivedAt) return false;\n const peers = Object.values(st.sessions).filter(\n (x) =>\n x.archivedAt === null &&\n x.provenance !== \"subagent\" &&\n (session.workspaceId\n ? x.workspaceId === session.workspaceId\n : x.workspaceId === null && x.hostId === session.hostId && x.cwd === session.cwd),\n );\n return primarySession(peers)?.id === session.id;\n });\n\n const takeover = useMutation(() => codeApi.takeover(session.id), {\n success: \"You have control. Automatic continuations are paused.\",\n errorToast: true,\n });\n const ret = useMutation(() => codeApi.returnToAutomation(session.id), {\n success: \"Returned to automation.\",\n errorToast: true,\n });\n const stop = useMutation(() => codeApi.stop(session.id), { success: \"Session stopped.\" });\n const resume = useMutation(() => codeApi.resume(session.id), {\n success: \"Session resumed.\",\n errorToast: true,\n });\n const rename = useMutation((t: string) => codeApi.rename(session.id, t), {\n success: \"Session renamed.\",\n });\n const cacheAlert = useMutation(() => codeApi.cacheAlert(session.id, !session.cacheAlert), {\n errorToast: true,\n });\n const archive = useMutation(() => codeApi.archive(session.id), { success: \"Session archived.\" });\n const unarchive = useMutation(() => codeApi.unarchive(session.id), {\n success: \"Session unarchived.\",\n errorToast: true,\n });\n\n const connected = ctx.link === \"connected\";\n const close = () => {\n setDialog(null);\n stop.reset();\n rename.reset();\n archive.reset();\n };\n\n const archiveBlocked = isBusy(session) ? \"Stop the session before archiving it\" : null;\n\n const dialogs = (\n <>\n <ConfirmDialog\n open={dialog === \"stop\"}\n onClose={close}\n title=\"Stop this session?\"\n description=\"Stops the current execution and clears queued messages.\"\n confirmLabel=\"Stop session\"\n busy={stop.busy}\n error={stop.error}\n errorTitle=\"Could not stop\"\n onConfirm={() => void stop.run().then((ok) => ok && setDialog(null))}\n >\n <p className=\"text-sm text-muted\">\n {run\n ? \"The task keeps its run, marked interrupted and blocked (Stopped by user). Automation settings are unchanged.\"\n : \"Pi stays available; you can send a new message afterwards.\"}\n </p>\n </ConfirmDialog>\n\n <Dialog\n open={dialog === \"rename\"}\n onClose={close}\n title=\"Rename session\"\n footer={\n <>\n <Button onClick={close}>Cancel</Button>\n <Button\n variant=\"primary\"\n type=\"submit\"\n form=\"sy-rename-form\"\n busy={rename.busy}\n disabled={!title.trim()}\n >\n Save\n </Button>\n </>\n }\n >\n <form\n id=\"sy-rename-form\"\n onSubmit={(e) => {\n e.preventDefault();\n if (!title.trim()) return;\n void rename.run(title.trim()).then((ok) => ok && setDialog(null));\n }}\n className=\"flex flex-col gap-2\"\n >\n <Field id=\"sy-rename-input\" label=\"Title\">\n <TextInput\n id=\"sy-rename-input\"\n value={title}\n maxLength={200}\n onChange={(e) => setTitle(e.target.value)}\n />\n </Field>\n {rename.error !== null && (\n <ErrorState compact title=\"Could not rename\" error={errorMessage(rename.error)} />\n )}\n </form>\n </Dialog>\n\n <ConfirmDialog\n open={dialog === \"archive\"}\n onClose={close}\n title=\"Archive this session?\"\n description=\"It leaves the navigator. The Pi session file stays on the host.\"\n danger={false}\n confirmLabel=\"Archive\"\n busy={archive.busy}\n error={archive.error}\n errorTitle=\"Could not archive\"\n onConfirm={() =>\n void archive.run().then((ok) => {\n if (!ok) return;\n setDialog(null);\n navigate(\"/code\");\n })\n }\n >\n {session.runtime === \"idle\" && (\n <p className=\"text-sm text-muted\">The idle Pi process is stopped first.</p>\n )}\n </ConfirmDialog>\n\n {ctx.workspace && (\n <LinkIssueDialog\n open={dialog === \"link\"}\n onClose={close}\n workspace={ctx.workspace}\n candidates={link.candidates}\n />\n )}\n\n <SessionInfoDialog\n session={session}\n hostLabel={`${ctx.hostName} (${ctx.link})`}\n open={dialog === \"info\"}\n onClose={close}\n />\n </>\n );\n\n return {\n canTakeover: control === \"automation\",\n canReturn: control === \"human\",\n canStop: isBusy(session) && connected,\n canResume: !isLive(session) && !!session.nativeHandle && !session.readOnly && connected,\n archiveBlocked,\n takeover: () => void takeover.run(),\n returnToAutomation: () => void ret.run(),\n requestStop: () => setDialog(\"stop\"),\n resume: () => void resume.run(),\n openRename: () => {\n setTitle(session.title);\n setDialog(\"rename\");\n },\n requestArchive: () => {\n if (archiveBlocked) toast.info(archiveBlocked);\n else setDialog(\"archive\");\n },\n openInfo: () => setDialog(\"info\"),\n toggleCacheAlert: () => void cacheAlert.run(),\n unarchive: () => void unarchive.run(),\n dismissAttention:\n inputAttention.length > 0\n ? () => {\n void Promise.all(inputAttention.map(dismissAttentionItem))\n .then(() => toast.success(\"Cleared. A question Pi is still waiting on stays.\"))\n .catch((e) => toast.error(errorMessage(e)));\n }\n : null,\n setPinned: (viewId, pinned) => {\n const path = `/api/views/${encodeURIComponent(viewId)}/sessions/${encodeURIComponent(session.id)}`;\n void (pinned ? apiPost(path) : apiDelete(path)).catch((e) => toast.error(errorMessage(e)));\n },\n isPrimary,\n setPrimary: (primary) => {\n void codeApi.setPrimary(session.id, primary).catch((e) => toast.error(errorMessage(e)));\n },\n newInBranch:\n session.projectId && session.workspaceId\n ? () => {\n void codeApi\n .createSession({\n projectId: session.projectId!,\n workspace: { existingId: session.workspaceId! },\n prompt: \"\",\n })\n .then((s) => {\n useSyncStore.getState().upsertSessionIfMissing(s);\n navigate(`/code/${encodeURIComponent(s.id)}`);\n })\n .catch((e) => toast.error(errorMessage(e)));\n }\n : null,\n issueLink:\n ctx.workspace && session.provenance !== \"subagent\"\n ? {\n ...link,\n open: () => setDialog(\"link\"),\n unlink: () => {\n const i = link.linked;\n if (!i) return;\n void unlinkIssue(i.id)\n .then(() => toast.success(`Unlinked from #${i.number}`))\n .catch((e) => toast.error(errorMessage(e)));\n },\n }\n : null,\n busy: {\n takeover: takeover.busy,\n ret: ret.busy,\n stop: stop.busy,\n resume: resume.busy,\n unarchive: unarchive.busy,\n },\n dialogs,\n };\n}\n\n/** Resolve one attention item by hand and store the result. */\nexport async function dismissAttentionItem(item: AttentionItem): Promise<AttentionItem> {\n const res = await apiPost<AttentionItem>(`/api/attention/${encodeURIComponent(item.id)}/dismiss`);\n const next =\n res && typeof res === \"object\" && \"id\" in res\n ? res\n : { ...item, resolvedAt: new Date().toISOString() };\n useSyncStore.setState((st) =>\n st.attention[item.id] ? { attention: { ...st.attention, [item.id]: next } } : {},\n );\n return next;\n}\n","import type { AttentionItem, AttentionReason, Project, Session, Task } from \"@switchyard/protocol\";\n\nexport const ATTENTION_GROUPS: AttentionReason[] = [\n \"needs_input\",\n \"failed\",\n \"ready_for_review\",\n \"unsupported_interaction\",\n \"host_unreachable\",\n \"cache_expiring\",\n];\n\n/** Group open attention by reason, keeping the input order within a group. */\nexport function groupAttention(items: AttentionItem[]): Record<AttentionReason, AttentionItem[]> {\n const out = Object.fromEntries(ATTENTION_GROUPS.map((r) => [r, [] as AttentionItem[]])) as Record<\n AttentionReason,\n AttentionItem[]\n >;\n for (const a of items) out[a.reason]?.push(a);\n return out;\n}\n\n/** Tooltips and accessible descriptions of the attention actions: what each does and leaves. */\nexport const ATTENTION_ACTION_HELP = {\n dismiss:\n \"Marks it as seen and moves it to Dismissed; it stays open, and a question keeps flagging its session.\",\n clear: \"Resolves it now: the session loses this flag and the item moves to History.\",\n clearNeedsInput:\n \"Removes this session's Needs input flag and moves it to History; a question Pi is still waiting on stays.\",\n} as const;\n\nexport type AttentionShow = \"open\" | \"dismissed\" | \"history\";\n\n/** Stored prefs from before History: \"all\" (open + dismissed) and unknown values read as \"open\". */\nexport function normalizeShow(v: unknown): AttentionShow {\n return v === \"dismissed\" || v === \"history\" ? v : \"open\";\n}\n\n/** Unacknowledged items for \"open\", acknowledged for \"dismissed\"; [] for \"history\". */\nexport function visibleAttention(all: AttentionItem[], show: AttentionShow): AttentionItem[] {\n if (show === \"history\") return [];\n return all.filter((a) => (show === \"open\" ? !a.acknowledgedAt : !!a.acknowledgedAt));\n}\n\n/** \"project · task · session\" (session only when its title differs from the task's), else \"Switchyard\". */\nexport function attentionMeta(project?: Project, task?: Task, session?: Session): string {\n return (\n [project?.name, task?.title, session && session.title !== task?.title ? session.title : null]\n .filter(Boolean)\n .join(\" · \") || \"Switchyard\"\n );\n}\n"],"mappings":"A,muBAGayD,GACX,wHAQIC,GAAuC,CAC3C,CAAE,GAAI,QAAS,MAAO,eAAgB,KAAM,QAAS,EACrD,CAAE,GAAI,UAAW,MAAO,uBAAwB,KAAM,SAAU,CAClE,EAEA,SAASC,GAAY,EAAwD,CAC3E,GAAIC,EAAK,IAAM,UAAW,OAAOA,EACjC,GAAIA,EAAK,IAAM,UACb,IAAK,IAAMC,KAAKD,EAAK,SAAU,CAC7B,IAAME,EAAQH,GAAYE,CAAC,EAC3B,GAAIC,EAAO,OAAOA,CACpB,CAEF,OAAO,IACT,CASA,SAAgBC,GAAc,EAAyB,CACrD,OAAOC,EAAE,QAAU,eAAiBA,EAAE,OAAO,OAAS,oBACxD,CAGA,SAAgBC,GAAgB,EAAiC,CAE/D,IAAMC,GADOP,GAAYK,EAAE,YACV,CAAA,EAAM,SAAW,CAAC,EAAA,CAChC,OACE,GAAmDG,EAAE,KAAO,SAAWA,EAAE,KAAO,SACnF,CAAC,CACA,IAAK,IAAO,CACX,GAAIA,EAAE,GACN,MAAOA,EAAE,MACT,KAAOA,EAAE,OAAS,UACd,YACCA,EAAE,OAASA,EAAE,KAAO,QAAU,SAAW,UAChD,EAAE,EACJ,MAAO,CACL,WAAYH,EAAE,QAAU,eAAiBA,EAAE,aAAe,KAC1D,QAASE,EAAQ,OAAS,EAAIA,EAAUR,GACxC,KAAMD,EACR,CACF,CAGA,SAAgBW,GAAY,EAAoD,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t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function r(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function i(){return a.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var a={stubThis:e=>e};function o(e){let{id:t}=e;return{...e,id:r(t),transports:e.transports,type:e.type}}function s(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var c=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function l({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new c({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new c({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new c({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new c({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new c({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new c({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new c({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new c({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!s(t))return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new c({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new c({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new c({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var u=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},d=[`cross-platform`,`platform`];function f(e){if(e&&!(d.indexOf(e)<0))return e}async function p(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:a=!1}=e;if(!i())throw Error(`WebAuthn is not supported in this browser`);let s={...t,challenge:r(t.challenge),user:{...t.user,id:r(t.user.id)},excludeCredentials:t.excludeCredentials?.map(o)},c={};a&&(c.mediation=`conditional`),c.publicKey=s,c.signal=u.createNewAbortSignal();let d;try{d=await navigator.credentials.create(c)}catch(e){throw l({error:e,options:c})}if(!d)throw Error(`Registration was not completed`);let{id:p,rawId:h,response:g,type:_}=d,v;typeof g.getTransports==`function`&&(v=g.getTransports());let y;if(typeof g.getPublicKeyAlgorithm==`function`)try{y=g.getPublicKeyAlgorithm()}catch(e){m(`getPublicKeyAlgorithm()`,e)}let b;if(typeof g.getPublicKey==`function`)try{let e=g.getPublicKey();e!==null&&(b=n(e))}catch(e){m(`getPublicKey()`,e)}let x;if(typeof g.getAuthenticatorData==`function`)try{x=n(g.getAuthenticatorData())}catch(e){m(`getAuthenticatorData()`,e)}return{id:p,rawId:n(h),response:{attestationObject:n(g.attestationObject),clientDataJSON:n(g.clientDataJSON),transports:v,publicKeyAlgorithm:y,publicKey:b,authenticatorData:x},type:_,clientExtensionResults:d.getClientExtensionResults(),authenticatorAttachment:f(d.authenticatorAttachment)}}function m(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function h(){if(!i())return g.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?g.stubThis(new Promise(e=>e(!1))):g.stubThis(e.isConditionalMediationAvailable())}var g={stubThis:e=>e};function _({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new c({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new c({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!s(t))return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new c({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new c({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function v(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:a=!1,verifyBrowserAutofillInput:s=!0}=e;if(!i())throw Error(`WebAuthn is not supported in this browser`);let c;t.allowCredentials?.length!==0&&(c=t.allowCredentials?.map(o));let l={...t,challenge:r(t.challenge),allowCredentials:c},d={};if(a){if(!await h())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');d.mediation=`conditional`,l.allowCredentials=[]}d.publicKey=l,d.signal=u.createNewAbortSignal();let p;try{p=await navigator.credentials.get(d)}catch(e){throw _({error:e,options:d})}if(!p)throw Error(`Authentication was not completed`);let{id:m,rawId:g,response:v,type:y}=p,b;return v.userHandle&&(b=n(v.userHandle)),{id:m,rawId:n(g),response:{authenticatorData:n(v.authenticatorData),clientDataJSON:n(v.clientDataJSON),signature:n(v.signature),userHandle:b},type:y,clientExtensionResults:p.getClientExtensionResults(),authenticatorAttachment:f(p.authenticatorAttachment)}}var y=e(t(),1);function b(e){return e instanceof Error&&(e.name===`NotAllowedError`||e.name===`AbortError`)}function x(){let[e,t]=(0,y.useState)(!1),n=(0,y.useRef)(0),r=(0,y.useRef)(!1),i=(0,y.useCallback)(e=>{r.current=e,t(e)},[]),a=(0,y.useCallback)(()=>{n.current++,u.cancelCeremony(),r.current=!1,t(!1)},[]),o=(0,y.useCallback)(async e=>{let t=++n.current;i(!0);try{let r=await e();return n.current===t?(i(!1),{ok:!0,value:r}):{ok:!1,canceled:!0}}catch(e){if(n.current!==t||(i(!1),b(e)))return{ok:!1,canceled:!0};throw e}},[i]);return(0,y.useEffect)(()=>()=>{r.current&&(n.current++,u.cancelCeremony())},[]),{waiting:e,run:o,cancel:a}}var S=2e3;function C(e){return{phase:`waiting`,startedAt:e,message:null}}function w(e,t){if(e.phase!==`waiting`)return e;if(t.type===`cancel`)return{...e,phase:`canceled`};if(t.now-e.startedAt>=6e5&&t.type!==`claim`)return{...e,phase:`timeout`};switch(t.type){case`tick`:return e;case`claim`:return t.result.status===`done`?{...e,phase:`done`}:t.now-e.startedAt>=6e5?{...e,phase:`timeout`}:e;case`claim_error`:return t.code===`unauthorized`||t.code===`invalid_request`?{...e,phase:`failed`,message:t.message}:e}}function T(e,t){return e.phase===`waiting`&&t}var E=`This account is not allowed to sign in to this server.`,D={enrollment_expired:"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.",enrollment_used:"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.",invalid_request:`The sign-in request was rejected. Try again.`,network:`Could not reach the coordinator. Check your connection and try again.`,rate_limited:`Too many attempts. Wait a minute and try again.`,unsupported_capability:`This sign-in method is not available on this server.`,unauthorized:`That sign-in was not accepted. Try again, or use another sign-in method.`};function O(e,t){let n=t?.trim()||null;switch(e){case`forbidden`:return n??E;case`oidc_failed`:return`Single sign-on failed: ${n??`the identity provider returned an error.`}`;case`unsupported_capability`:return n??D.unsupported_capability;default:return D[e]??n??`Sign-in failed (${e}).`}}function k(e){switch(e){case`enrollment_expired`:return`Sign-in link expired`;case`enrollment_used`:return`Sign-in link already used`;case`forbidden`:return`Not allowed`;case`oidc_failed`:return`Single sign-on failed`;case`rate_limited`:return`Too many attempts`;default:return`Sign-in failed`}}function A(e=navigator.userAgent){let t=/iPhone/.test(e)?`iPhone`:/iPad/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1?`iPad`:/Android/.test(e)?`Android`:/Macintosh|Mac OS X/.test(e)?`Mac`:/Windows/.test(e)?`Windows`:/Linux/.test(e)?`Linux`:`device`;return`${/Edg\//.test(e)?`Edge`:/Firefox\/|FxiOS/.test(e)?`Firefox`:/Chrome\/|CriOS/.test(e)?`Chrome`:/Safari\//.test(e)?`Safari`:`Browser`} on ${t}`}export{k as a,C as c,p as d,i as f,O as i,x as l,S as n,w as o,A as r,T as s,D as t,v as u};
|
|
2
|
-
//# sourceMappingURL=logic-
|
|
1
|
+
import{S as e,y as t}from"./Button-C7TQGuSX.js";function n(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function r(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function i(){return a.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var a={stubThis:e=>e};function o(e){let{id:t}=e;return{...e,id:r(t),transports:e.transports,type:e.type}}function s(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var c=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function l({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new c({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new c({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new c({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new c({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new c({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new c({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new c({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new c({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!s(t))return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new c({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new c({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new c({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var u=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},d=[`cross-platform`,`platform`];function f(e){if(e&&!(d.indexOf(e)<0))return e}async function p(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:a=!1}=e;if(!i())throw Error(`WebAuthn is not supported in this browser`);let s={...t,challenge:r(t.challenge),user:{...t.user,id:r(t.user.id)},excludeCredentials:t.excludeCredentials?.map(o)},c={};a&&(c.mediation=`conditional`),c.publicKey=s,c.signal=u.createNewAbortSignal();let d;try{d=await navigator.credentials.create(c)}catch(e){throw l({error:e,options:c})}if(!d)throw Error(`Registration was not completed`);let{id:p,rawId:h,response:g,type:_}=d,v;typeof g.getTransports==`function`&&(v=g.getTransports());let y;if(typeof g.getPublicKeyAlgorithm==`function`)try{y=g.getPublicKeyAlgorithm()}catch(e){m(`getPublicKeyAlgorithm()`,e)}let b;if(typeof g.getPublicKey==`function`)try{let e=g.getPublicKey();e!==null&&(b=n(e))}catch(e){m(`getPublicKey()`,e)}let x;if(typeof g.getAuthenticatorData==`function`)try{x=n(g.getAuthenticatorData())}catch(e){m(`getAuthenticatorData()`,e)}return{id:p,rawId:n(h),response:{attestationObject:n(g.attestationObject),clientDataJSON:n(g.clientDataJSON),transports:v,publicKeyAlgorithm:y,publicKey:b,authenticatorData:x},type:_,clientExtensionResults:d.getClientExtensionResults(),authenticatorAttachment:f(d.authenticatorAttachment)}}function m(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function h(){if(!i())return g.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?g.stubThis(new Promise(e=>e(!1))):g.stubThis(e.isConditionalMediationAvailable())}var g={stubThis:e=>e};function _({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new c({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new c({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!s(t))return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new c({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new c({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function v(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:a=!1,verifyBrowserAutofillInput:s=!0}=e;if(!i())throw Error(`WebAuthn is not supported in this browser`);let c;t.allowCredentials?.length!==0&&(c=t.allowCredentials?.map(o));let l={...t,challenge:r(t.challenge),allowCredentials:c},d={};if(a){if(!await h())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');d.mediation=`conditional`,l.allowCredentials=[]}d.publicKey=l,d.signal=u.createNewAbortSignal();let p;try{p=await navigator.credentials.get(d)}catch(e){throw _({error:e,options:d})}if(!p)throw Error(`Authentication was not completed`);let{id:m,rawId:g,response:v,type:y}=p,b;return v.userHandle&&(b=n(v.userHandle)),{id:m,rawId:n(g),response:{authenticatorData:n(v.authenticatorData),clientDataJSON:n(v.clientDataJSON),signature:n(v.signature),userHandle:b},type:y,clientExtensionResults:p.getClientExtensionResults(),authenticatorAttachment:f(p.authenticatorAttachment)}}var y=e(t(),1);function b(e){return e instanceof Error&&(e.name===`NotAllowedError`||e.name===`AbortError`)}function x(){let[e,t]=(0,y.useState)(!1),n=(0,y.useRef)(0),r=(0,y.useRef)(!1),i=(0,y.useCallback)(e=>{r.current=e,t(e)},[]),a=(0,y.useCallback)(()=>{n.current++,u.cancelCeremony(),r.current=!1,t(!1)},[]),o=(0,y.useCallback)(async e=>{let t=++n.current;i(!0);try{let r=await e();return n.current===t?(i(!1),{ok:!0,value:r}):{ok:!1,canceled:!0}}catch(e){if(n.current!==t||(i(!1),b(e)))return{ok:!1,canceled:!0};throw e}},[i]);return(0,y.useEffect)(()=>()=>{r.current&&(n.current++,u.cancelCeremony())},[]),{waiting:e,run:o,cancel:a}}var S=2e3;function C(e){return{phase:`waiting`,startedAt:e,message:null}}function w(e,t){if(e.phase!==`waiting`)return e;if(t.type===`cancel`)return{...e,phase:`canceled`};if(t.now-e.startedAt>=6e5&&t.type!==`claim`)return{...e,phase:`timeout`};switch(t.type){case`tick`:return e;case`claim`:return t.result.status===`done`?{...e,phase:`done`}:t.now-e.startedAt>=6e5?{...e,phase:`timeout`}:e;case`claim_error`:return t.code===`unauthorized`||t.code===`invalid_request`?{...e,phase:`failed`,message:t.message}:e}}function T(e,t){return e.phase===`waiting`&&t}var E=`This account is not allowed to sign in to this server.`,D={enrollment_expired:"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.",enrollment_used:"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.",invalid_request:`The sign-in request was rejected. Try again.`,network:`Could not reach the coordinator. Check your connection and try again.`,rate_limited:`Too many attempts. Wait a minute and try again.`,unsupported_capability:`This sign-in method is not available on this server.`,unauthorized:`That sign-in was not accepted. Try again, or use another sign-in method.`};function O(e,t){let n=t?.trim()||null;switch(e){case`forbidden`:return n??E;case`oidc_failed`:return`Single sign-on failed: ${n??`the identity provider returned an error.`}`;case`unsupported_capability`:return n??D.unsupported_capability;default:return D[e]??n??`Sign-in failed (${e}).`}}function k(e){switch(e){case`enrollment_expired`:return`Sign-in link expired`;case`enrollment_used`:return`Sign-in link already used`;case`forbidden`:return`Not allowed`;case`oidc_failed`:return`Single sign-on failed`;case`rate_limited`:return`Too many attempts`;default:return`Sign-in failed`}}function A(e=navigator.userAgent){let t=/iPhone/.test(e)?`iPhone`:/iPad/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1?`iPad`:/Android/.test(e)?`Android`:/Macintosh|Mac OS X/.test(e)?`Mac`:/Windows/.test(e)?`Windows`:/Linux/.test(e)?`Linux`:`device`;return`${/Edg\//.test(e)?`Edge`:/Firefox\/|FxiOS/.test(e)?`Firefox`:/Chrome\/|CriOS/.test(e)?`Chrome`:/Safari\//.test(e)?`Safari`:`Browser`} on ${t}`}export{k as a,C as c,p as d,i as f,O as i,x as l,S as n,w as o,A as r,T as s,D as t,v as u};
|
|
2
|
+
//# sourceMappingURL=logic-BnSIy9_P.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logic-CzU-NdeO.js","names":["useState","useRef","useCallback","__toESM","require_react","bufferToBase64URLString","bytes","buffer","str","charCode","base64URLStringToBuffer","base64","base64URLString","padLength","padded","binary","i","browserSupportsWebAuthn","_browserSupportsWebAuthnInternals","value","toPublicKeyCredentialDescriptor","descriptor","id","isValidDomain","hostname","WebAuthnError","message","name","cause","code","identifyRegistrationError","options","publicKey","error","param","effectiveDomain","WebAuthnAbortService","abortError","newController","attachments","toAuthenticatorAttachment","attachment","startRegistration","optionsJSON","createOptions","useAutoRegister","credential","err","transports","response","responsePublicKeyAlgorithm","warnOnBrokenImplementation","responsePublicKey","_publicKey","responseAuthenticatorData","rawId","methodName","browserSupportsWebAuthnAutofill","_browserSupportsWebAuthnAutofillInternals","resolve","globalPublicKeyCredential","identifyAuthenticationError","startAuthentication","allowCredentials","getOptions","useBrowserAutofill","verifyBrowserAutofillInput","userHandle","import_react","isCanceledCeremony","usePasskeyCeremony","waiting","setWaiting","token","waitingRef","set","v","cancel","run","mine","fn","HANDOFF_POLL_MS","startHandoff","now","handoffReduce","state","event","shouldPoll","visible","GENERIC_FORBIDDEN","ERROR_TEXT","enrollErrorText","d","detail","enrollErrorTitle","defaultDeviceName","device","ua"],"sources":["../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/bufferToBase64URLString.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/base64URLStringToBuffer.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthn.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toPublicKeyCredentialDescriptor.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/isValidDomain.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyRegistrationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnAbortService.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toAuthenticatorAttachment.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startRegistration.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthnAutofill.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyAuthenticationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startAuthentication.js","../../src/app/passkeyCeremony.ts","../../src/features/enroll/logic.ts"],"sourcesContent":["/**\n * Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various\n * credential response ArrayBuffers to string for sending back to the server as JSON.\n *\n * Helper method to compliment `base64URLStringToBuffer`\n */\nexport function bufferToBase64URLString(buffer) {\n const bytes = new Uint8Array(buffer);\n let str = '';\n for (const charCode of bytes) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n return base64String.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n","/**\n * Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a\n * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or\n * excludeCredentials\n *\n * Helper method to compliment `bufferToBase64URLString`\n */\nexport function base64URLStringToBuffer(base64URLString) {\n // Convert from Base64URL to Base64\n const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');\n /**\n * Pad with '=' until it's a multiple of four\n * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding\n * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding\n * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding\n * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding\n */\n const padLength = (4 - (base64.length % 4)) % 4;\n const padded = base64.padEnd(base64.length + padLength, '=');\n // Convert to a binary string\n const binary = atob(padded);\n // Convert binary string to buffer\n const buffer = new ArrayBuffer(binary.length);\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * Determine if the browser is capable of Webauthn\n */\nexport function browserSupportsWebAuthn() {\n return _browserSupportsWebAuthnInternals.stubThis(globalThis?.PublicKeyCredential !== undefined &&\n typeof globalThis.PublicKeyCredential === 'function');\n}\n/**\n * Make it possible to stub the return value during testing\n * @ignore Don't include this in docs output\n */\nexport const _browserSupportsWebAuthnInternals = {\n stubThis: (value) => value,\n};\n","import { base64URLStringToBuffer } from './base64URLStringToBuffer.js';\nexport function toPublicKeyCredentialDescriptor(descriptor) {\n const { id } = descriptor;\n return {\n ...descriptor,\n id: base64URLStringToBuffer(id),\n transports: descriptor.transports,\n type: descriptor.type,\n };\n}\n","/**\n * A simple test to determine if a hostname is a properly-formatted domain name\n *\n * A \"valid domain\" is defined here: https://url.spec.whatwg.org/#valid-domain\n *\n * Regex was originally sourced from here, then remixed to add punycode support:\n * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html\n */\nexport function isValidDomain(hostname) {\n return (\n // Consider localhost valid as well since it's okay wrt Secure Contexts\n hostname === 'localhost' ||\n // Support punycode (ACE) or ascii labels and domains\n /^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(hostname));\n}\n","/**\n * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented\n * errors in the spec was raised after calling `navigator.credentials.create()` or\n * `navigator.credentials.get()`:\n *\n * - `AbortError`\n * - `ConstraintError`\n * - `InvalidStateError`\n * - `NotAllowedError`\n * - `NotSupportedError`\n * - `SecurityError`\n * - `TypeError`\n * - `UnknownError`\n *\n * Error messages were determined through investigation of the spec to determine under which\n * scenarios a given error would be raised.\n */\nexport class WebAuthnError extends Error {\n constructor({ message, code, cause, name, }) {\n // @ts-ignore: help Rollup understand that `cause` is okay to set\n super(message, { cause });\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = name ?? cause.name;\n this.code = code;\n }\n}\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`\n */\nexport function identifyRegistrationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Registration ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'ConstraintError') {\n if (publicKey.authenticatorSelection?.requireResidentKey === true) {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)\n return new WebAuthnError({\n message: 'Discoverable credentials were required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',\n cause: error,\n });\n }\n else if (\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n options.mediation === 'conditional' &&\n publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)\n return new WebAuthnError({\n message: 'User verification was required during automatic registration but it could not be performed',\n code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',\n cause: error,\n });\n }\n else if (publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)\n return new WebAuthnError({\n message: 'User verification was required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',\n cause: error,\n });\n }\n }\n else if (error.name === 'InvalidStateError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)\n return new WebAuthnError({\n message: 'The authenticator was previously registered',\n code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',\n cause: error,\n });\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'NotSupportedError') {\n const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');\n if (validPubKeyCredParams.length === 0) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)\n return new WebAuthnError({\n message: 'No entry in pubKeyCredParams was of type \"public-key\"',\n code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',\n cause: error,\n });\n }\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)\n return new WebAuthnError({\n message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',\n code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rp.id !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rp.id}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'TypeError') {\n if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)\n return new WebAuthnError({\n message: 'User ID was not between 1 and 64 characters',\n code: 'ERROR_INVALID_USER_ID_LENGTH',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new credential',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","class BaseWebAuthnAbortService {\n constructor() {\n Object.defineProperty(this, \"controller\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n createNewAbortSignal() {\n // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()\n if (this.controller) {\n const abortError = new Error('Cancelling existing WebAuthn API call for new one');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n }\n const newController = new AbortController();\n this.controller = newController;\n return newController.signal;\n }\n cancelCeremony() {\n if (this.controller) {\n const abortError = new Error('Manually cancelling existing WebAuthn API call');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n this.controller = undefined;\n }\n }\n}\n/**\n * A service singleton to help ensure that only a single WebAuthn ceremony is active at a time.\n *\n * Users of **@simplewebauthn/browser** shouldn't typically need to use this, but it can help e.g.\n * developers building projects that use client-side routing to better control the behavior of\n * their UX in response to router navigation events.\n */\nexport const WebAuthnAbortService = new BaseWebAuthnAbortService();\n","const attachments = ['cross-platform', 'platform'];\n/**\n * If possible coerce a `string` value into a known `AuthenticatorAttachment`\n */\nexport function toAuthenticatorAttachment(attachment) {\n if (!attachment) {\n return;\n }\n if (attachments.indexOf(attachment) < 0) {\n return;\n }\n return attachment;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyRegistrationError } from '../helpers/identifyRegistrationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"registration\" via WebAuthn attestation\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`\n * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.\n */\nexport async function startRegistration(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useAutoRegister = false } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n user: {\n ...optionsJSON.user,\n id: base64URLStringToBuffer(optionsJSON.user.id),\n },\n excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),\n };\n // Prepare options for `.create()`\n const createOptions = {};\n /**\n * Try to use conditional create to register a passkey for the user with the password manager\n * the user just used to authenticate with. The user won't be shown any prominent UI by the\n * browser.\n */\n if (useAutoRegister) {\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n createOptions.mediation = 'conditional';\n }\n // Finalize options\n createOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n createOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete attestation\n let credential;\n try {\n credential = (await navigator.credentials.create(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n createOptions));\n }\n catch (err) {\n throw identifyRegistrationError({ error: err, options: createOptions });\n }\n if (!credential) {\n throw new Error('Registration was not completed');\n }\n const { id, rawId, response, type } = credential;\n // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required\n let transports = undefined;\n if (typeof response.getTransports === 'function') {\n transports = response.getTransports();\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responsePublicKeyAlgorithm = undefined;\n if (typeof response.getPublicKeyAlgorithm === 'function') {\n try {\n responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);\n }\n }\n let responsePublicKey = undefined;\n if (typeof response.getPublicKey === 'function') {\n try {\n const _publicKey = response.getPublicKey();\n if (_publicKey !== null) {\n responsePublicKey = bufferToBase64URLString(_publicKey);\n }\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKey()', error);\n }\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responseAuthenticatorData;\n if (typeof response.getAuthenticatorData === 'function') {\n try {\n responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());\n }\n catch (error) {\n warnOnBrokenImplementation('getAuthenticatorData()', error);\n }\n }\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n attestationObject: bufferToBase64URLString(response.attestationObject),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n transports,\n publicKeyAlgorithm: responsePublicKeyAlgorithm,\n publicKey: responsePublicKey,\n authenticatorData: responseAuthenticatorData,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n/**\n * Visibly warn when we detect an issue related to a passkey provider intercepting WebAuthn API\n * calls\n */\nfunction warnOnBrokenImplementation(methodName, cause) {\n console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\\n`, cause);\n}\n","import { browserSupportsWebAuthn } from './browserSupportsWebAuthn.js';\n/**\n * Determine if the browser supports conditional UI, so that WebAuthn credentials can\n * be shown to the user in the browser's typical password autofill popup.\n */\nexport function browserSupportsWebAuthnAutofill() {\n if (!browserSupportsWebAuthn()) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n /**\n * I don't like the `as unknown` here but there's a `declare var PublicKeyCredential` in\n * TS' DOM lib that's making it difficult for me to just go `as PublicKeyCredentialFuture` as I\n * want. I think I'm fine with this for now since it's _supposed_ to be temporary, until TS types\n * have a chance to catch up.\n */\n const globalPublicKeyCredential = globalThis\n .PublicKeyCredential;\n if (globalPublicKeyCredential?.isConditionalMediationAvailable === undefined) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n return _browserSupportsWebAuthnAutofillInternals.stubThis(globalPublicKeyCredential.isConditionalMediationAvailable());\n}\n// Make it possible to stub the return value during testing\nexport const _browserSupportsWebAuthnAutofillInternals = {\n stubThis: (value) => value,\n};\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`\n */\nexport function identifyAuthenticationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Authentication ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rpId !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rpId}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { browserSupportsWebAuthnAutofill } from '../helpers/browserSupportsWebAuthnAutofill.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyAuthenticationError } from '../helpers/identifyAuthenticationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"login\" via WebAuthn assertion\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`\n * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.\n * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.\n */\nexport async function startAuthentication(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to avoid passing empty array to avoid blocking retrieval\n // of public key\n let allowCredentials;\n if (optionsJSON.allowCredentials?.length !== 0) {\n allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n allowCredentials,\n };\n // Prepare options for `.get()`\n const getOptions = {};\n /**\n * Set up the page to prompt the user to select a credential for authentication via the browser's\n * input autofill mechanism.\n */\n if (useBrowserAutofill) {\n if (!(await browserSupportsWebAuthnAutofill())) {\n throw Error('Browser does not support WebAuthn autofill');\n }\n // Check for an <input> with \"webauthn\" in its `autocomplete` attribute\n const eligibleInputs = document.querySelectorAll(\"input[autocomplete$='webauthn']\");\n // WebAuthn autofill requires at least one valid input\n if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {\n throw Error('No <input> with \"webauthn\" as the only or last value in its `autocomplete` attribute was detected');\n }\n // `CredentialMediationRequirement` doesn't know about \"conditional\" yet as of\n // typescript@4.6.3\n getOptions.mediation = 'conditional';\n // Conditional UI requires an empty allow list\n publicKey.allowCredentials = [];\n }\n // Finalize options\n getOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n getOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete assertion\n let credential;\n try {\n credential = (await navigator.credentials.get(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n getOptions));\n }\n catch (err) {\n throw identifyAuthenticationError({ error: err, options: getOptions });\n }\n if (!credential) {\n throw new Error('Authentication was not completed');\n }\n const { id, rawId, response, type } = credential;\n let userHandle = undefined;\n if (response.userHandle) {\n userHandle = bufferToBase64URLString(response.userHandle);\n }\n // Convert values to base64 to make it easier to send back to the server\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n authenticatorData: bufferToBase64URLString(response.authenticatorData),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n signature: bufferToBase64URLString(response.signature),\n userHandle,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n","import { WebAuthnAbortService } from \"@simplewebauthn/browser\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** A dismissed or aborted passkey prompt. */\nexport function isCanceledCeremony(err: unknown): boolean {\n return err instanceof Error && (err.name === \"NotAllowedError\" || err.name === \"AbortError\");\n}\n\n/**\n * Runs a WebAuthn ceremony the user can cancel at once. Some authenticator UIs never reject when\n * their popup closes, so Cancel does not wait for the browser: it resets and ignores the late result.\n */\nexport function usePasskeyCeremony() {\n const [waiting, setWaiting] = useState(false);\n const token = useRef(0);\n const waitingRef = useRef(false);\n\n const set = useCallback((v: boolean) => {\n waitingRef.current = v;\n setWaiting(v);\n }, []);\n\n const cancel = useCallback(() => {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n waitingRef.current = false;\n setWaiting(false);\n }, []);\n\n const run = useCallback(\n async <T>(\n fn: () => Promise<T>,\n ): Promise<{ ok: true; value: T } | { ok: false; canceled: true }> => {\n const mine = ++token.current;\n set(true);\n try {\n const value = await fn();\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n return { ok: true, value };\n } catch (err) {\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n if (isCanceledCeremony(err)) return { ok: false, canceled: true };\n throw err;\n }\n },\n [set],\n );\n\n useEffect(\n () => () => {\n if (waitingRef.current) {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n }\n },\n [],\n );\n\n return { waiting, run, cancel };\n}\n","import type { OidcClaimResponse } from \"@switchyard/protocol\";\n\n/** How often the PWA polls `POST /api/auth/oidc/claim` while the screen is visible. */\nexport const HANDOFF_POLL_MS = 2000;\n/** How long a handoff waits before giving up (the coordinator flow lives 10 minutes). */\nexport const HANDOFF_TIMEOUT_MS = 10 * 60 * 1000;\n\nexport type HandoffPhase = \"waiting\" | \"done\" | \"timeout\" | \"failed\" | \"canceled\";\n\nexport interface HandoffState {\n phase: HandoffPhase;\n startedAt: number;\n /** Set when `phase` is `failed`. */\n message: string | null;\n}\n\nexport type HandoffEvent =\n | { type: \"claim\"; result: OidcClaimResponse; now: number }\n | { type: \"claim_error\"; code: string; message: string; now: number }\n | { type: \"tick\"; now: number }\n | { type: \"cancel\" };\n\nexport function startHandoff(now: number): HandoffState {\n return { phase: \"waiting\", startedAt: now, message: null };\n}\n\n/**\n * Pure state machine for the PWA single sign-on handoff. Terminal phases\n * never change. A transient error (network, server hiccup) keeps waiting;\n * an expired or unknown flow (`unauthorized`, `invalid_request`) fails.\n */\nexport function handoffReduce(state: HandoffState, event: HandoffEvent): HandoffState {\n if (state.phase !== \"waiting\") return state;\n if (event.type === \"cancel\") return { ...state, phase: \"canceled\" };\n if (event.now - state.startedAt >= HANDOFF_TIMEOUT_MS && event.type !== \"claim\") {\n return { ...state, phase: \"timeout\" };\n }\n switch (event.type) {\n case \"tick\":\n return state;\n case \"claim\":\n if (event.result.status === \"done\") return { ...state, phase: \"done\" };\n return event.now - state.startedAt >= HANDOFF_TIMEOUT_MS\n ? { ...state, phase: \"timeout\" }\n : state;\n case \"claim_error\":\n if (event.code === \"unauthorized\" || event.code === \"invalid_request\") {\n return { ...state, phase: \"failed\", message: event.message };\n }\n return state;\n }\n}\n\n/** Whether a poll should run now: still waiting and the page is visible. */\nexport function shouldPoll(state: HandoffState, visible: boolean): boolean {\n return state.phase === \"waiting\" && visible;\n}\n\nconst GENERIC_FORBIDDEN = \"This account is not allowed to sign in to this server.\";\n\n/** Static texts for coordinator error codes shown on /sign-in. */\nexport const ERROR_TEXT: Record<string, string> = {\n enrollment_expired:\n \"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.\",\n enrollment_used:\n \"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.\",\n invalid_request: \"The sign-in request was rejected. Try again.\",\n network: \"Could not reach the coordinator. Check your connection and try again.\",\n rate_limited: \"Too many attempts. Wait a minute and try again.\",\n unsupported_capability: \"This sign-in method is not available on this server.\",\n unauthorized: \"That sign-in was not accepted. Try again, or use another sign-in method.\",\n};\n\n/**\n * Message for an error code, with the coordinator's `detail` where it is the\n * useful part (`/sign-in?error=forbidden&detail=Signed in as ...`).\n */\nexport function enrollErrorText(code: string, detail?: string | null): string {\n const d = detail?.trim() || null;\n switch (code) {\n case \"forbidden\":\n return d ?? GENERIC_FORBIDDEN;\n case \"oidc_failed\":\n return `Single sign-on failed: ${d ?? \"the identity provider returned an error.\"}`;\n case \"unsupported_capability\":\n return d ?? (ERROR_TEXT.unsupported_capability as string);\n default:\n return ERROR_TEXT[code] ?? d ?? `Sign-in failed (${code}).`;\n }\n}\n\n/** Short heading for an error alert. */\nexport function enrollErrorTitle(code: string): string {\n switch (code) {\n case \"enrollment_expired\":\n return \"Sign-in link expired\";\n case \"enrollment_used\":\n return \"Sign-in link already used\";\n case \"forbidden\":\n return \"Not allowed\";\n case \"oidc_failed\":\n return \"Single sign-on failed\";\n case \"rate_limited\":\n return \"Too many attempts\";\n default:\n return \"Sign-in failed\";\n }\n}\n\n/** A readable default device name from the user agent, e.g. \"Safari on iPhone\". */\nexport function defaultDeviceName(ua: string = navigator.userAgent): string {\n const device = /iPhone/.test(ua)\n ? \"iPhone\"\n : /iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)\n ? \"iPad\"\n : /Android/.test(ua)\n ? \"Android\"\n : /Macintosh|Mac OS X/.test(ua)\n ? \"Mac\"\n : /Windows/.test(ua)\n ? \"Windows\"\n : /Linux/.test(ua)\n ? \"Linux\"\n : \"device\";\n const browser = /Edg\\//.test(ua)\n ? \"Edge\"\n : /Firefox\\/|FxiOS/.test(ua)\n ? \"Firefox\"\n : /Chrome\\/|CriOS/.test(ua)\n ? \"Chrome\"\n : /Safari\\//.test(ua)\n ? \"Safari\"\n : \"Browser\";\n return `${browser} on ${device}`;\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12],"mappings":"A,gDAMA,SAAgBK,EAAwB,EAAQ,CAC5C,IAAMC,EAAQ,IAAI,WAAWC,CAAM,EAC/BC,EAAM,GACV,IAAK,IAAMC,KAAYH,EACnB,GAAO,OAAO,aAAaG,CAAQ,EAGvC,OADqB,KAAKD,CACR,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,KAAM,EAAE,CAChF,CCPA,SAAgBE,EAAwB,EAAiB,CAErD,IAAMC,EAASC,EAAgB,QAAQ,KAAM,GAAG,CAAC,CAAC,QAAQ,KAAM,GAAG,EAQ7DC,GAAa,EAAKF,EAAO,OAAS,GAAM,EACxCG,EAASH,EAAO,OAAOA,EAAO,OAASE,EAAW,GAAG,EAErDE,EAAS,KAAKD,CAAM,EAEpBP,EAAS,IAAI,YAAYQ,EAAO,MAAM,EACtCT,EAAQ,IAAI,WAAWC,CAAM,EACnC,IAAK,IAAIS,EAAI,EAAGA,EAAID,EAAO,OAAQ,IAC/B,EAAMC,GAAKD,EAAO,WAAWC,CAAC,EAElC,OAAOT,CACX,CCzBA,SAAgBU,GAA0B,CACtC,OAAOC,EAAkC,SAAS,YAAY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d,MAAO,GATS,QAAQ,KAAKA,CAAE,EAC3B,OACA,kBAAkB,KAAKA,CAAE,EACvB,UACA,iBAAiB,KAAKA,CAAE,EACtB,SACA,WAAW,KAAKA,CAAE,EAChB,SACA,UACQ,MAAMD,GAC1B,C"}
|
|
1
|
+
{"version":3,"file":"logic-BnSIy9_P.js","names":["useState","useRef","useCallback","__toESM","require_react","bufferToBase64URLString","bytes","buffer","str","charCode","base64URLStringToBuffer","base64","base64URLString","padLength","padded","binary","i","browserSupportsWebAuthn","_browserSupportsWebAuthnInternals","value","toPublicKeyCredentialDescriptor","descriptor","id","isValidDomain","hostname","WebAuthnError","message","name","cause","code","identifyRegistrationError","options","publicKey","error","param","effectiveDomain","WebAuthnAbortService","abortError","newController","attachments","toAuthenticatorAttachment","attachment","startRegistration","optionsJSON","createOptions","useAutoRegister","credential","err","transports","response","responsePublicKeyAlgorithm","warnOnBrokenImplementation","responsePublicKey","_publicKey","responseAuthenticatorData","rawId","methodName","browserSupportsWebAuthnAutofill","_browserSupportsWebAuthnAutofillInternals","resolve","globalPublicKeyCredential","identifyAuthenticationError","startAuthentication","allowCredentials","getOptions","useBrowserAutofill","verifyBrowserAutofillInput","userHandle","import_react","isCanceledCeremony","usePasskeyCeremony","waiting","setWaiting","token","waitingRef","set","v","cancel","run","mine","fn","HANDOFF_POLL_MS","startHandoff","now","handoffReduce","state","event","shouldPoll","visible","GENERIC_FORBIDDEN","ERROR_TEXT","enrollErrorText","d","detail","enrollErrorTitle","defaultDeviceName","device","ua"],"sources":["../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/bufferToBase64URLString.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/base64URLStringToBuffer.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthn.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toPublicKeyCredentialDescriptor.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/isValidDomain.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyRegistrationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnAbortService.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toAuthenticatorAttachment.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startRegistration.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthnAutofill.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyAuthenticationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startAuthentication.js","../../src/app/passkeyCeremony.ts","../../src/features/enroll/logic.ts"],"sourcesContent":["/**\n * Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various\n * credential response ArrayBuffers to string for sending back to the server as JSON.\n *\n * Helper method to compliment `base64URLStringToBuffer`\n */\nexport function bufferToBase64URLString(buffer) {\n const bytes = new Uint8Array(buffer);\n let str = '';\n for (const charCode of bytes) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n return base64String.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n","/**\n * Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a\n * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or\n * excludeCredentials\n *\n * Helper method to compliment `bufferToBase64URLString`\n */\nexport function base64URLStringToBuffer(base64URLString) {\n // Convert from Base64URL to Base64\n const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');\n /**\n * Pad with '=' until it's a multiple of four\n * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding\n * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding\n * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding\n * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding\n */\n const padLength = (4 - (base64.length % 4)) % 4;\n const padded = base64.padEnd(base64.length + padLength, '=');\n // Convert to a binary string\n const binary = atob(padded);\n // Convert binary string to buffer\n const buffer = new ArrayBuffer(binary.length);\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * Determine if the browser is capable of Webauthn\n */\nexport function browserSupportsWebAuthn() {\n return _browserSupportsWebAuthnInternals.stubThis(globalThis?.PublicKeyCredential !== undefined &&\n typeof globalThis.PublicKeyCredential === 'function');\n}\n/**\n * Make it possible to stub the return value during testing\n * @ignore Don't include this in docs output\n */\nexport const _browserSupportsWebAuthnInternals = {\n stubThis: (value) => value,\n};\n","import { base64URLStringToBuffer } from './base64URLStringToBuffer.js';\nexport function toPublicKeyCredentialDescriptor(descriptor) {\n const { id } = descriptor;\n return {\n ...descriptor,\n id: base64URLStringToBuffer(id),\n transports: descriptor.transports,\n type: descriptor.type,\n };\n}\n","/**\n * A simple test to determine if a hostname is a properly-formatted domain name\n *\n * A \"valid domain\" is defined here: https://url.spec.whatwg.org/#valid-domain\n *\n * Regex was originally sourced from here, then remixed to add punycode support:\n * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html\n */\nexport function isValidDomain(hostname) {\n return (\n // Consider localhost valid as well since it's okay wrt Secure Contexts\n hostname === 'localhost' ||\n // Support punycode (ACE) or ascii labels and domains\n /^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(hostname));\n}\n","/**\n * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented\n * errors in the spec was raised after calling `navigator.credentials.create()` or\n * `navigator.credentials.get()`:\n *\n * - `AbortError`\n * - `ConstraintError`\n * - `InvalidStateError`\n * - `NotAllowedError`\n * - `NotSupportedError`\n * - `SecurityError`\n * - `TypeError`\n * - `UnknownError`\n *\n * Error messages were determined through investigation of the spec to determine under which\n * scenarios a given error would be raised.\n */\nexport class WebAuthnError extends Error {\n constructor({ message, code, cause, name, }) {\n // @ts-ignore: help Rollup understand that `cause` is okay to set\n super(message, { cause });\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = name ?? cause.name;\n this.code = code;\n }\n}\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`\n */\nexport function identifyRegistrationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Registration ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'ConstraintError') {\n if (publicKey.authenticatorSelection?.requireResidentKey === true) {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)\n return new WebAuthnError({\n message: 'Discoverable credentials were required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',\n cause: error,\n });\n }\n else if (\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n options.mediation === 'conditional' &&\n publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)\n return new WebAuthnError({\n message: 'User verification was required during automatic registration but it could not be performed',\n code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',\n cause: error,\n });\n }\n else if (publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)\n return new WebAuthnError({\n message: 'User verification was required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',\n cause: error,\n });\n }\n }\n else if (error.name === 'InvalidStateError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)\n return new WebAuthnError({\n message: 'The authenticator was previously registered',\n code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',\n cause: error,\n });\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'NotSupportedError') {\n const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');\n if (validPubKeyCredParams.length === 0) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)\n return new WebAuthnError({\n message: 'No entry in pubKeyCredParams was of type \"public-key\"',\n code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',\n cause: error,\n });\n }\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)\n return new WebAuthnError({\n message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',\n code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rp.id !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rp.id}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'TypeError') {\n if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)\n return new WebAuthnError({\n message: 'User ID was not between 1 and 64 characters',\n code: 'ERROR_INVALID_USER_ID_LENGTH',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new credential',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","class BaseWebAuthnAbortService {\n constructor() {\n Object.defineProperty(this, \"controller\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n createNewAbortSignal() {\n // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()\n if (this.controller) {\n const abortError = new Error('Cancelling existing WebAuthn API call for new one');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n }\n const newController = new AbortController();\n this.controller = newController;\n return newController.signal;\n }\n cancelCeremony() {\n if (this.controller) {\n const abortError = new Error('Manually cancelling existing WebAuthn API call');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n this.controller = undefined;\n }\n }\n}\n/**\n * A service singleton to help ensure that only a single WebAuthn ceremony is active at a time.\n *\n * Users of **@simplewebauthn/browser** shouldn't typically need to use this, but it can help e.g.\n * developers building projects that use client-side routing to better control the behavior of\n * their UX in response to router navigation events.\n */\nexport const WebAuthnAbortService = new BaseWebAuthnAbortService();\n","const attachments = ['cross-platform', 'platform'];\n/**\n * If possible coerce a `string` value into a known `AuthenticatorAttachment`\n */\nexport function toAuthenticatorAttachment(attachment) {\n if (!attachment) {\n return;\n }\n if (attachments.indexOf(attachment) < 0) {\n return;\n }\n return attachment;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyRegistrationError } from '../helpers/identifyRegistrationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"registration\" via WebAuthn attestation\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`\n * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.\n */\nexport async function startRegistration(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useAutoRegister = false } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n user: {\n ...optionsJSON.user,\n id: base64URLStringToBuffer(optionsJSON.user.id),\n },\n excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),\n };\n // Prepare options for `.create()`\n const createOptions = {};\n /**\n * Try to use conditional create to register a passkey for the user with the password manager\n * the user just used to authenticate with. The user won't be shown any prominent UI by the\n * browser.\n */\n if (useAutoRegister) {\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n createOptions.mediation = 'conditional';\n }\n // Finalize options\n createOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n createOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete attestation\n let credential;\n try {\n credential = (await navigator.credentials.create(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n createOptions));\n }\n catch (err) {\n throw identifyRegistrationError({ error: err, options: createOptions });\n }\n if (!credential) {\n throw new Error('Registration was not completed');\n }\n const { id, rawId, response, type } = credential;\n // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required\n let transports = undefined;\n if (typeof response.getTransports === 'function') {\n transports = response.getTransports();\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responsePublicKeyAlgorithm = undefined;\n if (typeof response.getPublicKeyAlgorithm === 'function') {\n try {\n responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);\n }\n }\n let responsePublicKey = undefined;\n if (typeof response.getPublicKey === 'function') {\n try {\n const _publicKey = response.getPublicKey();\n if (_publicKey !== null) {\n responsePublicKey = bufferToBase64URLString(_publicKey);\n }\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKey()', error);\n }\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responseAuthenticatorData;\n if (typeof response.getAuthenticatorData === 'function') {\n try {\n responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());\n }\n catch (error) {\n warnOnBrokenImplementation('getAuthenticatorData()', error);\n }\n }\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n attestationObject: bufferToBase64URLString(response.attestationObject),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n transports,\n publicKeyAlgorithm: responsePublicKeyAlgorithm,\n publicKey: responsePublicKey,\n authenticatorData: responseAuthenticatorData,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n/**\n * Visibly warn when we detect an issue related to a passkey provider intercepting WebAuthn API\n * calls\n */\nfunction warnOnBrokenImplementation(methodName, cause) {\n console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\\n`, cause);\n}\n","import { browserSupportsWebAuthn } from './browserSupportsWebAuthn.js';\n/**\n * Determine if the browser supports conditional UI, so that WebAuthn credentials can\n * be shown to the user in the browser's typical password autofill popup.\n */\nexport function browserSupportsWebAuthnAutofill() {\n if (!browserSupportsWebAuthn()) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n /**\n * I don't like the `as unknown` here but there's a `declare var PublicKeyCredential` in\n * TS' DOM lib that's making it difficult for me to just go `as PublicKeyCredentialFuture` as I\n * want. I think I'm fine with this for now since it's _supposed_ to be temporary, until TS types\n * have a chance to catch up.\n */\n const globalPublicKeyCredential = globalThis\n .PublicKeyCredential;\n if (globalPublicKeyCredential?.isConditionalMediationAvailable === undefined) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n return _browserSupportsWebAuthnAutofillInternals.stubThis(globalPublicKeyCredential.isConditionalMediationAvailable());\n}\n// Make it possible to stub the return value during testing\nexport const _browserSupportsWebAuthnAutofillInternals = {\n stubThis: (value) => value,\n};\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`\n */\nexport function identifyAuthenticationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Authentication ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rpId !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rpId}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { browserSupportsWebAuthnAutofill } from '../helpers/browserSupportsWebAuthnAutofill.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyAuthenticationError } from '../helpers/identifyAuthenticationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"login\" via WebAuthn assertion\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`\n * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.\n * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.\n */\nexport async function startAuthentication(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to avoid passing empty array to avoid blocking retrieval\n // of public key\n let allowCredentials;\n if (optionsJSON.allowCredentials?.length !== 0) {\n allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n allowCredentials,\n };\n // Prepare options for `.get()`\n const getOptions = {};\n /**\n * Set up the page to prompt the user to select a credential for authentication via the browser's\n * input autofill mechanism.\n */\n if (useBrowserAutofill) {\n if (!(await browserSupportsWebAuthnAutofill())) {\n throw Error('Browser does not support WebAuthn autofill');\n }\n // Check for an <input> with \"webauthn\" in its `autocomplete` attribute\n const eligibleInputs = document.querySelectorAll(\"input[autocomplete$='webauthn']\");\n // WebAuthn autofill requires at least one valid input\n if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {\n throw Error('No <input> with \"webauthn\" as the only or last value in its `autocomplete` attribute was detected');\n }\n // `CredentialMediationRequirement` doesn't know about \"conditional\" yet as of\n // typescript@4.6.3\n getOptions.mediation = 'conditional';\n // Conditional UI requires an empty allow list\n publicKey.allowCredentials = [];\n }\n // Finalize options\n getOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n getOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete assertion\n let credential;\n try {\n credential = (await navigator.credentials.get(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n getOptions));\n }\n catch (err) {\n throw identifyAuthenticationError({ error: err, options: getOptions });\n }\n if (!credential) {\n throw new Error('Authentication was not completed');\n }\n const { id, rawId, response, type } = credential;\n let userHandle = undefined;\n if (response.userHandle) {\n userHandle = bufferToBase64URLString(response.userHandle);\n }\n // Convert values to base64 to make it easier to send back to the server\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n authenticatorData: bufferToBase64URLString(response.authenticatorData),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n signature: bufferToBase64URLString(response.signature),\n userHandle,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n","import { WebAuthnAbortService } from \"@simplewebauthn/browser\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** A dismissed or aborted passkey prompt. */\nexport function isCanceledCeremony(err: unknown): boolean {\n return err instanceof Error && (err.name === \"NotAllowedError\" || err.name === \"AbortError\");\n}\n\n/**\n * Runs a WebAuthn ceremony the user can cancel at once. Some authenticator UIs never reject when\n * their popup closes, so Cancel does not wait for the browser: it resets and ignores the late result.\n */\nexport function usePasskeyCeremony() {\n const [waiting, setWaiting] = useState(false);\n const token = useRef(0);\n const waitingRef = useRef(false);\n\n const set = useCallback((v: boolean) => {\n waitingRef.current = v;\n setWaiting(v);\n }, []);\n\n const cancel = useCallback(() => {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n waitingRef.current = false;\n setWaiting(false);\n }, []);\n\n const run = useCallback(\n async <T>(\n fn: () => Promise<T>,\n ): Promise<{ ok: true; value: T } | { ok: false; canceled: true }> => {\n const mine = ++token.current;\n set(true);\n try {\n const value = await fn();\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n return { ok: true, value };\n } catch (err) {\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n if (isCanceledCeremony(err)) return { ok: false, canceled: true };\n throw err;\n }\n },\n [set],\n );\n\n useEffect(\n () => () => {\n if (waitingRef.current) {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n }\n },\n [],\n );\n\n return { waiting, run, cancel };\n}\n","import type { OidcClaimResponse } from \"@switchyard/protocol\";\n\n/** How often the PWA polls `POST /api/auth/oidc/claim` while the screen is visible. */\nexport const HANDOFF_POLL_MS = 2000;\n/** How long a handoff waits before giving up (the coordinator flow lives 10 minutes). */\nexport const HANDOFF_TIMEOUT_MS = 10 * 60 * 1000;\n\nexport type HandoffPhase = \"waiting\" | \"done\" | \"timeout\" | \"failed\" | \"canceled\";\n\nexport interface HandoffState {\n phase: HandoffPhase;\n startedAt: number;\n /** Set when `phase` is `failed`. */\n message: string | null;\n}\n\nexport type HandoffEvent =\n | { type: \"claim\"; result: OidcClaimResponse; now: number }\n | { type: \"claim_error\"; code: string; message: string; now: number }\n | { type: \"tick\"; now: number }\n | { type: \"cancel\" };\n\nexport function startHandoff(now: number): HandoffState {\n return { phase: \"waiting\", startedAt: now, message: null };\n}\n\n/**\n * Pure state machine for the PWA single sign-on handoff. Terminal phases\n * never change. A transient error (network, server hiccup) keeps waiting;\n * an expired or unknown flow (`unauthorized`, `invalid_request`) fails.\n */\nexport function handoffReduce(state: HandoffState, event: HandoffEvent): HandoffState {\n if (state.phase !== \"waiting\") return state;\n if (event.type === \"cancel\") return { ...state, phase: \"canceled\" };\n if (event.now - state.startedAt >= HANDOFF_TIMEOUT_MS && event.type !== \"claim\") {\n return { ...state, phase: \"timeout\" };\n }\n switch (event.type) {\n case \"tick\":\n return state;\n case \"claim\":\n if (event.result.status === \"done\") return { ...state, phase: \"done\" };\n return event.now - state.startedAt >= HANDOFF_TIMEOUT_MS\n ? { ...state, phase: \"timeout\" }\n : state;\n case \"claim_error\":\n if (event.code === \"unauthorized\" || event.code === \"invalid_request\") {\n return { ...state, phase: \"failed\", message: event.message };\n }\n return state;\n }\n}\n\n/** Whether a poll should run now: still waiting and the page is visible. */\nexport function shouldPoll(state: HandoffState, visible: boolean): boolean {\n return state.phase === \"waiting\" && visible;\n}\n\nconst GENERIC_FORBIDDEN = \"This account is not allowed to sign in to this server.\";\n\n/** Static texts for coordinator error codes shown on /sign-in. */\nexport const ERROR_TEXT: Record<string, string> = {\n enrollment_expired:\n \"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.\",\n enrollment_used:\n \"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.\",\n invalid_request: \"The sign-in request was rejected. Try again.\",\n network: \"Could not reach the coordinator. Check your connection and try again.\",\n rate_limited: \"Too many attempts. Wait a minute and try again.\",\n unsupported_capability: \"This sign-in method is not available on this server.\",\n unauthorized: \"That sign-in was not accepted. Try again, or use another sign-in method.\",\n};\n\n/**\n * Message for an error code, with the coordinator's `detail` where it is the\n * useful part (`/sign-in?error=forbidden&detail=Signed in as ...`).\n */\nexport function enrollErrorText(code: string, detail?: string | null): string {\n const d = detail?.trim() || null;\n switch (code) {\n case \"forbidden\":\n return d ?? GENERIC_FORBIDDEN;\n case \"oidc_failed\":\n return `Single sign-on failed: ${d ?? \"the identity provider returned an error.\"}`;\n case \"unsupported_capability\":\n return d ?? (ERROR_TEXT.unsupported_capability as string);\n default:\n return ERROR_TEXT[code] ?? d ?? `Sign-in failed (${code}).`;\n }\n}\n\n/** Short heading for an error alert. */\nexport function enrollErrorTitle(code: string): string {\n switch (code) {\n case \"enrollment_expired\":\n return \"Sign-in link expired\";\n case \"enrollment_used\":\n return \"Sign-in link already used\";\n case \"forbidden\":\n return \"Not allowed\";\n case \"oidc_failed\":\n return \"Single sign-on failed\";\n case \"rate_limited\":\n return \"Too many attempts\";\n default:\n return \"Sign-in failed\";\n }\n}\n\n/** A readable default device name from the user agent, e.g. \"Safari on iPhone\". */\nexport function defaultDeviceName(ua: string = navigator.userAgent): string {\n const device = /iPhone/.test(ua)\n ? \"iPhone\"\n : /iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)\n ? \"iPad\"\n : /Android/.test(ua)\n ? \"Android\"\n : /Macintosh|Mac OS X/.test(ua)\n ? \"Mac\"\n : /Windows/.test(ua)\n ? \"Windows\"\n : /Linux/.test(ua)\n ? \"Linux\"\n : \"device\";\n const browser = /Edg\\//.test(ua)\n ? \"Edge\"\n : /Firefox\\/|FxiOS/.test(ua)\n ? \"Firefox\"\n : /Chrome\\/|CriOS/.test(ua)\n ? \"Chrome\"\n : /Safari\\//.test(ua)\n ? \"Safari\"\n : \"Browser\";\n return `${browser} on ${device}`;\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12],"mappings":"A,gDAMA,SAAgBK,EAAwB,EAAQ,CAC5C,IAAMC,EAAQ,IAAI,WAAWC,CAAM,EAC/BC,EAAM,GACV,IAAK,IAAMC,KAAYH,EACnB,GAAO,OAAO,aAAaG,CAAQ,EAGvC,OADqB,KAAKD,CACR,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,KAAM,EAAE,CAChF,CCPA,SAAgBE,EAAwB,EAAiB,CAErD,IAAMC,EAASC,EAAgB,QAAQ,KAAM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,MAAO,4BACT,IAAK,YACH,MAAO,cACT,IAAK,cACH,MAAO,wBACT,IAAK,eACH,MAAO,oBACT,QACE,MAAO,gBACX,CACF,CAGA,SAAgBkE,EAAkB,EAAa,UAAU,UAAmB,CAC1E,IAAMC,EAAS,SAAS,KAAKC,CAAE,EAC3B,SACA,OAAO,KAAKA,CAAE,GAAM,YAAY,KAAKA,CAAE,GAAK,UAAU,eAAiB,EACrE,OACA,UAAU,KAAKA,CAAE,EACf,UACA,qBAAqB,KAAKA,CAAE,EAC1B,MACA,UAAU,KAAKA,CAAE,EACf,UACA,QAAQ,KAAKA,CAAE,EACb,QACA,SAUd,MAAO,GATS,QAAQ,KAAKA,CAAE,EAC3B,OACA,kBAAkB,KAAKA,CAAE,EACvB,UACA,iBAAiB,KAAKA,CAAE,EACtB,SACA,WAAW,KAAKA,CAAE,EAChB,SACA,UACQ,MAAMD,GAC1B,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{i as e,l as t,t as n}from"./Button-C7TQGuSX.js";import{t as r}from"./chevron-right-BM1IJI2z.js";import{n as i,t as a}from"./timer-DFrvOKOy.js";import{R as o,_n as s,pn as c}from"./index-BUZpNu-R.js";var l=e(),u=[{to:`/tasks`,label:`Tasks`,description:`Automation tasks and review`,icon:i},{to:`/queue`,label:`Queue`,description:`Running and queued runs`,icon:a},{to:`/automations`,label:`Automations`,description:`Schedules, webhooks and history`,icon:c},{to:`/settings`,label:`Settings`,description:`Hosts, devices, projects, notifications`,icon:s}];function d(){return(0,l.jsxs)(`div`,{className:`mx-auto flex w-full max-w-xl flex-col gap-3 px-4 pb-4 safe-pt-4`,children:[(0,l.jsx)(`h1`,{className:`text-lg font-semibold`,children:`More`}),(0,l.jsx)(`ul`,{"aria-label":`More navigation`,tabIndex:-1,"data-keyboard-scope":!0,"data-keyboard-default":!0,className:`overflow-hidden rounded-lg border border-border bg-surface focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent`,children:u.map(({to:e,label:n,description:i,icon:a})=>(0,l.jsx)(`li`,{className:`border-b border-border last:border-b-0`,children:(0,l.jsxs)(t,{to:e,"data-keyboard-item":!0,className:`tap flex min-h-14 items-center gap-3 px-4 py-2 hover:bg-surface-2`,children:[(0,l.jsx)(a,{"aria-hidden":!0,className:`size-5 shrink-0 text-muted`}),(0,l.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,l.jsx)(`span`,{className:`block font-medium`,children:n}),(0,l.jsx)(`span`,{className:`block truncate text-sm text-muted`,children:i})]}),(0,l.jsx)(r,{"aria-hidden":!0,className:`size-4 shrink-0 text-subtle`})]})},e))}),(0,l.jsx)(n,{variant:`secondary`,onClick:()=>o.getState().setHelpOpen(!0),children:`Keyboard shortcuts`})]})}export{d as default};
|
|
2
|
+
//# sourceMappingURL=more-C1oPXLVM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"more-
|
|
1
|
+
{"version":3,"file":"more-C1oPXLVM.js","names":["require_jsx_runtime","Link","Button","ChevronRight","ListChecks","Timer","usePalette","Settings","Workflow","import_jsx_runtime","ITEMS","MoreView","Icon","label","description","to"],"sources":["../../src/features/more/index.tsx"],"sourcesContent":["import { ChevronRight, ListChecks, type LucideIcon, Settings, Timer, Workflow } from \"lucide-react\";\nimport { Link } from \"react-router\";\nimport { Button } from \"../../components/ui/Button\";\nimport { usePalette } from \"../palette/registry\";\n\nconst ITEMS: { to: string; label: string; description: string; icon: LucideIcon }[] = [\n { to: \"/tasks\", label: \"Tasks\", description: \"Automation tasks and review\", icon: ListChecks },\n { to: \"/queue\", label: \"Queue\", description: \"Running and queued runs\", icon: Timer },\n {\n to: \"/automations\",\n label: \"Automations\",\n description: \"Schedules, webhooks and history\",\n icon: Workflow,\n },\n {\n to: \"/settings\",\n label: \"Settings\",\n description: \"Hosts, devices, projects, notifications\",\n icon: Settings,\n },\n];\n\n/** Mobile \"More\": Tasks, Queue, Automations and Settings (spec 10). */\nexport default function MoreView() {\n return (\n <div className=\"mx-auto flex w-full max-w-xl flex-col gap-3 px-4 pb-4 safe-pt-4\">\n <h1 className=\"text-lg font-semibold\">More</h1>\n <ul\n aria-label=\"More navigation\"\n tabIndex={-1}\n data-keyboard-scope\n data-keyboard-default\n className=\"overflow-hidden rounded-lg border border-border bg-surface focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent\"\n >\n {ITEMS.map(({ to, label, description, icon: Icon }) => (\n <li key={to} className=\"border-b border-border last:border-b-0\">\n <Link\n to={to}\n data-keyboard-item\n className=\"tap flex min-h-14 items-center gap-3 px-4 py-2 hover:bg-surface-2\"\n >\n <Icon aria-hidden className=\"size-5 shrink-0 text-muted\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block font-medium\">{label}</span>\n <span className=\"block truncate text-sm text-muted\">{description}</span>\n </span>\n <ChevronRight aria-hidden className=\"size-4 shrink-0 text-subtle\" />\n </Link>\n </li>\n ))}\n </ul>\n <Button variant=\"secondary\" onClick={() => usePalette.getState().setHelpOpen(true)}>\n Keyboard shortcuts\n </Button>\n </div>\n );\n}\n"],"mappings":"A,wNAKMU,EAAgF,CACpF,CAAE,GAAI,SAAU,MAAO,QAAS,YAAa,8BAA+B,KAAMN,CAAW,EAC7F,CAAE,GAAI,SAAU,MAAO,QAAS,YAAa,0BAA2B,KAAMC,CAAM,EACpF,CACE,GAAI,eACJ,MAAO,cACP,YAAa,kCACb,KAAMG,CACR,EACA,CACE,GAAI,YACJ,MAAO,WACP,YAAa,0CACb,KAAMD,CACR,CACF,EAGA,SAAwBI,GAAW,CACjC,OACE,EAAAF,EAAA,KAAA,CAAC,MAAD,CAAK,UAAU,kEAAf,SAAA,EACE,EAAAA,EAAA,IAAA,CAAC,KAAD,CAAI,UAAU,wBAAwB,SAAA,MAAQ,CAAA,GAC9C,EAAAA,EAAA,IAAA,CAAC,KAAD,CACE,aAAW,kBACX,SAAU,GACV,sBAAA,GACA,wBAAA,GACA,UAAU,wIAET,SAAAC,EAAM,KAAK,CAAE,KAAI,QAAO,cAAa,KAAME,MAC1C,EAAAH,EAAA,IAAA,CAAC,KAAD,CAAa,UAAU,yCACrB,UAAA,EAAAA,EAAA,KAAA,CAACR,EAAD,CACM,KACJ,qBAAA,GACA,UAAU,oEAHZ,SAAA,EAKE,EAAAQ,EAAA,IAAA,CAACG,EAAD,CAAM,cAAA,GAAY,UAAU,4BAA8B,CAAA,GAC1D,EAAAH,EAAA,KAAA,CAAC,OAAD,CAAM,UAAU,iBAAhB,SAAA,EACE,EAAAA,EAAA,IAAA,CAAC,OAAD,CAAM,UAAU,oBAAqB,SAAAI,CAAY,CAAA,GACjD,EAAAJ,EAAA,IAAA,CAAC,OAAD,CAAM,UAAU,oCAAqC,SAAAK,CAAkB,CAAA,CACnE,C,IACN,EAAAL,EAAA,IAAA,CAACN,EAAD,CAAc,cAAA,GAAY,UAAU,6BAA+B,CAAA,CAC/D,C,EACJ,EAbKY,CAaL,CACL,CACC,CAAA,GACJ,EAAAN,EAAA,IAAA,CAACP,EAAD,CAAQ,QAAQ,YAAY,YAAeI,EAAW,SAAS,CAAC,CAAC,YAAY,EAAI,EAAG,SAAA,oBAE5E,CAAA,CACL,C,EAET,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as e}from"./Button-
|
|
2
|
-
//# sourceMappingURL=pencil-
|
|
1
|
+
import{o as e}from"./Button-C7TQGuSX.js";var t={name:`git-branch`,size:24,node:[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]};t.node;var n=e(t),r={name:`pencil`,size:24,node:[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]};r.node;var i=e(r);export{n,i as t};
|
|
2
|
+
//# sourceMappingURL=pencil-DeML-0z2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pencil-
|
|
1
|
+
{"version":3,"file":"pencil-DeML-0z2.js","names":["__iconData","createLucideIcon","__iconData$1","GitBranch","__iconData","Pencil"],"sources":["../../../../node_modules/.pnpm/lucide-react@1.61.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/git-branch.mjs","../../../../node_modules/.pnpm/lucide-react@1.61.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/pencil.mjs"],"sourcesContent":["/**\n * @license lucide-react v1.61.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"git-branch\",\n size: 24,\n node: [\n [\"path\", { d: \"M15 6a9 9 0 0 0-9 9V3\", key: \"1cii5b\" }],\n [\"circle\", { cx: \"18\", cy: \"6\", r: \"3\", key: \"1h7g24\" }],\n [\"circle\", { cx: \"6\", cy: \"18\", r: \"3\", key: \"fqmcym\" }]\n ]\n};\n__iconData.node;\nconst GitBranch = createLucideIcon(__iconData);\n\nexport { __iconData, GitBranch as default };\n//# sourceMappingURL=git-branch.mjs.map\n","/**\n * @license lucide-react v1.61.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"pencil\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z\",\n key: \"1a8usu\"\n }\n ],\n [\"path\", { d: \"m15 5 4 4\", key: \"1mk7zo\" }]\n ]\n};\n__iconData.node;\nconst Pencil = createLucideIcon(__iconData);\n\nexport { __iconData, Pencil as default };\n//# sourceMappingURL=pencil.mjs.map\n"],"ignoreList":[0,1],"mappings":"A,yCASA,IAAMA,EAAa,CACjB,KAAM,aACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,wBAAyB,IAAK,QAAS,CAAC,EACtD,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,IAAK,EAAG,IAAK,IAAK,QAAS,CAAC,EACvD,CAAC,SAAU,CAAE,GAAI,IAAK,GAAI,KAAM,EAAG,IAAK,IAAK,QAAS,CAAC,CACzD,CACF,EACAA,EAAW,KACX,IAAMG,EAAYF,EAAiBD,CAAU,ECVvCI,EAAa,CACjB,KAAM,SACN,KAAM,GACN,KAAM,CACJ,CACE,OACA,CACE,EAAG,mIACH,IAAK,QACP,CACF,EACA,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,CAC5C,CACF,EACAA,EAAW,KACX,IAAMC,EAASJ,EAAiBG,CAAU,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as e}from"./Button-
|
|
2
|
-
//# sourceMappingURL=play-
|
|
1
|
+
import{o as e}from"./Button-C7TQGuSX.js";var t={name:`play`,size:24,node:[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]};t.node;var n=e(t);export{n as t};
|
|
2
|
+
//# sourceMappingURL=play-NHO6U6cY.js.map
|