@blocklet/pages-kit-inner-components 0.4.24 → 0.4.25

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.
@@ -1,4 +1,4 @@
1
- "use strict";const st=require("vite-plugin-node-polyfills/shims/process"),nt=require("vite-plugin-node-polyfills/shims/global"),ot=require("@blocklet/pages-kit/builtin/utils"),te=require("@blocklet/pages-kit/types"),ne=require("@blocklet/pages-kit/utils/property"),$=require("@blocklet/quickjs"),rt=require("@blocklet/sdk/lib/config"),Te=require("lru-cache"),Me=require("node-fetch"),v=require("ufo"),ie=require("crypto"),at=require("@blocklet/logger"),it=require("vite-plugin-node-polyfills/shims/buffer"),ct=require("@blocklet/pages-kit/utils/builtin"),me=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),ce=require("@blocklet/sdk/lib/component"),lt=require("autoprefixer"),ut=require("esbuild"),E=require("fs"),pt=require("postcss"),dt=require("tailwindcss"),ft=require("typescript"),mt=require("@reactivedata/reactive"),Z=require("@syncedstore/core"),ge=require("glob"),gt=require("lib0/decoding"),ht=require("lib0/encoding"),R=require("lodash"),yt=require("nanoid"),St=require("p-limit"),m=require("path"),wt=require("stream/promises"),Et=require("tar"),bt=require("wait-on"),G=require("y-protocols/awareness"),ue=require("y-protocols/sync"),Tt=require("yaml"),Ot=require("yjs"),Ct=require("lodash/isNil"),j=require("sequelize");require("sqlite3");const x=e=>e&&e.__esModule?e:{default:e};function Q(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 oe=x(st),xe=x(nt),w=x(rt),jt=x(Me),It=x(at),Pt=x(it),At=x(lt),_t=Q(ut),vt=x(pt),xt=x(dt),D=x(ft),pe=Q(gt),A=Q(ht),Dt=x(St),kt=x(m),Rt=x(bt),J=Q(Tt),B=Q(Ot),Nt=x(Ct);w.default.env.mode;const Lt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Ut=oe.default.env.DATABASE_URL||kt.default.join(w.default.env.dataDir,"db/pages-kit.db"),De=w.default,Mt=()=>w.default.env.tenantMode==="multiple",Ft=()=>{var e;return(Nt.default(De.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=De.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},I=It.default("pages-kit"),qt=j.DataTypes.sqlite.DATE.parse;j.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):qt(e,s);const X=new j.Sequelize({dialect:"sqlite",storage:Ut,benchmark:oe.default.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:oe.default.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});X.query("pragma journal_mode = WAL;");X.query("pragma synchronous = normal;");X.query("pragma journal_size_limit = 67108864;");class le extends j.Model{}le.init({id:{type:j.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:j.DataTypes.UUIDV4},projectId:{type:j.DataTypes.UUID,allowNull:!1},componentId:{type:j.DataTypes.STRING,allowNull:!1}},{sequelize:X,tableName:"ProjectComponents",timestamps:!1});class q extends j.Model{static async getProjectByIdOrSlug(s){return q.findOne({where:{[j.Op.or]:[{id:s},{slug:s}]}})}}q.init({id:{type:j.DataTypes.UUID,defaultValue:j.DataTypes.UUIDV4,primaryKey:!0},name:{type:j.DataTypes.STRING,allowNull:!1},description:j.DataTypes.TEXT,createdAt:j.DataTypes.DATE,updatedAt:j.DataTypes.DATE,createdBy:{type:j.DataTypes.STRING,allowNull:!1},updatedBy:{type:j.DataTypes.STRING,allowNull:!1},slug:j.DataTypes.STRING,icon:j.DataTypes.STRING,pinnedAt:j.DataTypes.DATE,useAllResources:j.DataTypes.BOOLEAN,relatedBlocklets:{type:j.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:X,paranoid:!0});q.hasMany(le,{foreignKey:"projectId",as:"components"});const $t=async(e,{componentId:s})=>{const t=`@tailwind components;
1
+ "use strict";const st=require("vite-plugin-node-polyfills/shims/process"),nt=require("vite-plugin-node-polyfills/shims/global"),ot=require("@blocklet/pages-kit/builtin/utils"),te=require("@blocklet/pages-kit/types"),ne=require("@blocklet/pages-kit/utils/property"),$=require("@blocklet/quickjs"),rt=require("@blocklet/sdk/lib/config"),Te=require("lru-cache"),Me=require("node-fetch"),v=require("ufo"),ie=require("crypto"),at=require("@blocklet/logger"),it=require("vite-plugin-node-polyfills/shims/buffer"),ct=require("@blocklet/pages-kit/utils/builtin"),me=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),ce=require("@blocklet/sdk/lib/component"),lt=require("autoprefixer"),ut=require("esbuild"),E=require("fs"),pt=require("postcss"),dt=require("tailwindcss"),ft=require("typescript"),mt=require("@reactivedata/reactive"),Z=require("@syncedstore/core"),ge=require("glob"),gt=require("lib0/decoding"),ht=require("lib0/encoding"),R=require("lodash"),yt=require("nanoid"),St=require("p-limit"),m=require("path"),wt=require("stream/promises"),Et=require("tar"),bt=require("wait-on"),G=require("y-protocols/awareness"),ue=require("y-protocols/sync"),Tt=require("yaml"),Ot=require("yjs"),jt=require("lodash/isNil"),C=require("sequelize");require("sqlite3");const x=e=>e&&e.__esModule?e:{default:e};function Q(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 oe=x(st),xe=x(nt),w=x(rt),Ct=x(Me),It=x(at),Pt=x(it),At=x(lt),_t=Q(ut),vt=x(pt),xt=x(dt),D=x(ft),pe=Q(gt),A=Q(ht),Dt=x(St),kt=x(m),Rt=x(bt),J=Q(Tt),B=Q(Ot),Nt=x(jt);w.default.env.mode;const Lt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Ut=oe.default.env.DATABASE_URL||kt.default.join(w.default.env.dataDir,"db/pages-kit.db"),De=w.default,Mt=()=>w.default.env.tenantMode==="multiple",Ft=()=>{var e;return(Nt.default(De.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=De.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},I=It.default("pages-kit"),qt=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):qt(e,s);const X=new C.Sequelize({dialect:"sqlite",storage:Ut,benchmark:oe.default.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:oe.default.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});X.query("pragma journal_mode = WAL;");X.query("pragma synchronous = normal;");X.query("pragma journal_size_limit = 67108864;");class le extends C.Model{}le.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:X,tableName:"ProjectComponents",timestamps:!1});class q extends C.Model{static async getProjectByIdOrSlug(s){return q.findOne({where:{[C.Op.or]:[{id:s},{slug:s}]}})}}q.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,relatedBlocklets:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:X,paranoid:!0});q.hasMany(le,{foreignKey:"projectId",as:"components"});const $t=async(e,{componentId:s})=>{const t=`@tailwind components;
2
2
  @tailwind utilities;
3
3
  `,n=`.CustomComponent_${s}`;return(await vt.default([xt.default({content:[{raw:e,extension:"tsx"}]}),At.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(l=>{l.selectors=l.selectors.map(r=>r.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},Bt=async(e,{componentId:s})=>{const t=await $t(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
4
4
 
@@ -29,7 +29,7 @@ var ${e} = ${t?"async":""} function () {
29
29
 
30
30
  return exports;
31
31
  };
32
- `},K=new Te.LRUCache({max:100}),qe=60*60,he=60;function $e(e){I.info("clear preload components cache",{cacheKey:e}),K.delete(e)}function Be(e){for(const s of K.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),$e(s))}function Ve({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ht({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:l,config:{defaultLocale:r}}=t;if(!r)return null;const i=(await Promise.all(o.map(async h=>{try{const S=Ve({mode:e,instanceId:h.id,componentId:h.componentId,locale:n});if(e!=="draft"&&h.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const P=Y({state:t,componentId:h.componentId});if(!P)return null;const _=await Ge({req:s,state:t,componentId:P.id,locale:n,defaultLocale:r,properties:h.properties});if(!_)return null;const N={instanceId:h.id,preload:_};if(e!=="draft"&&h.useCache){let L=qe;h.cacheDuration&&(L=h.cacheDuration),I.info(`set preload component to cache(${L}s): ${S}`),K.set(S,N,{ttl:L*1e3})}return N}catch(S){return I.error("get preload component error",{instanceId:h.id,componentId:h.componentId},{error:S}),null}}))).filter(h=>!!h),c=Object.values(i.reduce((h,S)=>({...h,...S.preload.components}),{}));async function u(){const h=await Promise.all(c.map(async S=>{const P=ne.componentUMDName({componentId:S.component.id}),_=a===te.PreloadComponentScriptModule.ESM?{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,moduleName:P,tailwind:e!=="draft"}),moduleName:P};return[S.component.id,{component:S.component,script:_}]}));return Object.fromEntries(h)}const p=await u();return{config:{defaultLocale:r,supportedLocales:l},components:p,instances:i.map(h=>({id:h.instanceId,componentId:h.preload.component.id,locales:{[h.preload.locale]:{props:h.preload.props}}}))}}async function Ge({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:l}=s,r=Y({state:s,componentId:t});if(!r)return null;const i=l.some(u=>u.locale===n)?n:o;if(!i)return null;const c=await He({req:e,state:s,componentId:t,locale:i,defaultLocale:o,properties:a});return c?{component:r,...c}:null}const Jt=20;async function He({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:l}){if(s>Jt)throw new RangeError("max component depth exceeded");const r=Kt({state:t,componentId:n,properties:l,locale:o});if(!r)return null;const{props:i}=r,c={locale:o||a,components:{[r.component.id]:{component:r.component,script:r.script}},props:{...i}};try{const u=await Yt({...r,req:e});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){I.error("preload data at server side error",{componentId:n,name:r.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===ne.RenderNestedComponent){const g=await He({req:e,depth:s+1,state:t,componentId:p.componentId,locale:o,defaultLocale:a,properties:p.properties});g&&(Object.assign(c.components,g.components),Object.assign(c.props,{[u]:{type:ne.RenderNestedComponent,componentId:p.componentId,props:g.props}}))}})),c}function Kt({state:e,componentId:s,locale:t,properties:n}){const o=Y({state:e,componentId:s});if(!o)return null;const a=ne.mergeComponent({componentId:s,getComponent:l=>Y({state:e,componentId:l}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.properties}}:null}function Y({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 zt({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var l;return((l=a.data.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var l;return((l=a.component.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:o.component)}async function Yt({component:e,script:s,props:t,req:n}){const o=await Fe(s,"getServerSideProps");if(!o)return null;let a=new AbortController;const l=new Promise((r,i)=>{setTimeout(()=>{i(new Error("getServerSideProps timeout in promise race")),a&&(a.abort(),a=null)},he*1e3)});try{return await Promise.race([l,$.Sandbox.callFunction({code:`${o}
32
+ `},K=new Te.LRUCache({max:100}),qe=60*60,he=60;function $e(e){I.info("clear preload components cache",{cacheKey:e}),K.delete(e)}function Be(e){for(const s of K.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),$e(s))}function Ve({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ht({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:l,config:{defaultLocale:r}}=t;if(!r)return null;const i=(await Promise.all(o.map(async h=>{try{const S=Ve({mode:e,instanceId:h.id,componentId:h.componentId,locale:n});if(e!=="draft"&&h.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const P=Y({state:t,componentId:h.componentId});if(!P)return null;const _=await Ge({req:s,state:t,componentId:P.id,locale:n,defaultLocale:r,properties:h.properties});if(!_)return null;const N={instanceId:h.id,preload:_};if(e!=="draft"&&h.useCache){let L=qe;h.cacheDuration&&(L=h.cacheDuration),I.info(`set preload component to cache(${L}s): ${S}`),K.set(S,N,{ttl:L*1e3})}return N}catch(S){return I.error("get preload component error",{instanceId:h.id,componentId:h.componentId},{error:S}),null}}))).filter(h=>!!h),c=Object.values(i.reduce((h,S)=>({...h,...S.preload.components}),{}));async function u(){const h=await Promise.all(c.map(async S=>{const P=ne.componentUMDName({componentId:S.component.id}),_=a===te.PreloadComponentScriptModule.ESM?{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,moduleName:P,tailwind:e!=="draft"}),moduleName:P};return[S.component.id,{component:S.component,script:_}]}));return Object.fromEntries(h)}const p=await u();return{config:{defaultLocale:r,supportedLocales:l},components:p,instances:i.map(h=>({id:h.instanceId,componentId:h.preload.component.id,locales:{[h.preload.locale]:{props:h.preload.props}}}))}}async function Ge({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:l}=s,r=Y({state:s,componentId:t});if(!r)return null;const i=l.some(u=>u.locale===n)?n:o;if(!i)return null;const c=await He({req:e,state:s,componentId:t,locale:i,defaultLocale:o,properties:a});return c?{component:r,...c}:null}const Jt=20;async function He({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:l}){if(s>Jt)throw new RangeError("max component depth exceeded");const r=Kt({state:t,componentId:n,properties:l,locale:o});if(!r)return null;const{props:i}=r,c={locale:o||a,components:{[r.component.id]:{component:r.component,script:r.script}},props:{...i}};try{const u=await Yt({...r,req:e});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){I.error("preload data at server side error",{componentId:n,name:r.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===ne.RenderNestedComponent){const g=await He({req:e,depth:s+1,state:t,componentId:p.componentId,locale:o,defaultLocale:a,properties:p.properties});g&&(Object.assign(c.components,g.components),Object.assign(c.props,{[u]:{type:ne.RenderNestedComponent,componentId:p.componentId,props:g.props}}))}})),c}function Kt({state:e,componentId:s,locale:t,properties:n}){const o=Y({state:e,componentId:s});if(!o)return null;const a=ne.mergeComponent({componentId:s,getComponent:l=>Y({state:e,componentId:l}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.properties}}:null}function Y({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 zt({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var l;return((l=a.data.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var l;return((l=a.component.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:o.component)}async function Yt({component:e,script:s,props:t,req:n}){const o=await Fe(s,"getServerSideProps");if(!o)return null;const a=new Promise((r,i)=>{setTimeout(()=>{i(new Error("getServerSideProps timeout in promise race"))},he*1e3)});return await Promise.race([a,$.Sandbox.callFunction({code:`${o}
33
33
 
34
34
  export async function getServerSidePropsWrapper(props) {
35
35
  const { location, fetch } = props;
@@ -48,10 +48,10 @@ export async function getServerSidePropsWrapper(props) {
48
48
  }
49
49
  }`,filename:`${e.name||e.id}.js`,moduleLoader:r=>{if(r==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
50
50
  export { joinURL, withQuery, getQuery, getComponentMountPoint }
51
- `;if(r==="@blocklet/pages-kit/builtin/dayjs")return $.BuiltinModules.dayjs},global:{console:{log:(...r)=>{I.info(...r)},warn:(...r)=>{I.warn(...r)},error:(...r)=>{I.error(...r)}},getComponentMountPoint:ot.getComponentMountPoint,joinURL:v.joinURL,withQuery:v.withQuery,getQuery:v.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:v.joinURL(v.withHttps(n.hostname),n.originalUrl)},fetch:(r,{...i}={})=>{const c=typeof r=="string"&&r.startsWith("/")?v.joinURL(w.default.env.appUrl,r):r;if(typeof c=="string"&&v.parseURL(c).host===v.parseURL(w.default.env.appUrl).host){const u=n.get("cookie");if(u){const p=new Me.Headers(i.headers);p.set("cookie",u),i.headers=p}}return jt.default(c,{...i,timeout:he*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:t}]})])}finally{a=null}}const Je=$.memoize(async(e,s,t)=>{const n=await Fe(e,s);if(n)try{return await $.Sandbox.callFunction({code:`
51
+ `;if(r==="@blocklet/pages-kit/builtin/dayjs")return $.BuiltinModules.dayjs},global:{console:{log:(...r)=>{I.info(...r)},warn:(...r)=>{I.warn(...r)},error:(...r)=>{I.error(...r)}},getComponentMountPoint:ot.getComponentMountPoint,joinURL:v.joinURL,withQuery:v.withQuery,getQuery:v.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:v.joinURL(v.withHttps(n.hostname),n.originalUrl)},fetch:(r,{...i}={})=>{const c=typeof r=="string"&&r.startsWith("/")?v.joinURL(w.default.env.appUrl,r):r;if(typeof c=="string"&&v.parseURL(c).host===v.parseURL(w.default.env.appUrl).host){const u=n.get("cookie");if(u){const p=new Me.Headers(i.headers);p.set("cookie",u),i.headers=p}}return Ct.default(c,{...i,timeout:he*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:t}]})])}const Je=$.memoize(async(e,s,t)=>{const n=await Fe(e,s);if(n)try{return await $.Sandbox.callFunction({code:`
52
52
  ${n}
53
53
 
54
54
  export function get${s}SchemaWrapper() {
55
55
  return ${s};
56
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=ie.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Wt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ye="page",Se="trigger-reload-project-resource",Oe=Wt,Qt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Xt}=require("@blocklet/uploader-server"),we=yt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ce=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,z=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Re=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Zt=1e4,es=3e4,ee=0,de=1,ts=0,ss=1,Ee=w.default,H=m.join(oe.default.env.BLOCKLET_DATA_DIR,"site-state"),ns=["production","draft"],os=["production"];function Ke(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function rs(){var t;const e=Ee.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const F=class F extends B.Doc{constructor(s){super(),this.options=s,this.states={},this.conns=new Map,this.awarenessChangeHandler=({added:t,updated:n,removed:o},a)=>{const l=t.concat(n,o);if(a!==null){const c=this.conns.get(a);c&&(t.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,l));const i=A.toUint8Array(r);this.conns.forEach((c,u)=>this.send(u,i))},this.updateHandler=t=>{const n=A.createEncoder();A.writeVarUint(n,ee),ue.writeUpdate(n,t);const o=A.toUint8Array(n);this.conns.forEach((a,l)=>this.send(l,o))},this.ensureDataStructure=()=>{var l;const{supportedLocales:t,pages:n,pageIds:o,config:a}=this.syncedStore;{const r=new Set(Object.keys(n));let i=0;for(;i<o.length;){const c=o[i];r.has(c)?(r.delete(c),i++):o.splice(i,1)}}t.splice(0,t.length),t.push(...Ee.env.languages.map(r=>({locale:r.code,name:r.name}))),a.defaultLocale=(l=t[0])==null?void 0:l.locale;{let r=0;const i=new Set;for(;r<t.length;){const{locale:c}=t[r];i.has(c)?t.splice(r,1):(r++,i.add(c))}}},this.send=(t,n)=>{t.readyState!==ts&&t.readyState!==ss&&this.closeConn(t);try{t.send(n,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}},this.closeConn=t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&G.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()},this.autoSave=R.debounce(()=>{E.mkdirSync(m.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Zt),this.save=({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()},this.publish=async({mode:t,pages:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await be(o,a,{pages:n,pageMergeMode:"replace",deletePages:!0,publishMode:t}),a.config.publishedAt=new Date().getTime();for(const l of n||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(t,a)},this.mergeState=async(t,n)=>{var r,i,c;const o=JSON.parse(JSON.stringify(n));(r=t.config).fontFamily??(r.fontFamily={});const a=(i=o.config)==null?void 0:i.fontFamily,l=(c=t.config)==null?void 0:c.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(l==null?void 0:l.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const g=await be(t,n);u(g)}catch(g){p(g)}})})},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)}}},es);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=A.createEncoder();A.writeVarUint(a,ee),ue.writeSyncStep1(a,this),this.send(t,A.toUint8Array(a));const l=this.awareness.getStates();if(l.size>0){const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(t,A.toUint8Array(r))}}},this.messageListener=(t,n)=>{try{const o=A.createEncoder(),a=pe.createDecoder(n),l=pe.readVarUint(a);switch(l){case ee:A.writeVarUint(o,ee),ue.readSyncMessage(a,o,this,null),A.length(o)>1&&(this.ensureDataStructure(),this.send(t,A.toUint8Array(o)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()},E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=mt.reactive(Z.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(s){if(!s)throw new Error("Should provide project context");try{const t=m.join(H,s),n=m.join(H,`@del-${s}`);E.renameSync(t,n)}catch(t){I.error("Failed to safe delete project state dir:",t)}}static get projectIds(){return ge.globSync("*/",{cwd:H,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(s=>F.shared(s))}static shared(s){if(!s)throw new Error("Should provide project context");let t=this.sharedInstances.get(s);return t||(t=new F({path:m.join(H,s)}),this.sharedInstances.set(s,t),t)}destroy(){this.conns.forEach((s,t)=>this.closeConn(t)),this.awareness.destroy(),super.destroy()}initObserver(){const s=n=>{n.observeDeep(o=>{o.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||n.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(n=>{const o=Z.getYjsValue(this.syncedStore.pages[n]);o&&o instanceof B.Map&&s(o)});const t=Z.getYjsValue(this.syncedStore.pages);t&&t instanceof B.Map&&t.observe(n=>{n.changes.keys.forEach((o,a)=>{if(o.action==="add"){const l=Z.getYjsValue(this.syncedStore.pages[a]);l&&l instanceof B.Map&&s(l)}})})}get draftYjsFilePath(){return m.join(this.options.path,"draft.yjs")}async getState(s){var t,n,o,a;if(s==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[s]&&(this.states[s]=await je(this.getPublishDir(s),{includeResources:!0})??rs(),!((n=(t=this.states[s])==null?void 0:t.config)!=null&&n.defaultLocale))){(o=this.states[s]).config??(o.config={});const l=Ee.env.languages.map(r=>({locale:r.code,name:r.name}));this.states[s].config.defaultLocale=(a=l[0])==null?void 0:a.locale}return{...this.states[s],resources:await _e().then(async l=>{var u,p,g,h;const{pages:r,components:i}=R.pick(l,"pages","components");let c=i;if((p=(u=this.states[s])==null?void 0:u.resources)!=null&&p.components)c={...(h=(g=this.states[s])==null?void 0:g.resources)==null?void 0:h.components};else{const S=m.basename(this.options.path),P=await q.findByPk(S);if(P!=null&&P.useAllResources)c=i;else{const N=(await le.findAll({where:{projectId:S}})).map(y=>y.componentId);c=Object.fromEntries(Object.entries(i||{}).filter(([y])=>N.includes(y)))}}return{pages:r,components:c}}).catch(()=>({}))}}async setState(s,t){const n=await We(t,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(s);E.mkdirSync(m.dirname(o),{recursive:!0}),E.rmSync(o,{force:!0,recursive:!0}),E.renameSync(n,o),this.states[s]=t}getPublishDir(s){return m.join(this.options.path,s)}static async pageUrlMap(s){const{projectIds:t}=this,n={};for(const o of t){const a=await q.findByPk(o);if(!a)continue;const l=await F.shared(o).getState(s),r=R.union(w.default.env.languages.map(i=>i.code),l.supportedLocales.map(i=>i.locale));for(const i of l.pageIds){const c=l.pages[i];if(!c||s==="production"&&!c.isPublic)continue;const u=c.slug,p=a.slug||o,g={projectId:o,projectSlug:p,pageSlug:u,pageId:i,defaultLocale:r==null?void 0:r[0],locales:r,publishedAt:l.config.publishedAt,isPublic:c.isPublic,isTemplate:c.isTemplate};p&&(n[v.joinURL("/",p,u)]={...g,shouldRedirect:!0,mainPage:!0}),n[v.joinURL("/",o,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const h of r){const S={...g,locale:h};n[v.joinURL("/",h,o,u)]=S,p&&(n[v.joinURL("/",h,p,u)]=S)}}}return n}};F.INSTANCE_TTL=30*60*1e3,F.sharedInstances=new Te.LRUCache({max:100,ttl:F.INSTANCE_TTL,dispose:s=>{s.destroy()}});let W=F;function ze(){return E.mkdtempSync(m.join(w.default.env.dataDir,"tmp-"))}function re(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>re(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>re(o,s,[...t,n])):s(e)?[t]:[]}function M(e){return e.filter(s=>s!=null)}async function as(e,s,t){if(!e||!E.existsSync(e)||!E.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>(await Xt({filePath:e,fileName:s})).data.filename)(),t[e]=n),n}const is=async(e,s)=>{const t=m.basename(e),n=await ce.call({name:Oe,path:v.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=E.createWriteStream(s);await wt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},cs=async(e,s)=>{await Promise.all(e.map(async t=>{try{await is(t,m.join(s,m.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function Ye(e){return Ce.test(e)?[e]:z.test(e)?(Re.lastIndex=0,Array.from(e.matchAll(Re)).map(t=>t[1]).filter(t=>!!t)):[]}async function fe(e,s,t){const{getFilename:n,exportAssets:o}=t,a=m.join(s,n(e));if(E.mkdirSync(m.dirname(a),{recursive:!0}),E.writeFileSync(a,J.stringify(e)),o){const r=re(e,i=>typeof i=="string"&&(Ce.test(i)||z.test(i))).map(i=>{const c=R.get(e,i);return Ye(c)}).flat().filter(Boolean);await cs(r,m.dirname(a))}}const Ne=new Te.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Le(e,s,t){var r;const n=re(e,i=>typeof i=="string"&&(Ce.test(i)||z.test(i))),o=Dt.default(2),a=n.map(i=>o(async()=>{try{const c=R.get(e,i),u=Ye(c);for(const p of u){const g=m.basename(p),h=t.getFilePath(p,i),S=h?`${h}:${g}`:g,P=Ne.get(S);if(P){z.test(c)||R.set(e,i,P);return}const _=await as(h,g,s);_&&(z.test(c)||R.set(e,i,_),Ne.set(S,_))}}catch(c){I.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(a);(r=t.onFinish)==null||r.call(t,l)}async function We(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1}={}){var N,L,y,O,T,C;const l=t==="all"?e.pageIds:t,r=ls({state:e,pageIds:l,componentIds:n==="all"?Object.keys(e.components):n}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},u=M(e.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=e.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),p=ze(),g=m.join(p,"pages");E.mkdirSync(g,{recursive:!0});const h=m.join(p,"components");E.mkdirSync(h,{recursive:!0});for(const{locale:f,slug:d,page:b}of u)await fe(b,g,{getFilename:()=>`${Ke(d)||"index"}.${f}.yml`,exportAssets:s});for(const f of r){const d=(N=e.components[f])==null?void 0:N.data;d&&await fe(d,h,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:s})}const S=m.join(p,".blocklet/pages/pages.config.yml");E.mkdirSync(m.dirname(S),{recursive:!0});const P={pages:M(l.map(f=>{const d=e.pages[f];return d&&{id:f,slug:d.slug}})),components:M(r.map(f=>{var b;const d=(b=e.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...a?{resources:{components:M(Object.keys(((L=e.resources)==null?void 0:L.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=e.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};E.writeFileSync(S,J.stringify(P));const _=m.join(p,"config.source.json");if(o&&E.writeFileSync(_,JSON.stringify(o)),a){const f=m.join(p,"resources"),d=m.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=e==null?void 0:e.resources)==null?void 0:y.components)??{})){const k=(C=(T=(O=e.resources)==null?void 0:O.components)==null?void 0:T[b])==null?void 0:C.component;k&&await fe(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:s})}}return p}async function je(e,{importAssets:s,includeResources:t}={}){var a,l,r;if(!E.existsSync(e))return null;let n,o=!1;try{E.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ze(),await Et.x({file:e,C:n}));const i=ge.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),c=i&&m.join(m.dirname(i),"../../pages"),u=i&&m.join(m.dirname(i),"../../components"),p=i&&m.join(m.dirname(i),"../../chunks");if(!i)return null;const g=J.parse(E.readFileSync(i).toString()),h=(y,O,T)=>{let C=m.join(y,`${O}${T?`.${T}`:""}.yml`);return(!E.existsSync(C)||!E.lstatSync(C).isFile())&&(C=m.join(y,O,`index${T?`.${T}`:""}.yml`),!E.existsSync(C)||!E.lstatSync(C))?null:J.parse(E.readFileSync(C).toString())},S=(y,O)=>{try{const T=ge.globSync(`*.${O}.yml`,{cwd:y,absolute:!0})[0];return T?J.parse(E.readFileSync(T).toString()):null}catch(T){I.error("parse component error",T)}return null},P=M(g.pages.map(({slug:y})=>{var f;const O=M(g.supportedLocales.map(({locale:d})=>{const b=c?h(c,Ke(y),d):void 0;if(b)return{locale:d,page:b};const k=c?h(c,y,d):void 0;return k&&{locale:d,page:k}})),T=(f=O[0])==null?void 0:f.page;if(!T)return null;const C=T.sections.map(d=>{const b=d.id||we();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,visibility:d.visibility,locales:Object.fromEntries(M(O.map(({locale:k,page:U})=>{const ve=U.sections.find(tt=>tt.id===b);return ve&&[k,ve.properties]})))}});return{id:T.id||we(),createdAt:T.createdAt,updatedAt:T.updatedAt,publishedAt:T.publishedAt,isPublic:T.isPublic??!0,isTemplate:T.isTemplate??!1,slug:y,sections:Object.fromEntries(C.map(d=>[d.id,d])),sectionIds:C.map(d=>d.id),locales:Object.fromEntries(O.map(({locale:d,page:b})=>[d,b.meta]))}})),_=u?M(((a=g.components)==null?void 0:a.map(({id:y})=>S(u,y)))??[]):[];if(s){const y=(...O)=>{I.info(`[${o?m.basename(e):m.basename(m.join(e,"../../../../"))}] importAssets:`,...O)};try{y("wait image-bin api ready"),await Rt.default({resources:[`${ce.getComponentWebEndpoint(Lt)}/api/sdk/uploads`],validateStatus:C=>C>=200&&C<=500}),y("image-bin api is ready");const O={},T={};y("start to upload assets"),await Promise.allSettled([Le(_,O,{getFilePath:C=>u&&m.join(u,C),onFinish:C=>{y(`upload ${C.length} component assets`)}}),Le(P,T,{getFilePath:(C,f)=>{const d=R.get(P,f.slice(0,1));return c&&m.join(c,m.dirname(d.slug),C)},onFinish:C=>{y(`upload ${C.length} page assets`)}})]),y("upload assets done"),xe.default.gc&&xe.default.gc()}catch(O){y("Error during asset import:",O)}}const N={};if(t){const y=i&&m.join(m.dirname(i),"../../resources/components"),O=M(((r=(l=g.resources)==null?void 0:l.components)==null?void 0:r.map(({id:T})=>S(y,T)))??[]);O.length>0&&(N.components=Object.fromEntries(O.map((T,C)=>[T.id,{index:C,component:T}])))}const L={};if(p&&E.existsSync(p)){const y=E.readdirSync(p);for(const O of y)L[O]=m.join(p,O)}return{supportedLocales:g.supportedLocales,pageIds:P.map(y=>y.id),components:Object.fromEntries(_.map((y,O)=>[y.id,{index:O,data:y}])),pages:Object.fromEntries(P.map(y=>[y.id,y])),config:g.config||{},resources:N,chunks:L}}finally{o&&n&&E.rmSync(n,{force:!0,recursive:!0})}}async function be(e,s,{pages:t,pageMergeMode:n="byUpdateTime",deletePages:o=!1,publishMode:a=void 0}={}){try{a&&Be(a)}catch(u){I.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:r,supportedLocales:i}=e;for(const u of t??l){const p=r[u];if(!p){const g=s.pageIds.indexOf(u);g!==-1&&o&&(s.pageIds.splice(g,1),delete s.pages[u]);continue}if(s.pageIds.includes(p.id)){if(n==="replace")s.pages[p.id]=p;else if(n==="byUpdateTime"){const g=s.pages[p.id];(!g||p.updatedAt&&p.updatedAt>g.updatedAt)&&(s.pages[p.id]=p)}}else s.pageIds.push(p.id),s.pages[p.id]=p}if(o&&!t)for(const u of s.pageIds)e.pageIds.includes(u)||delete s.pages[u],s.pageIds=[...s.pageIds].filter(p=>e.pageIds.includes(p));if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...R.cloneDeep(i)),o)for(const u of Object.keys(s.components))delete s.components[u];let c=JSON.parse(JSON.stringify(e.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const g=await Qe(p==null?void 0:p.data);return[u,{...p,data:g}]}))),Object.assign(s.components,c),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const Qe=$.memoize(async e=>{var s;if(!R.isEmpty(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)try{const n=await Je(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 l;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((l=e==null?void 0:e.renderer)==null?void 0:l.type)||"",o=(e==null?void 0:e.properties)||{},a=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",s,t,n,a])},lruOptions:{max:100,ttl:1e3*60*60}});function ls({state:e,pageIds:s=[],componentIds:t=[]}){var l;const n=(r,i=new Set)=>(Array.isArray(r)&&r.forEach(c=>n(c,i)),r&&typeof r=="object"&&(typeof r.componentId=="string"&&i.add(r.componentId),Object.values(r).forEach(c=>n(c,i))),i),o=new Set(t);for(const r of s){const i=e.pages[r];n(i,o)}const a=[...o];for(;a.length;){const r=a.shift();o.has(r)||o.add(r);const i=(l=e.components[r])==null?void 0:l.data;if(i)for(const c of n(i))o.has(c)||a.push(c)}return[...o]}let ae,V,Ie,Pe,Ae;function Xe(){return ae=(async()=>{const e=ce.getResources({types:[{did:Oe,type:ye},{did:Qt,type:ye}]});V=(await Promise.all(e.map(async t=>{const n=t.path?await je(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),Ie=V.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=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await Qe(n.component);return[t,{...n,component:o}]}))),Ae=V.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),ae}function Ze(e){const s=R.debounce(async()=>{await Xe().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:V,pages:Ie,components:Pe,chunks:Ae}))},3e3,{leading:!1,trailing:!0});return s(),w.default.events.on(w.default.Events.componentAdded,s),w.default.events.on(w.default.Events.componentRemoved,s),w.default.events.on(w.default.Events.componentStarted,s),w.default.events.on(w.default.Events.componentStopped,s),w.default.events.on(w.default.Events.componentUpdated,s),w.default.events.on(Se,s),()=>{w.default.events.off(w.default.Events.componentAdded,s),w.default.events.off(w.default.Events.componentRemoved,s),w.default.events.off(w.default.Events.componentStarted,s),w.default.events.off(w.default.Events.componentStopped,s),w.default.events.off(w.default.Events.componentUpdated,s),w.default.events.off(Se,s)}}const et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),se=globalThis;var Ue;(Ue=se[et])==null||Ue.call(se);se[et]=Ze(async({pages:e,components:s})=>{const{projectIds:t}=W;await Promise.all(t.map(async n=>{const o=W.shared(n);o.syncedStore.resources.pages=e;const a=await q.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const r=(await le.findAll({where:{projectId:n}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(s||{}).filter(([c])=>r.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))});async function us(){I.info("trigger reload all project resource"),w.default.events.emit(Se)}async function _e({ensureLoaded:e=!0}={}){return e&&(ae??(ae=Xe()),await ae),{states:V,pages:Ie,components:Pe,chunks:Ae}}exports.COMPONENT_DID=Oe;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=qe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=he;exports.PUBLISH_MODES=os;exports.Project=q;exports.RESOURCE_TYPE=ye;exports.SITE_STATE_PATH=H;exports.STATE_MODES=ns;exports.SiteState=W;exports.clearPreloadComponentsCache=$e;exports.clearPreloadComponentsCacheByMode=Be;exports.fromPackage=je;exports.getComponentFromState=Y;exports.getComponentFromStateByName=zt;exports.getExportSchemaValueFromCode=Je;exports.getMultiTenantAllProjectAccessPassports=Ft;exports.getPreloadComponent=Ge;exports.getPreloadComponents=Ht;exports.getPreloadComponentsCacheKey=Ve;exports.getResourceStates=_e;exports.initPackResourceStates=Ze;exports.isMultiTenant=Mt;exports.logger=I;exports.mergeState=be;exports.nextId=we;exports.toPackage=We;exports.triggerReloadAllProjectResource=us;
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=ie.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Wt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ye="page",Se="trigger-reload-project-resource",Oe=Wt,Qt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Xt}=require("@blocklet/uploader-server"),we=yt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),je=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,z=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Re=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Zt=1e4,es=3e4,ee=0,de=1,ts=0,ss=1,Ee=w.default,H=m.join(oe.default.env.BLOCKLET_DATA_DIR,"site-state"),ns=["production","draft"],os=["production"];function Ke(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function rs(){var t;const e=Ee.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const F=class F extends B.Doc{constructor(s){super(),this.options=s,this.states={},this.conns=new Map,this.awarenessChangeHandler=({added:t,updated:n,removed:o},a)=>{const l=t.concat(n,o);if(a!==null){const c=this.conns.get(a);c&&(t.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,l));const i=A.toUint8Array(r);this.conns.forEach((c,u)=>this.send(u,i))},this.updateHandler=t=>{const n=A.createEncoder();A.writeVarUint(n,ee),ue.writeUpdate(n,t);const o=A.toUint8Array(n);this.conns.forEach((a,l)=>this.send(l,o))},this.ensureDataStructure=()=>{var l;const{supportedLocales:t,pages:n,pageIds:o,config:a}=this.syncedStore;{const r=new Set(Object.keys(n));let i=0;for(;i<o.length;){const c=o[i];r.has(c)?(r.delete(c),i++):o.splice(i,1)}}t.splice(0,t.length),t.push(...Ee.env.languages.map(r=>({locale:r.code,name:r.name}))),a.defaultLocale=(l=t[0])==null?void 0:l.locale;{let r=0;const i=new Set;for(;r<t.length;){const{locale:c}=t[r];i.has(c)?t.splice(r,1):(r++,i.add(c))}}},this.send=(t,n)=>{t.readyState!==ts&&t.readyState!==ss&&this.closeConn(t);try{t.send(n,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}},this.closeConn=t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&G.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()},this.autoSave=R.debounce(()=>{E.mkdirSync(m.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Zt),this.save=({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()},this.publish=async({mode:t,pages:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await be(o,a,{pages:n,pageMergeMode:"replace",deletePages:!0,publishMode:t}),a.config.publishedAt=new Date().getTime();for(const l of n||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(t,a)},this.mergeState=async(t,n)=>{var r,i,c;const o=JSON.parse(JSON.stringify(n));(r=t.config).fontFamily??(r.fontFamily={});const a=(i=o.config)==null?void 0:i.fontFamily,l=(c=t.config)==null?void 0:c.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(l==null?void 0:l.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const g=await be(t,n);u(g)}catch(g){p(g)}})})},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)}}},es);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=A.createEncoder();A.writeVarUint(a,ee),ue.writeSyncStep1(a,this),this.send(t,A.toUint8Array(a));const l=this.awareness.getStates();if(l.size>0){const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(t,A.toUint8Array(r))}}},this.messageListener=(t,n)=>{try{const o=A.createEncoder(),a=pe.createDecoder(n),l=pe.readVarUint(a);switch(l){case ee:A.writeVarUint(o,ee),ue.readSyncMessage(a,o,this,null),A.length(o)>1&&(this.ensureDataStructure(),this.send(t,A.toUint8Array(o)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()},E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=mt.reactive(Z.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(s){if(!s)throw new Error("Should provide project context");try{const t=m.join(H,s),n=m.join(H,`@del-${s}`);E.renameSync(t,n)}catch(t){I.error("Failed to safe delete project state dir:",t)}}static get projectIds(){return ge.globSync("*/",{cwd:H,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(s=>F.shared(s))}static shared(s){if(!s)throw new Error("Should provide project context");let t=this.sharedInstances.get(s);return t||(t=new F({path:m.join(H,s)}),this.sharedInstances.set(s,t),t)}destroy(){this.conns.forEach((s,t)=>this.closeConn(t)),this.awareness.destroy(),super.destroy()}initObserver(){const s=n=>{n.observeDeep(o=>{o.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||n.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(n=>{const o=Z.getYjsValue(this.syncedStore.pages[n]);o&&o instanceof B.Map&&s(o)});const t=Z.getYjsValue(this.syncedStore.pages);t&&t instanceof B.Map&&t.observe(n=>{n.changes.keys.forEach((o,a)=>{if(o.action==="add"){const l=Z.getYjsValue(this.syncedStore.pages[a]);l&&l instanceof B.Map&&s(l)}})})}get draftYjsFilePath(){return m.join(this.options.path,"draft.yjs")}async getState(s){var t,n,o,a;if(s==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[s]&&(this.states[s]=await Ce(this.getPublishDir(s),{includeResources:!0})??rs(),!((n=(t=this.states[s])==null?void 0:t.config)!=null&&n.defaultLocale))){(o=this.states[s]).config??(o.config={});const l=Ee.env.languages.map(r=>({locale:r.code,name:r.name}));this.states[s].config.defaultLocale=(a=l[0])==null?void 0:a.locale}return{...this.states[s],resources:await _e().then(async l=>{var u,p,g,h;const{pages:r,components:i}=R.pick(l,"pages","components");let c=i;if((p=(u=this.states[s])==null?void 0:u.resources)!=null&&p.components)c={...(h=(g=this.states[s])==null?void 0:g.resources)==null?void 0:h.components};else{const S=m.basename(this.options.path),P=await q.findByPk(S);if(P!=null&&P.useAllResources)c=i;else{const N=(await le.findAll({where:{projectId:S}})).map(y=>y.componentId);c=Object.fromEntries(Object.entries(i||{}).filter(([y])=>N.includes(y)))}}return{pages:r,components:c}}).catch(()=>({}))}}async setState(s,t){const n=await We(t,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(s);E.mkdirSync(m.dirname(o),{recursive:!0}),E.rmSync(o,{force:!0,recursive:!0}),E.renameSync(n,o),this.states[s]=t}getPublishDir(s){return m.join(this.options.path,s)}static async pageUrlMap(s){const{projectIds:t}=this,n={};for(const o of t){const a=await q.findByPk(o);if(!a)continue;const l=await F.shared(o).getState(s),r=R.union(w.default.env.languages.map(i=>i.code),l.supportedLocales.map(i=>i.locale));for(const i of l.pageIds){const c=l.pages[i];if(!c||s==="production"&&!c.isPublic)continue;const u=c.slug,p=a.slug||o,g={projectId:o,projectSlug:p,pageSlug:u,pageId:i,defaultLocale:r==null?void 0:r[0],locales:r,publishedAt:l.config.publishedAt,isPublic:c.isPublic,isTemplate:c.isTemplate};p&&(n[v.joinURL("/",p,u)]={...g,shouldRedirect:!0,mainPage:!0}),n[v.joinURL("/",o,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const h of r){const S={...g,locale:h};n[v.joinURL("/",h,o,u)]=S,p&&(n[v.joinURL("/",h,p,u)]=S)}}}return n}};F.INSTANCE_TTL=30*60*1e3,F.sharedInstances=new Te.LRUCache({max:100,ttl:F.INSTANCE_TTL,dispose:s=>{s.destroy()}});let W=F;function ze(){return E.mkdtempSync(m.join(w.default.env.dataDir,"tmp-"))}function re(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>re(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>re(o,s,[...t,n])):s(e)?[t]:[]}function M(e){return e.filter(s=>s!=null)}async function as(e,s,t){if(!e||!E.existsSync(e)||!E.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>(await Xt({filePath:e,fileName:s})).data.filename)(),t[e]=n),n}const is=async(e,s)=>{const t=m.basename(e),n=await ce.call({name:Oe,path:v.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=E.createWriteStream(s);await wt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},cs=async(e,s)=>{await Promise.all(e.map(async t=>{try{await is(t,m.join(s,m.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function Ye(e){return je.test(e)?[e]:z.test(e)?(Re.lastIndex=0,Array.from(e.matchAll(Re)).map(t=>t[1]).filter(t=>!!t)):[]}async function fe(e,s,t){const{getFilename:n,exportAssets:o}=t,a=m.join(s,n(e));if(E.mkdirSync(m.dirname(a),{recursive:!0}),E.writeFileSync(a,J.stringify(e)),o){const r=re(e,i=>typeof i=="string"&&(je.test(i)||z.test(i))).map(i=>{const c=R.get(e,i);return Ye(c)}).flat().filter(Boolean);await cs(r,m.dirname(a))}}const Ne=new Te.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Le(e,s,t){var r;const n=re(e,i=>typeof i=="string"&&(je.test(i)||z.test(i))),o=Dt.default(2),a=n.map(i=>o(async()=>{try{const c=R.get(e,i),u=Ye(c);for(const p of u){const g=m.basename(p),h=t.getFilePath(p,i),S=h?`${h}:${g}`:g,P=Ne.get(S);if(P){z.test(c)||R.set(e,i,P);return}const _=await as(h,g,s);_&&(z.test(c)||R.set(e,i,_),Ne.set(S,_))}}catch(c){I.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(a);(r=t.onFinish)==null||r.call(t,l)}async function We(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1}={}){var N,L,y,O,T,j;const l=t==="all"?e.pageIds:t,r=ls({state:e,pageIds:l,componentIds:n==="all"?Object.keys(e.components):n}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},u=M(e.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=e.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),p=ze(),g=m.join(p,"pages");E.mkdirSync(g,{recursive:!0});const h=m.join(p,"components");E.mkdirSync(h,{recursive:!0});for(const{locale:f,slug:d,page:b}of u)await fe(b,g,{getFilename:()=>`${Ke(d)||"index"}.${f}.yml`,exportAssets:s});for(const f of r){const d=(N=e.components[f])==null?void 0:N.data;d&&await fe(d,h,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:s})}const S=m.join(p,".blocklet/pages/pages.config.yml");E.mkdirSync(m.dirname(S),{recursive:!0});const P={pages:M(l.map(f=>{const d=e.pages[f];return d&&{id:f,slug:d.slug}})),components:M(r.map(f=>{var b;const d=(b=e.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...a?{resources:{components:M(Object.keys(((L=e.resources)==null?void 0:L.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=e.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};E.writeFileSync(S,J.stringify(P));const _=m.join(p,"config.source.json");if(o&&E.writeFileSync(_,JSON.stringify(o)),a){const f=m.join(p,"resources"),d=m.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=e==null?void 0:e.resources)==null?void 0:y.components)??{})){const k=(j=(T=(O=e.resources)==null?void 0:O.components)==null?void 0:T[b])==null?void 0:j.component;k&&await fe(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:s})}}return p}async function Ce(e,{importAssets:s,includeResources:t}={}){var a,l,r;if(!E.existsSync(e))return null;let n,o=!1;try{E.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ze(),await Et.x({file:e,C:n}));const i=ge.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),c=i&&m.join(m.dirname(i),"../../pages"),u=i&&m.join(m.dirname(i),"../../components"),p=i&&m.join(m.dirname(i),"../../chunks");if(!i)return null;const g=J.parse(E.readFileSync(i).toString()),h=(y,O,T)=>{let j=m.join(y,`${O}${T?`.${T}`:""}.yml`);return(!E.existsSync(j)||!E.lstatSync(j).isFile())&&(j=m.join(y,O,`index${T?`.${T}`:""}.yml`),!E.existsSync(j)||!E.lstatSync(j))?null:J.parse(E.readFileSync(j).toString())},S=(y,O)=>{try{const T=ge.globSync(`*.${O}.yml`,{cwd:y,absolute:!0})[0];return T?J.parse(E.readFileSync(T).toString()):null}catch(T){I.error("parse component error",T)}return null},P=M(g.pages.map(({slug:y})=>{var f;const O=M(g.supportedLocales.map(({locale:d})=>{const b=c?h(c,Ke(y),d):void 0;if(b)return{locale:d,page:b};const k=c?h(c,y,d):void 0;return k&&{locale:d,page:k}})),T=(f=O[0])==null?void 0:f.page;if(!T)return null;const j=T.sections.map(d=>{const b=d.id||we();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,visibility:d.visibility,locales:Object.fromEntries(M(O.map(({locale:k,page:U})=>{const ve=U.sections.find(tt=>tt.id===b);return ve&&[k,ve.properties]})))}});return{id:T.id||we(),createdAt:T.createdAt,updatedAt:T.updatedAt,publishedAt:T.publishedAt,isPublic:T.isPublic??!0,isTemplate:T.isTemplate??!1,slug:y,sections:Object.fromEntries(j.map(d=>[d.id,d])),sectionIds:j.map(d=>d.id),locales:Object.fromEntries(O.map(({locale:d,page:b})=>[d,b.meta]))}})),_=u?M(((a=g.components)==null?void 0:a.map(({id:y})=>S(u,y)))??[]):[];if(s){const y=(...O)=>{I.info(`[${o?m.basename(e):m.basename(m.join(e,"../../../../"))}] importAssets:`,...O)};try{y("wait image-bin api ready"),await Rt.default({resources:[`${ce.getComponentWebEndpoint(Lt)}/api/sdk/uploads`],validateStatus:j=>j>=200&&j<=500}),y("image-bin api is ready");const O={},T={};y("start to upload assets"),await Promise.allSettled([Le(_,O,{getFilePath:j=>u&&m.join(u,j),onFinish:j=>{y(`upload ${j.length} component assets`)}}),Le(P,T,{getFilePath:(j,f)=>{const d=R.get(P,f.slice(0,1));return c&&m.join(c,m.dirname(d.slug),j)},onFinish:j=>{y(`upload ${j.length} page assets`)}})]),y("upload assets done"),xe.default.gc&&xe.default.gc()}catch(O){y("Error during asset import:",O)}}const N={};if(t){const y=i&&m.join(m.dirname(i),"../../resources/components"),O=M(((r=(l=g.resources)==null?void 0:l.components)==null?void 0:r.map(({id:T})=>S(y,T)))??[]);O.length>0&&(N.components=Object.fromEntries(O.map((T,j)=>[T.id,{index:j,component:T}])))}const L={};if(p&&E.existsSync(p)){const y=E.readdirSync(p);for(const O of y)L[O]=m.join(p,O)}return{supportedLocales:g.supportedLocales,pageIds:P.map(y=>y.id),components:Object.fromEntries(_.map((y,O)=>[y.id,{index:O,data:y}])),pages:Object.fromEntries(P.map(y=>[y.id,y])),config:g.config||{},resources:N,chunks:L}}finally{o&&n&&E.rmSync(n,{force:!0,recursive:!0})}}async function be(e,s,{pages:t,pageMergeMode:n="byUpdateTime",deletePages:o=!1,publishMode:a=void 0}={}){try{a&&Be(a)}catch(u){I.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:r,supportedLocales:i}=e;for(const u of t??l){const p=r[u];if(!p){const g=s.pageIds.indexOf(u);g!==-1&&o&&(s.pageIds.splice(g,1),delete s.pages[u]);continue}if(s.pageIds.includes(p.id)){if(n==="replace")s.pages[p.id]=p;else if(n==="byUpdateTime"){const g=s.pages[p.id];(!g||p.updatedAt&&p.updatedAt>g.updatedAt)&&(s.pages[p.id]=p)}}else s.pageIds.push(p.id),s.pages[p.id]=p}if(o&&!t)for(const u of s.pageIds)e.pageIds.includes(u)||delete s.pages[u],s.pageIds=[...s.pageIds].filter(p=>e.pageIds.includes(p));if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...R.cloneDeep(i)),o)for(const u of Object.keys(s.components))delete s.components[u];let c=JSON.parse(JSON.stringify(e.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const g=await Qe(p==null?void 0:p.data);return[u,{...p,data:g}]}))),Object.assign(s.components,c),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const Qe=$.memoize(async e=>{var s;if(!R.isEmpty(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)try{const n=await Je(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 l;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((l=e==null?void 0:e.renderer)==null?void 0:l.type)||"",o=(e==null?void 0:e.properties)||{},a=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",s,t,n,a])},lruOptions:{max:100,ttl:1e3*60*60}});function ls({state:e,pageIds:s=[],componentIds:t=[]}){var l;const n=(r,i=new Set)=>(Array.isArray(r)&&r.forEach(c=>n(c,i)),r&&typeof r=="object"&&(typeof r.componentId=="string"&&i.add(r.componentId),Object.values(r).forEach(c=>n(c,i))),i),o=new Set(t);for(const r of s){const i=e.pages[r];n(i,o)}const a=[...o];for(;a.length;){const r=a.shift();o.has(r)||o.add(r);const i=(l=e.components[r])==null?void 0:l.data;if(i)for(const c of n(i))o.has(c)||a.push(c)}return[...o]}let ae,V,Ie,Pe,Ae;function Xe(){return ae=(async()=>{const e=ce.getResources({types:[{did:Oe,type:ye},{did:Qt,type:ye}]});V=(await Promise.all(e.map(async t=>{const n=t.path?await Ce(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),Ie=V.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=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await Qe(n.component);return[t,{...n,component:o}]}))),Ae=V.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),ae}function Ze(e){const s=R.debounce(async()=>{await Xe().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:V,pages:Ie,components:Pe,chunks:Ae}))},3e3,{leading:!1,trailing:!0});return s(),w.default.events.on(w.default.Events.componentAdded,s),w.default.events.on(w.default.Events.componentRemoved,s),w.default.events.on(w.default.Events.componentStarted,s),w.default.events.on(w.default.Events.componentStopped,s),w.default.events.on(w.default.Events.componentUpdated,s),w.default.events.on(Se,s),()=>{w.default.events.off(w.default.Events.componentAdded,s),w.default.events.off(w.default.Events.componentRemoved,s),w.default.events.off(w.default.Events.componentStarted,s),w.default.events.off(w.default.Events.componentStopped,s),w.default.events.off(w.default.Events.componentUpdated,s),w.default.events.off(Se,s)}}const et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),se=globalThis;var Ue;(Ue=se[et])==null||Ue.call(se);se[et]=Ze(async({pages:e,components:s})=>{const{projectIds:t}=W;await Promise.all(t.map(async n=>{const o=W.shared(n);o.syncedStore.resources.pages=e;const a=await q.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const r=(await le.findAll({where:{projectId:n}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(s||{}).filter(([c])=>r.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))});async function us(){I.info("trigger reload all project resource"),w.default.events.emit(Se)}async function _e({ensureLoaded:e=!0}={}){return e&&(ae??(ae=Xe()),await ae),{states:V,pages:Ie,components:Pe,chunks:Ae}}exports.COMPONENT_DID=Oe;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=qe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=he;exports.PUBLISH_MODES=os;exports.Project=q;exports.RESOURCE_TYPE=ye;exports.SITE_STATE_PATH=H;exports.STATE_MODES=ns;exports.SiteState=W;exports.clearPreloadComponentsCache=$e;exports.clearPreloadComponentsCacheByMode=Be;exports.fromPackage=Ce;exports.getComponentFromState=Y;exports.getComponentFromStateByName=zt;exports.getExportSchemaValueFromCode=Je;exports.getMultiTenantAllProjectAccessPassports=Ft;exports.getPreloadComponent=Ge;exports.getPreloadComponents=Ht;exports.getPreloadComponentsCacheKey=Ve;exports.getResourceStates=_e;exports.initPackResourceStates=Ze;exports.isMultiTenant=Mt;exports.logger=I;exports.mergeState=be;exports.nextId=we;exports.toPackage=We;exports.triggerReloadAllProjectResource=us;
@@ -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-B57sn0Rr.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;
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-DNRKik3e.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;
@@ -1,10 +1,10 @@
1
- "use strict";const J=require("vite-plugin-node-polyfills/shims/process"),k=require("./_chunks/site-state-B57sn0Rr.js"),S=require("@blocklet/crawler/middlewares"),G=require("@blocklet/pages-kit/types"),z=require("@blocklet/pages-kit/utils/preload"),K=require("@blocklet/sdk/lib/component"),R=require("@blocklet/sdk/lib/config"),Q=require("cheerio"),V=require("express"),I=require("fs"),X=require("mustache"),U=require("path"),j=require("ufo"),T=e=>e&&e.__esModule?e:{default:e};function Y(e){if(e&&e.__esModule)return e;const c=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const p=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(c,t,p.get?p:{enumerable:!0,get:()=>e[t]})}}return c.default=e,Object.freeze(c)}const q=T(J),d=T(R),D=Y(Q),Z=T(X),F=["/assets/"],x=()=>[!0,"true"].includes(d.default.env.preferences.allowCrawler);function B(){x()?S.initCronCrawlBlocklet({time:"30 30 */12 * * *",options:{}}):S.cancelCronCrawlBlocklet()}B();d.default.events.on(d.default.Events.envUpdate,B);function ee({app:e,viteDevServer:c,state:t}){let p;if(c){const l=I.readFileSync(U.resolve(q.default.cwd(),"./index.html"),"utf-8");e.use(async(b,$,y)=>{const v=b.originalUrl;p=await c.transformIndexHtml(v,l),y()})}else p=I.readFileSync(U.resolve(q.default.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const C=V.Router();C.use(S.initSEOMiddleware({autoReturnHtml:!1,allowCrawler:x})),C.get("/:path(*)?",async(l,b,$)=>{var L,M,O;if(F.some(r=>l.path.startsWith(r))){$();return}const y=performance.now(),v=()=>Math.round(performance.now()-y),H="production";let o,u,h=p;if(l.path.startsWith("/pages")){const r=l.params.lang,g=l.cookies.nf_lang,w=new Set([...d.default.env.languages.map(f=>f.code)]);let m=(r&&w.has(r)?r:void 0)||(w.has(g)?g:void 0)||[...w][0];if((!m||!((L=t.supportedLocales)!=null&&L.find(f=>f.locale===m)))&&(m=((O=(M=t.supportedLocales)==null?void 0:M[0])==null?void 0:O.locale)||""),m){const f=[];Object.values(t.pages).forEach(s=>{const P=Object.values((s==null?void 0:s.sections)??{}).filter(a=>{var _;return a.component==="custom-component"&&((_=a.config)==null?void 0:_.componentId)}).map(a=>{var _,A;return{id:a.id,componentId:a.config.componentId,useCache:a.config.useCache,cacheDuration:a.config.cacheDuration,properties:(A=(_=a.locales)==null?void 0:_[m])==null?void 0:A.properties}});f.push(...P)});const W=new Promise((s,P)=>{setTimeout(()=>{P(new Error("getPreloadComponents timeout in promise race, skip it"))},90*1e3)});try{await Promise.race([W,k.getPreloadComponents({mode:H,req:l,state:t,locale:m,instances:f,module:G.PreloadComponentScriptModule.UMD_FN}).then(s=>{s&&(u=z.injectPreloadComponents(s))})])}catch(s){k.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),k.logger.warn(s)}}}try{const r=(o==null?void 0:o.title)||d.default.env.appName,g=(o==null?void 0:o.description)||d.default.env.appDescription,w=j.withQuery(j.joinURL(d.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:r,description:g});h=Z.default.render(p,{ogTitle:r,ogDescription:g,ogImage:te(o==null?void 0:o.image)||w,pagesPublishedAt:(t==null?void 0:t.config.publishedAt)||new Date().getTime()})}catch{}const n=t==null?void 0:t.config.fontFamily,N=l.query.mode==="draft"||l.url.includes("preview");let i=D.load(h);i("head").find("#injected-head-elements").replaceWith(`
2
- ${o!=null&&o.backgroundColor?`<meta name="theme-color" content="${o.backgroundColor}" /><style>html,body,#app {background-color: ${o.backgroundColor} !important;}</style>`:""}
3
- ${n!=null&&n.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${n.title}&display=swap">`:""}
4
- ${n!=null&&n.description&&(n==null?void 0:n.description)!==(n==null?void 0:n.title)?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${n.description}&display=swap">`:""}
1
+ "use strict";const N=require("vite-plugin-node-polyfills/shims/process"),_=require("./_chunks/site-state-DNRKik3e.js"),P=require("@blocklet/crawler/middlewares"),J=require("@blocklet/pages-kit/types"),G=require("@blocklet/pages-kit/utils/preload"),W=require("@blocklet/sdk/lib/component"),R=require("@blocklet/sdk/lib/config"),K=require("express"),I=require("fs"),Q=require("mustache"),U=require("path"),S=require("ufo"),E=o=>o&&o.__esModule?o:{default:o},x=E(N),p=E(R),z=E(Q),V=["/assets/"],q=()=>[!0,"true"].includes(p.default.env.preferences.allowCrawler);function D(){q()?P.initCronCrawlBlocklet({time:"30 30 */12 * * *",options:{}}):P.cancelCronCrawlBlocklet()}D();p.default.events.on(p.default.Events.envUpdate,D);function X({app:o,viteDevServer:g,state:c}){let w;if(g){const n=I.readFileSync(U.resolve(x.default.cwd(),"./index.html"),"utf-8");o.use(async(y,T,k)=>{const b=y.originalUrl;w=await g.transformIndexHtml(b,n),k()})}else w=I.readFileSync(U.resolve(x.default.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const C=K.Router();C.use(P.initSEOMiddleware({autoReturnHtml:!1,allowCrawler:q})),C.get("/:path(*)?",async(n,y,T)=>{var L,M,j;if(V.some(l=>n.path.startsWith(l))){T();return}const k=performance.now(),b=()=>Math.round(performance.now()-k),O="production";let e,u,s=w;if(n.path.startsWith("/pages")){const l=n.params.lang,i=n.cookies.nf_lang,d=new Set([...p.default.env.languages.map(f=>f.code)]);let m=(l&&d.has(l)?l:void 0)||(d.has(i)?i:void 0)||[...d][0];if((!m||!((L=c.supportedLocales)!=null&&L.find(f=>f.locale===m)))&&(m=((j=(M=c.supportedLocales)==null?void 0:M[0])==null?void 0:j.locale)||""),m){const f=[];Object.values(c.pages).forEach(r=>{const v=Object.values((r==null?void 0:r.sections)??{}).filter(a=>{var h;return a.component==="custom-component"&&((h=a.config)==null?void 0:h.componentId)}).map(a=>{var h,A;return{id:a.id,componentId:a.config.componentId,useCache:a.config.useCache,cacheDuration:a.config.cacheDuration,properties:(A=(h=a.locales)==null?void 0:h[m])==null?void 0:A.properties}});f.push(...v)});const H=new Promise((r,v)=>{setTimeout(()=>{v(new Error("getPreloadComponents timeout in promise race, skip it"))},90*1e3)});try{await Promise.race([H,_.getPreloadComponents({mode:O,req:n,state:c,locale:m,instances:f,module:J.PreloadComponentScriptModule.UMD_FN}).then(r=>{r&&(u=G.injectPreloadComponents(r))})])}catch(r){_.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),_.logger.warn(r)}}}try{const l=(e==null?void 0:e.title)||p.default.env.appName,i=(e==null?void 0:e.description)||p.default.env.appDescription,d=S.withQuery(S.joinURL(p.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:l,description:i});s=z.default.render(w,{ogTitle:l,ogDescription:i,ogImage:Y(e==null?void 0:e.image)||d,pagesPublishedAt:(c==null?void 0:c.config.publishedAt)||new Date().getTime()})}catch{}const t=c==null?void 0:c.config.fontFamily,B=n.query.mode==="draft"||n.url.includes("preview");s=s.replace('<script id="injected-head-elements"><\/script>',`
2
+ ${e!=null&&e.backgroundColor?`<meta name="theme-color" content="${e.backgroundColor}" /><style>html,body,#app {background-color: ${e.backgroundColor} !important;}</style>`:""}
3
+ ${t!=null&&t.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${t.title}&display=swap">`:""}
4
+ ${t!=null&&t.description&&(t==null?void 0:t.description)!==(t==null?void 0:t.title)?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${t.description}&display=swap">`:""}
5
5
  <script>
6
6
 
7
- window.__PAGE_STATE__ = ${JSON.stringify(t)}
7
+ window.__PAGE_STATE__ = ${JSON.stringify(c)}
8
8
 
9
9
  document.querySelectorAll('link[rel="preload"][as="style"]').forEach(function (link) {
10
10
  const l = document.createElement('link');
@@ -14,10 +14,10 @@
14
14
  });
15
15
  <\/script>
16
16
 
17
- ${N?`<script src="https://cdn.tailwindcss.com"><\/script>
17
+ ${B?`<script src="https://cdn.tailwindcss.com"><\/script>
18
18
  <script>
19
19
  window.tailwind.config = {
20
20
  darkMode: "class",
21
21
  };
22
22
  <\/script>`:""}
23
- `);const E=R.getBlockletJs();if(E&&i('script[src="__blocklet__.js"]').replaceWith(`<script>${E}<\/script>`),u!=null&&u.html&&i("head").find("#injected-html-elements").replaceWith(u.html),l.cachedHtml){const r=D.load(l.cachedHtml);i("body").html(r("body").html()||"")}h=i.html(),b.send(h),k.logger.info(`[html] render: ${l.path}, ${v()}ms`),i.root().children().remove(),i=null,i=null,h=null,o=null,u=null}),e.use(C)}function te(e){const c=K.getComponentMountPoint("image-bin");return c&&e&&!/^(https?:\/\/|\/)/.test(e)?d.default.env.appUrl+j.joinURL(c,"uploads",e):e}module.exports=ee;
23
+ `);const $=R.getBlockletJs();if($&&(s=s.replace('<script src="__blocklet__.js"><\/script>',`<script>${$}<\/script>`)),u!=null&&u.html&&(s=s.replace('<script id="injected-html-elements"><\/script>',u.html)),n.cachedHtml){const l=/<body>([\s\S]*?)<\/body>/,i=l.exec(n.cachedHtml),d=i?i[1]:"";s=s.replace(l,`<body>${d}</body>`)}y.send(s),_.logger.info(`[html] render: ${n.path}, ${b()}ms`),s=null,e=null,u=null}),o.use(C)}function Y(o){const g=W.getComponentMountPoint("image-bin");return g&&o&&!/^(https?:\/\/|\/)/.test(o)?p.default.env.appUrl+S.joinURL(g,"uploads",o):o}module.exports=X;
@@ -1 +1 @@
1
- "use strict";const c=require("./_chunks/site-state-B57sn0Rr.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),O=require("lodash"),b=require("path"),X=require("@blocklet/sdk/lib/middlewares/auth"),W=require("@blocklet/sdk/lib/component"),E=t=>t&&t.__esModule?t:{default:t},p=E(F),I=E(J),k=E(b),v=E(X);new M.AsyncLocalStorage;const $=async(t,e,o)=>{var n,s,r,a;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 P=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!P)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===P,i=(a=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:a.call(r,h);if(!w&&!i)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=p.default.createReadStream(t),r=p.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await p.default.promises.mkdir(e,{recursive:!0});const o=await p.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 G(t,e){(await p.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const D=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),K=(t,e)=>{const o=W.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",y=":",_="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(y),Y=t=>{const[e,o,n]=t.split(y);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(y),z=t=>{const[e,o,n]=t.split(y);if(e===q)return{componentId:n,projectId:o}},H=t=>[L,t].join(y),Q=t=>{const[e,o]=t.split(y);if(e===L)return o},V=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 a=e.pages[r];if(a)return{id:C({pageId:r,projectId:t}),name:a.slug}}).filter(Boolean),s=O.sortBy(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:H(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:_,projectId:t}),name:"Pages",children:n},{id:A({componentId:_,projectId:t}),name:"Components",children:s}]}}S.get("/resources",D,async(t,e)=>{const{projectId:o}=V(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await $(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 Z=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",D,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await Z.validateAsync(t.body),r="production",a=[],u=[];for(const i of o){if(Q(i))continue;const{pageId:m,projectId:j}=Y(i)||{};if(m)m===_||m&&j&&a.push({pageId:m,projectId:j});else{const{componentId:l,projectId:d}=z(i)||{};l===_||l&&d&&u.push({componentId:l,projectId:d})}}const f=O.groupBy(a,"projectId"),P=O.groupBy(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(P)]),w=K(n,s);p.default.rmSync(w,{recursive:!0,force:!0}),p.default.mkdirSync(w,{recursive:!0});for(const i of h){const m=await c.SiteState.shared(i).getState(r),j=f[i],l=P[i],d=j==null?void 0:j.map(g=>g.pageId),R=l==null?void 0:l.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 G(g,w),p.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${i}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",D,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;
1
+ "use strict";const c=require("./_chunks/site-state-DNRKik3e.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),O=require("lodash"),b=require("path"),X=require("@blocklet/sdk/lib/middlewares/auth"),W=require("@blocklet/sdk/lib/component"),E=t=>t&&t.__esModule?t:{default:t},p=E(F),I=E(J),k=E(b),v=E(X);new M.AsyncLocalStorage;const $=async(t,e,o)=>{var n,s,r,a;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 P=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!P)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===P,i=(a=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:a.call(r,h);if(!w&&!i)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=p.default.createReadStream(t),r=p.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await p.default.promises.mkdir(e,{recursive:!0});const o=await p.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 G(t,e){(await p.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const D=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),K=(t,e)=>{const o=W.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",y=":",_="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(y),Y=t=>{const[e,o,n]=t.split(y);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(y),z=t=>{const[e,o,n]=t.split(y);if(e===q)return{componentId:n,projectId:o}},H=t=>[L,t].join(y),Q=t=>{const[e,o]=t.split(y);if(e===L)return o},V=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 a=e.pages[r];if(a)return{id:C({pageId:r,projectId:t}),name:a.slug}}).filter(Boolean),s=O.sortBy(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:H(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:_,projectId:t}),name:"Pages",children:n},{id:A({componentId:_,projectId:t}),name:"Components",children:s}]}}S.get("/resources",D,async(t,e)=>{const{projectId:o}=V(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await $(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 Z=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",D,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await Z.validateAsync(t.body),r="production",a=[],u=[];for(const i of o){if(Q(i))continue;const{pageId:m,projectId:j}=Y(i)||{};if(m)m===_||m&&j&&a.push({pageId:m,projectId:j});else{const{componentId:l,projectId:d}=z(i)||{};l===_||l&&d&&u.push({componentId:l,projectId:d})}}const f=O.groupBy(a,"projectId"),P=O.groupBy(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(P)]),w=K(n,s);p.default.rmSync(w,{recursive:!0,force:!0}),p.default.mkdirSync(w,{recursive:!0});for(const i of h){const m=await c.SiteState.shared(i).getState(r),j=f[i],l=P[i],d=j==null?void 0:j.map(g=>g.pageId),R=l==null?void 0:l.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 G(g,w),p.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${i}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",D,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;
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("vite-plugin-node-polyfills/shims/process");require("vite-plugin-node-polyfills/shims/global");const e=require("./_chunks/site-state-B57sn0Rr.js");require("@blocklet/quickjs");require("@blocklet/sdk/lib/component");require("@blocklet/sdk/lib/config");require("@reactivedata/reactive");require("@syncedstore/core");require("crypto");require("fs");require("glob");require("lib0/decoding");require("lib0/encoding");require("lodash");require("lru-cache");require("nanoid");require("p-limit");require("path");require("stream/promises");require("tar");require("ufo");require("wait-on");require("y-protocols/awareness");require("y-protocols/sync");require("yaml");require("yjs");exports.PUBLISH_MODES=e.PUBLISH_MODES;exports.SITE_STATE_PATH=e.SITE_STATE_PATH;exports.STATE_MODES=e.STATE_MODES;exports.default=e.SiteState;exports.fromPackage=e.fromPackage;exports.getResourceStates=e.getResourceStates;exports.initPackResourceStates=e.initPackResourceStates;exports.mergeState=e.mergeState;exports.nextId=e.nextId;exports.toPackage=e.toPackage;exports.triggerReloadAllProjectResource=e.triggerReloadAllProjectResource;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("vite-plugin-node-polyfills/shims/process");require("vite-plugin-node-polyfills/shims/global");const e=require("./_chunks/site-state-DNRKik3e.js");require("@blocklet/quickjs");require("@blocklet/sdk/lib/component");require("@blocklet/sdk/lib/config");require("@reactivedata/reactive");require("@syncedstore/core");require("crypto");require("fs");require("glob");require("lib0/decoding");require("lib0/encoding");require("lodash");require("lru-cache");require("nanoid");require("p-limit");require("path");require("stream/promises");require("tar");require("ufo");require("wait-on");require("y-protocols/awareness");require("y-protocols/sync");require("yaml");require("yjs");exports.PUBLISH_MODES=e.PUBLISH_MODES;exports.SITE_STATE_PATH=e.SITE_STATE_PATH;exports.STATE_MODES=e.STATE_MODES;exports.default=e.SiteState;exports.fromPackage=e.fromPackage;exports.getResourceStates=e.getResourceStates;exports.initPackResourceStates=e.initPackResourceStates;exports.mergeState=e.mergeState;exports.nextId=e.nextId;exports.toPackage=e.toPackage;exports.triggerReloadAllProjectResource=e.triggerReloadAllProjectResource;
@@ -2,12 +2,12 @@ import ee from "vite-plugin-node-polyfills/shims/process";
2
2
  import Oe from "vite-plugin-node-polyfills/shims/global";
3
3
  import { getComponentMountPoint as ot } from "@blocklet/pages-kit/builtin/utils";
4
4
  import { PreloadComponentScriptModule as Q } from "@blocklet/pages-kit/types";
5
- import { componentUMDName as nt, RenderNestedComponent as Ae, mergeComponent as rt } from "@blocklet/pages-kit/utils/property";
5
+ import { componentUMDName as nt, RenderNestedComponent as ve, mergeComponent as rt } from "@blocklet/pages-kit/utils/property";
6
6
  import { memoize as ae, Sandbox as $e, BuiltinModules as at } from "@blocklet/quickjs";
7
7
  import w from "@blocklet/sdk/lib/config";
8
8
  import { LRUCache as he } from "lru-cache";
9
9
  import it, { Headers as ct } from "node-fetch";
10
- import { joinURL as U, parseURL as ve, withHttps as lt, getQuery as pt, withQuery as ut } from "ufo";
10
+ import { joinURL as U, getQuery as lt, withQuery as pt, parseURL as Ae, withHttps as ut } from "ufo";
11
11
  import { createHash as ie } from "crypto";
12
12
  import dt from "@blocklet/logger";
13
13
  import mt from "vite-plugin-node-polyfills/shims/buffer";
@@ -16,16 +16,16 @@ import { createBuiltinModuleTransformer as gt, isRelativeModule as Te } from "@b
16
16
  import { call as Be, getResources as ht, getComponentWebEndpoint as yt } from "@blocklet/sdk/lib/component";
17
17
  import wt from "autoprefixer";
18
18
  import * as St from "esbuild";
19
- import { readFileSync as J, existsSync as B, lstatSync as X, readdirSync as Et, rmSync as Ve, mkdtempSync as bt, mkdirSync as M, writeFileSync as te, renameSync as Ce, createWriteStream as It } from "fs";
19
+ import { readFileSync as J, existsSync as B, lstatSync as X, readdirSync as Et, rmSync as Ve, mkdtempSync as bt, mkdirSync as M, writeFileSync as te, renameSync as Pe, createWriteStream as It } from "fs";
20
20
  import Ot from "postcss";
21
- import At from "tailwindcss";
21
+ import vt from "tailwindcss";
22
22
  import x from "typescript";
23
- import { reactive as vt } from "@reactivedata/reactive";
23
+ import { reactive as At } from "@reactivedata/reactive";
24
24
  import { syncedStore as Tt, getYjsValue as le } from "@syncedstore/core";
25
25
  import { globSync as me } from "glob";
26
26
  import * as pe from "lib0/decoding";
27
- import * as C from "lib0/encoding";
28
- import { get as ye, isEmpty as Ct, set as Pe, debounce as Ge, pick as Pt, union as xt, cloneDeep as jt } from "lodash";
27
+ import * as P from "lib0/encoding";
28
+ import { get as ye, isEmpty as Pt, set as Ce, debounce as Ge, pick as Ct, union as xt, cloneDeep as jt } from "lodash";
29
29
  import { customAlphabet as kt } from "nanoid";
30
30
  import Nt from "p-limit";
31
31
  import Dt, { join as O, dirname as L, basename as G } from "path";
@@ -45,7 +45,7 @@ w.env.INIT_TEMPLATE_PATH;
45
45
  const Wt = ee.env.DATABASE_URL || Dt.join(w.env.dataDir, "db/pages-kit.db"), je = w, no = () => w.env.tenantMode === "multiple", ro = () => {
46
46
  var t;
47
47
  return (Gt(je.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = je.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
48
- }, A = dt("pages-kit"), zt = T.sqlite.DATE.parse;
48
+ }, v = dt("pages-kit"), zt = T.sqlite.DATE.parse;
49
49
  T.sqlite.DATE.parse = (t, s) => typeof t == "number" ? new Date(t) : zt(t, s);
50
50
  const z = new Jt({
51
51
  dialect: "sqlite",
@@ -143,7 +143,7 @@ const Yt = async (t, { componentId: s }) => {
143
143
  @tailwind utilities;
144
144
  `, o = `.CustomComponent_${s}`;
145
145
  return (await Ot([
146
- At({ content: [{ raw: t, extension: "tsx" }] }),
146
+ vt({ content: [{ raw: t, extension: "tsx" }] }),
147
147
  wt({
148
148
  overrideBrowserslist: ["> 1%", "last 2 versions"],
149
149
  stats: {}
@@ -294,11 +294,11 @@ var ${t} = ${e ? "async" : ""} function () {
294
294
  max: 100
295
295
  }), Zt = 60 * 60, Ne = 60;
296
296
  function es(t) {
297
- A.info("clear preload components cache", { cacheKey: t }), K.delete(t);
297
+ v.info("clear preload components cache", { cacheKey: t }), K.delete(t);
298
298
  }
299
299
  function ts(t) {
300
300
  for (const s of K.keys())
301
- s.includes(t) && (A.info("clear preload components cache", { cacheKey: s }), es(s));
301
+ s.includes(t) && (v.info("clear preload components cache", { cacheKey: s }), es(s));
302
302
  }
303
303
  function ss({
304
304
  mode: t,
@@ -331,28 +331,28 @@ async function ao({
331
331
  locale: o
332
332
  });
333
333
  if (t !== "draft" && g.useCache && K.has(y))
334
- return A.info(`get preload component from cache: ${y}`), K.get(y);
335
- const v = se({ state: e, componentId: g.componentId });
336
- if (!v) return null;
337
- const P = await os({
334
+ return v.info(`get preload component from cache: ${y}`), K.get(y);
335
+ const A = se({ state: e, componentId: g.componentId });
336
+ if (!A) return null;
337
+ const C = await os({
338
338
  req: s,
339
339
  state: e,
340
- componentId: v.id,
340
+ componentId: A.id,
341
341
  locale: o,
342
342
  defaultLocale: r,
343
343
  properties: g.properties
344
344
  });
345
- if (!P) return null;
346
- const k = { instanceId: g.id, preload: P };
345
+ if (!C) return null;
346
+ const k = { instanceId: g.id, preload: C };
347
347
  if (t !== "draft" && g.useCache) {
348
348
  let N = Zt;
349
- g.cacheDuration && (N = g.cacheDuration), A.info(`set preload component to cache(${N}s): ${y}`), K.set(y, k, {
349
+ g.cacheDuration && (N = g.cacheDuration), v.info(`set preload component to cache(${N}s): ${y}`), K.set(y, k, {
350
350
  ttl: N * 1e3
351
351
  });
352
352
  }
353
353
  return k;
354
354
  } catch (y) {
355
- return A.error("get preload component error", { instanceId: g.id, componentId: g.componentId }, { error: y }), null;
355
+ return v.error("get preload component error", { instanceId: g.id, componentId: g.componentId }, { error: y }), null;
356
356
  }
357
357
  })
358
358
  )).filter((g) => !!g), c = Object.values(
@@ -361,7 +361,7 @@ async function ao({
361
361
  async function p() {
362
362
  const g = await Promise.all(
363
363
  c.map(async (y) => {
364
- const v = nt({ componentId: y.component.id }), P = a === Q.ESM ? {
364
+ const A = nt({ componentId: y.component.id }), C = a === Q.ESM ? {
365
365
  module: a,
366
366
  script: await ke(y.script, {
367
367
  componentId: y.component.id,
@@ -373,12 +373,12 @@ async function ao({
373
373
  script: await ke(y.script, {
374
374
  componentId: y.component.id,
375
375
  module: a,
376
- moduleName: v,
376
+ moduleName: A,
377
377
  tailwind: t !== "draft"
378
378
  }),
379
- moduleName: v
379
+ moduleName: A
380
380
  };
381
- return [y.component.id, { component: y.component, script: P }];
381
+ return [y.component.id, { component: y.component, script: C }];
382
382
  })
383
383
  );
384
384
  return Object.fromEntries(g);
@@ -434,11 +434,11 @@ async function Ke({
434
434
  const p = await as({ ...r, req: t });
435
435
  p != null && p.props && Object.assign(c.props, p.props);
436
436
  } catch (p) {
437
- A.error("preload data at server side error", { componentId: o, name: r.component.name }, { error: p });
437
+ v.error("preload data at server side error", { componentId: o, name: r.component.name }, { error: p });
438
438
  }
439
439
  return await Promise.all(
440
440
  Object.entries(i).map(async ([p, u]) => {
441
- if ((u == null ? void 0 : u.type) === Ae) {
441
+ if ((u == null ? void 0 : u.type) === ve) {
442
442
  const f = await Ke({
443
443
  req: t,
444
444
  depth: s + 1,
@@ -450,7 +450,7 @@ async function Ke({
450
450
  });
451
451
  f && (Object.assign(c.components, f.components), Object.assign(c.props, {
452
452
  [p]: {
453
- type: Ae,
453
+ type: ve,
454
454
  componentId: u.componentId,
455
455
  props: f.props
456
456
  }
@@ -499,17 +499,15 @@ async function as({
499
499
  }) {
500
500
  const n = await He(s, "getServerSideProps");
501
501
  if (!n) return null;
502
- let a = new AbortController();
503
- const l = new Promise((r, i) => {
502
+ const a = new Promise((r, i) => {
504
503
  setTimeout(() => {
505
- i(new Error("getServerSideProps timeout in promise race")), a && (a.abort(), a = null);
504
+ i(new Error("getServerSideProps timeout in promise race"));
506
505
  }, Ne * 1e3);
507
506
  });
508
- try {
509
- return await Promise.race([
510
- l,
511
- $e.callFunction({
512
- code: `${n}
507
+ return await Promise.race([
508
+ a,
509
+ $e.callFunction({
510
+ code: `${n}
513
511
 
514
512
  export async function getServerSidePropsWrapper(props) {
515
513
  const { location, fetch } = props;
@@ -527,68 +525,65 @@ export async function getServerSidePropsWrapper(props) {
527
525
  if (originalFetch) globalThis.fetch = originalFetch;
528
526
  }
529
527
  }`,
530
- filename: `${t.name || t.id}.js`,
531
- moduleLoader: (r) => {
532
- if (r === "@blocklet/pages-kit/builtin/utils")
533
- return `const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
528
+ filename: `${t.name || t.id}.js`,
529
+ moduleLoader: (r) => {
530
+ if (r === "@blocklet/pages-kit/builtin/utils")
531
+ return `const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
534
532
  export { joinURL, withQuery, getQuery, getComponentMountPoint }
535
533
  `;
536
- if (r === "@blocklet/pages-kit/builtin/dayjs")
537
- return at.dayjs;
538
- },
539
- global: {
540
- console: {
541
- // NOTE: do not return logger.xxx result, it will cause memory leak
542
- // eslint-disable-next-line prettier/prettier
543
- log: (...r) => {
544
- A.info(...r);
545
- },
546
- warn: (...r) => {
547
- A.warn(...r);
548
- },
549
- error: (...r) => {
550
- A.error(...r);
551
- }
534
+ if (r === "@blocklet/pages-kit/builtin/dayjs")
535
+ return at.dayjs;
536
+ },
537
+ global: {
538
+ console: {
539
+ // NOTE: do not return logger.xxx result, it will cause memory leak
540
+ // eslint-disable-next-line prettier/prettier
541
+ log: (...r) => {
542
+ v.info(...r);
543
+ },
544
+ warn: (...r) => {
545
+ v.warn(...r);
552
546
  },
553
- getComponentMountPoint: ot,
554
- joinURL: U,
555
- withQuery: ut,
556
- getQuery: pt
547
+ error: (...r) => {
548
+ v.error(...r);
549
+ }
557
550
  },
558
- functionName: "getServerSidePropsWrapper",
559
- args: [
560
- {
561
- // NOTE: IMPORTANT! place location and fetch (has side effect) at the args not global
562
- // because the global is shared between all runtime and just init once
563
- location: { href: U(lt(o.hostname), o.originalUrl) },
564
- fetch: (r, { ...i } = {}) => {
565
- const c = typeof r == "string" && r.startsWith("/") ? U(w.env.appUrl, r) : r;
566
- if (typeof c == "string" && ve(c).host === ve(w.env.appUrl).host) {
567
- const p = o.get("cookie");
568
- if (p) {
569
- const u = new ct(i.headers);
570
- u.set("cookie", p), i.headers = u;
571
- }
551
+ getComponentMountPoint: ot,
552
+ joinURL: U,
553
+ withQuery: pt,
554
+ getQuery: lt
555
+ },
556
+ functionName: "getServerSidePropsWrapper",
557
+ args: [
558
+ {
559
+ // NOTE: IMPORTANT! place location and fetch (has side effect) at the args not global
560
+ // because the global is shared between all runtime and just init once
561
+ location: { href: U(ut(o.hostname), o.originalUrl) },
562
+ fetch: (r, { ...i } = {}) => {
563
+ const c = typeof r == "string" && r.startsWith("/") ? U(w.env.appUrl, r) : r;
564
+ if (typeof c == "string" && Ae(c).host === Ae(w.env.appUrl).host) {
565
+ const p = o.get("cookie");
566
+ if (p) {
567
+ const u = new ct(i.headers);
568
+ u.set("cookie", p), i.headers = u;
572
569
  }
573
- return it(c, {
574
- ...i,
575
- timeout: Ne * 1e3
576
- }).then((p) => ({
577
- ok: p.ok,
578
- status: p.status,
579
- statusText: p.statusText,
580
- headers: Object.fromEntries(p.headers.entries()),
581
- json: () => p.json()
582
- }));
583
- },
584
- props: e
585
- }
586
- ]
587
- })
588
- ]);
589
- } finally {
590
- a = null;
591
- }
570
+ }
571
+ return it(c, {
572
+ ...i,
573
+ timeout: Ne * 1e3
574
+ }).then((p) => ({
575
+ ok: p.ok,
576
+ status: p.status,
577
+ statusText: p.statusText,
578
+ headers: Object.fromEntries(p.headers.entries()),
579
+ json: () => p.json()
580
+ }));
581
+ },
582
+ props: e
583
+ }
584
+ ]
585
+ })
586
+ ]);
592
587
  }
593
588
  const is = ae(
594
589
  async (t, s, e) => {
@@ -607,7 +602,7 @@ const is = ae(
607
602
  functionName: `get${s}SchemaWrapper`
608
603
  });
609
604
  } catch (n) {
610
- return A.error(`获取 ${s} 失败`, { componentId: e, error: n }), null;
605
+ return v.error(`获取 ${s} 失败`, { componentId: e, error: n }), null;
611
606
  }
612
607
  return null;
613
608
  },
@@ -649,14 +644,14 @@ const _ = class _ extends $.Doc {
649
644
  c.delete(p);
650
645
  }));
651
646
  }
652
- const r = C.createEncoder();
653
- C.writeVarUint(r, ue), C.writeVarUint8Array(r, xe(this.awareness, l));
654
- const i = C.toUint8Array(r);
647
+ const r = P.createEncoder();
648
+ P.writeVarUint(r, ue), P.writeVarUint8Array(r, xe(this.awareness, l));
649
+ const i = P.toUint8Array(r);
655
650
  this.conns.forEach((c, p) => this.send(p, i));
656
651
  }, this.updateHandler = (e) => {
657
- const o = C.createEncoder();
658
- C.writeVarUint(o, Y), $t(o, e);
659
- const n = C.toUint8Array(o);
652
+ const o = P.createEncoder();
653
+ P.writeVarUint(o, Y), $t(o, e);
654
+ const n = P.toUint8Array(o);
660
655
  this.conns.forEach((a, l) => this.send(l, n));
661
656
  }, this.ensureDataStructure = () => {
662
657
  var l;
@@ -741,33 +736,33 @@ const _ = class _ extends $.Doc {
741
736
  o = !0;
742
737
  });
743
738
  {
744
- const a = C.createEncoder();
745
- C.writeVarUint(a, Y), Bt(a, this), this.send(e, C.toUint8Array(a));
739
+ const a = P.createEncoder();
740
+ P.writeVarUint(a, Y), Bt(a, this), this.send(e, P.toUint8Array(a));
746
741
  const l = this.awareness.getStates();
747
742
  if (l.size > 0) {
748
- const r = C.createEncoder();
749
- C.writeVarUint(r, ue), C.writeVarUint8Array(r, xe(this.awareness, Array.from(l.keys()))), this.send(e, C.toUint8Array(r));
743
+ const r = P.createEncoder();
744
+ P.writeVarUint(r, ue), P.writeVarUint8Array(r, xe(this.awareness, Array.from(l.keys()))), this.send(e, P.toUint8Array(r));
750
745
  }
751
746
  }
752
747
  }, this.messageListener = (e, o) => {
753
748
  try {
754
- const n = C.createEncoder(), a = pe.createDecoder(o), l = pe.readVarUint(a);
749
+ const n = P.createEncoder(), a = pe.createDecoder(o), l = pe.readVarUint(a);
755
750
  switch (l) {
756
751
  case Y:
757
- C.writeVarUint(n, Y), Vt(a, n, this, null), C.length(n) > 1 && (this.ensureDataStructure(), this.send(e, C.toUint8Array(n)));
752
+ P.writeVarUint(n, Y), Vt(a, n, this, null), P.length(n) > 1 && (this.ensureDataStructure(), this.send(e, P.toUint8Array(n)));
758
753
  break;
759
754
  case ue: {
760
755
  Mt(this.awareness, pe.readVarUint8Array(a), e);
761
756
  break;
762
757
  }
763
758
  default:
764
- A.warn(`Unsupported messageType ${l}`);
759
+ v.warn(`Unsupported messageType ${l}`);
765
760
  }
766
761
  } catch (n) {
767
- A.error(n);
762
+ v.error(n);
768
763
  }
769
764
  this.save();
770
- }, B(this.draftYjsFilePath) && $.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore = vt(
765
+ }, B(this.draftYjsFilePath) && $.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore = At(
771
766
  Tt(
772
767
  { pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
773
768
  this
@@ -780,9 +775,9 @@ const _ = class _ extends $.Doc {
780
775
  throw new Error("Should provide project context");
781
776
  try {
782
777
  const e = O(q, s), o = O(q, `@del-${s}`);
783
- Ce(e, o);
778
+ Pe(e, o);
784
779
  } catch (e) {
785
- A.error("Failed to safe delete project state dir:", e);
780
+ v.error("Failed to safe delete project state dir:", e);
786
781
  }
787
782
  }
788
783
  static get projectIds() {
@@ -842,15 +837,15 @@ const _ = class _ extends $.Doc {
842
837
  ...this.states[s],
843
838
  resources: await tt().then(async (l) => {
844
839
  var p, u, f, g;
845
- const { pages: r, components: i } = Pt(l, "pages", "components");
840
+ const { pages: r, components: i } = Ct(l, "pages", "components");
846
841
  let c = i;
847
842
  if ((u = (p = this.states[s]) == null ? void 0 : p.resources) != null && u.components)
848
843
  c = {
849
844
  ...(g = (f = this.states[s]) == null ? void 0 : f.resources) == null ? void 0 : g.components
850
845
  };
851
846
  else {
852
- const y = G(this.options.path), v = await F.findByPk(y);
853
- if (v != null && v.useAllResources)
847
+ const y = G(this.options.path), A = await F.findByPk(y);
848
+ if (A != null && A.useAllResources)
854
849
  c = i;
855
850
  else {
856
851
  const k = (await ce.findAll({ where: { projectId: y } })).map((h) => h.componentId);
@@ -865,7 +860,7 @@ const _ = class _ extends $.Doc {
865
860
  }
866
861
  async setState(s, e) {
867
862
  const o = await Ss(e, { exportAssets: !1, includeResources: !0 }), n = this.getPublishDir(s);
868
- M(L(n), { recursive: !0 }), Ve(n, { force: !0, recursive: !0 }), Ce(o, n), this.states[s] = e;
863
+ M(L(n), { recursive: !0 }), Ve(n, { force: !0, recursive: !0 }), Pe(o, n), this.states[s] = e;
869
864
  }
870
865
  getPublishDir(s) {
871
866
  return O(this.options.path, s);
@@ -958,7 +953,7 @@ const ys = async (t, s) => {
958
953
  try {
959
954
  await ys(e, O(s, G(e)));
960
955
  } catch (o) {
961
- A.error(`Failed to export assets: ${e}, ${o}`);
956
+ v.error(`Failed to export assets: ${e}, ${o}`);
962
957
  }
963
958
  })
964
959
  );
@@ -993,16 +988,16 @@ async function _e(t, s, e) {
993
988
  try {
994
989
  const c = ye(t, i), p = qe(c);
995
990
  for (const u of p) {
996
- const f = G(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f, v = Ue.get(y);
997
- if (v) {
998
- W.test(c) || Pe(t, i, v);
991
+ const f = G(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f, A = Ue.get(y);
992
+ if (A) {
993
+ W.test(c) || Ce(t, i, A);
999
994
  return;
1000
995
  }
1001
- const P = await hs(g, f, s);
1002
- P && (W.test(c) || Pe(t, i, P), Ue.set(y, P));
996
+ const C = await hs(g, f, s);
997
+ C && (W.test(c) || Ce(t, i, C), Ue.set(y, C));
1003
998
  }
1004
999
  } catch (c) {
1005
- A.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
1000
+ v.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
1006
1001
  }
1007
1002
  })
1008
1003
  ), l = await Promise.allSettled(a);
@@ -1077,7 +1072,7 @@ async function Ss(t, {
1077
1072
  }
1078
1073
  const y = O(u, ".blocklet/pages/pages.config.yml");
1079
1074
  M(L(y), { recursive: !0 });
1080
- const v = {
1075
+ const A = {
1081
1076
  pages: R(
1082
1077
  l.map((m) => {
1083
1078
  const d = t.pages[m];
@@ -1110,9 +1105,9 @@ async function Ss(t, {
1110
1105
  supportedLocales: t.supportedLocales,
1111
1106
  config: t.config
1112
1107
  };
1113
- te(y, H.stringify(v));
1114
- const P = O(u, "config.source.json");
1115
- if (n && te(P, JSON.stringify(n)), a) {
1108
+ te(y, H.stringify(A));
1109
+ const C = O(u, "config.source.json");
1110
+ if (n && te(C, JSON.stringify(n)), a) {
1116
1111
  const m = O(u, "resources"), d = O(m, "components");
1117
1112
  M(d, { recursive: !0 });
1118
1113
  for (const S of Object.keys(((h = t == null ? void 0 : t.resources) == null ? void 0 : h.components) ?? {})) {
@@ -1143,10 +1138,10 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
1143
1138
  const E = me(`*.${b}.yml`, { cwd: h, absolute: !0 })[0];
1144
1139
  return E ? H.parse(J(E).toString()) : null;
1145
1140
  } catch (E) {
1146
- A.error("parse component error", E);
1141
+ v.error("parse component error", E);
1147
1142
  }
1148
1143
  return null;
1149
- }, v = R(
1144
+ }, A = R(
1150
1145
  f.pages.map(({ slug: h }) => {
1151
1146
  var m;
1152
1147
  const b = R(
@@ -1192,10 +1187,10 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
1192
1187
  locales: Object.fromEntries(b.map(({ locale: d, page: S }) => [d, S.meta]))
1193
1188
  };
1194
1189
  })
1195
- ), P = p ? R(((a = f.components) == null ? void 0 : a.map(({ id: h }) => y(p, h))) ?? []) : [];
1190
+ ), C = p ? R(((a = f.components) == null ? void 0 : a.map(({ id: h }) => y(p, h))) ?? []) : [];
1196
1191
  if (s) {
1197
1192
  const h = (...b) => {
1198
- A.info(`[${n ? G(t) : G(O(t, "../../../../"))}] importAssets:`, ...b);
1193
+ v.info(`[${n ? G(t) : G(O(t, "../../../../"))}] importAssets:`, ...b);
1199
1194
  };
1200
1195
  try {
1201
1196
  h("wait image-bin api ready"), await Ut({
@@ -1204,15 +1199,15 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
1204
1199
  }), h("image-bin api is ready");
1205
1200
  const b = {}, E = {};
1206
1201
  h("start to upload assets"), await Promise.allSettled([
1207
- _e(P, b, {
1202
+ _e(C, b, {
1208
1203
  getFilePath: (I) => p && O(p, I),
1209
1204
  onFinish: (I) => {
1210
1205
  h(`upload ${I.length} component assets`);
1211
1206
  }
1212
1207
  }),
1213
- _e(v, E, {
1208
+ _e(A, E, {
1214
1209
  getFilePath: (I, m) => {
1215
- const d = ye(v, m.slice(0, 1));
1210
+ const d = ye(A, m.slice(0, 1));
1216
1211
  return c && O(c, L(d.slug), I);
1217
1212
  },
1218
1213
  onFinish: (I) => {
@@ -1241,9 +1236,9 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
1241
1236
  }
1242
1237
  return {
1243
1238
  supportedLocales: f.supportedLocales,
1244
- pageIds: v.map((h) => h.id),
1245
- components: Object.fromEntries(P.map((h, b) => [h.id, { index: b, data: h }])),
1246
- pages: Object.fromEntries(v.map((h) => [h.id, h])),
1239
+ pageIds: A.map((h) => h.id),
1240
+ components: Object.fromEntries(C.map((h, b) => [h.id, { index: b, data: h }])),
1241
+ pages: Object.fromEntries(A.map((h) => [h.id, h])),
1247
1242
  config: f.config || {},
1248
1243
  resources: k,
1249
1244
  chunks: N
@@ -1261,7 +1256,7 @@ async function Me(t, s, {
1261
1256
  try {
1262
1257
  a && ts(a);
1263
1258
  } catch (p) {
1264
- A.error("clear preload page cache error", { error: p });
1259
+ v.error("clear preload page cache error", { error: p });
1265
1260
  }
1266
1261
  const { pageIds: l, pages: r, supportedLocales: i } = t;
1267
1262
  for (const p of e ?? l) {
@@ -1306,7 +1301,7 @@ async function Me(t, s, {
1306
1301
  const Xe = ae(
1307
1302
  async (t) => {
1308
1303
  var s;
1309
- if (!Ct(t == null ? void 0 : t.properties))
1304
+ if (!Pt(t == null ? void 0 : t.properties))
1310
1305
  return t;
1311
1306
  if (((s = t == null ? void 0 : t.renderer) == null ? void 0 : s.type) === "react-component") {
1312
1307
  const { script: e } = (t == null ? void 0 : t.renderer) || {};
@@ -1320,7 +1315,7 @@ const Xe = ae(
1320
1315
  });
1321
1316
  }));
1322
1317
  } catch (o) {
1323
- A.error("checkPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: o });
1318
+ v.error("checkPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: o });
1324
1319
  }
1325
1320
  }
1326
1321
  return t;
@@ -1411,7 +1406,7 @@ function bs(t) {
1411
1406
  const s = Ge(
1412
1407
  async () => {
1413
1408
  await Ze().catch((e) => {
1414
- A.error("load resource states error", { error: e });
1409
+ v.error("load resource states error", { error: e });
1415
1410
  }), await (t == null ? void 0 : t({
1416
1411
  states: V,
1417
1412
  pages: Se,
@@ -1444,7 +1439,7 @@ Z[et] = bs(async ({ pages: t, components: s }) => {
1444
1439
  );
1445
1440
  n.syncedStore.resources.components = i;
1446
1441
  }
1447
- A.info(`update [${o}] resource states:`, {
1442
+ v.info(`update [${o}] resource states:`, {
1448
1443
  pages: Object.keys(n.syncedStore.resources.pages || {}).length,
1449
1444
  components: Object.keys(n.syncedStore.resources.components || {}).length
1450
1445
  });
@@ -1452,7 +1447,7 @@ Z[et] = bs(async ({ pages: t, components: s }) => {
1452
1447
  );
1453
1448
  });
1454
1449
  async function po() {
1455
- A.info("trigger reload all project resource"), w.events.emit(fe);
1450
+ v.info("trigger reload all project resource"), w.events.emit(fe);
1456
1451
  }
1457
1452
  async function tt({
1458
1453
  ensureLoaded: t = !0
@@ -1476,7 +1471,7 @@ export {
1476
1471
  no as i,
1477
1472
  se as j,
1478
1473
  io as k,
1479
- A as l,
1474
+ v as l,
1480
1475
  is as m,
1481
1476
  Le as n,
1482
1477
  q as o,
@@ -7,7 +7,7 @@ import "lru-cache";
7
7
  import "node-fetch";
8
8
  import "ufo";
9
9
  import "crypto";
10
- import { c as _, G as E, d as i, e as d, j as l, k as N, m as O, h as P, b as c, f as g } from "./_chunks/site-state-D28bWM8J.js";
10
+ import { c as _, G as E, d as i, e as d, j as l, k as N, m as O, h as P, b as c, f as g } from "./_chunks/site-state-B0nM69Rk.js";
11
11
  export {
12
12
  _ as CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS,
13
13
  E as GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS,
@@ -1,117 +1,117 @@
1
- import I from "vite-plugin-node-polyfills/shims/process";
2
- import { b as W, l as P } from "./_chunks/site-state-D28bWM8J.js";
3
- import { initCronCrawlBlocklet as N, cancelCronCrawlBlocklet as J, initSEOMiddleware as G } from "@blocklet/crawler/middlewares";
4
- import { PreloadComponentScriptModule as K } from "@blocklet/pages-kit/types";
5
- import { injectPreloadComponents as Q } from "@blocklet/pages-kit/utils/preload";
6
- import { getComponentMountPoint as z } from "@blocklet/sdk/lib/component";
7
- import a, { getBlockletJs as V } from "@blocklet/sdk/lib/config";
8
- import * as j from "cheerio";
9
- import { Router as X } from "express";
10
- import { readFileSync as U } from "fs";
11
- import Y from "mustache";
12
- import { resolve as M } from "path";
13
- import { withQuery as Z, joinURL as D } from "ufo";
14
- const F = ["/assets/"], O = () => [!0, "true"].includes(a.env.preferences.allowCrawler);
15
- function R() {
16
- O() ? N({
1
+ import A from "vite-plugin-node-polyfills/shims/process";
2
+ import { b as B, l as v } from "./_chunks/site-state-B0nM69Rk.js";
3
+ import { initCronCrawlBlocklet as H, cancelCronCrawlBlocklet as N, initSEOMiddleware as J } from "@blocklet/crawler/middlewares";
4
+ import { PreloadComponentScriptModule as G } from "@blocklet/pages-kit/types";
5
+ import { injectPreloadComponents as W } from "@blocklet/pages-kit/utils/preload";
6
+ import { getComponentMountPoint as K } from "@blocklet/sdk/lib/component";
7
+ import p, { getBlockletJs as Q } from "@blocklet/sdk/lib/config";
8
+ import { Router as z } from "express";
9
+ import { readFileSync as I } from "fs";
10
+ import V from "mustache";
11
+ import { resolve as j } from "path";
12
+ import { withQuery as X, joinURL as M } from "ufo";
13
+ const Y = ["/assets/"], U = () => [!0, "true"].includes(p.env.preferences.allowCrawler);
14
+ function x() {
15
+ U() ? H({
17
16
  time: "30 30 */12 * * *",
18
17
  options: {}
19
- }) : J();
18
+ }) : N();
20
19
  }
21
- R();
22
- a.events.on(a.Events.envUpdate, R);
23
- function ue({
24
- app: i,
25
- viteDevServer: u,
20
+ x();
21
+ p.events.on(p.Events.envUpdate, x);
22
+ function me({
23
+ app: s,
24
+ viteDevServer: h,
26
25
  // projectId,
27
26
  state: n
28
27
  }) {
29
- let C;
30
- if (u) {
31
- const t = U(M(I.cwd(), "./index.html"), "utf-8");
32
- i.use(async (b, $, y) => {
33
- const _ = b.originalUrl;
34
- C = await u.transformIndexHtml(_, t), y();
28
+ let w;
29
+ if (h) {
30
+ const t = I(j(A.cwd(), "./index.html"), "utf-8");
31
+ s.use(async (k, P, b) => {
32
+ const y = k.originalUrl;
33
+ w = await h.transformIndexHtml(y, t), b();
35
34
  });
36
35
  } else
37
- C = U(M(I.env.BLOCKLET_APP_DIR, "dist/index.html"), "utf-8");
38
- const k = X();
39
- k.use(
40
- G({
36
+ w = I(j(A.env.BLOCKLET_APP_DIR, "dist/index.html"), "utf-8");
37
+ const C = z();
38
+ C.use(
39
+ J({
41
40
  autoReturnHtml: !1,
42
- allowCrawler: O
41
+ allowCrawler: U
43
42
  })
44
- ), k.get("/:path(*)?", async (t, b, $) => {
45
- var T, S, L;
46
- if (F.some((r) => t.path.startsWith(r))) {
47
- $();
43
+ ), C.get("/:path(*)?", async (t, k, P) => {
44
+ var E, S, T;
45
+ if (Y.some((c) => t.path.startsWith(c))) {
46
+ P();
48
47
  return;
49
48
  }
50
- const y = performance.now(), _ = () => Math.round(performance.now() - y), x = "production";
51
- let e, p, h = C;
49
+ const b = performance.now(), y = () => Math.round(performance.now() - b), R = "production";
50
+ let e, d, r = w;
52
51
  if (t.path.startsWith("/pages")) {
53
- const r = t.params.lang, f = t.cookies.nf_lang, g = /* @__PURE__ */ new Set([...a.env.languages.map((d) => d.code)]);
54
- let m = (r && g.has(r) ? r : void 0) || (g.has(f) ? f : void 0) || [...g][0];
55
- if ((!m || !((T = n.supportedLocales) != null && T.find((d) => d.locale === m))) && (m = ((L = (S = n.supportedLocales) == null ? void 0 : S[0]) == null ? void 0 : L.locale) || ""), m) {
56
- const d = [];
52
+ const c = t.params.lang, i = t.cookies.nf_lang, m = /* @__PURE__ */ new Set([...p.env.languages.map((f) => f.code)]);
53
+ let u = (c && m.has(c) ? c : void 0) || (m.has(i) ? i : void 0) || [...m][0];
54
+ if ((!u || !((E = n.supportedLocales) != null && E.find((f) => f.locale === u))) && (u = ((T = (S = n.supportedLocales) == null ? void 0 : S[0]) == null ? void 0 : T.locale) || ""), u) {
55
+ const f = [];
57
56
  Object.values(n.pages).forEach((l) => {
58
- const v = Object.values((l == null ? void 0 : l.sections) ?? {}).filter(
59
- (s) => {
60
- var w;
61
- return s.component === "custom-component" && ((w = s.config) == null ? void 0 : w.componentId);
57
+ const _ = Object.values((l == null ? void 0 : l.sections) ?? {}).filter(
58
+ (a) => {
59
+ var g;
60
+ return a.component === "custom-component" && ((g = a.config) == null ? void 0 : g.componentId);
62
61
  }
63
- ).map((s) => {
64
- var w, A;
62
+ ).map((a) => {
63
+ var g, L;
65
64
  return {
66
- id: s.id,
67
- componentId: s.config.componentId,
68
- useCache: s.config.useCache,
69
- cacheDuration: s.config.cacheDuration,
70
- properties: (A = (w = s.locales) == null ? void 0 : w[m]) == null ? void 0 : A.properties
65
+ id: a.id,
66
+ componentId: a.config.componentId,
67
+ useCache: a.config.useCache,
68
+ cacheDuration: a.config.cacheDuration,
69
+ properties: (L = (g = a.locales) == null ? void 0 : g[u]) == null ? void 0 : L.properties
71
70
  };
72
71
  });
73
- d.push(...v);
72
+ f.push(..._);
74
73
  });
75
- const H = new Promise((l, v) => {
74
+ const O = new Promise((l, _) => {
76
75
  setTimeout(() => {
77
- v(new Error("getPreloadComponents timeout in promise race, skip it"));
76
+ _(new Error("getPreloadComponents timeout in promise race, skip it"));
78
77
  }, 90 * 1e3);
79
78
  });
80
79
  try {
81
80
  await Promise.race([
82
- H,
83
- W({
84
- mode: x,
81
+ O,
82
+ B({
83
+ mode: R,
85
84
  req: t,
86
85
  state: n,
87
- locale: m,
88
- instances: d,
89
- module: K.UMD_FN
86
+ locale: u,
87
+ instances: f,
88
+ module: G.UMD_FN
90
89
  }).then((l) => {
91
- l && (p = Q(l));
90
+ l && (d = W(l));
92
91
  })
93
92
  ]);
94
93
  } catch (l) {
95
- P.warn("getPreloadComponents timeout in promise race, skip inject html elements"), P.warn(l);
94
+ v.warn("getPreloadComponents timeout in promise race, skip inject html elements"), v.warn(l);
96
95
  }
97
96
  }
98
97
  }
99
98
  try {
100
- const r = (e == null ? void 0 : e.title) || a.env.appName, f = (e == null ? void 0 : e.description) || a.env.appDescription, g = Z(D(a.env.appUrl, "/.well-known/service/blocklet/og.png"), {
101
- title: r,
102
- description: f
99
+ const c = (e == null ? void 0 : e.title) || p.env.appName, i = (e == null ? void 0 : e.description) || p.env.appDescription, m = X(M(p.env.appUrl, "/.well-known/service/blocklet/og.png"), {
100
+ title: c,
101
+ description: i
103
102
  });
104
- h = Y.render(C, {
105
- ogTitle: r,
106
- ogDescription: f,
107
- ogImage: q(e == null ? void 0 : e.image) || g,
103
+ r = V.render(w, {
104
+ ogTitle: c,
105
+ ogDescription: i,
106
+ ogImage: Z(e == null ? void 0 : e.image) || m,
108
107
  pagesPublishedAt: (n == null ? void 0 : n.config.publishedAt) || (/* @__PURE__ */ new Date()).getTime()
109
108
  });
110
109
  } catch {
111
110
  }
112
- const o = n == null ? void 0 : n.config.fontFamily, B = t.query.mode === "draft" || t.url.includes("preview");
113
- let c = j.load(h);
114
- c("head").find("#injected-head-elements").replaceWith(`
111
+ const o = n == null ? void 0 : n.config.fontFamily, D = t.query.mode === "draft" || t.url.includes("preview");
112
+ r = r.replace(
113
+ '<script id="injected-head-elements"><\/script>',
114
+ `
115
115
  ${e != null && e.backgroundColor ? `<meta name="theme-color" content="${e.backgroundColor}" /><style>html,body,#app {background-color: ${e.backgroundColor} !important;}</style>` : ""}
116
116
  ${o != null && o.title ? `<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${o.title}&display=swap">` : ""}
117
117
  ${o != null && o.description && (o == null ? void 0 : o.description) !== (o == null ? void 0 : o.title) ? `<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${o.description}&display=swap">` : ""}
@@ -127,25 +127,26 @@ function ue({
127
127
  });
128
128
  <\/script>
129
129
 
130
- ${B ? `<script src="https://cdn.tailwindcss.com"><\/script>
130
+ ${D ? `<script src="https://cdn.tailwindcss.com"><\/script>
131
131
  <script>
132
132
  window.tailwind.config = {
133
133
  darkMode: "class",
134
134
  };
135
135
  <\/script>` : ""}
136
- `);
137
- const E = V();
138
- if (E && c('script[src="__blocklet__.js"]').replaceWith(`<script>${E}<\/script>`), p != null && p.html && c("head").find("#injected-html-elements").replaceWith(p.html), t.cachedHtml) {
139
- const r = j.load(t.cachedHtml);
140
- c("body").html(r("body").html() || "");
136
+ `
137
+ );
138
+ const $ = Q();
139
+ if ($ && (r = r.replace('<script src="__blocklet__.js"><\/script>', `<script>${$}<\/script>`)), d != null && d.html && (r = r.replace('<script id="injected-html-elements"><\/script>', d.html)), t.cachedHtml) {
140
+ const c = /<body>([\s\S]*?)<\/body>/, i = c.exec(t.cachedHtml), m = i ? i[1] : "";
141
+ r = r.replace(c, `<body>${m}</body>`);
141
142
  }
142
- h = c.html(), b.send(h), P.info(`[html] render: ${t.path}, ${_()}ms`), c.root().children().remove(), c = null, c = null, h = null, e = null, p = null;
143
- }), i.use(k);
143
+ k.send(r), v.info(`[html] render: ${t.path}, ${y()}ms`), r = null, e = null, d = null;
144
+ }), s.use(C);
144
145
  }
145
- function q(i) {
146
- const u = z("image-bin");
147
- return u && i && !/^(https?:\/\/|\/)/.test(i) ? a.env.appUrl + D(u, "uploads", i) : i;
146
+ function Z(s) {
147
+ const h = K("image-bin");
148
+ return h && s && !/^(https?:\/\/|\/)/.test(s) ? p.env.appUrl + M(h, "uploads", s) : s;
148
149
  }
149
150
  export {
150
- ue as default
151
+ me as default
151
152
  };
@@ -1,4 +1,4 @@
1
- import { P as S, i as b, g as M, l as x, C as J, R as X, S as N, t as W, a as G } from "./_chunks/site-state-D28bWM8J.js";
1
+ import { P as S, i as b, g as M, l as x, C as J, R as X, S as N, t as W, a as G } from "./_chunks/site-state-B0nM69Rk.js";
2
2
  import { AsyncLocalStorage as K } from "async_hooks";
3
3
  import { Router as Y } from "express";
4
4
  import d from "fs";
@@ -1,6 +1,6 @@
1
1
  import "vite-plugin-node-polyfills/shims/process";
2
2
  import "vite-plugin-node-polyfills/shims/global";
3
- import { q as H, o as M, p as O, S as j, r as q, a as v, u as B, s as L, n as U, t as b, v as h } from "./_chunks/site-state-D28bWM8J.js";
3
+ import { q as H, o as M, p as O, S as j, r as q, a as v, u as B, s as L, n as U, t as b, v as h } from "./_chunks/site-state-B0nM69Rk.js";
4
4
  import "@blocklet/quickjs";
5
5
  import "@blocklet/sdk/lib/component";
6
6
  import "@blocklet/sdk/lib/config";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blocklet/pages-kit-inner-components",
3
- "version": "0.4.24",
3
+ "version": "0.4.25",
4
4
  "description": "Pages Kit inner components library",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -202,8 +202,8 @@
202
202
  "yaml": "^2.5.0",
203
203
  "yjs": "^13.6.18",
204
204
  "zustand": "^4.5.5",
205
- "@blocklet/pages-kit-block-studio": "^0.4.24",
206
- "@blocklet/pages-kit": "^0.4.24"
205
+ "@blocklet/pages-kit": "^0.4.25",
206
+ "@blocklet/pages-kit-block-studio": "^0.4.25"
207
207
  },
208
208
  "devDependencies": {
209
209
  "@trivago/prettier-plugin-sort-imports": "^5.2.1",