@blocklet/pages-kit-inner-components 0.4.91 → 0.4.92

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";var ft=Object.defineProperty;var mt=(t,n,e)=>n in t?ft(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>mt(t,typeof n!="symbol"?n+"":n,e);const gt=require("@blocklet/pages-kit/builtin/utils"),ue=require("@blocklet/pages-kit/types"),se=require("@blocklet/pages-kit/utils/property"),K=require("@blocklet/quickjs"),ht=require("@blocklet/sdk/lib/config"),ve=require("lru-cache"),Je=require("node-fetch"),R=require("ufo"),me=require("crypto"),yt=require("@blocklet/logger"),St=require("@blocklet/pages-kit/utils/builtin"),Ke=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),De=require("@blocklet/sdk/lib/component"),wt=require("autoprefixer"),Et=require("esbuild"),h=require("fs"),bt=require("postcss"),Tt=require("tailwindcss"),Ct=require("typescript"),It=require("@reactivedata/reactive"),ce=require("@syncedstore/core"),Ce=require("glob"),Ot=require("lib0/decoding"),jt=require("lib0/encoding"),Pt=require("lodash/cloneDeep"),_t=require("lodash/debounce"),At=require("lodash/get"),vt=require("lodash/isEmpty"),Dt=require("lodash/pick"),xt=require("lodash/set"),kt=require("lodash/union"),Rt=require("nanoid"),Nt=require("p-limit"),d=require("path"),Lt=require("stream/promises"),Ut=require("tar"),Mt=require("wait-on"),W=require("y-protocols/awareness"),we=require("y-protocols/sync"),Ft=require("yaml"),qt=require("yjs"),$t=require("lodash/isNil"),O=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const D=t=>t&&t.__esModule?t:{default:t};function re(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,s.get?s:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const w=D(ht),Bt=D(Je),Ht=D(yt),Vt=D(wt),Gt=re(Et),zt=D(bt),Jt=D(Tt),k=D(Ct),Ee=re(Ot),v=re(jt),Kt=D(Pt),Ye=D(_t),xe=D(At),Yt=D(vt),Qt=D(Dt),qe=D(xt),Wt=D(kt),Xt=D(Nt),Zt=D(d),es=D(Mt),Z=re(Ft),J=re(qt),ts=D($t);w.default.env.mode;process.env.OPENAI_API_KEY;const ss="image-bin";w.default.env.INIT_TEMPLATE_PATH;const ns=process.env.DATABASE_URL||Zt.default.join(w.default.env.dataDir,"db/pages-kit.db"),$e=w.default,os=()=>w.default.env.tenantMode==="multiple",rs=()=>{var t;return(ts.default($e.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=$e.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},T=Ht.default("pages-kit"),as=O.DataTypes.sqlite.DATE.parse;O.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):as(t,n);const ae=new O.Sequelize({dialect:"sqlite",storage:ns,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});ae.query("pragma journal_mode = WAL;");ae.query("pragma synchronous = normal;");ae.query("pragma journal_size_limit = 67108864;");class ge extends O.Model{}ge.init({id:{type:O.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:O.DataTypes.UUIDV4},projectId:{type:O.DataTypes.UUID,allowNull:!1},componentId:{type:O.DataTypes.STRING,allowNull:!1}},{sequelize:ae,tableName:"ProjectComponents",timestamps:!1});class H extends O.Model{static async getProjectByIdOrSlug(n){return H.findOne({where:{[O.Op.or]:[{id:n},{slug:n}]}})}}H.init({id:{type:O.DataTypes.UUID,defaultValue:O.DataTypes.UUIDV4,primaryKey:!0},name:{type:O.DataTypes.STRING,allowNull:!1},description:O.DataTypes.TEXT,createdAt:O.DataTypes.DATE,updatedAt:O.DataTypes.DATE,createdBy:{type:O.DataTypes.STRING,allowNull:!1},updatedBy:{type:O.DataTypes.STRING,allowNull:!1},slug:O.DataTypes.STRING,icon:O.DataTypes.STRING,pinnedAt:O.DataTypes.DATE,useAllResources:O.DataTypes.BOOLEAN,npmSecret:O.DataTypes.STRING,relatedBlocklets:{type:O.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:ae,paranoid:!0});H.hasMany(ge,{foreignKey:"projectId",as:"components"});const is=async(t,{componentId:n})=>{const e=`@tailwind components;
1
+ "use strict";var ft=Object.defineProperty;var mt=(t,n,e)=>n in t?ft(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>mt(t,typeof n!="symbol"?n+"":n,e);const gt=require("@blocklet/pages-kit/builtin/utils"),ue=require("@blocklet/pages-kit/types"),se=require("@blocklet/pages-kit/utils/property"),K=require("@blocklet/quickjs"),ht=require("@blocklet/sdk/lib/config"),ve=require("lru-cache"),Je=require("node-fetch"),R=require("ufo"),me=require("crypto"),yt=require("@blocklet/logger"),St=require("@blocklet/pages-kit/utils/builtin"),Ke=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),De=require("@blocklet/sdk/lib/component"),wt=require("autoprefixer"),Et=require("esbuild"),h=require("fs"),bt=require("postcss"),Tt=require("tailwindcss"),It=require("typescript"),Ct=require("@reactivedata/reactive"),ce=require("@syncedstore/core"),Ie=require("glob"),Ot=require("lib0/decoding"),Pt=require("lib0/encoding"),_t=require("lodash/cloneDeep"),jt=require("lodash/debounce"),At=require("lodash/get"),vt=require("lodash/isEmpty"),Dt=require("lodash/pick"),xt=require("lodash/set"),kt=require("lodash/union"),Rt=require("nanoid"),Nt=require("p-limit"),d=require("path"),Lt=require("stream/promises"),Ut=require("tar"),Mt=require("wait-on"),W=require("y-protocols/awareness"),we=require("y-protocols/sync"),Ft=require("yaml"),qt=require("yjs"),$t=require("lodash/isNil"),O=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const D=t=>t&&t.__esModule?t:{default:t};function re(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,s.get?s:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const y=D(ht),Bt=D(Je),Ht=D(yt),Vt=D(wt),Gt=re(Et),zt=D(bt),Jt=D(Tt),k=D(It),Ee=re(Ot),v=re(Pt),Kt=D(_t),Ye=D(jt),xe=D(At),Yt=D(vt),Qt=D(Dt),qe=D(xt),Wt=D(kt),Xt=D(Nt),Zt=D(d),es=D(Mt),Z=re(Ft),J=re(qt),ts=D($t);y.default.env.mode;y.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;y.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;const ss="image-bin";y.default.env.INIT_TEMPLATE_PATH;const ns=process.env.DATABASE_URL||Zt.default.join(y.default.env.dataDir,"db/pages-kit.db"),$e=y.default,os=()=>y.default.env.tenantMode==="multiple",rs=()=>{var t;return(ts.default($e.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=$e.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},T=Ht.default("pages-kit"),as=O.DataTypes.sqlite.DATE.parse;O.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):as(t,n);const ae=new O.Sequelize({dialect:"sqlite",storage:ns,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});ae.query("pragma journal_mode = WAL;");ae.query("pragma synchronous = normal;");ae.query("pragma journal_size_limit = 67108864;");class ge extends O.Model{}ge.init({id:{type:O.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:O.DataTypes.UUIDV4},projectId:{type:O.DataTypes.UUID,allowNull:!1},componentId:{type:O.DataTypes.STRING,allowNull:!1}},{sequelize:ae,tableName:"ProjectComponents",timestamps:!1});class H extends O.Model{static async getProjectByIdOrSlug(n){return H.findOne({where:{[O.Op.or]:[{id:n},{slug:n}]}})}}H.init({id:{type:O.DataTypes.UUID,defaultValue:O.DataTypes.UUIDV4,primaryKey:!0},name:{type:O.DataTypes.STRING,allowNull:!1},description:O.DataTypes.TEXT,createdAt:O.DataTypes.DATE,updatedAt:O.DataTypes.DATE,createdBy:{type:O.DataTypes.STRING,allowNull:!1},updatedBy:{type:O.DataTypes.STRING,allowNull:!1},slug:O.DataTypes.STRING,icon:O.DataTypes.STRING,pinnedAt:O.DataTypes.DATE,useAllResources:O.DataTypes.BOOLEAN,npmSecret:O.DataTypes.STRING,relatedBlocklets:{type:O.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:ae,paranoid:!0});H.hasMany(ge,{foreignKey:"projectId",as:"components"});const is=async(t,{componentId:n})=>{const e=`@tailwind components;
2
2
  @tailwind utilities;
3
3
  `,s=`.CustomComponent_${n}`;return(await zt.default([Jt.default({content:[{raw:t,extension:"tsx"}]}),Vt.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),r=>{r.walkRules(l=>{l.selectors=l.selectors.map(a=>a.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(e)).css},cs=async(t,{componentId:n})=>{const e=await is(t,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(e)};
4
4
 
@@ -29,7 +29,7 @@ var ${t} = ${e?"async":""} function () {
29
29
 
30
30
  return exports;
31
31
  };
32
- `},ee=new ve.LRUCache({max:100}),We=60*60,Ie=60;function Xe(t){T.info("clear preload components cache",{cacheKey:t}),ee.delete(t)}function Ze(t){for(const n of ee.keys())n.includes(t)&&(T.info("clear preload components cache",{cacheKey:n}),Xe(n))}function et({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function ps({mode:t,req:n,state:e,locale:s,instances:o,module:r}){const{supportedLocales:l,config:{defaultLocale:a}}=e;if(!a)return null;const i=(await Promise.all(o.map(async g=>{try{const S=et({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&ee.has(S))return T.info(`get preload component from cache: ${S}`),ee.get(S);const _=ne({state:e,componentId:g.componentId});if(!_)return null;const x=await tt({req:n,state:e,componentId:_.id,locale:s,defaultLocale:a,properties:g.properties});if(!x)return null;const F={instanceId:g.id,preload:x};if(t!=="draft"&&g.useCache){let N=We;g.cacheDuration&&(N=g.cacheDuration),T.info(`set preload component to cache(${N}s): ${S}`),ee.set(S,F,{ttl:N*1e3})}return F}catch(S){return T.error("get preload component error",{instanceId:g.id,componentId:g.componentId},{error:S}),null}}))).filter(g=>!!g),c=Object.values(i.reduce((g,S)=>({...g,...S.preload.components}),{}));async function u(){const g=await Promise.all(c.map(async S=>{const _=se.componentUMDName({componentId:S.component.id}),x=r===ue.PreloadComponentScriptModule.ESM?{module:r,script:await Be(S.script,{componentId:S.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await Be(S.script,{componentId:S.component.id,module:r,moduleName:_,tailwind:t!=="draft"}),moduleName:_};return[S.component.id,{component:S.component,script:x}]}));return Object.fromEntries(g)}const p=await u();return{config:{defaultLocale:a,supportedLocales:l},components:p,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function tt({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:l}=n,a=ne({state:n,componentId:e});if(!a)return null;const i=l.some(u=>u.locale===s)?s:o;if(!i)return null;const c=await st({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const ds=20;async function st({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:l}){if(n>ds)throw new RangeError("max component depth exceeded");const a=fs({state:e,componentId:s,properties:l,locale:o});if(!a)return null;const{props:i}=a,c={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...i}};try{const u=await gs({...a,req:t});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){T.error("preload data at server side error",{componentId:s,name:a.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===se.RenderNestedComponent){const f=await st({req:t,depth:n+1,state:e,componentId:p.componentId,locale:o,defaultLocale:r,properties:p.properties});f&&(Object.assign(c.components,f.components),Object.assign(c.props,{[u]:{type:se.RenderNestedComponent,componentId:p.componentId,props:f.props}}))}})),c}function fs({state:t,componentId:n,locale:e,properties:s}){const o=ne({state:t,componentId:n});if(!o)return null;const r=se.mergeComponent({componentId:n,getComponent:l=>ne({state:t,componentId:l}),locale:e,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:e,...r.properties}}:null}function ne({state:t,componentId:n}){var e,s,o;return((e=t.components[n])==null?void 0:e.data)??((o=(s=t.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function ms({state:t,name:n}){var s,o;const e=n.toLowerCase();return((s=Object.values(t.components).find(r=>{var l;return((l=r.data.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:s.data)??((o=t.resources.components&&Object.values(t.resources.components).find(r=>{var l;return((l=r.component.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:o.component)}async function gs({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Qe(n,"getServerSideProps");if(!o)return null;const r=new Promise(a=>{setTimeout(()=>{a({})},Ie*1e3)});return await Promise.race([r,K.Sandbox.callFunction({code:`${o}
32
+ `},ee=new ve.LRUCache({max:100}),We=60*60,Ce=60;function Xe(t){T.info("clear preload components cache",{cacheKey:t}),ee.delete(t)}function Ze(t){for(const n of ee.keys())n.includes(t)&&(T.info("clear preload components cache",{cacheKey:n}),Xe(n))}function et({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function ps({mode:t,req:n,state:e,locale:s,instances:o,module:r}){const{supportedLocales:l,config:{defaultLocale:a}}=e;if(!a)return null;const i=(await Promise.all(o.map(async g=>{try{const w=et({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&ee.has(w))return T.info(`get preload component from cache: ${w}`),ee.get(w);const j=ne({state:e,componentId:g.componentId});if(!j)return null;const x=await tt({req:n,state:e,componentId:j.id,locale:s,defaultLocale:a,properties:g.properties});if(!x)return null;const F={instanceId:g.id,preload:x};if(t!=="draft"&&g.useCache){let N=We;g.cacheDuration&&(N=g.cacheDuration),T.info(`set preload component to cache(${N}s): ${w}`),ee.set(w,F,{ttl:N*1e3})}return F}catch(w){return T.error("get preload component error",{instanceId:g.id,componentId:g.componentId},{error:w}),null}}))).filter(g=>!!g),c=Object.values(i.reduce((g,w)=>({...g,...w.preload.components}),{}));async function u(){const g=await Promise.all(c.map(async w=>{const j=se.componentUMDName({componentId:w.component.id}),x=r===ue.PreloadComponentScriptModule.ESM?{module:r,script:await Be(w.script,{componentId:w.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await Be(w.script,{componentId:w.component.id,module:r,moduleName:j,tailwind:t!=="draft"}),moduleName:j};return[w.component.id,{component:w.component,script:x}]}));return Object.fromEntries(g)}const p=await u();return{config:{defaultLocale:a,supportedLocales:l},components:p,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function tt({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:l}=n,a=ne({state:n,componentId:e});if(!a)return null;const i=l.some(u=>u.locale===s)?s:o;if(!i)return null;const c=await st({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const ds=20;async function st({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:l}){if(n>ds)throw new RangeError("max component depth exceeded");const a=fs({state:e,componentId:s,properties:l,locale:o});if(!a)return null;const{props:i}=a,c={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...i}};try{const u=await gs({...a,req:t});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){T.error("preload data at server side error",{componentId:s,name:a.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===se.RenderNestedComponent){const f=await st({req:t,depth:n+1,state:e,componentId:p.componentId,locale:o,defaultLocale:r,properties:p.properties});f&&(Object.assign(c.components,f.components),Object.assign(c.props,{[u]:{type:se.RenderNestedComponent,componentId:p.componentId,props:f.props}}))}})),c}function fs({state:t,componentId:n,locale:e,properties:s}){const o=ne({state:t,componentId:n});if(!o)return null;const r=se.mergeComponent({componentId:n,getComponent:l=>ne({state:t,componentId:l}),locale:e,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:e,...r.properties}}:null}function ne({state:t,componentId:n}){var e,s,o;return((e=t.components[n])==null?void 0:e.data)??((o=(s=t.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function ms({state:t,name:n}){var s,o;const e=n.toLowerCase();return((s=Object.values(t.components).find(r=>{var l;return((l=r.data.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:s.data)??((o=t.resources.components&&Object.values(t.resources.components).find(r=>{var l;return((l=r.component.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:o.component)}async function gs({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Qe(n,"getServerSideProps");if(!o)return null;const r=new Promise(a=>{setTimeout(()=>{a({})},Ce*1e3)});return await Promise.race([r,K.Sandbox.callFunction({code:`${o}
33
33
 
34
34
  export async function getServerSidePropsWrapper(props) {
35
35
  const { location, fetch, props: componentProps } = props;
@@ -48,10 +48,10 @@ export async function getServerSidePropsWrapper(props) {
48
48
  }
49
49
  }`,filename:`${t.name||t.id}.js`,moduleLoader:a=>{if(a==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
50
50
  export { joinURL, withQuery, getQuery, getComponentMountPoint }
51
- `;if(a==="@blocklet/pages-kit/builtin/dayjs")return K.BuiltinModules.dayjs},global:{console:{log:(...a)=>{T.info(...a)},warn:(...a)=>{T.warn(...a)},error:(...a)=>{T.error(...a)}},getComponentMountPoint:gt.getComponentMountPoint,joinURL:R.joinURL,withQuery:R.withQuery,getQuery:R.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:R.joinURL(R.withHttps(s.hostname),s.originalUrl)},fetch:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?R.joinURL(w.default.env.appUrl,a):a;if(typeof c=="string"&&R.parseURL(c).host===R.parseURL(w.default.env.appUrl).host){const u=s.get("cookie");if(u){const p=new Je.Headers(i.headers);p.set("cookie",u),i.headers=p}}return Bt.default(c,{...i,timeout:Ie*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:e}]})])}const nt=K.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Qe(t,n);if(s)try{return await K.Sandbox.callFunction({code:`
51
+ `;if(a==="@blocklet/pages-kit/builtin/dayjs")return K.BuiltinModules.dayjs},global:{console:{log:(...a)=>{T.info(...a)},warn:(...a)=>{T.warn(...a)},error:(...a)=>{T.error(...a)}},getComponentMountPoint:gt.getComponentMountPoint,joinURL:R.joinURL,withQuery:R.withQuery,getQuery:R.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:R.joinURL(R.withHttps(s.hostname),s.originalUrl)},fetch:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?R.joinURL(y.default.env.appUrl,a):a;if(typeof c=="string"&&R.parseURL(c).host===R.parseURL(y.default.env.appUrl).host){const u=s.get("cookie");if(u){const p=new Je.Headers(i.headers);p.set("cookie",u),i.headers=p}}return Bt.default(c,{...i,timeout:Ce*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:e}]})])}const nt=K.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Qe(t,n);if(s)try{return await K.Sandbox.callFunction({code:`
52
52
  ${s}
53
53
 
54
54
  export function get${n}SchemaWrapper() {
55
55
  return ${n};
56
56
  }
57
- `,filename:`${e}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return T.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=me.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),hs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Oe="page",je="trigger-reload-project-resource",ke=hs,ys="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",{uploadToMediaKit:Ss}=require("@blocklet/uploader-server"),Pe=Rt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Re=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,te=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,He=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,ws=1e4,Es=3e4,le=0,be=1,bs=0,Ts=1,_e=w.default,X=d.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Cs=["production","draft"],Is=["production"];function ot(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function Os(){var e;const t=_e.env.languages.map(s=>({locale:s.code,name:s.name})),n=(e=t[0])==null?void 0:e.locale;return{pageIds:[],pages:{},components:{},supportedLocales:t,config:{defaultLocale:n},resources:{}}}const B=class B extends J.Doc{constructor(e){super();A(this,"states",{});A(this,"syncedStore");A(this,"conns",new Map);A(this,"awareness");A(this,"awarenessChangeHandler",({added:e,updated:s,removed:o},r)=>{const l=e.concat(s,o);if(r!==null){const c=this.conns.get(r);c&&(e.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const a=v.createEncoder();v.writeVarUint(a,be),v.writeVarUint8Array(a,W.encodeAwarenessUpdate(this.awareness,l));const i=v.toUint8Array(a);this.conns.forEach((c,u)=>this.send(u,i))});A(this,"updateHandler",e=>{const s=v.createEncoder();v.writeVarUint(s,le),we.writeUpdate(s,e);const o=v.toUint8Array(s);this.conns.forEach((r,l)=>this.send(l,o))});A(this,"ensureDataStructure",()=>{var l;const{supportedLocales:e,pages:s,pageIds:o,config:r}=this.syncedStore;{const a=new Set(Object.keys(s));let i=0;for(;i<o.length;){const c=o[i];a.has(c)?(a.delete(c),i++):o.splice(i,1)}}e.splice(0,e.length),e.push(..._e.env.languages.map(a=>({locale:a.code,name:a.name}))),r.defaultLocale=(l=e[0])==null?void 0:l.locale;{let a=0;const i=new Set;for(;a<e.length;){const{locale:c}=e[a];i.has(c)?e.splice(a,1):(a++,i.add(c))}}});A(this,"send",(e,s)=>{e.readyState!==bs&&e.readyState!==Ts&&this.closeConn(e);try{e.send(s,o=>{o&&this.closeConn(e)})}catch{this.closeConn(e)}});A(this,"closeConn",e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&W.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",Ye.default(()=>{h.mkdirSync(d.dirname(this.draftYjsFilePath),{recursive:!0}),h.writeFileSync(this.draftYjsFilePath,J.encodeStateAsUpdate(this))},ws));A(this,"save",({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()});A(this,"publish",async({mode:e,pages:s})=>{const o=await this.getState("draft"),r=await this.getState("production");await Ae(o,r,{pages:s,pageMergeMode:"replace",deletePages:!0,publishMode:e}),r.config.publishedAt=new Date().getTime();for(const l of s||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(e,r)});A(this,"mergeState",async(e,s)=>{var a,i,c;const o=JSON.parse(JSON.stringify(s));(a=e.config).fontFamily??(a.fontFamily={});const r=(i=o.config)==null?void 0:i.fontFamily,l=(c=e.config)==null?void 0:c.fontFamily;e.config.fontFamily.title=(r==null?void 0:r.title)||(l==null?void 0:l.title),e.config.fontFamily.description=(r==null?void 0:r.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const f=await Ae(e,s);u(f)}catch(f){p(f)}})})});A(this,"addConnection",e=>{if(this.conns.has(e))return;e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",r=>this.messageListener(e,new Uint8Array(r)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(o);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(o)}}},Es);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=v.createEncoder();v.writeVarUint(r,le),we.writeSyncStep1(r,this),this.send(e,v.toUint8Array(r));const l=this.awareness.getStates();if(l.size>0){const a=v.createEncoder();v.writeVarUint(a,be),v.writeVarUint8Array(a,W.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,v.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=v.createEncoder(),r=Ee.createDecoder(s),l=Ee.readVarUint(r);switch(l){case le:v.writeVarUint(o,le),we.readSyncMessage(r,o,this,null),v.length(o)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(o)));break;case be:{W.applyAwarenessUpdate(this.awareness,Ee.readVarUint8Array(r),e);break}default:T.warn(`Unsupported messageType ${l}`)}}catch(o){T.error(o)}this.save()});this.options=e,h.existsSync(this.draftYjsFilePath)&&J.applyUpdate(this,h.readFileSync(this.draftYjsFilePath)),this.syncedStore=It.reactive(ce.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new W.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=d.join(X,e),o=d.join(X,`@del-${e}`);h.renameSync(s,o)}catch(s){T.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return Ce.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>B.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new B({path:d.join(X,e)}),this.sharedInstances.set(e,s),s)}destroy(){this.conns.forEach((e,s)=>this.closeConn(s)),this.awareness.destroy(),super.destroy()}initObserver(){const e=o=>{o.observeDeep(r=>{r.some(l=>l.changes.keys.has("updatedAt")||l.changes.keys.has("publishedAt"))||o.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(o=>{const r=ce.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof J.Map&&e(r)});const s=ce.getYjsValue(this.syncedStore.pages);s&&s instanceof J.Map&&s.observe(o=>{o.changes.keys.forEach((r,l)=>{if(r.action==="add"){const a=ce.getYjsValue(this.syncedStore.pages[l]);a&&a instanceof J.Map&&e(a)}})})}get draftYjsFilePath(){return d.join(this.options.path,"draft.yjs")}async getState(e){var s,o,r,l;if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[e]&&(this.states[e]=await Ne(this.getPublishDir(e),{includeResources:!0})??Os(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=_e.env.languages.map(i=>({locale:i.code,name:i.name}));this.states[e].config.defaultLocale=(l=a[0])==null?void 0:l.locale}return{...this.states[e],resources:await he().then(async a=>{var p,f,g,S;const{pages:i,components:c}=Qt.default(a,"pages","components");let u=c;if((f=(p=this.states[e])==null?void 0:p.resources)!=null&&f.components)u={...(S=(g=this.states[e])==null?void 0:g.resources)==null?void 0:S.components};else{const _=d.basename(this.options.path),x=await H.findByPk(_);if(x!=null&&x.useAllResources)u=c;else{const N=(await ge.findAll({where:{projectId:_}})).map(E=>E.componentId);u=Object.fromEntries(Object.entries(c||{}).filter(([E])=>N.includes(E)))}}return{pages:i,components:u}}).catch(()=>({}))}}async setState(e,s){const o=await it(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);h.mkdirSync(d.dirname(r),{recursive:!0}),h.rmSync(r,{force:!0,recursive:!0}),h.renameSync(o,r),this.states[e]=s}getPublishDir(e){return d.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const l=await H.findByPk(r);if(!l)continue;const a=await B.shared(r).getState(e),i=Wt.default(w.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const u=a.pages[c];if(!u||e==="production"&&!u.isPublic)continue;const p=u.slug,f=l.slug||r,g={projectId:r,projectSlug:f,pageSlug:p,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:u.isPublic,templateConfig:u.templateConfig};f&&(o[R.joinURL("/",f,p)]={...g,shouldRedirect:!0,mainPage:!0}),o[R.joinURL("/",r,p)]={...g,shouldRedirect:!0,mainPage:!0};for(const S of i){const _={...g,locale:S};o[R.joinURL("/",S,r,p)]=_,f&&(o[R.joinURL("/",S,f,p)]=_)}}}return o}getDocumentSize(){return J.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,o]of this.sharedInstances.entries()){const r=o.getDocumentSize();e.push({projectId:s,sizeInBytes:r,sizeInMB:`${(r/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return e}};A(B,"INSTANCE_TTL",30*60*1e3),A(B,"sharedInstances",new ve.LRUCache({max:100,ttl:B.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let oe=B;function rt(){return h.mkdtempSync(d.join(w.default.env.dataDir,"tmp-"))}function de(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>de(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>de(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function js(t,n,e){if(!t||!h.existsSync(t)||!h.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Ss({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return T.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const Ps=async(t,n)=>{const e=d.basename(t),s=await De.call({name:ke,path:R.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=h.createWriteStream(n);await Lt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},_s=async(t,n)=>{await Promise.all(t.map(async e=>{try{await Ps(e,d.join(n,d.basename(e)))}catch(s){T.error(`Failed to export assets: ${e}, ${s}`)}}))};function at(t){return Re.test(t)?[t]:te.test(t)?(He.lastIndex=0,Array.from(t.matchAll(He)).map(e=>e[1]).filter(e=>!!e)):[]}async function Te(t,n,e){const{getFilename:s,exportAssets:o}=e,r=d.join(n,s(t));if(h.mkdirSync(d.dirname(r),{recursive:!0}),h.writeFileSync(r,Z.stringify(t)),o){const a=de(t,i=>typeof i=="string"&&(Re.test(i)||te.test(i))).map(i=>{const c=xe.default(t,i);return at(c)}).flat().filter(Boolean);await _s(a,d.dirname(r))}}const Ve=new ve.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Ge(t,n,e){var a;const s=de(t,i=>typeof i=="string"&&(Re.test(i)||te.test(i))),o=Xt.default(2),r=s.map(i=>o(async()=>{try{const c=xe.default(t,i),u=at(c);for(const p of u){const f=d.basename(p),g=e.getFilePath(p,i),S=g?`${g}:${f}`:f,_=Ve.get(S);if(_){te.test(c)||qe.default(t,i,_);return}const x=await js(g,f,n);x&&(te.test(c)||qe.default(t,i,x),Ve.set(S,x))}}catch(c){T.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(r);(a=e.onFinish)==null||a.call(e,l)}async function it(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,N,y,E,b,C,V,I,L,G,ie,Q;const l=e==="all"?t.pageIds:e,a=se.getComponentDependencies({state:t,pageIds:l,componentIds:s==="all"?Object.keys(t.components):s}),i=(m,j)=>{var P;return{id:m.id,name:m.name,isTemplateSection:m.isTemplateSection??!1,templateDescription:m.templateDescription,llmConfig:m.llmConfig,component:m.component,config:m.config,visibility:m.visibility,properties:((P=m.locales)==null?void 0:P[j])??{}}},c=(m,j)=>{var P;return{id:m.id,createdAt:m.createdAt,updatedAt:m.updatedAt,publishedAt:m.publishedAt,isPublic:m.isPublic??!0,templateConfig:m.templateConfig,meta:((P=m.locales)==null?void 0:P[j])??{},sections:M(m.sectionIds.map($=>{const q=m.sections[$];return q&&i(q,j)}))}},u=M(t.supportedLocales.map(m=>m.locale).flatMap(m=>l.map(j=>{const P=t.pages[j];return P&&{locale:m,slug:P.slug,page:c(P,m)}}))),p=rt(),f=d.join(p,"pages");h.mkdirSync(f,{recursive:!0});const g=d.join(p,"components");h.mkdirSync(g,{recursive:!0});for(const{locale:m,slug:j,page:P}of u)await Te(P,f,{getFilename:()=>`${ot(j)||"index"}.${m}.yml`,exportAssets:n});for(const m of a){const j=(F=t.components[m])==null?void 0:F.data;j&&await Te(j,g,{getFilename:P=>`${P.name||"unnamed"}.${P.id}.yml`,exportAssets:n})}const S=d.join(p,".blocklet/pages/pages.config.yml");h.mkdirSync(d.dirname(S),{recursive:!0});const _={pages:M(l.map(m=>{const j=t.pages[m];return j&&{id:m,slug:j.slug}})),components:M(a.map(m=>{var P;const j=(P=t.components[m])==null?void 0:P.data;return j&&{id:m,name:j.name}})),...r?{resources:{components:M(Object.keys(((N=t.resources)==null?void 0:N.components)||{}).filter(m=>a.includes(m)).map(m=>{var j,P,$,q;return{id:m,name:(q=($=(P=(j=t.resources)==null?void 0:j.components)==null?void 0:P[m])==null?void 0:$.component)==null?void 0:q.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};h.writeFileSync(S,Z.stringify(_));const x=d.join(p,"config.source.json");if(o&&h.writeFileSync(x,JSON.stringify(o)),r){const m=d.join(p,"resources"),j=d.join(m,"components");h.mkdirSync(j,{recursive:!0});for(const q of Object.keys(((y=t==null?void 0:t.resources)==null?void 0:y.components)??{}).filter(U=>a.includes(U))){const U=(C=(b=(E=t.resources)==null?void 0:E.components)==null?void 0:b[q])==null?void 0:C.component;U&&await Te(U,j,{getFilename:z=>`${z.name||"unnamed"}.${z.id}.yml`,exportAssets:n})}const P=d.join(p,"chunks");h.mkdirSync(P,{recursive:!0});const{chunks:$}=await he();for(const q of Object.keys(((V=t==null?void 0:t.resources)==null?void 0:V.components)??{}).filter(U=>a.includes(U))){const U=(G=(L=(I=t.resources)==null?void 0:I.components)==null?void 0:L[q])==null?void 0:G.component;if(U&&((ie=U.renderer)==null?void 0:ie.type)==="react-component"){const z=((Q=U.renderer)==null?void 0:Q.chunks)??[];if((z==null?void 0:z.length)>0)for(const ye of z){const Fe=d.join(P,ye),Se=$==null?void 0:$[ye];try{Se&&h.existsSync(Se)&&!h.existsSync(Fe)&&h.copyFileSync(Se,Fe)}catch(dt){T.error(`copy chunk ${ye} error`,dt.message)}}}}}return p}async function Ne(t,{importAssets:n,includeResources:e}={}){var r,l,a;if(!h.existsSync(t))return null;let s,o=!1;try{h.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=rt(),await Ut.x({file:t,C:s}));const i=Ce.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&d.join(d.dirname(i),"../../pages"),u=i&&d.join(d.dirname(i),"../../components"),p=i&&d.join(d.dirname(i),"../../chunks");if(!i)return null;const f=Z.parse(h.readFileSync(i).toString()),g=(y,E,b)=>{let C=d.join(y,`${E}${b?`.${b}`:""}.yml`);return(!h.existsSync(C)||!h.lstatSync(C).isFile())&&(C=d.join(y,E,`index${b?`.${b}`:""}.yml`),!h.existsSync(C)||!h.lstatSync(C))?null:Z.parse(h.readFileSync(C).toString())},S=(y,E)=>{try{const b=Ce.globSync(`*.${E}.yml`,{cwd:y,absolute:!0})[0];return b?Z.parse(h.readFileSync(b).toString()):null}catch(b){T.error("parse component error",b)}return null},_=M(f.pages.map(({slug:y})=>{var V;const E=M(f.supportedLocales.map(({locale:I})=>{const L=c?g(c,ot(y),I):void 0;if(L)return{locale:I,page:L};const G=c?g(c,y,I):void 0;return G&&{locale:I,page:G}})),b=(V=E[0])==null?void 0:V.page;if(!b)return null;const C=b.sections.map(I=>{const L=I.id||Pe();return{id:L,component:I.component,config:I.config,name:I.name,isTemplateSection:I.isTemplateSection??!1,templateDescription:I.templateDescription,llmConfig:I.llmConfig,visibility:I.visibility,locales:Object.fromEntries(M(E.map(({locale:G,page:ie})=>{const Q=ie.sections.find(m=>m.id===L);return Q&&[G,Q.properties]})))}});return{id:b.id||Pe(),createdAt:b.createdAt,updatedAt:b.updatedAt,publishedAt:b.publishedAt,isPublic:b.isPublic??!0,templateConfig:b.templateConfig,slug:y,sections:Object.fromEntries(C.map(I=>[I.id,I])),sectionIds:C.map(I=>I.id),locales:Object.fromEntries(E.map(({locale:I,page:L})=>[I,L.meta]))}})),x=u?M(((r=f.components)==null?void 0:r.map(({id:y})=>S(u,y)))??[]):[];if(n){const y=(...E)=>{T.info(`[${o?d.basename(t):d.basename(d.join(t,"../../../../"))}] importAssets:`,...E)};try{y("wait image-bin api ready"),await es.default({resources:[`${De.getComponentWebEndpoint(ss)}/api/sdk/uploads`],validateStatus:C=>C>=200&&C<=500}),y("image-bin api is ready");const E={},b={};y("start to upload assets"),await Promise.allSettled([Ge(x,E,{getFilePath:C=>u&&d.join(u,C),onFinish:C=>{y(`upload ${C.length} component assets`)}}),Ge(_,b,{getFilePath:(C,V)=>{const I=xe.default(_,V.slice(0,1));return c&&d.join(c,d.dirname(I.slug),C)},onFinish:C=>{y(`upload ${C.length} page assets`)}})]),y("upload assets done"),global.gc&&global.gc()}catch(E){y("Error during asset import:",E)}}const F={};if(e){const y=i&&d.join(d.dirname(i),"../../resources/components"),E=M(((a=(l=f.resources)==null?void 0:l.components)==null?void 0:a.map(({id:b})=>S(y,b)))??[]);E.length>0&&(F.components=Object.fromEntries(E.map((b,C)=>[b.id,{index:C,component:b}])))}const N={};if(p&&h.existsSync(p)){const y=h.readdirSync(p);for(const E of y)N[E]=d.join(p,E)}return{supportedLocales:f.supportedLocales,pageIds:_.map(y=>y.id),components:Object.fromEntries(x.map((y,E)=>[y.id,{index:E,data:y}])),pages:Object.fromEntries(_.map(y=>[y.id,y])),config:f.config||{},resources:F,chunks:N}}finally{o&&s&&h.rmSync(s,{force:!0,recursive:!0})}}async function Ae(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&Ze(r)}catch(u){T.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:a,supportedLocales:i}=t;for(const u of e??l){const p=a[u];if(!p){const f=n.pageIds.indexOf(u);f!==-1&&o&&(n.pageIds.splice(f,1),delete n.pages[u]);continue}if(n.pageIds.includes(p.id)){if(s==="replace")n.pages[p.id]=p;else if(s==="byUpdateTime"){const f=n.pages[p.id];(!f||p.updatedAt&&p.updatedAt>f.updatedAt)&&(n.pages[p.id]=p)}}else n.pageIds.push(p.id),n.pages[p.id]=p}if(o&&!e)for(const u of n.pageIds)t.pageIds.includes(u)||delete n.pages[u],n.pageIds=[...n.pageIds].filter(p=>t.pageIds.includes(p));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...Kt.default(i)),o)for(const u of Object.keys(n.components))delete n.components[u];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const f=await ct(p==null?void 0:p.data);return[u,{...p,data:f}]}))),Object.assign(n.components,c),Object.assign(n.config,JSON.parse(JSON.stringify(t.config))),n.resources.components=JSON.parse(JSON.stringify(t.resources.components||{}))}const ct=K.memoize(async t=>{var n;if(!Yt.default(t==null?void 0:t.properties))return t;if(((n=t==null?void 0:t.renderer)==null?void 0:n.type)==="react-component"){const{script:e}=(t==null?void 0:t.renderer)||{};if(e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await nt(e,"PROPERTIES_SCHEMA",t.id);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t!=null&&t.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){T.error("checkPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{keyGenerator:t=>{var l;const n=(t==null?void 0:t.id)||"",e=(t==null?void 0:t.name)||"",s=((l=t==null?void 0:t.renderer)==null?void 0:l.type)||"",o=(t==null?void 0:t.properties)||{},r=me.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});let fe,Y,Le,Ue,Me;function lt(){return fe=(async()=>{const t=De.getResources({types:[{did:ke,type:Oe},{did:ys,type:Oe}]});Y=(await Promise.all(t.map(async e=>{const s=e.path?await Ne(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Le=Y.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=Y.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Ue=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await ct(s.component);return[e,{...s,component:o}]}))),Me=Y.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),fe}function ut(t){const n=Ye.default(async()=>{await lt().catch(e=>{T.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:Y,pages:Le,components:Ue,chunks:Me}))},3e3,{leading:!1,trailing:!0});return n(),w.default.events.on(w.default.Events.componentAdded,n),w.default.events.on(w.default.Events.componentRemoved,n),w.default.events.on(w.default.Events.componentStarted,n),w.default.events.on(w.default.Events.componentStopped,n),w.default.events.on(w.default.Events.componentUpdated,n),w.default.events.on(je,n),()=>{w.default.events.off(w.default.Events.componentAdded,n),w.default.events.off(w.default.Events.componentRemoved,n),w.default.events.off(w.default.Events.componentStarted,n),w.default.events.off(w.default.Events.componentStopped,n),w.default.events.off(w.default.Events.componentUpdated,n),w.default.events.off(je,n)}}const pt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),pe=globalThis;var ze;(ze=pe[pt])==null||ze.call(pe);pe[pt]=ut(async({pages:t,components:n})=>{const{projectIds:e}=oe;T.info(`start update resource states projects(${e.length})`,e),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(e.map(async s=>{const o=oe.shared(s);o.syncedStore.resources.pages=t;const r=await H.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ge.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}T.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(s=>{T.error("update resource states failed:",s)})});async function As(){T.info("trigger reload all project resource"),w.default.events.emit(je)}async function he({ensureLoaded:t=!0}={}){return t&&(fe??(fe=lt()),await fe),{states:Y,pages:Le,components:Ue,chunks:Me}}exports.COMPONENT_DID=ke;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=We;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ie;exports.PUBLISH_MODES=Is;exports.Project=H;exports.RESOURCE_TYPE=Oe;exports.SITE_STATE_PATH=X;exports.STATE_MODES=Cs;exports.SiteState=oe;exports.clearPreloadComponentsCache=Xe;exports.clearPreloadComponentsCacheByMode=Ze;exports.fromPackage=Ne;exports.getComponentFromState=ne;exports.getComponentFromStateByName=ms;exports.getExportSchemaValueFromCode=nt;exports.getMultiTenantAllProjectAccessPassports=rs;exports.getPreloadComponent=tt;exports.getPreloadComponents=ps;exports.getPreloadComponentsCacheKey=et;exports.getResourceStates=he;exports.initPackResourceStates=ut;exports.isMultiTenant=os;exports.logger=T;exports.mergeState=Ae;exports.nextId=Pe;exports.toPackage=it;exports.triggerReloadAllProjectResource=As;
57
+ `,filename:`${e}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return T.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=me.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),hs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Oe="page",Pe="trigger-reload-project-resource",ke=hs,ys="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",{uploadToMediaKit:Ss}=require("@blocklet/uploader-server"),_e=Rt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Re=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,te=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,He=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,ws=1e4,Es=3e4,le=0,be=1,bs=0,Ts=1,je=y.default,X=d.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Is=["production","draft"],Cs=["production"];function ot(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function Os(){var e;const t=je.env.languages.map(s=>({locale:s.code,name:s.name})),n=(e=t[0])==null?void 0:e.locale;return{pageIds:[],pages:{},components:{},supportedLocales:t,config:{defaultLocale:n},resources:{}}}const B=class B extends J.Doc{constructor(e){super();A(this,"states",{});A(this,"syncedStore");A(this,"conns",new Map);A(this,"awareness");A(this,"awarenessChangeHandler",({added:e,updated:s,removed:o},r)=>{const l=e.concat(s,o);if(r!==null){const c=this.conns.get(r);c&&(e.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const a=v.createEncoder();v.writeVarUint(a,be),v.writeVarUint8Array(a,W.encodeAwarenessUpdate(this.awareness,l));const i=v.toUint8Array(a);this.conns.forEach((c,u)=>this.send(u,i))});A(this,"updateHandler",e=>{const s=v.createEncoder();v.writeVarUint(s,le),we.writeUpdate(s,e);const o=v.toUint8Array(s);this.conns.forEach((r,l)=>this.send(l,o))});A(this,"ensureDataStructure",()=>{var l;const{supportedLocales:e,pages:s,pageIds:o,config:r}=this.syncedStore;{const a=new Set(Object.keys(s));let i=0;for(;i<o.length;){const c=o[i];a.has(c)?(a.delete(c),i++):o.splice(i,1)}}e.splice(0,e.length),e.push(...je.env.languages.map(a=>({locale:a.code,name:a.name}))),r.defaultLocale=(l=e[0])==null?void 0:l.locale;{let a=0;const i=new Set;for(;a<e.length;){const{locale:c}=e[a];i.has(c)?e.splice(a,1):(a++,i.add(c))}}});A(this,"send",(e,s)=>{e.readyState!==bs&&e.readyState!==Ts&&this.closeConn(e);try{e.send(s,o=>{o&&this.closeConn(e)})}catch{this.closeConn(e)}});A(this,"closeConn",e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&W.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",Ye.default(()=>{h.mkdirSync(d.dirname(this.draftYjsFilePath),{recursive:!0}),h.writeFileSync(this.draftYjsFilePath,J.encodeStateAsUpdate(this))},ws));A(this,"save",({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()});A(this,"publish",async({mode:e,pages:s})=>{const o=await this.getState("draft"),r=await this.getState("production");await Ae(o,r,{pages:s,pageMergeMode:"replace",deletePages:!0,publishMode:e}),r.config.publishedAt=new Date().getTime();for(const l of s||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(e,r)});A(this,"mergeState",async(e,s)=>{var a,i,c;const o=JSON.parse(JSON.stringify(s));(a=e.config).fontFamily??(a.fontFamily={});const r=(i=o.config)==null?void 0:i.fontFamily,l=(c=e.config)==null?void 0:c.fontFamily;e.config.fontFamily.title=(r==null?void 0:r.title)||(l==null?void 0:l.title),e.config.fontFamily.description=(r==null?void 0:r.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const f=await Ae(e,s);u(f)}catch(f){p(f)}})})});A(this,"addConnection",e=>{if(this.conns.has(e))return;e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",r=>this.messageListener(e,new Uint8Array(r)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(o);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(o)}}},Es);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=v.createEncoder();v.writeVarUint(r,le),we.writeSyncStep1(r,this),this.send(e,v.toUint8Array(r));const l=this.awareness.getStates();if(l.size>0){const a=v.createEncoder();v.writeVarUint(a,be),v.writeVarUint8Array(a,W.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,v.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=v.createEncoder(),r=Ee.createDecoder(s),l=Ee.readVarUint(r);switch(l){case le:v.writeVarUint(o,le),we.readSyncMessage(r,o,this,null),v.length(o)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(o)));break;case be:{W.applyAwarenessUpdate(this.awareness,Ee.readVarUint8Array(r),e);break}default:T.warn(`Unsupported messageType ${l}`)}}catch(o){T.error(o)}this.save()});this.options=e,h.existsSync(this.draftYjsFilePath)&&J.applyUpdate(this,h.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ct.reactive(ce.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new W.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=d.join(X,e),o=d.join(X,`@del-${e}`);h.renameSync(s,o)}catch(s){T.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return Ie.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>B.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new B({path:d.join(X,e)}),this.sharedInstances.set(e,s),s)}destroy(){this.conns.forEach((e,s)=>this.closeConn(s)),this.awareness.destroy(),super.destroy()}initObserver(){const e=o=>{o.observeDeep(r=>{r.some(l=>l.changes.keys.has("updatedAt")||l.changes.keys.has("publishedAt"))||o.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(o=>{const r=ce.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof J.Map&&e(r)});const s=ce.getYjsValue(this.syncedStore.pages);s&&s instanceof J.Map&&s.observe(o=>{o.changes.keys.forEach((r,l)=>{if(r.action==="add"){const a=ce.getYjsValue(this.syncedStore.pages[l]);a&&a instanceof J.Map&&e(a)}})})}get draftYjsFilePath(){return d.join(this.options.path,"draft.yjs")}async getState(e){var s,o,r,l;if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[e]&&(this.states[e]=await Ne(this.getPublishDir(e),{includeResources:!0})??Os(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=je.env.languages.map(i=>({locale:i.code,name:i.name}));this.states[e].config.defaultLocale=(l=a[0])==null?void 0:l.locale}return{...this.states[e],resources:await he().then(async a=>{var p,f,g,w;const{pages:i,components:c}=Qt.default(a,"pages","components");let u=c;if((f=(p=this.states[e])==null?void 0:p.resources)!=null&&f.components)u={...(w=(g=this.states[e])==null?void 0:g.resources)==null?void 0:w.components};else{const j=d.basename(this.options.path),x=await H.findByPk(j);if(x!=null&&x.useAllResources)u=c;else{const N=(await ge.findAll({where:{projectId:j}})).map(E=>E.componentId);u=Object.fromEntries(Object.entries(c||{}).filter(([E])=>N.includes(E)))}}return{pages:i,components:u}}).catch(()=>({}))}}async setState(e,s){const o=await it(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);h.mkdirSync(d.dirname(r),{recursive:!0}),h.rmSync(r,{force:!0,recursive:!0}),h.renameSync(o,r),this.states[e]=s}getPublishDir(e){return d.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const l=await H.findByPk(r);if(!l)continue;const a=await B.shared(r).getState(e),i=Wt.default(y.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const u=a.pages[c];if(!u||e==="production"&&!u.isPublic)continue;const p=u.slug,f=l.slug||r,g={projectId:r,projectSlug:f,pageSlug:p,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:u.isPublic,templateConfig:u.templateConfig};f&&(o[R.joinURL("/",f,p)]={...g,shouldRedirect:!0,mainPage:!0}),o[R.joinURL("/",r,p)]={...g,shouldRedirect:!0,mainPage:!0};for(const w of i){const j={...g,locale:w};o[R.joinURL("/",w,r,p)]=j,f&&(o[R.joinURL("/",w,f,p)]=j)}}}return o}getDocumentSize(){return J.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,o]of this.sharedInstances.entries()){const r=o.getDocumentSize();e.push({projectId:s,sizeInBytes:r,sizeInMB:`${(r/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return e}};A(B,"INSTANCE_TTL",30*60*1e3),A(B,"sharedInstances",new ve.LRUCache({max:100,ttl:B.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let oe=B;function rt(){return h.mkdtempSync(d.join(y.default.env.dataDir,"tmp-"))}function de(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>de(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>de(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function Ps(t,n,e){if(!t||!h.existsSync(t)||!h.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Ss({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return T.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const _s=async(t,n)=>{const e=d.basename(t),s=await De.call({name:ke,path:R.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=h.createWriteStream(n);await Lt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},js=async(t,n)=>{await Promise.all(t.map(async e=>{try{await _s(e,d.join(n,d.basename(e)))}catch(s){T.error(`Failed to export assets: ${e}, ${s}`)}}))};function at(t){return Re.test(t)?[t]:te.test(t)?(He.lastIndex=0,Array.from(t.matchAll(He)).map(e=>e[1]).filter(e=>!!e)):[]}async function Te(t,n,e){const{getFilename:s,exportAssets:o}=e,r=d.join(n,s(t));if(h.mkdirSync(d.dirname(r),{recursive:!0}),h.writeFileSync(r,Z.stringify(t)),o){const a=de(t,i=>typeof i=="string"&&(Re.test(i)||te.test(i))).map(i=>{const c=xe.default(t,i);return at(c)}).flat().filter(Boolean);await js(a,d.dirname(r))}}const Ve=new ve.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Ge(t,n,e){var a;const s=de(t,i=>typeof i=="string"&&(Re.test(i)||te.test(i))),o=Xt.default(2),r=s.map(i=>o(async()=>{try{const c=xe.default(t,i),u=at(c);for(const p of u){const f=d.basename(p),g=e.getFilePath(p,i),w=g?`${g}:${f}`:f,j=Ve.get(w);if(j){te.test(c)||qe.default(t,i,j);return}const x=await Ps(g,f,n);x&&(te.test(c)||qe.default(t,i,x),Ve.set(w,x))}}catch(c){T.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(r);(a=e.onFinish)==null||a.call(e,l)}async function it(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,N,S,E,b,I,V,C,L,G,ie,Q;const l=e==="all"?t.pageIds:e,a=se.getComponentDependencies({state:t,pageIds:l,componentIds:s==="all"?Object.keys(t.components):s}),i=(m,P)=>{var _;return{id:m.id,name:m.name,isTemplateSection:m.isTemplateSection??!1,templateDescription:m.templateDescription,llmConfig:m.llmConfig,component:m.component,config:m.config,visibility:m.visibility,properties:((_=m.locales)==null?void 0:_[P])??{}}},c=(m,P)=>{var _;return{id:m.id,createdAt:m.createdAt,updatedAt:m.updatedAt,publishedAt:m.publishedAt,isPublic:m.isPublic??!0,templateConfig:m.templateConfig,meta:((_=m.locales)==null?void 0:_[P])??{},sections:M(m.sectionIds.map($=>{const q=m.sections[$];return q&&i(q,P)}))}},u=M(t.supportedLocales.map(m=>m.locale).flatMap(m=>l.map(P=>{const _=t.pages[P];return _&&{locale:m,slug:_.slug,page:c(_,m)}}))),p=rt(),f=d.join(p,"pages");h.mkdirSync(f,{recursive:!0});const g=d.join(p,"components");h.mkdirSync(g,{recursive:!0});for(const{locale:m,slug:P,page:_}of u)await Te(_,f,{getFilename:()=>`${ot(P)||"index"}.${m}.yml`,exportAssets:n});for(const m of a){const P=(F=t.components[m])==null?void 0:F.data;P&&await Te(P,g,{getFilename:_=>`${_.name||"unnamed"}.${_.id}.yml`,exportAssets:n})}const w=d.join(p,".blocklet/pages/pages.config.yml");h.mkdirSync(d.dirname(w),{recursive:!0});const j={pages:M(l.map(m=>{const P=t.pages[m];return P&&{id:m,slug:P.slug}})),components:M(a.map(m=>{var _;const P=(_=t.components[m])==null?void 0:_.data;return P&&{id:m,name:P.name}})),...r?{resources:{components:M(Object.keys(((N=t.resources)==null?void 0:N.components)||{}).filter(m=>a.includes(m)).map(m=>{var P,_,$,q;return{id:m,name:(q=($=(_=(P=t.resources)==null?void 0:P.components)==null?void 0:_[m])==null?void 0:$.component)==null?void 0:q.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};h.writeFileSync(w,Z.stringify(j));const x=d.join(p,"config.source.json");if(o&&h.writeFileSync(x,JSON.stringify(o)),r){const m=d.join(p,"resources"),P=d.join(m,"components");h.mkdirSync(P,{recursive:!0});for(const q of Object.keys(((S=t==null?void 0:t.resources)==null?void 0:S.components)??{}).filter(U=>a.includes(U))){const U=(I=(b=(E=t.resources)==null?void 0:E.components)==null?void 0:b[q])==null?void 0:I.component;U&&await Te(U,P,{getFilename:z=>`${z.name||"unnamed"}.${z.id}.yml`,exportAssets:n})}const _=d.join(p,"chunks");h.mkdirSync(_,{recursive:!0});const{chunks:$}=await he();for(const q of Object.keys(((V=t==null?void 0:t.resources)==null?void 0:V.components)??{}).filter(U=>a.includes(U))){const U=(G=(L=(C=t.resources)==null?void 0:C.components)==null?void 0:L[q])==null?void 0:G.component;if(U&&((ie=U.renderer)==null?void 0:ie.type)==="react-component"){const z=((Q=U.renderer)==null?void 0:Q.chunks)??[];if((z==null?void 0:z.length)>0)for(const ye of z){const Fe=d.join(_,ye),Se=$==null?void 0:$[ye];try{Se&&h.existsSync(Se)&&!h.existsSync(Fe)&&h.copyFileSync(Se,Fe)}catch(dt){T.error(`copy chunk ${ye} error`,dt.message)}}}}}return p}async function Ne(t,{importAssets:n,includeResources:e}={}){var r,l,a;if(!h.existsSync(t))return null;let s,o=!1;try{h.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=rt(),await Ut.x({file:t,C:s}));const i=Ie.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&d.join(d.dirname(i),"../../pages"),u=i&&d.join(d.dirname(i),"../../components"),p=i&&d.join(d.dirname(i),"../../chunks");if(!i)return null;const f=Z.parse(h.readFileSync(i).toString()),g=(S,E,b)=>{let I=d.join(S,`${E}${b?`.${b}`:""}.yml`);return(!h.existsSync(I)||!h.lstatSync(I).isFile())&&(I=d.join(S,E,`index${b?`.${b}`:""}.yml`),!h.existsSync(I)||!h.lstatSync(I))?null:Z.parse(h.readFileSync(I).toString())},w=(S,E)=>{try{const b=Ie.globSync(`*.${E}.yml`,{cwd:S,absolute:!0})[0];return b?Z.parse(h.readFileSync(b).toString()):null}catch(b){T.error("parse component error",b)}return null},j=M(f.pages.map(({slug:S})=>{var V;const E=M(f.supportedLocales.map(({locale:C})=>{const L=c?g(c,ot(S),C):void 0;if(L)return{locale:C,page:L};const G=c?g(c,S,C):void 0;return G&&{locale:C,page:G}})),b=(V=E[0])==null?void 0:V.page;if(!b)return null;const I=b.sections.map(C=>{const L=C.id||_e();return{id:L,component:C.component,config:C.config,name:C.name,isTemplateSection:C.isTemplateSection??!1,templateDescription:C.templateDescription,llmConfig:C.llmConfig,visibility:C.visibility,locales:Object.fromEntries(M(E.map(({locale:G,page:ie})=>{const Q=ie.sections.find(m=>m.id===L);return Q&&[G,Q.properties]})))}});return{id:b.id||_e(),createdAt:b.createdAt,updatedAt:b.updatedAt,publishedAt:b.publishedAt,isPublic:b.isPublic??!0,templateConfig:b.templateConfig,slug:S,sections:Object.fromEntries(I.map(C=>[C.id,C])),sectionIds:I.map(C=>C.id),locales:Object.fromEntries(E.map(({locale:C,page:L})=>[C,L.meta]))}})),x=u?M(((r=f.components)==null?void 0:r.map(({id:S})=>w(u,S)))??[]):[];if(n){const S=(...E)=>{T.info(`[${o?d.basename(t):d.basename(d.join(t,"../../../../"))}] importAssets:`,...E)};try{S("wait image-bin api ready"),await es.default({resources:[`${De.getComponentWebEndpoint(ss)}/api/sdk/uploads`],validateStatus:I=>I>=200&&I<=500}),S("image-bin api is ready");const E={},b={};S("start to upload assets"),await Promise.allSettled([Ge(x,E,{getFilePath:I=>u&&d.join(u,I),onFinish:I=>{S(`upload ${I.length} component assets`)}}),Ge(j,b,{getFilePath:(I,V)=>{const C=xe.default(j,V.slice(0,1));return c&&d.join(c,d.dirname(C.slug),I)},onFinish:I=>{S(`upload ${I.length} page assets`)}})]),S("upload assets done"),global.gc&&global.gc()}catch(E){S("Error during asset import:",E)}}const F={};if(e){const S=i&&d.join(d.dirname(i),"../../resources/components"),E=M(((a=(l=f.resources)==null?void 0:l.components)==null?void 0:a.map(({id:b})=>w(S,b)))??[]);E.length>0&&(F.components=Object.fromEntries(E.map((b,I)=>[b.id,{index:I,component:b}])))}const N={};if(p&&h.existsSync(p)){const S=h.readdirSync(p);for(const E of S)N[E]=d.join(p,E)}return{supportedLocales:f.supportedLocales,pageIds:j.map(S=>S.id),components:Object.fromEntries(x.map((S,E)=>[S.id,{index:E,data:S}])),pages:Object.fromEntries(j.map(S=>[S.id,S])),config:f.config||{},resources:F,chunks:N}}finally{o&&s&&h.rmSync(s,{force:!0,recursive:!0})}}async function Ae(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&Ze(r)}catch(u){T.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:a,supportedLocales:i}=t;for(const u of e??l){const p=a[u];if(!p){const f=n.pageIds.indexOf(u);f!==-1&&o&&(n.pageIds.splice(f,1),delete n.pages[u]);continue}if(n.pageIds.includes(p.id)){if(s==="replace")n.pages[p.id]=p;else if(s==="byUpdateTime"){const f=n.pages[p.id];(!f||p.updatedAt&&p.updatedAt>f.updatedAt)&&(n.pages[p.id]=p)}}else n.pageIds.push(p.id),n.pages[p.id]=p}if(o&&!e)for(const u of n.pageIds)t.pageIds.includes(u)||delete n.pages[u],n.pageIds=[...n.pageIds].filter(p=>t.pageIds.includes(p));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...Kt.default(i)),o)for(const u of Object.keys(n.components))delete n.components[u];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const f=await ct(p==null?void 0:p.data);return[u,{...p,data:f}]}))),Object.assign(n.components,c),Object.assign(n.config,JSON.parse(JSON.stringify(t.config))),n.resources.components=JSON.parse(JSON.stringify(t.resources.components||{}))}const ct=K.memoize(async t=>{var n;if(!Yt.default(t==null?void 0:t.properties))return t;if(((n=t==null?void 0:t.renderer)==null?void 0:n.type)==="react-component"){const{script:e}=(t==null?void 0:t.renderer)||{};if(e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await nt(e,"PROPERTIES_SCHEMA",t.id);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t!=null&&t.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){T.error("checkPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{keyGenerator:t=>{var l;const n=(t==null?void 0:t.id)||"",e=(t==null?void 0:t.name)||"",s=((l=t==null?void 0:t.renderer)==null?void 0:l.type)||"",o=(t==null?void 0:t.properties)||{},r=me.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});let fe,Y,Le,Ue,Me;function lt(){return fe=(async()=>{const t=De.getResources({types:[{did:ke,type:Oe},{did:ys,type:Oe}]});Y=(await Promise.all(t.map(async e=>{const s=e.path?await Ne(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Le=Y.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=Y.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Ue=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await ct(s.component);return[e,{...s,component:o}]}))),Me=Y.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),fe}function ut(t){const n=Ye.default(async()=>{await lt().catch(e=>{T.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:Y,pages:Le,components:Ue,chunks:Me}))},3e3,{leading:!1,trailing:!0});return n(),y.default.events.on(y.default.Events.componentAdded,n),y.default.events.on(y.default.Events.componentRemoved,n),y.default.events.on(y.default.Events.componentStarted,n),y.default.events.on(y.default.Events.componentStopped,n),y.default.events.on(y.default.Events.componentUpdated,n),y.default.events.on(Pe,n),()=>{y.default.events.off(y.default.Events.componentAdded,n),y.default.events.off(y.default.Events.componentRemoved,n),y.default.events.off(y.default.Events.componentStarted,n),y.default.events.off(y.default.Events.componentStopped,n),y.default.events.off(y.default.Events.componentUpdated,n),y.default.events.off(Pe,n)}}const pt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),pe=globalThis;var ze;(ze=pe[pt])==null||ze.call(pe);pe[pt]=ut(async({pages:t,components:n})=>{const{projectIds:e}=oe;T.info(`start update resource states projects(${e.length})`,e),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(e.map(async s=>{const o=oe.shared(s);o.syncedStore.resources.pages=t;const r=await H.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ge.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}T.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(s=>{T.error("update resource states failed:",s)})});async function As(){T.info("trigger reload all project resource"),y.default.events.emit(Pe)}async function he({ensureLoaded:t=!0}={}){return t&&(fe??(fe=lt()),await fe),{states:Y,pages:Le,components:Ue,chunks:Me}}exports.COMPONENT_DID=ke;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=We;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ce;exports.PUBLISH_MODES=Cs;exports.Project=H;exports.RESOURCE_TYPE=Oe;exports.SITE_STATE_PATH=X;exports.STATE_MODES=Is;exports.SiteState=oe;exports.clearPreloadComponentsCache=Xe;exports.clearPreloadComponentsCacheByMode=Ze;exports.fromPackage=Ne;exports.getComponentFromState=ne;exports.getComponentFromStateByName=ms;exports.getExportSchemaValueFromCode=nt;exports.getMultiTenantAllProjectAccessPassports=rs;exports.getPreloadComponent=tt;exports.getPreloadComponents=ps;exports.getPreloadComponentsCacheKey=et;exports.getResourceStates=he;exports.initPackResourceStates=ut;exports.isMultiTenant=os;exports.logger=T;exports.mergeState=Ae;exports.nextId=_e;exports.toPackage=it;exports.triggerReloadAllProjectResource=As;
@@ -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-B0YNPQJU.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-CJ36w6-7.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,4 +1,4 @@
1
- "use strict";const k=require("./chunks/site-state-B0YNPQJU.js"),P=require("@blocklet/crawler/middlewares"),W=require("@blocklet/pages-kit/types"),J=require("@blocklet/pages-kit/utils/preload"),G=require("@blocklet/sdk/lib/component"),U=require("@blocklet/sdk/lib/config"),z=require("cheerio/slim"),K=require("express"),O=require("fs"),Q=require("mustache"),A=require("path"),S=require("ufo"),D=e=>e&&e.__esModule?e:{default:e};function V(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 p=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,p.get?p:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const d=D(U),I=V(z),X=D(Q),Y=["/assets/"],q=()=>[!0,"true"].includes(d.default.env.preferences.allowCrawler);function R(){q()?P.initCronCrawlBlocklet({time:"0 0 */12 * * *",options:{}}):P.cancelCronCrawlBlocklet()}R();d.default.events.on(d.default.Events.envUpdate,R);function Z({app:e,viteDevServer:s,state:t}){let p;if(s){const c=O.readFileSync(A.resolve(process.cwd(),"./index.html"),"utf-8");e.use(async(b,j,y)=>{const v=b.originalUrl;p=await s.transformIndexHtml(v,c),y()})}else p=O.readFileSync(A.resolve(process.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const C=K.Router();C.use(P.initSEOMiddleware({autoReturnHtml:!0,allowCrawler:q})),C.get("/:path(*)?",async(c,b,j)=>{var $,E,L;if(Y.some(l=>{var i;return(i=c.path)==null?void 0:i.startsWith(l)})){j();return}const y=performance.now(),v=()=>Math.round(performance.now()-y),x="production";let o,u,g=p;if(c.path.startsWith("/pages")){const l=c.params.lang,i=c.cookies.nf_lang,w=new Set([...d.default.env.languages.map(h=>h.code)]);let f=(l&&w.has(l)?l:void 0)||(w.has(i)?i:void 0)||[...w][0];if((!f||!(($=t.supportedLocales)!=null&&$.find(h=>h.locale===f)))&&(f=((L=(E=t.supportedLocales)==null?void 0:E[0])==null?void 0:L.locale)||""),f){const h=[];Object.values(t.pages).forEach(r=>{const N=Object.values((r==null?void 0:r.sections)??{}).filter(a=>{var _;return a.component==="custom-component"&&((_=a.config)==null?void 0:_.componentId)}).map(a=>{var _,M;return{id:a.id,componentId:a.config.componentId,useCache:a.config.useCache,cacheDuration:a.config.cacheDuration,properties:(M=(_=a.locales)==null?void 0:_[f])==null?void 0:M.properties}});h.push(...N)});const H=new Promise(r=>{setTimeout(()=>{r({})},90*1e3)});try{await Promise.race([H,k.getPreloadComponents({mode:x,req:c,state:t,locale:f,instances:h,module:W.PreloadComponentScriptModule.UMD_FN}).then(r=>{r&&(u=J.injectPreloadComponents(r))})])}catch(r){k.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),k.logger.warn(r)}}}try{const l=(o==null?void 0:o.title)||d.default.env.appName,i=(o==null?void 0:o.description)||d.default.env.appDescription,w=S.withQuery(S.joinURL(d.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:l,description:i});g=X.default.render(p,{ogTitle:l,ogDescription:i,ogImage:F(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,B=c.query.mode==="draft"||c.url.includes("preview"),m=I.load(g);m("head").find("#injected-head-elements").replaceWith(`
1
+ "use strict";const k=require("./chunks/site-state-CJ36w6-7.js"),P=require("@blocklet/crawler/middlewares"),W=require("@blocklet/pages-kit/types"),J=require("@blocklet/pages-kit/utils/preload"),G=require("@blocklet/sdk/lib/component"),U=require("@blocklet/sdk/lib/config"),z=require("cheerio/slim"),K=require("express"),O=require("fs"),Q=require("mustache"),A=require("path"),S=require("ufo"),D=e=>e&&e.__esModule?e:{default:e};function V(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 p=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,p.get?p:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const d=D(U),I=V(z),X=D(Q),Y=["/assets/"],q=()=>[!0,"true"].includes(d.default.env.preferences.allowCrawler);function R(){q()?P.initCronCrawlBlocklet({time:"0 0 */12 * * *",options:{}}):P.cancelCronCrawlBlocklet()}R();d.default.events.on(d.default.Events.envUpdate,R);function Z({app:e,viteDevServer:s,state:t}){let p;if(s){const c=O.readFileSync(A.resolve(process.cwd(),"./index.html"),"utf-8");e.use(async(b,j,y)=>{const v=b.originalUrl;p=await s.transformIndexHtml(v,c),y()})}else p=O.readFileSync(A.resolve(process.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const C=K.Router();C.use(P.initSEOMiddleware({autoReturnHtml:!0,allowCrawler:q})),C.get("/:path(*)?",async(c,b,j)=>{var $,E,L;if(Y.some(l=>{var i;return(i=c.path)==null?void 0:i.startsWith(l)})){j();return}const y=performance.now(),v=()=>Math.round(performance.now()-y),x="production";let o,u,g=p;if(c.path.startsWith("/pages")){const l=c.params.lang,i=c.cookies.nf_lang,w=new Set([...d.default.env.languages.map(h=>h.code)]);let f=(l&&w.has(l)?l:void 0)||(w.has(i)?i:void 0)||[...w][0];if((!f||!(($=t.supportedLocales)!=null&&$.find(h=>h.locale===f)))&&(f=((L=(E=t.supportedLocales)==null?void 0:E[0])==null?void 0:L.locale)||""),f){const h=[];Object.values(t.pages).forEach(r=>{const N=Object.values((r==null?void 0:r.sections)??{}).filter(a=>{var _;return a.component==="custom-component"&&((_=a.config)==null?void 0:_.componentId)}).map(a=>{var _,M;return{id:a.id,componentId:a.config.componentId,useCache:a.config.useCache,cacheDuration:a.config.cacheDuration,properties:(M=(_=a.locales)==null?void 0:_[f])==null?void 0:M.properties}});h.push(...N)});const H=new Promise(r=>{setTimeout(()=>{r({})},90*1e3)});try{await Promise.race([H,k.getPreloadComponents({mode:x,req:c,state:t,locale:f,instances:h,module:W.PreloadComponentScriptModule.UMD_FN}).then(r=>{r&&(u=J.injectPreloadComponents(r))})])}catch(r){k.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),k.logger.warn(r)}}}try{const l=(o==null?void 0:o.title)||d.default.env.appName,i=(o==null?void 0:o.description)||d.default.env.appDescription,w=S.withQuery(S.joinURL(d.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:l,description:i});g=X.default.render(p,{ogTitle:l,ogDescription:i,ogImage:F(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,B=c.query.mode==="draft"||c.url.includes("preview"),m=I.load(g);m("head").find("#injected-head-elements").replaceWith(`
2
2
  ${o!=null&&o.backgroundColor?`<meta name="theme-color" content="${o.backgroundColor}" /><style>html,body,#app {background-color: ${o.backgroundColor} !important;}</style>`:""}
3
3
  ${n!=null&&n.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${n.title}&display=swap">`:""}
4
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 +1 @@
1
- "use strict";const c=require("./chunks/site-state-B0YNPQJU.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),X=require("lodash/groupBy"),W=require("lodash/sortBy"),b=require("path"),$=require("@blocklet/sdk/lib/middlewares/auth"),G=require("@blocklet/sdk/lib/component"),y=t=>t&&t.__esModule?t:{default:t},l=y(F),I=y(J),D=y(X),K=y(W),k=y(b),v=y($);new M.AsyncLocalStorage;const Y=async(t,e,o)=>{var n,s,r,i;try{const{projectId:u}=t.params;if(!u)return o();const f=await c.Project.findByPk(u);if(!f)return e==null?void 0:e.status(404).json({error:"Project not found"});const _=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!_)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===_,a=(i=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:i.call(r,h);if(!w&&!a)return e==null?void 0:e.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(h))return e==null?void 0:e.status(403).json({error:"No permission to access this project in single-tenant mode"});t.project=f,t.projectId=u,o()}catch(u){c.logger.error("Project middleware error:",u),e==null||e.status(500).json({error:"Internal server error"})}};function N(t,e){return new Promise((o,n)=>{const s=l.default.createReadStream(t),r=l.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await l.default.promises.mkdir(e,{recursive:!0});const o=await l.default.promises.readdir(t,{withFileTypes:!0});for(const n of o){const s=k.default.join(t,n.name),r=k.default.join(e,n.name);n.isDirectory()?await T(s,r):await N(s,r)}}async function z(t,e){(await l.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const O=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),H=(t,e)=>{const o=G.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",P=":",E="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(P),Q=t=>{const[e,o,n]=t.split(P);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(P),V=t=>{const[e,o,n]=t.split(P);if(e===q)return{componentId:n,projectId:o}},Z=t=>[L,t].join(P),tt=t=>{const[e,o]=t.split(P);if(e===L)return o},et=t=>{try{return JSON.parse(t)}catch{}return{}};async function x(t){const e=await c.SiteState.shared(t).getState("production"),o=await c.Project.findByPk(t),n=e.pageIds.map(r=>{const i=e.pages[r];if(i)return{id:C({pageId:r,projectId:t}),name:i.slug}}).filter(Boolean),s=K.default(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:Z(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:E,projectId:t}),name:"Pages",children:n},{id:A({componentId:E,projectId:t}),name:"Components",children:s}]}}S.get("/resources",O,async(t,e)=>{const{projectId:o}=et(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await Y(t,e,()=>{});const r=await x(o);e.json({resources:[r]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(r=>x(r.id)));e.json({resources:s})});const ot=I.default.object({projectId:I.default.string().required().min(1),releaseId:I.default.string().allow(""),resources:I.default.array().items(I.default.string()).required(),locale:I.default.string().allow("")});S.post("/resources",O,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await ot.validateAsync(t.body),r="production",i=[],u=[];for(const a of o){if(tt(a))continue;const{pageId:m,projectId:j}=Q(a)||{};if(m)m===E||m&&j&&i.push({pageId:m,projectId:j});else{const{componentId:p,projectId:d}=V(a)||{};p===E||p&&d&&u.push({componentId:p,projectId:d})}}const f=D.default(i,"projectId"),_=D.default(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(_)]),w=H(n,s);l.default.rmSync(w,{recursive:!0,force:!0}),l.default.mkdirSync(w,{recursive:!0});for(const a of h){const m=await c.SiteState.shared(a).getState(r),j=f[a],p=_[a],d=j==null?void 0:j.map(g=>g.pageId),R=p==null?void 0:p.map(g=>g.componentId);if(d!=null&&d.length||R!=null&&R.length){const g=await c.toPackage(m,{exportAssets:!0,pageIds:d,componentIds:R});await z(g,w),l.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${a}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",O,async(t,e)=>{const{states:o}=await c.getResourceStates(),n=o==null?void 0:o.map(s=>{const r={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(r.components=s.state.components),Object.keys(r.components).length!==0)return r}).filter(Boolean);e.json(n)});module.exports=S;
1
+ "use strict";const c=require("./chunks/site-state-CJ36w6-7.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),X=require("lodash/groupBy"),W=require("lodash/sortBy"),b=require("path"),$=require("@blocklet/sdk/lib/middlewares/auth"),G=require("@blocklet/sdk/lib/component"),y=t=>t&&t.__esModule?t:{default:t},l=y(F),I=y(J),D=y(X),K=y(W),k=y(b),v=y($);new M.AsyncLocalStorage;const Y=async(t,e,o)=>{var n,s,r,i;try{const{projectId:u}=t.params;if(!u)return o();const f=await c.Project.findByPk(u);if(!f)return e==null?void 0:e.status(404).json({error:"Project not found"});const _=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!_)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===_,a=(i=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:i.call(r,h);if(!w&&!a)return e==null?void 0:e.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(h))return e==null?void 0:e.status(403).json({error:"No permission to access this project in single-tenant mode"});t.project=f,t.projectId=u,o()}catch(u){c.logger.error("Project middleware error:",u),e==null||e.status(500).json({error:"Internal server error"})}};function N(t,e){return new Promise((o,n)=>{const s=l.default.createReadStream(t),r=l.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await l.default.promises.mkdir(e,{recursive:!0});const o=await l.default.promises.readdir(t,{withFileTypes:!0});for(const n of o){const s=k.default.join(t,n.name),r=k.default.join(e,n.name);n.isDirectory()?await T(s,r):await N(s,r)}}async function z(t,e){(await l.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const O=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),H=(t,e)=>{const o=G.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",P=":",E="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(P),Q=t=>{const[e,o,n]=t.split(P);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(P),V=t=>{const[e,o,n]=t.split(P);if(e===q)return{componentId:n,projectId:o}},Z=t=>[L,t].join(P),tt=t=>{const[e,o]=t.split(P);if(e===L)return o},et=t=>{try{return JSON.parse(t)}catch{}return{}};async function x(t){const e=await c.SiteState.shared(t).getState("production"),o=await c.Project.findByPk(t),n=e.pageIds.map(r=>{const i=e.pages[r];if(i)return{id:C({pageId:r,projectId:t}),name:i.slug}}).filter(Boolean),s=K.default(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:Z(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:E,projectId:t}),name:"Pages",children:n},{id:A({componentId:E,projectId:t}),name:"Components",children:s}]}}S.get("/resources",O,async(t,e)=>{const{projectId:o}=et(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await Y(t,e,()=>{});const r=await x(o);e.json({resources:[r]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(r=>x(r.id)));e.json({resources:s})});const ot=I.default.object({projectId:I.default.string().required().min(1),releaseId:I.default.string().allow(""),resources:I.default.array().items(I.default.string()).required(),locale:I.default.string().allow("")});S.post("/resources",O,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await ot.validateAsync(t.body),r="production",i=[],u=[];for(const a of o){if(tt(a))continue;const{pageId:m,projectId:j}=Q(a)||{};if(m)m===E||m&&j&&i.push({pageId:m,projectId:j});else{const{componentId:p,projectId:d}=V(a)||{};p===E||p&&d&&u.push({componentId:p,projectId:d})}}const f=D.default(i,"projectId"),_=D.default(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(_)]),w=H(n,s);l.default.rmSync(w,{recursive:!0,force:!0}),l.default.mkdirSync(w,{recursive:!0});for(const a of h){const m=await c.SiteState.shared(a).getState(r),j=f[a],p=_[a],d=j==null?void 0:j.map(g=>g.pageId),R=p==null?void 0:p.map(g=>g.componentId);if(d!=null&&d.length||R!=null&&R.length){const g=await c.toPackage(m,{exportAssets:!0,pageIds:d,componentIds:R});await z(g,w),l.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${a}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",O,async(t,e)=>{const{states:o}=await c.getResourceStates(),n=o==null?void 0:o.map(s=>{const r={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(r.components=s.state.components),Object.keys(r.components).length!==0)return r}).filter(Boolean);e.json(n)});module.exports=S;
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./chunks/site-state-B0YNPQJU.js");require("@blocklet/pages-kit/utils/property");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/cloneDeep");require("lodash/debounce");require("lodash/get");require("lodash/isEmpty");require("lodash/pick");require("lodash/set");require("lodash/union");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");const t=require("@blocklet/pages-kit/types/state");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;Object.keys(t).forEach(r=>{r!=="default"&&!Object.prototype.hasOwnProperty.call(exports,r)&&Object.defineProperty(exports,r,{enumerable:!0,get:()=>t[r]})});
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./chunks/site-state-CJ36w6-7.js");require("@blocklet/pages-kit/utils/property");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/cloneDeep");require("lodash/debounce");require("lodash/get");require("lodash/isEmpty");require("lodash/pick");require("lodash/set");require("lodash/union");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");const t=require("@blocklet/pages-kit/types/state");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;Object.keys(t).forEach(r=>{r!=="default"&&!Object.prototype.hasOwnProperty.call(exports,r)&&Object.defineProperty(exports,r,{enumerable:!0,get:()=>t[r]})});
@@ -5,23 +5,23 @@ import { getComponentMountPoint as dt } from "@blocklet/pages-kit/builtin/utils"
5
5
  import { PreloadComponentScriptModule as ae } from "@blocklet/pages-kit/types";
6
6
  import { componentUMDName as mt, RenderNestedComponent as Le, mergeComponent as ft, getComponentDependencies as gt } from "@blocklet/pages-kit/utils/property";
7
7
  import { memoize as fe, Sandbox as We, BuiltinModules as ht } from "@blocklet/quickjs";
8
- import y from "@blocklet/sdk/lib/config";
9
- import { LRUCache as Ae } from "lru-cache";
8
+ import g from "@blocklet/sdk/lib/config";
9
+ import { LRUCache as Ce } from "lru-cache";
10
10
  import yt, { Headers as St } from "node-fetch";
11
11
  import { joinURL as G, getQuery as wt, withQuery as Et, parseURL as Re, withHttps as bt } from "ufo";
12
12
  import { createHash as ge } from "crypto";
13
13
  import It from "@blocklet/logger";
14
14
  import { BuiltinModules as Ot } from "@blocklet/pages-kit/utils/builtin";
15
- import { createBuiltinModuleTransformer as vt, isRelativeModule as Ct } from "@blocklet/pages-kit/utils/typescript/builtin-module-transformer";
16
- import { getResources as At, getComponentWebEndpoint as Pt, call as Tt } from "@blocklet/sdk/lib/component";
15
+ import { createBuiltinModuleTransformer as At, isRelativeModule as vt } from "@blocklet/pages-kit/utils/typescript/builtin-module-transformer";
16
+ import { getResources as Ct, getComponentWebEndpoint as Pt, call as Tt } from "@blocklet/sdk/lib/component";
17
17
  import xt from "autoprefixer";
18
18
  import * as jt from "esbuild";
19
- import { readFileSync as X, existsSync as V, lstatSync as ie, readdirSync as kt, rmSync as qe, mkdtempSync as Dt, renameSync as Ue, mkdirSync as B, writeFileSync as le, copyFileSync as Nt, createWriteStream as Lt } from "fs";
19
+ import { readFileSync as X, existsSync as V, lstatSync as ie, readdirSync as kt, rmSync as qe, mkdtempSync as Dt, renameSync as _e, mkdirSync as B, writeFileSync as le, copyFileSync as Nt, createWriteStream as Lt } from "fs";
20
20
  import Rt from "postcss";
21
- import Ut from "tailwindcss";
21
+ import _t from "tailwindcss";
22
22
  import k from "typescript";
23
- import { reactive as Mt } from "@reactivedata/reactive";
24
- import { syncedStore as _t, getYjsValue as we } from "@syncedstore/core";
23
+ import { reactive as Ut } from "@reactivedata/reactive";
24
+ import { syncedStore as Mt, getYjsValue as we } from "@syncedstore/core";
25
25
  import { globSync as Oe } from "glob";
26
26
  import * as Ee from "lib0/decoding";
27
27
  import * as x from "lib0/encoding";
@@ -30,7 +30,7 @@ import Qe from "lodash/debounce";
30
30
  import Pe from "lodash/get";
31
31
  import Ft from "lodash/isEmpty";
32
32
  import Bt from "lodash/pick";
33
- import Me from "lodash/set";
33
+ import Ue from "lodash/set";
34
34
  import Gt from "lodash/union";
35
35
  import { customAlphabet as Vt } from "nanoid";
36
36
  import Jt from "p-limit";
@@ -38,7 +38,7 @@ import Ht, { join as E, dirname as R, basename as q } from "path";
38
38
  import { pipeline as Kt } from "stream/promises";
39
39
  import { x as zt } from "tar";
40
40
  import Yt from "wait-on";
41
- import { Awareness as Wt, encodeAwarenessUpdate as _e, removeAwarenessStates as qt, applyAwarenessUpdate as Qt } from "y-protocols/awareness";
41
+ import { Awareness as Wt, encodeAwarenessUpdate as Me, removeAwarenessStates as qt, applyAwarenessUpdate as Qt } from "y-protocols/awareness";
42
42
  import { writeUpdate as Xt, writeSyncStep1 as Zt, readSyncMessage as es } from "y-protocols/sync";
43
43
  import * as Z from "yaml";
44
44
  import * as z from "yjs";
@@ -46,11 +46,12 @@ import ts from "lodash/isNil";
46
46
  import { DataTypes as P, Sequelize as ss, Model as Xe, Op as os } from "sequelize";
47
47
  import "sqlite3";
48
48
  import "@blocklet/pages-kit/types/state";
49
- y.env.mode;
50
- process.env.OPENAI_API_KEY;
49
+ g.env.mode;
50
+ g.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY;
51
+ g.env.OPENAI_BASE_URL || process.env.OPENAI_BASE_URL;
51
52
  const ns = "image-bin";
52
- y.env.INIT_TEMPLATE_PATH;
53
- const rs = process.env.DATABASE_URL || Ht.join(y.env.dataDir, "db/pages-kit.db"), $e = y, bo = () => y.env.tenantMode === "multiple", Io = () => {
53
+ g.env.INIT_TEMPLATE_PATH;
54
+ const rs = process.env.DATABASE_URL || Ht.join(g.env.dataDir, "db/pages-kit.db"), $e = g, bo = () => g.env.tenantMode === "multiple", Io = () => {
54
55
  var t;
55
56
  return (ts($e.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = $e.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
56
57
  }, b = It("pages-kit"), as = P.sqlite.DATE.parse;
@@ -152,7 +153,7 @@ const is = async (t, { componentId: o }) => {
152
153
  @tailwind utilities;
153
154
  `, s = `.CustomComponent_${o}`;
154
155
  return (await Rt([
155
- Ut({ content: [{ raw: t, extension: "tsx" }] }),
156
+ _t({ content: [{ raw: t, extension: "tsx" }] }),
156
157
  xt({
157
158
  overrideBrowserslist: ["> 1%", "last 2 versions"],
158
159
  stats: {}
@@ -180,7 +181,7 @@ ${t}
180
181
  module: k.ModuleKind.ESNext
181
182
  },
182
183
  transformers: {
183
- before: [vt(k)]
184
+ before: [At(k)]
184
185
  }
185
186
  }).outputText;
186
187
  if (o.tailwind && (e = await cs(e, { componentId: o.componentId })), o.module === ae.ESM) return e;
@@ -232,7 +233,7 @@ ${t}
232
233
  return { contents: `export { ${o} } from './component'`, loader: "tsx" };
233
234
  if (p.path === "component.tsx")
234
235
  return { contents: t, loader: "tsx" };
235
- if (Ct(p.path)) {
236
+ if (vt(p.path)) {
236
237
  const d = p.path.split("/").pop();
237
238
  if (c || (c = await De({ ensureLoaded: !1 })), (u = c == null ? void 0 : c.chunks) != null && u[d])
238
239
  try {
@@ -296,7 +297,7 @@ var ${t} = ${e ? "async" : ""} function () {
296
297
  return exports;
297
298
  };
298
299
  `;
299
- }, ee = new Ae({
300
+ }, ee = new Ce({
300
301
  max: 100
301
302
  }), us = 60 * 60, Be = 60;
302
303
  function ds(t) {
@@ -330,61 +331,61 @@ async function Oo({
330
331
  const i = (await Promise.all(
331
332
  n.map(async (f) => {
332
333
  try {
333
- const h = fs({
334
+ const y = fs({
334
335
  mode: t,
335
336
  instanceId: f.id,
336
337
  componentId: f.componentId,
337
338
  locale: s
338
339
  });
339
- if (t !== "draft" && f.useCache && ee.has(h))
340
- return b.info(`get preload component from cache: ${h}`), ee.get(h);
341
- const A = pe({ state: e, componentId: f.componentId });
342
- if (!A) return null;
340
+ if (t !== "draft" && f.useCache && ee.has(y))
341
+ return b.info(`get preload component from cache: ${y}`), ee.get(y);
342
+ const C = pe({ state: e, componentId: f.componentId });
343
+ if (!C) return null;
343
344
  const j = await gs({
344
345
  req: o,
345
346
  state: e,
346
- componentId: A.id,
347
+ componentId: C.id,
347
348
  locale: s,
348
349
  defaultLocale: a,
349
350
  properties: f.properties
350
351
  });
351
352
  if (!j) return null;
352
- const M = { instanceId: f.id, preload: j };
353
+ const U = { instanceId: f.id, preload: j };
353
354
  if (t !== "draft" && f.useCache) {
354
355
  let D = us;
355
- f.cacheDuration && (D = f.cacheDuration), b.info(`set preload component to cache(${D}s): ${h}`), ee.set(h, M, {
356
+ f.cacheDuration && (D = f.cacheDuration), b.info(`set preload component to cache(${D}s): ${y}`), ee.set(y, U, {
356
357
  ttl: D * 1e3
357
358
  });
358
359
  }
359
- return M;
360
- } catch (h) {
361
- return b.error("get preload component error", { instanceId: f.id, componentId: f.componentId }, { error: h }), null;
360
+ return U;
361
+ } catch (y) {
362
+ return b.error("get preload component error", { instanceId: f.id, componentId: f.componentId }, { error: y }), null;
362
363
  }
363
364
  })
364
365
  )).filter((f) => !!f), c = Object.values(
365
- i.reduce((f, h) => ({ ...f, ...h.preload.components }), {})
366
+ i.reduce((f, y) => ({ ...f, ...y.preload.components }), {})
366
367
  );
367
368
  async function p() {
368
369
  const f = await Promise.all(
369
- c.map(async (h) => {
370
- const A = mt({ componentId: h.component.id }), j = r === ae.ESM ? {
370
+ c.map(async (y) => {
371
+ const C = mt({ componentId: y.component.id }), j = r === ae.ESM ? {
371
372
  module: r,
372
- script: await Fe(h.script, {
373
- componentId: h.component.id,
373
+ script: await Fe(y.script, {
374
+ componentId: y.component.id,
374
375
  module: r,
375
376
  tailwind: t !== "draft"
376
377
  })
377
378
  } : {
378
379
  module: r,
379
- script: await Fe(h.script, {
380
- componentId: h.component.id,
380
+ script: await Fe(y.script, {
381
+ componentId: y.component.id,
381
382
  module: r,
382
- moduleName: A,
383
+ moduleName: C,
383
384
  tailwind: t !== "draft"
384
385
  }),
385
- moduleName: A
386
+ moduleName: C
386
387
  };
387
- return [h.component.id, { component: h.component, script: j }];
388
+ return [y.component.id, { component: y.component, script: j }];
388
389
  })
389
390
  );
390
391
  return Object.fromEntries(f);
@@ -486,7 +487,7 @@ function pe({ state: t, componentId: o }) {
486
487
  var e, s, n;
487
488
  return ((e = t.components[o]) == null ? void 0 : e.data) ?? ((n = (s = t.resources.components) == null ? void 0 : s[o]) == null ? void 0 : n.component);
488
489
  }
489
- function vo({ state: t, name: o }) {
490
+ function Ao({ state: t, name: o }) {
490
491
  var s, n;
491
492
  const e = o.toLowerCase();
492
493
  return ((s = Object.values(t.components).find((r) => {
@@ -568,8 +569,8 @@ export { joinURL, withQuery, getQuery, getComponentMountPoint }
568
569
  // because the global is shared between all runtime and just init once
569
570
  location: { href: G(bt(s.hostname), s.originalUrl) },
570
571
  fetch: (a, { ...i } = {}) => {
571
- const c = typeof a == "string" && a.startsWith("/") ? G(y.env.appUrl, a) : a;
572
- if (typeof c == "string" && Re(c).host === Re(y.env.appUrl).host) {
572
+ const c = typeof a == "string" && a.startsWith("/") ? G(g.env.appUrl, a) : a;
573
+ if (typeof c == "string" && Re(c).host === Re(g.env.appUrl).host) {
573
574
  const p = s.get("cookie");
574
575
  if (p) {
575
576
  const u = new St(i.headers);
@@ -626,13 +627,13 @@ const ws = fe(
626
627
  ttl: 1e3 * 60 * 60
627
628
  }
628
629
  }
629
- ), Es = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", Ge = "page", ve = "trigger-reload-project-resource", tt = Es, bs = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM", { uploadToMediaKit: Is } = require("@blocklet/uploader-server"), Ve = Vt("abcdefghijklmnopqrstuvwxyz0123456789", 16), Te = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, te = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Je = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, Os = 1e4, vs = 3e4, ne = 0, be = 1, Cs = 0, As = 1, Ce = y, re = E(process.env.BLOCKLET_DATA_DIR, "site-state"), Co = ["production", "draft"], Ao = ["production"];
630
+ ), Es = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", Ge = "page", Ae = "trigger-reload-project-resource", tt = Es, bs = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM", { uploadToMediaKit: Is } = require("@blocklet/uploader-server"), Ve = Vt("abcdefghijklmnopqrstuvwxyz0123456789", 16), Te = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, te = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Je = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, Os = 1e4, As = 3e4, ne = 0, be = 1, vs = 0, Cs = 1, ve = g, re = E(process.env.BLOCKLET_DATA_DIR, "site-state"), vo = ["production", "draft"], Co = ["production"];
630
631
  function st(t) {
631
632
  return (t == null ? void 0 : t.replace(/\//g, "|")) || "";
632
633
  }
633
634
  function Ps() {
634
635
  var e;
635
- const t = Ce.env.languages.map((s) => ({ locale: s.code, name: s.name })), o = (e = t[0]) == null ? void 0 : e.locale;
636
+ const t = ve.env.languages.map((s) => ({ locale: s.code, name: s.name })), o = (e = t[0]) == null ? void 0 : e.locale;
636
637
  return {
637
638
  pageIds: [],
638
639
  pages: {},
@@ -660,7 +661,7 @@ const F = class F extends z.Doc {
660
661
  }));
661
662
  }
662
663
  const a = x.createEncoder();
663
- x.writeVarUint(a, be), x.writeVarUint8Array(a, _e(this.awareness, l));
664
+ x.writeVarUint(a, be), x.writeVarUint8Array(a, Me(this.awareness, l));
664
665
  const i = x.toUint8Array(a);
665
666
  this.conns.forEach((c, p) => this.send(p, i));
666
667
  });
@@ -681,7 +682,7 @@ const F = class F extends z.Doc {
681
682
  a.has(c) ? (a.delete(c), i++) : n.splice(i, 1);
682
683
  }
683
684
  }
684
- e.splice(0, e.length), e.push(...Ce.env.languages.map((a) => ({ locale: a.code, name: a.name }))), r.defaultLocale = (l = e[0]) == null ? void 0 : l.locale;
685
+ e.splice(0, e.length), e.push(...ve.env.languages.map((a) => ({ locale: a.code, name: a.name }))), r.defaultLocale = (l = e[0]) == null ? void 0 : l.locale;
685
686
  {
686
687
  let a = 0;
687
688
  const i = /* @__PURE__ */ new Set();
@@ -692,7 +693,7 @@ const F = class F extends z.Doc {
692
693
  }
693
694
  });
694
695
  T(this, "send", (e, s) => {
695
- e.readyState !== Cs && e.readyState !== As && this.closeConn(e);
696
+ e.readyState !== vs && e.readyState !== Cs && this.closeConn(e);
696
697
  try {
697
698
  e.send(s, (n) => {
698
699
  n && this.closeConn(e);
@@ -753,7 +754,7 @@ const F = class F extends z.Doc {
753
754
  this.closeConn(e), clearInterval(n);
754
755
  }
755
756
  }
756
- }, vs);
757
+ }, As);
757
758
  e.on("close", () => {
758
759
  this.closeConn(e), clearInterval(n);
759
760
  }), e.on("pong", () => {
@@ -765,7 +766,7 @@ const F = class F extends z.Doc {
765
766
  const l = this.awareness.getStates();
766
767
  if (l.size > 0) {
767
768
  const a = x.createEncoder();
768
- x.writeVarUint(a, be), x.writeVarUint8Array(a, _e(this.awareness, Array.from(l.keys()))), this.send(e, x.toUint8Array(a));
769
+ x.writeVarUint(a, be), x.writeVarUint8Array(a, Me(this.awareness, Array.from(l.keys()))), this.send(e, x.toUint8Array(a));
769
770
  }
770
771
  }
771
772
  });
@@ -788,8 +789,8 @@ const F = class F extends z.Doc {
788
789
  }
789
790
  this.save();
790
791
  });
791
- this.options = e, V(this.draftYjsFilePath) && z.applyUpdate(this, X(this.draftYjsFilePath)), this.syncedStore = Mt(
792
- _t(
792
+ this.options = e, V(this.draftYjsFilePath) && z.applyUpdate(this, X(this.draftYjsFilePath)), this.syncedStore = Ut(
793
+ Mt(
793
794
  { pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
794
795
  this
795
796
  )
@@ -801,7 +802,7 @@ const F = class F extends z.Doc {
801
802
  throw new Error("Should provide project context");
802
803
  try {
803
804
  const s = E(re, e), n = E(re, `@del-${e}`);
804
- Ue(s, n);
805
+ _e(s, n);
805
806
  } catch (s) {
806
807
  b.error("Failed to safe delete project state dir:", s);
807
808
  }
@@ -856,25 +857,25 @@ const F = class F extends z.Doc {
856
857
  return JSON.parse(JSON.stringify(this.syncedStore));
857
858
  if (!this.states[e] && (this.states[e] = await rt(this.getPublishDir(e), { includeResources: !0 }) ?? Ps(), !((n = (s = this.states[e]) == null ? void 0 : s.config) != null && n.defaultLocale))) {
858
859
  (r = this.states[e]).config ?? (r.config = {});
859
- const a = Ce.env.languages.map((i) => ({ locale: i.code, name: i.name }));
860
+ const a = ve.env.languages.map((i) => ({ locale: i.code, name: i.name }));
860
861
  this.states[e].config.defaultLocale = (l = a[0]) == null ? void 0 : l.locale;
861
862
  }
862
863
  return {
863
864
  ...this.states[e],
864
865
  resources: await De().then(async (a) => {
865
- var u, d, f, h;
866
+ var u, d, f, y;
866
867
  const { pages: i, components: c } = Bt(a, "pages", "components");
867
868
  let p = c;
868
869
  if ((d = (u = this.states[e]) == null ? void 0 : u.resources) != null && d.components)
869
870
  p = {
870
- ...(h = (f = this.states[e]) == null ? void 0 : f.resources) == null ? void 0 : h.components
871
+ ...(y = (f = this.states[e]) == null ? void 0 : f.resources) == null ? void 0 : y.components
871
872
  };
872
873
  else {
873
- const A = q(this.options.path), j = await Y.findByPk(A);
874
+ const C = q(this.options.path), j = await Y.findByPk(C);
874
875
  if (j != null && j.useAllResources)
875
876
  p = c;
876
877
  else {
877
- const D = (await he.findAll({ where: { projectId: A } })).map((S) => S.componentId);
878
+ const D = (await he.findAll({ where: { projectId: C } })).map((S) => S.componentId);
878
879
  p = Object.fromEntries(
879
880
  Object.entries(c || {}).filter(([S]) => D.includes(S))
880
881
  );
@@ -886,7 +887,7 @@ const F = class F extends z.Doc {
886
887
  }
887
888
  async setState(e, s) {
888
889
  const n = await ks(s, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(e);
889
- B(R(r), { recursive: !0 }), qe(r, { force: !0, recursive: !0 }), Ue(n, r), this.states[e] = s;
890
+ B(R(r), { recursive: !0 }), qe(r, { force: !0, recursive: !0 }), _e(n, r), this.states[e] = s;
890
891
  }
891
892
  getPublishDir(e) {
892
893
  return E(this.options.path, e);
@@ -897,7 +898,7 @@ const F = class F extends z.Doc {
897
898
  const l = await Y.findByPk(r);
898
899
  if (!l) continue;
899
900
  const a = await F.shared(r).getState(e), i = Gt(
900
- y.env.languages.map((c) => c.code),
901
+ g.env.languages.map((c) => c.code),
901
902
  a.supportedLocales.map((c) => c.locale)
902
903
  );
903
904
  for (const c of a.pageIds) {
@@ -925,9 +926,9 @@ const F = class F extends z.Doc {
925
926
  shouldRedirect: !0,
926
927
  mainPage: !0
927
928
  };
928
- for (const h of i) {
929
- const A = { ...f, locale: h };
930
- n[G("/", h, r, u)] = A, d && (n[G("/", h, d, u)] = A);
929
+ for (const y of i) {
930
+ const C = { ...f, locale: y };
931
+ n[G("/", y, r, u)] = C, d && (n[G("/", y, d, u)] = C);
931
932
  }
932
933
  }
933
934
  }
@@ -951,7 +952,7 @@ const F = class F extends z.Doc {
951
952
  }
952
953
  };
953
954
  T(F, "INSTANCE_TTL", 30 * 60 * 1e3), // 30 minutes
954
- T(F, "sharedInstances", new Ae({
955
+ T(F, "sharedInstances", new Ce({
955
956
  max: 100,
956
957
  // Maximum number of instances to store
957
958
  ttl: F.INSTANCE_TTL,
@@ -961,12 +962,12 @@ T(F, "sharedInstances", new Ae({
961
962
  }));
962
963
  let ue = F;
963
964
  function ot() {
964
- return Dt(E(y.env.dataDir, "tmp-"));
965
+ return Dt(E(g.env.dataDir, "tmp-"));
965
966
  }
966
967
  function de(t, o, e = []) {
967
968
  return Array.isArray(t) ? t.flatMap((s, n) => de(s, o, [...e, n])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([s, n]) => de(n, o, [...e, s])) : o(t) ? [e] : [];
968
969
  }
969
- function U(t) {
970
+ function _(t) {
970
971
  return t.filter((o) => o != null);
971
972
  }
972
973
  async function Ts(t, o, e) {
@@ -1025,7 +1026,7 @@ async function Ie(t, o, e) {
1025
1026
  await js(a, R(r));
1026
1027
  }
1027
1028
  }
1028
- const He = new Ae({
1029
+ const He = new Ce({
1029
1030
  max: 1e3,
1030
1031
  ttl: 30 * 24 * 60 * 60 * 1e3
1031
1032
  });
@@ -1039,13 +1040,13 @@ async function Ke(t, o, e) {
1039
1040
  try {
1040
1041
  const c = Pe(t, i), p = nt(c);
1041
1042
  for (const u of p) {
1042
- const d = q(u), f = e.getFilePath(u, i), h = f ? `${f}:${d}` : d, A = He.get(h);
1043
- if (A) {
1044
- te.test(c) || Me(t, i, A);
1043
+ const d = q(u), f = e.getFilePath(u, i), y = f ? `${f}:${d}` : d, C = He.get(y);
1044
+ if (C) {
1045
+ te.test(c) || Ue(t, i, C);
1045
1046
  return;
1046
1047
  }
1047
1048
  const j = await Ts(f, d, o);
1048
- j && (te.test(c) || Me(t, i, j), He.set(h, j));
1049
+ j && (te.test(c) || Ue(t, i, j), He.set(y, j));
1049
1050
  }
1050
1051
  } catch (c) {
1051
1052
  b.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
@@ -1061,13 +1062,13 @@ async function ks(t, {
1061
1062
  rawConfig: n,
1062
1063
  includeResources: r = !1
1063
1064
  } = {}) {
1064
- var M, D, g, S, w, I, J, O, N, H, oe, Q;
1065
+ var U, D, h, S, w, I, J, O, N, H, oe, Q;
1065
1066
  const l = e === "all" ? t.pageIds : e, a = gt({
1066
1067
  state: t,
1067
1068
  pageIds: l,
1068
1069
  componentIds: s === "all" ? Object.keys(t.components) : s
1069
- }), i = (m, v) => {
1070
- var C;
1070
+ }), i = (m, A) => {
1071
+ var v;
1071
1072
  return {
1072
1073
  id: m.id,
1073
1074
  name: m.name,
@@ -1077,10 +1078,10 @@ async function ks(t, {
1077
1078
  component: m.component,
1078
1079
  config: m.config,
1079
1080
  visibility: m.visibility,
1080
- properties: ((C = m.locales) == null ? void 0 : C[v]) ?? {}
1081
+ properties: ((v = m.locales) == null ? void 0 : v[A]) ?? {}
1081
1082
  };
1082
- }, c = (m, v) => {
1083
- var C;
1083
+ }, c = (m, A) => {
1084
+ var v;
1084
1085
  return {
1085
1086
  id: m.id,
1086
1087
  createdAt: m.createdAt,
@@ -1088,22 +1089,22 @@ async function ks(t, {
1088
1089
  publishedAt: m.publishedAt,
1089
1090
  isPublic: m.isPublic ?? !0,
1090
1091
  templateConfig: m.templateConfig,
1091
- meta: ((C = m.locales) == null ? void 0 : C[v]) ?? {},
1092
- sections: U(
1092
+ meta: ((v = m.locales) == null ? void 0 : v[A]) ?? {},
1093
+ sections: _(
1093
1094
  m.sectionIds.map(($) => {
1094
- const _ = m.sections[$];
1095
- return _ && i(_, v);
1095
+ const M = m.sections[$];
1096
+ return M && i(M, A);
1096
1097
  })
1097
1098
  )
1098
1099
  };
1099
- }, p = U(
1100
+ }, p = _(
1100
1101
  t.supportedLocales.map((m) => m.locale).flatMap(
1101
- (m) => l.map((v) => {
1102
- const C = t.pages[v];
1103
- return C && {
1102
+ (m) => l.map((A) => {
1103
+ const v = t.pages[A];
1104
+ return v && {
1104
1105
  locale: m,
1105
- slug: C.slug,
1106
- page: c(C, m)
1106
+ slug: v.slug,
1107
+ page: c(v, m)
1107
1108
  };
1108
1109
  })
1109
1110
  )
@@ -1111,45 +1112,45 @@ async function ks(t, {
1111
1112
  B(d, { recursive: !0 });
1112
1113
  const f = E(u, "components");
1113
1114
  B(f, { recursive: !0 });
1114
- for (const { locale: m, slug: v, page: C } of p)
1115
- await Ie(C, d, {
1116
- getFilename: () => `${st(v) || "index"}.${m}.yml`,
1115
+ for (const { locale: m, slug: A, page: v } of p)
1116
+ await Ie(v, d, {
1117
+ getFilename: () => `${st(A) || "index"}.${m}.yml`,
1117
1118
  exportAssets: o
1118
1119
  });
1119
1120
  for (const m of a) {
1120
- const v = (M = t.components[m]) == null ? void 0 : M.data;
1121
- v && await Ie(v, f, {
1122
- getFilename: (C) => `${C.name || "unnamed"}.${C.id}.yml`,
1121
+ const A = (U = t.components[m]) == null ? void 0 : U.data;
1122
+ A && await Ie(A, f, {
1123
+ getFilename: (v) => `${v.name || "unnamed"}.${v.id}.yml`,
1123
1124
  exportAssets: o
1124
1125
  });
1125
1126
  }
1126
- const h = E(u, ".blocklet/pages/pages.config.yml");
1127
- B(R(h), { recursive: !0 });
1128
- const A = {
1129
- pages: U(
1127
+ const y = E(u, ".blocklet/pages/pages.config.yml");
1128
+ B(R(y), { recursive: !0 });
1129
+ const C = {
1130
+ pages: _(
1130
1131
  l.map((m) => {
1131
- const v = t.pages[m];
1132
- return v && { id: m, slug: v.slug };
1132
+ const A = t.pages[m];
1133
+ return A && { id: m, slug: A.slug };
1133
1134
  })
1134
1135
  ),
1135
- components: U(
1136
+ components: _(
1136
1137
  a.map((m) => {
1137
- var C;
1138
- const v = (C = t.components[m]) == null ? void 0 : C.data;
1139
- return v && {
1138
+ var v;
1139
+ const A = (v = t.components[m]) == null ? void 0 : v.data;
1140
+ return A && {
1140
1141
  id: m,
1141
- name: v.name
1142
+ name: A.name
1142
1143
  };
1143
1144
  })
1144
1145
  ),
1145
1146
  ...r ? {
1146
1147
  resources: {
1147
- components: U(
1148
+ components: _(
1148
1149
  Object.keys(((D = t.resources) == null ? void 0 : D.components) || {}).filter((m) => a.includes(m)).map((m) => {
1149
- var v, C, $, _;
1150
+ var A, v, $, M;
1150
1151
  return {
1151
1152
  id: m,
1152
- name: (_ = ($ = (C = (v = t.resources) == null ? void 0 : v.components) == null ? void 0 : C[m]) == null ? void 0 : $.component) == null ? void 0 : _.name
1153
+ name: (M = ($ = (v = (A = t.resources) == null ? void 0 : A.components) == null ? void 0 : v[m]) == null ? void 0 : $.component) == null ? void 0 : M.name
1153
1154
  };
1154
1155
  })
1155
1156
  )
@@ -1158,32 +1159,32 @@ async function ks(t, {
1158
1159
  supportedLocales: t.supportedLocales,
1159
1160
  config: t.config
1160
1161
  };
1161
- le(h, Z.stringify(A));
1162
+ le(y, Z.stringify(C));
1162
1163
  const j = E(u, "config.source.json");
1163
1164
  if (n && le(j, JSON.stringify(n)), r) {
1164
- const m = E(u, "resources"), v = E(m, "components");
1165
- B(v, { recursive: !0 });
1166
- for (const _ of Object.keys(((g = t == null ? void 0 : t.resources) == null ? void 0 : g.components) ?? {}).filter(
1165
+ const m = E(u, "resources"), A = E(m, "components");
1166
+ B(A, { recursive: !0 });
1167
+ for (const M of Object.keys(((h = t == null ? void 0 : t.resources) == null ? void 0 : h.components) ?? {}).filter(
1167
1168
  (L) => a.includes(L)
1168
1169
  )) {
1169
- const L = (I = (w = (S = t.resources) == null ? void 0 : S.components) == null ? void 0 : w[_]) == null ? void 0 : I.component;
1170
- L && await Ie(L, v, {
1170
+ const L = (I = (w = (S = t.resources) == null ? void 0 : S.components) == null ? void 0 : w[M]) == null ? void 0 : I.component;
1171
+ L && await Ie(L, A, {
1171
1172
  getFilename: (K) => `${K.name || "unnamed"}.${K.id}.yml`,
1172
1173
  exportAssets: o
1173
1174
  });
1174
1175
  }
1175
- const C = E(u, "chunks");
1176
- B(C, { recursive: !0 });
1176
+ const v = E(u, "chunks");
1177
+ B(v, { recursive: !0 });
1177
1178
  const { chunks: $ } = await De();
1178
- for (const _ of Object.keys(((J = t == null ? void 0 : t.resources) == null ? void 0 : J.components) ?? {}).filter(
1179
+ for (const M of Object.keys(((J = t == null ? void 0 : t.resources) == null ? void 0 : J.components) ?? {}).filter(
1179
1180
  (L) => a.includes(L)
1180
1181
  )) {
1181
- const L = (H = (N = (O = t.resources) == null ? void 0 : O.components) == null ? void 0 : N[_]) == null ? void 0 : H.component;
1182
+ const L = (H = (N = (O = t.resources) == null ? void 0 : O.components) == null ? void 0 : N[M]) == null ? void 0 : H.component;
1182
1183
  if (L && ((oe = L.renderer) == null ? void 0 : oe.type) === "react-component") {
1183
1184
  const K = ((Q = L.renderer) == null ? void 0 : Q.chunks) ?? [];
1184
1185
  if ((K == null ? void 0 : K.length) > 0)
1185
1186
  for (const ye of K) {
1186
- const Ne = E(C, ye), Se = $ == null ? void 0 : $[ye];
1187
+ const Ne = E(v, ye), Se = $ == null ? void 0 : $[ye];
1187
1188
  try {
1188
1189
  Se && V(Se) && !V(Ne) && Nt(Se, Ne);
1189
1190
  } catch (lt) {
@@ -1205,26 +1206,26 @@ async function rt(t, { importAssets: o, includeResources: e } = {}) {
1205
1206
  const i = Oe("**/.blocklet/pages/pages.config.yml", { cwd: s, absolute: !0 }).at(0), c = i && E(R(i), "../../pages"), p = i && E(R(i), "../../components"), u = i && E(R(i), "../../chunks");
1206
1207
  if (!i)
1207
1208
  return null;
1208
- const d = Z.parse(X(i).toString()), f = (g, S, w) => {
1209
- let I = E(g, `${S}${w ? `.${w}` : ""}.yml`);
1210
- return (!V(I) || !ie(I).isFile()) && (I = E(g, S, `index${w ? `.${w}` : ""}.yml`), !V(I) || !ie(I)) ? null : Z.parse(X(I).toString());
1211
- }, h = (g, S) => {
1209
+ const d = Z.parse(X(i).toString()), f = (h, S, w) => {
1210
+ let I = E(h, `${S}${w ? `.${w}` : ""}.yml`);
1211
+ return (!V(I) || !ie(I).isFile()) && (I = E(h, S, `index${w ? `.${w}` : ""}.yml`), !V(I) || !ie(I)) ? null : Z.parse(X(I).toString());
1212
+ }, y = (h, S) => {
1212
1213
  try {
1213
- const w = Oe(`*.${S}.yml`, { cwd: g, absolute: !0 })[0];
1214
+ const w = Oe(`*.${S}.yml`, { cwd: h, absolute: !0 })[0];
1214
1215
  return w ? Z.parse(X(w).toString()) : null;
1215
1216
  } catch (w) {
1216
1217
  b.error("parse component error", w);
1217
1218
  }
1218
1219
  return null;
1219
- }, A = U(
1220
- d.pages.map(({ slug: g }) => {
1220
+ }, C = _(
1221
+ d.pages.map(({ slug: h }) => {
1221
1222
  var J;
1222
- const S = U(
1223
+ const S = _(
1223
1224
  d.supportedLocales.map(({ locale: O }) => {
1224
- const N = c ? f(c, st(g), O) : void 0;
1225
+ const N = c ? f(c, st(h), O) : void 0;
1225
1226
  if (N)
1226
1227
  return { locale: O, page: N };
1227
- const H = c ? f(c, g, O) : void 0;
1228
+ const H = c ? f(c, h, O) : void 0;
1228
1229
  return H && { locale: O, page: H };
1229
1230
  })
1230
1231
  ), w = (J = S[0]) == null ? void 0 : J.page;
@@ -1242,7 +1243,7 @@ async function rt(t, { importAssets: o, includeResources: e } = {}) {
1242
1243
  llmConfig: O.llmConfig,
1243
1244
  visibility: O.visibility,
1244
1245
  locales: Object.fromEntries(
1245
- U(
1246
+ _(
1246
1247
  S.map(({ locale: H, page: oe }) => {
1247
1248
  const Q = oe.sections.find((m) => m.id === N);
1248
1249
  return Q && [H, Q.properties];
@@ -1258,66 +1259,66 @@ async function rt(t, { importAssets: o, includeResources: e } = {}) {
1258
1259
  publishedAt: w.publishedAt,
1259
1260
  isPublic: w.isPublic ?? !0,
1260
1261
  templateConfig: w.templateConfig,
1261
- slug: g,
1262
+ slug: h,
1262
1263
  sections: Object.fromEntries(I.map((O) => [O.id, O])),
1263
1264
  sectionIds: I.map((O) => O.id),
1264
1265
  locales: Object.fromEntries(S.map(({ locale: O, page: N }) => [O, N.meta]))
1265
1266
  };
1266
1267
  })
1267
- ), j = p ? U(((r = d.components) == null ? void 0 : r.map(({ id: g }) => h(p, g))) ?? []) : [];
1268
+ ), j = p ? _(((r = d.components) == null ? void 0 : r.map(({ id: h }) => y(p, h))) ?? []) : [];
1268
1269
  if (o) {
1269
- const g = (...S) => {
1270
+ const h = (...S) => {
1270
1271
  b.info(`[${n ? q(t) : q(E(t, "../../../../"))}] importAssets:`, ...S);
1271
1272
  };
1272
1273
  try {
1273
- g("wait image-bin api ready"), await Yt({
1274
+ h("wait image-bin api ready"), await Yt({
1274
1275
  resources: [`${Pt(ns)}/api/sdk/uploads`],
1275
1276
  validateStatus: (I) => I >= 200 && I <= 500
1276
- }), g("image-bin api is ready");
1277
+ }), h("image-bin api is ready");
1277
1278
  const S = {}, w = {};
1278
- g("start to upload assets"), await Promise.allSettled([
1279
+ h("start to upload assets"), await Promise.allSettled([
1279
1280
  Ke(j, S, {
1280
1281
  getFilePath: (I) => p && E(p, I),
1281
1282
  onFinish: (I) => {
1282
- g(`upload ${I.length} component assets`);
1283
+ h(`upload ${I.length} component assets`);
1283
1284
  }
1284
1285
  }),
1285
- Ke(A, w, {
1286
+ Ke(C, w, {
1286
1287
  getFilePath: (I, J) => {
1287
- const O = Pe(A, J.slice(0, 1));
1288
+ const O = Pe(C, J.slice(0, 1));
1288
1289
  return c && E(c, R(O.slug), I);
1289
1290
  },
1290
1291
  onFinish: (I) => {
1291
- g(`upload ${I.length} page assets`);
1292
+ h(`upload ${I.length} page assets`);
1292
1293
  }
1293
1294
  })
1294
- ]), g("upload assets done"), global.gc && global.gc();
1295
+ ]), h("upload assets done"), global.gc && global.gc();
1295
1296
  } catch (S) {
1296
- g("Error during asset import:", S);
1297
+ h("Error during asset import:", S);
1297
1298
  }
1298
1299
  }
1299
- const M = {};
1300
+ const U = {};
1300
1301
  if (e) {
1301
- const g = i && E(R(i), "../../resources/components"), S = U(
1302
- ((a = (l = d.resources) == null ? void 0 : l.components) == null ? void 0 : a.map(({ id: w }) => h(g, w))) ?? []
1302
+ const h = i && E(R(i), "../../resources/components"), S = _(
1303
+ ((a = (l = d.resources) == null ? void 0 : l.components) == null ? void 0 : a.map(({ id: w }) => y(h, w))) ?? []
1303
1304
  );
1304
- S.length > 0 && (M.components = Object.fromEntries(
1305
+ S.length > 0 && (U.components = Object.fromEntries(
1305
1306
  S.map((w, I) => [w.id, { index: I, component: w }])
1306
1307
  ));
1307
1308
  }
1308
1309
  const D = {};
1309
1310
  if (u && V(u)) {
1310
- const g = kt(u);
1311
- for (const S of g)
1311
+ const h = kt(u);
1312
+ for (const S of h)
1312
1313
  D[S] = E(u, S);
1313
1314
  }
1314
1315
  return {
1315
1316
  supportedLocales: d.supportedLocales,
1316
- pageIds: A.map((g) => g.id),
1317
- components: Object.fromEntries(j.map((g, S) => [g.id, { index: S, data: g }])),
1318
- pages: Object.fromEntries(A.map((g) => [g.id, g])),
1317
+ pageIds: C.map((h) => h.id),
1318
+ components: Object.fromEntries(j.map((h, S) => [h.id, { index: S, data: h }])),
1319
+ pages: Object.fromEntries(C.map((h) => [h.id, h])),
1319
1320
  config: d.config || {},
1320
- resources: M,
1321
+ resources: U,
1321
1322
  chunks: D
1322
1323
  };
1323
1324
  } finally {
@@ -1412,7 +1413,7 @@ const at = fe(
1412
1413
  let me, W, xe, je, ke;
1413
1414
  function it() {
1414
1415
  return me = (async () => {
1415
- const t = At({
1416
+ const t = Ct({
1416
1417
  types: [
1417
1418
  { did: tt, type: Ge },
1418
1419
  { did: bs, type: Ge }
@@ -1473,8 +1474,8 @@ function Ds(t) {
1473
1474
  // 3s
1474
1475
  { leading: !1, trailing: !0 }
1475
1476
  );
1476
- return o(), y.events.on(y.Events.componentAdded, o), y.events.on(y.Events.componentRemoved, o), y.events.on(y.Events.componentStarted, o), y.events.on(y.Events.componentStopped, o), y.events.on(y.Events.componentUpdated, o), y.events.on(ve, o), () => {
1477
- y.events.off(y.Events.componentAdded, o), y.events.off(y.Events.componentRemoved, o), y.events.off(y.Events.componentStarted, o), y.events.off(y.Events.componentStopped, o), y.events.off(y.Events.componentUpdated, o), y.events.off(ve, o);
1477
+ return o(), g.events.on(g.Events.componentAdded, o), g.events.on(g.Events.componentRemoved, o), g.events.on(g.Events.componentStarted, o), g.events.on(g.Events.componentStopped, o), g.events.on(g.Events.componentUpdated, o), g.events.on(Ae, o), () => {
1478
+ g.events.off(g.Events.componentAdded, o), g.events.off(g.Events.componentRemoved, o), g.events.off(g.Events.componentStarted, o), g.events.off(g.Events.componentStopped, o), g.events.off(g.Events.componentUpdated, o), g.events.off(Ae, o);
1478
1479
  };
1479
1480
  }
1480
1481
  const ct = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), ce = globalThis;
@@ -1512,7 +1513,7 @@ ce[ct] = Ds(async ({ pages: t, components: o }) => {
1512
1513
  });
1513
1514
  });
1514
1515
  async function Po() {
1515
- b.info("trigger reload all project resource"), y.events.emit(ve);
1516
+ b.info("trigger reload all project resource"), g.events.emit(Ae);
1516
1517
  }
1517
1518
  async function De({
1518
1519
  ensureLoaded: t = !0
@@ -1535,13 +1536,13 @@ export {
1535
1536
  gs as h,
1536
1537
  bo as i,
1537
1538
  pe as j,
1538
- vo as k,
1539
+ Ao as k,
1539
1540
  b as l,
1540
1541
  ws as m,
1541
1542
  Ve as n,
1542
1543
  re as o,
1543
- Co as p,
1544
- Ao as q,
1544
+ vo as p,
1545
+ Co as q,
1545
1546
  rt as r,
1546
1547
  ze as s,
1547
1548
  ks as t,
@@ -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-BVJJFXxb.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-1S8NcEDR.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,4 +1,4 @@
1
- import { b as H, l as _ } from "./chunks/site-state-BVJJFXxb.js";
1
+ import { b as H, l as _ } from "./chunks/site-state-1S8NcEDR.js";
2
2
  import { initCronCrawlBlocklet as W, cancelCronCrawlBlocklet as N, initSEOMiddleware as J } from "@blocklet/crawler/middlewares";
3
3
  import { PreloadComponentScriptModule as G } from "@blocklet/pages-kit/types";
4
4
  import { injectPreloadComponents as K } from "@blocklet/pages-kit/utils/preload";
@@ -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-BVJJFXxb.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-1S8NcEDR.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,4 +1,4 @@
1
- import { q as v, o as B, p as L, S as U, r as b, a as h, u as w, s as y, n as z, t as C, v as F } from "./chunks/site-state-BVJJFXxb.js";
1
+ import { q as v, o as B, p as L, S as U, r as b, a as h, u as w, s as y, n as z, t as C, v as F } from "./chunks/site-state-1S8NcEDR.js";
2
2
  import "@blocklet/pages-kit/utils/property";
3
3
  import "@blocklet/quickjs";
4
4
  import "@blocklet/sdk/lib/component";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blocklet/pages-kit-inner-components",
3
- "version": "0.4.91",
3
+ "version": "0.4.92",
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": "^0.4.91",
206
- "@blocklet/pages-kit-block-studio": "^0.4.91"
205
+ "@blocklet/pages-kit": "^0.4.92",
206
+ "@blocklet/pages-kit-block-studio": "^0.4.92"
207
207
  },
208
208
  "devDependencies": {
209
209
  "@trivago/prettier-plugin-sort-imports": "^5.2.1",