@uibot/creation-kit 0.5.0 → 0.7.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/dist/client.js +1 -1
- package/dist/index-31w4ne7n.js +17 -0
- package/dist/{index-wsse4x6x.js → index-yg2ewbrj.js} +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/testing.js +1 -1
- package/dist/use-creation-workspace.d.ts +13 -0
- package/dist/workspace-controller.d.ts +105 -0
- package/package.json +3 -3
- package/dist/index-rep1qesa.js +0 -17
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e,
|
|
1
|
+
import{e,C,y}from"./index-yg2ewbrj.js";export{e as CreationApiError,y as createCreationClient,C as creationProjectPath};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{e}from"./index-yg2ewbrj.js";var t=1;var Xe=/^[a-z][a-z0-9-]{0,39}$/;function Ze(C,pe,y,ge){if(pe.has(y))throw Error(`Duplicate creation ${C} "${y}" (plugin ${ge})`);pe.add(y)}function P(C){let pe=new Set,y=new Map,ge=new Map,fe=new Set,ve=[],ye=new Map;for(let ue of C){if(ue.kitApi!==t)throw Error(`Creation plugin "${ue.id}" targets kit API ${String(ue.kitApi)}, expected ${t}`);Ze("plugin",pe,ue.id,ue.id);for(let be of ue.kinds??[]){if(!Xe.test(be.kind))throw Error(`Invalid creation kind "${be.kind}" (plugin ${ue.id})`);if(y.has(be.kind))throw Error(`Duplicate creation kind "${be.kind}" (plugin ${ue.id})`);y.set(be.kind,be)}for(let be of ue.editors??[]){let we=`${be.id}:${be.format}`;if(ge.has(we))throw Error(`Duplicate creation editor "${we}" (plugin ${ue.id})`);ge.set(we,be)}for(let be of ue.views??[])Ze("view",fe,be.id,ue.id),ve.push(be);for(let be of ue.projectAssets??[]){if(ye.has(be.slot))throw Error(`Duplicate creation asset slot "${be.slot}" (plugin ${ue.id})`);ye.set(be.slot,be)}}let he=[...y.values()].sort((ue,be)=>(ue.order??100)-(be.order??100)||ue.kind.localeCompare(be.kind));return{plugins:C,taskKind:(ue)=>ue?y.get(ue):void 0,taskKinds:()=>[...he],kindOptions(ue,be,we){let Se=ue.map((me)=>({value:me.artifactKind,label:we?.(me)??me.title,disabled:!me.enabled})),Re=new Set(Se.map((me)=>me.value));for(let me of he){if(Re.has(me.kind)){console.error(`Creation workbench kind "${me.kind}" shadows a server domain and is hidden`);continue}Se.push({value:me.kind,label:me.label[be]})}return Se},label:(ue,be,we)=>y.get(ue)?.label[be]??we??ue,editor:(ue,be)=>ue?ge.get(`${ue}:${be}`):void 0,views:(ue)=>ve.filter((be)=>be.match(ue)),projectAssets:()=>[...ye.values()],projectAsset:(ue)=>ye.get(ue),parseRouteSearch(ue){let be=typeof ue.kind==="string"&&Xe.test(ue.kind)?ue.kind:void 0,we={};for(let Se of he){if(!Se.parseSearch)continue;Object.assign(we,Se.parseSearch(ue))}return{...be?{kind:be}:{},extra:we}}}}import{createContext as dt,useContext as ut}from"react";import{jsx as pt}from"react/jsx-runtime";var Qe=dt(null);function v(C){return pt(Qe.Provider,{value:C.transport,children:C.children})}function x(){let C=ut(Qe);if(!C)throw Error("useCreationTransport requires a CreationTransportProvider");return C}import{clsx as ft}from"clsx";import{twMerge as gt}from"tailwind-merge";function h(...C){return gt(ft(C))}function k(C){if(!(C instanceof Error))return;let{status:pe}=C;return typeof pe==="number"?pe:void 0}import{createContext as mt,useContext as Ct}from"react";import{jsx as bt}from"react/jsx-runtime";var et=mt("en");function o(C){return bt(et.Provider,{value:C.locale,children:C.children})}function T(){return Ct(et)}import{createContext as yt,useContext as vt}from"react";import{jsx as nt}from"react/jsx-runtime";var tt=yt(null);function r(C){return nt(tt.Provider,{value:C.primitives,children:C.children})}function xt(){let C=vt(tt);if(!C)throw Error("Creation UI primitives require a CreationUiProvider");return C}function ke(C,pe){let y=(ge)=>{let fe=C(xt());return nt(fe,{...ge})};return y.displayName=pe,y}var w=ke((C)=>C.Button,"Button"),R=ke((C)=>C.Badge,"Badge"),I=ke((C)=>C.Label,"Label"),j=ke((C)=>C.Input,"Input"),S=ke((C)=>C.Textarea,"Textarea"),D=ke((C)=>C.Checkbox,"Checkbox"),A=ke((C)=>C.Collapsible,"Collapsible"),E=ke((C)=>C.CollapsibleTrigger,"CollapsibleTrigger"),L=ke((C)=>C.CollapsibleContent,"CollapsibleContent"),U=ke((C)=>C.ScrollArea,"ScrollArea"),N=ke((C)=>C.ScrollBar,"ScrollBar"),O=ke((C)=>C.Select,"Select"),q=ke((C)=>C.SelectTrigger,"SelectTrigger"),K=ke((C)=>C.SelectValue,"SelectValue"),F=ke((C)=>C.SelectContent,"SelectContent"),B=ke((C)=>C.SelectItem,"SelectItem"),z=ke((C)=>C.Tabs,"Tabs"),W=ke((C)=>C.TabsList,"TabsList"),V=ke((C)=>C.TabsTrigger,"TabsTrigger"),_=ke((C)=>C.TabsContent,"TabsContent"),M=ke((C)=>C.Tooltip,"Tooltip"),G=ke((C)=>C.TooltipProvider,"TooltipProvider"),H=ke((C)=>C.TooltipTrigger,"TooltipTrigger"),J=ke((C)=>C.TooltipContent,"TooltipContent"),Y=ke((C)=>C.Popover,"Popover"),X=ke((C)=>C.PopoverTrigger,"PopoverTrigger"),Z=ke((C)=>C.PopoverContent,"PopoverContent"),Q=ke((C)=>C.Dialog,"Dialog"),ee=ke((C)=>C.DialogTrigger,"DialogTrigger"),te=ke((C)=>C.DialogContent,"DialogContent"),ne=ke((C)=>C.DialogHeader,"DialogHeader"),oe=ke((C)=>C.DialogFooter,"DialogFooter"),re=ke((C)=>C.DialogTitle,"DialogTitle"),ie=ke((C)=>C.DialogDescription,"DialogDescription"),ae=ke((C)=>C.Prompt,"Prompt");var Me=/<(\/?)section\b[^>]*>/gi;function Ke(C,pe){let y=new RegExp(`\\b${pe}(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`,"i").exec(C);if(!y)return;return y[1]??y[2]??y[3]??""}function Pt(C){if(Ke(C,"data-slide")!==void 0)return!0;return/\bslide\b/i.test(Ke(C,"class")??"")}function Be(C,pe){return C.exec(pe)?.[1]??""}function kt(C){return C.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function ot(C){return kt(C.replace(/<[^>]+>/g," ")).replace(/\s+/g," ").trim()}function rt(C){let pe=[];Me.lastIndex=0;let y=0,ge=-1;for(let fe=Me.exec(C);fe;fe=Me.exec(C)){if(fe[1]==="/"){if(y===0)continue;if(y-=1,y===0&&ge>=0)pe.push(C.slice(ge,fe.index+fe[0].length)),ge=-1;continue}if(y===0){if(!Pt(fe[0]))continue;ge=fe.index}y+=1}return pe}function c(C){return Boolean(C)&&rt(C).length>0}var ht=/<aside\b([^>]*)>([\s\S]*?)<\/aside>/i;function Tt(C){let pe="";return{slide:C.replace(ht,(ge,fe,ve)=>{if(!(Ke(`<aside ${fe}>`,"data-notes")!==void 0||/\bnotes\b/i.test(Ke(`<aside ${fe}>`,"class")??"")))return ge;return pe=ot(ve),""}),notes:pe}}function l(C){let pe=rt(C);if(pe.length===0)return{isDeck:!1,slides:[],head:"",bodyClass:"",bodyStyle:"",title:"deck"};let y=Be(/<head\b[^>]*>([\s\S]*?)<\/head>/i,C),ge=`<body ${Be(/<body\b([^>]*)>/i,C)}>`,fe=Ke(ge,"class")??"",ve=Ke(ge,"style")??"",ye=ot(Be(/<title\b[^>]*>([\s\S]*?)<\/title>/i,y))||"deck",he=new Set;return{isDeck:!0,slides:pe.map((be,we)=>{let Se=Be(/(<section\b[^>]*>)/i,be),Re=Ke(Se,"data-slide")||Ke(Se,"data-slide-id")||String(we+1),me=he.has(Re)?`${Re}-${we+1}`:Re;he.add(me);let je=Be(/background(?:-color)?\s*:\s*([^;"']+)/i,Ke(Se,"style")??"").trim()||void 0,{slide:Ie,notes:de}=Tt(be);return{html:`<!DOCTYPE html><html><head>${y}
|
|
2
|
+
<style>
|
|
3
|
+
html, body { margin:0; padding:0; }
|
|
4
|
+
body { display:flex; align-items:center; justify-content:center; min-height:100vh; }
|
|
5
|
+
.slide, [data-slide] { transform-origin: center center !important; }
|
|
6
|
+
</style></head><body class="${fe}" style="${ve}">${Ie}</body></html>`,notes:de,id:me,...je?{bg:je}:{}}}),head:y,bodyClass:fe,bodyStyle:ve,title:ye}}function b(C){return`<!DOCTYPE html><html><head>
|
|
7
|
+
<style>
|
|
8
|
+
@page { size: 1280px 720px; margin: 0; }
|
|
9
|
+
html, body { margin:0; padding:0; }
|
|
10
|
+
.page { width: 1280px; height: 720px; overflow: hidden; page-break-after: always; }
|
|
11
|
+
.page:last-child { page-break-after: auto; }
|
|
12
|
+
.page iframe.slide { display:block; width:100%; height:100%; border:0; }
|
|
13
|
+
</style></head><body>
|
|
14
|
+
${Array.from({length:C},(y,ge)=>`<div class="page"><iframe class="slide" data-slide-index="${ge}" sandbox="allow-scripts"></iframe></div>`).join(`
|
|
15
|
+
`)}
|
|
16
|
+
<script>window.onload=()=>setTimeout(()=>window.print(),300)</script>
|
|
17
|
+
</body></html>`}function d(C,pe=(y,ge)=>window.open(y,ge)){let y=pe("","_blank");if(!y)return!1;y.opener=null,y.document.write(b(C.slides.length)),y.document.close();let ge=y.document.querySelectorAll("iframe.slide");return C.slides.forEach((fe,ve)=>{let ye=ge[ve];if(ye)ye.srcdoc=fe.html}),!0}import{ChevronLeft as wt,ChevronRight as Rt,FileDown as St,Maximize2 as It,StickyNote as jt}from"lucide-react";import{useEffect as it,useMemo as Dt,useRef as At,useState as Ge}from"react";import{jsx as Le,jsxs as Fe}from"react/jsx-runtime";var Et={empty:"No slides found (each slide must be a <section data-slide>).",prev:"Previous slide",next:"Next slide",notes:"Notes",notesTitle:"Speaker notes (N)",notesHeading:"Speaker notes",present:"Present",presentTitle:"Full screen (F)",pdfTitle:"Print to PDF",blocked:"The popup was blocked. Allow popups for this site and try again.",page:"Slide"},Lt={empty:"未检测到幻灯片(每页需为 <section data-slide>)。",prev:"上一页",next:"下一页",notes:"备注",notesTitle:"演讲者备注(N)",notesHeading:"演讲者备注",present:"放映",presentTitle:"全屏放映(F)",pdfTitle:"打印为 PDF",blocked:"弹窗被拦截,请允许本站弹出窗口后重试。",page:"第"},Nt={en:Et,zh:Lt},He="inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs";function i({content:C,locale:pe,active:y}){let ge=Nt[pe],fe=Dt(()=>l(C),[C]),[ve,ye]=Ge(0),[he,ue]=Ge(!1),[be,we]=Ge(""),Se=At(null),Re=fe.slides.length,me=Math.min(ve,Math.max(0,Re-1)),je=fe.slides[me];if(it(()=>ye(0),[C]),it(()=>{if(!y||Re===0)return;let Ie=(de)=>{let Ce=de.target;if(Ce&&(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable))return;if(de.key==="ArrowRight"||de.key==="PageDown"||de.key===" ")de.preventDefault(),ye((xe)=>Math.min(xe+1,Re-1));else if(de.key==="ArrowLeft"||de.key==="PageUp")de.preventDefault(),ye((xe)=>Math.max(xe-1,0));else if(de.key==="Home")ye(0);else if(de.key==="End")ye(Re-1);else if(de.key.toLowerCase()==="n")ue((xe)=>!xe);else if(de.key.toLowerCase()==="f")if(document.fullscreenElement)document.exitFullscreen();else Se.current?.requestFullscreen?.()};return window.addEventListener("keydown",Ie),()=>window.removeEventListener("keydown",Ie)},[y,Re]),!je)return Le("div",{className:"flex h-full items-center justify-center p-6 text-sm text-muted-foreground",children:ge.empty});return Fe("div",{ref:Se,className:"flex h-full min-h-72 flex-col bg-muted/30",children:[Fe("div",{className:"relative min-h-0 flex-1",children:[Le("iframe",{title:`slide-${je.id}`,srcDoc:je.html,sandbox:"allow-scripts",className:"h-full w-full border-0 bg-white"},je.id),Le("button",{type:"button",onClick:()=>ye((Ie)=>Math.max(Ie-1,0)),disabled:me===0,className:"absolute left-2 top-1/2 -translate-y-1/2 rounded-full border bg-background/80 p-1.5 shadow backdrop-blur disabled:opacity-30","aria-label":ge.prev,children:Le(wt,{className:"size-4"})}),Le("button",{type:"button",onClick:()=>ye((Ie)=>Math.min(Ie+1,Re-1)),disabled:me===Re-1,className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-full border bg-background/80 p-1.5 shadow backdrop-blur disabled:opacity-30","aria-label":ge.next,children:Le(Rt,{className:"size-4"})}),Fe("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full bg-foreground/80 px-2.5 py-0.5 text-xs tabular-nums text-background",children:[me+1," / ",Re]}),he&&je.notes&&Fe("div",{className:"absolute inset-x-3 bottom-10 max-h-[40%] overflow-y-auto rounded-md border bg-background/95 p-3 text-sm shadow-lg",children:[Le("div",{className:"mb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:ge.notesHeading}),je.notes]})]}),be&&Le("p",{role:"status",className:"border-t bg-background px-3 py-1 text-xs text-destructive",children:be}),Fe("div",{className:"flex items-center gap-2 border-t bg-background px-3 py-2",children:[Le("div",{className:"flex min-w-0 flex-1 gap-1.5 overflow-x-auto",children:fe.slides.map((Ie,de)=>Le("button",{type:"button",onClick:()=>ye(de),"aria-label":`${ge.page} ${de+1}`,"aria-current":de===me?"true":void 0,...Ie.bg?{style:{background:Ie.bg}}:{},className:`flex size-7 shrink-0 items-center justify-center rounded border text-[11px] tabular-nums ${de===me?"border-primary ring-2 ring-primary/30":"text-muted-foreground hover:border-foreground/30"}`,children:de+1},Ie.id))}),Fe("button",{type:"button",onClick:()=>ue((Ie)=>!Ie),className:`${He} ${he?"border-primary bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent"}`,title:ge.notesTitle,children:[Le(jt,{className:"size-3.5"}),ge.notes]}),Fe("button",{type:"button",onClick:()=>{if(!document.fullscreenElement)Se.current?.requestFullscreen?.()},className:`${He} text-muted-foreground hover:bg-accent`,title:ge.presentTitle,children:[Le(It,{className:"size-3.5"}),ge.present]}),Fe("button",{type:"button",onClick:()=>we(d(fe)?"":ge.blocked),className:`${He} text-muted-foreground hover:bg-accent`,title:ge.pdfTitle,children:[Le(St,{className:"size-3.5"}),"PDF"]})]})]})}var se={id:"presentation-deck",version:"1.0.0",kitApi:t,views:[{id:"slides",label:{zh:"幻灯片",en:"Slides"},match:(C)=>C.artifactKind==="presentation"&&C.format==="html"&&c(C.content),View:i}]};var Ut=["queued","running","interrupted","completed","failed","cancelled","conflict"];function a(C){if(!C||typeof C!=="object"||Array.isArray(C))return"unknown";if(typeof C.status!=="string"||!Ut.includes(C.status))return"unknown";if(C.error?.code==="inference-outcome-unknown")return"unknown";let pe=C.modelRequests;if(pe!==void 0){if(!Array.isArray(pe))return"unknown";for(let y of pe){if(!y||typeof y!=="object"||Array.isArray(y))return"unknown";let ge=y;if(typeof ge.requestId!=="string"||!ge.requestId||ge.purpose!=="generation"&&ge.purpose!=="requirement-review"||typeof ge.dispatchedAt!=="string"||!ge.dispatchedAt||ge.dispatched!==void 0&&typeof ge.dispatched!=="boolean"||typeof ge.outcome!=="string"||!["pending","completed","failed","unknown"].includes(ge.outcome))return"unknown";if(ge.outcome==="unknown")return"unknown";if(ge.outcome==="pending"&&!["queued","running","interrupted"].includes(C.status))return"unknown"}}return C.status}function n(C=[]){if(!Array.isArray(C))return[C];return C.filter((pe)=>["queued","running","interrupted","unknown"].includes(a(pe)))}var qt={zh:{noRecord:"尚未读到原请求记录;不会重新发送。",unknown:"原请求结果未知;不会重新发送。",settled:"原请求结果已确认。",running:"原请求仍在进行中。",storageFailed:"未发送生成请求:无法保存原请求核对记录。",rejected:"生成请求未被接受;请检查当前版本和生成能力后重新发起。",noLocks:"未发送生成请求:当前浏览器无法锁定项目生成操作。",lockFailed:"未能取得项目生成锁;请稍后核对原请求状态。",readFailed:"状态读取失败;保留原请求并稍后只读核对。",unreadable:"无法读取原请求核对记录;生成已禁用。"},en:{noRecord:"The original request is not recorded yet; it will not be sent again.",unknown:"The original request's outcome is unknown; it will not be sent again.",settled:"The original request's outcome is confirmed.",running:"The original request is still in progress.",storageFailed:"Not sent: the request record could not be saved.",rejected:"The request was not accepted; check the current version and generation, then try again.",noLocks:"Not sent: this browser cannot lock project generation.",lockFailed:"Could not take the project generation lock; check the original request later.",readFailed:"Reading the status failed; the original request is kept for a later check.",unreadable:"The request record cannot be read; generation is disabled."}},u=Object.freeze({pending:!0,sending:!1,checking:!1,writingBlocked:!0,canReconcile:!1,message:""});function Kt(C){return C instanceof e&&(C.status===422&&["invalid-input","invalid-format","unknown-domain"].includes(C.code)||C.status===409&&["revision-conflict","format-conflict","domain-disabled","brand-conflict"].includes(C.code)||C.status===503&&C.code==="model-unavailable")}function $e(C,pe,y){if(!C)return{ok:!1,pending:null};try{let ge=C.getItem(pe);if(ge===null)return{ok:!0,pending:null};let fe=JSON.parse(ge);if(!fe||fe.version!==1||fe.projectId!==y||typeof fe.requestId!=="string"||!fe.requestId||typeof fe.kind!=="string"||!fe.kind||!["new","rewrite"].includes(fe.mode))return{ok:!1,pending:null};if(fe.mode==="rewrite"&&(typeof fe.artifactId!=="string"||!fe.artifactId||typeof fe.expectedRevisionId!=="string"||!fe.expectedRevisionId))return{ok:!1,pending:null};if(fe.reference&&(typeof fe.reference.artifactId!=="string"||!fe.reference.artifactId||typeof fe.reference.revisionId!=="string"||!fe.reference.revisionId))return{ok:!1,pending:null};return{ok:!0,pending:fe}}catch{return{ok:!1,pending:null}}}function p(C){let pe=qt[C.locale??"en"],y=C.storageKey,ge=C.project.id,fe=C.authority??(()=>""),ve=C.newRequestId??(()=>crypto.randomUUID()),ye=C.project,he=$e(C.storage,y,ge),ue=!1,be=!1,we="",Se=!0,Re=!1,me=!1,je=0,Ie=new Set,de=Ce();function Ce(){let Pe=n(ye.runs);return{pending:!he.ok||!!he.pending||Pe.length>0||ue,sending:ue,checking:be,writingBlocked:ue||!!he.pending||Pe.length>0,canReconcile:he.ok&&(!!he.pending||Pe.some((De)=>!!De?.requestId)),message:!he.ok?pe.unreadable:we}}function xe(){let Pe=Ce();if(JSON.stringify(Pe)===JSON.stringify(de))return;let De=Pe.writingBlocked!==de.writingBlocked;if(de=Pe,De)C.onWritingBlocked?.(Pe.writingBlocked);for(let Ee of Ie)Ee()}function Te(Pe){if(JSON.stringify(Pe)===JSON.stringify(he))return;he=Pe,xe()}function Ae(Pe,De){return Se&&Pe===je&&fe()===De}function Ue(Pe){let De=$e(C.storage,y,ge);if(De.ok&&De.pending?.requestId===Pe){try{C.storage?.removeItem(y)}catch{}Te($e(C.storage,y,ge)),C.broadcast?.()}}function _e(Pe,De,Ee,ze){if(!Ae(ze,Ee))return;let qe=Pe.runs?.find((Ve)=>Ve?.requestId===De);if(!qe){we=pe.noRecord,xe();return}let Oe=a(qe),Ne=["completed","failed","cancelled","conflict"].includes(Oe);if(Ne){try{C.storage?.removeItem(y)}catch{}Te($e(C.storage,y,ge)),C.broadcast?.()}we=Oe==="unknown"?pe.unknown:Ne?pe.settled:pe.running,ye=Pe,xe(),C.onProject?.(Pe,Oe==="completed"?qe.artifactId:void 0)}async function ct(Pe){if(de.pending||Re)return;let De=$e(C.storage,y,ge);if(!De.ok||De.pending||n(ye.runs).length){Te(De);return}let Ee=ve(),ze={version:1,projectId:ge,requestId:Ee,kind:Pe.kind,mode:Pe.artifactId?"rewrite":"new",...Pe.artifactId?{artifactId:Pe.artifactId,expectedRevisionId:Pe.expectedRevisionId}:{},...Pe.reference?{reference:Pe.reference}:{}};try{let Ne=JSON.stringify(ze);if(C.storage?.setItem(y,Ne),!C.storage||C.storage.getItem(y)!==Ne)throw Error("storage-readback")}catch{he=$e(C.storage,y,ge),we=pe.storageFailed,xe();return}Re=!0,ue=!0,he={ok:!0,pending:ze},xe(),C.broadcast?.();let qe=je,Oe=fe();try{let Ne=await C.client.startRun(ge,{...Pe,requestId:Ee});_e(Ne,Ee,Oe,qe)}catch(Ne){if(!Ae(qe,Oe))return;let Ve=Kt(Ne);if(Ne instanceof e&&Ne.status===404&&Ne.code==="not-found")try{let We=await C.client.getProject(ge);if(!Ae(qe,Oe))return;if(We.id===ge){if(We.runs?.some((lt)=>lt?.requestId===Ee)){_e(We,Ee,Oe,qe);return}ye=We,C.onProject?.(We),Ve=!0}}catch{}if(Ve)Ue(Ee),we=pe.rejected;else we=pe.unknown;xe()}finally{if(Re=!1,Se&&qe===je)ue=!1,xe()}}return{getState:()=>de,subscribe(Pe){return Ie.add(Pe),()=>Ie.delete(Pe)},setProject(Pe){if(Pe.id!==ge)return;ye=Pe,xe()},refresh(){Te($e(C.storage,y,ge))},async start(Pe){if(de.pending||Re||me)return;if(!C.locks){we=pe.noLocks,xe();return}let De=je,Ee=fe();me=!0;try{await C.locks.request(y,async()=>{if(!Ae(De,Ee))return;await ct(Pe)})}catch{if(Ae(De,Ee))we=pe.lockFailed,xe()}finally{me=!1}},async reconcile(){if(Re||be||!he.ok)return;let Pe=he.pending?.requestId??n(ye.runs).find((ze)=>!!ze?.requestId)?.requestId;if(!Pe)return;let De=je,Ee=fe();Re=!0,be=!0,xe();try{_e(await C.client.getProject(ge),Pe,Ee,De)}catch{if(Ae(De,Ee))we=pe.readFailed,xe()}finally{if(Re=!1,Se&&De===je)be=!1,xe()}},activate(){Se=!0},deactivate(){Se=!1,je+=1,ue=!1,be=!1,xe()}}}import{useEffect as Je,useLayoutEffect as Ot,useMemo as Ft,useRef as $t,useSyncExternalStore as zt}from"react";var s="uibot:creation-run-changed",Wt=typeof window>"u"?Je:Ot;function Bt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Vt(){let C=typeof navigator>"u"?void 0:navigator.locks;return C?.request?C:void 0}function ce(C){let pe=$t(C);pe.current=C;let{storageKey:y}=C,ge=C.project.id,fe=Ft(()=>p({client:{startRun:(ye,he)=>pe.current.client.startRun(ye,he),getProject:(ye,he)=>pe.current.client.getProject(ye,he)},project:C.project,storageKey:y,storage:C.storage??Bt(),locks:C.locks??Vt(),authority:()=>pe.current.authority?.()??"",broadcast:()=>{if(typeof window<"u")window.dispatchEvent(new Event(s))},...C.locale?{locale:C.locale}:{},onProject:(ye,he)=>pe.current.onProject(ye,he),onWritingBlocked:(ye)=>pe.current.onPending?.(ye)}),[y,ge]);Je(()=>{if(fe.activate(),typeof window>"u")return()=>fe.deactivate();let ye=()=>fe.refresh();return window.addEventListener(s,ye),window.addEventListener("storage",ye),ye(),()=>{window.removeEventListener(s,ye),window.removeEventListener("storage",ye),fe.deactivate()}},[fe]),Wt(()=>{fe.setProject(C.project)},[fe,C.project]);let ve=zt(fe.subscribe,fe.getState,()=>u);return Je(()=>{pe.current.onPending?.(fe.getState().writingBlocked)},[fe]),{...ve,start:fe.start,reconcile:fe.reconcile}}var _t={zh:{conflict:"版本已更新。你的草稿仍保留;重新读取后再编辑。",requestFailed:"作品请求失败,请稍后重试。",capabilitiesRefreshed:"工件能力已刷新。",domainGone:(C)=>`所选工件类型“${C}”已不可用,请重新选择。`,refreshFailed:"无法刷新工件能力,请稍后重试。",projectReadFailed:"无法读取所选作品。",rereadFailed:"无法重新读取作品。",saveInProgress:"保存正在进行中",editorClosed:"编辑器已关闭",saveUnreadable:"保存结果无法读取"},en:{conflict:"This revision changed. Your draft is kept; reread before editing again.",requestFailed:"The creation request failed. Try again later.",capabilitiesRefreshed:"Artifact capabilities refreshed.",domainGone:(C)=>`The selected artifact type "${C}" is no longer available; choose another.`,refreshFailed:"Could not refresh artifact capabilities. Try again later.",projectReadFailed:"Could not read the selected project.",rereadFailed:"Could not reread the project.",saveInProgress:"A save is already in progress",editorClosed:"The editor is closed",saveUnreadable:"The saved revision could not be read"}};function at(C){return C instanceof Error&&"status"in C&&C.status===409}function Ye(C){return C.revisions.find((pe)=>pe.id===C.currentRevisionId)}function f(C){let pe=new Set;return C.filter((y)=>{if(!y.enabled||!y.formats.includes("html")||pe.has(y.artifactKind))return!1;return pe.add(y.artifactKind),!0})}function st(C){return{id:C.id,title:C.title,updatedAt:C.updatedAt,artifactCount:C.artifacts.length}}var g=Object.freeze({status:"loading",capabilities:{domains:[]},domains:[],projects:[],project:null,selectedArtifact:void 0,selectedRevision:void 0,selectedDomainKind:"",enabledDomain:void 0,capabilitiesFresh:!1,refreshingDomains:!1,busy:!1,message:"",conflict:!1,editorDirty:!1,editorResetGeneration:0,exportRevisionId:"",generationPending:!1});function m(C){let pe=_t[C.locale??"en"],{client:y}=C,ge=C.newRequestId??(()=>crypto.randomUUID()),fe=new Set,ve=!0,ye=!1,he=null,ue={status:"loading",capabilities:{domains:[]},domains:[],projects:[],project:null,selectedArtifactId:"",selectedDomainKind:"",capabilitiesFresh:!1,refreshingDomains:!1,busy:!1,message:"",conflict:!1,editorDirty:!1,editorResetGeneration:0,exportRevisionId:"",pending:{html:!1,reference:!1}},be=Re();function we(de){return(Ce)=>de.some((xe)=>xe.artifactKind===Ce.kind)&&!!Ye(Ce)}function Se(de,Ce){let xe=we(ue.domains);return de?.artifacts.find((Te)=>Te.id===Ce&&xe(Te))??de?.artifacts.find(xe)}function Re(){let{selectedArtifactId:de,pending:Ce,...xe}=ue,Te=Se(ue.project,de);return{...xe,selectedArtifact:Te,selectedRevision:Te?Ye(Te):void 0,enabledDomain:ue.domains.find((Ae)=>Ae.artifactKind===ue.selectedDomainKind),generationPending:Ce.html||Ce.reference}}function me(de){ue={...ue,...de},be=Re();for(let Ce of fe)Ce()}function je(de){return{project:de,projects:ue.projects.map((Ce)=>Ce.id===de.id?st(de):Ce)}}let Ie=(de)=>at(de)?pe.conflict:pe.requestFailed;return{getState:()=>be,subscribe(de){return fe.add(de),()=>fe.delete(de)},activate(){let de=!1;return ve=!0,me({status:"loading"}),Promise.all([y.getConfiguration(),y.listProjects()]).then(async([Ce,xe])=>{if(de||!ve)return;let Te=f(Ce.domains);me({capabilities:Ce,domains:Te,capabilitiesFresh:!0,selectedDomainKind:Te.some((Ue)=>Ue.artifactKind===ue.selectedDomainKind)?ue.selectedDomainKind:Te[0]?.artifactKind??"",projects:xe.projects});let Ae=xe.projects[0];if(Ae){let Ue=await y.getProject(Ae.id);if(!de&&ve)me({project:Ue,selectedArtifactId:Ue.artifacts[0]?.id??""})}if(!de&&ve)me({status:"ready"})}).catch(()=>{if(de||!ve)return;me({status:"failed"})}),()=>{de=!0,ve=!1}},async refreshDomains(){if(ue.refreshingDomains||ue.editorDirty||be.generationPending)return;me({refreshingDomains:!0,capabilitiesFresh:!1,message:""});try{let de=await y.getConfiguration();if(!ve)return;let Ce=f(de.domains);me({capabilities:de,domains:Ce,capabilitiesFresh:!0,message:Ce.some((xe)=>xe.artifactKind===ue.selectedDomainKind)?pe.capabilitiesRefreshed:pe.domainGone(ue.selectedDomainKind)})}catch{if(ve)me({message:pe.refreshFailed})}finally{if(ve)me({refreshingDomains:!1})}},async selectProject(de){me({busy:!0,message:""});try{let Ce=await y.getProject(de);if(!ve)return;let xe=Ce.artifacts[0]?.id??"",Te=Ce.id===ue.project?.id&&Se(Ce,xe)?.id===be.selectedArtifact?.id;me({...Te?{}:{editorDirty:!1},project:Ce,selectedArtifactId:xe,exportRevisionId:"",conflict:!1})}catch{if(ve)me({message:pe.projectReadFailed})}finally{if(ve)me({busy:!1})}},async createProject(de){let Ce=de.trim();if(!Ce||ye||be.generationPending)return!1;if(he?.title!==Ce)he={title:Ce,requestId:ge()};let xe=he;ye=!0,me({busy:!0,message:""});try{let Te=await y.createProject(xe);if(!ve)return!1;he=null;let Ae=Te.id===ue.project?.id&&Te.artifacts.find(we(ue.domains))?.id===be.selectedArtifact?.id;return me({...Ae?{}:{editorDirty:!1},project:Te,selectedArtifactId:"",projects:[st(Te),...ue.projects.filter((Ue)=>Ue.id!==Te.id)]}),!0}catch(Te){if(ve)me({message:Ie(Te)});return!1}finally{if(ye=!1,ve)me({busy:!1})}},async appendArtifact(de){let{project:Ce}=ue,xe=be.enabledDomain,Te=de.title.trim();if(!Ce||!xe||!ue.capabilitiesFresh||ue.refreshingDomains||!Te||ye||be.generationPending)return!1;ye=!0,me({busy:!0,message:""});try{let Ae=await y.appendArtifact(Ce.id,{title:Te,kind:xe.artifactKind,source:de.source});if(!ve)return!1;let Ue=Ae.artifacts.at(-1)?.id??"";return me({...Ue!==be.selectedArtifact?.id?{editorDirty:!1}:{},...je(Ae),selectedArtifactId:Ue,exportRevisionId:""}),!0}catch(Ae){if(ve)me({message:Ie(Ae)});return!1}finally{if(ye=!1,ve)me({busy:!1})}},async saveRevision(de){if(ye||!ve||ue.refreshingDomains||be.generationPending)throw Error(pe.saveInProgress);ye=!0,me({busy:!0,message:""});try{let Ce=await y.saveRevision(de.projectId,de.artifactId,{expectedRevisionId:de.expectedRevisionId,source:de.source});if(!ve)throw Error(pe.editorClosed);me({...je(Ce),conflict:!1});let xe=Ce.artifacts.find((Ae)=>Ae.id===de.artifactId),Te=xe&&Ye(xe);if(!Te)throw Error(pe.saveUnreadable);return{revisionId:Te.id,number:Te.number,content:Te.source.content}}catch(Ce){if(ve)me({...at(Ce)?{conflict:!0}:{},message:Ie(Ce)});throw Error(Ie(Ce))}finally{if(ye=!1,ve)me({busy:!1})}},async rereadProject(){let{project:de}=ue;if(!de||ue.busy)return;me({busy:!0,message:""});try{let Ce=await y.getProject(de.id);if(!ve)return;me({editorDirty:!1,...je(Ce),selectedArtifactId:Ce.artifacts.some((xe)=>xe.id===ue.selectedArtifactId)?ue.selectedArtifactId:Ce.artifacts[0]?.id??"",editorResetGeneration:ue.editorResetGeneration+1,conflict:!1})}catch{if(ve)me({message:pe.rereadFailed})}finally{if(ve)me({busy:!1})}},applyProject(de,Ce){me({...Ce&&Ce!==ue.selectedArtifactId?{editorDirty:!1}:{},...je(de),...Ce?{selectedArtifactId:Ce}:{}})},selectDomain(de){me({selectedDomainKind:de,message:""})},selectExportRevision(de){me({exportRevisionId:de})},setEditorDirty(de){if(ue.editorDirty!==de)me({editorDirty:de})},setGenerationPending(de,Ce){if(ue.pending[de]!==Ce)me({pending:{...ue.pending,[de]:Ce}})}}}import{useEffect as Mt,useMemo as Gt,useRef as Ht,useSyncExternalStore as Jt}from"react";function le(C){let pe=Ht(C);pe.current=C;let y=Gt(()=>m({client:{getConfiguration:()=>pe.current.client.getConfiguration(),listProjects:()=>pe.current.client.listProjects(),getProject:(fe)=>pe.current.client.getProject(fe),createProject:(fe)=>pe.current.client.createProject(fe),appendArtifact:(fe,ve)=>pe.current.client.appendArtifact(fe,ve),saveRevision:(fe,ve,ye)=>pe.current.client.saveRevision(fe,ve,ye)},...C.locale?{locale:C.locale}:{},...C.newRequestId?{newRequestId:C.newRequestId}:{}}),[]);return Mt(()=>y.activate(),[y]),{...Jt(y.subscribe,y.getState,()=>g),refreshDomains:y.refreshDomains,selectProject:y.selectProject,createProject:y.createProject,appendArtifact:y.appendArtifact,saveRevision:y.saveRevision,rereadProject:y.rereadProject,applyProject:y.applyProject,selectDomain:y.selectDomain,selectExportRevision:y.selectExportRevision,setEditorDirty:y.setEditorDirty,setGenerationPending:y.setGenerationPending}}export{t,P,v,x,h,k,o,T,r,w,R,I,j,S,D,A,E,L,U,N,O,q,K,F,B,z,W,V,_,M,G,H,J,Y,X,Z,Q,ee,te,ne,oe,re,ie,ae,c,l,b,d,i,se,a,n,u,p,s,ce,f,g,m,le};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e extends Error{code;status;constructor(i,u,p){super(u);this.code=i;this.status=p;this.name="CreationApiError"}}function
|
|
2
|
-
export{e,
|
|
1
|
+
class e extends Error{code;status;constructor(i,u,p){super(u);this.code=i;this.status=p;this.name="CreationApiError"}}function C(i){return`/projects/${encodeURIComponent(i)}`}function y(i){let u=i.base.replace(/\/$/,""),p=i.fetch??((t,n)=>globalThis.fetch(t,n));async function r(t,n={}){let d=n.method??(n.body===void 0?"GET":"POST"),s=await p(`${u}${t}`,{method:d,headers:{accept:"application/json",...n.body===void 0?{}:{"content-type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.signal?{signal:n.signal}:{}}),g=await s.text(),a=null;if(g)try{a=JSON.parse(g)}catch{a=null}if(!s.ok){let c=a?.error;throw new e(typeof c?.code==="string"?c.code:"request-failed",typeof c?.message==="string"?c.message:`Request failed (${s.status})`,s.status)}if(a===null)throw new e("invalid-response","Empty or non-JSON response",s.status);return a}let o=C;return{request:r,getConfiguration:(t)=>r(i.configurationPath??"",{method:"GET",...t?{signal:t}:{}}),listProjects:(t)=>r("/projects",{method:"GET",...t?{signal:t}:{}}),createProject:(t)=>r("/projects",{body:t}),getProject:(t,n)=>r(o(t),{method:"GET",...n?{signal:n}:{}}),addSource:(t,n)=>r(`${o(t)}/sources`,{body:n}),appendArtifact:(t,n)=>r(`${o(t)}/artifacts`,{body:n}),saveRevision:(t,n,d)=>r(`${o(t)}/artifacts/${encodeURIComponent(n)}/revisions`,{body:d}),startRun:(t,n)=>r(`${o(t)}/runs`,{body:n}),cancelRun:(t,n)=>r(`${o(t)}/runs/${encodeURIComponent(n)}/cancel`,{body:{}}),resumeRun:(t,n)=>r(`${o(t)}/runs/${encodeURIComponent(n)}/resume`,{body:{}})}}
|
|
2
|
+
export{e,C,y};
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t,
|
|
1
|
+
import{t,P,v,x,h,k,o,T,r,w,R,I,j,S,D,A,E,L,U,N,O,q,K,F,B,z,W,V,_,M,G,H,J,Y,X,Z,Q,ee,te,ne,oe,re,ie,ae,c,l,b,d,i,se,a,n,u,p,s,ce,f,g,m,le}from"./index-31w4ne7n.js";import{e,C,y}from"./index-yg2ewbrj.js";export{R as Badge,w as Button,t as CREATION_KIT_API,s as CREATION_RUN_CHANGED_EVENT,u as CREATION_RUN_SERVER_STATE,g as CREATION_WORKSPACE_INITIAL_STATE,D as Checkbox,A as Collapsible,L as CollapsibleContent,E as CollapsibleTrigger,e as CreationApiError,o as CreationLocaleProvider,v as CreationTransportProvider,r as CreationUiProvider,i as DeckViewer,Q as Dialog,te as DialogContent,ie as DialogDescription,oe as DialogFooter,ne as DialogHeader,re as DialogTitle,ee as DialogTrigger,j as Input,I as Label,Y as Popover,Z as PopoverContent,X as PopoverTrigger,ae as Prompt,U as ScrollArea,N as ScrollBar,O as Select,F as SelectContent,B as SelectItem,q as SelectTrigger,K as SelectValue,z as Tabs,_ as TabsContent,W as TabsList,V as TabsTrigger,S as Textarea,M as Tooltip,J as TooltipContent,G as TooltipProvider,H as TooltipTrigger,b as buildPrintShellHtml,h as cn,y as createCreationClient,P as createCreationKindRegistry,p as createCreationRunController,m as createCreationWorkspaceController,k as creationErrorStatus,C as creationProjectPath,a as creationRunStatus,f as htmlAuthoringDomains,c as isDeck,l as parseDeck,se as presentationDeckPlugin,d as printDeckToPdf,n as unresolvedCreationRuns,T as useCreationLocale,ce as useCreationRun,x as useCreationTransport,le as useCreationWorkspace};
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{o,r}from"./index-31w4ne7n.js";import"./index-yg2ewbrj.js";import{createElement as d}from"react";import{jsx as s}from"react/jsx-runtime";var g={Button:"button",Input:"input",Label:"label",Textarea:"textarea",DialogTitle:"h2",DialogDescription:"p"},u=new Set(["asChild","viewportProps","showCloseButton","sideOffset","align","side"]);function C(){let e=new Map;return new Proxy({},{get(v,i){let t=e.get(i);if(!t){let c=g[i]??"div";t=(l)=>{let n={};for(let[a,p]of Object.entries(l))if(!u.has(a))n[a]=p;return d(c,n)},t.displayName=i,e.set(i,t)}return t}})}function m(e){return s(r,{primitives:C(),children:s(o,{locale:e.locale??"en",children:e.children})})}export{m as PlainKitProviders,C as createPlainUi};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CreationLocale } from "./contract.js";
|
|
2
|
+
import { type CreationWorkspaceClient, type CreationWorkspaceController, type CreationWorkspaceState } from "./workspace-controller.js";
|
|
3
|
+
export interface UseCreationWorkspaceOptions {
|
|
4
|
+
client: CreationWorkspaceClient;
|
|
5
|
+
locale?: CreationLocale;
|
|
6
|
+
newRequestId?: () => string;
|
|
7
|
+
}
|
|
8
|
+
export type UseCreationWorkspaceResult = CreationWorkspaceState & Omit<CreationWorkspaceController, "getState" | "subscribe" | "activate">;
|
|
9
|
+
/**
|
|
10
|
+
* React binding for {@link createCreationWorkspaceController}: one workspace per mount (hosts key
|
|
11
|
+
* the component by identity/tenant), loaded on mount; responses arriving after unmount are ignored.
|
|
12
|
+
*/
|
|
13
|
+
export declare function useCreationWorkspace(options: UseCreationWorkspaceOptions): UseCreationWorkspaceResult;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { CreationArtifact, CreationContent, CreationDomain, CreationProject, CreationProjectSummary, CreationRevision } from "@uibot/contracts";
|
|
2
|
+
import type { CreationArtifactInput } from "./client.js";
|
|
3
|
+
import type { CreationLocale } from "./contract.js";
|
|
4
|
+
/**
|
|
5
|
+
* Manual HTML creation workspace shared by hosts (ported from InfoOS, ADR 0012 R4): project list
|
|
6
|
+
* and selection, idempotent project creation, artifact append, compare-and-swap revision saves
|
|
7
|
+
* with an explicit conflict/reread step, and capability refresh. Generation runs are owned by
|
|
8
|
+
* {@link createCreationRunController}; their pending state is reported here so manual writes wait.
|
|
9
|
+
*/
|
|
10
|
+
export interface CreationWorkspaceClient {
|
|
11
|
+
getConfiguration(): Promise<CreationWorkspaceCapabilities>;
|
|
12
|
+
listProjects(): Promise<{
|
|
13
|
+
projects: CreationProjectSummary[];
|
|
14
|
+
}>;
|
|
15
|
+
getProject(projectId: string): Promise<CreationProject>;
|
|
16
|
+
createProject(input: {
|
|
17
|
+
title: string;
|
|
18
|
+
requestId: string;
|
|
19
|
+
}): Promise<CreationProject>;
|
|
20
|
+
appendArtifact(projectId: string, input: CreationArtifactInput): Promise<CreationProject>;
|
|
21
|
+
saveRevision(projectId: string, artifactId: string, input: {
|
|
22
|
+
expectedRevisionId: string;
|
|
23
|
+
source: CreationContent;
|
|
24
|
+
}): Promise<CreationProject>;
|
|
25
|
+
}
|
|
26
|
+
/** What the workspace and generation blocks read from the configuration endpoint. */
|
|
27
|
+
export interface CreationWorkspaceCapabilities {
|
|
28
|
+
domains: CreationDomain[];
|
|
29
|
+
generation?: {
|
|
30
|
+
ready: boolean;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Same shape as `HtmlSourceEditor`'s save input/result, so the editor can call it directly. */
|
|
34
|
+
export interface CreationWorkspaceSaveInput {
|
|
35
|
+
projectId: string;
|
|
36
|
+
artifactId: string;
|
|
37
|
+
expectedRevisionId: string;
|
|
38
|
+
source: CreationContent;
|
|
39
|
+
}
|
|
40
|
+
export interface CreationWorkspaceSaveResult {
|
|
41
|
+
revisionId: string;
|
|
42
|
+
number: number;
|
|
43
|
+
content: string;
|
|
44
|
+
}
|
|
45
|
+
export type CreationGenerationEntry = "html" | "reference";
|
|
46
|
+
export interface CreationWorkspaceState {
|
|
47
|
+
status: "loading" | "failed" | "ready";
|
|
48
|
+
capabilities: CreationWorkspaceCapabilities;
|
|
49
|
+
/** Enabled HTML-authoring domains, first one per artifact kind. */
|
|
50
|
+
domains: CreationDomain[];
|
|
51
|
+
projects: CreationProjectSummary[];
|
|
52
|
+
project: CreationProject | null;
|
|
53
|
+
/** The artifact the editor shows: the selected one when eligible, else the first eligible. */
|
|
54
|
+
selectedArtifact: CreationArtifact | undefined;
|
|
55
|
+
selectedRevision: CreationRevision | undefined;
|
|
56
|
+
/** Kind chosen for the next appended artifact; may name a domain that is no longer enabled. */
|
|
57
|
+
selectedDomainKind: string;
|
|
58
|
+
enabledDomain: CreationDomain | undefined;
|
|
59
|
+
/** Append needs capabilities read since the last refresh started. */
|
|
60
|
+
capabilitiesFresh: boolean;
|
|
61
|
+
refreshingDomains: boolean;
|
|
62
|
+
busy: boolean;
|
|
63
|
+
message: string;
|
|
64
|
+
conflict: boolean;
|
|
65
|
+
editorDirty: boolean;
|
|
66
|
+
/** Bumped after a reread so the host remounts the editor on the server's revision. */
|
|
67
|
+
editorResetGeneration: number;
|
|
68
|
+
/** Saved revision chosen for export; empty means the current revision. */
|
|
69
|
+
exportRevisionId: string;
|
|
70
|
+
/** Either generation entry holds the shared run reservation; manual writes wait. */
|
|
71
|
+
generationPending: boolean;
|
|
72
|
+
}
|
|
73
|
+
export interface CreationWorkspaceControllerOptions {
|
|
74
|
+
client: CreationWorkspaceClient;
|
|
75
|
+
locale?: CreationLocale;
|
|
76
|
+
newRequestId?: () => string;
|
|
77
|
+
}
|
|
78
|
+
export interface CreationWorkspaceController {
|
|
79
|
+
getState(): CreationWorkspaceState;
|
|
80
|
+
subscribe(listener: () => void): () => void;
|
|
81
|
+
/** Load capabilities and projects; the returned function ignores everything still in flight. */
|
|
82
|
+
activate(): () => void;
|
|
83
|
+
refreshDomains(): Promise<void>;
|
|
84
|
+
selectProject(projectId: string): Promise<void>;
|
|
85
|
+
/** Retries of the same title reuse one request id, so a lost response cannot create twice. */
|
|
86
|
+
createProject(title: string): Promise<boolean>;
|
|
87
|
+
appendArtifact(input: {
|
|
88
|
+
title: string;
|
|
89
|
+
source: CreationContent;
|
|
90
|
+
}): Promise<boolean>;
|
|
91
|
+
/** Rejects with a display-safe message; a 409 also raises the conflict step. */
|
|
92
|
+
saveRevision(input: CreationWorkspaceSaveInput): Promise<CreationWorkspaceSaveResult>;
|
|
93
|
+
rereadProject(): Promise<void>;
|
|
94
|
+
/** A generation run or export refresh produced this project (optionally a new artifact). */
|
|
95
|
+
applyProject(project: CreationProject, artifactId?: string): void;
|
|
96
|
+
selectDomain(kind: string): void;
|
|
97
|
+
selectExportRevision(revisionId: string): void;
|
|
98
|
+
setEditorDirty(dirty: boolean): void;
|
|
99
|
+
setGenerationPending(entry: CreationGenerationEntry, pending: boolean): void;
|
|
100
|
+
}
|
|
101
|
+
/** Enabled domains that accept HTML sources, first one per artifact kind. */
|
|
102
|
+
export declare function htmlAuthoringDomains(domains: CreationDomain[]): CreationDomain[];
|
|
103
|
+
/** Server-render and first-paint state: nothing has been read yet. */
|
|
104
|
+
export declare const CREATION_WORKSPACE_INITIAL_STATE: CreationWorkspaceState;
|
|
105
|
+
export declare function createCreationWorkspaceController(options: CreationWorkspaceControllerOptions): CreationWorkspaceController;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uibot/creation-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
"react-dom": "^19"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@uibot/contracts": "^0.
|
|
43
|
-
"@uibot/ai-chat": "^0.
|
|
42
|
+
"@uibot/contracts": "^0.7.0",
|
|
43
|
+
"@uibot/ai-chat": "^0.7.0",
|
|
44
44
|
"lucide-react": "^1.56.0",
|
|
45
45
|
"clsx": "^2.1.1",
|
|
46
46
|
"tailwind-merge": "^3.7.0"
|
package/dist/index-rep1qesa.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{e}from"./index-wsse4x6x.js";var t=1;var Me=/^[a-z][a-z0-9-]{0,39}$/;function He(g,ce,ae,C){if(ce.has(ae))throw Error(`Duplicate creation ${g} "${ae}" (plugin ${C})`);ce.add(ae)}function m(g){let ce=new Set,ae=new Map,C=new Map,se=new Set,we=[],pe=new Map;for(let le of g){if(le.kitApi!==t)throw Error(`Creation plugin "${le.id}" targets kit API ${String(le.kitApi)}, expected ${t}`);He("plugin",ce,le.id,le.id);for(let de of le.kinds??[]){if(!Me.test(de.kind))throw Error(`Invalid creation kind "${de.kind}" (plugin ${le.id})`);if(ae.has(de.kind))throw Error(`Duplicate creation kind "${de.kind}" (plugin ${le.id})`);ae.set(de.kind,de)}for(let de of le.editors??[]){let Ce=`${de.id}:${de.format}`;if(C.has(Ce))throw Error(`Duplicate creation editor "${Ce}" (plugin ${le.id})`);C.set(Ce,de)}for(let de of le.views??[])He("view",se,de.id,le.id),we.push(de);for(let de of le.projectAssets??[]){if(pe.has(de.slot))throw Error(`Duplicate creation asset slot "${de.slot}" (plugin ${le.id})`);pe.set(de.slot,de)}}let fe=[...ae.values()].sort((le,de)=>(le.order??100)-(de.order??100)||le.kind.localeCompare(de.kind));return{plugins:g,taskKind:(le)=>le?ae.get(le):void 0,taskKinds:()=>[...fe],kindOptions(le,de,Ce){let ke=le.map((be)=>({value:be.artifactKind,label:Ce?.(be)??be.title,disabled:!be.enabled})),ye=new Set(ke.map((be)=>be.value));for(let be of fe){if(ye.has(be.kind)){console.error(`Creation workbench kind "${be.kind}" shadows a server domain and is hidden`);continue}ke.push({value:be.kind,label:be.label[de]})}return ke},label:(le,de,Ce)=>ae.get(le)?.label[de]??Ce??le,editor:(le,de)=>le?C.get(`${le}:${de}`):void 0,views:(le)=>we.filter((de)=>de.match(le)),projectAssets:()=>[...pe.values()],projectAsset:(le)=>pe.get(le),parseRouteSearch(le){let de=typeof le.kind==="string"&&Me.test(le.kind)?le.kind:void 0,Ce={};for(let ke of fe){if(!ke.parseSearch)continue;Object.assign(Ce,ke.parseSearch(le))}return{...de?{kind:de}:{},extra:Ce}}}}import{createContext as nt,useContext as rt}from"react";import{jsx as it}from"react/jsx-runtime";var Je=nt(null);function b(g){return it(Je.Provider,{value:g.transport,children:g.children})}function y(){let g=rt(Je);if(!g)throw Error("useCreationTransport requires a CreationTransportProvider");return g}import{clsx as at}from"clsx";import{twMerge as st}from"tailwind-merge";function x(...g){return st(at(g))}function P(g){if(!(g instanceof Error))return;let{status:ce}=g;return typeof ce==="number"?ce:void 0}import{createContext as ct,useContext as lt}from"react";import{jsx as dt}from"react/jsx-runtime";var We=ct("en");function n(g){return dt(We.Provider,{value:g.locale,children:g.children})}function v(){return lt(We)}import{createContext as pt,useContext as ut}from"react";import{jsx as Ye}from"react/jsx-runtime";var Ge=pt(null);function r(g){return Ye(Ge.Provider,{value:g.primitives,children:g.children})}function gt(){let g=ut(Ge);if(!g)throw Error("Creation UI primitives require a CreationUiProvider");return g}function ge(g,ce){let ae=(C)=>{let se=g(gt());return Ye(se,{...C})};return ae.displayName=ce,ae}var k=ge((g)=>g.Button,"Button"),h=ge((g)=>g.Badge,"Badge"),T=ge((g)=>g.Label,"Label"),w=ge((g)=>g.Input,"Input"),S=ge((g)=>g.Textarea,"Textarea"),R=ge((g)=>g.Checkbox,"Checkbox"),I=ge((g)=>g.Collapsible,"Collapsible"),j=ge((g)=>g.CollapsibleTrigger,"CollapsibleTrigger"),D=ge((g)=>g.CollapsibleContent,"CollapsibleContent"),A=ge((g)=>g.ScrollArea,"ScrollArea"),E=ge((g)=>g.ScrollBar,"ScrollBar"),L=ge((g)=>g.Select,"Select"),N=ge((g)=>g.SelectTrigger,"SelectTrigger"),U=ge((g)=>g.SelectValue,"SelectValue"),O=ge((g)=>g.SelectContent,"SelectContent"),q=ge((g)=>g.SelectItem,"SelectItem"),F=ge((g)=>g.Tabs,"Tabs"),K=ge((g)=>g.TabsList,"TabsList"),B=ge((g)=>g.TabsTrigger,"TabsTrigger"),V=ge((g)=>g.TabsContent,"TabsContent"),z=ge((g)=>g.Tooltip,"Tooltip"),M=ge((g)=>g.TooltipProvider,"TooltipProvider"),_=ge((g)=>g.TooltipTrigger,"TooltipTrigger"),H=ge((g)=>g.TooltipContent,"TooltipContent"),J=ge((g)=>g.Popover,"Popover"),G=ge((g)=>g.PopoverTrigger,"PopoverTrigger"),W=ge((g)=>g.PopoverContent,"PopoverContent"),Y=ge((g)=>g.Dialog,"Dialog"),X=ge((g)=>g.DialogTrigger,"DialogTrigger"),Z=ge((g)=>g.DialogContent,"DialogContent"),Q=ge((g)=>g.DialogHeader,"DialogHeader"),ee=ge((g)=>g.DialogFooter,"DialogFooter"),te=ge((g)=>g.DialogTitle,"DialogTitle"),oe=ge((g)=>g.DialogDescription,"DialogDescription"),ne=ge((g)=>g.Prompt,"Prompt");var ze=/<(\/?)section\b[^>]*>/gi;function De(g,ce){let ae=new RegExp(`\\b${ce}(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`,"i").exec(g);if(!ae)return;return ae[1]??ae[2]??ae[3]??""}function ft(g){if(De(g,"data-slide")!==void 0)return!0;return/\bslide\b/i.test(De(g,"class")??"")}function Oe(g,ce){return g.exec(ce)?.[1]??""}function mt(g){return g.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function Xe(g){return mt(g.replace(/<[^>]+>/g," ")).replace(/\s+/g," ").trim()}function Ze(g){let ce=[];ze.lastIndex=0;let ae=0,C=-1;for(let se=ze.exec(g);se;se=ze.exec(g)){if(se[1]==="/"){if(ae===0)continue;if(ae-=1,ae===0&&C>=0)ce.push(g.slice(C,se.index+se[0].length)),C=-1;continue}if(ae===0){if(!ft(se[0]))continue;C=se.index}ae+=1}return ce}function c(g){return Boolean(g)&&Ze(g).length>0}var Ct=/<aside\b([^>]*)>([\s\S]*?)<\/aside>/i;function bt(g){let ce="";return{slide:g.replace(Ct,(C,se,we)=>{if(!(De(`<aside ${se}>`,"data-notes")!==void 0||/\bnotes\b/i.test(De(`<aside ${se}>`,"class")??"")))return C;return ce=Xe(we),""}),notes:ce}}function l(g){let ce=Ze(g);if(ce.length===0)return{isDeck:!1,slides:[],head:"",bodyClass:"",bodyStyle:"",title:"deck"};let ae=Oe(/<head\b[^>]*>([\s\S]*?)<\/head>/i,g),C=`<body ${Oe(/<body\b([^>]*)>/i,g)}>`,se=De(C,"class")??"",we=De(C,"style")??"",pe=Xe(Oe(/<title\b[^>]*>([\s\S]*?)<\/title>/i,ae))||"deck",fe=new Set;return{isDeck:!0,slides:ce.map((de,Ce)=>{let ke=Oe(/(<section\b[^>]*>)/i,de),ye=De(ke,"data-slide")||De(ke,"data-slide-id")||String(Ce+1),be=fe.has(ye)?`${ye}-${Ce+1}`:ye;fe.add(be);let he=Oe(/background(?:-color)?\s*:\s*([^;"']+)/i,De(ke,"style")??"").trim()||void 0,{slide:Te,notes:me}=bt(de);return{html:`<!DOCTYPE html><html><head>${ae}
|
|
2
|
-
<style>
|
|
3
|
-
html, body { margin:0; padding:0; }
|
|
4
|
-
body { display:flex; align-items:center; justify-content:center; min-height:100vh; }
|
|
5
|
-
.slide, [data-slide] { transform-origin: center center !important; }
|
|
6
|
-
</style></head><body class="${se}" style="${we}">${Te}</body></html>`,notes:me,id:be,...he?{bg:he}:{}}}),head:ae,bodyClass:se,bodyStyle:we,title:pe}}function f(g){return`<!DOCTYPE html><html><head>
|
|
7
|
-
<style>
|
|
8
|
-
@page { size: 1280px 720px; margin: 0; }
|
|
9
|
-
html, body { margin:0; padding:0; }
|
|
10
|
-
.page { width: 1280px; height: 720px; overflow: hidden; page-break-after: always; }
|
|
11
|
-
.page:last-child { page-break-after: auto; }
|
|
12
|
-
.page iframe.slide { display:block; width:100%; height:100%; border:0; }
|
|
13
|
-
</style></head><body>
|
|
14
|
-
${Array.from({length:g},(ae,C)=>`<div class="page"><iframe class="slide" data-slide-index="${C}" sandbox="allow-scripts"></iframe></div>`).join(`
|
|
15
|
-
`)}
|
|
16
|
-
<script>window.onload=()=>setTimeout(()=>window.print(),300)</script>
|
|
17
|
-
</body></html>`}function d(g,ce=(ae,C)=>window.open(ae,C)){let ae=ce("","_blank");if(!ae)return!1;ae.opener=null,ae.document.write(f(g.slides.length)),ae.document.close();let C=ae.document.querySelectorAll("iframe.slide");return g.slides.forEach((se,we)=>{let pe=C[we];if(pe)pe.srcdoc=se.html}),!0}import{ChevronLeft as yt,ChevronRight as xt,FileDown as kt,Maximize2 as vt,StickyNote as Tt}from"lucide-react";import{useEffect as Qe,useMemo as ht,useRef as Pt,useState as Be}from"react";import{jsx as Se,jsxs as Ee}from"react/jsx-runtime";var wt={empty:"No slides found (each slide must be a <section data-slide>).",prev:"Previous slide",next:"Next slide",notes:"Notes",notesTitle:"Speaker notes (N)",notesHeading:"Speaker notes",present:"Present",presentTitle:"Full screen (F)",pdfTitle:"Print to PDF",blocked:"The popup was blocked. Allow popups for this site and try again.",page:"Slide"},St={empty:"未检测到幻灯片(每页需为 <section data-slide>)。",prev:"上一页",next:"下一页",notes:"备注",notesTitle:"演讲者备注(N)",notesHeading:"演讲者备注",present:"放映",presentTitle:"全屏放映(F)",pdfTitle:"打印为 PDF",blocked:"弹窗被拦截,请允许本站弹出窗口后重试。",page:"第"},Rt={en:wt,zh:St},Ve="inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs";function i({content:g,locale:ce,active:ae}){let C=Rt[ce],se=ht(()=>l(g),[g]),[we,pe]=Be(0),[fe,le]=Be(!1),[de,Ce]=Be(""),ke=Pt(null),ye=se.slides.length,be=Math.min(we,Math.max(0,ye-1)),he=se.slides[be];if(Qe(()=>pe(0),[g]),Qe(()=>{if(!ae||ye===0)return;let Te=(me)=>{let Ae=me.target;if(Ae&&(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable))return;if(me.key==="ArrowRight"||me.key==="PageDown"||me.key===" ")me.preventDefault(),pe((ve)=>Math.min(ve+1,ye-1));else if(me.key==="ArrowLeft"||me.key==="PageUp")me.preventDefault(),pe((ve)=>Math.max(ve-1,0));else if(me.key==="Home")pe(0);else if(me.key==="End")pe(ye-1);else if(me.key.toLowerCase()==="n")le((ve)=>!ve);else if(me.key.toLowerCase()==="f")if(document.fullscreenElement)document.exitFullscreen();else ke.current?.requestFullscreen?.()};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[ae,ye]),!he)return Se("div",{className:"flex h-full items-center justify-center p-6 text-sm text-muted-foreground",children:C.empty});return Ee("div",{ref:ke,className:"flex h-full min-h-72 flex-col bg-muted/30",children:[Ee("div",{className:"relative min-h-0 flex-1",children:[Se("iframe",{title:`slide-${he.id}`,srcDoc:he.html,sandbox:"allow-scripts",className:"h-full w-full border-0 bg-white"},he.id),Se("button",{type:"button",onClick:()=>pe((Te)=>Math.max(Te-1,0)),disabled:be===0,className:"absolute left-2 top-1/2 -translate-y-1/2 rounded-full border bg-background/80 p-1.5 shadow backdrop-blur disabled:opacity-30","aria-label":C.prev,children:Se(yt,{className:"size-4"})}),Se("button",{type:"button",onClick:()=>pe((Te)=>Math.min(Te+1,ye-1)),disabled:be===ye-1,className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-full border bg-background/80 p-1.5 shadow backdrop-blur disabled:opacity-30","aria-label":C.next,children:Se(xt,{className:"size-4"})}),Ee("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full bg-foreground/80 px-2.5 py-0.5 text-xs tabular-nums text-background",children:[be+1," / ",ye]}),fe&&he.notes&&Ee("div",{className:"absolute inset-x-3 bottom-10 max-h-[40%] overflow-y-auto rounded-md border bg-background/95 p-3 text-sm shadow-lg",children:[Se("div",{className:"mb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:C.notesHeading}),he.notes]})]}),de&&Se("p",{role:"status",className:"border-t bg-background px-3 py-1 text-xs text-destructive",children:de}),Ee("div",{className:"flex items-center gap-2 border-t bg-background px-3 py-2",children:[Se("div",{className:"flex min-w-0 flex-1 gap-1.5 overflow-x-auto",children:se.slides.map((Te,me)=>Se("button",{type:"button",onClick:()=>pe(me),"aria-label":`${C.page} ${me+1}`,"aria-current":me===be?"true":void 0,...Te.bg?{style:{background:Te.bg}}:{},className:`flex size-7 shrink-0 items-center justify-center rounded border text-[11px] tabular-nums ${me===be?"border-primary ring-2 ring-primary/30":"text-muted-foreground hover:border-foreground/30"}`,children:me+1},Te.id))}),Ee("button",{type:"button",onClick:()=>le((Te)=>!Te),className:`${Ve} ${fe?"border-primary bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent"}`,title:C.notesTitle,children:[Se(Tt,{className:"size-3.5"}),C.notes]}),Ee("button",{type:"button",onClick:()=>{if(!document.fullscreenElement)ke.current?.requestFullscreen?.()},className:`${Ve} text-muted-foreground hover:bg-accent`,title:C.presentTitle,children:[Se(vt,{className:"size-3.5"}),C.present]}),Ee("button",{type:"button",onClick:()=>Ce(d(se)?"":C.blocked),className:`${Ve} text-muted-foreground hover:bg-accent`,title:C.pdfTitle,children:[Se(kt,{className:"size-3.5"}),"PDF"]})]})]})}var re={id:"presentation-deck",version:"1.0.0",kitApi:t,views:[{id:"slides",label:{zh:"幻灯片",en:"Slides"},match:(g)=>g.artifactKind==="presentation"&&g.format==="html"&&c(g.content),View:i}]};var It=["queued","running","interrupted","completed","failed","cancelled","conflict"];function a(g){if(!g||typeof g!=="object"||Array.isArray(g))return"unknown";if(typeof g.status!=="string"||!It.includes(g.status))return"unknown";if(g.error?.code==="inference-outcome-unknown")return"unknown";let ce=g.modelRequests;if(ce!==void 0){if(!Array.isArray(ce))return"unknown";for(let ae of ce){if(!ae||typeof ae!=="object"||Array.isArray(ae))return"unknown";let C=ae;if(typeof C.requestId!=="string"||!C.requestId||C.purpose!=="generation"&&C.purpose!=="requirement-review"||typeof C.dispatchedAt!=="string"||!C.dispatchedAt||C.dispatched!==void 0&&typeof C.dispatched!=="boolean"||typeof C.outcome!=="string"||!["pending","completed","failed","unknown"].includes(C.outcome))return"unknown";if(C.outcome==="unknown")return"unknown";if(C.outcome==="pending"&&!["queued","running","interrupted"].includes(g.status))return"unknown"}}return g.status}function o(g=[]){if(!Array.isArray(g))return[g];return g.filter((ce)=>["queued","running","interrupted","unknown"].includes(a(ce)))}var Dt={zh:{noRecord:"尚未读到原请求记录;不会重新发送。",unknown:"原请求结果未知;不会重新发送。",settled:"原请求结果已确认。",running:"原请求仍在进行中。",storageFailed:"未发送生成请求:无法保存原请求核对记录。",rejected:"生成请求未被接受;请检查当前版本和生成能力后重新发起。",noLocks:"未发送生成请求:当前浏览器无法锁定项目生成操作。",lockFailed:"未能取得项目生成锁;请稍后核对原请求状态。",readFailed:"状态读取失败;保留原请求并稍后只读核对。",unreadable:"无法读取原请求核对记录;生成已禁用。"},en:{noRecord:"The original request is not recorded yet; it will not be sent again.",unknown:"The original request's outcome is unknown; it will not be sent again.",settled:"The original request's outcome is confirmed.",running:"The original request is still in progress.",storageFailed:"Not sent: the request record could not be saved.",rejected:"The request was not accepted; check the current version and generation, then try again.",noLocks:"Not sent: this browser cannot lock project generation.",lockFailed:"Could not take the project generation lock; check the original request later.",readFailed:"Reading the status failed; the original request is kept for a later check.",unreadable:"The request record cannot be read; generation is disabled."}},u=Object.freeze({pending:!0,sending:!1,checking:!1,writingBlocked:!0,canReconcile:!1,message:""});function At(g){return g instanceof e&&(g.status===422&&["invalid-input","invalid-format","unknown-domain"].includes(g.code)||g.status===409&&["revision-conflict","format-conflict","domain-disabled","brand-conflict"].includes(g.code)||g.status===503&&g.code==="model-unavailable")}function Le(g,ce,ae){if(!g)return{ok:!1,pending:null};try{let C=g.getItem(ce);if(C===null)return{ok:!0,pending:null};let se=JSON.parse(C);if(!se||se.version!==1||se.projectId!==ae||typeof se.requestId!=="string"||!se.requestId||typeof se.kind!=="string"||!se.kind||!["new","rewrite"].includes(se.mode))return{ok:!1,pending:null};if(se.mode==="rewrite"&&(typeof se.artifactId!=="string"||!se.artifactId||typeof se.expectedRevisionId!=="string"||!se.expectedRevisionId))return{ok:!1,pending:null};if(se.reference&&(typeof se.reference.artifactId!=="string"||!se.reference.artifactId||typeof se.reference.revisionId!=="string"||!se.reference.revisionId))return{ok:!1,pending:null};return{ok:!0,pending:se}}catch{return{ok:!1,pending:null}}}function p(g){let ce=Dt[g.locale??"en"],ae=g.storageKey,C=g.project.id,se=g.authority??(()=>""),we=g.newRequestId??(()=>crypto.randomUUID()),pe=g.project,fe=Le(g.storage,ae,C),le=!1,de=!1,Ce="",ke=!0,ye=!1,be=!1,he=0,Te=new Set,me=Ae();function Ae(){let ue=o(pe.runs);return{pending:!fe.ok||!!fe.pending||ue.length>0||le,sending:le,checking:de,writingBlocked:le||!!fe.pending||ue.length>0,canReconcile:fe.ok&&(!!fe.pending||ue.some((xe)=>!!xe?.requestId)),message:!fe.ok?ce.unreadable:Ce}}function ve(){let ue=Ae();if(JSON.stringify(ue)===JSON.stringify(me))return;let xe=ue.writingBlocked!==me.writingBlocked;if(me=ue,xe)g.onWritingBlocked?.(ue.writingBlocked);for(let Pe of Te)Pe()}function $e(ue){if(JSON.stringify(ue)===JSON.stringify(fe))return;fe=ue,ve()}function Ne(ue,xe){return ke&&ue===he&&se()===xe}function et(ue){let xe=Le(g.storage,ae,C);if(xe.ok&&xe.pending?.requestId===ue){try{g.storage?.removeItem(ae)}catch{}$e(Le(g.storage,ae,C)),g.broadcast?.()}}function Ke(ue,xe,Pe,Ue){if(!Ne(Ue,Pe))return;let Ie=ue.runs?.find((Fe)=>Fe?.requestId===xe);if(!Ie){Ce=ce.noRecord,ve();return}let je=a(Ie),Re=["completed","failed","cancelled","conflict"].includes(je);if(Re){try{g.storage?.removeItem(ae)}catch{}$e(Le(g.storage,ae,C)),g.broadcast?.()}Ce=je==="unknown"?ce.unknown:Re?ce.settled:ce.running,pe=ue,ve(),g.onProject?.(ue,je==="completed"?Ie.artifactId:void 0)}async function tt(ue){if(me.pending||ye)return;let xe=Le(g.storage,ae,C);if(!xe.ok||xe.pending||o(pe.runs).length){$e(xe);return}let Pe=we(),Ue={version:1,projectId:C,requestId:Pe,kind:ue.kind,mode:ue.artifactId?"rewrite":"new",...ue.artifactId?{artifactId:ue.artifactId,expectedRevisionId:ue.expectedRevisionId}:{},...ue.reference?{reference:ue.reference}:{}};try{let Re=JSON.stringify(Ue);if(g.storage?.setItem(ae,Re),!g.storage||g.storage.getItem(ae)!==Re)throw Error("storage-readback")}catch{fe=Le(g.storage,ae,C),Ce=ce.storageFailed,ve();return}ye=!0,le=!0,fe={ok:!0,pending:Ue},ve(),g.broadcast?.();let Ie=he,je=se();try{let Re=await g.client.startRun(C,{...ue,requestId:Pe});Ke(Re,Pe,je,Ie)}catch(Re){if(!Ne(Ie,je))return;let Fe=At(Re);if(Re instanceof e&&Re.status===404&&Re.code==="not-found")try{let qe=await g.client.getProject(C);if(!Ne(Ie,je))return;if(qe.id===C){if(qe.runs?.some((ot)=>ot?.requestId===Pe)){Ke(qe,Pe,je,Ie);return}pe=qe,g.onProject?.(qe),Fe=!0}}catch{}if(Fe)et(Pe),Ce=ce.rejected;else Ce=ce.unknown;ve()}finally{if(ye=!1,ke&&Ie===he)le=!1,ve()}}return{getState:()=>me,subscribe(ue){return Te.add(ue),()=>Te.delete(ue)},setProject(ue){if(ue.id!==C)return;pe=ue,ve()},refresh(){$e(Le(g.storage,ae,C))},async start(ue){if(me.pending||ye||be)return;if(!g.locks){Ce=ce.noLocks,ve();return}let xe=he,Pe=se();be=!0;try{await g.locks.request(ae,async()=>{if(!Ne(xe,Pe))return;await tt(ue)})}catch{if(Ne(xe,Pe))Ce=ce.lockFailed,ve()}finally{be=!1}},async reconcile(){if(ye||de||!fe.ok)return;let ue=fe.pending?.requestId??o(pe.runs).find((Ue)=>!!Ue?.requestId)?.requestId;if(!ue)return;let xe=he,Pe=se();ye=!0,de=!0,ve();try{Ke(await g.client.getProject(C),ue,Pe,xe)}catch{if(Ne(xe,Pe))Ce=ce.readFailed,ve()}finally{if(ye=!1,ke&&xe===he)de=!1,ve()}},activate(){ke=!0},deactivate(){ke=!1,he+=1,le=!1,de=!1,ve()}}}import{useEffect as _e,useLayoutEffect as jt,useMemo as Et,useRef as Lt,useSyncExternalStore as Nt}from"react";var s="uibot:creation-run-changed",Ut=typeof window>"u"?_e:jt;function qt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Ot(){let g=typeof navigator>"u"?void 0:navigator.locks;return g?.request?g:void 0}function ie(g){let ce=Lt(g);ce.current=g;let{storageKey:ae}=g,C=g.project.id,se=Et(()=>p({client:{startRun:(pe,fe)=>ce.current.client.startRun(pe,fe),getProject:(pe,fe)=>ce.current.client.getProject(pe,fe)},project:g.project,storageKey:ae,storage:g.storage??qt(),locks:g.locks??Ot(),authority:()=>ce.current.authority?.()??"",broadcast:()=>{if(typeof window<"u")window.dispatchEvent(new Event(s))},...g.locale?{locale:g.locale}:{},onProject:(pe,fe)=>ce.current.onProject(pe,fe),onWritingBlocked:(pe)=>ce.current.onPending?.(pe)}),[ae,C]);_e(()=>{if(se.activate(),typeof window>"u")return()=>se.deactivate();let pe=()=>se.refresh();return window.addEventListener(s,pe),window.addEventListener("storage",pe),pe(),()=>{window.removeEventListener(s,pe),window.removeEventListener("storage",pe),se.deactivate()}},[se]),Ut(()=>{se.setProject(g.project)},[se,g.project]);let we=Nt(se.subscribe,se.getState,()=>u);return _e(()=>{ce.current.onPending?.(se.getState().writingBlocked)},[se]),{...we,start:se.start,reconcile:se.reconcile}}export{t,m,b,y,x,P,n,v,r,k,h,T,w,S,R,I,j,D,A,E,L,N,U,O,q,F,K,B,V,z,M,_,H,J,G,W,Y,X,Z,Q,ee,te,oe,ne,c,l,f,d,i,re,a,o,u,p,s,ie};
|