@blocklet/pages-kit-inner-components 0.4.144 → 0.4.146
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 +1 -1
- package/lib/cjs/chunks/{array-D-LDfLBW.js → array-6wh7d5gC.js} +1 -1
- package/lib/cjs/chunks/{config-string-BMi-8GXv.js → config-string-DnwpUGUo.js} +1 -1
- package/lib/cjs/chunks/{draft-data-C-aBMmuZ.js → draft-data-DPZIakr4.js} +1 -1
- package/lib/cjs/chunks/{home-BJQNqMrM.js → home-B5XHNRCN.js} +3 -3
- package/lib/cjs/chunks/{publish-button-3_BAbHTk.js → publish-button-Cr534T09.js} +1 -1
- package/lib/cjs/chunks/site-state-Cio9RMaq.js +57 -0
- package/lib/cjs/chunks/state-D4MG-uJB.js +1 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/add-component.js +3 -3
- package/lib/es/chunks/{array-BfSgATE1.js → array-DudMqbtU.js} +4 -4
- package/lib/es/chunks/{config-string-BObBTkZS.js → config-string-CNgatAMw.js} +1 -1
- package/lib/es/chunks/{draft-data-PScFOAJJ.js → draft-data-DB1pDB18.js} +1 -1
- package/lib/es/chunks/{home-DCFkaVAX.js → home-Bqe3w7ou.js} +4 -4
- package/lib/es/chunks/{publish-button-DOPF0sFB.js → publish-button-BauXdoix.js} +3 -3
- package/lib/es/chunks/{site-state-BvVjkzSF.js → site-state-BjimJvYN.js} +591 -576
- package/lib/es/chunks/state-BcZbsEn6.js +474 -0
- package/lib/es/components.js +1 -1
- package/lib/es/home.js +3 -3
- package/lib/es/project-html.js +1 -1
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +2 -2
- package/lib/es/site-state.js +14 -15
- package/package.json +3 -3
- package/lib/cjs/chunks/site-state-W1QFSZu4.js +0 -57
- package/lib/cjs/chunks/state-DPSTH2vo.js +0 -1
- package/lib/es/chunks/state-DGyH1TW3.js +0 -456
package/lib/cjs/add-component.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var TI=Object.create;var gI=Object.defineProperty;var WI=Object.getOwnPropertyDescriptor;var xI=Object.getOwnPropertyNames;var YI=Object.getPrototypeOf,rI=Object.prototype.hasOwnProperty;var hI=(C,s,w,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let o of xI(s))!rI.call(C,o)&&o!==w&&gI(C,o,{get:()=>s[o],enumerable:!(i=WI(s,o))||i.enumerable});return C};var ZI=(C,s,w)=>(w=C!=null?TI(YI(C)):{},hI(s||!C||!C.__esModule?gI(w,"default",{value:C,enumerable:!0}):w,C));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const I=require("react/jsx-runtime"),H=require("./chunks/state-
|
|
1
|
+
"use strict";var TI=Object.create;var gI=Object.defineProperty;var WI=Object.getOwnPropertyDescriptor;var xI=Object.getOwnPropertyNames;var YI=Object.getPrototypeOf,rI=Object.prototype.hasOwnProperty;var hI=(C,s,w,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let o of xI(s))!rI.call(C,o)&&o!==w&&gI(C,o,{get:()=>s[o],enumerable:!(i=WI(s,o))||i.enumerable});return C};var ZI=(C,s,w)=>(w=C!=null?TI(YI(C)):{},hI(s||!C||!C.__esModule?gI(w,"default",{value:C,enumerable:!0}):w,C));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const I=require("react/jsx-runtime"),H=require("./chunks/state-D4MG-uJB.js"),QI=require("@arcblock/ux/lib/Empty"),T=require("@arcblock/ux/lib/Locale/context"),p=require("@iconify-icon/react"),kI=require("@mui/icons-material/Check"),A=require("@mui/material"),u=require("ahooks"),m=require("react"),h=require("./chunks/array-6wh7d5gC.js"),U=require("@arcblock/ux/lib/Theme");require("@blocklet/pages-kit/builtin/color-picker");require("@blocklet/pages-kit/utils/style");const RI=require("@emotion/css");require("lodash/without");const X=require("@mui/material/colors"),G=require("./chunks/config-string-DnwpUGUo.js"),pI=require("lodash/cloneDeep"),r=require("@mui/icons-material"),AI=require("react-dnd");require("@arcblock/ux/lib/Tabs");require("lodash/pick");const UI=require("@mui/lab"),a=require("immer"),fI=require("./theme.js"),_=require("react-use"),mI=require("@arcblock/ux/lib/Toast"),GI=require("@mui/material/Tooltip"),VI=require("@mui/icons-material/KeyboardArrowLeft"),vI=require("@mui/material/Box"),_I=require("@mui/material/DialogTitle"),PI=require("@mui/material/IconButton"),qI=require("@mui/material/Dialog"),$I=require("@mui/material/useMediaQuery"),SI=require("@emotion/react"),IC=require("@mui/material/Alert"),CC=require("@mui/material/AlertTitle"),gC=require("react-error-boundary"),AC=require("ufo"),iC=require("@emotion/styled"),sC=require("@mui/material/Typography"),oC=require("joi"),P=require("@blocklet/ai-kit/api"),wC=require("@blocklet/js-sdk"),BI=require("@mui/x-date-pickers"),MC=require("@mui/x-date-pickers/AdapterDayjs"),LC=require("@mui/x-date-pickers/LocalizationProvider"),iI=require("circular-natal-horoscope-js/dist"),jC=require("dayjs"),JC=require("dayjs/plugin/timezone"),OC=require("dayjs/plugin/utc"),mC=require("fast-deep-equal"),SC=require("lodash/isNil"),BC=require("tz-lookup"),yC=require("@mui/icons-material/CheckCircleOutline"),DC=require("lodash/uniq"),eC=require("lodash/get"),bC=require("lodash/set"),NC=require("@blocklet/pages-kit/components"),F=C=>C&&C.__esModule?C:{default:C},yI=F(QI),KC=F(kI),DI=F(m),dC=F(pI),eI=F(mI),cC=F(GI),q=F(VI),Y=F(vI),$=F(_I),II=F(PI),zC=F(qI),FC=F($I),aC=F(IC),lC=F(CC),Q=F(iC),sI=F(sC),E=F(oC),Z=F(jC),tC=F(JC),HC=F(OC),EC=F(mC),uC=F(SC),bI=F(BC),nC=F(yC),oI=F(DC),XC=F(eC),TC=F(bC);X.red[300],X.pink[300],X.purple[300],X.indigo[300],X.blue[300],X.cyan[300],X.teal[300],X.green[300],X.lime[300],X.yellow[300],X.amber[300],X.orange[300],X.brown[300],X.grey[300],X.blueGrey[300];U.styled(A.Box)`
|
|
2
2
|
.color-item {
|
|
3
3
|
position: relative;
|
|
4
4
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var kt=Object.create;var ot=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var Bt=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of St(e))!Ct.call(t,n)&&n!==r&&ot(t,n,{get:()=>e[n],enumerable:!(i=$t(e,n))||i.enumerable});return t};var Pt=(t,e,r)=>(r=t!=null?kt(Nt(t)):{},Bt(e||!t||!t.__esModule?ot(r,"default",{value:t,enumerable:!0}):r,t));const o=require("react/jsx-runtime");require("@mui/icons-material");const x=require("@mui/material"),f=require("react"),It=require("lodash/keyBy"),j=require("./state-
|
|
1
|
+
"use strict";var kt=Object.create;var ot=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var Bt=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of St(e))!Ct.call(t,n)&&n!==r&&ot(t,n,{get:()=>e[n],enumerable:!(i=$t(e,n))||i.enumerable});return t};var Pt=(t,e,r)=>(r=t!=null?kt(Nt(t)):{},Bt(e||!t||!t.__esModule?ot(r,"default",{value:t,enumerable:!0}):r,t));const o=require("react/jsx-runtime");require("@mui/icons-material");const x=require("@mui/material"),f=require("react"),It=require("lodash/keyBy"),j=require("./state-D4MG-uJB.js"),F=require("@blocklet/ai-runtime/components"),Rt=require("@mui/utils"),Wt=require("lodash/pick"),Tt=require("react-error-boundary"),zt=require("@blocklet/pages-kit/builtin/markdown/markdown-renderer"),mt=require("@blocklet/pages-kit/contexts/color"),g=require("@emotion/css"),Et=require("react-syntax-highlighter/dist/esm/styles/prism"),k=require("@arcblock/ux/lib/Theme"),qt=require("@arcblock/react-hooks/lib/useBrowser"),Lt=require("@arcblock/ux/lib/Colors"),J=require("@blocklet/pages-kit/components"),nt=require("@blocklet/pages-kit/utils/style"),At=require("@mui/material/useMediaQuery"),Ot=require("lodash/omit"),pt=require("@iconify-icon/react"),Ut=require("@arcblock/ux/lib/Screenshot"),G=require("react-router-dom"),Ft=require("@arcblock/ux/lib/Button"),Dt=require("is-uri"),D=require("pathe"),W=require("ufo"),Mt=require("@blocklet/embed/message"),Vt=require("ahooks"),Ht=require("lodash/isEqual"),Yt=require("@blocklet/embed/react"),Jt=require("react-twitter-embed"),rt=require("react-use"),$=t=>t&&t.__esModule?t:{default:t},Gt=$(f),V=$(It),K=$(Wt),Kt=$(zt),Xt=$(qt),it=$(Lt),xt=$(At),N=$(Ot),Qt=$(Ut),Zt=$(Ft),H=$(Dt),te=$(Ht),ht="{{CUSTOM_VALUE}}",ee=[{title:"None",value:"none",sx:{py:0}},{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}}}],oe=[{title:"None",value:"none",sx:{py:0}},{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}}}],ne=[{title:"None",value:"none",sx:{px:0}},{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}}}],M=(t,e,r)=>{const i=t.breakpoints.values[r];return`${e}${i?` (${i}px)`:""}`},re=[{title:"100%",value:"full",sx:{maxWidth:"100%"}},{title:t=>M(t,"Small","sm"),value:"sm",sx:{maxWidth:t=>t.breakpoints.values.sm,width:"100%",mx:"auto"}},{title:t=>M(t,"Normal","md"),value:"md",sx:{maxWidth:t=>t.breakpoints.values.md,width:"100%",mx:"auto"}},{title:t=>M(t,"Large","lg"),value:"lg",sx:{maxWidth:t=>t.breakpoints.values.lg,width:"100%",mx:"auto"}},{title:t=>M(t,"Extra Large","xl"),value:"xl",sx:{maxWidth:t=>t.breakpoints.values.xl,width:"100%",mx:"auto"}},{title:"Custom",value:"custom",sx:{maxWidth:ht,width:"100%",mx:"auto"}}],ie=V.default(ee,"value"),se=V.default(oe,"value"),ae=V.default(ne,"value"),le=V.default(re,"value"),ce=new Map([["baseSectionPaddingY",ie],["maxWidth",le],["paddingY",se],["paddingX",ae]]);function ft(t){var l;const{type:e,value:r,format:i="sx",defaultValue:n=null}=t,s=ce.get(e);if(!s)return n;const d=r.startsWith("custom:"),a=d?"custom":r;if(s!=null&&s[a]&&((l=s==null?void 0:s[a])!=null&&l[i])){const c=s[a][i];if(d){const u=r.replace("custom:","");try{return JSON.parse(JSON.stringify(c||{}).replaceAll(ht,u))}catch{}}return c}return n}const gt=f.createContext({page:null,getPageMeta:()=>({}),getPageMetaStyle:()=>({})});function de(){return f.useContext(gt)}function ue({page:t,children:e,defaultLocale:r="en",currentLocale:i}){const n=f.useMemo(()=>t?JSON.parse(JSON.stringify(t)):null,[JSON.stringify(t)]),s=f.useCallback(()=>{var c;if(!n)return{};const l=i||r;return((c=n.locales)==null?void 0:c[l])??{}},[n,r,i]),d=f.useCallback((l="sx")=>{const c=s();return!c||!c.style?{}:Object.entries(c.style||{}).reduce((m,[h,p])=>{if(!p)return m;const y=`${h}Custom`;c.style[y];const w=ft({type:h,value:p,format:l});return w?{...m,...w}:m},{})},[s]),a=f.useMemo(()=>({page:n,getPageMeta:s,getPageMetaStyle:d}),[n,s,d]);return o.jsx(gt.Provider,{value:a,children:e})}function R({actions:t,center:e,className:r,align:i}){return t&&(t!=null&&t.length)?o.jsx(x.Box,{className:g.cx("flex gap-4 flex-wrap","lg:flex-row lg:gap-8",(e||i==="center")&&"justify-center",!e&&i==="right"&&"justify-end",!e&&i==="left"&&"justify-start",r),sx:{alignItems:"center"},children:t}):null}const me="section",pe=x.styled(x.Box)`
|
|
2
2
|
overflow: hidden;
|
|
3
3
|
|
|
4
4
|
.section__title {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const i=require("react/jsx-runtime"),s=require("@blocklet/pages-kit/builtin/uploader"),h=require("@iconify-icon/react"),n=require("@mui/material"),l=require("react"),q=require("react-use"),I=require("./state-
|
|
1
|
+
"use strict";const i=require("react/jsx-runtime"),s=require("@blocklet/pages-kit/builtin/uploader"),h=require("@iconify-icon/react"),n=require("@mui/material"),l=require("react"),q=require("react-use"),I=require("./state-D4MG-uJB.js"),v=l.forwardRef(function({showMarkdown:S,markdown:j,onMarkdownChange:o,showUploader:p,value:c,meta:A,onChange:a,...u},z){const[t,m]=l.useState("");l.useEffect(()=>{m(c||"")},[c,m]);const f=async()=>{if(t!==c){const e=I.getImageAbsoluteUrl(t);if(!e){a(t,void 0);return}const r=await s.getImageSize(e).catch(()=>s.getVideoSize(e)).catch(()=>{});a(t,{...r,filename:t})}};q.useDebounce(()=>{t!==c&&a(t)},300,[t]),l.useImperativeHandle(z,()=>({submit:f}));const g={};return p&&(g.InputProps={sx:{pr:0},endAdornment:i.jsx(n.InputAdornment,{position:"end",sx:{mx:.5},children:i.jsx(s.UploaderButton,{onChange:async({response:e})=>{var b;const r=(b=e==null?void 0:e.data)==null?void 0:b.filename,d=I.getImageAbsoluteUrl(r)||"";let x={};d&&(x=await s.getImageSize(d).catch(()=>s.getVideoSize(d)).catch(()=>{})),a(r,{...x,filename:r})}})})}),i.jsx(n.TextField,{size:"small",fullWidth:!0,...u,label:i.jsxs(n.Stack,{direction:"row",spacing:1,alignItems:"center",children:[u.label,S&&i.jsxs(i.Fragment,{children:[" (",i.jsx(n.FormControlLabel,{checked:j,label:i.jsx(n.Box,{component:h.Icon,icon:"tabler:markdown",sx:{verticalAlign:"middle"}}),labelPlacement:"start",control:i.jsx(n.Switch,{size:"small"}),sx:{ml:.25,pr:1},onChange:(e,r)=>o==null?void 0:o(r)}),")"]})]}),InputLabelProps:{shrink:!0,...u.InputLabelProps},value:t,onChange:e=>m(e.target.value),...g,onKeyDown:e=>{e.keyCode!==229&&e.key==="Enter"&&f()}})});exports.ConfigString=v;
|
|
@@ -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-D4MG-uJB.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"),E=require("./state-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),E=require("./state-D4MG-uJB.js"),X=require("@arcblock/ux/lib/Locale/context"),ce=require("@arcblock/ux/lib/Result"),le=require("@blocklet/pages-kit/builtin/page/header"),ue=require("@blocklet/pages-kit/contexts/color"),Y=require("@blocklet/pages-kit/utils/data-source"),de=require("@blocklet/pages-kit/utils/route"),pe=require("@blocklet/ui-react/lib/Header"),J=require("@emotion/css"),N=require("@emotion/react"),ge=require("@emotion/styled"),P=require("@mui/material"),z=require("ahooks"),me=require("isomorphic-dompurify"),fe=require("lodash/cloneDeep"),he=require("lodash/isEmpty"),xe=require("lodash/isEqual"),g=require("react"),je=require("react-helmet"),w=require("react-router-dom"),Z=require("react-use"),M=require("ufo"),I=require("./array-6wh7d5gC.js"),G=require("@arcblock/ux/lib/Theme"),ye=require("@blocklet/ui-react/lib/Footer");require("webfontloader");const be=require("@arcblock/did-connect/lib/Session"),k=t=>t&&t.__esModule?t:{default:t},ee=k(ce),ve=k(pe),te=k(ge),we=k(me),V=k(fe),Pe=k(he),ne=k(xe),Se=k(ye),Re=G.styled(Se.default,{shouldForwardProp:t=>!!t})`
|
|
2
2
|
& > div > .MuiContainer-root {
|
|
3
3
|
max-width: unset;
|
|
4
4
|
}
|
|
@@ -26,11 +26,11 @@
|
|
|
26
26
|
font-family: ${s};
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
`})}const{SessionProvider:Ue,SessionContext:Ee,SessionConsumer:Ae,withSession:Ne}=be.createAuthServiceSessionContext();function W(){return g.useContext(Ee)}function Ie(...t){var r;const{session:n}=W();return t.includes((r=n.user)==null?void 0:r.role)}function Be(...t){var a;const{session:n}=W(),r=Ie(...t);return((a=window.blocklet)==null?void 0:a.tenantMode)==="multiple"?!!n.user:r}function Le(){const[t]=w.useSearchParams(),{session:n}=W(),r=Be("owner","admin","pagesEditor","member"),a=g.useMemo(()=>{const o=t.get("mode");return I.STATE_MODES.includes(o)?o:"production"},[t]),s=a==="production"?a:n.user?r?a:"production":null;return s?e.jsx(se,{mode:s}):null}function se({mode:t}){if(t!=="draft"){const n=window.__PAGE_STATE__;return n?e.jsx(A,{mode:t,state:n}):e.jsx(De,{mode:t,children:({state:r})=>e.jsx(A,{mode:t,state:r})})}return e.jsx(Te,{children:({state:n})=>e.jsx(A,{mode:t,state:n})})}const Te=g.lazy(()=>Promise.resolve().then(()=>require("./draft-data-
|
|
29
|
+
`})}const{SessionProvider:Ue,SessionContext:Ee,SessionConsumer:Ae,withSession:Ne}=be.createAuthServiceSessionContext();function W(){return g.useContext(Ee)}function Ie(...t){var r;const{session:n}=W();return t.includes((r=n.user)==null?void 0:r.role)}function Be(...t){var a;const{session:n}=W(),r=Ie(...t);return((a=window.blocklet)==null?void 0:a.tenantMode)==="multiple"?!!n.user:r}function Le(){const[t]=w.useSearchParams(),{session:n}=W(),r=Be("owner","admin","pagesEditor","member"),a=g.useMemo(()=>{const o=t.get("mode");return I.STATE_MODES.includes(o)?o:"production"},[t]),s=a==="production"?a:n.user?r?a:"production":null;return s?e.jsx(se,{mode:s}):null}function se({mode:t}){if(t!=="draft"){const n=window.__PAGE_STATE__;return n?e.jsx(A,{mode:t,state:n}):e.jsx(De,{mode:t,children:({state:r})=>e.jsx(A,{mode:t,state:r})})}return e.jsx(Te,{children:({state:n})=>e.jsx(A,{mode:t,state:n})})}const Te=g.lazy(()=>Promise.resolve().then(()=>require("./draft-data-DPZIakr4.js")));function De({mode:t,children:n}){const r=document.querySelector('meta[property="pages:version"]'),a=r==null?void 0:r.content,s=E.useProjectId(),o=g.useMemo(()=>{if(a==="{{pagesPublishedAt}}"){const l=localStorage.getItem(E.getProjectPageVersionKey(s??""));return Number(l)?Number(l):new Date().getTime()}return Number(a)},[a]),{loading:m,value:c}=Z.useAsync(()=>I.getPages({mode:t,version:o}),[t,o]);return m?e.jsx(oe,{}):c?n({state:c}):null}function A({mode:t,state:n}){const{t:r,locale:a}=X.useLocaleContext(),[s]=w.useSearchParams(),o=s.get("hiddenBadge")==="true",m=s.get("showPublish")==="true",{pageIds:c,pages:l,routeIds:f,routes:p,supportedLocales:u,config:{defaultLocale:j},resources:b}=n,v=E.getAllComponents(n),y=g.useMemo(()=>u!=null&&u.some(d=>d.locale===a)?a:void 0,[a,u]),h=Object.values(l).find(d=>(d==null?void 0:d.slug)==="/")?void 0:Object.values(l)[0],H=g.useMemo(()=>c.map(d=>{const i=l[d];return i&&{id:i.id,path:M.joinURL("/",y||"",i.slug,t!=="production"?`?mode=${t}`:"")}}).filter(I.nonNullable),[c,l,y,t]),C=([...d])=>(t!=="production"&&m&&d.unshift(e.jsx(g.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(Oe,{mode:"production",state:n})})),d);return e.jsxs(I.Provider,{value:{pages:H},children:[e.jsxs(w.Routes,{children:[h&&e.jsx(w.Route,{index:!0,element:e.jsx(w.Navigate,{to:M.joinURL("/",y||"",h.slug)})}),f==null?void 0:f.map(d=>{var B,L,T,S;const i=p==null?void 0:p[d];if(!i||!i.displayTemplateId)return null;const q=l[i.displayTemplateId];if(!q)return null;let _=[];if(i.params&&i.params.length>0){const x=de.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});_=x==null?void 0:x.map(R=>{var D,F,K,Q;const U=R.paramOptionIds.join("-");return e.jsx(w.Route,{path:M.joinURL(":projectIdOrSlug?",R.path),element:e.jsx($,{mode:t,components:v,page:q,locale:y,defaultLocale:j,headerAddons:C,state:n,pageData:(Q=(K=(F=(D=i.dataSource)==null?void 0:D.pathDataMappings)==null?void 0:F[U])==null?void 0:K.dataCache)==null?void 0:Q[y||j||"en"]})},U)})}return _.push(e.jsx(w.Route,{path:M.joinURL(":projectIdOrSlug?",i.path),element:e.jsx($,{mode:t,components:v,page:q,locale:y,defaultLocale:j,headerAddons:C,state:n,pageData:(S=(T=(L=(B=i.dataSource)==null?void 0:B.pathDataMappings)==null?void 0:L[i.id])==null?void 0:T.dataCache)==null?void 0:S[y||j||"en"]})},i.id)),_}),c.map(d=>{const i=l[d];return i?e.jsx(w.Route,{path:M.joinURL(":projectIdOrSlug?",i.slug),element:e.jsx(O,{mode:t,components:v,page:i,locale:y,defaultLocale:j,headerAddons:C})},i.id):null}),b.pages&&Object.values(b.pages).map(({blockletId:d,page:i})=>e.jsx(w.Route,{path:M.joinURL("/",`@${d}`,i.slug),element:e.jsx(O,{mode:t,components:v,page:i,locale:y,defaultLocale:j,headerAddons:C})},i.id)),e.jsx(w.Route,{path:"*",element:e.jsx(P.Box,{width:"100vw",height:"100vh",display:"flex",justifyContent:"center",alignItems:"center",children:e.jsx(ee.default,{status:404,extra:e.jsx(ie,{href:"/",children:r("common.back")})})})})]}),t!=="production"&&!o&&e.jsx(Ce,{sx:{bgcolor:"info.light"},children:t}),e.jsx(Me,{})]})}function $({mode:t,pageData:n,components:r,page:a,locale:s,defaultLocale:o,headerAddons:m,state:c}){const l=z.useReactive({page:null});g.useEffect(()=>{const p=a||null;p?l.page=V.default(p):l.page=null},[a,l]);const f=g.useRef();return g.useEffect(()=>{ne.default(n,f.current)||n&&l.page&&(Y.setPageDataSource(l.page,c,s,n),f.current=V.default(n))},[l.page,n,s,c]),l.page?e.jsx(O,{mode:t,components:r,page:l.page,locale:s,defaultLocale:o,headerAddons:m}):null}function Fe({mode:t,state:n,path:r,pageData:a}){const{t:s,locale:o}=X.useLocaleContext(),{pages:m,supportedLocales:c,config:{defaultLocale:l},resources:f}=n,p=Object.values(m).find(h=>(h==null?void 0:h.slug)===r),u=Object.values(f.pages||{}).find(h=>h.page.slug===r),j=g.useMemo(()=>c!=null&&c.some(h=>h.locale===o)?o:void 0,[o,c]),b=z.useReactive({page:null});g.useEffect(()=>{const h=p||(u==null?void 0:u.page)||null;h?b.page=V.default(h):b.page=null},[p,u]);const v=g.useRef();if(g.useEffect(()=>{ne.default(a,v.current)||a&&b.page&&(Y.setPageDataSource(b.page,n,j,a),v.current=V.default(a))},[{}]),!p&&!(u!=null&&u.page))return e.jsx(P.Box,{width:"100vw",height:"100vh",display:"flex",justifyContent:"center",alignItems:"center",children:e.jsx(ee.default,{style:{background:"inherit"},status:404,extra:e.jsx(ie,{href:"/",children:s("common.back")})})});const y=E.getAllComponents(n);return b.page?e.jsx(O,{mode:t,components:y,page:b.page,locale:j,defaultLocale:l}):null}function O({mode:t,components:n,page:r,locale:a,defaultLocale:s,headerAddons:o}){var H,C,d,i,q,_,B,L,T;const m=ue.useColorConvert(),c=((H=r.locales)==null?void 0:H[a])??((C=r.locales)==null?void 0:C[s])??{},l=c.title||((d=window.blocklet)==null?void 0:d.appName),f=c.description||((i=window.blocklet)==null?void 0:i.appDescription),p=E.autoResizeImage(E.getImageAbsoluteUrl(c.image),540),{logo:u,brand:j,description:b,...v}=le.useHeaderState(),y=g.useMemo(()=>S=>{var R;let x=(o==null?void 0:o(S))??S;return x=((R=v.addons)==null?void 0:R.call(v,x))??x,x},[v.addons,o]),h=(q=c.header)!=null&&q.translucent?ae:re;return e.jsxs(I.PageProvider,{page:r,defaultLocale:s,currentLocale:a,children:[e.jsx(N.Global,{styles:N.css`
|
|
30
30
|
body {
|
|
31
31
|
background-color: ${m(!c.backgroundColor||c.backgroundColor==="transparent"?"background.default":c.backgroundColor)} !important;
|
|
32
32
|
}
|
|
33
|
-
`}),e.jsx(h,{hideNavMenu:!!((_=c.header)!=null&&_.hideNavMenus),translucentTextColor:(B=c.header)==null?void 0:B.translucentTextColor,...u?{logo:u}:{},...j?{brand:j}:{},...b?{description:b}:{},className:J.cx(((L=c.header)==null?void 0:L.sticky)&&"sticky","page-header"),maxWidth:!1,addons:y}),e.jsx(w.ScrollRestoration,{}),e.jsxs(je.Helmet,{children:[e.jsx("title",{children:l}),e.jsx("meta",{name:"og:title",content:l}),e.jsx("meta",{name:"og:description",content:f}),e.jsx("meta",{name:"og:image",content:p}),e.jsx("meta",{name:"twitter:image:src",content:p}),e.jsx("meta",{name:"twitter:image",content:p}),e.jsx("meta",{property:"twitter:description",content:f}),e.jsx("meta",{property:"twitter:title",content:l}),e.jsx("meta",{name:"description",content:f})]}),e.jsx(P.Stack,{flexGrow:1,className:"PageView-root",sx:{"& .BlockBase-root:first-child":{pt:"0 !important"}},children:r.sectionIds.map(S=>{var D,F;const x=r.sections[S];if(!x||x.visibility==="hidden")return null;const R=(D=x.locales)==null?void 0:D[a],U=((F=x.locales)==null?void 0:F[s])??{};return e.jsx(I.BlockRenderer,{id:S,type:x.component,mode:t,section:x,config:{...Pe.default(R)?U:R,locale:a,dev:t==="draft"?{mode:t,components:n,defaultLocale:s}:{mode:t}}},S)})}),!((T=c.footer)!=null&&T.hidden)&&e.jsx(ke,{})]})}const Oe=g.lazy(()=>Promise.resolve().then(()=>require("./publish-button-
|
|
33
|
+
`}),e.jsx(h,{hideNavMenu:!!((_=c.header)!=null&&_.hideNavMenus),translucentTextColor:(B=c.header)==null?void 0:B.translucentTextColor,...u?{logo:u}:{},...j?{brand:j}:{},...b?{description:b}:{},className:J.cx(((L=c.header)==null?void 0:L.sticky)&&"sticky","page-header"),maxWidth:!1,addons:y}),e.jsx(w.ScrollRestoration,{}),e.jsxs(je.Helmet,{children:[e.jsx("title",{children:l}),e.jsx("meta",{name:"og:title",content:l}),e.jsx("meta",{name:"og:description",content:f}),e.jsx("meta",{name:"og:image",content:p}),e.jsx("meta",{name:"twitter:image:src",content:p}),e.jsx("meta",{name:"twitter:image",content:p}),e.jsx("meta",{property:"twitter:description",content:f}),e.jsx("meta",{property:"twitter:title",content:l}),e.jsx("meta",{name:"description",content:f})]}),e.jsx(P.Stack,{flexGrow:1,className:"PageView-root",sx:{"& .BlockBase-root:first-child":{pt:"0 !important"}},children:r.sectionIds.map(S=>{var D,F;const x=r.sections[S];if(!x||x.visibility==="hidden")return null;const R=(D=x.locales)==null?void 0:D[a],U=((F=x.locales)==null?void 0:F[s])??{};return e.jsx(I.BlockRenderer,{id:S,type:x.component,mode:t,section:x,config:{...Pe.default(R)?U:R,locale:a,dev:t==="draft"?{mode:t,components:n,defaultLocale:s}:{mode:t}}},S)})}),!((T=c.footer)!=null&&T.hidden)&&e.jsx(ke,{})]})}const Oe=g.lazy(()=>Promise.resolve().then(()=>require("./publish-button-Cr534T09.js"))),re=te.default(ve.default)`
|
|
34
34
|
&.sticky {
|
|
35
35
|
position: sticky;
|
|
36
36
|
top: 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),F=require("./state-DPSTH2vo.js"),$=require("@arcblock/ux/lib/Locale/context"),ee=require("@arcblock/ux/lib/Toast"),te=require("@blocklet/pages-kit/utils/route"),P=require("@mui/icons-material"),J=require("@mui/lab"),s=require("@mui/material"),se=require("immer"),ne=require("lodash/difference"),l=require("react"),ie=require("react-use"),re=require("./home-BJQNqMrM.js"),U=require("./array-D-LDfLBW.js"),G=r=>r&&r.__esModule?r:{default:r},W=G(ee),H=G(ne);function oe(r){const[j,k]=l.useState(!1);return e.jsx(J.LoadingButton,{...r,loading:r.loading||j,onClick:u=>{var b;const p=(b=r.onClick)==null?void 0:b.call(r,u);p instanceof Promise&&(k(!0),p.finally(()=>{k(!1)}))}})}const ae=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 le(){const[r,j]=l.useState(),k=l.useMemo(()=>r?e.jsx(s.Dialog,{...r}):null,[r]),u=l.useCallback(()=>{j(void 0)},[]),p=l.useCallback(({title:b,content:d,cancelText:S="Cancel",okText:f="Ok",onOk:g,onClose:c,okIcon:O,okColor:w="primary",cancelColor:y="primary",DialogContentProps:A,form:M,...z})=>{j({...z,open:!0,children:e.jsxs("form",{onSubmit:R=>R.preventDefault(),children:[b&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:"1px solid #E5E7EB"},children:[e.jsx(s.Box,{children:b}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{u(),c==null||c()},children:e.jsx(ae,{})})]}),d&&e.jsx(s.DialogContent,{...A,sx:{mt:-3,...A==null?void 0:A.sx},children:e.jsx(s.Box,{pt:3,children:d})}),e.jsxs(s.DialogActions,{children:[e.jsx(s.Button,{variant:"outlined",color:y||"primary",onClick:c??u,children:S}),e.jsx(oe,{variant:"contained",color:w||"primary",startIcon:O,loadingPosition:O?"start":"center",onClick:async()=>{await(g==null?void 0:g()),u()},type:"submit",children:f})]})]}),onClose:c??u})},[u]);return{dialog:k,showDialog:p,closeDialog:u}}const ce=l.forwardRef(({mode:r,state:j},k)=>{const{t:u}=$.useLocaleContext(),[p,b]=l.useState(!1),{dialog:d,showDialog:S}=le(),f=F.useProjectId(),g=l.useCallback(O=>{let w=[];S({title:u("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(P.Warning,{}),children:u("maker.publishToProductionTip")}),e.jsx(s.Box,{maxHeight:"50vh",overflow:"auto",mt:2,children:e.jsx(de,{state:j,toMode:r,onChange:y=>w=y,defaultRouteIds:O})})]}),okText:u("maker.publish"),cancelText:u("common.cancel"),onOk:async()=>{if((w==null?void 0:w.length)===0){const y=u("maker.publishSelectPagesMessage");throw W.default.error(y),new Error(y)}localStorage.setItem(F.getProjectPageVersionKey(f??""),String(new Date().getTime())),b(!0);try{await U.publishPages({mode:r,routes:w}),W.default.success(u("maker.publishSuccessMessage"))}catch(y){throw W.default.error(y.message),y}finally{b(!1)}}})},[r,j,u,f,S]);l.useImperativeHandle(k,()=>({openPublishDialog:g}));const c=l.useCallback(()=>{g()},[g]);return e.jsxs(e.Fragment,{children:[e.jsx(J.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:c,loading:p,disabled:p,children:u("maker.publishToProduction")}),d]})});function ue({routePathInfo:r,checked:j,onClick:k,route:u}){var d,S,f,g,c;const{t:p}=$.useLocaleContext(),b=!((d=r.routeMetaData)!=null&&d.publishedAt)||((S=r.routeMetaData)==null?void 0:S.updatedAt)&&new Date((f=r.routeMetaData)==null?void 0:f.updatedAt)>new Date((g=r.routeMetaData)==null?void 0:g.publishedAt);return e.jsx(s.ListItem,{sx:{pl:4,pr:3},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{display:"flex",alignItems:"center",sx:{minWidth:"auto"},children:[b&&e.jsx(s.Box,{mr:.35,className:"visible",color:"warning.main",sx:{display:"flex",alignItems:"center"},title:p("maker.pages.needPublish"),children:e.jsx(s.Tooltip,{title:p("maker.pages.needPublish"),children:e.jsx(P.Sync,{fontSize:"small",sx:{fontSize:"16px"}})})}),(!((c=r.routeMetaData)!=null&&c.isPublic)||!u.isPublic)&&e.jsx(s.Box,{className:"visible",color:"warning.main",children:e.jsx(s.Tooltip,{title:p("maker.pages.notPublic"),children:e.jsx(P.VisibilityOff,{fontSize:"small",sx:{fontSize:"16px"}})})})]}),children:e.jsxs(s.ListItemButton,{onClick:k,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:j,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:r.path,primaryTypographyProps:{fontSize:"0.8rem",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pr:1}})]})})}function de({state:r,toMode:j,onChange:k,defaultRouteIds:u}){const{t:p,locale:b}=$.useLocaleContext(),[d,S]=l.useState(!1),[f,g]=l.useState(()=>u?Object.fromEntries(u.filter(t=>!t.includes("-")).map(t=>[t,!0])):{}),[c,O]=l.useState({}),[w,y]=l.useState(()=>u?Object.fromEntries(u.filter(t=>t.includes("-")).map(t=>[t,!0])):{}),[A,M]=l.useState({}),{loading:z,error:R,value:x}=ie.useAsync(()=>U.getPages({mode:j}),[j]);if(R)throw R;const T=l.useMemo(()=>r.routeIds||[],[r]),I=l.useMemo(()=>(x==null?void 0:x.pageIds)||[],[x]),D=l.useMemo(()=>!T||!r.routes?[]:JSON.parse(JSON.stringify(T)).sort((o,i)=>{var h,m;const n=(h=r.routes)==null?void 0:h[o],a=(m=r.routes)==null?void 0:m[i];return n!=null&&n.publishedAt&&new Date(n.publishedAt).getTime()<new Date(n.updatedAt).getTime()?-1:a!=null&&a.publishedAt&&new Date(a.publishedAt).getTime()<new Date(a.updatedAt).getTime()?1:new Date((n==null?void 0:n.updatedAt)??"").getTime()-new Date((a==null?void 0:a.updatedAt)??"").getTime()}),[r,T]),q=l.useMemo(()=>{if(!D)return[];if(!c)return D;const t=[...D].filter(o=>!c[o]);return Object.values(c).forEach(o=>{o.forEach(i=>{t.push(`${i.originalRouteId}-${i.paramOptionIds.join("-")}`)})}),t},[D,c]),L=l.useMemo(()=>!x||!I||!q?[]:H.default(I,q),[q,x,I]),C=l.useMemo(()=>T?[...T].concat(L):L,[T,L]),_=l.useCallback(()=>{const t={};D==null||D.forEach(o=>{var n;const i=(n=r.routes)==null?void 0:n[o];if(i&&i.params&&i.params.length>0&&i.paramsOptions&&i.paramsOptions.length>0){const a=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});a.length>0&&(t[i.id]=a)}}),O(t)},[D,r.routes]);l.useEffect(()=>{_()},[_]),l.useEffect(()=>{M(t=>{const o={...t};return Object.keys(c).forEach(i=>{var n;c[i]&&((n=c[i])==null?void 0:n.length)>0&&o[i]===void 0&&(o[i]=!0)}),o})},[c]);const K=l.useRef(!0);l.useEffect(()=>{y(t=>{const o={...t};return Object.keys(c).length===0||(Object.keys(c).forEach(i=>{const n=c[i]||[],a=d||!!f[i];n.forEach(h=>{const m=`${i}-${h.paramOptionIds.join("-")}`;K.current?o[m]=a||t[m]||!1:o[m]=a})}),K.current=!1),o})},[f,c,d]);const Q=(t,o)=>{o.stopPropagation(),M(i=>{const n={...i};return n[t]=!n[t],n})},N=l.useCallback(t=>{g(o=>{const i=se.produce(o,n=>{d?(Object.assign(n,Object.fromEntries(C.map(a=>[a,!0]))),delete n[t]):n[t]?(delete n[t],L.includes(t)&&(T||[]).filter(a=>{var h,m;return((h=r.pages[a])==null?void 0:h.slug)===((m=x==null?void 0:x.pages[t])==null?void 0:m.slug)}).forEach(a=>{delete n[a]})):(n[t]=!0,T&&T.includes(t)&&L.filter(a=>{var h,m;return((h=x==null?void 0:x.pages[a])==null?void 0:h.slug)===((m=r.pages[t])==null?void 0:m.slug)}).forEach(a=>{n[a]=!0}))});return S(H.default(C,Object.keys(i)).length===0),i})},[d,C,L,r,x,T]),X=l.useCallback((t,o)=>{const i=`${t}-${o.paramOptionIds.join("-")}`;y(n=>{var m;const a={...n};a[i]=!a[i];const h=((m=c[t])==null?void 0:m.every(B=>a[`${t}-${B.paramOptionIds.join("-")}`]))??!1;return g(B=>{if(h&&!B[t])return{...B,[t]:!0};if(!h&&B[t]){const v={...B};return delete v[t],v}return B}),a})},[c]),Y=l.useCallback(()=>{S(t=>(t&&g({}),!t))},[]);return l.useEffect(()=>{const t=d?C:Object.keys(f),o=Object.entries(w).filter(([,n])=>n).map(([n])=>n).filter(n=>n!==void 0),i=Array.from(new Set([...t,...o]));k(d?null:i)},[d,f,w,C,k]),z?e.jsx(re.Loading,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:700},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,bgcolor:"background.paper",zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:Y,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:p("common.all")})]})}),D.map(t=>{var B,v;const o=(B=r.routes)==null?void 0:B[t];if(!o)return null;const i=!1,n=c&&c[t]&&((v=c[t])==null?void 0:v.length)>0,a=A[t]!==!1,h=c[t]||[],m=!o.publishedAt||o.updatedAt&&new Date(o.updatedAt).getTime()>new Date(o.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:[m&&e.jsx(s.Tooltip,{title:p("maker.pages.needPublish"),children:e.jsx(P.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!o.isPublic&&e.jsx(s.Tooltip,{title:p("maker.pages.notPublic"),children:e.jsx(P.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),i,n&&e.jsx(s.Box,{onClick:E=>Q(t,E),sx:{display:"inline-flex",alignItems:"center",mr:.35,cursor:"pointer",color:"info.main"},children:a?e.jsx(P.KeyboardArrowDown,{fontSize:"small",sx:{fontSize:"18px"}}):e.jsx(P.KeyboardArrowRight,{fontSize:"small",sx:{fontSize:"18px"}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>N(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:o.path,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})}),n&&e.jsx(s.Collapse,{in:a,children:e.jsx(s.Box,{children:h.map(E=>{const V=`${t}-${E.paramOptionIds.join("-")}`,Z=w[V]||!1;return e.jsx(ue,{routePathInfo:E,checked:d||Z,onClick:()=>X(t,E),route:o},V)})})})]},t)}),L.map(t=>{var i,n;const o=x==null?void 0:x.pages[t];return o?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>N(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:o.slug,secondary:(n=(i=o.locales)==null?void 0:i[b])==null?void 0:n.title,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})},t):null})]})}exports.default=ce;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),F=require("./state-D4MG-uJB.js"),$=require("@arcblock/ux/lib/Locale/context"),ee=require("@arcblock/ux/lib/Toast"),te=require("@blocklet/pages-kit/utils/route"),P=require("@mui/icons-material"),J=require("@mui/lab"),s=require("@mui/material"),se=require("immer"),ne=require("lodash/difference"),l=require("react"),ie=require("react-use"),re=require("./home-B5XHNRCN.js"),U=require("./array-6wh7d5gC.js"),G=r=>r&&r.__esModule?r:{default:r},W=G(ee),H=G(ne);function oe(r){const[j,k]=l.useState(!1);return e.jsx(J.LoadingButton,{...r,loading:r.loading||j,onClick:u=>{var b;const p=(b=r.onClick)==null?void 0:b.call(r,u);p instanceof Promise&&(k(!0),p.finally(()=>{k(!1)}))}})}const ae=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 le(){const[r,j]=l.useState(),k=l.useMemo(()=>r?e.jsx(s.Dialog,{...r}):null,[r]),u=l.useCallback(()=>{j(void 0)},[]),p=l.useCallback(({title:b,content:d,cancelText:S="Cancel",okText:f="Ok",onOk:g,onClose:c,okIcon:O,okColor:w="primary",cancelColor:y="primary",DialogContentProps:A,form:M,...z})=>{j({...z,open:!0,children:e.jsxs("form",{onSubmit:R=>R.preventDefault(),children:[b&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:"1px solid #E5E7EB"},children:[e.jsx(s.Box,{children:b}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{u(),c==null||c()},children:e.jsx(ae,{})})]}),d&&e.jsx(s.DialogContent,{...A,sx:{mt:-3,...A==null?void 0:A.sx},children:e.jsx(s.Box,{pt:3,children:d})}),e.jsxs(s.DialogActions,{children:[e.jsx(s.Button,{variant:"outlined",color:y||"primary",onClick:c??u,children:S}),e.jsx(oe,{variant:"contained",color:w||"primary",startIcon:O,loadingPosition:O?"start":"center",onClick:async()=>{await(g==null?void 0:g()),u()},type:"submit",children:f})]})]}),onClose:c??u})},[u]);return{dialog:k,showDialog:p,closeDialog:u}}const ce=l.forwardRef(({mode:r,state:j},k)=>{const{t:u}=$.useLocaleContext(),[p,b]=l.useState(!1),{dialog:d,showDialog:S}=le(),f=F.useProjectId(),g=l.useCallback(O=>{let w=[];S({title:u("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(P.Warning,{}),children:u("maker.publishToProductionTip")}),e.jsx(s.Box,{maxHeight:"50vh",overflow:"auto",mt:2,children:e.jsx(de,{state:j,toMode:r,onChange:y=>w=y,defaultRouteIds:O})})]}),okText:u("maker.publish"),cancelText:u("common.cancel"),onOk:async()=>{if((w==null?void 0:w.length)===0){const y=u("maker.publishSelectPagesMessage");throw W.default.error(y),new Error(y)}localStorage.setItem(F.getProjectPageVersionKey(f??""),String(new Date().getTime())),b(!0);try{await U.publishPages({mode:r,routes:w}),W.default.success(u("maker.publishSuccessMessage"))}catch(y){throw W.default.error(y.message),y}finally{b(!1)}}})},[r,j,u,f,S]);l.useImperativeHandle(k,()=>({openPublishDialog:g}));const c=l.useCallback(()=>{g()},[g]);return e.jsxs(e.Fragment,{children:[e.jsx(J.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:c,loading:p,disabled:p,children:u("maker.publishToProduction")}),d]})});function ue({routePathInfo:r,checked:j,onClick:k,route:u}){var d,S,f,g,c;const{t:p}=$.useLocaleContext(),b=!((d=r.routeMetaData)!=null&&d.publishedAt)||((S=r.routeMetaData)==null?void 0:S.updatedAt)&&new Date((f=r.routeMetaData)==null?void 0:f.updatedAt)>new Date((g=r.routeMetaData)==null?void 0:g.publishedAt);return e.jsx(s.ListItem,{sx:{pl:4,pr:3},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{display:"flex",alignItems:"center",sx:{minWidth:"auto"},children:[b&&e.jsx(s.Box,{mr:.35,className:"visible",color:"warning.main",sx:{display:"flex",alignItems:"center"},title:p("maker.pages.needPublish"),children:e.jsx(s.Tooltip,{title:p("maker.pages.needPublish"),children:e.jsx(P.Sync,{fontSize:"small",sx:{fontSize:"16px"}})})}),(!((c=r.routeMetaData)!=null&&c.isPublic)||!u.isPublic)&&e.jsx(s.Box,{className:"visible",color:"warning.main",children:e.jsx(s.Tooltip,{title:p("maker.pages.notPublic"),children:e.jsx(P.VisibilityOff,{fontSize:"small",sx:{fontSize:"16px"}})})})]}),children:e.jsxs(s.ListItemButton,{onClick:k,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:j,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:r.path,primaryTypographyProps:{fontSize:"0.8rem",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pr:1}})]})})}function de({state:r,toMode:j,onChange:k,defaultRouteIds:u}){const{t:p,locale:b}=$.useLocaleContext(),[d,S]=l.useState(!1),[f,g]=l.useState(()=>u?Object.fromEntries(u.filter(t=>!t.includes("-")).map(t=>[t,!0])):{}),[c,O]=l.useState({}),[w,y]=l.useState(()=>u?Object.fromEntries(u.filter(t=>t.includes("-")).map(t=>[t,!0])):{}),[A,M]=l.useState({}),{loading:z,error:R,value:x}=ie.useAsync(()=>U.getPages({mode:j}),[j]);if(R)throw R;const T=l.useMemo(()=>r.routeIds||[],[r]),I=l.useMemo(()=>(x==null?void 0:x.pageIds)||[],[x]),D=l.useMemo(()=>!T||!r.routes?[]:JSON.parse(JSON.stringify(T)).sort((o,i)=>{var h,m;const n=(h=r.routes)==null?void 0:h[o],a=(m=r.routes)==null?void 0:m[i];return n!=null&&n.publishedAt&&new Date(n.publishedAt).getTime()<new Date(n.updatedAt).getTime()?-1:a!=null&&a.publishedAt&&new Date(a.publishedAt).getTime()<new Date(a.updatedAt).getTime()?1:new Date((n==null?void 0:n.updatedAt)??"").getTime()-new Date((a==null?void 0:a.updatedAt)??"").getTime()}),[r,T]),q=l.useMemo(()=>{if(!D)return[];if(!c)return D;const t=[...D].filter(o=>!c[o]);return Object.values(c).forEach(o=>{o.forEach(i=>{t.push(`${i.originalRouteId}-${i.paramOptionIds.join("-")}`)})}),t},[D,c]),L=l.useMemo(()=>!x||!I||!q?[]:H.default(I,q),[q,x,I]),C=l.useMemo(()=>T?[...T].concat(L):L,[T,L]),_=l.useCallback(()=>{const t={};D==null||D.forEach(o=>{var n;const i=(n=r.routes)==null?void 0:n[o];if(i&&i.params&&i.params.length>0&&i.paramsOptions&&i.paramsOptions.length>0){const a=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});a.length>0&&(t[i.id]=a)}}),O(t)},[D,r.routes]);l.useEffect(()=>{_()},[_]),l.useEffect(()=>{M(t=>{const o={...t};return Object.keys(c).forEach(i=>{var n;c[i]&&((n=c[i])==null?void 0:n.length)>0&&o[i]===void 0&&(o[i]=!0)}),o})},[c]);const K=l.useRef(!0);l.useEffect(()=>{y(t=>{const o={...t};return Object.keys(c).length===0||(Object.keys(c).forEach(i=>{const n=c[i]||[],a=d||!!f[i];n.forEach(h=>{const m=`${i}-${h.paramOptionIds.join("-")}`;K.current?o[m]=a||t[m]||!1:o[m]=a})}),K.current=!1),o})},[f,c,d]);const Q=(t,o)=>{o.stopPropagation(),M(i=>{const n={...i};return n[t]=!n[t],n})},N=l.useCallback(t=>{g(o=>{const i=se.produce(o,n=>{d?(Object.assign(n,Object.fromEntries(C.map(a=>[a,!0]))),delete n[t]):n[t]?(delete n[t],L.includes(t)&&(T||[]).filter(a=>{var h,m;return((h=r.pages[a])==null?void 0:h.slug)===((m=x==null?void 0:x.pages[t])==null?void 0:m.slug)}).forEach(a=>{delete n[a]})):(n[t]=!0,T&&T.includes(t)&&L.filter(a=>{var h,m;return((h=x==null?void 0:x.pages[a])==null?void 0:h.slug)===((m=r.pages[t])==null?void 0:m.slug)}).forEach(a=>{n[a]=!0}))});return S(H.default(C,Object.keys(i)).length===0),i})},[d,C,L,r,x,T]),X=l.useCallback((t,o)=>{const i=`${t}-${o.paramOptionIds.join("-")}`;y(n=>{var m;const a={...n};a[i]=!a[i];const h=((m=c[t])==null?void 0:m.every(B=>a[`${t}-${B.paramOptionIds.join("-")}`]))??!1;return g(B=>{if(h&&!B[t])return{...B,[t]:!0};if(!h&&B[t]){const v={...B};return delete v[t],v}return B}),a})},[c]),Y=l.useCallback(()=>{S(t=>(t&&g({}),!t))},[]);return l.useEffect(()=>{const t=d?C:Object.keys(f),o=Object.entries(w).filter(([,n])=>n).map(([n])=>n).filter(n=>n!==void 0),i=Array.from(new Set([...t,...o]));k(d?null:i)},[d,f,w,C,k]),z?e.jsx(re.Loading,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:700},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,bgcolor:"background.paper",zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:Y,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:p("common.all")})]})}),D.map(t=>{var B,v;const o=(B=r.routes)==null?void 0:B[t];if(!o)return null;const i=!1,n=c&&c[t]&&((v=c[t])==null?void 0:v.length)>0,a=A[t]!==!1,h=c[t]||[],m=!o.publishedAt||o.updatedAt&&new Date(o.updatedAt).getTime()>new Date(o.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:[m&&e.jsx(s.Tooltip,{title:p("maker.pages.needPublish"),children:e.jsx(P.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!o.isPublic&&e.jsx(s.Tooltip,{title:p("maker.pages.notPublic"),children:e.jsx(P.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),i,n&&e.jsx(s.Box,{onClick:E=>Q(t,E),sx:{display:"inline-flex",alignItems:"center",mr:.35,cursor:"pointer",color:"info.main"},children:a?e.jsx(P.KeyboardArrowDown,{fontSize:"small",sx:{fontSize:"18px"}}):e.jsx(P.KeyboardArrowRight,{fontSize:"small",sx:{fontSize:"18px"}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>N(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:o.path,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})}),n&&e.jsx(s.Collapse,{in:a,children:e.jsx(s.Box,{children:h.map(E=>{const V=`${t}-${E.paramOptionIds.join("-")}`,Z=w[V]||!1;return e.jsx(ue,{routePathInfo:E,checked:d||Z,onClick:()=>X(t,E),route:o},V)})})})]},t)}),L.map(t=>{var i,n;const o=x==null?void 0:x.pages[t];return o?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>N(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:o.slug,secondary:(n=(i=o.locales)==null?void 0:i[b])==null?void 0:n.title,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})},t):null})]})}exports.default=ce;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";var Ot=Object.defineProperty;var At=(e,s,t)=>s in e?Ot(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var x=(e,s,t)=>At(e,typeof s!="symbol"?s+"":s,t);const Tt=require("@blocklet/pages-kit/builtin/utils"),he=require("@blocklet/pages-kit/types"),re=require("@blocklet/pages-kit/utils/property"),Q=require("@blocklet/quickjs"),Pt=require("@blocklet/sdk/lib/config"),Fe=require("lru-cache"),st=require("node-fetch"),M=require("ufo"),Ae=require("crypto"),jt=require("@blocklet/logger"),_t=require("@blocklet/pages-kit/utils/builtin"),nt=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),qe=require("@blocklet/sdk/lib/component"),Ct=require("autoprefixer"),Dt=require("esbuild"),b=require("fs"),vt=require("postcss"),xt=require("tailwindcss"),kt=require("typescript"),W=require("@syncedstore/core"),Nt=require("yjs"),S=require("path"),Rt=require("@blocklet/pages-kit/utils/data-source"),we=require("@blocklet/pages-kit/utils/route"),Lt=require("lodash"),Mt=require("@reactivedata/reactive"),ke=require("glob"),Ut=require("lib0/decoding"),Ft=require("lib0/encoding"),qt=require("lodash/cloneDeep"),$t=require("lodash/debounce"),Bt=require("lodash/get"),Gt=require("lodash/isEmpty"),Vt=require("lodash/pick"),Ht=require("lodash/set"),Jt=require("lodash/union"),zt=require("nanoid"),Kt=require("p-limit"),Yt=require("stream/promises"),Wt=require("tar"),Qt=require("wait-on"),se=require("y-protocols/awareness"),Ce=require("y-protocols/sync"),Xt=require("yaml"),Zt=require("lodash/isNil"),C=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const N=e=>e&&e.__esModule?e:{default:e};function le(e){if(e&&e.__esModule)return e;const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,n.get?n:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const O=N(Pt),es=N(st),ts=N(jt),ss=N(Ct),ns=le(Dt),os=N(vt),as=N(xt),L=N(kt),B=le(Nt),rs=N(S),De=le(Ut),k=le(Ft),is=N(qt),ot=N($t),$e=N(Bt),cs=N(Gt),ls=N(Vt),Ye=N(Ht),ps=N(Jt),us=N(Kt),ds=N(Qt),X=le(Xt),fs=N(Zt);O.default.env.mode;O.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;O.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;O.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;O.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const ms="image-bin";O.default.env.INIT_TEMPLATE_PATH;const gs=process.env.DATABASE_URL||rs.default.join(O.default.env.dataDir,"db/pages-kit.db"),We=O.default,hs=()=>O.default.env.tenantMode==="multiple",ys=()=>{var e;return(fs.default(We.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=We.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},I=ts.default("pages-kit"),Ss=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):Ss(e,s);const pe=new C.Sequelize({dialect:"sqlite",storage:gs,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});pe.query("pragma journal_mode = WAL;");pe.query("pragma synchronous = normal;");pe.query("pragma journal_size_limit = 67108864;");class Te extends C.Model{}Te.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:pe,tableName:"ProjectComponents",timestamps:!1});class J extends C.Model{static async getProjectByIdOrSlug(s){return J.findOne({where:{[C.Op.or]:[{id:s},{slug:s}]}})}}J.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(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:pe,paranoid:!0});J.hasMany(Te,{foreignKey:"projectId",as:"components"});const ws=async(e,{componentId:s})=>{const t=`@tailwind components;
|
|
2
|
+
@tailwind utilities;
|
|
3
|
+
`,n=`.CustomComponent_${s}`;return(await os.default([as.default({content:[{raw:e,extension:"tsx"}]}),ss.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(p=>{p.selectors=p.selectors.map(c=>c.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},bs=async(e,{componentId:s})=>{const t=await ws(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
|
|
4
|
+
|
|
5
|
+
${e}
|
|
6
|
+
`},Qe=Q.memoize(async(e,s)=>{let t=L.default.transpileModule(e,{compilerOptions:{jsx:L.default.JsxEmit.React,target:L.default.ScriptTarget.ES2016,module:L.default.ModuleKind.ESNext},transformers:{before:[nt.createBuiltinModuleTransformer(L.default)]}}).outputText;if(s.tailwind&&(t=await bs(t,{componentId:s.componentId})),s.module===he.PreloadComponentScriptModule.ESM)return t;const n=L.default.transpileModule(t,{compilerOptions:{jsx:L.default.JsxEmit.React,target:L.default.ScriptTarget.ES2016,module:L.default.ModuleKind.CommonJS,moduleResolution:L.default.ModuleResolutionKind.Node16}}).outputText;return s.module===he.PreloadComponentScriptModule.CJS?n:Is(s.moduleName,n)},{keyGenerator:(e,s)=>{const t=Ae.createHash("md5").update(e).digest("hex"),n={...s,componentId:s.componentId,module:s.module,...s.module!==he.PreloadComponentScriptModule.ESM?{moduleName:s.moduleName}:{},tailwind:s.tailwind};return JSON.stringify(["transpileModule",t,n])},lruOptions:{max:100,ttl:1e3*60*60}}),Es=async(e,s)=>{var p,c;const n=(c=(p=(await ns.build({entryPoints:["index.tsx"],external:Object.keys(_t.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(u){let l=null;u.onResolve({filter:/.*/},d=>d.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:d.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),u.onLoad({filter:/.*/,namespace:"vfs"},async d=>{var y;if(d.path==="index.tsx")return{contents:`export { ${s} } from './component'`,loader:"tsx"};if(d.path==="component.tsx")return{contents:e,loader:"tsx"};if(nt.isRelativeModule(d.path)){const h=d.path.split("/").pop();if(l||(l=await Pe({ensureLoaded:!1})),(y=l==null?void 0:l.chunks)!=null&&y[h])try{const r=b.readFileSync(l.chunks[h],"utf-8");return I.info("get chunk from local file system",h),{contents:r,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:p[0])==null?void 0:c.contents;if(!n)throw new Error("Failed to build server code");const o=Buffer.from(n).toString();return L.default.transpileModule(o,{compilerOptions:{module:L.default.ModuleKind.ESNext,target:L.default.ScriptTarget.ES2020}}).outputText},at=Q.memoize(async(e,s)=>{const t=await Es(e,s);return new RegExp(`export\\s+\\{\\s+${s}\\s+\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,s)=>{const t=Ae.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,s])},lruOptions:{max:100,ttl:1e3*60*60}}),Is=(e,s)=>`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
+
var ${e} = function () {
|
|
8
|
+
|
|
9
|
+
const exports = {};
|
|
10
|
+
let moduleExports = null;
|
|
11
|
+
|
|
12
|
+
// add commonjs module compatibility layer
|
|
13
|
+
const module = { exports: moduleExports };
|
|
14
|
+
|
|
15
|
+
// execute component code
|
|
16
|
+
${s}
|
|
17
|
+
|
|
18
|
+
// handle possible module.exports
|
|
19
|
+
if (module.exports && module.exports !== moduleExports) {
|
|
20
|
+
// if module.exports is used, use it first
|
|
21
|
+
return typeof module.exports === 'object' ? module.exports : { default: module.exports };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ensure a default export
|
|
25
|
+
if (!('default' in exports) && Object.keys(exports).length === 0) {
|
|
26
|
+
// module has no exports, return null to indicate invalid
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return exports;
|
|
31
|
+
};
|
|
32
|
+
`,oe=new Fe.LRUCache({max:100}),rt=60*60,Ne=60;function it(e){I.info("clear preload components cache",{cacheKey:e}),oe.delete(e)}function ct(e){for(const s of oe.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),it(s))}function lt({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Os({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:p,config:{defaultLocale:c}}=t;if(!c)return null;const u=(await Promise.all(o.map(async r=>{try{const i=lt({mode:e,instanceId:r.id,componentId:r.componentId,locale:n});if(e!=="draft"&&r.useCache&&oe.has(i))return I.info(`get preload component from cache: ${i}`),oe.get(i);const f=ie({state:t,componentId:r.componentId});if(!f)return null;const E=await pt({req:s,state:t,componentId:f.id,locale:n,defaultLocale:c,properties:r.properties});if(!E)return null;const v={instanceId:r.id,preload:E};if(e!=="draft"&&r.useCache){let T=rt;r.cacheDuration&&(T=r.cacheDuration),I.info(`set preload component to cache(${T}s): ${i}`),oe.set(i,v,{ttl:T*1e3})}return v}catch(i){return I.error("get preload component error",{instanceId:r.id,componentId:r.componentId},{error:i}),null}}))).filter(r=>!!r),l=Object.values(u.reduce((r,i)=>({...r,...i.preload.components}),{}));async function d(){const r=await Promise.all(l.map(async i=>{const f=re.componentUMDName({componentId:i.component.id}),E=a===he.PreloadComponentScriptModule.ESM?{module:a,script:await Qe(i.script,{componentId:i.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await Qe(i.script,{componentId:i.component.id,module:a,moduleName:f,tailwind:e!=="draft"}),moduleName:f};return[i.component.id,{component:i.component,script:E}]}));return Object.fromEntries(r)}const y=await d();return{config:{defaultLocale:c,supportedLocales:p},components:y,instances:u.map(r=>({id:r.instanceId,componentId:r.preload.component.id,locales:{[r.preload.locale]:{props:r.preload.props}}}))}}async function pt({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:p}=s,c=ie({state:s,componentId:t});if(!c)return null;const u=p.some(d=>d.locale===n)?n:o;if(!u)return null;const l=await ut({req:e,state:s,componentId:t,locale:u,defaultLocale:o,properties:a});return l?{component:c,...l}:null}const As=20;async function ut({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:p}){if(s>As)throw new RangeError("max component depth exceeded");const c=Ts({state:t,componentId:n,properties:p,locale:o});if(!c)return null;const{props:u}=c,l={locale:o||a,components:{[c.component.id]:{component:c.component,script:c.script}},props:{...u}};try{const d=await js({...c,req:e});d!=null&&d.props&&Object.assign(l.props,d.props)}catch(d){I.error("preload data at server side error",{componentId:n,name:c.component.name},{error:d})}return await Promise.all(Object.entries(u).map(async([d,y])=>{if((y==null?void 0:y.type)===re.RenderNestedComponent){const h=await ut({req:e,depth:s+1,state:t,componentId:y.componentId,locale:o,defaultLocale:a,properties:y.properties});h&&(Object.assign(l.components,h.components),Object.assign(l.props,{[d]:{type:re.RenderNestedComponent,componentId:y.componentId,props:h.props}}))}})),l}function Ts({state:e,componentId:s,locale:t,properties:n}){const o=ie({state:e,componentId:s});if(!o)return null;const a=re.mergeComponent({componentId:s,getComponent:p=>ie({state:e,componentId:p}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.props}}:null}function ie({state:e,componentId:s}){var t,n,o;return((t=e.components[s])==null?void 0:t.data)??((o=(n=e.resources.components)==null?void 0:n[s])==null?void 0:o.component)}function Ps({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var p;return((p=a.data.name)==null?void 0:p.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var p;return((p=a.component.name)==null?void 0:p.toLowerCase())===t}))==null?void 0:o.component)}async function js({component:e,script:s,props:t,req:n}){if(!(s!=null&&s.includes("getServerSideProps")))return null;const o=await at(s,"getServerSideProps");if(!o)return null;const a=new Promise(c=>{setTimeout(()=>{c({})},Ne*1e3)});return await Promise.race([a,Q.Sandbox.callFunction({code:`${o}
|
|
33
|
+
|
|
34
|
+
export async function getServerSidePropsWrapper(props) {
|
|
35
|
+
const { location, fetch, props: componentProps } = props;
|
|
36
|
+
// 使用局部变量而不是全局变量
|
|
37
|
+
const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
|
|
38
|
+
const originalFetch = globalThis.fetch;
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
globalThis.location = location;
|
|
42
|
+
globalThis.fetch = fetch;
|
|
43
|
+
return await getServerSideProps(componentProps);
|
|
44
|
+
} finally {
|
|
45
|
+
// 清理全局状态
|
|
46
|
+
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
+
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
+
}
|
|
49
|
+
}`,filename:`${e.name||e.id}.js`,moduleLoader:c=>{if(c==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
+
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
+
`;if(c==="@blocklet/pages-kit/builtin/dayjs")return Q.BuiltinModules.dayjs},global:{console:{log:(...c)=>{I.info(...c)},warn:(...c)=>{I.warn(...c)},error:(...c)=>{I.error(...c)}},getComponentMountPoint:Tt.getComponentMountPoint,joinURL:M.joinURL,withQuery:M.withQuery,getQuery:M.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:M.joinURL(M.withHttps(n.hostname),n.originalUrl)},fetch:(c,{...u}={})=>{const l=typeof c=="string"&&c.startsWith("/")?M.joinURL(O.default.env.appUrl,c):c;if(typeof l=="string"&&M.parseURL(l).host===M.parseURL(O.default.env.appUrl).host){const d=n.get("cookie");if(d){const y=new st.Headers(u.headers);y.set("cookie",d),u.headers=y}}return es.default(l,{...u,timeout:Ne*1e3}).then(d=>({ok:d.ok,status:d.status,statusText:d.statusText,headers:Object.fromEntries(d.headers.entries()),json:()=>d.json()}))},props:t}]})])}const dt=Q.memoize(async(e,s,t)=>{if(!(e!=null&&e.includes(s)))return null;const n=await at(e,s);if(n)try{return await Q.Sandbox.callFunction({code:`
|
|
52
|
+
${n}
|
|
53
|
+
|
|
54
|
+
export function get${s}SchemaWrapper() {
|
|
55
|
+
return ${s};
|
|
56
|
+
}
|
|
57
|
+
`,filename:`${t}.js`,functionName:`get${s}SchemaWrapper`})}catch(o){return I.error(`获取 ${s} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,s,t)=>{const n=Ae.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),_s="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Re="page",Le="trigger-reload-project-resource",Be=_s,Cs="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function be(e){e.observeDeep(s=>{s.some(t=>t.changes.keys.has("updatedAt")||t.changes.keys.has("publishedAt"))||e.set("updatedAt",new Date().toISOString())})}function ft(){return b.mkdtempSync(S.join(O.default.env.dataDir,"tmp-"))}function Ee(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>Ee(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>Ee(o,s,[...t,n])):s(e)?[t]:[]}function U(e){return e.filter(s=>s!=null)}function Ds(e){e.pages&&Object.keys(e.pages).forEach(t=>{const n=W.getYjsValue(e.pages[t]);n&&n instanceof B.Map&&be(n)});const s=W.getYjsValue(e.pages);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,o)=>{if(n.action==="add"){const a=W.getYjsValue(e.pages[o]);a&&a instanceof B.Map&&be(a)}})})}function vs(e){e.routes&&Object.keys(e.routes).forEach(t=>{var o;const n=W.getYjsValue((o=e.routes)==null?void 0:o[t]);n&&n instanceof B.Map&&be(n)});const s=W.getYjsValue(e.routes);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,o)=>{var a;if(n.action==="add"){const p=W.getYjsValue((a=e.routes)==null?void 0:a[o]);p&&p instanceof B.Map&&be(p)}})})}function xs(e,s){var t;for(const n of s||Object.keys(e.routes||{})){let o=n,a=[];if(n.includes("-")){const[p,...c]=n.split("-");o=p,a=c||[]}if(((t=e.routes)==null?void 0:t[o])!==void 0){e.routes[o].publishedAt=new Date().toISOString();const p=e.routes[o];if(!p||!p.params||p.params.length===0)continue;if(n.includes("-")&&a.length>0){const c=we.getRouteMetaDataByOptionIds(a,p);c&&(c.publishedAt=new Date().toISOString())}if(!s){const c=we.generateParamCombinations({basePath:p.path,params:p.params,routeId:p.id,paramsOptions:p.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const u of c)u.routeMetaData??(u.routeMetaData={}),u.routeMetaData.publishedAt=new Date().toISOString()}}}}function ve({page:e,route:s,state:t,routeId:n,routePathInfo:o}){var p,c,u,l,d,y,h,r,i;I.info(`Executing datasource data assembly, routeId: ${n}, routePathInfo: ${JSON.stringify(o)}`);const a={...Lt.cloneDeep(e),id:n,slug:(o==null?void 0:o.path)??s.path,createdAt:s.createdAt,updatedAt:((p=o==null?void 0:o.routeMetaData)==null?void 0:p.updatedAt)??s.updatedAt,publishedAt:((c=o==null?void 0:o.routeMetaData)==null?void 0:c.publishedAt)??s.publishedAt,isPublic:(((u=o==null?void 0:o.routeMetaData)==null?void 0:u.isPublic)??s.isPublic)&&s.isPublic};for(const f of t.supportedLocales){if(s.dataSource){let E=s.id;o&&(E=o.paramOptionIds.join("-"));const v=((y=(d=(l=s.dataSource.pathDataMappings)==null?void 0:l[E])==null?void 0:d.dataCache)==null?void 0:y[f.locale])??((i=(r=(h=s.dataSource.pathDataMappings)==null?void 0:h[E])==null?void 0:r.dataCache)==null?void 0:i[t.config.defaultLocale||"en"]);if(!v)continue;Rt.setPageDataSource(a,t,f.locale,v)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return a}const{uploadToMediaKit:ks}=require("@blocklet/uploader-server"),ye=zt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ge=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,ae=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Xe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Ns=1e4,Rs=3e4,me=0,xe=1,Ls=0,Ms=1,Me=O.default,ne=S.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Us=["production","draft"],Fs=["production"];function Ie(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function qs(){var t;const e=Me.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const H=class H extends B.Doc{constructor(t){super();x(this,"states",{});x(this,"syncedStore");x(this,"conns",new Map);x(this,"awareness");x(this,"awarenessChangeHandler",({added:t,updated:n,removed:o},a)=>{const p=t.concat(n,o);if(a!==null){const l=this.conns.get(a);l&&(t.forEach(d=>{l.add(d)}),o.forEach(d=>{l.delete(d)}))}const c=k.createEncoder();k.writeVarUint(c,xe),k.writeVarUint8Array(c,se.encodeAwarenessUpdate(this.awareness,p));const u=k.toUint8Array(c);this.conns.forEach((l,d)=>this.send(d,u))});x(this,"updateHandler",t=>{const n=k.createEncoder();k.writeVarUint(n,me),Ce.writeUpdate(n,t);const o=k.toUint8Array(n);this.conns.forEach((a,p)=>this.send(p,o))});x(this,"ensureDataStructure",()=>{var p;const{supportedLocales:t,pages:n,pageIds:o,config:a}=this.syncedStore;{const c=new Set(Object.keys(n));let u=0;for(;u<o.length;){const l=o[u];c.has(l)?(c.delete(l),u++):o.splice(u,1)}}t.splice(0,t.length),t.push(...Me.env.languages.map(c=>({locale:c.code,name:c.name}))),a.defaultLocale=(p=t[0])==null?void 0:p.locale;{let c=0;const u=new Set;for(;c<t.length;){const{locale:l}=t[c];u.has(l)?t.splice(c,1):(c++,u.add(l))}}});x(this,"send",(t,n)=>{t.readyState!==Ls&&t.readyState!==Ms&&this.closeConn(t);try{t.send(n,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}});x(this,"closeConn",t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&se.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()});x(this,"autoSave",ot.default(()=>{b.mkdirSync(S.dirname(this.draftYjsFilePath),{recursive:!0}),b.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Ns));x(this,"save",({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()});x(this,"publish",async({mode:t,routes:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await Ue(o,a,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:t}),a.config.publishedAt=new Date().getTime(),xs(this.syncedStore,n),await this.setState(t,a)});x(this,"mergeState",async(t,n)=>{var c,u,l;const o=JSON.parse(JSON.stringify(n));(c=t.config).fontFamily??(c.fontFamily={});const a=(u=o.config)==null?void 0:u.fontFamily,p=(l=t.config)==null?void 0:l.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(p==null?void 0:p.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(p==null?void 0:p.description),await new Promise((d,y)=>{this.transact(async()=>{try{const h=await Ue(t,n);d(h)}catch(h){y(h)}})})});x(this,"addConnection",t=>{if(this.conns.has(t))return;t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",a=>this.messageListener(t,new Uint8Array(a)));let n=!0;const o=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},Rs);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=k.createEncoder();k.writeVarUint(a,me),Ce.writeSyncStep1(a,this),this.send(t,k.toUint8Array(a));const p=this.awareness.getStates();if(p.size>0){const c=k.createEncoder();k.writeVarUint(c,xe),k.writeVarUint8Array(c,se.encodeAwarenessUpdate(this.awareness,Array.from(p.keys()))),this.send(t,k.toUint8Array(c))}}});x(this,"messageListener",(t,n)=>{try{const o=k.createEncoder(),a=De.createDecoder(n),p=De.readVarUint(a);switch(p){case me:k.writeVarUint(o,me),Ce.readSyncMessage(a,o,this,null),k.length(o)>1&&(this.ensureDataStructure(),this.send(t,k.toUint8Array(o)));break;case xe:{se.applyAwarenessUpdate(this.awareness,De.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${p}`)}}catch(o){I.error(o)}this.save()});this.options=t,b.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,b.readFileSync(this.draftYjsFilePath)),this.syncedStore=Mt.reactive(W.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new se.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(t){if(!t)throw new Error("Should provide project context");try{const n=S.join(ne,t),o=S.join(ne,`@del-${t}`);b.renameSync(n,o)}catch(n){I.error("Failed to safe delete project state dir:",n)}}static get projectIds(){return ke.globSync("*/",{cwd:ne,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(t=>H.shared(t))}static shared(t){if(!t)throw new Error("Should provide project context");let n=this.sharedInstances.get(t);return n||(n=new H({path:S.join(ne,t)}),this.sharedInstances.set(t,n),n)}destroy(){this.conns.forEach((t,n)=>this.closeConn(n)),this.awareness.destroy(),super.destroy()}initObserver(){Ds(this.syncedStore),vs(this.syncedStore)}get draftYjsFilePath(){return S.join(this.options.path,"draft.yjs")}async getState(t){var n,o,a,p;if(t==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[t]&&(this.states[t]=await Ve(this.getPublishDir(t),{includeResources:!0})??qs(),!((o=(n=this.states[t])==null?void 0:n.config)!=null&&o.defaultLocale))){(a=this.states[t]).config??(a.config={});const c=Me.env.languages.map(u=>({locale:u.code,name:u.name}));this.states[t].config.defaultLocale=(p=c[0])==null?void 0:p.locale}return{...this.states[t],resources:await Pe().then(async c=>{var r,i,f,E;const{pages:u,components:l}=ls.default(c,"pages","components");let d=l;const y=S.basename(this.options.path),h=await J.findByPk(y);if(h!=null&&h.useAllResources)d=l;else{const T=(await Te.findAll({where:{projectId:y}})).map(F=>F.componentId);d=Object.fromEntries(Object.entries(l||{}).filter(([F])=>T.includes(F)))}return Object.keys(((i=(r=this.states[t])==null?void 0:r.resources)==null?void 0:i.components)||{}).length>0&&(d={...d,...(E=(f=this.states[t])==null?void 0:f.resources)==null?void 0:E.components}),{pages:u,components:d}}).catch(()=>({}))}}async setState(t,n){const o=await yt(n,{exportAssets:!1,includeResources:!0}),a=this.getPublishDir(t);b.mkdirSync(S.dirname(a),{recursive:!0}),b.rmSync(a,{force:!0,recursive:!0}),b.renameSync(o,a),this.states[t]=n}getPublishDir(t){return S.join(this.options.path,t)}static async pageUrlMap(t){var a,p;const{projectIds:n}=this,o={};for(const c of n){const u=await J.findByPk(c);if(!u)continue;const l=await H.shared(c).getState(t),d=u.slug||c,y=ps.default(O.default.env.languages.map(r=>r.code),l.supportedLocales.map(r=>r.locale)),h=(r,i)=>{d&&(o[M.joinURL("/",d,r)]={...i,shouldRedirect:!0,mainPage:!0}),o[M.joinURL("/",c,r)]={...i,shouldRedirect:!0,mainPage:!0};for(const f of y){const E={...i,locale:f};o[M.joinURL("/",f,c,r)]=E,d&&(o[M.joinURL("/",f,d,r)]=E)}};if(t==="draft")for(const r of l.routeIds||[]){const i=(a=l==null?void 0:l.routes)==null?void 0:a[r];if(!i)continue;if(i.params&&i.params.length>0){const v=we.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const T of v){const R=T.path,F={projectId:c,projectSlug:d,pageSlug:R,pageId:i.displayTemplateId||"",routeId:r,defaultLocale:y==null?void 0:y[0],locales:y,publishedAt:l.config.publishedAt,isPublic:i.isPublic&&((p=T==null?void 0:T.routeMetaData)==null?void 0:p.isPublic)};h(R,F)}}const f=i.path,E={projectId:c,projectSlug:d,pageSlug:f,pageId:i.displayTemplateId||"",routeId:r,defaultLocale:y==null?void 0:y[0],locales:y,publishedAt:l.config.publishedAt,isPublic:i.isPublic};h(f,E)}for(const r of l.pageIds){const i=l.pages[r];if(!i||t==="production"&&!i.isPublic)continue;const f=i.slug,E=u.slug||c,v={projectId:c,projectSlug:E,pageSlug:f,pageId:r,defaultLocale:y==null?void 0:y[0],locales:y,publishedAt:l.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};h(f,v)}}return o}getDocumentSize(){return B.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const t=[];for(const[n,o]of this.sharedInstances.entries()){const a=o.getDocumentSize();t.push({projectId:n,sizeInBytes:a,sizeInMB:`${(a/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return t}};x(H,"INSTANCE_TTL",30*60*1e3),x(H,"sharedInstances",new Fe.LRUCache({max:100,ttl:H.INSTANCE_TTL,dispose:t=>{t.destroy()}}));let ce=H;async function $s(e,s,t){if(!e||!b.existsSync(e)||!b.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>{var o;try{const a=(o=await ks({filePath:e,fileName:s}))==null?void 0:o.data;return a==null?void 0:a.filename}catch(a){return I.error(`Failed to upload asset ${e}:`,a),null}})(),t[e]=n),n}const mt=async(e,s)=>{const t=S.basename(e),n=await qe.call({name:Be,path:M.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=b.createWriteStream(s);await Yt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},gt=async(e,s)=>{await Promise.all(e.map(async t=>{try{await mt(t,S.join(s,S.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function ht(e){return Ge.test(e)?[e]:ae.test(e)?(Xe.lastIndex=0,Array.from(e.matchAll(Xe)).map(t=>t[1]).filter(t=>!!t)):[]}async function ge(e,s,t){const{getFilename:n,exportAssets:o}=t,a=S.join(s,n(e));if(b.mkdirSync(S.dirname(a),{recursive:!0}),b.writeFileSync(a,X.stringify(e)),o){const c=Ee(e,u=>typeof u=="string"&&(Ge.test(u)||ae.test(u))).map(u=>{const l=$e.default(e,u);return ht(l)}).flat().filter(Boolean);await gt(c,S.dirname(a))}}const Ze=new Fe.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function et(e,s,t){var c;const n=Ee(e,u=>typeof u=="string"&&(Ge.test(u)||ae.test(u))),o=us.default(2),a=n.map(u=>o(async()=>{try{const l=$e.default(e,u),d=ht(l);for(const y of d){const h=S.basename(y),r=t.getFilePath(y,u),i=r?`${r}:${h}`:h,f=Ze.get(i);if(f){ae.test(l)||Ye.default(e,u,f);return}const E=await $s(r,h,s);E&&(ae.test(l)||Ye.default(e,u,E),Ze.set(i,E))}}catch(l){I.error(`Failed to process upload for path ${u.join(".")}:`,l.message||l.reason)}})),p=await Promise.allSettled(a);(c=t.onFinish)==null||c.call(t,p)}async function yt(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1,routeIds:p="all"}={}){var ee,w,m,A,j,z,_,q,K,de,te,fe;const c=t==="all"?e.pageIds:t,u=re.getComponentDependencies({state:e,pageIds:c,componentIds:n==="all"?Object.keys(e.components):n}),l=p==="all"?e.routeIds:p,d=(g,P)=>{var D;return{id:g.id,name:g.name,isTemplateSection:g.isTemplateSection??!1,templateDescription:g.templateDescription,llmConfig:g.llmConfig,component:g.component,config:g.config,visibility:g.visibility,properties:((D=g.locales)==null?void 0:D[P])??{}}},y=(g,P)=>{var D;return{id:g.id,createdAt:g.createdAt,updatedAt:g.updatedAt,publishedAt:g.publishedAt,isPublic:g.isPublic??!0,templateConfig:g.templateConfig,meta:((D=g.locales)==null?void 0:D[P])??{},sections:U(g.sectionIds.map(V=>{const G=g.sections[V];return G&&d(G,P)}))}},h=g=>({id:g.id,createdAt:g.createdAt,updatedAt:g.updatedAt,publishedAt:g.publishedAt,path:g.path,handler:g.handler,isPublic:g.isPublic??!0,params:g.params??[],enabledGenerate:g.enabledGenerate??!1,displayTemplateId:g.displayTemplateId,dataSource:g.dataSource}),r=U(l.map(g=>{const P=e.routes[g];return P&&h(P)})),i=U(e.supportedLocales.map(g=>g.locale).flatMap(g=>c.map(P=>{const D=e.pages[P];return D&&{locale:g,slug:D.slug,page:y(D,g)}}))),f=ft(),E=S.join(f,"pages");b.mkdirSync(E,{recursive:!0});const v=S.join(f,"components");b.mkdirSync(v,{recursive:!0});const T=S.join(f,"routes");b.mkdirSync(T,{recursive:!0});for(const{locale:g,slug:P,page:D}of i)await ge(D,E,{getFilename:()=>`${Ie(P)||"index"}.${g}.yml`,exportAssets:s});for(const g of r)await ge(g,T,{getFilename:()=>`${Ie(g.path)||"index"}.yml`,exportAssets:s});for(const g of u){const P=(ee=e.components[g])==null?void 0:ee.data;P&&await ge(P,v,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:s})}const R=S.join(f,".blocklet/pages/pages.config.yml");b.mkdirSync(S.dirname(R),{recursive:!0});const F={pages:U(c.map(g=>{const P=e.pages[g];return P&&{id:g,slug:P.slug}})),routes:U(l.map(g=>{const P=e.routes[g];return P&&{id:g,path:P.path}})),components:U(u.map(g=>{var D;const P=(D=e.components[g])==null?void 0:D.data;return P&&{id:g,name:P.name}})),...a?{resources:{components:U(Object.keys(((w=e.resources)==null?void 0:w.components)||{}).filter(g=>u.includes(g)).map(g=>{var P,D,V,G;return{id:g,name:(G=(V=(D=(P=e.resources)==null?void 0:P.components)==null?void 0:D[g])==null?void 0:V.component)==null?void 0:G.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};b.writeFileSync(R,X.stringify(F));const ue=S.join(f,"config.source.json");if(o&&b.writeFileSync(ue,JSON.stringify(o)),a){const g=S.join(f,"resources"),P=S.join(g,"components");b.mkdirSync(P,{recursive:!0});for(const G of Object.keys(((m=e==null?void 0:e.resources)==null?void 0:m.components)??{}).filter($=>u.includes($))){const $=(z=(j=(A=e.resources)==null?void 0:A.components)==null?void 0:j[G])==null?void 0:z.component;$&&await ge($,P,{getFilename:Y=>`${Y.name||"unnamed"}.${Y.id}.yml`,exportAssets:s})}const D=S.join(f,"chunks");b.mkdirSync(D,{recursive:!0});const{chunks:V}=await Pe();for(const G of Object.keys(((_=e==null?void 0:e.resources)==null?void 0:_.components)??{}).filter($=>u.includes($))){const $=(de=(K=(q=e.resources)==null?void 0:q.components)==null?void 0:K[G])==null?void 0:de.component;if($&&((te=$.renderer)==null?void 0:te.type)==="react-component"){const Y=((fe=$.renderer)==null?void 0:fe.chunks)??[];if((Y==null?void 0:Y.length)>0)for(const je of Y){const Ke=S.join(D,je),_e=V==null?void 0:V[je];try{_e&&b.existsSync(_e)&&!b.existsSync(Ke)&&b.copyFileSync(_e,Ke)}catch(It){I.error(`copy chunk ${je} error`,It.message)}}}}}return f}async function Ve(e,{importAssets:s,includeResources:t}={}){var a,p,c,u;if(!b.existsSync(e))return null;let n,o=!1;try{b.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ft(),await Wt.x({file:e,C:n}));const l=ke.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),d=l&&S.join(S.dirname(l),"../../pages"),y=l&&S.join(S.dirname(l),"../../components"),h=l&&S.join(S.dirname(l),"../../chunks"),r=l&&S.join(S.dirname(l),"../../routes");if(!l)return null;const i=X.parse(b.readFileSync(l).toString()),f=(w,m,A)=>{let j=S.join(w,`${m}${A?`.${A}`:""}.yml`);return(!b.existsSync(j)||!b.lstatSync(j).isFile())&&(j=S.join(w,m,`index${A?`.${A}`:""}.yml`),!b.existsSync(j)||!b.lstatSync(j))?null:X.parse(b.readFileSync(j).toString())},E=(w,m)=>{try{const A=ke.globSync(`*.${m}.yml`,{cwd:w,absolute:!0})[0];return A?X.parse(b.readFileSync(A).toString()):null}catch(A){I.error("parse component error",A)}return null},v=(w,m)=>{let A=S.join(w,`${m}.yml`);return(!b.existsSync(A)||!b.lstatSync(A).isFile())&&(A=S.join(w,m,"index.yml"),!b.existsSync(A)||!b.lstatSync(A))?null:X.parse(b.readFileSync(A).toString())},T=U(i.pages.map(({slug:w})=>{var z;const m=U(i.supportedLocales.map(({locale:_})=>{const q=d?f(d,Ie(w),_):void 0;if(q)return{locale:_,page:q};const K=d?f(d,w,_):void 0;return K&&{locale:_,page:K}})),A=(z=m[0])==null?void 0:z.page;if(!A)return null;const j=A.sections.map(_=>{const q=_.id||ye();return{id:q,component:_.component,config:_.config,name:_.name,isTemplateSection:_.isTemplateSection??!1,templateDescription:_.templateDescription,llmConfig:_.llmConfig,visibility:_.visibility,locales:Object.fromEntries(U(m.map(({locale:K,page:de})=>{const te=de.sections.find(fe=>fe.id===q);return te&&[K,te.properties]})))}});return{id:A.id||ye(),createdAt:A.createdAt,updatedAt:A.updatedAt,publishedAt:A.publishedAt,isPublic:A.isPublic??!0,templateConfig:A.templateConfig,slug:w,sections:Object.fromEntries(j.map(_=>[_.id,_])),sectionIds:j.map(_=>_.id),locales:Object.fromEntries(m.map(({locale:_,page:q})=>[_,q.meta]))}})),R=U(((a=i==null?void 0:i.routes)==null?void 0:a.map(({path:w})=>{const m=r?v(r,Ie(w)):void 0;return{...m,id:(m==null?void 0:m.id)||ye(),createdAt:(m==null?void 0:m.createdAt)??new Date().toISOString(),updatedAt:(m==null?void 0:m.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(m==null?void 0:m.path)??`/${m==null?void 0:m.id}`,params:m==null?void 0:m.params,handler:(m==null?void 0:m.handler)??"Pages Kit",isPublic:(m==null?void 0:m.isPublic)??!0,enabledGenerate:(m==null?void 0:m.enabledGenerate)??!1,displayTemplateId:(m==null?void 0:m.displayTemplateId)??void 0,dataSource:(m==null?void 0:m.dataSource)??{}}}))??[]),F=y?U(((p=i.components)==null?void 0:p.map(({id:w})=>E(y,w)))??[]):[];if(s){const w=(...m)=>{I.info(`[${o?S.basename(e):S.basename(S.join(e,"../../../../"))}] importAssets:`,...m)};try{w("wait image-bin api ready"),await ds.default({resources:[`${qe.getComponentWebEndpoint(ms)}/api/sdk/uploads`],validateStatus:j=>j>=200&&j<=500}),w("image-bin api is ready");const m={},A={};w("start to upload assets"),await Promise.allSettled([et(F,m,{getFilePath:j=>y&&S.join(y,j),onFinish:j=>{w(`upload ${j.length} component assets`)}}),et(T,A,{getFilePath:(j,z)=>{const _=$e.default(T,z.slice(0,1));return d&&S.join(d,S.dirname(_.slug),j)},onFinish:j=>{w(`upload ${j.length} page assets`)}})]),w("upload assets done"),global.gc&&global.gc()}catch(m){w("Error during asset import:",m)}}const ue={};if(t){const w=l&&S.join(S.dirname(l),"../../resources/components"),m=U(((u=(c=i.resources)==null?void 0:c.components)==null?void 0:u.map(({id:A})=>E(w,A)))??[]);m.length>0&&(ue.components=Object.fromEntries(m.map((A,j)=>[A.id,{index:j,component:A}])))}const ee={};if(h&&b.existsSync(h)){const w=b.readdirSync(h);for(const m of w)ee[m]=S.join(h,m)}return{supportedLocales:i.supportedLocales,pageIds:T.map(w=>w.id),components:Object.fromEntries(F.map((w,m)=>[w.id,{index:m,data:w}])),pages:Object.fromEntries(T.map(w=>[w.id,w])),config:i.config||{},resources:ue,chunks:ee,routeIds:R.map(w=>w.id),routes:Object.fromEntries(R.map(w=>[w.id,w])),dataSourceIds:[],dataSources:{}}}finally{o&&n&&b.rmSync(n,{force:!0,recursive:!0})}}async function Ue(e,s,{routes:t,mergeMode:n="byUpdateTime",deleteRoutes:o=!1,publishMode:a=void 0}={}){try{a&&ct(a)}catch(h){I.error("clear preload page cache error",{error:h})}const{pages:p,pageIds:c,routeIds:u,routes:l,supportedLocales:d}=e;if(a==="production"){let h=t??[],r=null;for(const i of u??[]){const f=l==null?void 0:l[i];if(f!=null&&f.params&&(f==null?void 0:f.params.length)>0&&(f!=null&&f.paramsOptions)&&(f==null?void 0:f.paramsOptions.length)>0){const E=we.generateParamCombinations({basePath:f.path,params:f.params,routeId:f.id,paramsOptions:f.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),v=Object.fromEntries(E.map(T=>[`${i}-${T.paramOptionIds.join("-")}`,T]));r={...r||{},...v},t||(h=[...h,...E.map(T=>`${i}-${T.paramOptionIds.join("-")}`)])}else t||h.push(i)}I.info("routeIds to be published: ",h);for(const i of h){let f=i;if(f.includes("-")){const[T]=f.split("-");f=T}const E=l==null?void 0:l[f];if(!E){const T=s.pageIds.indexOf(f);T!==-1&&o&&(s.pageIds.splice(T,1),delete s.pages[f]);for(const R of s.pageIds)R.includes(`${f}-`)&&(s.pageIds.splice(s.pageIds.indexOf(R),1),delete s.pages[R]);I.info("delete main route page",f);continue}if(i.includes("-")&&!(r!=null&&r[i])){const T=s.pageIds.indexOf(i);T!==-1&&o&&(s.pageIds.splice(T,1),delete s.pages[i]),I.info("delete page",i);continue}if(!E.displayTemplateId){I.info("no display template",i);continue}const v=p[E.displayTemplateId];if(!v){I.info("no template page",i);continue}if(s.pageIds.includes(i)){if(I.info("has need update page",i),n==="replace")s.pages[i]=ve({page:v,route:E,state:e,routeId:i,routePathInfo:r==null?void 0:r[i]}),I.info("replace page",i);else if(n==="byUpdateTime"){const T=s.pages[E.id];(!T||E.updatedAt&&E.updatedAt>T.updatedAt)&&(s.pages[i]=ve({page:v,route:E,state:e,routeId:i,routePathInfo:r==null?void 0:r[i]}),I.info("replace page by update time",i))}}else s.pageIds.push(i),s.pages[i]=ve({page:v,route:E,state:e,routeId:i,routePathInfo:r==null?void 0:r[i]}),I.info("add page",i)}if(o&&!t)for(const i of s.pageIds)h!=null&&h.includes(i)||(delete s.pages[i],I.info("delete page",i)),s.pageIds=[...s.pageIds].filter(f=>h==null?void 0:h.includes(f))}else{for(const h of c){const r=p[h];if(r)if(s.pageIds.includes(r.id)){if(n==="replace")s.pages[r.id]=r;else if(n==="byUpdateTime"){const i=s.pages[r.id];(!i||r.updatedAt&&r.updatedAt>i.updatedAt)&&(s.pages[r.id]=r)}}else s.pageIds.push(r.id),s.pages[r.id]=r}for(const h of u){const r=l[h];if(r)if(s.pageIds.includes(r.id)){if(n==="replace")s.routes[r.id]=r;else if(n==="byUpdateTime"){const i=s.routes[r.id];(!i||r.updatedAt&&r.updatedAt>i.updatedAt)&&(s.routes[r.id]=r)}}else s.routeIds.push(r.id),s.routes[r.id]=r}}if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...is.default(d)),o)for(const h of Object.keys(s.components))delete s.components[h];let y=JSON.parse(JSON.stringify(e.components));y=Object.fromEntries(await Promise.all(Object.entries(y).map(async([h,r])=>{const i=await St(r==null?void 0:r.data);return[h,{...r,data:i}]}))),Object.assign(s.components,y),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const St=Q.memoize(async e=>{var s;if(!cs.default(e==null?void 0:e.properties))return e;if(((s=e==null?void 0:e.renderer)==null?void 0:s.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t&&t.includes("PROPERTIES_SCHEMA"))try{const n=await dt(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(n){I.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var p;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((p=e==null?void 0:e.renderer)==null?void 0:p.type)||"",o=(e==null?void 0:e.properties)||{},a=Ae.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",s,t,n,a])},lruOptions:{max:100,ttl:1e3*60*60}});let Oe,Z,He,Je,ze;function wt(){return Oe=(async()=>{const e=qe.getResources({types:[{did:Be,type:Re},{did:Cs,type:Re}]});Z=(await Promise.all(e.map(async t=>{const n=t.path?await Ve(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),He=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:n.blockletId}]:[]))),{});const s=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Je=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await St(n.component);return[t,{...n,component:o}]}))),ze=Z.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),Oe}function bt(e){const s=ot.default(async()=>{await wt().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:Z,pages:He,components:Je,chunks:ze}))},3e3,{leading:!1,trailing:!0});return s(),O.default.events.on(O.default.Events.componentAdded,s),O.default.events.on(O.default.Events.componentRemoved,s),O.default.events.on(O.default.Events.componentStarted,s),O.default.events.on(O.default.Events.componentStopped,s),O.default.events.on(O.default.Events.componentUpdated,s),O.default.events.on(Le,s),()=>{O.default.events.off(O.default.Events.componentAdded,s),O.default.events.off(O.default.Events.componentRemoved,s),O.default.events.off(O.default.Events.componentStarted,s),O.default.events.off(O.default.Events.componentStopped,s),O.default.events.off(O.default.Events.componentUpdated,s),O.default.events.off(Le,s)}}const Et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),Se=globalThis;var tt;(tt=Se[Et])==null||tt.call(Se);Se[Et]=bt(async({pages:e,components:s})=>{const{projectIds:t}=ce;I.info(`start update resource states projects(${t.length})`,t),await Promise.race([new Promise(n=>{setTimeout(()=>{n({})},30*1e3)}),Promise.all(t.map(async n=>{const o=ce.shared(n);o.syncedStore.resources.pages=e;const a=await J.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const c=(await Te.findAll({where:{projectId:n}})).map(l=>l.componentId),u=Object.fromEntries(Object.entries(s||{}).filter(([l])=>c.includes(l)));o.syncedStore.resources.components=u}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(n=>{I.error("update resource states failed:",n)})});async function Bs(){I.info("trigger reload all project resource"),O.default.events.emit(Le)}async function Pe({ensureLoaded:e=!0}={}){return e&&(Oe??(Oe=wt()),await Oe),{states:Z,pages:He,components:Je,chunks:ze}}exports.COMPONENT_DID=Be;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=rt;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ne;exports.PUBLISH_MODES=Fs;exports.Project=J;exports.RESOURCE_TYPE=Re;exports.SITE_STATE_PATH=ne;exports.STATE_MODES=Us;exports.SiteState=ce;exports.clearPreloadComponentsCache=it;exports.clearPreloadComponentsCacheByMode=ct;exports.downloadAsset=mt;exports.downloadAssets=gt;exports.fromPackage=Ve;exports.getComponentFromState=ie;exports.getComponentFromStateByName=Ps;exports.getExportSchemaValueFromCode=dt;exports.getMultiTenantAllProjectAccessPassports=ys;exports.getPreloadComponent=pt;exports.getPreloadComponents=Os;exports.getPreloadComponentsCacheKey=lt;exports.getResourceStates=Pe;exports.initPackResourceStates=bt;exports.isMultiTenant=hs;exports.logger=I;exports.mergeState=Ue;exports.nextId=ye;exports.toPackage=yt;exports.triggerReloadAllProjectResource=Bs;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const _=require("react/jsx-runtime"),T=require("@mui/material"),b=require("ufo"),Z=require("@blocklet/js-sdk"),H=require("lodash/isEmpty"),ee=require("yaml"),te=require("@arcblock/ux/lib/Locale/context"),N=require("@syncedstore/core"),ne=require("@syncedstore/react"),oe=require("ahooks"),C=require("immer"),re=require("js-cookie"),se=require("lodash/debounce"),ce=require("nanoid"),d=require("react"),V=require("react-router-dom"),ie=require("y-indexeddb"),ae=require("y-websocket"),de=require("yjs");require("@blocklet/pages-kit/types");const E=t=>t&&t.__esModule?t:{default:t};function ue(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const i in t)if(i!=="default"){const S=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,S.get?S:{enumerable:!0,get:()=>t[i]})}}return n.default=t,Object.freeze(n)}const le=E(H),fe=ue(ee),me=E(N),Se=E(re),W=E(se),we=t=>{const n=blocklet==null?void 0:blocklet.componentMountPoints.find(i=>i.name===t);return n?n.mountPoint:"/"};function z(){const{pathname:t}=window.location,n=t.match(/\/admin\/(maker|previewer)\/([^/]+)/),i=n==null?void 0:n[2],S=window.__PROJECT_ID__;if(!i&&!S)throw new Error("Unable to get projectId from pathname");return i||S}function pe(t){return`${t}:pages:version`}function Pe(t,n){return n==="yaml"?le.default(t)?"":fe.stringify(t,{indent:2}):n==="json"?JSON.parse(JSON.stringify(t||{})):n==="array"?JSON.parse(JSON.stringify(t||[])):t}function Ie({error:t}){return _.jsx(T.Box,{children:_.jsx(T.Alert,{severity:"error",children:t.message})})}var G;const k=((G=window.blocklet)==null?void 0:G.prefix)||"/",L=Z.createAxios({timeout:200*1e3}),ge=window.location.protocol==="https:"?"wss":"ws",je=t=>b.joinURL(`${ge}://${window.location.hostname}`,k,`api/${t}/ws/pages`),ye="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var F;(F=blocklet==null?void 0:blocklet.componentMountPoints.find(t=>t.did===ye))!=null&&F.mountPoint||b.joinURL(k,"/image-bin");function Ce(t){return t&&!/^(https?:\/\/|\/)/.test(t)?window.location.origin+b.joinURL(k,"uploads",t):t}const be=window.innerWidth<=750;function he(t,n,i){if(!t||/\.gif/.test(t))return t;const S=(be?n/1.5:n)*(i==="quality"?1.5:1);return ve(t,{imageFilter:"resize",w:S,f:"webp"})}function ve(t,n){return!t||!n?t:b.withQuery(t,n)}async function xe(t){return L.get(`/api/projects/${t}`).then(n=>n.data)}async function Oe(t){return L.post(`/api/projects/${t.id}/update`,t).then(n=>n.data)}const Ee=500,x=ce.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),J=d.createContext(null);function _e({url:t,name:n,children:i,waitingSynced:S}){const[g,P]=d.useState(!1),{locale:j}=te.useLocaleContext(),w=R(),e=`${w}:MakerLocalState`,o=`${w}:${n}`,[s,r]=oe.useLocalStorageState(e,{defaultValue:{},listenStorageChange:!0}),c=d.useRef(s);c.current=s;const a=d.useMemo(()=>me.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),u=d.useMemo(()=>N.getYjsDoc(a),[a]);d.useMemo(()=>new ie.IndexeddbPersistence(o,u),[o,u]);const p=d.useMemo(()=>new ae.WebsocketProvider(t,o,u,{params:{token:Se.default.get("login_token")},resyncInterval:5*60*1e3}),[t,o,u]),h=d.useCallback(()=>{p&&(p.disconnect(),p.connect())},[p]),y=d.useMemo(()=>new de.UndoManager([u.getArray("pageIds"),u.getMap("pages"),u.getArray("supportedLocales"),u.getMap("config")],{doc:u}),[u]),[v,O]=d.useState(null),[A,M]=d.useState(!1),[q,D]=d.useState(void 0),U=d.useCallback(async()=>{if(w){M(!0);try{const l=await xe(w);O(l)}catch(l){console.error("Failed to fetch project:",l)}finally{M(!1)}}},[w]),$=d.useCallback(async(l,f)=>{var I;if(D(void 0),!!w){f!=null&&f.optimisticUpdate&&v&&O(m=>({...m,...l}));try{const m=await Oe({...l});O(m)}catch(m){console.error("Failed to update project:",m),f!=null&&f.optimisticUpdate&&O(v),D((I=m==null?void 0:m.response)==null?void 0:I.data)}}},[w,v]);d.useEffect(()=>{w&&U()},[w,U]);const Y=d.useMemo(()=>({doc:u,state:a,localState:{...s,currentLocale:j},setLocalState:l=>r(typeof l=="function"?f=>l(f??{}):l),undoManager:y,projectState:{project:v,isLoadingProject:A,error:q},updateProject:$,forceSync:h}),[u,a,JSON.stringify(s),r,y,v,A,$,q,j,h]);return d.useEffect(()=>{y.on("stack-item-added",({stackItem:l})=>{const{currentPageId:f,currentLocale:I,pages:m}=c.current;l.meta.set("localState",{currentPageId:f,currentLocale:I,pages:m})}),y.on("stack-item-popped",({stackItem:l})=>{const f=l.meta.get("localState");f&&r(I=>({...I,...f}))})},[y,r]),d.useEffect(()=>{p.awareness.setLocalState(s)},[p,s]),d.useEffect(()=>{p.once("synced",()=>P(!0));const l=()=>{r(m=>({...m,networkStatus:void 0}))},f=()=>{r(m=>({...m,networkStatus:"offline"}))},I=W.default(({status:m})=>{m==="connected"?l():m==="disconnected"&&f()},Ee);return p.on("status",I),window.addEventListener("online",l),window.addEventListener("offline",f),()=>{p.off("status",I),window.removeEventListener("online",l),window.removeEventListener("offline",f)}},[p,r]),S&&!g?null:_.jsx(J.Provider,{value:Y,children:i})}const B=()=>{const t=d.useContext(J);if(!t)throw new Error("Context is null");const n=ne.useSyncedStore(t.state),{setLocalState:i,localState:S}=t,g=V.useNavigate(),P=R(),j=d.useMemo(()=>({setCurrentSectionId:(e,o)=>{var s,r;e===S.currentPageId&&o===((r=(s=S.pages)==null?void 0:s[e])==null?void 0:r.currentSectionId)||(g(b.joinURL("/admin/maker",P??"","pages",e)),i(c=>C.produce(c,a=>{var u;a.currentPageId=e,a.currentComponentId=void 0,a.customComponentPreviewerProperties={},o!==void 0&&(a.pages??(a.pages={}),(u=a.pages)[e]??(u[e]={}),a.pages[e].currentSectionId=o??void 0),o?window.sessionStorage.setItem("iframe_show_id",`"${o}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{e!==S.currentComponentId&&(g(b.joinURL("/admin/maker",P??"","components",e)),i(o=>C.produce(o,s=>{s.currentComponentId=e,s.customComponentPreviewerProperties={}})))},setCurrentRouteId:({routeId:e,dynamicParams:o})=>{i(s=>C.produce(s,r=>{r.currentRouteId=e,r.currentDynamicParams=o}))},setCustomComponentPreviewerProperties:(()=>{const e={},o=W.default(()=>{i(s=>C.produce(s,r=>{r.customComponentPreviewerProperties={...r==null?void 0:r.customComponentPreviewerProperties,...e},Object.keys(e).forEach(c=>delete e[c])}))},5);return s=>{Object.assign(e,s),o()}})(),setRouteGenerateProcess:e=>{i(o=>C.produce(o,s=>{e?s.routeGenerateProcess={...s.routeGenerateProcess,...e}:s.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{i(e=>C.produce(e,o=>{o.routeGenerateProcess={progress:"complete"}}))}}),[i,g,P]),w=d.useMemo(()=>({addPage:(e,o)=>{var c,a,u,p,h,y;const s=(e==null?void 0:e.id)??x(),r={...e,id:s,createdAt:(e==null?void 0:e.createdAt)??new Date().toISOString(),updatedAt:(e==null?void 0:e.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:(e==null?void 0:e.slug)??`/${s}`,sections:(e==null?void 0:e.sections)??{},sectionIds:(e==null?void 0:e.sectionIds)??[],isPublic:(e==null?void 0:e.isPublic)??!0,templateConfig:(e==null?void 0:e.templateConfig)??{isTemplate:((c=e==null?void 0:e.templateConfig)==null?void 0:c.isTemplate)??!0,displayTemplateId:((a=e==null?void 0:e.templateConfig)==null?void 0:a.displayTemplateId)??void 0,dataSourceIds:((u=e==null?void 0:e.templateConfig)==null?void 0:u.dataSourceIds)??void 0,dataSourceParameters:((p=e==null?void 0:e.templateConfig)==null?void 0:p.dataSourceParameters)??{},enabledGenerate:((h=e==null?void 0:e.templateConfig)==null?void 0:h.enabledGenerate)??!1,agentId:((y=e==null?void 0:e.templateConfig)==null?void 0:y.agentId)??void 0}};return t.doc.transact(()=>{n.pages[r.id]=r,n.pageIds.splice(o??n.pageIds.length,0,r.id)}),r},addRoute:(e,o)=>{const s=(e==null?void 0:e.id)??x(),r={...e,id:s,createdAt:(e==null?void 0:e.createdAt)??new Date().toISOString(),updatedAt:(e==null?void 0:e.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(e==null?void 0:e.path)??`/${s}`,handler:(e==null?void 0:e.handler)??"Pages Kit",isPublic:(e==null?void 0:e.isPublic)??!0,params:(e==null?void 0:e.params)??[],enabledGenerate:(e==null?void 0:e.enabledGenerate)??!1,displayTemplateId:(e==null?void 0:e.displayTemplateId)??void 0,dataSource:(e==null?void 0:e.dataSource)??{}};return t.doc.transact(()=>{n.routes??(n.routes={}),n.routeIds??(n.routeIds=[]),n.routes[r.id]=r,n.routeIds.splice(o??n.routeIds.length,0,r.id)}),r},deleteRoute:e=>{var s;if(!e)return;const o=(s=n.routeIds)==null?void 0:s.indexOf(e);o!==void 0&&o!==-1&&t.doc.transact(()=>{var r,c;(r=n.routeIds)==null||r.splice(o,1),(c=n.routes)==null||delete c[e]})},deletePage:e=>{const o=n.pageIds.indexOf(e);o!==-1&&t.doc.transact(()=>{n.pageIds.splice(o,1),delete n.pages[e]})},movePage:(e,o)=>{const{pageIds:s}=n,r=s.indexOf(e);r>=0&&s.splice(o,0,...s.splice(r,1))},addSection:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const c={...o,id:o.id??x(),isTemplateSection:o.isTemplateSection??!0,llmConfig:o.llmConfig??{}};return t.doc.transact(()=>{r.sections[c.id]=c,r.sectionIds.splice(s??r.sectionIds.length,0,c.id)}),c},deleteSection:(e,o)=>{const s=n.pages[e];if(!s)throw new Error(`Page ${e} is not exists`);const r=s.sectionIds.indexOf(o);r!==-1&&t.doc.transact(()=>{s.sectionIds.splice(r,1),delete s.sections[o]})},toggleSectionVisibility:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const c=r.sections[o];c&&(c.visibility=s)},moveSection:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const{sectionIds:c}=r,a=c.indexOf(o);a>=0&&c.splice(s,0,...c.splice(a,1))},addDataSource:e=>{const o=e.id??x(),s={...e??{},id:o,createdAt:new Date().toISOString()};return t.doc.transact(()=>{n.dataSourceIds??(n.dataSourceIds=[]),n.dataSources??(n.dataSources={}),n.dataSourceIds.push(o),n.dataSources[o]=s}),n.dataSources[o]},deleteDataSource:e=>{const o=n.dataSourceIds.indexOf(e);o!==-1&&t.doc.transact(()=>{n.dataSourceIds.splice(o,1),delete n.dataSources[e]})}}),[n,t.doc]);return{...t,state:n,actions:w,localActions:j,get currentPage(){const{localState:{currentPageId:e}}=t;return e?n.pages[e]:void 0},get currentSection(){var r,c,a;const{localState:{currentPageId:e,...o}}=t;if(!e)return;const s=(c=(r=o.pages)==null?void 0:r[e])==null?void 0:c.currentSectionId;if(s)return(a=n.pages[e])==null?void 0:a.sections[s]},get currentRoute(){var o;const{localState:{currentRouteId:e}}=t;return e?(o=n.routes)==null?void 0:o[e]:void 0}}},R=()=>{const{projectId:t}=V.useParams();return t??z()??""};function K(t){var S,g;const{resources:n}=t;if(!n.components)return{};const i={};return(g=(S=window==null?void 0:window.blocklet)==null?void 0:S.componentMountPoints)==null||g.forEach(P=>{i[P.did]=P}),Object.fromEntries(Object.entries(n.components).map(([P,{blockletId:j,component:w}])=>{var e;return[P,{data:w,blockletId:j,blockletTitle:((e=i[j])==null?void 0:e.title)||j}]}))}function Q(t){const{components:n}=t;return n||{}}function X(t){return{...K(t),...Q(t)}}const ke=()=>X(B().state);exports.ErrorView=Ie;exports.StoreProvider=_e;exports.api=L;exports.autoResizeImage=he;exports.getAllComponents=X;exports.getCustomComponents=Q;exports.getImageAbsoluteUrl=Ce;exports.getMountPoint=we;exports.getProjectIdFromPathnameOrWindow=z;exports.getProjectPageVersionKey=pe;exports.getResourceComponents=K;exports.getWssURL=je;exports.nextId=x;exports.transformValue=Pe;exports.useAllComponents=ke;exports.useProjectId=R;exports.useStore=B;
|
package/lib/cjs/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("@blocklet/pages-kit/builtin/utils");require("@blocklet/pages-kit/types");require("@blocklet/pages-kit/utils/property");require("@blocklet/quickjs");require("@blocklet/sdk/lib/config");require("lru-cache");require("node-fetch");require("ufo");require("crypto");const e=require("./chunks/site-state-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("@blocklet/pages-kit/builtin/utils");require("@blocklet/pages-kit/types");require("@blocklet/pages-kit/utils/property");require("@blocklet/quickjs");require("@blocklet/sdk/lib/config");require("lru-cache");require("node-fetch");require("ufo");require("crypto");const e=require("./chunks/site-state-Cio9RMaq.js");exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=e.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=e.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS;exports.clearPreloadComponentsCache=e.clearPreloadComponentsCache;exports.clearPreloadComponentsCacheByMode=e.clearPreloadComponentsCacheByMode;exports.getComponentFromState=e.getComponentFromState;exports.getComponentFromStateByName=e.getComponentFromStateByName;exports.getExportSchemaValueFromCode=e.getExportSchemaValueFromCode;exports.getPreloadComponent=e.getPreloadComponent;exports.getPreloadComponents=e.getPreloadComponents;exports.getPreloadComponentsCacheKey=e.getPreloadComponentsCacheKey;
|
package/lib/cjs/home.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("react/jsx-runtime");require("./chunks/state-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("react/jsx-runtime");require("./chunks/state-D4MG-uJB.js");require("@arcblock/ux/lib/Locale/context");require("@arcblock/ux/lib/Result");require("@blocklet/pages-kit/builtin/page/header");require("@blocklet/pages-kit/contexts/color");require("@blocklet/pages-kit/utils/data-source");require("@blocklet/pages-kit/utils/route");require("@blocklet/ui-react/lib/Header");require("@emotion/css");require("@emotion/react");require("@emotion/styled");require("@mui/material");require("ahooks");require("isomorphic-dompurify");require("lodash/cloneDeep");require("lodash/isEmpty");require("lodash/isEqual");require("react");require("react-helmet");require("react-router-dom");require("react-use");require("ufo");require("./chunks/array-6wh7d5gC.js");const e=require("./chunks/home-B5XHNRCN.js");exports.HomeView=e.HomeView;exports.PageRoutes=e.PageRoutes;exports.PageView=e.PageView;exports.PageViewByPath=e.PageViewByPath;exports.PageViewWithDataSource=e.PageViewWithDataSource;exports.TranslucentHeader=e.TranslucentHeader;exports.default=e.Home;
|
package/lib/cjs/project-html.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const z=require("@arcblock/did-auth-storage-nedb"),D=require("@blocklet/sdk/lib/config"),G=require("@blocklet/sdk/lib/service/auth"),K=require("@blocklet/sdk/lib/wallet"),Q=require("@blocklet/sdk/lib/wallet-authenticator"),V=require("@blocklet/sdk/lib/wallet-handler"),P=require("path"),S=require("./chunks/site-state-
|
|
1
|
+
"use strict";const z=require("@arcblock/did-auth-storage-nedb"),D=require("@blocklet/sdk/lib/config"),G=require("@blocklet/sdk/lib/service/auth"),K=require("@blocklet/sdk/lib/wallet"),Q=require("@blocklet/sdk/lib/wallet-authenticator"),V=require("@blocklet/sdk/lib/wallet-handler"),P=require("path"),S=require("./chunks/site-state-Cio9RMaq.js"),A=require("@blocklet/crawler/middlewares"),X=require("@blocklet/pages-kit/types"),Y=require("@blocklet/pages-kit/utils/common"),Z=require("@blocklet/pages-kit/utils/preload"),F=require("@blocklet/sdk/lib/component"),ee=require("cheerio/slim"),te=require("express"),E=require("fs"),oe=require("lodash/get"),ne=require("mustache"),I=require("ufo"),u=o=>o&&o.__esModule?o:{default:o};function le(o){if(o&&o.__esModule)return o;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const e in o)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>o[e]})}}return t.default=o,Object.freeze(t)}const re=u(z),i=u(D),ce=u(G),se=u(K),ae=u(Q),ie=u(V),ue=u(P),L=le(ee),de=u(oe),pe=u(ne),fe=(o={})=>{const t={data:new Map,timers:new Map,set:(e,a,_=o.ttl||36e5)=>{o.max&&t.data.size>=o.max&&t.delete(t.data.keys().next().value),t.timers.has(e)&&clearTimeout(t.timers.get(e)),t.timers.set(e,setTimeout(()=>t.delete(e),_)),t.data.set(e,a)},get:e=>t.data.get(e),has:e=>t.data.has(e),delete:e=>(t.timers.has(e)&&clearTimeout(t.timers.get(e)),t.timers.delete(e),t.data.delete(e)),clear:()=>{t.data.clear();for(const e of t.timers.values())clearTimeout(e);t.timers.clear()}};return t},O=fe({max:1,ttl:1e3*30});se.default();const he=new ae.default;new ie.default({authenticator:he,tokenStorage:new re.default({dbPath:ue.default.join(i.default.env.dataDir,"auth.db")})});const me=new ce.default,ge=async()=>{try{const o=O.get("blockletInfo");if(o)return o;const{blocklet:t}=await me.getBlocklet();return O.set("blockletInfo",t),t}catch{return null}},we=["/assets/"],U=()=>[!0,"true"].includes(i.default.env.preferences.allowCrawler);function B(){U()?A.initCronCrawlBlocklet({time:"0 0 */12 * * *",options:{}}):A.cancelCronCrawlBlocklet()}B();i.default.events.on(i.default.Events.envUpdate,B);function _e({app:o,viteDevServer:t,state:e}){let a;if(t){const n=E.readFileSync(P.resolve(process.cwd(),"./index.html"),"utf-8");o.use(async(b,v,T)=>{const q=b.originalUrl;a=await t.transformIndexHtml(q,n),T()})}else a=E.readFileSync(P.resolve(process.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const _=te.Router();_.use((n,b,v)=>{if(n.headers["x-unique-record"]==="dial_http"){S.logger.info("[html] dial http request, return 200 status code"),b.status(200).send("ok");return}v()},A.initSEOMiddleware({autoReturnHtml:!0,allowCrawler:U})),_.get("/:path(*)?",async(n,b,v)=>{var M,$,W;if(we.some(c=>{var p;return(p=n.path)==null?void 0:p.startsWith(c)})){v();return}const T=performance.now(),q=()=>Math.round(performance.now()-T),H="production";let r,h,C=a;if(n.path.startsWith("/pages")){const c=n.params.lang,p=n.cookies.nf_lang,k=new Set([...i.default.env.languages.map(w=>w.code)]);let g=(c&&k.has(c)?c:void 0)||(k.has(p)?p:void 0)||[...k][0];if((!g||!((M=e.supportedLocales)!=null&&M.find(w=>w.locale===g)))&&(g=((W=($=e.supportedLocales)==null?void 0:$[0])==null?void 0:W.locale)||""),g){const w=[];Object.values(e.pages).forEach(s=>{const J=Object.values((s==null?void 0:s.sections)??{}).filter(f=>{var y;return f.component==="custom-component"&&((y=f.config)==null?void 0:y.componentId)}).map(f=>{var y,x;return{id:f.id,componentId:f.config.componentId,useCache:f.config.useCache,cacheDuration:f.config.cacheDuration,properties:(x=(y=f.locales)==null?void 0:y[g])==null?void 0:x.properties}});w.push(...J)});const N=new Promise(s=>{setTimeout(()=>{s({})},90*1e3)});try{await Promise.race([N,S.getPreloadComponents({mode:H,req:n,state:e,locale:g,instances:w,module:X.PreloadComponentScriptModule.UMD_FN}).then(s=>{s&&(h=Z.injectPreloadComponents(s))})])}catch(s){S.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements",s)}}}try{const c=(r==null?void 0:r.title)||i.default.env.appName,p=(r==null?void 0:r.description)||i.default.env.appDescription,k=I.withQuery(I.joinURL(i.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:c,description:p});C=pe.default.render(a,{ogTitle:c,ogDescription:p,ogImage:be(r==null?void 0:r.image)||k,pagesPublishedAt:(e==null?void 0:e.config.publishedAt)||new Date().getTime()})}catch{}const l=e==null?void 0:e.config.fontFamily,R=n.query.mode==="draft"||n.url.includes("preview"),m=L.load(C);let d=r==null?void 0:r.backgroundColor;if(d&&Y.isMuiColorKey(d)){const c=await ge();d=de.default(c,`settings.theme.light.palette.${d}`,d)}m("head").find("#injected-head-elements").replaceWith(`
|
|
2
2
|
${d?`<meta name="theme-color" content="${d}" /><style>html,body,#app {background-color: ${d};}</style>`:""}
|
|
3
3
|
${l!=null&&l.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${l.title}&display=swap">`:""}
|
|
4
4
|
${l!=null&&l.description&&(l==null?void 0:l.description)!==(l==null?void 0:l.title)?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${l.description}&display=swap">`:""}
|
package/lib/cjs/resources.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const c=require("./chunks/site-state-
|
|
1
|
+
"use strict";const c=require("./chunks/site-state-Cio9RMaq.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),X=require("lodash/groupBy"),W=require("lodash/sortBy"),b=require("path"),$=require("@blocklet/sdk/lib/middlewares/auth"),G=require("@blocklet/sdk/lib/component"),y=t=>t&&t.__esModule?t:{default:t},l=y(F),I=y(J),D=y(X),K=y(W),k=y(b),v=y($);new M.AsyncLocalStorage;const Y=async(t,e,o)=>{var n,s,r,i;try{const{projectId:u}=t.params;if(!u)return o();const f=await c.Project.findByPk(u);if(!f)return e==null?void 0:e.status(404).json({error:"Project not found"});const _=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!_)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===_,a=(i=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:i.call(r,h);if(!w&&!a)return e==null?void 0:e.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(h))return e==null?void 0:e.status(403).json({error:"No permission to access this project in single-tenant mode"});t.project=f,t.projectId=u,o()}catch(u){c.logger.error("Project middleware error:",u),e==null||e.status(500).json({error:"Internal server error"})}};function N(t,e){return new Promise((o,n)=>{const s=l.default.createReadStream(t),r=l.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await l.default.promises.mkdir(e,{recursive:!0});const o=await l.default.promises.readdir(t,{withFileTypes:!0});for(const n of o){const s=k.default.join(t,n.name),r=k.default.join(e,n.name);n.isDirectory()?await T(s,r):await N(s,r)}}async function z(t,e){(await l.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const O=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),H=(t,e)=>{const o=G.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",P=":",E="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(P),Q=t=>{const[e,o,n]=t.split(P);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(P),V=t=>{const[e,o,n]=t.split(P);if(e===q)return{componentId:n,projectId:o}},Z=t=>[L,t].join(P),tt=t=>{const[e,o]=t.split(P);if(e===L)return o},et=t=>{try{return JSON.parse(t)}catch{}return{}};async function x(t){const e=await c.SiteState.shared(t).getState("production"),o=await c.Project.findByPk(t),n=e.pageIds.map(r=>{const i=e.pages[r];if(i)return{id:C({pageId:r,projectId:t}),name:i.slug}}).filter(Boolean),s=K.default(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:Z(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:E,projectId:t}),name:"Pages",children:n},{id:A({componentId:E,projectId:t}),name:"Components",children:s}]}}S.get("/resources",O,async(t,e)=>{const{projectId:o}=et(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await Y(t,e,()=>{});const r=await x(o);e.json({resources:[r]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(r=>x(r.id)));e.json({resources:s})});const ot=I.default.object({projectId:I.default.string().required().min(1),releaseId:I.default.string().allow(""),resources:I.default.array().items(I.default.string()).required(),locale:I.default.string().allow("")});S.post("/resources",O,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await ot.validateAsync(t.body),r="production",i=[],u=[];for(const a of o){if(tt(a))continue;const{pageId:m,projectId:j}=Q(a)||{};if(m)m===E||m&&j&&i.push({pageId:m,projectId:j});else{const{componentId:p,projectId:d}=V(a)||{};p===E||p&&d&&u.push({componentId:p,projectId:d})}}const f=D.default(i,"projectId"),_=D.default(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(_)]),w=H(n,s);l.default.rmSync(w,{recursive:!0,force:!0}),l.default.mkdirSync(w,{recursive:!0});for(const a of h){const m=await c.SiteState.shared(a).getState(r),j=f[a],p=_[a],d=j==null?void 0:j.map(g=>g.pageId),R=p==null?void 0:p.map(g=>g.componentId);if(d!=null&&d.length||R!=null&&R.length){const g=await c.toPackage(m,{exportAssets:!0,pageIds:d,componentIds:R});await z(g,w),l.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${a}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",O,async(t,e)=>{const{states:o}=await c.getResourceStates(),n=o==null?void 0:o.map(s=>{const r={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(r.components=s.state.components),Object.keys(r.components).length!==0)return r}).filter(Boolean);e.json(n)});module.exports=S;
|