@blocklet/pages-kit-inner-components 0.6.71 → 0.6.73
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/lib/cjs/add-component.js +12 -12
- package/lib/cjs/chunks/{draft-data-DfZ81oCU.js → draft-data-1hI-ev3X.js} +1 -1
- package/lib/cjs/chunks/{home-CP3WKJ_e.js → home-ymdnbwRQ.js} +2 -2
- package/lib/cjs/chunks/{index-BqynZDZ3.js → index-BAiZumV7.js} +1 -1
- package/lib/cjs/chunks/{publish-button-t3lAZwFy.js → publish-button-45a3egG-.js} +1 -1
- package/lib/cjs/chunks/{site-state-BRYYpS9Q.js → site-state-CcYU6tKv.js} +1 -1
- package/lib/cjs/chunks/state-BAjDjwwp.js +1 -0
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/locales.js +2 -2
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +3 -3
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/add-component.js +274 -242
- package/lib/es/chunks/{draft-data-BtzZ0_tq.js → draft-data--WtLtXxy.js} +1 -1
- package/lib/es/chunks/{home-DBOWtpCK.js → home-BIH-BNIG.js} +3 -3
- package/lib/es/chunks/{index-CjNVgrdz.js → index-Cj977HLf.js} +1 -1
- package/lib/es/chunks/{publish-button-CFzWcpJ3.js → publish-button-Dn3ikSo5.js} +3 -3
- package/lib/es/chunks/{site-state-DYm1fKT3.js → site-state-BXM-5tZw.js} +5 -1
- package/lib/es/chunks/state-DS2djQbR.js +873 -0
- package/lib/es/home.js +3 -3
- package/lib/es/locales.js +20 -4
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +829 -799
- package/lib/es/site-state.js +1 -1
- package/package.json +11 -11
- package/lib/cjs/chunks/state-BP5DoD6I.js +0 -1
- package/lib/es/chunks/state-Biqa_a5U.js +0 -685
package/lib/cjs/add-component.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),k=require("./chunks/state-BAjDjwwp.js"),X=require("@arcblock/ux/lib/Empty"),O=require("@arcblock/ux/lib/Locale/context"),A=require("@iconify-icon/react"),Y=require("@mui/icons-material/Check"),e=require("@mui/material"),N=require("ahooks"),f=require("react"),T=require("./chunks/index-BAiZumV7.js"),h=require("@arcblock/ux/lib/Theme");require("@blocklet/pages-kit/builtin/color-picker");require("@blocklet/pages-kit/utils/style");require("@emotion/css");require("lodash/without");const m=require("@mui/material/colors");require("@blocklet/pages-kit/builtin/uploader");require("react-use");require("lodash/cloneDeep");require("@dnd-kit/core");require("@dnd-kit/sortable");require("@mui/icons-material");require("@dnd-kit/utilities");require("@mui/lab");require("immer");require("lodash/omit");require("react-router-dom");require("@arcblock/ux/lib/Button");require("is-uri");require("@arcblock/ux/lib/Toast");require("@mui/material/Tooltip");require("@mui/icons-material/KeyboardArrowLeft");const K=require("@mui/material/Box");require("@mui/material/DialogTitle");require("@mui/material/IconButton");require("@mui/material/Dialog");require("@mui/material/useMediaQuery");const J=require("@emotion/react");require("@mui/material/Alert");require("@mui/material/AlertTitle");require("react-error-boundary");require("ufo");require("lodash/isEmpty");require("yaml");require("@mui/material/Typography");require("joi");const E=require("@blocklet/aigne-hub/api"),Z=require("@blocklet/js-sdk");require("@mui/x-date-pickers");require("@mui/x-date-pickers/AdapterDayjs");require("@mui/x-date-pickers/LocalizationProvider");require("circular-natal-horoscope-js/dist");const ee=require("dayjs"),te=require("dayjs/plugin/timezone"),oe=require("dayjs/plugin/utc");require("fast-deep-equal");require("lodash/isNil");require("tz-lookup");require("@mui/icons-material/CheckCircleOutline");require("lodash/uniq");require("lodash/get");require("lodash/set");const D=require("@blocklet/pages-kit/utils/common"),re=require("@blocklet/pages-kit/components"),R=t=>t&&t.__esModule?t:{default:t},G=R(X),ie=R(Y),ne=R(K),F=R(ee),se=R(te),ae=R(oe);m.red[300],m.pink[300],m.purple[300],m.indigo[300],m.blue[300],m.cyan[300],m.teal[300],m.green[300],m.lime[300],m.yellow[300],m.amber[300],m.orange[300],m.brown[300],m.grey[300],m.blueGrey[300];h.styled(e.Box)`
|
|
2
2
|
.color-item {
|
|
3
3
|
position: relative;
|
|
4
4
|
}
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
top: 0;
|
|
43
43
|
transform: translateY(-50%);
|
|
44
44
|
}
|
|
45
|
-
`;const le=
|
|
45
|
+
`;const le=f.createContext({embed:!1}),{Provider:ue}=le;f.createContext(void 0);E.createStatusApi({axios:k.api,path:"/api/ai/status"});E.createStatusApi({axios:k.api,path:"/api/ai/agent-status"});E.createTextCompletionApi({fetch:Z.createFetch(),path:"/api/ai/completions"});F.default.extend(ae.default);F.default.extend(se.default);h.styled(e.Box)`
|
|
46
46
|
flex-grow: 1;
|
|
47
47
|
display: flex;
|
|
48
48
|
flex-direction: column;
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
`;
|
|
148
|
+
`;f.createContext({});h.styled(e.Box)`
|
|
149
149
|
display: flex;
|
|
150
150
|
flex-direction: column;
|
|
151
151
|
flex: 1;
|
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
border-radius: 12px;
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
-
`;
|
|
160
|
+
`;h.styled(e.Box)`
|
|
161
161
|
background: #fbfbfb;
|
|
162
162
|
border: 1px solid #f6f6f6;
|
|
163
163
|
border-radius: 4px;
|
|
@@ -178,7 +178,7 @@
|
|
|
178
178
|
color: #25292f;
|
|
179
179
|
cursor: pointer;
|
|
180
180
|
}
|
|
181
|
-
`;
|
|
181
|
+
`;h.styled(ne.default)`
|
|
182
182
|
background: #f6f2ff;
|
|
183
183
|
margin-bottom: 20px;
|
|
184
184
|
|
|
@@ -198,7 +198,7 @@
|
|
|
198
198
|
color: #9397a1;
|
|
199
199
|
margin-top: 4px;
|
|
200
200
|
}
|
|
201
|
-
`;
|
|
201
|
+
`;h.styled(e.Box)`
|
|
202
202
|
display: block;
|
|
203
203
|
padding: 16px;
|
|
204
204
|
text-decoration: none;
|
|
@@ -232,7 +232,7 @@
|
|
|
232
232
|
.MuiMenu-root {
|
|
233
233
|
z-index: 13010 !important;
|
|
234
234
|
}
|
|
235
|
-
`;
|
|
235
|
+
`;h.styled(e.Box)`
|
|
236
236
|
display: flex;
|
|
237
237
|
flex-direction: column;
|
|
238
238
|
flex: 1;
|
|
@@ -244,7 +244,7 @@
|
|
|
244
244
|
border-radius: 12px;
|
|
245
245
|
}
|
|
246
246
|
}
|
|
247
|
-
`;
|
|
247
|
+
`;h.styled(e.Box)`
|
|
248
248
|
background: #fbfbfb;
|
|
249
249
|
border: 1px solid #f6f6f6;
|
|
250
250
|
border-radius: 4px;
|
|
@@ -267,7 +267,7 @@
|
|
|
267
267
|
color: #25292f;
|
|
268
268
|
cursor: pointer;
|
|
269
269
|
}
|
|
270
|
-
`;
|
|
270
|
+
`;h.styled(e.Box)`
|
|
271
271
|
> .ai-button {
|
|
272
272
|
display: none;
|
|
273
273
|
z-index: 1;
|
|
@@ -285,7 +285,7 @@
|
|
|
285
285
|
margin: auto;
|
|
286
286
|
}
|
|
287
287
|
}
|
|
288
|
-
`;
|
|
288
|
+
`;h.styled(e.Box)`
|
|
289
289
|
> .language-button {
|
|
290
290
|
display: none;
|
|
291
291
|
z-index: 1;
|
|
@@ -303,7 +303,7 @@
|
|
|
303
303
|
margin: auto;
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
|
-
`;
|
|
306
|
+
`;h.styled(e.Box)`
|
|
307
307
|
position: relative;
|
|
308
308
|
|
|
309
309
|
.action {
|
|
@@ -326,4 +326,4 @@
|
|
|
326
326
|
display: inline-flex;
|
|
327
327
|
}
|
|
328
328
|
}
|
|
329
|
-
`;D.nextId();const ce={type:"default",title:"Section CardList",description:"This is Section CardList",center:!0,dark:!1,background:"",col:3,gap:2,align:"top",textAlign:"left",iconSize:100,padding:"normal",list:[{id:D.nextId(),title:"Simplified Service Delivery",description:"Block Server's Service Gateway makes networking easy with access to load balancing, SSL termination, automatic and customizable URL mapping, and redirects.",image:"https://www.arcblock.io/static/ead0cabde7f2b7ff34db8f3e8ceca271/afc4b/builder.png"}]};function de({componentId:t,locale:
|
|
329
|
+
`;D.nextId();const ce={type:"default",title:"Section CardList",description:"This is Section CardList",center:!0,dark:!1,background:"",col:3,gap:2,align:"top",textAlign:"left",iconSize:100,padding:"normal",list:[{id:D.nextId(),title:"Simplified Service Delivery",description:"Block Server's Service Gateway makes networking easy with access to load balancing, SSL termination, automatic and customizable URL mapping, and redirects.",image:"https://www.arcblock.io/static/ead0cabde7f2b7ff34db8f3e8ceca271/afc4b/builder.png"}]};function de({componentId:t,locale:d,components:p}){const{state:{config:{defaultLocale:l}},localState:{customComponentPreviewerProperties:w}}=k.useStore(),n=k.useAllComponents(),y=p||n,x=y?.[t],c=x?.data??(x&&typeof x=="object"&&"component"in x?x.component:void 0),b=c?.renderer;if(b?.type==="component-template"&&c){const g=k.createComponentTemplatePage(c,b),s=d||l||"en",r=k.getProjectIdFromPathnameOrWindow();return o.jsx(T.PageProvider,{page:g,defaultLocale:l,currentLocale:s,children:o.jsx(T.RenderQueueProvider,{children:o.jsx(e.Stack,{spacing:2,sx:{p:1},children:g.sectionIds.map((C,v)=>{const u=g.sections[C];if(!u||u.visibility==="hidden")return null;const B=g.dataSource?.[u.id]?.[s]??(l?g.dataSource?.[u.id]?.[l]:void 0)??{},q=u.properties??{};return o.jsx(T.BlockRenderer,{id:u.id,type:u.component,section:u,config:{...q,...B,locale:s,editing:!0,dev:{mode:"draft",defaultLocale:l,components:y,projectId:r}},page:g,renderIndex:v},u.id)})})})})}return o.jsx(re.CustomComponentRenderer,{componentId:t,locale:d,dev:{mode:"draft",components:y,defaultLocale:l},properties:w?.[t]??{}})}const L=260,pe=5,H="IGNORE_RENDER_BLOCKLET_TITLE",M=(t,d)=>t?Object.entries(t).map(([p,l])=>({id:p,component:p,name:l?.data?.name||l?.component?.name||p,properties:l?.data||l.component,previewImage:l?.data?.previewImage||null,type:d,blockletId:l?.blockletId,blockletTitle:l?.blockletTitle})):[],W=[{id:"section",name:"Section",properties:T.SectionBlockDefaultProps},{id:"section-card-list",name:"Section Card List",properties:ce},{id:"toc",name:"Toc",properties:T.TocDefaultProps},{id:"iframe",name:"Embed",properties:T.IFrameBlockDefaultProps},{id:"layout-block",name:"Section Layout",properties:{}}].map(t=>({...t,type:"basic",component:t.id}));function Q({state:t,open:d,onClose:p,onSelect:l,defaultTab:w,title:n,componentGroups:y,components:x,multiple:c=!1,defaultSelected:b,emptyText:g}){const{t:s}=O.useLocaleContext(),r=N.useReactive({selectedComponent:null,activeTab:w,searchQuery:""}),C=f.useMemo(()=>y||[{name:"basic",label:s("maker.components.basicGroup"),components:W},t&&{name:"custom",label:s("maker.components.customGroup"),components:M(k.getCustomComponents(t),"custom")},t&&{name:"resource",label:s("maker.components.resourceGroup"),components:M(k.getResourceComponents(t),"resource")}].filter(Boolean),[y,s,t,d]),v=r.activeTab||C[0]?.name,u=()=>{r.selectedComponent&&(l(r.selectedComponent),p())},B=i=>{if(i){if(q(i)){c?r.selectedComponent=r.selectedComponent.filter(a=>a.id!==i.id):r.selectedComponent=null;return}if(c){const a=Array.isArray(r.selectedComponent)?r.selectedComponent:[],j=a.some(z=>z.id===i.id);r.selectedComponent=j?a.filter(z=>z.id!==i.id):[...a,i]}else r.selectedComponent=i}},q=i=>r.selectedComponent?c?r.selectedComponent.some(a=>a.id===i.id):r.selectedComponent.id===i.id:!1,I=C?.length===0,_=f.useMemo(()=>{const i=C.find(a=>a?.name===v)?.components||[];return r.searchQuery?i.filter(a=>a.name.toLowerCase().includes(r.searchQuery.toLowerCase())):i},[v,C,r.searchQuery]);f.useEffect(()=>{r.searchQuery="",d&&b?r.selectedComponent=c?Array.isArray(b)?b:[b]:b:r.selectedComponent=null},[d,b,c]);const S=_?.length===0,P=g||s(v==="resource"?"maker.components.needAddResource":"maker.components.noComponents"),U=f.useMemo(()=>_?_.reduce((i,a)=>{const j=a.blockletId||H,z=a.blockletTitle||s("maker.components.defaultGroup");return i[j]||(i[j]={title:z,components:[]}),i[j].components.push(a),i},{}):{},[_]);return o.jsxs(e.Dialog,{open:d,onClose:p,maxWidth:"lg",fullWidth:!0,slotProps:{paper:{sx:{height:"80vh",maxHeight:"80vh",display:"flex",flexDirection:"column"}}},children:[o.jsxs(e.DialogTitle,{className:"between",sx:{display:"flex",gap:2},children:[o.jsx(e.Box,{children:n||s("maker.components.addComponent")}),o.jsx(e.TextField,{size:"small",placeholder:s("maker.components.searchComponent"),value:r.searchQuery,onChange:i=>r.searchQuery=i.target.value,sx:{flex:1,maxWidth:350},slotProps:{input:{startAdornment:o.jsx(A.Icon,{icon:"tabler:search",style:{marginRight:8}})}}}),o.jsx(e.IconButton,{size:"small",onClick:p,children:o.jsx(e.Box,{component:A.Icon,icon:"tabler:x",sx:{color:"text.primary"}})})]}),o.jsxs(e.DialogContent,{sx:{display:"flex",gap:2,pl:"8px !important",flex:1,overflow:"hidden"},children:[!I&&o.jsx(e.Box,{sx:{width:150,borderRight:1,borderColor:"divider"},children:o.jsx(e.Tabs,{orientation:"vertical",value:v,onChange:(i,a)=>r.activeTab=a,sx:{"& .MuiTab-root":{alignItems:"flex-start",textAlign:"left",minHeight:48,py:1.5,px:2}},children:C.map((i,a)=>o.jsx(e.Tab,{label:i?.label,value:i?.name},a))})}),o.jsx(e.Box,{sx:{flex:1,overflowX:"hidden",overflowY:"auto",pr:1},children:S?o.jsx(G.default,{children:P}):o.jsx($,{wrapperComponent:e.Grid,wrapperComponentProps:{container:!0,spacing:2,sx:S?{height:"100%"}:{}},groups:U,emptyText:P,renderItem:i=>{const a=q(i);return o.jsx(e.Grid,{sx:{width:"100%","& .add-component-card":{boxShadow:"none",border:1,borderColor:a?"primary.main":"grey.200","& .check-container":{display:a?"flex":"none",position:"absolute",right:0,bottom:0,justifyContent:"flex-end",alignItems:"flex-end",width:30,height:30,overflow:"hidden",transition:"all 0.3s ease",color:"white","&::after":{position:"absolute",zIndex:0,display:"block",width:0,height:0,borderTop:"transparent solid 15px",borderLeft:"transparent solid 15px",borderBottom:j=>`solid 15px ${j.palette.primary.main}`,borderRight:j=>`solid 15px ${j.palette.primary.main}`,transition:"all 0.1s ease",content:'""'},"& .check-icon":{position:"relative",zIndex:2,margin:"0 1px 1px 0",fontSize:16,transition:"all 0.2s ease"}}}},size:{xs:12,md:6,lg:4},children:o.jsxs(e.Card,{className:"add-component-card",sx:{position:"relative",width:"100%",cursor:"pointer"},onClick:()=>B(i),children:[o.jsx(e.CardMedia,{sx:{width:"100%",height:L,overflow:"auto",position:"relative"},children:o.jsx(V,{components:x,containerHeight:L,component:i},i.id)}),o.jsx(e.CardContent,{sx:{bgcolor:"background.paper",borderTop:1,borderColor:a?"primary.main":"grey.200"},children:o.jsx(e.Typography,{variant:"body1",noWrap:!0,sx:{fontWeight:"bold"},children:i.name})}),o.jsx(e.Box,{className:"check-container",children:o.jsx(ie.default,{className:"check-icon"})})]})},i.id)}})})]}),o.jsxs(e.DialogActions,{sx:{borderTop:1,borderColor:"divider",p:2},children:[o.jsx(e.Button,{onClick:p,variant:"outlined",children:s("common.cancel")}),o.jsx(e.Button,{onClick:u,variant:"contained",disabled:!r.selectedComponent||c&&Array.isArray(r.selectedComponent)&&r.selectedComponent.length===0,children:c&&Array.isArray(r.selectedComponent)&&r.selectedComponent.length>0?s("common.addMultiple",{count:r.selectedComponent.length}):s("common.add")})]})]})}function V({containerHeight:t,component:d,minScale:p=.1,components:l}){const{locale:w}=O.useLocaleContext(),n=N.useReactive({scale:1,shouldScroll:!1,isVisible:!1,hadInit:!1}),{currentPage:y}=k.useStore(),x=f.useRef(null),c=f.useRef(null),b=f.useRef(0),g=f.useRef(null);f.useEffect(()=>{const q=new IntersectionObserver(([I])=>{n.isVisible=I.isIntersecting},{root:null,rootMargin:"50px",threshold:0});return c.current&&q.observe(c.current),()=>q.disconnect()},[]),f.useEffect(()=>{const q=()=>{if(b.current+=1,b.current>pe){I.disconnect();return}if(!d.previewImage&&x.current){const _=x.current.scrollHeight,S=t/_;S<p?(n.scale=p,n.shouldScroll=!0):S<1?(n.scale=S,n.shouldScroll=!1):(n.scale=1,n.shouldScroll=!1)}g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{n.hadInit=!0},200)},I=new ResizeObserver(()=>{setTimeout(q,20)});return x.current&&n.isVisible&&I.observe(x.current),()=>{I.disconnect()}},[t,p,n.isVisible,d]);const{id:s,type:r,component:C,properties:v,previewImage:u}=d,B=f.useMemo(()=>n.isVisible?u?o.jsx(e.Box,{component:"img",loading:"lazy",src:k.getImageAbsoluteUrl(u),alt:d.name,sx:{width:"100%",height:"100%",objectFit:"cover",borderRadius:1,cursor:"pointer"}},s):r==="basic"?o.jsx(T.BlockRenderer,{id:s,type:C,section:v,config:{...v,locale:w,editing:!1,dev:{mode:"draft"}},page:y},s):o.jsx(de,{componentId:s,locale:w,components:l},s):null,[s,r,C,v,w,u,n.isVisible]);return o.jsx(e.Box,{ref:c,sx:{position:"relative",width:"100%",height:"100%",overflowX:"hidden",overflowY:n.shouldScroll?"auto":"hidden",transition:"all 0.3s ease"},children:o.jsxs(e.Box,{sx:{transform:`scale(${n.scale})`,transformOrigin:"top left",width:`${100/n.scale}%`,height:n.hadInit&&n.shouldScroll?"100%":`${100/n.scale}%`},children:[!n.hadInit&&o.jsx(e.Skeleton,{variant:"rectangular",width:"100%",height:"100%"}),o.jsx(e.Box,{ref:x,sx:{width:"100%",height:u?"100%":"auto",pointerEvents:"none",opacity:n.hadInit?1:0},children:B})]})})}function $({groups:t,emptyText:d,renderItem:p,wrapperComponent:l=e.Box,wrapperComponentProps:w={display:"inline-flex",flexWrap:"wrap",gap:1}}){return o.jsx(e.Box,{children:Object.keys(t).length>0?Object.entries(t).map(([n,{title:y,components:x}])=>o.jsxs(e.Box,{sx:{mb:3},children:[n!==H&&o.jsxs(e.Typography,{className:"blocklet-title",variant:"subtitle2",sx:{mb:2,fontWeight:500,color:"text.primary",display:"flex",alignItems:"center",gap:1},children:[o.jsx(e.Box,{component:"span",sx:{width:4,height:20,backgroundColor:"primary.main",borderRadius:1,display:"inline-block"}}),y]}),o.jsx(l,{...w,children:x.map(c=>p(c))})]},n)):o.jsx(G.default,{children:d})})}exports.AddComponent=Q;exports.AutoScaledComponentRenderer=V;exports.BASIC_COMPONENT_LIST=W;exports.GroupedComponentsList=$;exports.default=Q;exports.formatComponent=M;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),t=require("./state-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),t=require("./state-BAjDjwwp.js");function n({children:e}){const r=t.useProjectId();return s.jsx(t.StoreProvider,{url:t.getWssURL(r??""),name:"root",waitingSynced:!0,children:s.jsx(o,{children:e})})}function o({children:e}){const{state:r}=t.useStore();return e({state:r})}exports.default=n;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),w=require("./state-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),w=require("./state-BAjDjwwp.js"),N=require("@arcblock/ux/lib/Locale/context"),ne=require("@arcblock/ux/lib/Result"),q=require("@arcblock/ux/lib/Theme"),oe=require("@blocklet/pages-kit/builtin/page/header"),re=require("@blocklet/pages-kit/contexts/color"),V=require("@blocklet/pages-kit/utils/data-source"),se=require("@blocklet/pages-kit/utils/route"),ae=require("@blocklet/ui-react/lib/Header"),ie=require("@emotion/css"),T=require("@emotion/react"),j=require("@mui/material"),A=require("ahooks"),ce=require("isomorphic-dompurify"),le=require("lodash/cloneDeep"),ue=require("lodash/isEmpty"),de=require("lodash/isEqual"),d=require("react"),pe=require("react-helmet"),P=require("react-router-dom"),W=require("react-use"),S=require("ufo"),v=require("./index-BAiZumV7.js"),ge=require("@blocklet/ui-react/lib/Footer");require("webfontloader");const F=require("./session-BZ3-x8Ef.js"),R=t=>t&&t.__esModule?t:{default:t},$=R(ne),me=R(ae),he=R(ce),L=R(le),fe=R(ue),G=R(de),xe=R(ge),je=q.styled(j.Box)`
|
|
2
2
|
display: contents;
|
|
3
3
|
& > div > div > .MuiContainer-root {
|
|
4
4
|
max-width: unset;
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
font-family: ${r};
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
-
`})}function z(t){return t!=null}function Se(){const[t]=P.useSearchParams(),{session:n}=F.useSessionContext(),a=F.useIsRoleOrMultiTenant("owner","admin","pagesEditor","member"),o=d.useMemo(()=>{const s=t.get("mode");return v.STATE_MODES.includes(s)?s:"production"},[t]),r=o==="production"?o:n.user?a?o:"production":null;return r?e.jsx(Y,{mode:r}):null}function Y({mode:t}){if(t!=="draft"){const n=window.__PAGE_STATE__;return n?e.jsx(_,{mode:t,state:n}):e.jsx(Me,{mode:t,children:({state:a})=>e.jsx(_,{mode:t,state:a})})}return e.jsx(Ce,{children:({state:n})=>e.jsx(_,{mode:t,state:n})})}const Re=d.lazy(()=>Promise.resolve().then(()=>require("./publish-button-
|
|
30
|
+
`})}function z(t){return t!=null}function Se(){const[t]=P.useSearchParams(),{session:n}=F.useSessionContext(),a=F.useIsRoleOrMultiTenant("owner","admin","pagesEditor","member"),o=d.useMemo(()=>{const s=t.get("mode");return v.STATE_MODES.includes(s)?s:"production"},[t]),r=o==="production"?o:n.user?a?o:"production":null;return r?e.jsx(Y,{mode:r}):null}function Y({mode:t}){if(t!=="draft"){const n=window.__PAGE_STATE__;return n?e.jsx(_,{mode:t,state:n}):e.jsx(Me,{mode:t,children:({state:a})=>e.jsx(_,{mode:t,state:a})})}return e.jsx(Ce,{children:({state:n})=>e.jsx(_,{mode:t,state:n})})}const Re=d.lazy(()=>Promise.resolve().then(()=>require("./publish-button-45a3egG-.js"))),Ce=d.lazy(()=>Promise.resolve().then(()=>require("./draft-data-1hI-ev3X.js")));function Me({mode:t,children:n}){const o=document.querySelector('meta[property="pages:version"]')?.content,r=w.useProjectId(),s=d.useMemo(()=>{if(o==="{{pagesPublishedAt}}"){const u=localStorage.getItem(w.getProjectPageVersionKey(r??""));return Number(u)?Number(u):new Date().getTime()}return Number(o)},[o]),{loading:p,value:l}=W.useAsync(()=>v.getPages({mode:t,version:s}),[t,s]);return p?e.jsx(K,{}):l?n({state:l}):null}function _({mode:t,state:n}){const{t:a,locale:o}=N.useLocaleContext(),[r]=P.useSearchParams(),s=w.useProjectId(),p=w.useProjectSlug(),l=r.get("hiddenBadge")==="true",u=r.get("showPublish")==="true",{pageIds:g,pages:c,routeIds:x,routes:m,supportedLocales:h,config:{defaultLocale:b},resources:C}=n,y=w.getAllComponents(n),k=d.useMemo(()=>h?.some(f=>f.locale===o)?o:void 0,[o,h]),D=Object.values(m||{}).find(f=>f?.path==="/")||Object.values(c).find(f=>f?.slug==="/")?void 0:Object.values(c)[0],te=d.useMemo(()=>t==="production"?g?.map(f=>{const i=c[f];return i&&{id:i.id,path:S.joinURL("/",p||s||"",i.slug),isLinkToPage:v.isLinkToPage(i)}}).filter(z):x?.map(f=>{const i=m[f];return i?{id:i.id,path:S.joinURL("/",p||s||"",i.path,`?mode=${t}&showPublish=true`)}:null}).filter(z),[g,c,t,m,x,s,p]),I=([...f])=>(t!=="production"&&u&&f.unshift(e.jsx(d.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(Re,{ref:{current:null},mode:"production",state:n})})),f);return e.jsxs(v.Provider,{value:{pages:te},children:[e.jsxs(P.Routes,{children:[D&&e.jsx(P.Route,{index:!0,element:e.jsx(P.Navigate,{to:S.joinURL("/",k||"",D.slug)})}),x?.map(f=>{const i=m?.[f];if(!i||!i.displayTemplateId)return null;const E=c[i.displayTemplateId];if(!E)return null;let B=[];return i.params&&i.params.length>0&&(B=se.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]})?.map(H=>{const U=H.paramOptionIds.join("-");return e.jsx(P.Route,{path:S.joinURL(":projectIdOrSlug?",H.path),element:e.jsx(O,{mode:t,components:y,page:E,locale:k,defaultLocale:b,headerAddons:I,state:n,pageData:i.dataSource?.pathDataMappings?.[U]?.dataCache?.[k||b||"en"]})},U)})),B.push(e.jsx(P.Route,{path:S.joinURL(":projectIdOrSlug?",i.path),element:e.jsx(O,{mode:t,components:y,page:E,locale:k,defaultLocale:b,headerAddons:I,state:n,pageData:i.dataSource?.pathDataMappings?.[i.id]?.dataCache?.[k||b||"en"]})},i.id)),B}),g?.map(f=>{const i=c[f];return!i||!v.isLinkToPage(i)?null:e.jsx(P.Route,{path:S.joinURL(":projectIdOrSlug?",i.slug),element:e.jsx(M,{mode:t,components:y,page:i,locale:k,defaultLocale:b,headerAddons:I})},i.id)}),C?.pages&&Object.values(C?.pages)?.map(({blockletId:f,page:i})=>e.jsx(P.Route,{path:S.joinURL("/",`@${f}`,i.slug),element:e.jsx(M,{mode:t,components:y,page:i,locale:k,defaultLocale:b,headerAddons:I})},i.id)),e.jsx(P.Route,{path:"*",element:e.jsx(j.Box,{sx:{width:"100vw",height:"100vh",display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx($.default,{status:404,extra:e.jsx(ee,{href:"/",children:a("common.back")}),sx:{bgcolor:"transparent",width:"100%",height:"100%"}})})})]}),t!=="production"&&!l&&e.jsx(Pe,{sx:{bgcolor:"info.light"},children:t}),e.jsx(ke,{})]})}function O({mode:t,pageData:n,components:a,page:o,locale:r,defaultLocale:s,headerAddons:p,state:l}){const u=A.useReactive({page:null});d.useEffect(()=>{const c=o||null;c?u.page=L.default(c):u.page=null},[o,JSON.stringify(o),u]);const g=d.useRef(void 0);return d.useEffect(()=>{G.default(n,g.current)||n&&u.page&&(V.setPageDataSource(u.page,l,r,n),g.current=L.default(n))},[u.page,n,r,l]),u.page?e.jsx(M,{mode:t,components:a,page:u.page,locale:r,defaultLocale:s,headerAddons:p}):null}function qe({mode:t,state:n,path:a,pageData:o}){const{t:r,locale:s}=N.useLocaleContext(),{pages:p,supportedLocales:l,config:{defaultLocale:u},resources:g}=n,c=Object.values(p).find(y=>y?.slug===a),x=Object.values(g?.pages||{}).find(y=>y.page.slug===a),m=d.useMemo(()=>l?.some(y=>y.locale===s)?s:void 0,[s,l]),h=A.useReactive({page:null});d.useEffect(()=>{const y=c||x?.page||null;y?h.page=L.default(y):h.page=null},[c,x]);const b=d.useRef(void 0);if(d.useEffect(()=>{G.default(o,b.current)||o&&h.page&&(V.setPageDataSource(h.page,n,m,o),b.current=L.default(o))},[{}]),!c&&!x?.page)return e.jsx(j.Box,{sx:{width:"100vw",height:"100vh",display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx($.default,{style:{background:"inherit"},status:404,extra:e.jsx(ee,{href:"/",children:r("common.back")})})});const C=w.getAllComponents(n);return h.page?e.jsx(M,{mode:t,components:C,page:h.page,locale:m,defaultLocale:u}):null}function M({mode:t,components:n,page:a,locale:o,defaultLocale:r,headerAddons:s}){const p=re.useColorConvert(),l=a.locales?.[o]??a.locales?.[r]??{},u=l.title||window.blocklet?.appName,g=l.description||window.blocklet?.appDescription,c=w.autoResizeImage(w.getImageAbsoluteUrl(l.image),540);return e.jsxs(v.PageProvider,{page:a,defaultLocale:r,currentLocale:o,children:[e.jsx(T.Global,{styles:T.css`
|
|
31
31
|
body {
|
|
32
32
|
background-color: ${p(!l.backgroundColor||l.backgroundColor==="transparent"?"background.default":l.backgroundColor)} !important;
|
|
33
33
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var lt=Object.create;var Ce=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var gt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of dt(t))!ut.call(e,i)&&i!==n&&Ce(e,i,{get:()=>t[i],enumerable:!(r=ct(t,i))||r.enumerable});return e};var mt=(e,t,n)=>(n=e!=null?lt(At(e)):{},gt(t||!e||!e.__esModule?Ce(n,"default",{value:e,enumerable:!0}):n,e));const o=require("react/jsx-runtime"),xt=require("@mui/icons-material"),A=require("@mui/material"),pt=require("lodash/isEmpty"),ht=require("lodash/pick"),m=require("react"),ft=require("lodash/keyBy"),W=require("ufo"),I=require("@arcblock/ux/lib/Theme"),v=require("@emotion/css"),bt=require("lodash/omit"),de=require("react-router-dom"),yt=require("@arcblock/ux/lib/Button"),kt=require("is-uri"),ze=require("@iconify-icon/react"),j=require("./state-BP5DoD6I.js"),vt=require("@blocklet/pages-kit/builtin/markdown/markdown-renderer"),Ue=require("@blocklet/pages-kit/contexts/color"),Bt=require("react-syntax-highlighter/dist/esm/styles/prism"),wt=require("@arcblock/react-hooks/lib/useBrowser"),Ct=require("@arcblock/ux/lib/Colors"),Ae=require("@blocklet/pages-kit/components"),je=require("@blocklet/pages-kit/utils/style"),jt=require("@mui/material/useMediaQuery"),Z=require("pathe");require("@blocklet/aigne-sdk/components");const It=require("@blocklet/embed/message"),Et=require("ahooks"),St=require("lodash/isEqual"),Rt=require("@blocklet/embed/react"),Dt=require("@arcblock/ux/lib/Locale/context"),Qt=require("@arcblock/ux/lib/Screenshot"),Mt=require("react-twitter-embed"),Ie=require("react-use"),S=e=>e&&e.__esModule?e:{default:e},Pt=S(pt),$=S(ht),Lt=S(m),R=S(ft),Q=S(bt),Nt=S(yt),ae=S(kt),zt=S(vt),Ut=S(wt),Ee=S(Ct),We=S(jt),Wt=S(St),Fe=S(Qt),q="{{CUSTOM_VALUE}}",Ft=[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{py:{xs:2.5,md:4,lg:4,xl:6}}},{title:"Normal",value:"normal",sx:{py:{xs:5,md:7.5,lg:10,xl:12.5}}},{title:"Large",value:"large",sx:{py:{xs:7.5,md:10,lg:12.5,xl:15}}}],Vt=[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{py:{xs:2.5,md:4,lg:4,xl:6}}},{title:"Normal",value:"normal",sx:{py:{xs:5,md:7,lg:7,xl:9}}},{title:"Large",value:"large",sx:{py:{xs:6,md:9,lg:9,xl:11}}},{title:"Extra Large",value:"xl",sx:{py:{xs:8,md:12,lg:12,xl:16}}}],Ht=[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{px:{xs:2,md:4,lg:4,xl:6}}},{title:"Normal",value:"normal",sx:{px:{xs:2.5,md:7.5,lg:10,xl:12.5}}},{title:"Large",value:"large",sx:{px:{xs:2.5,md:10,lg:12.5,xl:15}}},{title:"Extra Large",value:"xl",sx:{px:{xs:3,md:12.5,lg:15,xl:17.5}}}],_=(e,t,n)=>{const r=e.breakpoints.values[n];return`${t}${r?` (${r}px)`:""}`},Tt=[{title:"100%",value:"full",sx:{}},{title:"None",value:"none",sx:{maxWidth:"none"}},{title:e=>_(e,"Small","sm"),value:"sm",sx:{maxWidth:e=>e.breakpoints.values.sm,width:"100%",mx:"auto"}},{title:e=>_(e,"Normal","md"),value:"md",sx:{maxWidth:e=>e.breakpoints.values.md,width:"100%",mx:"auto"}},{title:e=>_(e,"Large","lg"),value:"lg",sx:{maxWidth:e=>e.breakpoints.values.lg,width:"100%",mx:"auto"}},{title:e=>_(e,"Extra Large","xl"),value:"xl",sx:{maxWidth:e=>e.breakpoints.values.xl,width:"100%",mx:"auto"}},{title:"Custom",value:"custom",sx:{maxWidth:q,width:"100%",mx:"auto"}}],Gt=[{title:"None",value:"none",sx:{gap:0}},{title:"Small",value:"small",sx:{gap:{xs:1,md:2,lg:2,xl:3}}},{title:"Normal",value:"normal",sx:{gap:{xs:2,md:3.5,lg:3.5,xl:5}}},{title:"Large",value:"large",sx:{gap:{xs:3,md:5,lg:5,xl:6.5}}}],ue=e=>[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{[e]:{xs:1,md:2,lg:2,xl:3}}},{title:"Normal",value:"normal",sx:{[e]:{xs:2.5,md:5,lg:5,xl:7.5}}},{title:"Large",value:"large",sx:{[e]:{xs:3,md:6,lg:6,xl:9}}},{title:"Extra Large",value:"xl",sx:{[e]:{xs:4,md:8,lg:8,xl:12}}},{title:"Custom",value:"custom",sx:{[e]:q}}],Ot=ue("p"),Yt=ue("px"),Jt=ue("py"),qt=[{title:"Start",value:"start",sx:{alignContent:"start"}},{title:"Center",value:"center",sx:{alignContent:"center"}},{title:"End",value:"end",sx:{alignContent:"end"}},{title:"Space Between",value:"space-between",sx:{alignContent:"space-between"}},{title:"Space Around",value:"space-around",sx:{alignContent:"space-around"}},{title:"Space Evenly",value:"space-evenly",sx:{alignContent:"space-evenly"}}],Xt=[{title:"Start",value:"start",sx:{justifyContent:"start"}},{title:"Center",value:"center",sx:{justifyContent:"center"}},{title:"End",value:"end",sx:{justifyContent:"end"}},{title:"Space Between",value:"space-between",sx:{justifyContent:"space-between"}},{title:"Space Around",value:"space-around",sx:{justifyContent:"space-around"}},{title:"Space Evenly",value:"space-evenly",sx:{justifyContent:"space-evenly"}}],Kt=[{title:"Solid",value:"solid",sx:{border:"1px solid",borderColor:"divider"},group:"borderFrame"},{title:"Dashed",value:"dashed",sx:{border:"1px dashed",borderColor:"divider"},group:"borderFrame"},{title:"Dotted",value:"dotted",sx:{border:"1px dotted",borderColor:"divider"},group:"borderFrame"},{title:"Custom",value:"custom",sx:{border:q},group:"borderFrame"}],Ve=[{value:"macbook",title:"MacBook",group:"deviceFrame"},{value:"phone",title:"Phone",group:"deviceFrame"}],Zt=e=>Ve.some(t=>t.value===e),He=[{value:"chrome",title:"Chrome Browser",group:"browserFrame",sx:{}},{value:"safari",title:"Safari Browser",group:"browserFrame",sx:{}}],_t=e=>He.some(t=>t.value===e),Te=[{value:"terminal",title:"Terminal",group:"terminalFrame",sx:{}}],$t=e=>Te.some(t=>t.value===e),eo=[{value:"shadow-sm",title:"Shadow Low Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[2]}},{value:"shadow-md",title:"Shadow Medium Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[6]}},{value:"shadow-lg",title:"Shadow High Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[12]}},{value:"shadow-xl",title:"Shadow Extra High Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[16]}},{value:"shadow-max",title:"Shadow Max Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[24]}}],to=[{title:"None",value:"none",sx:{border:"none"},group:"commonFrame"},...Kt,...He,...Ve,...Te,...eo],oo=[{title:"None",value:"none",sx:{borderRadius:0}},{title:"Small",value:"small",sx:{borderRadius:1}},{title:"Medium",value:"medium",sx:{borderRadius:2}},{title:"Large",value:"large",sx:{borderRadius:3}},{title:"Extra Large",value:"xl",sx:{borderRadius:4}},{title:"Rounded",value:"rounded",sx:{borderRadius:"50%"}},{title:"Custom",value:"custom",sx:{borderRadius:q}}],no=[{title:"100%",value:"100%",sx:{height:"100%"}},{title:"Auto",value:"auto",sx:{height:"auto"}},{title:"Unset",value:"unset",sx:{height:"unset"}},{title:"Inherit",value:"inherit",sx:{height:"inherit"}},{title:"Initial",value:"initial",sx:{height:"initial"}},{title:"Fit Content",value:"fit-content",sx:{height:"fit-content"}},{title:"Max Content",value:"max-content",sx:{height:"max-content"}},{title:"Min Content",value:"min-content",sx:{height:"min-content"}}],ro=R.default(Ft,"value"),io=R.default(Vt,"value"),so=R.default(Ht,"value"),ao=R.default(Tt,"value"),lo=R.default(Gt,"value"),co=R.default(Ot,"value"),Ao=R.default(Yt,"value"),uo=R.default(Jt,"value"),go=R.default(qt,"value"),mo=R.default(Xt,"value"),xo=R.default(to,"value"),po=R.default(oo,"value"),ho=R.default(no,"value"),fo=new Map([["baseSectionPaddingY",ro],["maxWidth",ao],["paddingY",io],["paddingX",so],["layoutBlockGap",lo],["layoutBlockPadding",co],["layoutBlockPaddingX",Ao],["layoutBlockPaddingY",uo],["layoutBlockAlignContent",go],["layoutBlockJustifyContent",mo],["layoutBlockBorder",xo],["layoutBlockBorderRadius",po],["layoutBlockHeight",ho]]);function D(e){const{type:t,value:n,format:r="sx",defaultValue:i=null}=e,s=fo.get(t);if(!s||typeof n!="string"||!n)return i;const l=n.startsWith("custom:"),a=l?"custom":n;if(s?.[a]&&s?.[a]?.[r]){const c=s[a][r];if(l){const u=n.replace("custom:","");try{return JSON.parse(JSON.stringify(c||{}).replaceAll(q,u))}catch{}}return c}return i}const bo=e=>e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^\w-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,""),yo=e=>{try{return new URL(e).origin!==window.location.origin}catch(t){return console.error(t),!1}},ko=(e,t,n)=>{if(!e||!yo(e))return e;try{const r=W.getQuery(e),i=bo(t),s={utm_source:window.location.hostname,utm_medium:"body_link",utm_campaign:"default",utm_content:i,...n,...r};return W.withQuery(e,s)}catch(r){return console.error(r),e}},Ge=m.createContext({page:null,getPageMeta:()=>({}),getPageMetaStyle:()=>({})});function ge(){return m.useContext(Ge)}function vo({page:e,children:t,defaultLocale:n="en",currentLocale:r}){const i=m.useMemo(()=>e?JSON.parse(JSON.stringify(e)):null,[JSON.stringify(e)]),s=m.useCallback(()=>{if(!i)return{};const d=r||n;return i.locales?.[d]??{}},[i,n,r]),l=m.useCallback((d="sx")=>{const g=s();return!g||!g.style?{}:Object.entries(g.style||{}).reduce((x,[h,y])=>{if(!y)return x;const f=`${h}Custom`;g.style[f];const k=D({type:h,value:y,format:d});return k?{...x,...k}:x},{})},[s]),a=m.useMemo(()=>({page:i,getPageMeta:s,getPageMetaStyle:l}),[i,s,l]),c=m.useCallback(d=>{const g=d.querySelector("h1, h2, h3, h4, h5, h6");if(g?.textContent?.trim())return g.textContent.trim();const p=[".MuiTypography-h1",".MuiTypography-h2",".MuiTypography-h3",".MuiTypography-h4",".MuiTypography-h5",".MuiTypography-h6",'[class*="title"]','[class*="Title"]','[class*="heading"]','[class*="Heading"]','[role="heading"]',".MuiBox-root",".MuiTypography-root"];for(const h of p){const y=d.querySelector(h);if(y?.textContent?.trim())return y.textContent.trim()}return(d.textContent?.trim()||"").replace(/\s+/g," ")},[]),u=m.useCallback(d=>{const g=s(),p=d.target?.closest("a");if(!p||!p.href)return;const{href:x}=p,h=c(p);p.href=ko(x,h,{utm_campaign:g.utmCampaign||"default"})},[c,s]);return m.useEffect(()=>(document.addEventListener("click",u),()=>{document.removeEventListener("click",u)}),[u]),o.jsx(Ge.Provider,{value:a,children:t})}const Oe=m.createContext(null);function Bo({children:e}){const[t,n]=m.useState(-1),[r,i]=m.useState(new Set),s=m.useRef(new Set([0])),l=m.useRef(null);m.useEffect(()=>(l.current||(l.current=new IntersectionObserver(p=>{const x=new Map,h=new Set;p.forEach(y=>{const f=parseInt(y.target.getAttribute("data-render-index")||"-1",10);f>=0&&(x.set(f,y.isIntersecting),y.isIntersecting?(s.current.add(f),h.add(f)):h.delete(f))}),x.size>0&&i(h)},{rootMargin:"100px",threshold:.1})),()=>{l.current&&(l.current.disconnect(),l.current=null)}),[]);const a=m.useCallback((p,x,h)=>typeof x!="number"||!h?()=>{}:(l.current&&(h.setAttribute("data-render-index",x.toString()),l.current.observe(h)),()=>{l.current&&l.current.unobserve(h)}),[]),c=m.useCallback((p,x)=>{if(typeof x!="number")return{};const h=x<=t;return{visibility:h?"visible":"hidden",opacity:h?1:0,willChange:"opacity",transition:"opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1), transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)"}},[t]),u=m.useCallback((p,x)=>{if(typeof x!="number")return"";const h=x<=t;return`${p}-${x}-${h?"visible":"hidden"}`},[t]);m.useEffect(()=>{const h=Array.from(s.current).sort((y,f)=>y-f).find(y=>y>t);if(h!==void 0){const y=setTimeout(()=>{n(h)},50);return()=>clearTimeout(y)}return()=>{}},[t,r]);const d=m.useCallback(p=>typeof p!="number"?!0:p<=t,[t]),g=m.useMemo(()=>({getSectionSx:c,getSectionKey:u,observeSection:a,shouldRender:d}),[c,a,d,u]);return o.jsx(Oe.Provider,{value:g,children:e})}const wo=()=>m.useContext(Oe),ee=["editing","height","locale","dev","sx"],Co=m.forwardRef((e,t)=>{const{className:n,...r}=e;return o.jsx(jo,{ref:t,...r,className:v.cx("BlockBase-root",n)})}),jo=I.styled(A.Box)`
|
|
1
|
+
"use strict";var lt=Object.create;var Ce=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var gt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of dt(t))!ut.call(e,i)&&i!==n&&Ce(e,i,{get:()=>t[i],enumerable:!(r=ct(t,i))||r.enumerable});return e};var mt=(e,t,n)=>(n=e!=null?lt(At(e)):{},gt(t||!e||!e.__esModule?Ce(n,"default",{value:e,enumerable:!0}):n,e));const o=require("react/jsx-runtime"),xt=require("@mui/icons-material"),A=require("@mui/material"),pt=require("lodash/isEmpty"),ht=require("lodash/pick"),m=require("react"),ft=require("lodash/keyBy"),W=require("ufo"),I=require("@arcblock/ux/lib/Theme"),v=require("@emotion/css"),bt=require("lodash/omit"),de=require("react-router-dom"),yt=require("@arcblock/ux/lib/Button"),kt=require("is-uri"),ze=require("@iconify-icon/react"),j=require("./state-BAjDjwwp.js"),vt=require("@blocklet/pages-kit/builtin/markdown/markdown-renderer"),Ue=require("@blocklet/pages-kit/contexts/color"),Bt=require("react-syntax-highlighter/dist/esm/styles/prism"),wt=require("@arcblock/react-hooks/lib/useBrowser"),Ct=require("@arcblock/ux/lib/Colors"),Ae=require("@blocklet/pages-kit/components"),je=require("@blocklet/pages-kit/utils/style"),jt=require("@mui/material/useMediaQuery"),Z=require("pathe");require("@blocklet/aigne-sdk/components");const It=require("@blocklet/embed/message"),Et=require("ahooks"),St=require("lodash/isEqual"),Rt=require("@blocklet/embed/react"),Dt=require("@arcblock/ux/lib/Locale/context"),Qt=require("@arcblock/ux/lib/Screenshot"),Mt=require("react-twitter-embed"),Ie=require("react-use"),S=e=>e&&e.__esModule?e:{default:e},Pt=S(pt),$=S(ht),Lt=S(m),R=S(ft),Q=S(bt),Nt=S(yt),ae=S(kt),zt=S(vt),Ut=S(wt),Ee=S(Ct),We=S(jt),Wt=S(St),Fe=S(Qt),q="{{CUSTOM_VALUE}}",Ft=[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{py:{xs:2.5,md:4,lg:4,xl:6}}},{title:"Normal",value:"normal",sx:{py:{xs:5,md:7.5,lg:10,xl:12.5}}},{title:"Large",value:"large",sx:{py:{xs:7.5,md:10,lg:12.5,xl:15}}}],Vt=[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{py:{xs:2.5,md:4,lg:4,xl:6}}},{title:"Normal",value:"normal",sx:{py:{xs:5,md:7,lg:7,xl:9}}},{title:"Large",value:"large",sx:{py:{xs:6,md:9,lg:9,xl:11}}},{title:"Extra Large",value:"xl",sx:{py:{xs:8,md:12,lg:12,xl:16}}}],Ht=[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{px:{xs:2,md:4,lg:4,xl:6}}},{title:"Normal",value:"normal",sx:{px:{xs:2.5,md:7.5,lg:10,xl:12.5}}},{title:"Large",value:"large",sx:{px:{xs:2.5,md:10,lg:12.5,xl:15}}},{title:"Extra Large",value:"xl",sx:{px:{xs:3,md:12.5,lg:15,xl:17.5}}}],_=(e,t,n)=>{const r=e.breakpoints.values[n];return`${t}${r?` (${r}px)`:""}`},Tt=[{title:"100%",value:"full",sx:{}},{title:"None",value:"none",sx:{maxWidth:"none"}},{title:e=>_(e,"Small","sm"),value:"sm",sx:{maxWidth:e=>e.breakpoints.values.sm,width:"100%",mx:"auto"}},{title:e=>_(e,"Normal","md"),value:"md",sx:{maxWidth:e=>e.breakpoints.values.md,width:"100%",mx:"auto"}},{title:e=>_(e,"Large","lg"),value:"lg",sx:{maxWidth:e=>e.breakpoints.values.lg,width:"100%",mx:"auto"}},{title:e=>_(e,"Extra Large","xl"),value:"xl",sx:{maxWidth:e=>e.breakpoints.values.xl,width:"100%",mx:"auto"}},{title:"Custom",value:"custom",sx:{maxWidth:q,width:"100%",mx:"auto"}}],Gt=[{title:"None",value:"none",sx:{gap:0}},{title:"Small",value:"small",sx:{gap:{xs:1,md:2,lg:2,xl:3}}},{title:"Normal",value:"normal",sx:{gap:{xs:2,md:3.5,lg:3.5,xl:5}}},{title:"Large",value:"large",sx:{gap:{xs:3,md:5,lg:5,xl:6.5}}}],ue=e=>[{title:"None",value:"none",sx:{}},{title:"Small",value:"small",sx:{[e]:{xs:1,md:2,lg:2,xl:3}}},{title:"Normal",value:"normal",sx:{[e]:{xs:2.5,md:5,lg:5,xl:7.5}}},{title:"Large",value:"large",sx:{[e]:{xs:3,md:6,lg:6,xl:9}}},{title:"Extra Large",value:"xl",sx:{[e]:{xs:4,md:8,lg:8,xl:12}}},{title:"Custom",value:"custom",sx:{[e]:q}}],Ot=ue("p"),Yt=ue("px"),Jt=ue("py"),qt=[{title:"Start",value:"start",sx:{alignContent:"start"}},{title:"Center",value:"center",sx:{alignContent:"center"}},{title:"End",value:"end",sx:{alignContent:"end"}},{title:"Space Between",value:"space-between",sx:{alignContent:"space-between"}},{title:"Space Around",value:"space-around",sx:{alignContent:"space-around"}},{title:"Space Evenly",value:"space-evenly",sx:{alignContent:"space-evenly"}}],Xt=[{title:"Start",value:"start",sx:{justifyContent:"start"}},{title:"Center",value:"center",sx:{justifyContent:"center"}},{title:"End",value:"end",sx:{justifyContent:"end"}},{title:"Space Between",value:"space-between",sx:{justifyContent:"space-between"}},{title:"Space Around",value:"space-around",sx:{justifyContent:"space-around"}},{title:"Space Evenly",value:"space-evenly",sx:{justifyContent:"space-evenly"}}],Kt=[{title:"Solid",value:"solid",sx:{border:"1px solid",borderColor:"divider"},group:"borderFrame"},{title:"Dashed",value:"dashed",sx:{border:"1px dashed",borderColor:"divider"},group:"borderFrame"},{title:"Dotted",value:"dotted",sx:{border:"1px dotted",borderColor:"divider"},group:"borderFrame"},{title:"Custom",value:"custom",sx:{border:q},group:"borderFrame"}],Ve=[{value:"macbook",title:"MacBook",group:"deviceFrame"},{value:"phone",title:"Phone",group:"deviceFrame"}],Zt=e=>Ve.some(t=>t.value===e),He=[{value:"chrome",title:"Chrome Browser",group:"browserFrame",sx:{}},{value:"safari",title:"Safari Browser",group:"browserFrame",sx:{}}],_t=e=>He.some(t=>t.value===e),Te=[{value:"terminal",title:"Terminal",group:"terminalFrame",sx:{}}],$t=e=>Te.some(t=>t.value===e),eo=[{value:"shadow-sm",title:"Shadow Low Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[2]}},{value:"shadow-md",title:"Shadow Medium Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[6]}},{value:"shadow-lg",title:"Shadow High Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[12]}},{value:"shadow-xl",title:"Shadow Extra High Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[16]}},{value:"shadow-max",title:"Shadow Max Elevation",group:"shadowFrame",sx:{boxShadow:e=>e.shadows[24]}}],to=[{title:"None",value:"none",sx:{border:"none"},group:"commonFrame"},...Kt,...He,...Ve,...Te,...eo],oo=[{title:"None",value:"none",sx:{borderRadius:0}},{title:"Small",value:"small",sx:{borderRadius:1}},{title:"Medium",value:"medium",sx:{borderRadius:2}},{title:"Large",value:"large",sx:{borderRadius:3}},{title:"Extra Large",value:"xl",sx:{borderRadius:4}},{title:"Rounded",value:"rounded",sx:{borderRadius:"50%"}},{title:"Custom",value:"custom",sx:{borderRadius:q}}],no=[{title:"100%",value:"100%",sx:{height:"100%"}},{title:"Auto",value:"auto",sx:{height:"auto"}},{title:"Unset",value:"unset",sx:{height:"unset"}},{title:"Inherit",value:"inherit",sx:{height:"inherit"}},{title:"Initial",value:"initial",sx:{height:"initial"}},{title:"Fit Content",value:"fit-content",sx:{height:"fit-content"}},{title:"Max Content",value:"max-content",sx:{height:"max-content"}},{title:"Min Content",value:"min-content",sx:{height:"min-content"}}],ro=R.default(Ft,"value"),io=R.default(Vt,"value"),so=R.default(Ht,"value"),ao=R.default(Tt,"value"),lo=R.default(Gt,"value"),co=R.default(Ot,"value"),Ao=R.default(Yt,"value"),uo=R.default(Jt,"value"),go=R.default(qt,"value"),mo=R.default(Xt,"value"),xo=R.default(to,"value"),po=R.default(oo,"value"),ho=R.default(no,"value"),fo=new Map([["baseSectionPaddingY",ro],["maxWidth",ao],["paddingY",io],["paddingX",so],["layoutBlockGap",lo],["layoutBlockPadding",co],["layoutBlockPaddingX",Ao],["layoutBlockPaddingY",uo],["layoutBlockAlignContent",go],["layoutBlockJustifyContent",mo],["layoutBlockBorder",xo],["layoutBlockBorderRadius",po],["layoutBlockHeight",ho]]);function D(e){const{type:t,value:n,format:r="sx",defaultValue:i=null}=e,s=fo.get(t);if(!s||typeof n!="string"||!n)return i;const l=n.startsWith("custom:"),a=l?"custom":n;if(s?.[a]&&s?.[a]?.[r]){const c=s[a][r];if(l){const u=n.replace("custom:","");try{return JSON.parse(JSON.stringify(c||{}).replaceAll(q,u))}catch{}}return c}return i}const bo=e=>e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^\w-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,""),yo=e=>{try{return new URL(e).origin!==window.location.origin}catch(t){return console.error(t),!1}},ko=(e,t,n)=>{if(!e||!yo(e))return e;try{const r=W.getQuery(e),i=bo(t),s={utm_source:window.location.hostname,utm_medium:"body_link",utm_campaign:"default",utm_content:i,...n,...r};return W.withQuery(e,s)}catch(r){return console.error(r),e}},Ge=m.createContext({page:null,getPageMeta:()=>({}),getPageMetaStyle:()=>({})});function ge(){return m.useContext(Ge)}function vo({page:e,children:t,defaultLocale:n="en",currentLocale:r}){const i=m.useMemo(()=>e?JSON.parse(JSON.stringify(e)):null,[JSON.stringify(e)]),s=m.useCallback(()=>{if(!i)return{};const d=r||n;return i.locales?.[d]??{}},[i,n,r]),l=m.useCallback((d="sx")=>{const g=s();return!g||!g.style?{}:Object.entries(g.style||{}).reduce((x,[h,y])=>{if(!y)return x;const f=`${h}Custom`;g.style[f];const k=D({type:h,value:y,format:d});return k?{...x,...k}:x},{})},[s]),a=m.useMemo(()=>({page:i,getPageMeta:s,getPageMetaStyle:l}),[i,s,l]),c=m.useCallback(d=>{const g=d.querySelector("h1, h2, h3, h4, h5, h6");if(g?.textContent?.trim())return g.textContent.trim();const p=[".MuiTypography-h1",".MuiTypography-h2",".MuiTypography-h3",".MuiTypography-h4",".MuiTypography-h5",".MuiTypography-h6",'[class*="title"]','[class*="Title"]','[class*="heading"]','[class*="Heading"]','[role="heading"]',".MuiBox-root",".MuiTypography-root"];for(const h of p){const y=d.querySelector(h);if(y?.textContent?.trim())return y.textContent.trim()}return(d.textContent?.trim()||"").replace(/\s+/g," ")},[]),u=m.useCallback(d=>{const g=s(),p=d.target?.closest("a");if(!p||!p.href)return;const{href:x}=p,h=c(p);p.href=ko(x,h,{utm_campaign:g.utmCampaign||"default"})},[c,s]);return m.useEffect(()=>(document.addEventListener("click",u),()=>{document.removeEventListener("click",u)}),[u]),o.jsx(Ge.Provider,{value:a,children:t})}const Oe=m.createContext(null);function Bo({children:e}){const[t,n]=m.useState(-1),[r,i]=m.useState(new Set),s=m.useRef(new Set([0])),l=m.useRef(null);m.useEffect(()=>(l.current||(l.current=new IntersectionObserver(p=>{const x=new Map,h=new Set;p.forEach(y=>{const f=parseInt(y.target.getAttribute("data-render-index")||"-1",10);f>=0&&(x.set(f,y.isIntersecting),y.isIntersecting?(s.current.add(f),h.add(f)):h.delete(f))}),x.size>0&&i(h)},{rootMargin:"100px",threshold:.1})),()=>{l.current&&(l.current.disconnect(),l.current=null)}),[]);const a=m.useCallback((p,x,h)=>typeof x!="number"||!h?()=>{}:(l.current&&(h.setAttribute("data-render-index",x.toString()),l.current.observe(h)),()=>{l.current&&l.current.unobserve(h)}),[]),c=m.useCallback((p,x)=>{if(typeof x!="number")return{};const h=x<=t;return{visibility:h?"visible":"hidden",opacity:h?1:0,willChange:"opacity",transition:"opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1), transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)"}},[t]),u=m.useCallback((p,x)=>{if(typeof x!="number")return"";const h=x<=t;return`${p}-${x}-${h?"visible":"hidden"}`},[t]);m.useEffect(()=>{const h=Array.from(s.current).sort((y,f)=>y-f).find(y=>y>t);if(h!==void 0){const y=setTimeout(()=>{n(h)},50);return()=>clearTimeout(y)}return()=>{}},[t,r]);const d=m.useCallback(p=>typeof p!="number"?!0:p<=t,[t]),g=m.useMemo(()=>({getSectionSx:c,getSectionKey:u,observeSection:a,shouldRender:d}),[c,a,d,u]);return o.jsx(Oe.Provider,{value:g,children:e})}const wo=()=>m.useContext(Oe),ee=["editing","height","locale","dev","sx"],Co=m.forwardRef((e,t)=>{const{className:n,...r}=e;return o.jsx(jo,{ref:t,...r,className:v.cx("BlockBase-root",n)})}),jo=I.styled(A.Box)`
|
|
2
2
|
position: relative;
|
|
3
3
|
color: ${({theme:e})=>e.palette.text.primary};
|
|
4
4
|
`,Ye=m.createContext({pages:[],project:void 0}),{Provider:Io,Consumer:pr}=Ye;function Je(){return m.useContext(Ye)}function Eo({icon:e,...t}){return o.jsx(ze.Icon,{icon:e,...t,ref:null})}function So({icon:e,className:t="",size:n="1rem",...r}){return o.jsx(Ro,{component:Eo,className:v.cx("css-icon",t),size:n,...r,icon:e})}const Ro=I.styled(A.Box)`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),N=require("./state-BP5DoD6I.js"),q=require("@arcblock/ux/lib/Locale/context"),Y=require("@arcblock/ux/lib/Toast"),Z=require("@blocklet/pages-kit/utils/route"),C=require("@mui/icons-material"),F=require("@mui/lab"),s=require("@mui/material"),ee=require("immer"),te=require("lodash/difference"),a=require("react"),se=require("react-use"),ne=require("./home-CP3WKJ_e.js"),H=require("./index-BqynZDZ3.js"),J=o=>o&&o.__esModule?o:{default:o},z=J(Y),V=J(te);function ie(o){const[x,g]=a.useState(!1);return e.jsx(F.LoadingButton,{...o,loading:o.loading||x,onClick:c=>{const m=o.onClick?.(c);m instanceof Promise&&(g(!0),m.finally(()=>{g(!1)}))}})}const oe=s.createSvgIcon(e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M7.75732 16.2426L16.2426 7.75736",stroke:"#4B5563",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M16.2426 16.2426L7.75732 7.75735",stroke:"#4B5563",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),"Close");function re(){const[o,x]=a.useState(),g=a.useMemo(()=>o?e.jsx(s.Dialog,{...o}):null,[o]),c=a.useCallback(()=>{x(void 0)},[]),m=a.useCallback(({title:b,content:d,cancelText:P="Cancel",okText:f="Ok",onOk:y,onClose:u,okIcon:L,okColor:k="primary",cancelColor:h="primary",DialogContentProps:v,form:R,...I})=>{x({...I,open:!0,children:e.jsxs("form",{onSubmit:B=>B.preventDefault(),children:[b&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:B=>`1px solid ${B.palette.divider}`},children:[e.jsx(s.Box,{children:b}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{c(),u?.()},children:e.jsx(oe,{})})]}),d&&e.jsx(s.DialogContent,{...v,sx:{mt:-3,...v?.sx,bgcolor:"background.paper"},children:e.jsx(s.Box,{sx:{pt:3},children:d})}),e.jsxs(s.DialogActions,{sx:{bgcolor:"background.paper"},children:[e.jsx(s.Button,{variant:"outlined",color:h||"primary",onClick:u??c,children:P}),e.jsx(ie,{variant:"contained",color:k||"primary",startIcon:L,loadingPosition:L?"start":"center",onClick:async()=>{await y?.(),c()},type:"submit",children:f})]})]}),onClose:u??c})},[c]);return{dialog:g,showDialog:m,closeDialog:c}}const ae=({ref:o,mode:x,state:g})=>{const{t:c}=q.useLocaleContext(),[m,b]=a.useState(!1),{dialog:d,showDialog:P}=re(),f=N.useProjectId(),y=a.useCallback(L=>{let k=[];P({title:c("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(C.Warning,{}),children:c("maker.publishToProductionTip")}),e.jsx(s.Box,{sx:{maxHeight:"50vh",overflow:"auto",mt:2},children:e.jsx(ce,{state:g,toMode:x,onChange:h=>k=h,defaultRouteIds:L})})]}),okText:c("maker.publish"),cancelText:c("common.cancel"),onOk:async()=>{if(k?.length===0){const h=c("maker.publishSelectPagesMessage");throw z.default.error(h),new Error(h)}localStorage.setItem(N.getProjectPageVersionKey(f??""),String(new Date().getTime())),b(!0);try{await H.publishPages({mode:x,routes:k}),z.default.success(c("maker.publishSuccessMessage"))}catch(h){throw z.default.error(h.message),h}finally{b(!1)}}})},[x,g,c,f,P]);a.useImperativeHandle(o,()=>({openPublishDialog:y}));const u=a.useCallback(()=>{y()},[y]);return e.jsxs(e.Fragment,{children:[e.jsx(F.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:u,loading:m,disabled:m,children:c("maker.publish")}),d]})};function le({routePathInfo:o,checked:x,onClick:g,route:c}){const{t:m}=q.useLocaleContext(),b=!o.routeMetaData?.publishedAt||o.routeMetaData?.updatedAt&&new Date(o.routeMetaData?.updatedAt)>new Date(o.routeMetaData?.publishedAt);return e.jsx(s.ListItem,{sx:{pl:4,pr:3},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{sx:{display:"flex",alignItems:"center",minWidth:"auto"},children:[b&&e.jsx(s.Box,{className:"visible",title:m("maker.pages.needPublish"),sx:{mr:.35,color:"warning.main",display:"flex",alignItems:"center"},children:e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(C.Sync,{fontSize:"small",sx:{fontSize:"16px"}})})}),(!o.routeMetaData?.isPublic||!c.isPublic)&&e.jsx(s.Box,{className:"visible",sx:{color:"warning.main"},children:e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(C.VisibilityOff,{fontSize:"small",sx:{fontSize:"16px"}})})})]}),children:e.jsxs(s.ListItemButton,{onClick:g,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:x,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:o.path,slotProps:{primary:{fontSize:"0.8rem",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pr:1}}})]})})}function ce({state:o,toMode:x,onChange:g,defaultRouteIds:c}){const{t:m,locale:b}=q.useLocaleContext(),[d,P]=a.useState(!1),[f,y]=a.useState(()=>c?Object.fromEntries(c.filter(t=>!t.includes("-")).map(t=>[t,!0])):{}),[u,L]=a.useState({}),[k,h]=a.useState(()=>c?Object.fromEntries(c.filter(t=>t.includes("-")).map(t=>[t,!0])):{}),[v,R]=a.useState({}),{loading:I,error:B,value:w}=se.useAsync(()=>H.getPages({mode:x}),[x]);if(B)throw B;const j=a.useMemo(()=>o.routeIds||[],[o]),M=a.useMemo(()=>w?.pageIds||[],[w]),D=a.useMemo(()=>!j||!o.routes?[]:JSON.parse(JSON.stringify(j)).sort((n,i)=>{const r=o.routes?.[n],l=o.routes?.[i];return r?.publishedAt&&new Date(r.publishedAt).getTime()<new Date(r.updatedAt).getTime()?-1:l?.publishedAt&&new Date(l.publishedAt).getTime()<new Date(l.updatedAt).getTime()?1:new Date(r?.updatedAt??"").getTime()-new Date(l?.updatedAt??"").getTime()}),[o,j]),E=a.useMemo(()=>{if(!D)return[];if(!u)return D;const t=[...D].filter(n=>!u[n]);return Object.values(u).forEach(n=>{n.forEach(i=>{t.push(`${i.originalRouteId}-${i.paramOptionIds.join("-")}`)})}),t},[D,u]),O=a.useMemo(()=>!w||!M||!E?[]:V.default(M,E),[E,w,M]),T=a.useMemo(()=>j?[...j].concat(O):O,[j,O]),$=a.useCallback(()=>{const t={};D?.forEach(n=>{const i=o.routes?.[n];if(i&&i.params&&i.params.length>0&&i.paramsOptions&&i.paramsOptions.length>0){const r=Z.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});r.length>0&&(t[i.id]=r)}}),L(t)},[D,o.routes]);a.useEffect(()=>{$()},[$]),a.useEffect(()=>{R(t=>{const n={...t};return Object.keys(u).forEach(i=>{u[i]&&u[i]?.length>0&&n[i]===void 0&&(n[i]=!0)}),n})},[u]);const W=a.useRef(!0);a.useEffect(()=>{h(t=>{const n={...t};return Object.keys(u).length===0||(Object.keys(u).forEach(i=>{const r=u[i]||[],l=d||!!f[i];r.forEach(A=>{const p=`${i}-${A.paramOptionIds.join("-")}`;W.current?n[p]=l||t[p]||!1:n[p]=l})}),W.current=!1),n})},[f,u,d]);const U=(t,n)=>{n.stopPropagation(),R(i=>{const r={...i};return r[t]=!r[t],r})},_=a.useCallback(t=>{y(n=>{const i=ee.produce(n,r=>{d?(Object.assign(r,Object.fromEntries(T.map(l=>[l,!0]))),delete r[t]):r[t]?(delete r[t],O.includes(t)&&(j||[]).filter(l=>o.pages[l]?.slug===w?.pages[t]?.slug).forEach(l=>{delete r[l]})):(r[t]=!0,j&&j.includes(t)&&O.filter(l=>w?.pages[l]?.slug===o.pages[t]?.slug).forEach(l=>{r[l]=!0}))});return P(V.default(T,Object.keys(i)).length===0),i})},[d,T,O,o,w,j]),G=a.useCallback((t,n)=>{const i=`${t}-${n.paramOptionIds.join("-")}`;h(r=>{const l={...r};l[i]=!l[i];const A=u[t]?.every(p=>l[`${t}-${p.paramOptionIds.join("-")}`])??!1;return y(p=>{if(A&&!p[t])return{...p,[t]:!0};if(!A&&p[t]){const S={...p};return delete S[t],S}return p}),l})},[u]),Q=a.useCallback(()=>{P(t=>(t&&y({}),!t))},[]);return a.useEffect(()=>{const t=d?T:Object.keys(f),n=Object.entries(k).filter(([,r])=>r).map(([r])=>r).filter(r=>r!==void 0),i=Array.from(new Set([...t,...n]));g(d?null:i)},[d,f,k,T,g]),I?e.jsx(ne.Loading,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:700},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:Q,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:m("common.all")})]})}),D.map(t=>{const n=o.routes?.[t];if(!n)return null;const i=!1,r=u&&u[t]&&u[t]?.length>0,l=v[t]!==!1,A=u[t]||[],p=!n.publishedAt||n.updatedAt&&new Date(n.updatedAt).getTime()>new Date(n.publishedAt).getTime();return e.jsxs(s.Box,{children:[e.jsx(s.ListItem,{sx:{pr:4},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{sx:{display:"flex",alignItems:"center"},children:[p&&e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(C.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!n.isPublic&&e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(C.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),i,r&&e.jsx(s.Box,{onClick:S=>U(t,S),sx:{display:"inline-flex",alignItems:"center",mr:.35,cursor:"pointer",color:"info.main"},children:l?e.jsx(C.KeyboardArrowDown,{fontSize:"small",sx:{fontSize:"18px"}}):e.jsx(C.KeyboardArrowRight,{fontSize:"small",sx:{fontSize:"18px"}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>_(t),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d||!!f[t],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:n.path,slotProps:{primary:{noWrap:!0,textOverflow:"ellipsis"},secondary:{noWrap:!0,textOverflow:"ellipsis"}}})]})}),r&&e.jsx(s.Collapse,{in:l,children:e.jsx(s.Box,{children:A.map(S=>{const K=`${t}-${S.paramOptionIds.join("-")}`,X=k[K]||!1;return e.jsx(le,{routePathInfo:S,checked:d||X,onClick:()=>G(t,S),route:n},K)})})})]},t)}),O.map(t=>{const n=w?.pages[t];return n?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>_(t),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d||!!f[t],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:n.slug,secondary:n.locales?.[b]?.title,slotProps:{primary:{noWrap:!0,textOverflow:"ellipsis"},secondary:{noWrap:!0,textOverflow:"ellipsis"}}})]})},t):null})]})}exports.default=ae;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),N=require("./state-BAjDjwwp.js"),q=require("@arcblock/ux/lib/Locale/context"),Y=require("@arcblock/ux/lib/Toast"),Z=require("@blocklet/pages-kit/utils/route"),C=require("@mui/icons-material"),F=require("@mui/lab"),s=require("@mui/material"),ee=require("immer"),te=require("lodash/difference"),a=require("react"),se=require("react-use"),ne=require("./home-ymdnbwRQ.js"),H=require("./index-BAiZumV7.js"),J=o=>o&&o.__esModule?o:{default:o},z=J(Y),V=J(te);function ie(o){const[x,g]=a.useState(!1);return e.jsx(F.LoadingButton,{...o,loading:o.loading||x,onClick:c=>{const m=o.onClick?.(c);m instanceof Promise&&(g(!0),m.finally(()=>{g(!1)}))}})}const oe=s.createSvgIcon(e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M7.75732 16.2426L16.2426 7.75736",stroke:"#4B5563",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M16.2426 16.2426L7.75732 7.75735",stroke:"#4B5563",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),"Close");function re(){const[o,x]=a.useState(),g=a.useMemo(()=>o?e.jsx(s.Dialog,{...o}):null,[o]),c=a.useCallback(()=>{x(void 0)},[]),m=a.useCallback(({title:b,content:d,cancelText:P="Cancel",okText:f="Ok",onOk:y,onClose:u,okIcon:L,okColor:k="primary",cancelColor:h="primary",DialogContentProps:v,form:R,...I})=>{x({...I,open:!0,children:e.jsxs("form",{onSubmit:B=>B.preventDefault(),children:[b&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:B=>`1px solid ${B.palette.divider}`},children:[e.jsx(s.Box,{children:b}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{c(),u?.()},children:e.jsx(oe,{})})]}),d&&e.jsx(s.DialogContent,{...v,sx:{mt:-3,...v?.sx,bgcolor:"background.paper"},children:e.jsx(s.Box,{sx:{pt:3},children:d})}),e.jsxs(s.DialogActions,{sx:{bgcolor:"background.paper"},children:[e.jsx(s.Button,{variant:"outlined",color:h||"primary",onClick:u??c,children:P}),e.jsx(ie,{variant:"contained",color:k||"primary",startIcon:L,loadingPosition:L?"start":"center",onClick:async()=>{await y?.(),c()},type:"submit",children:f})]})]}),onClose:u??c})},[c]);return{dialog:g,showDialog:m,closeDialog:c}}const ae=({ref:o,mode:x,state:g})=>{const{t:c}=q.useLocaleContext(),[m,b]=a.useState(!1),{dialog:d,showDialog:P}=re(),f=N.useProjectId(),y=a.useCallback(L=>{let k=[];P({title:c("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(C.Warning,{}),children:c("maker.publishToProductionTip")}),e.jsx(s.Box,{sx:{maxHeight:"50vh",overflow:"auto",mt:2},children:e.jsx(ce,{state:g,toMode:x,onChange:h=>k=h,defaultRouteIds:L})})]}),okText:c("maker.publish"),cancelText:c("common.cancel"),onOk:async()=>{if(k?.length===0){const h=c("maker.publishSelectPagesMessage");throw z.default.error(h),new Error(h)}localStorage.setItem(N.getProjectPageVersionKey(f??""),String(new Date().getTime())),b(!0);try{await H.publishPages({mode:x,routes:k}),z.default.success(c("maker.publishSuccessMessage"))}catch(h){throw z.default.error(h.message),h}finally{b(!1)}}})},[x,g,c,f,P]);a.useImperativeHandle(o,()=>({openPublishDialog:y}));const u=a.useCallback(()=>{y()},[y]);return e.jsxs(e.Fragment,{children:[e.jsx(F.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:u,loading:m,disabled:m,children:c("maker.publish")}),d]})};function le({routePathInfo:o,checked:x,onClick:g,route:c}){const{t:m}=q.useLocaleContext(),b=!o.routeMetaData?.publishedAt||o.routeMetaData?.updatedAt&&new Date(o.routeMetaData?.updatedAt)>new Date(o.routeMetaData?.publishedAt);return e.jsx(s.ListItem,{sx:{pl:4,pr:3},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{sx:{display:"flex",alignItems:"center",minWidth:"auto"},children:[b&&e.jsx(s.Box,{className:"visible",title:m("maker.pages.needPublish"),sx:{mr:.35,color:"warning.main",display:"flex",alignItems:"center"},children:e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(C.Sync,{fontSize:"small",sx:{fontSize:"16px"}})})}),(!o.routeMetaData?.isPublic||!c.isPublic)&&e.jsx(s.Box,{className:"visible",sx:{color:"warning.main"},children:e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(C.VisibilityOff,{fontSize:"small",sx:{fontSize:"16px"}})})})]}),children:e.jsxs(s.ListItemButton,{onClick:g,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:x,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:o.path,slotProps:{primary:{fontSize:"0.8rem",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pr:1}}})]})})}function ce({state:o,toMode:x,onChange:g,defaultRouteIds:c}){const{t:m,locale:b}=q.useLocaleContext(),[d,P]=a.useState(!1),[f,y]=a.useState(()=>c?Object.fromEntries(c.filter(t=>!t.includes("-")).map(t=>[t,!0])):{}),[u,L]=a.useState({}),[k,h]=a.useState(()=>c?Object.fromEntries(c.filter(t=>t.includes("-")).map(t=>[t,!0])):{}),[v,R]=a.useState({}),{loading:I,error:B,value:w}=se.useAsync(()=>H.getPages({mode:x}),[x]);if(B)throw B;const j=a.useMemo(()=>o.routeIds||[],[o]),M=a.useMemo(()=>w?.pageIds||[],[w]),D=a.useMemo(()=>!j||!o.routes?[]:JSON.parse(JSON.stringify(j)).sort((n,i)=>{const r=o.routes?.[n],l=o.routes?.[i];return r?.publishedAt&&new Date(r.publishedAt).getTime()<new Date(r.updatedAt).getTime()?-1:l?.publishedAt&&new Date(l.publishedAt).getTime()<new Date(l.updatedAt).getTime()?1:new Date(r?.updatedAt??"").getTime()-new Date(l?.updatedAt??"").getTime()}),[o,j]),E=a.useMemo(()=>{if(!D)return[];if(!u)return D;const t=[...D].filter(n=>!u[n]);return Object.values(u).forEach(n=>{n.forEach(i=>{t.push(`${i.originalRouteId}-${i.paramOptionIds.join("-")}`)})}),t},[D,u]),O=a.useMemo(()=>!w||!M||!E?[]:V.default(M,E),[E,w,M]),T=a.useMemo(()=>j?[...j].concat(O):O,[j,O]),$=a.useCallback(()=>{const t={};D?.forEach(n=>{const i=o.routes?.[n];if(i&&i.params&&i.params.length>0&&i.paramsOptions&&i.paramsOptions.length>0){const r=Z.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});r.length>0&&(t[i.id]=r)}}),L(t)},[D,o.routes]);a.useEffect(()=>{$()},[$]),a.useEffect(()=>{R(t=>{const n={...t};return Object.keys(u).forEach(i=>{u[i]&&u[i]?.length>0&&n[i]===void 0&&(n[i]=!0)}),n})},[u]);const W=a.useRef(!0);a.useEffect(()=>{h(t=>{const n={...t};return Object.keys(u).length===0||(Object.keys(u).forEach(i=>{const r=u[i]||[],l=d||!!f[i];r.forEach(A=>{const p=`${i}-${A.paramOptionIds.join("-")}`;W.current?n[p]=l||t[p]||!1:n[p]=l})}),W.current=!1),n})},[f,u,d]);const U=(t,n)=>{n.stopPropagation(),R(i=>{const r={...i};return r[t]=!r[t],r})},_=a.useCallback(t=>{y(n=>{const i=ee.produce(n,r=>{d?(Object.assign(r,Object.fromEntries(T.map(l=>[l,!0]))),delete r[t]):r[t]?(delete r[t],O.includes(t)&&(j||[]).filter(l=>o.pages[l]?.slug===w?.pages[t]?.slug).forEach(l=>{delete r[l]})):(r[t]=!0,j&&j.includes(t)&&O.filter(l=>w?.pages[l]?.slug===o.pages[t]?.slug).forEach(l=>{r[l]=!0}))});return P(V.default(T,Object.keys(i)).length===0),i})},[d,T,O,o,w,j]),G=a.useCallback((t,n)=>{const i=`${t}-${n.paramOptionIds.join("-")}`;h(r=>{const l={...r};l[i]=!l[i];const A=u[t]?.every(p=>l[`${t}-${p.paramOptionIds.join("-")}`])??!1;return y(p=>{if(A&&!p[t])return{...p,[t]:!0};if(!A&&p[t]){const S={...p};return delete S[t],S}return p}),l})},[u]),Q=a.useCallback(()=>{P(t=>(t&&y({}),!t))},[]);return a.useEffect(()=>{const t=d?T:Object.keys(f),n=Object.entries(k).filter(([,r])=>r).map(([r])=>r).filter(r=>r!==void 0),i=Array.from(new Set([...t,...n]));g(d?null:i)},[d,f,k,T,g]),I?e.jsx(ne.Loading,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:700},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:Q,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:m("common.all")})]})}),D.map(t=>{const n=o.routes?.[t];if(!n)return null;const i=!1,r=u&&u[t]&&u[t]?.length>0,l=v[t]!==!1,A=u[t]||[],p=!n.publishedAt||n.updatedAt&&new Date(n.updatedAt).getTime()>new Date(n.publishedAt).getTime();return e.jsxs(s.Box,{children:[e.jsx(s.ListItem,{sx:{pr:4},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{sx:{display:"flex",alignItems:"center"},children:[p&&e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(C.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!n.isPublic&&e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(C.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),i,r&&e.jsx(s.Box,{onClick:S=>U(t,S),sx:{display:"inline-flex",alignItems:"center",mr:.35,cursor:"pointer",color:"info.main"},children:l?e.jsx(C.KeyboardArrowDown,{fontSize:"small",sx:{fontSize:"18px"}}):e.jsx(C.KeyboardArrowRight,{fontSize:"small",sx:{fontSize:"18px"}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>_(t),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d||!!f[t],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:n.path,slotProps:{primary:{noWrap:!0,textOverflow:"ellipsis"},secondary:{noWrap:!0,textOverflow:"ellipsis"}}})]})}),r&&e.jsx(s.Collapse,{in:l,children:e.jsx(s.Box,{children:A.map(S=>{const K=`${t}-${S.paramOptionIds.join("-")}`,X=k[K]||!1;return e.jsx(le,{routePathInfo:S,checked:d||X,onClick:()=>G(t,S),route:n},K)})})})]},t)}),O.map(t=>{const n=w?.pages[t];return n?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>_(t),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d||!!f[t],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:n.slug,secondary:n.locales?.[b]?.title,slotProps:{primary:{noWrap:!0,textOverflow:"ellipsis"},secondary:{noWrap:!0,textOverflow:"ellipsis"}}})]})},t):null})]})}exports.default=ae;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const f=require("./components-DLLpFRy5.js"),F=require("@syncedstore/core"),Je=require("yjs"),We=require("@blocklet/pages-kit/utils/data-source"),Q=require("@blocklet/pages-kit/utils/route"),Qe=require("lodash/cloneDeep"),Xe=require("@blocklet/sdk/lib/config"),I=require("fs"),g=require("path"),Te=require("@blocklet/pages-kit/utils/common"),Ze=require("@blocklet/pages-kit/utils/page-model"),et=require("@blocklet/pages-kit/utils/property"),Ie=require("@blocklet/sdk/lib/component"),tt=require("@reactivedata/reactive"),X=require("glob"),st=require("lib0/decoding"),at=require("lib0/encoding"),nt=require("lodash/debounce"),ot=require("lodash/get"),rt=require("lodash/isEmpty"),it=require("lodash/set"),ct=require("lodash/union"),be=require("lru-cache"),lt=require("p-limit"),C=require("sequelize"),pt=require("stream/promises"),ut=require("tar"),z=require("ufo"),dt=require("wait-on"),G=require("y-protocols/awareness"),le=require("y-protocols/sync"),ft=require("yaml"),De=require("./html-JOhPskS4.js");require("sqlite3");require("@blocklet/pages-kit/types/state");const $=t=>t&&t.__esModule?t:{default:t};function ae(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const a=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const U=ae(Je),Le=$(Qe),w=$(Xe),pe=ae(st),k=ae(at),_e=$(nt),Ee=$(ot),we=$(rt),ve=$(it),gt=$(ct),mt=$(lt),ht=$(dt),x=ae(ft),yt=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):yt(t,e);const M=new C.Sequelize({dialect:"sqlite",storage:f.databaseUrl,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});M.query("pragma journal_mode = WAL;");M.query("pragma synchronous = normal;");M.query("pragma journal_size_limit = 33554432;");M.query("pragma cache_size = -2000;");M.query("pragma mmap_size = 33554432;");process.on("SIGINT",async()=>{await M.close(),process.exit(0)});process.on("SIGTERM",async()=>{await M.close(),process.exit(0)});async function St(t,e){try{if(t.getDialect()!=="sqlite")return;const[s]=await t.query("SELECT 1");if(!s||s.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(s){if(s.name==="SequelizeConnectionError"||s?.message&&/closed!/.test(s.message))return;console.error("Failed to cleanup SQLite memory",e,s)}}let fe=null;fe&&clearInterval(fe);fe=setInterval(async()=>{f.logger.info("Start cleanupSqliteMemory"),await St(M,f.databaseUrl),f.logger.info("End cleanupSqliteMemory")},60*1e3*10);class Ae extends C.Model{}Ae.init({id:{type:C.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:C.DataTypes.UUIDV4},projectId:{type:C.DataTypes.UUID,allowNull:!1},componentId:{type:C.DataTypes.STRING,allowNull:!1}},{sequelize:M,tableName:"ProjectComponents",timestamps:!1});class L extends C.Model{static async getProjectByIdOrSlug(e){return L.findOne({where:{[C.Op.or]:[{id:e},{slug:e}]}})}}L.init({id:{type:C.DataTypes.UUID,defaultValue:C.DataTypes.UUIDV4,primaryKey:!0},name:{type:C.DataTypes.STRING,allowNull:!1},description:C.DataTypes.TEXT,createdAt:C.DataTypes.DATE,updatedAt:C.DataTypes.DATE,createdBy:{type:C.DataTypes.STRING,allowNull:!1},updatedBy:{type:C.DataTypes.STRING,allowNull:!1},slug:C.DataTypes.STRING,icon:C.DataTypes.STRING,pinnedAt:C.DataTypes.DATE,useAllResources:C.DataTypes.BOOLEAN,npmSecret:C.DataTypes.STRING,relatedBlocklets:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("relatedBlocklets");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.logger.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){f.logger.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("productionState");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.logger.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){f.logger.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}}},{sequelize:M,paranoid:!0});L.hasMany(Ae,{foreignKey:"projectId",as:"components"});const It="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ge="page",me="trigger-reload-project-resource",Pe=It,bt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function Z(t){t.observeDeep(e=>{e.some(s=>s.changes.keys.has("updatedAt")||s.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Ue(){return I.mkdtempSync(g.join(w.default.env.dataDir,"tmp-"))}function ee(t,e,s=[]){return Array.isArray(t)?t.flatMap((a,n)=>ee(a,e,[...s,n])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([a,n])=>ee(n,e,[...s,a])):e(t)?[s]:[]}function R(t){return t.filter(e=>e!=null)}function Et(t){t.pages&&Object.keys(t.pages).forEach(s=>{const a=F.getYjsValue(t.pages[s]);a&&a instanceof U.Map&&Z(a)});const e=F.getYjsValue(t.pages);e&&e instanceof U.Map&&e.observe(s=>{s.changes.keys.forEach((a,n)=>{if(a.action==="add"){const o=F.getYjsValue(t.pages[n]);o&&o instanceof U.Map&&Z(o)}})})}function wt(t){t.routes&&Object.keys(t.routes).forEach(s=>{const a=F.getYjsValue(t.routes?.[s]);a&&a instanceof U.Map&&Z(a)});const e=F.getYjsValue(t.routes);e&&e instanceof U.Map&&e.observe(s=>{s.changes.keys.forEach((a,n)=>{if(a.action==="add"){const o=F.getYjsValue(t.routes?.[n]);o&&o instanceof U.Map&&Z(o)}})})}function At(t,e){for(const s of e||Object.keys(t.routes||{})){let a=s,n=[];if(s.includes("-")){const[o,...c]=s.split("-");a=o,n=c||[]}if(t.routes?.[a]!==void 0){t.routes[a].publishedAt=new Date().toISOString();const o=t.routes[a];if(!o||!o.params||o.params.length===0)continue;if(s.includes("-")&&n.length>0){const c=Q.getRouteMetaDataByOptionIds(n,o);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=Q.generateParamCombinations({basePath:o.path,params:o.params,routeId:o.id,paramsOptions:o.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const p of c)p.routeMetaData??={},p.routeMetaData.publishedAt=new Date().toISOString()}}}}function ue({page:t,route:e,state:s,routeId:a,routePathInfo:n}){f.logger.info(`Executing datasource data assembly, routeId: ${a}, routePathInfo: ${JSON.stringify(n)}`);const o={...Le.default(t),id:a,slug:n?.path??e.path,createdAt:e.createdAt,updatedAt:n?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:n?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(n?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of s.supportedLocales){if(e.dataSource){let p=e.id;n&&(p=n.paramOptionIds.join("-"));const l=e.dataSource.pathDataMappings?.[p]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[p]?.dataCache?.[s.config.defaultLocale||"en"];if(!l)continue;We.setPageDataSource(o,s,c.locale,l)}n&&n.routeMetaData&&(n.routeMetaData.publishedAt=new Date().toISOString())}return o}["true","1","yes","y"].includes(process.env.USE_FS_CACHE_HTML??"");const Pt=60*60*1e3,Y=new be.LRUCache({max:100,ttl:Pt,ttlResolution:10*1e3,allowStale:!0});function jt(t,e=[]){let s=0;const a=Array.from(Y.keys());for(const n of a)for(const o of t){if(De.matchCacheKey(n,{currentPath:o})){Y.delete(n),s++,f.logger.info(`[Cache CLEAR] key: ${n}`);break}for(const c of e)if(De.matchCacheKey(n,{currentPath:`/${c}${o}`})){Y.delete(n),s++,f.logger.info(`[Cache CLEAR] key: ${n}`);break}}return f.logger.info(`[Cache CLEAR] cleared ${s} entries for paths:`,t),s}function Ot(){const t=Y.size;return Y.clear(),f.logger.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}w.default.events.on(w.default.Events.envUpdate,Ot);const{uploadToMediaKit:Ct}=require("@blocklet/uploader-server"),je=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,H=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,ke=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Tt=1e4,Dt=3e4,J=0,de=1,vt=0,kt=1,he=w.default,q=g.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Rt=["production","draft"],Lt=["production"];function te(t){return t?.replace(/\//g,"|")||""}function Me(){const t=he.env.languages?.map(s=>({locale:s.code,name:s.name}))||[],e=t[0]?.locale||"en";return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class O extends U.Doc{constructor(e){super(),this.options=e,I.existsSync(this.draftYjsFilePath)&&U.applyUpdate(this,I.readFileSync(this.draftYjsFilePath)),this.syncedStore=tt.reactive(F.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new be.LRUCache({max:100,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=g.join(q,e),a=g.join(q,`@del-${e}`);I.renameSync(s,a)}catch(s){f.logger.error("Failed to safe delete project state dir:",s)}}static async getProjectIds(){return(await L.findAll({attributes:["id"],raw:!0}))?.map(e=>e.id)}static get projectIds(){return X.globSync("*/",{cwd:q,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>O.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=O.sharedInstances[e];return s||(s=new O({path:g.join(q,e)}),O.sharedInstances[e]=s,s)}static async getProductionState(e){const s=await L.findByPk(e,{attributes:["productionState"]});if(we.default(s?.productionState)){const a=g.join(q,e,"production"),n=await Oe(a,{includeResources:!0})??Me();if(!n?.config?.defaultLocale){n.config??={};const o=he.env.languages?.map(c=>({locale:c.code,name:c.name}))||[];n.config.defaultLocale=o[0]?.locale}return n}return s?.productionState}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((s,a)=>this.closeConn(a)),this.awareness.destroy();const e=g.basename(this.options.path);delete O.sharedInstances[e],super.destroy()}initObserver(){Et(this.syncedStore),wt(this.syncedStore)}get draftYjsFilePath(){return g.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,s){if(s==="draft"){const a=O.shared(e);return JSON.parse(JSON.stringify(a.syncedStore))}return O.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const s=g.basename(this.options.path);return O.getProductionState(s)}async setState(e,s){const a=await qe(s,{exportAssets:!1,includeResources:!0}),n=this.getPublishDir(e);if(I.mkdirSync(g.dirname(n),{recursive:!0}),I.rmSync(n,{force:!0,recursive:!0}),I.renameSync(a,n),e==="production"){const o=g.basename(this.options.path);O.pageUrlMapCache.delete(o),await L.update({productionState:{...s}},{where:{id:o}})}}getPublishDir(e){return g.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:s,removed:a},n)=>{const o=e.concat(s,a);if(n!==null){const l=this.conns.get(n);l&&(e.forEach(S=>{l.add(S)}),a.forEach(S=>{l.delete(S)}))}const c=k.createEncoder();k.writeVarUint(c,de),k.writeVarUint8Array(c,G.encodeAwarenessUpdate(this.awareness,o));const p=k.toUint8Array(c);this.conns.forEach((l,S)=>this.send(S,p))};updateHandler=e=>{const s=k.createEncoder();k.writeVarUint(s,J),le.writeUpdate(s,e);const a=k.toUint8Array(s);this.conns.forEach((n,o)=>this.send(o,a))};ensureDataStructure=()=>{const{supportedLocales:e,pages:s,pageIds:a,config:n,routes:o,routeIds:c}=this.syncedStore;{const p=new Set(Object.keys(s));let l=0;for(;l<a.length;){const S=a[l];p.has(S)?(p.delete(S),l++):a.splice(l,1)}}{const p=new Set(Object.keys(o));let l=0;for(;l<c.length;){const S=c[l];p.has(S)?(p.delete(S),l++):c.splice(l,1)}}e.splice(0,e.length),e.push(...he.env.languages.map(p=>({locale:p.code,name:p.name}))),n.defaultLocale=e[0]?.locale;{let p=0;const l=new Set;for(;p<e.length;){const{locale:S}=e[p];l.has(S)?e.splice(p,1):(p++,l.add(S))}}};send=(e,s)=>{e.readyState!==vt&&e.readyState!==kt&&this.closeConn(e);try{e.send(s,a=>{a&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&G.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=g.basename(this.options.path);this.releaseTimer=setTimeout(()=>{f.logger.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},O.RELEASE_DELAY),f.logger.info(`[SiteState] scheduled release for project ${e} in ${O.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=g.basename(this.options.path);f.logger.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=_e.default(()=>{I.mkdirSync(g.dirname(this.draftYjsFilePath),{recursive:!0}),I.writeFileSync(this.draftYjsFilePath,U.encodeStateAsUpdate(this))},Tt);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:s})=>{const a=await this.getState("draft"),n=await this.getState("production");await Se(a,n,{routes:s,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),n.config.publishedAt=new Date().getTime(),At(this.syncedStore,s),await this.setState(e,n),await this.clearPageCacheForRoutes(s,n)};mergeState=async(e,s)=>{const a=JSON.parse(JSON.stringify(s));e.config.fontFamily??={};const n=a.config?.fontFamily,o=e.config?.fontFamily;e.config.fontFamily.title=n?.title||o?.title,e.config.fontFamily.description=n?.description||o?.description,await new Promise((c,p)=>{this.transact(async()=>{try{const l=await Se(e,s);c(l)}catch(l){p(l)}})})};clearPageCacheForRoutes=async(e,s)=>{const a=g.basename(this.options.path),o=(await L.findByPk(a))?.slug||a;let c=e;(!c||c.length===0)&&(c=s.pageIds??[]),f.logger.info(`[SiteState] clearing page cache for project ${a}, routes:`,c||[]);const p=s.supportedLocales.map(A=>A.locale),l=[],S=c.filter(A=>s.pageIds?.includes(A));for(const A of S){const E=s.pages[A].slug;o&&o!==a&&(o==="/"?l.push(E):l.push(`/${o}${E}`)),l.push(`/${a}${E}`)}if(f.logger.info(`[SiteState] clearing page cache for project ${a}, pathPatterns:`,l),l.length>0)try{const A=jt(l,p);f.logger.info(`[SiteState] cleared ${A} page cache entries for project ${a}, routes:`,c)}catch{}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",n=>this.messageListener(e,new Uint8Array(n)));let s=!0;const a=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(a);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(a)}}},Dt);e.on("close",()=>{this.closeConn(e),clearInterval(a)}),e.on("pong",()=>{s=!0});{const n=k.createEncoder();k.writeVarUint(n,J),le.writeSyncStep1(n,this),this.send(e,k.toUint8Array(n));const o=this.awareness.getStates();if(o.size>0){const c=k.createEncoder();k.writeVarUint(c,de),k.writeVarUint8Array(c,G.encodeAwarenessUpdate(this.awareness,Array.from(o.keys()))),this.send(e,k.toUint8Array(c))}}};messageListener=(e,s)=>{try{const a=k.createEncoder(),n=pe.createDecoder(s),o=pe.readVarUint(n);switch(o){case J:k.writeVarUint(a,J),le.readSyncMessage(n,a,this,null),k.length(a)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(a)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(n),e);break}default:f.logger.warn(`Unsupported messageType ${o}`)}}catch(a){f.logger.error(a)}this.save()};static async pageUrlMap(e,s){let a=[];s?a=[s]:a=await this.getProjectIds();let n={};if(e==="production"&&a?.length){const o=new Map(a?.map(c=>[c,!0])||[]);for(const c of a){const p=O.pageUrlMapCache.get(c);p&&(n={...n,...p},o.delete(c))}a=Array.from(o.keys())}if(a?.length){const o=await L.findAll({where:{id:{[C.Op.in]:a}}});await Promise.all(o?.map(async c=>{const p=c.id,l=c.slug||p,S={},A=e==="production"&&c?.productionState?c.productionState:await O.getStateByProjectId(c.id,e),v=gt.default(w.default.env.languages?.map(u=>u.code)||[],A.supportedLocales?.map(u=>u.locale)||[]),E=(u,i)=>{l&&(S[z.joinURL("/",l,u)]={...i,shouldRedirect:!0,mainPage:!0}),S[z.joinURL("/",p,u)]={...i,shouldRedirect:!0,mainPage:!0};for(const h of v){const T={...i,locale:h};S[z.joinURL("/",h,p,u)]=T,l&&(S[z.joinURL("/",h,l,u)]=T)}};if(e==="draft")for(const u of A.routeIds||[]){const i=A?.routes?.[u];if(!i)continue;if(i.params&&i.params.length>0){const m=Q.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const d of m){const y=d.path,P={projectId:p,projectSlug:l,pageSlug:y,pageId:i.displayTemplateId||"",routeId:u,defaultLocale:v?.[0],locales:v,publishedAt:A.config.publishedAt,isPublic:i.isPublic&&d?.routeMetaData?.isPublic};E(y,P)}}const h=i.path,T={projectId:p,projectSlug:l,pageSlug:h,pageId:i.displayTemplateId||"",routeId:u,defaultLocale:v?.[0],locales:v,publishedAt:A.config.publishedAt,isPublic:i.isPublic};E(h,T)}for(const u of A.pageIds||[]){const i=A.pages[u];if(!i||e==="production"&&!i.isPublic)continue;const h=i.slug,T=c.slug||p,m={projectId:p,projectSlug:T,pageSlug:h,pageId:u,defaultLocale:v?.[0],locales:v,publishedAt:A.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};E(h,m)}e==="production"&&O.pageUrlMapCache.set(p,S),n={...n,...S}}))}return n}getDocumentSize(){return U.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,a]of Object.entries(O.sharedInstances)){const n=a.getDocumentSize();e.push({projectId:s,sizeInBytes:n,sizeInMB:`${(n/(1024*1024)).toFixed(2)} MB`,activeConnections:a.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),f.logger.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,f.logger.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(O.sharedInstances).length,s=[],a=[];for(const[n,o]of Object.entries(O.sharedInstances))o.conns.size===0?s.push({projectId:n,instance:o}):a.push({projectId:n,connections:o.conns.size});if(f.logger.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${a.length}, without connections: ${s.length}`),s.length>0){f.logger.info(`[SiteState] releasing ${s.length} instances without connections:`,s.map(o=>o.projectId));let n=0;for(const{projectId:o,instance:c}of s)try{f.logger.info(`[SiteState] releasing instance due to periodic check: ${o}`),c.destroy(),n++}catch(p){f.logger.error(`[SiteState] failed to release instance ${o} during periodic check:`,p)}f.logger.info(`[SiteState] periodic check completed: ${n}/${s.length} instances released successfully`)}else e>0?f.logger.debug("[SiteState] periodic check: all instances have active connections"):f.logger.debug("[SiteState] periodic check: no instances exist")}}async function _t(t,e,s){if(!t||!I.existsSync(t)||!I.lstatSync(t).isFile())return null;let a=s[t];return a||(a=(async()=>{try{return(await Ct({filePath:t,fileName:e}))?.data?.filename}catch(n){return f.logger.error(`Failed to upload asset ${t}:`,n),null}})(),s[t]=a),a}const $e=async(t,e)=>{const s=g.basename(t),a=await Ie.call({name:Pe,path:z.joinURL("/uploads",s),responseType:"stream",method:"GET"});if(a.status>=200&&a.status<400){const n=I.createWriteStream(e);await pt.pipeline(a.data,n)}else throw new Error(`download asset failed ${a.status}`)},Ne=async(t,e)=>{await Promise.all(t.map(async s=>{try{await $e(s,g.join(e,g.basename(s)))}catch(a){f.logger.error(`Failed to export assets: ${s}, ${a}`)}}))};function Fe(t){return je.test(t)?[t]:H.test(t)?(ke.lastIndex=0,Array.from(t.matchAll(ke)).map(s=>s[1]).filter(s=>!!s)):[]}async function W(t,e,s){const{getFilename:a,exportAssets:n}=s,o=g.join(e,a(t));if(I.mkdirSync(g.dirname(o),{recursive:!0}),I.writeFileSync(o,x.stringify(t)),n){const p=ee(t,l=>typeof l=="string"&&(je.test(l)||H.test(l))).map(l=>{const S=Ee.default(t,l);return Fe(S)}).flat().filter(Boolean);await Ne(p,g.dirname(o))}}const ye=new be.LRUCache({max:100,ttl:1*60*1e3});async function Re(t,e,s){const a=ee(t,p=>typeof p=="string"&&(je.test(p)||H.test(p))),n=mt.default(2),o=a.map(p=>n(async()=>{try{const l=Ee.default(t,p),S=Fe(l);for(const A of S){const v=g.basename(A),E=s.getFilePath(A,p),u=E?`${E}:${v}`:v,i=ye.get(u);if(i){H.test(l)||ve.default(t,p,i);return}const h=await _t(E,v,e);h&&(H.test(l)||ve.default(t,p,h),ye.set(u,h))}}catch(l){f.logger.error(`Failed to process upload for path ${p.join(".")}:`,l.message||l.reason)}})),c=await Promise.allSettled(o);s.onFinish?.(c)}async function qe(t,{exportAssets:e,pageIds:s="all",componentIds:a="all",rawConfig:n,includeResources:o=!1,routeIds:c="all"}={}){const p=s==="all"?t.pageIds:s,l=et.getComponentDependencies({state:t,pageIds:p,componentIds:a==="all"?Object.keys(t.components):a}),S=c==="all"?t.routeIds:c,A=r=>({id:r.id,name:r.name,isTemplateSection:r.isTemplateSection??!1,templateDescription:r.templateDescription,component:r.component,config:r.config,visibility:r.visibility,sections:r?.sectionIds?R(r?.sectionIds?.map(b=>{const D=r.sections?.[b];return D&&A(D)})):void 0}),v=(r,b)=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,meta:r.locales?.[b]??{},sections:R(r.sectionIds.map(D=>{const N=r.sections[D];return N&&A(N)})),dataSource:Object.fromEntries(Object.entries(r.dataSource||{}).map(([D,N])=>[D,N?.[b]??{}]))}),E=r=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,path:r.path,handler:r.handler,isPublic:r.isPublic??!0,params:r.params??[],enabledGenerate:r.enabledGenerate??!1,displayTemplateId:r.displayTemplateId,dataSource:r.dataSource}),u=R(S.map(r=>{const b=t.routes[r];return b&&E(b)})),i=R(t.supportedLocales.map(r=>r.locale).flatMap(r=>p.map(b=>{const D=t.pages[b];return D&&{locale:r,slug:D.slug,page:v(D,r)}}))),h=Ue(),T=g.join(h,"pages");I.mkdirSync(T,{recursive:!0});const m=g.join(h,"components");I.mkdirSync(m,{recursive:!0});const d=g.join(h,"routes");I.mkdirSync(d,{recursive:!0});for(const{locale:r,slug:b,page:D}of i)await W(D,T,{getFilename:()=>`${te(b)||"index"}.${r}.yml`,exportAssets:e});for(const r of u)await W(r,d,{getFilename:()=>`${te(r.path)||"index"}.yml`,exportAssets:e});for(const r of l){const b=t.components[r]?.data;b&&await W(b,m,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:e})}const y=g.join(h,".blocklet/pages/pages.config.yml");I.mkdirSync(g.dirname(y),{recursive:!0});const P={pages:R(p.map(r=>{const b=t.pages[r];return b&&{id:r,slug:b.slug}})),routes:R(S.map(r=>{const b=t.routes[r];return b&&{id:r,path:b.path}})),components:R(l.map(r=>{const b=t.components[r]?.data;return b&&{id:r,name:b.name}})),...o?{resources:{components:R(Object.keys(t.resources?.components||{}).filter(r=>l.includes(r)).map(r=>({id:r,name:t.resources?.components?.[r]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};I.writeFileSync(y,x.stringify(P));const j=g.join(h,"config.source.json");if(n&&I.writeFileSync(j,JSON.stringify(n)),o){const r=g.join(h,"resources"),b=g.join(r,"components");I.mkdirSync(b,{recursive:!0});for(const B of Object.keys(t?.resources?.components??{}).filter(_=>l.includes(_))){const _=t.resources?.components?.[B]?.component;_&&await W(_,b,{getFilename:V=>`${V.name||"unnamed"}.${V.id}.yml`,exportAssets:e})}const D=g.join(h,"chunks");I.mkdirSync(D,{recursive:!0});const N=Ut();for(const B of Object.keys(t?.resources?.components??{}).filter(_=>l.includes(_))){const _=t.resources?.components?.[B]?.component;if(_&&_.renderer?.type==="react-component"){const V=_.renderer?.chunks??[];if(V?.length>0)for(const ie of V){const Ce=g.join(D,ie),ce=N?.[ie];try{ce&&I.existsSync(ce)&&!I.existsSync(Ce)&&I.copyFileSync(ce,Ce)}catch(Ke){f.logger.error(`copy chunk ${ie} error`,Ke.message)}}}}}return h}async function Oe(t,{importAssets:e,includeResources:s}={}){if(!I.existsSync(t))return null;let a,n=!1;try{I.lstatSync(t).isDirectory()?a=t:/\.(tgz|gz|tar)$/.test(t)&&(n=!0,a=Ue(),await ut.x({file:t,C:a}));const o=X.globSync("**/.blocklet/pages/pages.config.yml",{cwd:a,absolute:!0}).at(0),c=o&&g.join(g.dirname(o),"../../pages"),p=o&&g.join(g.dirname(o),"../../components"),l=o&&g.join(g.dirname(o),"../../routes");if(!o)return null;const S=x.parse(I.readFileSync(o).toString()),A=(m,d,y)=>{let P=g.join(m,`${d}${y?`.${y}`:""}.yml`);return(!I.existsSync(P)||!I.lstatSync(P).isFile())&&(P=g.join(m,d,`index${y?`.${y}`:""}.yml`),!I.existsSync(P)||!I.lstatSync(P))?null:x.parse(I.readFileSync(P).toString())},v=(m,d)=>{try{const y=X.globSync(`*.${d}.yml`,{cwd:m,absolute:!0})[0];return y?x.parse(I.readFileSync(y).toString()):null}catch(y){f.logger.error("parse component error",y)}return null},E=(m,d)=>{let y=g.join(m,`${d}.yml`);return(!I.existsSync(y)||!I.lstatSync(y).isFile())&&(y=g.join(m,d,"index.yml"),!I.existsSync(y)||!I.lstatSync(y))?null:x.parse(I.readFileSync(y).toString())},u=R(S.pages.map(({slug:m})=>{const d=R(S.supportedLocales.map(({locale:j})=>{const r=c?A(c,te(m),j):void 0;if(r)return{locale:j,page:r};const b=c?A(c,m,j):void 0;return b&&{locale:j,page:b}})),y=d[0]?.page;if(!y)return null;const P=y.sections.map(Ze.unzipSection);return{id:y.id||Te.nextId(),createdAt:y.createdAt,updatedAt:y.updatedAt,publishedAt:y.publishedAt,isPublic:y.isPublic??!0,templateConfig:y.templateConfig,slug:m,sections:Object.fromEntries(P.map(j=>[j.id,j])),sectionIds:P.map(j=>j.id),locales:Object.fromEntries(d.map(({locale:j,page:r})=>[j,r.meta])),dataSource:y.dataSource?Object.fromEntries([...new Set(d.flatMap(({page:j})=>Object.keys(j.dataSource??{})))].map(j=>[j,Object.fromEntries(d.map(({locale:r,page:b})=>{const D=b.dataSource?.[j];return[r,D||{}]}))])):Object.fromEntries([...new Set(d.flatMap(({page:j})=>j.sections.map(r=>r.id)))].map(j=>[j,Object.fromEntries(d.map(({locale:r,page:b})=>{const D=b.dataSource?.[j];if(D)return[r,D];const N=b.sections.find(B=>B.id===j);return[r,N?.properties||{}]}))]))}})),i=R(S?.routes?.map(({path:m})=>{const d=l?E(l,te(m)):void 0;return{...d,id:d?.id||Te.nextId(),createdAt:d?.createdAt??new Date().toISOString(),updatedAt:d?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:d?.path??`/${d?.id}`,params:d?.params,handler:d?.handler??"Pages Kit",isPublic:d?.isPublic??!0,enabledGenerate:d?.enabledGenerate??!1,displayTemplateId:d?.displayTemplateId??void 0,dataSource:d?.dataSource??{}}})??[]),h=p?R(S.components?.map(({id:m})=>v(p,m))??[]):[];if(e){const m=(...d)=>{f.logger.info(`[${n?g.basename(t):g.basename(g.join(t,"../../../../"))}] importAssets:`,...d)};try{m("wait image-bin api ready"),await ht.default({resources:[`${Ie.getComponentWebEndpoint(f.IMAGE_BIN_NAME)}/api/sdk/uploads`],validateStatus:P=>P>=200&&P<=500}),m("image-bin api is ready");const d={},y={};m("start to upload assets"),await Promise.allSettled([Re(h,d,{getFilePath:P=>p&&g.join(p,P),onFinish:P=>{m(`upload ${P.length} component assets`)}}),Re(u,y,{getFilePath:(P,j)=>{const r=Ee.default(u,j.slice(0,1));return c&&g.join(c,g.dirname(r.slug),P)},onFinish:P=>{m(`upload ${P.length} page assets`)}})]),m("upload assets done"),ye.clear(),global.gc&&global.gc()}catch(d){m("Error during asset import:",d)}}const T={};if(s){const m=o&&g.join(g.dirname(o),"../../resources/components"),d=R(S.resources?.components?.map(({id:y})=>v(m,y))??[]);d.length>0&&(T.components=Object.fromEntries(d.map((y,P)=>[y.id,{index:P,component:y}])))}return{supportedLocales:S.supportedLocales,pageIds:u.map(m=>m.id),components:Object.fromEntries(h.map((m,d)=>[m.id,{index:d,data:m}])),pages:Object.fromEntries(u.map(m=>[m.id,m])),config:S.config||{},resources:T,routeIds:i.map(m=>m.id),routes:Object.fromEntries(i.map(m=>[m.id,m])),dataSourceIds:[],dataSources:{}}}finally{n&&a&&I.rmSync(a,{force:!0,recursive:!0})}}async function Se(t,e,{routes:s,mergeMode:a="byUpdateTime",deleteRoutes:n=!1,publishMode:o=void 0}={}){try{o&&f.clearPreloadComponentsCacheByMode(o)}catch(E){f.logger.error("clear preload page cache error",{error:E})}const{pages:c,pageIds:p,routeIds:l,routes:S,supportedLocales:A}=t;if(o==="production"){let E=s??[],u=null;for(const i of l??[]){const h=S?.[i];if(h?.params&&h?.params.length>0&&h?.paramsOptions&&h?.paramsOptions.length>0){const T=Q.generateParamCombinations({basePath:h.path,params:h.params,routeId:h.id,paramsOptions:h.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),m=Object.fromEntries(T.map(d=>[`${i}-${d.paramOptionIds.join("-")}`,d]));u={...u||{},...m},s||(E=[...E,...T.map(d=>`${i}-${d.paramOptionIds.join("-")}`)])}else s||E.push(i)}f.logger.info("routeIds to be published: ",E);for(const i of E){let h=i;if(h.includes("-")){const[d]=h.split("-");h=d}const T=S?.[h];if(!T){const d=e.pageIds.indexOf(h);d!==-1&&n&&(e.pageIds.splice(d,1),delete e.pages[h]);for(const y of e.pageIds)y.includes(`${h}-`)&&(e.pageIds.splice(e.pageIds.indexOf(y),1),delete e.pages[y]);f.logger.info("delete main route page",h);continue}if(i.includes("-")&&!u?.[i]){const d=e.pageIds.indexOf(i);d!==-1&&n&&(e.pageIds.splice(d,1),delete e.pages[i]),f.logger.info("delete page",i);continue}if(!T.displayTemplateId){f.logger.info("no display template",i);continue}const m=c[T.displayTemplateId];if(!m){f.logger.info("no template page",i);continue}if(e.pageIds.includes(i)){if(f.logger.info("has need update page",i),a==="replace")e.pages[i]=ue({page:m,route:T,state:t,routeId:i,routePathInfo:u?.[i]}),f.logger.info("replace page",i);else if(a==="byUpdateTime"){const d=e.pages[T.id];(!d||T.updatedAt&&T.updatedAt>d.updatedAt)&&(e.pages[i]=ue({page:m,route:T,state:t,routeId:i,routePathInfo:u?.[i]}),f.logger.info("replace page by update time",i))}}else e.pageIds.push(i),e.pages[i]=ue({page:m,route:T,state:t,routeId:i,routePathInfo:u?.[i]}),f.logger.info("add page",i)}if(n&&!s)for(const i of e.pageIds)E?.includes(i)||(delete e.pages[i],f.logger.info("delete page",i)),e.pageIds=[...e.pageIds].filter(h=>E?.includes(h))}else{for(const E of p){const u=c[E];if(u)if(e.pageIds.includes(u.id)){if(a==="replace")e.pages[u.id]=u;else if(a==="byUpdateTime"){const i=e.pages[u.id];(!i||u.updatedAt&&u.updatedAt>i.updatedAt)&&(e.pages[u.id]=u)}}else e.pageIds.push(u.id),e.pages[u.id]=u}for(const E of l){const u=S[E];if(u)if(e.routeIds.includes(u.id)){if(a==="replace")e.routes[u.id]=u;else if(a==="byUpdateTime"){const i=e.routes[u.id];(!i||u.updatedAt&&u.updatedAt>i.updatedAt)&&(e.routes[u.id]=u)}}else e.routeIds.push(u.id),e.routes[u.id]=u}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Le.default(A)),n)for(const E of Object.keys(e.components))delete e.components[E];let v=JSON.parse(JSON.stringify(t.components));v=Object.fromEntries(await Promise.all(Object.entries(v).map(async([E,u])=>{const i=await xe(u?.data);return[E,{...u,data:i}]}))),Object.assign(e.components,v),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),we.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const xe=f.memoizeWithFs(async t=>{if(!we.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:s}=t?.renderer||{};if(s||e&&e.includes("PROPERTIES_SCHEMA"))try{const a=await f.getExportSchemaValueFromCode(e??"","PROPERTIES_SCHEMA",t.id,s);a&&a.length>0&&t&&(t.properties={},a.forEach((n,o)=>{t?.properties&&(t.properties[n.id]={index:o,data:n})}))}catch(a){f.logger.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:a})}}return t},{subdir:"getPropertiesFromCode"});let se,K,ne,oe;const Be=()=>Ie.getResources({types:[{did:Pe,type:ge},{did:bt,type:ge}]}),Ut=()=>{const t=Be(),e={};return t.forEach(s=>{const a=X.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s.path,absolute:!0}).at(0),n=a&&g.join(g.dirname(a),"../../chunks");if(n&&I.existsSync(n)){const o=I.readdirSync(n);for(const c of o)e[c]=g.join(n,c)}}),e};function Ve(){return se=(async()=>{const t=Be();K=(await Promise.all(t.map(async s=>{const a=s.path?await Oe(s.path,{importAssets:!1}):void 0;return a?{blockletId:s.did,state:a,blockletTitle:s.title}:void 0}))).filter(s=>!!s),ne=K.reduce((s,a)=>Object.assign(s,Object.fromEntries(Object.values(a.state.pages).map(n=>n?[n?.id,{page:n,blockletId:a.blockletId}]:[]))),{});const e=K.reduce((s,a)=>Object.assign(s,Object.fromEntries(Object.values(a.state.components).map(n=>[n.data.id,{blockletId:a.blockletId,component:n.data}]))),{});oe=Object.fromEntries(await Promise.all(Object.entries(e).map(async([s,a])=>{const n=await xe(a.component);return[s,{...a,component:n}]})))})(),se}function Ge(t){const e=_e.default(async()=>{await Ve().catch(s=>{f.logger.error("load resource states error",{error:s})}),await t?.({states:K,pages:ne,components:oe})},3e3,{leading:!1,trailing:!0});return e(),w.default.events.on(w.default.Events.componentAdded,e),w.default.events.on(w.default.Events.componentRemoved,e),w.default.events.on(w.default.Events.componentStarted,e),w.default.events.on(w.default.Events.componentStopped,e),w.default.events.on(w.default.Events.componentUpdated,e),w.default.events.on(me,e),()=>{w.default.events.off(w.default.Events.componentAdded,e),w.default.events.off(w.default.Events.componentRemoved,e),w.default.events.off(w.default.Events.componentStarted,e),w.default.events.off(w.default.Events.componentStopped,e),w.default.events.off(w.default.Events.componentUpdated,e),w.default.events.off(me,e)}}const ze=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),Ye=Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"),re=globalThis;re[ze]?.();re[ze]=Ge(async({pages:t,components:e})=>{const s=await O.getProjectIds();f.logger.info(`start update resource states projects(${s.length})`,s),await Promise.race([new Promise(a=>{setTimeout(()=>{a({})},30*1e3)}),Promise.all(s.map(async a=>{He({projectId:a,pages:t,components:e})}))]).catch(a=>{f.logger.error("update resource states failed:",a)})});re[Ye]?.();re[Ye]=()=>{const t=()=>{O.pageUrlMapCache.clear(),f.logger.info("[Cache CLEAR ALL] clear all page url map cache by env update")};return w.default.events.on(w.default.Events.envUpdate,t),()=>{w.default.events.off(w.default.Events.envUpdate,t)}};O.startPeriodicCheck();process.on("beforeExit",()=>{O.stopPeriodicCheck()});process.on("SIGINT",()=>{O.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{O.stopPeriodicCheck(),process.exit(0)});async function He({projectId:t,pages:e,components:s}){const a=O.sharedInstances[t];if(!a){f.logger.info(`projectId: ${t} not found in sharedInstances`);return}if(a.syncedStore.resources.pages=e,(await L.findByPk(t))?.useAllResources)a.syncedStore.resources.components=s;else{const c=(await Ae.findAll({where:{projectId:t}})).map(l=>l.componentId),p=Object.fromEntries(Object.entries(s||{}).filter(([l])=>c.includes(l)));a.syncedStore.resources.components=p}f.logger.info(`update [${t}] resource states:`,{pages:Object.keys(a.syncedStore.resources.pages||{}).length,components:Object.keys(a.syncedStore.resources.components||{}).length})}async function Mt(t){return He({projectId:t,pages:ne,components:oe})}async function $t(){f.logger.info("trigger reload all project resource"),w.default.events.emit(me)}async function Nt({ensureLoaded:t=!0}={}){return t&&(se??=Ve(),await se),{states:K,pages:ne,components:oe}}exports.COMPONENT_DID=Pe;exports.PUBLISH_MODES=Lt;exports.Project=L;exports.RESOURCE_TYPE=ge;exports.SITE_STATE_PATH=q;exports.STATE_MODES=Rt;exports.SiteState=O;exports.downloadAsset=$e;exports.downloadAssets=Ne;exports.fromPackage=Oe;exports.getDefaultState=Me;exports.getResourceStates=Nt;exports.initPackResourceStates=Ge;exports.mergeState=Se;exports.toPackage=qe;exports.triggerReloadAllProjectResource=$t;exports.updateResourceStatesByProjectId=Mt;
|
|
1
|
+
"use strict";const f=require("./components-DLLpFRy5.js"),F=require("@syncedstore/core"),Je=require("yjs"),We=require("@blocklet/pages-kit/utils/data-source"),Q=require("@blocklet/pages-kit/utils/route"),Qe=require("lodash/cloneDeep"),Xe=require("@blocklet/sdk/lib/config"),I=require("fs"),g=require("path"),Te=require("@blocklet/pages-kit/utils/common"),Ze=require("@blocklet/pages-kit/utils/page-model"),et=require("@blocklet/pages-kit/utils/property"),Ie=require("@blocklet/sdk/lib/component"),tt=require("@reactivedata/reactive"),X=require("glob"),st=require("lib0/decoding"),at=require("lib0/encoding"),nt=require("lodash/debounce"),ot=require("lodash/get"),rt=require("lodash/isEmpty"),it=require("lodash/set"),ct=require("lodash/union"),be=require("lru-cache"),lt=require("p-limit"),C=require("sequelize"),pt=require("stream/promises"),ut=require("tar"),z=require("ufo"),dt=require("wait-on"),G=require("y-protocols/awareness"),le=require("y-protocols/sync"),ft=require("yaml"),De=require("./html-JOhPskS4.js");require("sqlite3");require("@blocklet/pages-kit/types/state");const $=t=>t&&t.__esModule?t:{default:t};function ae(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const a=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const U=ae(Je),Le=$(Qe),w=$(Xe),pe=ae(st),k=ae(at),_e=$(nt),Ee=$(ot),we=$(rt),ve=$(it),gt=$(ct),mt=$(lt),ht=$(dt),x=ae(ft),yt=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):yt(t,e);const M=new C.Sequelize({dialect:"sqlite",storage:f.databaseUrl,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});M.query("pragma journal_mode = WAL;");M.query("pragma synchronous = normal;");M.query("pragma journal_size_limit = 33554432;");M.query("pragma cache_size = -2000;");M.query("pragma mmap_size = 33554432;");process.on("SIGINT",async()=>{await M.close(),process.exit(0)});process.on("SIGTERM",async()=>{await M.close(),process.exit(0)});async function St(t,e){try{if(t.getDialect()!=="sqlite")return;const[s]=await t.query("SELECT 1");if(!s||s.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(s){if(s.name==="SequelizeConnectionError"||s?.message&&/closed!/.test(s.message))return;console.error("Failed to cleanup SQLite memory",e,s)}}let fe=null;fe&&clearInterval(fe);fe=setInterval(async()=>{f.logger.info("Start cleanupSqliteMemory"),await St(M,f.databaseUrl),f.logger.info("End cleanupSqliteMemory")},60*1e3*10);class Ae extends C.Model{}Ae.init({id:{type:C.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:C.DataTypes.UUIDV4},projectId:{type:C.DataTypes.UUID,allowNull:!1},componentId:{type:C.DataTypes.STRING,allowNull:!1}},{sequelize:M,tableName:"ProjectComponents",timestamps:!1});class L extends C.Model{static async getProjectByIdOrSlug(e){return L.findOne({where:{[C.Op.or]:[{id:e},{slug:e}]}})}}L.init({id:{type:C.DataTypes.UUID,defaultValue:C.DataTypes.UUIDV4,primaryKey:!0},name:{type:C.DataTypes.STRING,allowNull:!1},description:C.DataTypes.TEXT,createdAt:C.DataTypes.DATE,updatedAt:C.DataTypes.DATE,createdBy:{type:C.DataTypes.STRING,allowNull:!1},updatedBy:{type:C.DataTypes.STRING,allowNull:!1},slug:C.DataTypes.STRING,icon:C.DataTypes.STRING,pinnedAt:C.DataTypes.DATE,useAllResources:C.DataTypes.BOOLEAN,npmSecret:C.DataTypes.STRING,relatedBlocklets:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("relatedBlocklets");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.logger.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){f.logger.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("productionState");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.logger.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){f.logger.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}}},{sequelize:M,paranoid:!0});L.hasMany(Ae,{foreignKey:"projectId",as:"components"});const It="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ge="page",me="trigger-reload-project-resource",Pe=It,bt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function Z(t){t.observeDeep(e=>{e.some(s=>s.changes.keys.has("updatedAt")||s.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Ue(){return I.mkdtempSync(g.join(w.default.env.dataDir,"tmp-"))}function ee(t,e,s=[]){return Array.isArray(t)?t.flatMap((a,n)=>ee(a,e,[...s,n])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([a,n])=>ee(n,e,[...s,a])):e(t)?[s]:[]}function R(t){return t.filter(e=>e!=null)}function Et(t){t.pages&&Object.keys(t.pages).forEach(s=>{const a=F.getYjsValue(t.pages[s]);a&&a instanceof U.Map&&Z(a)});const e=F.getYjsValue(t.pages);e&&e instanceof U.Map&&e.observe(s=>{s.changes.keys.forEach((a,n)=>{if(a.action==="add"){const o=F.getYjsValue(t.pages[n]);o&&o instanceof U.Map&&Z(o)}})})}function wt(t){t.routes&&Object.keys(t.routes).forEach(s=>{const a=F.getYjsValue(t.routes?.[s]);a&&a instanceof U.Map&&Z(a)});const e=F.getYjsValue(t.routes);e&&e instanceof U.Map&&e.observe(s=>{s.changes.keys.forEach((a,n)=>{if(a.action==="add"){const o=F.getYjsValue(t.routes?.[n]);o&&o instanceof U.Map&&Z(o)}})})}function At(t,e){for(const s of e||Object.keys(t.routes||{})){let a=s,n=[];if(s.includes("-")){const[o,...c]=s.split("-");a=o,n=c||[]}if(t.routes?.[a]!==void 0){t.routes[a].publishedAt=new Date().toISOString();const o=t.routes[a];if(!o||!o.params||o.params.length===0)continue;if(s.includes("-")&&n.length>0){const c=Q.getRouteMetaDataByOptionIds(n,o);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=Q.generateParamCombinations({basePath:o.path,params:o.params,routeId:o.id,paramsOptions:o.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const p of c)p.routeMetaData??={},p.routeMetaData.publishedAt=new Date().toISOString()}}}}function ue({page:t,route:e,state:s,routeId:a,routePathInfo:n}){f.logger.info(`Executing datasource data assembly, routeId: ${a}, routePathInfo: ${JSON.stringify(n)}`);const o={...Le.default(t),id:a,slug:n?.path??e.path,createdAt:e.createdAt,updatedAt:n?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:n?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(n?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of s.supportedLocales){if(e.dataSource){let p=e.id;n&&(p=n.paramOptionIds.join("-"));const l=e.dataSource.pathDataMappings?.[p]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[p]?.dataCache?.[s.config.defaultLocale||"en"];if(!l)continue;We.setPageDataSource(o,s,c.locale,l)}n&&n.routeMetaData&&(n.routeMetaData.publishedAt=new Date().toISOString())}return o}["true","1","yes","y"].includes(process.env.USE_FS_CACHE_HTML??"");const Pt=60*60*1e3,Y=new be.LRUCache({max:100,ttl:Pt,ttlResolution:10*1e3,allowStale:!0});function jt(t,e=[]){let s=0;const a=Array.from(Y.keys());for(const n of a)for(const o of t){if(De.matchCacheKey(n,{currentPath:o})){Y.delete(n),s++,f.logger.info(`[Cache CLEAR] key: ${n}`);break}for(const c of e)if(De.matchCacheKey(n,{currentPath:`/${c}${o}`})){Y.delete(n),s++,f.logger.info(`[Cache CLEAR] key: ${n}`);break}}return f.logger.info(`[Cache CLEAR] cleared ${s} entries for paths:`,t),s}function Ot(){const t=Y.size;return Y.clear(),f.logger.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}w.default.events.on(w.default.Events.envUpdate,Ot);const{uploadToMediaKit:Ct}=require("@blocklet/uploader-server"),je=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,H=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,ke=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Tt=1e4,Dt=3e4,J=0,de=1,vt=0,kt=1,he=w.default,q=g.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Rt=["production","draft"],Lt=["production"];function te(t){return t?.replace(/\//g,"|")||""}function Me(){const t=he.env.languages?.map(s=>({locale:s.code,name:s.name}))||[],e=t[0]?.locale||"en";return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class O extends U.Doc{constructor(e){super(),this.options=e,I.existsSync(this.draftYjsFilePath)&&U.applyUpdate(this,I.readFileSync(this.draftYjsFilePath)),this.syncedStore=tt.reactive(F.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new be.LRUCache({max:100,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=g.join(q,e),a=g.join(q,`@del-${e}`);I.renameSync(s,a)}catch(s){f.logger.error("Failed to safe delete project state dir:",s)}}static async getProjectIds(){return(await L.findAll({attributes:["id"],raw:!0}))?.map(e=>e.id)}static get projectIds(){return X.globSync("*/",{cwd:q,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>O.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=O.sharedInstances[e];return s||(s=new O({path:g.join(q,e)}),O.sharedInstances[e]=s,s)}static async getProductionState(e){const s=await L.findByPk(e,{attributes:["productionState"]});if(we.default(s?.productionState)){const a=g.join(q,e,"production"),n=await Oe(a,{includeResources:!0})??Me();if(!n?.config?.defaultLocale){n.config??={};const o=he.env.languages?.map(c=>({locale:c.code,name:c.name}))||[];n.config.defaultLocale=o[0]?.locale}return n}return s?.productionState}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((s,a)=>this.closeConn(a)),this.awareness.destroy();const e=g.basename(this.options.path);delete O.sharedInstances[e],super.destroy()}initObserver(){Et(this.syncedStore),wt(this.syncedStore)}get draftYjsFilePath(){return g.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,s){if(s==="draft"){const a=O.shared(e);return JSON.parse(JSON.stringify(a.syncedStore))}return O.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const s=g.basename(this.options.path);return O.getProductionState(s)}async setState(e,s){const a=await qe(s,{exportAssets:!1,includeResources:!0}),n=this.getPublishDir(e);if(I.mkdirSync(g.dirname(n),{recursive:!0}),I.rmSync(n,{force:!0,recursive:!0}),I.renameSync(a,n),e==="production"){const o=g.basename(this.options.path);O.pageUrlMapCache.delete(o),await L.update({productionState:{...s}},{where:{id:o}})}}getPublishDir(e){return g.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:s,removed:a},n)=>{const o=e.concat(s,a);if(n!==null){const l=this.conns.get(n);l&&(e.forEach(S=>{l.add(S)}),a.forEach(S=>{l.delete(S)}))}const c=k.createEncoder();k.writeVarUint(c,de),k.writeVarUint8Array(c,G.encodeAwarenessUpdate(this.awareness,o));const p=k.toUint8Array(c);this.conns.forEach((l,S)=>this.send(S,p))};updateHandler=e=>{const s=k.createEncoder();k.writeVarUint(s,J),le.writeUpdate(s,e);const a=k.toUint8Array(s);this.conns.forEach((n,o)=>this.send(o,a))};ensureDataStructure=()=>{const{supportedLocales:e,pages:s,pageIds:a,config:n,routes:o,routeIds:c}=this.syncedStore;{const p=new Set(Object.keys(s));let l=0;for(;l<a.length;){const S=a[l];p.has(S)?(p.delete(S),l++):a.splice(l,1)}}{const p=new Set(Object.keys(o));let l=0;for(;l<c.length;){const S=c[l];p.has(S)?(p.delete(S),l++):c.splice(l,1)}}e.splice(0,e.length),e.push(...he.env.languages.map(p=>({locale:p.code,name:p.name}))),n.defaultLocale=e[0]?.locale;{let p=0;const l=new Set;for(;p<e.length;){const{locale:S}=e[p];l.has(S)?e.splice(p,1):(p++,l.add(S))}}};send=(e,s)=>{e.readyState!==vt&&e.readyState!==kt&&this.closeConn(e);try{e.send(s,a=>{a&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&G.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=g.basename(this.options.path);this.releaseTimer=setTimeout(()=>{f.logger.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},O.RELEASE_DELAY),f.logger.info(`[SiteState] scheduled release for project ${e} in ${O.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=g.basename(this.options.path);f.logger.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=_e.default(()=>{I.mkdirSync(g.dirname(this.draftYjsFilePath),{recursive:!0}),I.writeFileSync(this.draftYjsFilePath,U.encodeStateAsUpdate(this))},Tt);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:s})=>{const a=await this.getState("draft"),n=await this.getState("production");await Se(a,n,{routes:s,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),n.config.publishedAt=new Date().getTime(),At(this.syncedStore,s),await this.setState(e,n),await this.clearPageCacheForRoutes(s,n)};mergeState=async(e,s)=>{const a=JSON.parse(JSON.stringify(s));e.config.fontFamily??={};const n=a.config?.fontFamily,o=e.config?.fontFamily;e.config.fontFamily.title=n?.title||o?.title,e.config.fontFamily.description=n?.description||o?.description,await new Promise((c,p)=>{this.transact(async()=>{try{const l=await Se(e,s);c(l)}catch(l){p(l)}})})};clearPageCacheForRoutes=async(e,s)=>{const a=g.basename(this.options.path),o=(await L.findByPk(a))?.slug||a;let c=e;(!c||c.length===0)&&(c=s.pageIds??[]),f.logger.info(`[SiteState] clearing page cache for project ${a}, routes:`,c||[]);const p=s.supportedLocales.map(A=>A.locale),l=[],S=c.filter(A=>s.pageIds?.includes(A));for(const A of S){const E=s.pages[A].slug;o&&o!==a&&(o==="/"?l.push(E):l.push(`/${o}${E}`)),l.push(`/${a}${E}`)}if(f.logger.info(`[SiteState] clearing page cache for project ${a}, pathPatterns:`,l),l.length>0)try{const A=jt(l,p);f.logger.info(`[SiteState] cleared ${A} page cache entries for project ${a}, routes:`,c)}catch{}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",n=>this.messageListener(e,new Uint8Array(n)));let s=!0;const a=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(a);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(a)}}},Dt);e.on("close",()=>{this.closeConn(e),clearInterval(a)}),e.on("pong",()=>{s=!0});{const n=k.createEncoder();k.writeVarUint(n,J),le.writeSyncStep1(n,this),this.send(e,k.toUint8Array(n));const o=this.awareness.getStates();if(o.size>0){const c=k.createEncoder();k.writeVarUint(c,de),k.writeVarUint8Array(c,G.encodeAwarenessUpdate(this.awareness,Array.from(o.keys()))),this.send(e,k.toUint8Array(c))}}};messageListener=(e,s)=>{try{const a=k.createEncoder(),n=pe.createDecoder(s),o=pe.readVarUint(n);switch(o){case J:k.writeVarUint(a,J),le.readSyncMessage(n,a,this,null),k.length(a)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(a)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(n),e);break}default:f.logger.warn(`Unsupported messageType ${o}`)}}catch(a){f.logger.error(a)}this.save()};static async pageUrlMap(e,s){let a=[];s?a=[s]:a=await this.getProjectIds();let n={};if(e==="production"&&a?.length){const o=new Map(a?.map(c=>[c,!0])||[]);for(const c of a){const p=O.pageUrlMapCache.get(c);p&&(n={...n,...p},o.delete(c))}a=Array.from(o.keys())}if(a?.length){const o=await L.findAll({where:{id:{[C.Op.in]:a}}});await Promise.all(o?.map(async c=>{const p=c.id,l=c.slug||p,S={},A=e==="production"&&c?.productionState?c.productionState:await O.getStateByProjectId(c.id,e),v=gt.default(w.default.env.languages?.map(u=>u.code)||[],A.supportedLocales?.map(u=>u.locale)||[]),E=(u,i)=>{l&&(S[z.joinURL("/",l,u)]={...i,shouldRedirect:!0,mainPage:!0}),S[z.joinURL("/",p,u)]={...i,shouldRedirect:!0,mainPage:!0};for(const h of v){const T={...i,locale:h};S[z.joinURL("/",h,p,u)]=T,l&&(S[z.joinURL("/",h,l,u)]=T)}};if(e==="draft")for(const u of A.routeIds||[]){const i=A?.routes?.[u];if(!i)continue;if(i.params&&i.params.length>0){const m=Q.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const d of m){const y=d.path,P={projectId:p,projectSlug:l,pageSlug:y,pageId:i.displayTemplateId||"",routeId:u,defaultLocale:v?.[0],locales:v,publishedAt:A.config.publishedAt,isPublic:i.isPublic&&d?.routeMetaData?.isPublic};E(y,P)}}const h=i.path,T={projectId:p,projectSlug:l,pageSlug:h,pageId:i.displayTemplateId||"",routeId:u,defaultLocale:v?.[0],locales:v,publishedAt:A.config.publishedAt,isPublic:i.isPublic};E(h,T)}for(const u of A.pageIds||[]){const i=A.pages[u];if(!i||e==="production"&&!i.isPublic)continue;const h=i.slug,T=c.slug||p,m={projectId:p,projectSlug:T,pageSlug:h,pageId:u,defaultLocale:v?.[0],locales:v,publishedAt:A.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};E(h,m)}e==="production"&&O.pageUrlMapCache.set(p,S),n={...n,...S}}))}return n}getDocumentSize(){return U.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,a]of Object.entries(O.sharedInstances)){const n=a.getDocumentSize();e.push({projectId:s,sizeInBytes:n,sizeInMB:`${(n/(1024*1024)).toFixed(2)} MB`,activeConnections:a.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),f.logger.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,f.logger.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(O.sharedInstances).length,s=[],a=[];for(const[n,o]of Object.entries(O.sharedInstances))o.conns.size===0?s.push({projectId:n,instance:o}):a.push({projectId:n,connections:o.conns.size});if(f.logger.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${a.length}, without connections: ${s.length}`),s.length>0){f.logger.info(`[SiteState] releasing ${s.length} instances without connections:`,s.map(o=>o.projectId));let n=0;for(const{projectId:o,instance:c}of s)try{f.logger.info(`[SiteState] releasing instance due to periodic check: ${o}`),c.destroy(),n++}catch(p){f.logger.error(`[SiteState] failed to release instance ${o} during periodic check:`,p)}f.logger.info(`[SiteState] periodic check completed: ${n}/${s.length} instances released successfully`)}else e>0?f.logger.debug("[SiteState] periodic check: all instances have active connections"):f.logger.debug("[SiteState] periodic check: no instances exist")}}async function _t(t,e,s){if(!t||!I.existsSync(t)||!I.lstatSync(t).isFile())return null;let a=s[t];return a||(a=(async()=>{try{return(await Ct({filePath:t,fileName:e}))?.data?.filename}catch(n){return f.logger.error(`Failed to upload asset ${t}:`,n),null}})(),s[t]=a),a}const $e=async(t,e)=>{const s=g.basename(t),a=await Ie.call({name:Pe,path:z.joinURL("/uploads",s),responseType:"stream",method:"GET"});if(a.status>=200&&a.status<400){const n=I.createWriteStream(e);await pt.pipeline(a.data,n)}else throw new Error(`download asset failed ${a.status}`)},Ne=async(t,e)=>{await Promise.all(t.map(async s=>{try{await $e(s,g.join(e,g.basename(s)))}catch(a){f.logger.error(`Failed to export assets: ${s}, ${a}`)}}))};function Fe(t){return je.test(t)?[t]:H.test(t)?(ke.lastIndex=0,Array.from(t.matchAll(ke)).map(s=>s[1]).filter(s=>!!s)):[]}async function W(t,e,s){const{getFilename:a,exportAssets:n}=s,o=g.join(e,a(t));if(I.mkdirSync(g.dirname(o),{recursive:!0}),I.writeFileSync(o,x.stringify(t)),n){const p=ee(t,l=>typeof l=="string"&&(je.test(l)||H.test(l))).map(l=>{const S=Ee.default(t,l);return Fe(S)}).flat().filter(Boolean);await Ne(p,g.dirname(o))}}const ye=new be.LRUCache({max:100,ttl:1*60*1e3});async function Re(t,e,s){const a=ee(t,p=>typeof p=="string"&&(je.test(p)||H.test(p))),n=mt.default(2),o=a.map(p=>n(async()=>{try{const l=Ee.default(t,p),S=Fe(l);for(const A of S){const v=g.basename(A),E=s.getFilePath(A,p),u=E?`${E}:${v}`:v,i=ye.get(u);if(i){H.test(l)||ve.default(t,p,i);return}const h=await _t(E,v,e);h&&(H.test(l)||ve.default(t,p,h),ye.set(u,h))}}catch(l){f.logger.error(`Failed to process upload for path ${p.join(".")}:`,l.message||l.reason)}})),c=await Promise.allSettled(o);s.onFinish?.(c)}async function qe(t,{exportAssets:e,pageIds:s="all",componentIds:a="all",rawConfig:n,includeResources:o=!1,routeIds:c="all"}={}){const p=s==="all"?t.pageIds:s,l=et.getComponentDependencies({state:t,pageIds:p,componentIds:a==="all"?Object.keys(t.components):a});Object.entries(t.components).forEach(([r,b])=>{b.data?.renderer?.type==="component-template"&&l.push(r)});const S=c==="all"?t.routeIds:c,A=r=>({id:r.id,name:r.name,isTemplateSection:r.isTemplateSection??!1,templateDescription:r.templateDescription,component:r.component,config:r.config,visibility:r.visibility,sections:r?.sectionIds?R(r?.sectionIds?.map(b=>{const D=r.sections?.[b];return D&&A(D)})):void 0}),v=(r,b)=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,meta:r.locales?.[b]??{},sections:R(r.sectionIds.map(D=>{const N=r.sections[D];return N&&A(N)})),dataSource:Object.fromEntries(Object.entries(r.dataSource||{}).map(([D,N])=>[D,N?.[b]??{}]))}),E=r=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,path:r.path,handler:r.handler,isPublic:r.isPublic??!0,params:r.params??[],enabledGenerate:r.enabledGenerate??!1,displayTemplateId:r.displayTemplateId,dataSource:r.dataSource}),u=R(S.map(r=>{const b=t.routes[r];return b&&E(b)})),i=R(t.supportedLocales.map(r=>r.locale).flatMap(r=>p.map(b=>{const D=t.pages[b];return D&&{locale:r,slug:D.slug,page:v(D,r)}}))),h=Ue(),T=g.join(h,"pages");I.mkdirSync(T,{recursive:!0});const m=g.join(h,"components");I.mkdirSync(m,{recursive:!0});const d=g.join(h,"routes");I.mkdirSync(d,{recursive:!0});for(const{locale:r,slug:b,page:D}of i)await W(D,T,{getFilename:()=>`${te(b)||"index"}.${r}.yml`,exportAssets:e});for(const r of u)await W(r,d,{getFilename:()=>`${te(r.path)||"index"}.yml`,exportAssets:e});for(const r of l){const b=t.components[r]?.data;b&&await W(b,m,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:e})}const y=g.join(h,".blocklet/pages/pages.config.yml");I.mkdirSync(g.dirname(y),{recursive:!0});const P={pages:R(p.map(r=>{const b=t.pages[r];return b&&{id:r,slug:b.slug}})),routes:R(S.map(r=>{const b=t.routes[r];return b&&{id:r,path:b.path}})),components:R(l.map(r=>{const b=t.components[r]?.data;return b&&{id:r,name:b.name}})),...o?{resources:{components:R(Object.keys(t.resources?.components||{}).filter(r=>l.includes(r)).map(r=>({id:r,name:t.resources?.components?.[r]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};I.writeFileSync(y,x.stringify(P));const j=g.join(h,"config.source.json");if(n&&I.writeFileSync(j,JSON.stringify(n)),o){const r=g.join(h,"resources"),b=g.join(r,"components");I.mkdirSync(b,{recursive:!0});for(const B of Object.keys(t?.resources?.components??{}).filter(_=>l.includes(_))){const _=t.resources?.components?.[B]?.component;_&&await W(_,b,{getFilename:V=>`${V.name||"unnamed"}.${V.id}.yml`,exportAssets:e})}const D=g.join(h,"chunks");I.mkdirSync(D,{recursive:!0});const N=Ut();for(const B of Object.keys(t?.resources?.components??{}).filter(_=>l.includes(_))){const _=t.resources?.components?.[B]?.component;if(_&&_.renderer?.type==="react-component"){const V=_.renderer?.chunks??[];if(V?.length>0)for(const ie of V){const Ce=g.join(D,ie),ce=N?.[ie];try{ce&&I.existsSync(ce)&&!I.existsSync(Ce)&&I.copyFileSync(ce,Ce)}catch(Ke){f.logger.error(`copy chunk ${ie} error`,Ke.message)}}}}}return h}async function Oe(t,{importAssets:e,includeResources:s}={}){if(!I.existsSync(t))return null;let a,n=!1;try{I.lstatSync(t).isDirectory()?a=t:/\.(tgz|gz|tar)$/.test(t)&&(n=!0,a=Ue(),await ut.x({file:t,C:a}));const o=X.globSync("**/.blocklet/pages/pages.config.yml",{cwd:a,absolute:!0}).at(0),c=o&&g.join(g.dirname(o),"../../pages"),p=o&&g.join(g.dirname(o),"../../components"),l=o&&g.join(g.dirname(o),"../../routes");if(!o)return null;const S=x.parse(I.readFileSync(o).toString()),A=(m,d,y)=>{let P=g.join(m,`${d}${y?`.${y}`:""}.yml`);return(!I.existsSync(P)||!I.lstatSync(P).isFile())&&(P=g.join(m,d,`index${y?`.${y}`:""}.yml`),!I.existsSync(P)||!I.lstatSync(P))?null:x.parse(I.readFileSync(P).toString())},v=(m,d)=>{try{const y=X.globSync(`*.${d}.yml`,{cwd:m,absolute:!0})[0];return y?x.parse(I.readFileSync(y).toString()):null}catch(y){f.logger.error("parse component error",y)}return null},E=(m,d)=>{let y=g.join(m,`${d}.yml`);return(!I.existsSync(y)||!I.lstatSync(y).isFile())&&(y=g.join(m,d,"index.yml"),!I.existsSync(y)||!I.lstatSync(y))?null:x.parse(I.readFileSync(y).toString())},u=R(S.pages.map(({slug:m})=>{const d=R(S.supportedLocales.map(({locale:j})=>{const r=c?A(c,te(m),j):void 0;if(r)return{locale:j,page:r};const b=c?A(c,m,j):void 0;return b&&{locale:j,page:b}})),y=d[0]?.page;if(!y)return null;const P=y.sections.map(Ze.unzipSection);return{id:y.id||Te.nextId(),createdAt:y.createdAt,updatedAt:y.updatedAt,publishedAt:y.publishedAt,isPublic:y.isPublic??!0,templateConfig:y.templateConfig,slug:m,sections:Object.fromEntries(P.map(j=>[j.id,j])),sectionIds:P.map(j=>j.id),locales:Object.fromEntries(d.map(({locale:j,page:r})=>[j,r.meta])),dataSource:y.dataSource?Object.fromEntries([...new Set(d.flatMap(({page:j})=>Object.keys(j.dataSource??{})))].map(j=>[j,Object.fromEntries(d.map(({locale:r,page:b})=>{const D=b.dataSource?.[j];return[r,D||{}]}))])):Object.fromEntries([...new Set(d.flatMap(({page:j})=>j.sections.map(r=>r.id)))].map(j=>[j,Object.fromEntries(d.map(({locale:r,page:b})=>{const D=b.dataSource?.[j];if(D)return[r,D];const N=b.sections.find(B=>B.id===j);return[r,N?.properties||{}]}))]))}})),i=R(S?.routes?.map(({path:m})=>{const d=l?E(l,te(m)):void 0;return{...d,id:d?.id||Te.nextId(),createdAt:d?.createdAt??new Date().toISOString(),updatedAt:d?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:d?.path??`/${d?.id}`,params:d?.params,handler:d?.handler??"Pages Kit",isPublic:d?.isPublic??!0,enabledGenerate:d?.enabledGenerate??!1,displayTemplateId:d?.displayTemplateId??void 0,dataSource:d?.dataSource??{}}})??[]),h=p?R(S.components?.map(({id:m})=>v(p,m))??[]):[];if(e){const m=(...d)=>{f.logger.info(`[${n?g.basename(t):g.basename(g.join(t,"../../../../"))}] importAssets:`,...d)};try{m("wait image-bin api ready"),await ht.default({resources:[`${Ie.getComponentWebEndpoint(f.IMAGE_BIN_NAME)}/api/sdk/uploads`],validateStatus:P=>P>=200&&P<=500}),m("image-bin api is ready");const d={},y={};m("start to upload assets"),await Promise.allSettled([Re(h,d,{getFilePath:P=>p&&g.join(p,P),onFinish:P=>{m(`upload ${P.length} component assets`)}}),Re(u,y,{getFilePath:(P,j)=>{const r=Ee.default(u,j.slice(0,1));return c&&g.join(c,g.dirname(r.slug),P)},onFinish:P=>{m(`upload ${P.length} page assets`)}})]),m("upload assets done"),ye.clear(),global.gc&&global.gc()}catch(d){m("Error during asset import:",d)}}const T={};if(s){const m=o&&g.join(g.dirname(o),"../../resources/components"),d=R(S.resources?.components?.map(({id:y})=>v(m,y))??[]);d.length>0&&(T.components=Object.fromEntries(d.map((y,P)=>[y.id,{index:P,component:y}])))}return{supportedLocales:S.supportedLocales,pageIds:u.map(m=>m.id),components:Object.fromEntries(h.map((m,d)=>[m.id,{index:d,data:m}])),pages:Object.fromEntries(u.map(m=>[m.id,m])),config:S.config||{},resources:T,routeIds:i.map(m=>m.id),routes:Object.fromEntries(i.map(m=>[m.id,m])),dataSourceIds:[],dataSources:{}}}finally{n&&a&&I.rmSync(a,{force:!0,recursive:!0})}}async function Se(t,e,{routes:s,mergeMode:a="byUpdateTime",deleteRoutes:n=!1,publishMode:o=void 0}={}){try{o&&f.clearPreloadComponentsCacheByMode(o)}catch(E){f.logger.error("clear preload page cache error",{error:E})}const{pages:c,pageIds:p,routeIds:l,routes:S,supportedLocales:A}=t;if(o==="production"){let E=s??[],u=null;for(const i of l??[]){const h=S?.[i];if(h?.params&&h?.params.length>0&&h?.paramsOptions&&h?.paramsOptions.length>0){const T=Q.generateParamCombinations({basePath:h.path,params:h.params,routeId:h.id,paramsOptions:h.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),m=Object.fromEntries(T.map(d=>[`${i}-${d.paramOptionIds.join("-")}`,d]));u={...u||{},...m},s||(E=[...E,...T.map(d=>`${i}-${d.paramOptionIds.join("-")}`)])}else s||E.push(i)}f.logger.info("routeIds to be published: ",E);for(const i of E){let h=i;if(h.includes("-")){const[d]=h.split("-");h=d}const T=S?.[h];if(!T){const d=e.pageIds.indexOf(h);d!==-1&&n&&(e.pageIds.splice(d,1),delete e.pages[h]);for(const y of e.pageIds)y.includes(`${h}-`)&&(e.pageIds.splice(e.pageIds.indexOf(y),1),delete e.pages[y]);f.logger.info("delete main route page",h);continue}if(i.includes("-")&&!u?.[i]){const d=e.pageIds.indexOf(i);d!==-1&&n&&(e.pageIds.splice(d,1),delete e.pages[i]),f.logger.info("delete page",i);continue}if(!T.displayTemplateId){f.logger.info("no display template",i);continue}const m=c[T.displayTemplateId];if(!m){f.logger.info("no template page",i);continue}if(e.pageIds.includes(i)){if(f.logger.info("has need update page",i),a==="replace")e.pages[i]=ue({page:m,route:T,state:t,routeId:i,routePathInfo:u?.[i]}),f.logger.info("replace page",i);else if(a==="byUpdateTime"){const d=e.pages[T.id];(!d||T.updatedAt&&T.updatedAt>d.updatedAt)&&(e.pages[i]=ue({page:m,route:T,state:t,routeId:i,routePathInfo:u?.[i]}),f.logger.info("replace page by update time",i))}}else e.pageIds.push(i),e.pages[i]=ue({page:m,route:T,state:t,routeId:i,routePathInfo:u?.[i]}),f.logger.info("add page",i)}if(n&&!s)for(const i of e.pageIds)E?.includes(i)||(delete e.pages[i],f.logger.info("delete page",i)),e.pageIds=[...e.pageIds].filter(h=>E?.includes(h))}else{for(const E of p){const u=c[E];if(u)if(e.pageIds.includes(u.id)){if(a==="replace")e.pages[u.id]=u;else if(a==="byUpdateTime"){const i=e.pages[u.id];(!i||u.updatedAt&&u.updatedAt>i.updatedAt)&&(e.pages[u.id]=u)}}else e.pageIds.push(u.id),e.pages[u.id]=u}for(const E of l){const u=S[E];if(u)if(e.routeIds.includes(u.id)){if(a==="replace")e.routes[u.id]=u;else if(a==="byUpdateTime"){const i=e.routes[u.id];(!i||u.updatedAt&&u.updatedAt>i.updatedAt)&&(e.routes[u.id]=u)}}else e.routeIds.push(u.id),e.routes[u.id]=u}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Le.default(A)),n)for(const E of Object.keys(e.components))delete e.components[E];let v=JSON.parse(JSON.stringify(t.components));v=Object.fromEntries(await Promise.all(Object.entries(v).map(async([E,u])=>{const i=await xe(u?.data);return[E,{...u,data:i}]}))),Object.assign(e.components,v),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),we.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const xe=f.memoizeWithFs(async t=>{if(!we.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:s}=t?.renderer||{};if(s||e&&e.includes("PROPERTIES_SCHEMA"))try{const a=await f.getExportSchemaValueFromCode(e??"","PROPERTIES_SCHEMA",t.id,s);a&&a.length>0&&t&&(t.properties={},a.forEach((n,o)=>{t?.properties&&(t.properties[n.id]={index:o,data:n})}))}catch(a){f.logger.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:a})}}return t},{subdir:"getPropertiesFromCode"});let se,K,ne,oe;const Be=()=>Ie.getResources({types:[{did:Pe,type:ge},{did:bt,type:ge}]}),Ut=()=>{const t=Be(),e={};return t.forEach(s=>{const a=X.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s.path,absolute:!0}).at(0),n=a&&g.join(g.dirname(a),"../../chunks");if(n&&I.existsSync(n)){const o=I.readdirSync(n);for(const c of o)e[c]=g.join(n,c)}}),e};function Ve(){return se=(async()=>{const t=Be();K=(await Promise.all(t.map(async s=>{const a=s.path?await Oe(s.path,{importAssets:!1}):void 0;return a?{blockletId:s.did,state:a,blockletTitle:s.title}:void 0}))).filter(s=>!!s),ne=K.reduce((s,a)=>Object.assign(s,Object.fromEntries(Object.values(a.state.pages).map(n=>n?[n?.id,{page:n,blockletId:a.blockletId}]:[]))),{});const e=K.reduce((s,a)=>Object.assign(s,Object.fromEntries(Object.values(a.state.components).map(n=>[n.data.id,{blockletId:a.blockletId,component:n.data}]))),{});oe=Object.fromEntries(await Promise.all(Object.entries(e).map(async([s,a])=>{const n=await xe(a.component);return[s,{...a,component:n}]})))})(),se}function Ge(t){const e=_e.default(async()=>{await Ve().catch(s=>{f.logger.error("load resource states error",{error:s})}),await t?.({states:K,pages:ne,components:oe})},3e3,{leading:!1,trailing:!0});return e(),w.default.events.on(w.default.Events.componentAdded,e),w.default.events.on(w.default.Events.componentRemoved,e),w.default.events.on(w.default.Events.componentStarted,e),w.default.events.on(w.default.Events.componentStopped,e),w.default.events.on(w.default.Events.componentUpdated,e),w.default.events.on(me,e),()=>{w.default.events.off(w.default.Events.componentAdded,e),w.default.events.off(w.default.Events.componentRemoved,e),w.default.events.off(w.default.Events.componentStarted,e),w.default.events.off(w.default.Events.componentStopped,e),w.default.events.off(w.default.Events.componentUpdated,e),w.default.events.off(me,e)}}const ze=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),Ye=Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"),re=globalThis;re[ze]?.();re[ze]=Ge(async({pages:t,components:e})=>{const s=await O.getProjectIds();f.logger.info(`start update resource states projects(${s.length})`,s),await Promise.race([new Promise(a=>{setTimeout(()=>{a({})},30*1e3)}),Promise.all(s.map(async a=>{He({projectId:a,pages:t,components:e})}))]).catch(a=>{f.logger.error("update resource states failed:",a)})});re[Ye]?.();re[Ye]=()=>{const t=()=>{O.pageUrlMapCache.clear(),f.logger.info("[Cache CLEAR ALL] clear all page url map cache by env update")};return w.default.events.on(w.default.Events.envUpdate,t),()=>{w.default.events.off(w.default.Events.envUpdate,t)}};O.startPeriodicCheck();process.on("beforeExit",()=>{O.stopPeriodicCheck()});process.on("SIGINT",()=>{O.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{O.stopPeriodicCheck(),process.exit(0)});async function He({projectId:t,pages:e,components:s}){const a=O.sharedInstances[t];if(!a){f.logger.info(`projectId: ${t} not found in sharedInstances`);return}if(a.syncedStore.resources.pages=e,(await L.findByPk(t))?.useAllResources)a.syncedStore.resources.components=s;else{const c=(await Ae.findAll({where:{projectId:t}})).map(l=>l.componentId),p=Object.fromEntries(Object.entries(s||{}).filter(([l])=>c.includes(l)));a.syncedStore.resources.components=p}f.logger.info(`update [${t}] resource states:`,{pages:Object.keys(a.syncedStore.resources.pages||{}).length,components:Object.keys(a.syncedStore.resources.components||{}).length})}async function Mt(t){return He({projectId:t,pages:ne,components:oe})}async function $t(){f.logger.info("trigger reload all project resource"),w.default.events.emit(me)}async function Nt({ensureLoaded:t=!0}={}){return t&&(se??=Ve(),await se),{states:K,pages:ne,components:oe}}exports.COMPONENT_DID=Pe;exports.PUBLISH_MODES=Lt;exports.Project=L;exports.RESOURCE_TYPE=ge;exports.SITE_STATE_PATH=q;exports.STATE_MODES=Rt;exports.SiteState=O;exports.downloadAsset=$e;exports.downloadAssets=Ne;exports.fromPackage=Oe;exports.getDefaultState=Me;exports.getResourceStates=Nt;exports.initPackResourceStates=Ge;exports.mergeState=Se;exports.toPackage=qe;exports.triggerReloadAllProjectResource=$t;exports.updateResourceStatesByProjectId=Mt;
|