@blocklet/pages-kit-inner-components 0.4.71 → 0.4.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- "use strict";var tt=Object.defineProperty;var st=(t,n,e)=>n in t?tt(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>st(t,typeof n!="symbol"?n+"":n,e);const nt=require("@blocklet/pages-kit/builtin/utils"),se=require("@blocklet/pages-kit/types"),oe=require("@blocklet/pages-kit/utils/property"),V=require("@blocklet/quickjs"),ot=require("@blocklet/sdk/lib/config"),Ee=require("lru-cache"),Le=require("node-fetch"),x=require("ufo"),ie=require("crypto"),rt=require("@blocklet/logger"),at=require("@blocklet/pages-kit/utils/builtin"),Ue=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),be=require("@blocklet/sdk/lib/component"),it=require("autoprefixer"),ct=require("esbuild"),E=require("fs"),lt=require("postcss"),pt=require("tailwindcss"),ut=require("typescript"),dt=require("@reactivedata/reactive"),ee=require("@syncedstore/core"),fe=require("glob"),ft=require("lib0/decoding"),mt=require("lib0/encoding"),N=require("lodash"),gt=require("nanoid"),ht=require("p-limit"),h=require("path"),yt=require("stream/promises"),St=require("tar"),wt=require("wait-on"),H=require("y-protocols/awareness"),le=require("y-protocols/sync"),Et=require("yaml"),bt=require("yjs"),Tt=require("lodash/isNil"),P=require("sequelize");require("sqlite3");const L=t=>t&&t.__esModule?t:{default:t};function X(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=L(ot),It=L(Le),Ot=L(rt),Ct=L(it),Pt=X(ct),jt=L(lt),At=L(pt),D=L(ut),pe=X(ft),_=X(mt),_t=L(ht),vt=L(h),Dt=L(wt),J=X(Et),B=X(bt),xt=L(Tt);w.default.env.mode;const kt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Rt=process.env.DATABASE_URL||vt.default.join(w.default.env.dataDir,"db/pages-kit.db"),ve=w.default,Nt=()=>w.default.env.tenantMode==="multiple",Lt=()=>{var t;return(xt.default(ve.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=ve.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},I=Ot.default("pages-kit"),Ut=P.DataTypes.sqlite.DATE.parse;P.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):Ut(t,n);const Z=new P.Sequelize({dialect:"sqlite",storage:Rt,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});Z.query("pragma journal_mode = WAL;");Z.query("pragma synchronous = normal;");Z.query("pragma journal_size_limit = 67108864;");class ce extends P.Model{}ce.init({id:{type:P.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:P.DataTypes.UUIDV4},projectId:{type:P.DataTypes.UUID,allowNull:!1},componentId:{type:P.DataTypes.STRING,allowNull:!1}},{sequelize:Z,tableName:"ProjectComponents",timestamps:!1});class $ extends P.Model{static async getProjectByIdOrSlug(n){return $.findOne({where:{[P.Op.or]:[{id:n},{slug:n}]}})}}$.init({id:{type:P.DataTypes.UUID,defaultValue:P.DataTypes.UUIDV4,primaryKey:!0},name:{type:P.DataTypes.STRING,allowNull:!1},description:P.DataTypes.TEXT,createdAt:P.DataTypes.DATE,updatedAt:P.DataTypes.DATE,createdBy:{type:P.DataTypes.STRING,allowNull:!1},updatedBy:{type:P.DataTypes.STRING,allowNull:!1},slug:P.DataTypes.STRING,icon:P.DataTypes.STRING,pinnedAt:P.DataTypes.DATE,useAllResources:P.DataTypes.BOOLEAN,npmSecret:P.DataTypes.STRING,relatedBlocklets:{type:P.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:Z,paranoid:!0});$.hasMany(ce,{foreignKey:"projectId",as:"components"});const Mt=async(t,{componentId:n})=>{const e=`@tailwind components;
1
+ "use strict";var tt=Object.defineProperty;var st=(t,n,e)=>n in t?tt(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>st(t,typeof n!="symbol"?n+"":n,e);const nt=require("@blocklet/pages-kit/builtin/utils"),se=require("@blocklet/pages-kit/types"),oe=require("@blocklet/pages-kit/utils/property"),H=require("@blocklet/quickjs"),ot=require("@blocklet/sdk/lib/config"),Ee=require("lru-cache"),Le=require("node-fetch"),x=require("ufo"),ie=require("crypto"),rt=require("@blocklet/logger"),at=require("@blocklet/pages-kit/utils/builtin"),Ue=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),be=require("@blocklet/sdk/lib/component"),it=require("autoprefixer"),ct=require("esbuild"),E=require("fs"),lt=require("postcss"),pt=require("tailwindcss"),ut=require("typescript"),dt=require("@reactivedata/reactive"),ee=require("@syncedstore/core"),fe=require("glob"),ft=require("lib0/decoding"),mt=require("lib0/encoding"),N=require("lodash"),gt=require("nanoid"),ht=require("p-limit"),h=require("path"),yt=require("stream/promises"),St=require("tar"),wt=require("wait-on"),G=require("y-protocols/awareness"),le=require("y-protocols/sync"),Et=require("yaml"),bt=require("yjs"),Tt=require("lodash/isNil"),P=require("sequelize");require("sqlite3");const L=t=>t&&t.__esModule?t:{default:t};function X(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=L(ot),It=L(Le),Ot=L(rt),Ct=L(it),Pt=X(ct),jt=L(lt),At=L(pt),D=L(ut),pe=X(ft),v=X(mt),vt=L(ht),_t=L(h),Dt=L(wt),J=X(Et),B=X(bt),xt=L(Tt);w.default.env.mode;const kt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Rt=process.env.DATABASE_URL||_t.default.join(w.default.env.dataDir,"db/pages-kit.db"),_e=w.default,Nt=()=>w.default.env.tenantMode==="multiple",Lt=()=>{var t;return(xt.default(_e.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=_e.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},I=Ot.default("pages-kit"),Ut=P.DataTypes.sqlite.DATE.parse;P.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):Ut(t,n);const Z=new P.Sequelize({dialect:"sqlite",storage:Rt,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});Z.query("pragma journal_mode = WAL;");Z.query("pragma synchronous = normal;");Z.query("pragma journal_size_limit = 67108864;");class ce extends P.Model{}ce.init({id:{type:P.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:P.DataTypes.UUIDV4},projectId:{type:P.DataTypes.UUID,allowNull:!1},componentId:{type:P.DataTypes.STRING,allowNull:!1}},{sequelize:Z,tableName:"ProjectComponents",timestamps:!1});class $ extends P.Model{static async getProjectByIdOrSlug(n){return $.findOne({where:{[P.Op.or]:[{id:n},{slug:n}]}})}}$.init({id:{type:P.DataTypes.UUID,defaultValue:P.DataTypes.UUIDV4,primaryKey:!0},name:{type:P.DataTypes.STRING,allowNull:!1},description:P.DataTypes.TEXT,createdAt:P.DataTypes.DATE,updatedAt:P.DataTypes.DATE,createdBy:{type:P.DataTypes.STRING,allowNull:!1},updatedBy:{type:P.DataTypes.STRING,allowNull:!1},slug:P.DataTypes.STRING,icon:P.DataTypes.STRING,pinnedAt:P.DataTypes.DATE,useAllResources:P.DataTypes.BOOLEAN,npmSecret:P.DataTypes.STRING,relatedBlocklets:{type:P.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:Z,paranoid:!0});$.hasMany(ce,{foreignKey:"projectId",as:"components"});const Mt=async(t,{componentId:n})=>{const e=`@tailwind components;
2
2
  @tailwind utilities;
3
3
  `,s=`.CustomComponent_${n}`;return(await jt.default([At.default({content:[{raw:t,extension:"tsx"}]}),Ct.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},Ft=async(t,{componentId:n})=>{const e=await Mt(t,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(e)};
4
4
 
5
5
  ${t}
6
- `},De=V.memoize(async(t,n)=>{let e=D.default.transpileModule(t,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.ESNext},transformers:{before:[Ue.createBuiltinModuleTransformer(D.default)]}}).outputText;if(n.tailwind&&(e=await Ft(e,{componentId:n.componentId})),n.module===se.PreloadComponentScriptModule.ESM)return e;const s=D.default.transpileModule(e,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.CommonJS,moduleResolution:D.default.ModuleResolutionKind.Node16}}).outputText;return n.module===se.PreloadComponentScriptModule.CJS?s:$t(n.moduleName,s)},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==se.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",e,s])},lruOptions:{max:100,ttl:1e3*60*60}}),qt=async(t,n)=>{var l,a;const s=(a=(l=(await Pt.build({entryPoints:["index.tsx"],external:Object.keys(at.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(i){let c=null;i.onResolve({filter:/.*/},p=>p.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:p.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),i.onLoad({filter:/.*/,namespace:"vfs"},async p=>{var u;if(p.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(p.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ue.isRelativeModule(p.path)){const m=p.path.split("/").pop();if(c||(c=await Ae({ensureLoaded:!1})),(u=c==null?void 0:c.chunks)!=null&&u[m])try{const g=E.readFileSync(c.chunks[m],"utf-8");return I.info("get chunk from local file system",m),{contents:g,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:l[0])==null?void 0:a.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return D.default.transpileModule(o,{compilerOptions:{module:D.default.ModuleKind.ESNext,target:D.default.ScriptTarget.ES2020}}).outputText},Me=V.memoize(async(t,n)=>{const e=await qt(t,n);return new RegExp(`export\\s+\\{\\s+${n}\\s+\\}`,"m").test(e)?e:void 0},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["extractExportValueSchema",e,n])},lruOptions:{max:100,ttl:1e3*60*60}}),$t=(t,n)=>{const e=/\bawait\b/.test(n);return`// GENERATED FILE. DO NOT EDIT.
6
+ `},De=H.memoize(async(t,n)=>{let e=D.default.transpileModule(t,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.ESNext},transformers:{before:[Ue.createBuiltinModuleTransformer(D.default)]}}).outputText;if(n.tailwind&&(e=await Ft(e,{componentId:n.componentId})),n.module===se.PreloadComponentScriptModule.ESM)return e;const s=D.default.transpileModule(e,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.CommonJS,moduleResolution:D.default.ModuleResolutionKind.Node16}}).outputText;return n.module===se.PreloadComponentScriptModule.CJS?s:$t(n.moduleName,s)},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==se.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",e,s])},lruOptions:{max:100,ttl:1e3*60*60}}),qt=async(t,n)=>{var l,a;const s=(a=(l=(await Pt.build({entryPoints:["index.tsx"],external:Object.keys(at.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(i){let c=null;i.onResolve({filter:/.*/},p=>p.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:p.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),i.onLoad({filter:/.*/,namespace:"vfs"},async p=>{var u;if(p.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(p.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ue.isRelativeModule(p.path)){const m=p.path.split("/").pop();if(c||(c=await Ae({ensureLoaded:!1})),(u=c==null?void 0:c.chunks)!=null&&u[m])try{const g=E.readFileSync(c.chunks[m],"utf-8");return I.info("get chunk from local file system",m),{contents:g,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:l[0])==null?void 0:a.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return D.default.transpileModule(o,{compilerOptions:{module:D.default.ModuleKind.ESNext,target:D.default.ScriptTarget.ES2020}}).outputText},Me=H.memoize(async(t,n)=>{const e=await qt(t,n);return new RegExp(`export\\s+\\{\\s+${n}\\s+\\}`,"m").test(e)?e:void 0},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["extractExportValueSchema",e,n])},lruOptions:{max:100,ttl:1e3*60*60}}),$t=(t,n)=>{const e=/\bawait\b/.test(n);return`// GENERATED FILE. DO NOT EDIT.
7
7
  var ${t} = ${e?"async":""} function () {
8
8
 
9
9
  const exports = {};
@@ -29,7 +29,7 @@ var ${t} = ${e?"async":""} function () {
29
29
 
30
30
  return exports;
31
31
  };
32
- `},K=new Ee.LRUCache({max:100}),Fe=60*60,me=60;function qe(t){I.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function $e(t){for(const n of K.keys())n.includes(t)&&(I.info("clear preload components cache",{cacheKey:n}),qe(n))}function Be({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function Bt({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=Be({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const j=W({state:e,componentId:g.componentId});if(!j)return null;const v=await Ve({req:n,state:e,componentId:j.id,locale:s,defaultLocale:a,properties:g.properties});if(!v)return null;const F={instanceId:g.id,preload:v};if(t!=="draft"&&g.useCache){let R=Fe;g.cacheDuration&&(R=g.cacheDuration),I.info(`set preload component to cache(${R}s): ${S}`),K.set(S,F,{ttl:R*1e3})}return F}catch(S){return I.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 p(){const g=await Promise.all(c.map(async S=>{const j=oe.componentUMDName({componentId:S.component.id}),v=r===se.PreloadComponentScriptModule.ESM?{module:r,script:await De(S.script,{componentId:S.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await De(S.script,{componentId:S.component.id,module:r,moduleName:j,tailwind:t!=="draft"}),moduleName:j};return[S.component.id,{component:S.component,script:v}]}));return Object.fromEntries(g)}const u=await p();return{config:{defaultLocale:a,supportedLocales:l},components:u,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function Ve({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:l}=n,a=W({state:n,componentId:e});if(!a)return null;const i=l.some(p=>p.locale===s)?s:o;if(!i)return null;const c=await Ge({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const Vt=20;async function Ge({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:l}){if(n>Vt)throw new RangeError("max component depth exceeded");const a=Gt({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 p=await zt({...a,req:t});p!=null&&p.props&&Object.assign(c.props,p.props)}catch(p){I.error("preload data at server side error",{componentId:s,name:a.component.name},{error:p})}return await Promise.all(Object.entries(i).map(async([p,u])=>{if((u==null?void 0:u.type)===oe.RenderNestedComponent){const m=await Ge({req:t,depth:n+1,state:e,componentId:u.componentId,locale:o,defaultLocale:r,properties:u.properties});m&&(Object.assign(c.components,m.components),Object.assign(c.props,{[p]:{type:oe.RenderNestedComponent,componentId:u.componentId,props:m.props}}))}})),c}function Gt({state:t,componentId:n,locale:e,properties:s}){const o=W({state:t,componentId:n});if(!o)return null;const r=oe.mergeComponent({componentId:n,getComponent:l=>W({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 W({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 Ht({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 zt({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Me(n,"getServerSideProps");if(!o)return null;const r=new Promise(a=>{setTimeout(()=>{I.error("getServerSideProps timeout"),a({})},me*1e3)});return await Promise.race([r,V.Sandbox.callFunction({code:`${o}
32
+ `},K=new Ee.LRUCache({max:100}),Fe=60*60,me=60;function qe(t){I.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function $e(t){for(const n of K.keys())n.includes(t)&&(I.info("clear preload components cache",{cacheKey:n}),qe(n))}function Be({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function Bt({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=Be({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const j=Q({state:e,componentId:g.componentId});if(!j)return null;const _=await He({req:n,state:e,componentId:j.id,locale:s,defaultLocale:a,properties:g.properties});if(!_)return null;const F={instanceId:g.id,preload:_};if(t!=="draft"&&g.useCache){let R=Fe;g.cacheDuration&&(R=g.cacheDuration),I.info(`set preload component to cache(${R}s): ${S}`),K.set(S,F,{ttl:R*1e3})}return F}catch(S){return I.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 p(){const g=await Promise.all(c.map(async S=>{const j=oe.componentUMDName({componentId:S.component.id}),_=r===se.PreloadComponentScriptModule.ESM?{module:r,script:await De(S.script,{componentId:S.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await De(S.script,{componentId:S.component.id,module:r,moduleName:j,tailwind:t!=="draft"}),moduleName:j};return[S.component.id,{component:S.component,script:_}]}));return Object.fromEntries(g)}const u=await p();return{config:{defaultLocale:a,supportedLocales:l},components:u,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function He({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:l}=n,a=Q({state:n,componentId:e});if(!a)return null;const i=l.some(p=>p.locale===s)?s:o;if(!i)return null;const c=await Ve({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const Ht=20;async function Ve({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:l}){if(n>Ht)throw new RangeError("max component depth exceeded");const a=Vt({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 p=await zt({...a,req:t});p!=null&&p.props&&Object.assign(c.props,p.props)}catch(p){I.error("preload data at server side error",{componentId:s,name:a.component.name},{error:p})}return await Promise.all(Object.entries(i).map(async([p,u])=>{if((u==null?void 0:u.type)===oe.RenderNestedComponent){const m=await Ve({req:t,depth:n+1,state:e,componentId:u.componentId,locale:o,defaultLocale:r,properties:u.properties});m&&(Object.assign(c.components,m.components),Object.assign(c.props,{[p]:{type:oe.RenderNestedComponent,componentId:u.componentId,props:m.props}}))}})),c}function Vt({state:t,componentId:n,locale:e,properties:s}){const o=Q({state:t,componentId:n});if(!o)return null;const r=oe.mergeComponent({componentId:n,getComponent:l=>Q({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 Q({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 Gt({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 zt({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Me(n,"getServerSideProps");if(!o)return null;const r=new Promise(a=>{setTimeout(()=>{I.error("getServerSideProps timeout"),a({})},me*1e3)});return await Promise.race([r,H.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 V.BuiltinModules.dayjs},global:{console:{log:(...a)=>{I.info(...a)},warn:(...a)=>{I.warn(...a)},error:(...a)=>{I.error(...a)}},getComponentMountPoint:nt.getComponentMountPoint,joinURL:x.joinURL,withQuery:x.withQuery,getQuery:x.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:x.joinURL(x.withHttps(s.hostname),s.originalUrl)},fetch:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?x.joinURL(w.default.env.appUrl,a):a;if(typeof c=="string"&&x.parseURL(c).host===x.parseURL(w.default.env.appUrl).host){const p=s.get("cookie");if(p){const u=new Le.Headers(i.headers);u.set("cookie",p),i.headers=u}}return It.default(c,{...i,timeout:me*1e3}).then(p=>({ok:p.ok,status:p.status,statusText:p.statusText,headers:Object.fromEntries(p.headers.entries()),json:()=>p.json()}))},props:e}]})])}const He=V.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Me(t,n);if(s)try{return await V.Sandbox.callFunction({code:`
51
+ `;if(a==="@blocklet/pages-kit/builtin/dayjs")return H.BuiltinModules.dayjs},global:{console:{log:(...a)=>{I.info(...a)},warn:(...a)=>{I.warn(...a)},error:(...a)=>{I.error(...a)}},getComponentMountPoint:nt.getComponentMountPoint,joinURL:x.joinURL,withQuery:x.withQuery,getQuery:x.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:x.joinURL(x.withHttps(s.hostname),s.originalUrl)},fetch:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?x.joinURL(w.default.env.appUrl,a):a;if(typeof c=="string"&&x.parseURL(c).host===x.parseURL(w.default.env.appUrl).host){const p=s.get("cookie");if(p){const u=new Le.Headers(i.headers);u.set("cookie",p),i.headers=u}}return It.default(c,{...i,timeout:me*1e3}).then(p=>({ok:p.ok,status:p.status,statusText:p.statusText,headers:Object.fromEntries(p.headers.entries()),json:()=>p.json()}))},props:e}]})])}const Ge=H.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Me(t,n);if(s)try{return await H.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 I.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),Jt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ge="page",he="trigger-reload-project-resource",Te=Jt,Kt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Yt}=require("@blocklet/uploader-server"),ye=gt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ie=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,Y=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,xe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Wt=1e4,Qt=3e4,te=0,ue=1,Xt=0,Zt=1,Se=w.default,z=h.join(process.env.BLOCKLET_DATA_DIR,"site-state"),es=["production","draft"],ts=["production"];function ze(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function ss(){var e;const t=Se.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 q=class q extends B.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(p=>{c.add(p)}),o.forEach(p=>{c.delete(p)}))}const a=_.createEncoder();_.writeVarUint(a,ue),_.writeVarUint8Array(a,H.encodeAwarenessUpdate(this.awareness,l));const i=_.toUint8Array(a);this.conns.forEach((c,p)=>this.send(p,i))});A(this,"updateHandler",e=>{const s=_.createEncoder();_.writeVarUint(s,te),le.writeUpdate(s,e);const o=_.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(...Se.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!==Xt&&e.readyState!==Zt&&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&&H.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",N.debounce(()=>{E.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Wt));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 we(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((p,u)=>{this.transact(async()=>{try{const m=await we(e,s);p(m)}catch(m){u(m)}})})});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)}}},Qt);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=_.createEncoder();_.writeVarUint(r,te),le.writeSyncStep1(r,this),this.send(e,_.toUint8Array(r));const l=this.awareness.getStates();if(l.size>0){const a=_.createEncoder();_.writeVarUint(a,ue),_.writeVarUint8Array(a,H.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,_.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=_.createEncoder(),r=pe.createDecoder(s),l=pe.readVarUint(r);switch(l){case te:_.writeVarUint(o,te),le.readSyncMessage(r,o,this,null),_.length(o)>1&&(this.ensureDataStructure(),this.send(e,_.toUint8Array(o)));break;case ue:{H.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(r),e);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()});this.options=e,E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=dt.reactive(ee.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new H.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=h.join(z,e),o=h.join(z,`@del-${e}`);E.renameSync(s,o)}catch(s){I.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return fe.globSync("*/",{cwd:z,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>q.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new q({path:h.join(z,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=ee.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof B.Map&&e(r)});const s=ee.getYjsValue(this.syncedStore.pages);s&&s instanceof B.Map&&s.observe(o=>{o.changes.keys.forEach((r,l)=>{if(r.action==="add"){const a=ee.getYjsValue(this.syncedStore.pages[l]);a&&a instanceof B.Map&&e(a)}})})}get draftYjsFilePath(){return h.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 Oe(this.getPublishDir(e),{includeResources:!0})??ss(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=Se.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 Ae().then(async a=>{var u,m,g,S;const{pages:i,components:c}=N.pick(a,"pages","components");let p=c;if((m=(u=this.states[e])==null?void 0:u.resources)!=null&&m.components)p={...(S=(g=this.states[e])==null?void 0:g.resources)==null?void 0:S.components};else{const j=h.basename(this.options.path),v=await $.findByPk(j);if(v!=null&&v.useAllResources)p=c;else{const R=(await ce.findAll({where:{projectId:j}})).map(T=>T.componentId);p=Object.fromEntries(Object.entries(c||{}).filter(([T])=>R.includes(T)))}}return{pages:i,components:p}}).catch(()=>({}))}}async setState(e,s){const o=await Ye(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);E.mkdirSync(h.dirname(r),{recursive:!0}),E.rmSync(r,{force:!0,recursive:!0}),E.renameSync(o,r),this.states[e]=s}getPublishDir(e){return h.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const l=await $.findByPk(r);if(!l)continue;const a=await q.shared(r).getState(e),i=N.union(w.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const p=a.pages[c];if(!p||e==="production"&&!p.isPublic)continue;const u=p.slug,m=l.slug||r,g={projectId:r,projectSlug:m,pageSlug:u,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:p.isPublic,isTemplate:p.isTemplate};m&&(o[x.joinURL("/",m,u)]={...g,shouldRedirect:!0,mainPage:!0}),o[x.joinURL("/",r,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const S of i){const j={...g,locale:S};o[x.joinURL("/",S,r,u)]=j,m&&(o[x.joinURL("/",S,m,u)]=j)}}}return o}getDocumentSize(){return B.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(q,"INSTANCE_TTL",30*60*1e3),A(q,"sharedInstances",new Ee.LRUCache({max:100,ttl:q.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let Q=q;function Je(){return E.mkdtempSync(h.join(w.default.env.dataDir,"tmp-"))}function re(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>re(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>re(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function ns(t,n,e){if(!t||!E.existsSync(t)||!E.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Yt({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return I.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const os=async(t,n)=>{const e=h.basename(t),s=await be.call({name:Te,path:x.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=E.createWriteStream(n);await yt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},rs=async(t,n)=>{await Promise.all(t.map(async e=>{try{await os(e,h.join(n,h.basename(e)))}catch(s){I.error(`Failed to export assets: ${e}, ${s}`)}}))};function Ke(t){return Ie.test(t)?[t]:Y.test(t)?(xe.lastIndex=0,Array.from(t.matchAll(xe)).map(e=>e[1]).filter(e=>!!e)):[]}async function de(t,n,e){const{getFilename:s,exportAssets:o}=e,r=h.join(n,s(t));if(E.mkdirSync(h.dirname(r),{recursive:!0}),E.writeFileSync(r,J.stringify(t)),o){const a=re(t,i=>typeof i=="string"&&(Ie.test(i)||Y.test(i))).map(i=>{const c=N.get(t,i);return Ke(c)}).flat().filter(Boolean);await rs(a,h.dirname(r))}}const ke=new Ee.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Re(t,n,e){var a;const s=re(t,i=>typeof i=="string"&&(Ie.test(i)||Y.test(i))),o=_t.default(2),r=s.map(i=>o(async()=>{try{const c=N.get(t,i),p=Ke(c);for(const u of p){const m=h.basename(u),g=e.getFilePath(u,i),S=g?`${g}:${m}`:m,j=ke.get(S);if(j){Y.test(c)||N.set(t,i,j);return}const v=await ns(g,m,n);v&&(Y.test(c)||N.set(t,i,v),ke.set(S,v))}}catch(c){I.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 Ye(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,R,y,T,O,C;const l=e==="all"?t.pageIds:e,a=as({state:t,pageIds:l,componentIds:s==="all"?Object.keys(t.components):s}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,templateDescription:f.templateDescription,llmConfig:f.llmConfig,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},p=M(t.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=t.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),u=Je(),m=h.join(u,"pages");E.mkdirSync(m,{recursive:!0});const g=h.join(u,"components");E.mkdirSync(g,{recursive:!0});for(const{locale:f,slug:d,page:b}of p)await de(b,m,{getFilename:()=>`${ze(d)||"index"}.${f}.yml`,exportAssets:n});for(const f of a){const d=(F=t.components[f])==null?void 0:F.data;d&&await de(d,g,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:n})}const S=h.join(u,".blocklet/pages/pages.config.yml");E.mkdirSync(h.dirname(S),{recursive:!0});const j={pages:M(l.map(f=>{const d=t.pages[f];return d&&{id:f,slug:d.slug}})),components:M(a.map(f=>{var b;const d=(b=t.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...r?{resources:{components:M(Object.keys(((R=t.resources)==null?void 0:R.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=t.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};E.writeFileSync(S,J.stringify(j));const v=h.join(u,"config.source.json");if(o&&E.writeFileSync(v,JSON.stringify(o)),r){const f=h.join(u,"resources"),d=h.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=t==null?void 0:t.resources)==null?void 0:y.components)??{})){const k=(C=(O=(T=t.resources)==null?void 0:T.components)==null?void 0:O[b])==null?void 0:C.component;k&&await de(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:n})}}return u}async function Oe(t,{importAssets:n,includeResources:e}={}){var r,l,a;if(!E.existsSync(t))return null;let s,o=!1;try{E.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Je(),await St.x({file:t,C:s}));const i=fe.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&h.join(h.dirname(i),"../../pages"),p=i&&h.join(h.dirname(i),"../../components"),u=i&&h.join(h.dirname(i),"../../chunks");if(!i)return null;const m=J.parse(E.readFileSync(i).toString()),g=(y,T,O)=>{let C=h.join(y,`${T}${O?`.${O}`:""}.yml`);return(!E.existsSync(C)||!E.lstatSync(C).isFile())&&(C=h.join(y,T,`index${O?`.${O}`:""}.yml`),!E.existsSync(C)||!E.lstatSync(C))?null:J.parse(E.readFileSync(C).toString())},S=(y,T)=>{try{const O=fe.globSync(`*.${T}.yml`,{cwd:y,absolute:!0})[0];return O?J.parse(E.readFileSync(O).toString()):null}catch(O){I.error("parse component error",O)}return null},j=M(m.pages.map(({slug:y})=>{var f;const T=M(m.supportedLocales.map(({locale:d})=>{const b=c?g(c,ze(y),d):void 0;if(b)return{locale:d,page:b};const k=c?g(c,y,d):void 0;return k&&{locale:d,page:k}})),O=(f=T[0])==null?void 0:f.page;if(!O)return null;const C=O.sections.map(d=>{const b=d.id||ye();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,templateDescription:d.templateDescription,llmConfig:d.llmConfig,visibility:d.visibility,locales:Object.fromEntries(M(T.map(({locale:k,page:U})=>{const _e=U.sections.find(et=>et.id===b);return _e&&[k,_e.properties]})))}});return{id:O.id||ye(),createdAt:O.createdAt,updatedAt:O.updatedAt,publishedAt:O.publishedAt,isPublic:O.isPublic??!0,isTemplate:O.isTemplate??!1,slug:y,sections:Object.fromEntries(C.map(d=>[d.id,d])),sectionIds:C.map(d=>d.id),locales:Object.fromEntries(T.map(({locale:d,page:b})=>[d,b.meta]))}})),v=p?M(((r=m.components)==null?void 0:r.map(({id:y})=>S(p,y)))??[]):[];if(n){const y=(...T)=>{I.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...T)};try{y("wait image-bin api ready"),await Dt.default({resources:[`${be.getComponentWebEndpoint(kt)}/api/sdk/uploads`],validateStatus:C=>C>=200&&C<=500}),y("image-bin api is ready");const T={},O={};y("start to upload assets"),await Promise.allSettled([Re(v,T,{getFilePath:C=>p&&h.join(p,C),onFinish:C=>{y(`upload ${C.length} component assets`)}}),Re(j,O,{getFilePath:(C,f)=>{const d=N.get(j,f.slice(0,1));return c&&h.join(c,h.dirname(d.slug),C)},onFinish:C=>{y(`upload ${C.length} page assets`)}})]),y("upload assets done"),global.gc&&global.gc()}catch(T){y("Error during asset import:",T)}}const F={};if(e){const y=i&&h.join(h.dirname(i),"../../resources/components"),T=M(((a=(l=m.resources)==null?void 0:l.components)==null?void 0:a.map(({id:O})=>S(y,O)))??[]);T.length>0&&(F.components=Object.fromEntries(T.map((O,C)=>[O.id,{index:C,component:O}])))}const R={};if(u&&E.existsSync(u)){const y=E.readdirSync(u);for(const T of y)R[T]=h.join(u,T)}return{supportedLocales:m.supportedLocales,pageIds:j.map(y=>y.id),components:Object.fromEntries(v.map((y,T)=>[y.id,{index:T,data:y}])),pages:Object.fromEntries(j.map(y=>[y.id,y])),config:m.config||{},resources:F,chunks:R}}finally{o&&s&&E.rmSync(s,{force:!0,recursive:!0})}}async function we(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&$e(r)}catch(p){I.error("clear preload page cache error",{error:p})}const{pageIds:l,pages:a,supportedLocales:i}=t;for(const p of e??l){const u=a[p];if(!u){const m=n.pageIds.indexOf(p);m!==-1&&o&&(n.pageIds.splice(m,1),delete n.pages[p]);continue}if(n.pageIds.includes(u.id)){if(s==="replace")n.pages[u.id]=u;else if(s==="byUpdateTime"){const m=n.pages[u.id];(!m||u.updatedAt&&u.updatedAt>m.updatedAt)&&(n.pages[u.id]=u)}}else n.pageIds.push(u.id),n.pages[u.id]=u}if(o&&!e)for(const p of n.pageIds)t.pageIds.includes(p)||delete n.pages[p],n.pageIds=[...n.pageIds].filter(u=>t.pageIds.includes(u));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...N.cloneDeep(i)),o)for(const p of Object.keys(n.components))delete n.components[p];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([p,u])=>{const m=await We(u==null?void 0:u.data);return[p,{...u,data:m}]}))),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 We=V.memoize(async t=>{var n;if(!N.isEmpty(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 He(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){I.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=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});function as({state:t,pageIds:n=[],componentIds:e=[]}){var l;const s=(a,i=new Set)=>(Array.isArray(a)&&a.forEach(c=>s(c,i)),a&&typeof a=="object"&&(typeof a.componentId=="string"&&i.add(a.componentId),Object.values(a).forEach(c=>s(c,i))),i),o=new Set(e);for(const a of n){const i=t.pages[a];s(i,o)}const r=[...o];for(;r.length;){const a=r.shift();o.has(a)||o.add(a);const i=(l=t.components[a])==null?void 0:l.data;if(i)for(const c of s(i))o.has(c)||r.push(c)}return[...o]}let ae,G,Ce,Pe,je;function Qe(){return ae=(async()=>{const t=be.getResources({types:[{did:Te,type:ge},{did:Kt,type:ge}]});G=(await Promise.all(t.map(async e=>{const s=e.path?await Oe(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Ce=G.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=G.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await We(s.component);return[e,{...s,component:o}]}))),je=G.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),ae}function Xe(t){const n=N.debounce(async()=>{await Qe().catch(e=>{I.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:G,pages:Ce,components:Pe,chunks:je}))},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(he,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(he,n)}}const Ze=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),ne=globalThis;var Ne;(Ne=ne[Ze])==null||Ne.call(ne);ne[Ze]=Xe(async({pages:t,components:n})=>{const{projectIds:e}=Q;I.info(`start update resource states projects(${e.length})`,e),await Promise.race([new Promise(s=>{setTimeout(()=>{I.error("update resource states timeout"),s({})},30*1e3)}),Promise.all(e.map(async s=>{const o=Q.shared(s);o.syncedStore.resources.pages=t;const r=await $.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ce.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(s=>{I.error("update resource states failed:",s)})});async function is(){I.info("trigger reload all project resource"),w.default.events.emit(he)}async function Ae({ensureLoaded:t=!0}={}){return t&&(ae??(ae=Qe()),await ae),{states:G,pages:Ce,components:Pe,chunks:je}}exports.COMPONENT_DID=Te;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=Fe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=me;exports.PUBLISH_MODES=ts;exports.Project=$;exports.RESOURCE_TYPE=ge;exports.SITE_STATE_PATH=z;exports.STATE_MODES=es;exports.SiteState=Q;exports.clearPreloadComponentsCache=qe;exports.clearPreloadComponentsCacheByMode=$e;exports.fromPackage=Oe;exports.getComponentFromState=W;exports.getComponentFromStateByName=Ht;exports.getExportSchemaValueFromCode=He;exports.getMultiTenantAllProjectAccessPassports=Lt;exports.getPreloadComponent=Ve;exports.getPreloadComponents=Bt;exports.getPreloadComponentsCacheKey=Be;exports.getResourceStates=Ae;exports.initPackResourceStates=Xe;exports.isMultiTenant=Nt;exports.logger=I;exports.mergeState=we;exports.nextId=ye;exports.toPackage=Ye;exports.triggerReloadAllProjectResource=is;
57
+ `,filename:`${e}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return I.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),Jt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ge="page",he="trigger-reload-project-resource",Te=Jt,Kt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",{uploadToMediaKit:Yt}=require("@blocklet/uploader-server"),ye=gt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ie=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,Y=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,xe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Qt=1e4,Wt=3e4,te=0,ue=1,Xt=0,Zt=1,Se=w.default,z=h.join(process.env.BLOCKLET_DATA_DIR,"site-state"),es=["production","draft"],ts=["production"];function ze(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function ss(){var e;const t=Se.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 q=class q extends B.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(p=>{c.add(p)}),o.forEach(p=>{c.delete(p)}))}const a=v.createEncoder();v.writeVarUint(a,ue),v.writeVarUint8Array(a,G.encodeAwarenessUpdate(this.awareness,l));const i=v.toUint8Array(a);this.conns.forEach((c,p)=>this.send(p,i))});A(this,"updateHandler",e=>{const s=v.createEncoder();v.writeVarUint(s,te),le.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(...Se.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!==Xt&&e.readyState!==Zt&&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&&G.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",N.debounce(()=>{E.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Qt));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 we(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((p,u)=>{this.transact(async()=>{try{const m=await we(e,s);p(m)}catch(m){u(m)}})})});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)}}},Wt);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=v.createEncoder();v.writeVarUint(r,te),le.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,ue),v.writeVarUint8Array(a,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,v.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=v.createEncoder(),r=pe.createDecoder(s),l=pe.readVarUint(r);switch(l){case te:v.writeVarUint(o,te),le.readSyncMessage(r,o,this,null),v.length(o)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(o)));break;case ue:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(r),e);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()});this.options=e,E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=dt.reactive(ee.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=h.join(z,e),o=h.join(z,`@del-${e}`);E.renameSync(s,o)}catch(s){I.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return fe.globSync("*/",{cwd:z,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>q.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new q({path:h.join(z,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=ee.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof B.Map&&e(r)});const s=ee.getYjsValue(this.syncedStore.pages);s&&s instanceof B.Map&&s.observe(o=>{o.changes.keys.forEach((r,l)=>{if(r.action==="add"){const a=ee.getYjsValue(this.syncedStore.pages[l]);a&&a instanceof B.Map&&e(a)}})})}get draftYjsFilePath(){return h.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 Oe(this.getPublishDir(e),{includeResources:!0})??ss(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=Se.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 Ae().then(async a=>{var u,m,g,S;const{pages:i,components:c}=N.pick(a,"pages","components");let p=c;if((m=(u=this.states[e])==null?void 0:u.resources)!=null&&m.components)p={...(S=(g=this.states[e])==null?void 0:g.resources)==null?void 0:S.components};else{const j=h.basename(this.options.path),_=await $.findByPk(j);if(_!=null&&_.useAllResources)p=c;else{const R=(await ce.findAll({where:{projectId:j}})).map(T=>T.componentId);p=Object.fromEntries(Object.entries(c||{}).filter(([T])=>R.includes(T)))}}return{pages:i,components:p}}).catch(()=>({}))}}async setState(e,s){const o=await Ye(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);E.mkdirSync(h.dirname(r),{recursive:!0}),E.rmSync(r,{force:!0,recursive:!0}),E.renameSync(o,r),this.states[e]=s}getPublishDir(e){return h.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const l=await $.findByPk(r);if(!l)continue;const a=await q.shared(r).getState(e),i=N.union(w.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const p=a.pages[c];if(!p||e==="production"&&!p.isPublic)continue;const u=p.slug,m=l.slug||r,g={projectId:r,projectSlug:m,pageSlug:u,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:p.isPublic,isTemplate:p.isTemplate};m&&(o[x.joinURL("/",m,u)]={...g,shouldRedirect:!0,mainPage:!0}),o[x.joinURL("/",r,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const S of i){const j={...g,locale:S};o[x.joinURL("/",S,r,u)]=j,m&&(o[x.joinURL("/",S,m,u)]=j)}}}return o}getDocumentSize(){return B.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(q,"INSTANCE_TTL",30*60*1e3),A(q,"sharedInstances",new Ee.LRUCache({max:100,ttl:q.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let W=q;function Je(){return E.mkdtempSync(h.join(w.default.env.dataDir,"tmp-"))}function re(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>re(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>re(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function ns(t,n,e){if(!t||!E.existsSync(t)||!E.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Yt({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return I.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const os=async(t,n)=>{const e=h.basename(t),s=await be.call({name:Te,path:x.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=E.createWriteStream(n);await yt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},rs=async(t,n)=>{await Promise.all(t.map(async e=>{try{await os(e,h.join(n,h.basename(e)))}catch(s){I.error(`Failed to export assets: ${e}, ${s}`)}}))};function Ke(t){return Ie.test(t)?[t]:Y.test(t)?(xe.lastIndex=0,Array.from(t.matchAll(xe)).map(e=>e[1]).filter(e=>!!e)):[]}async function de(t,n,e){const{getFilename:s,exportAssets:o}=e,r=h.join(n,s(t));if(E.mkdirSync(h.dirname(r),{recursive:!0}),E.writeFileSync(r,J.stringify(t)),o){const a=re(t,i=>typeof i=="string"&&(Ie.test(i)||Y.test(i))).map(i=>{const c=N.get(t,i);return Ke(c)}).flat().filter(Boolean);await rs(a,h.dirname(r))}}const ke=new Ee.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Re(t,n,e){var a;const s=re(t,i=>typeof i=="string"&&(Ie.test(i)||Y.test(i))),o=vt.default(2),r=s.map(i=>o(async()=>{try{const c=N.get(t,i),p=Ke(c);for(const u of p){const m=h.basename(u),g=e.getFilePath(u,i),S=g?`${g}:${m}`:m,j=ke.get(S);if(j){Y.test(c)||N.set(t,i,j);return}const _=await ns(g,m,n);_&&(Y.test(c)||N.set(t,i,_),ke.set(S,_))}}catch(c){I.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 Ye(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,R,y,T,O,C;const l=e==="all"?t.pageIds:e,a=as({state:t,pageIds:l,componentIds:s==="all"?Object.keys(t.components):s}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,templateDescription:f.templateDescription,llmConfig:f.llmConfig,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},p=M(t.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=t.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),u=Je(),m=h.join(u,"pages");E.mkdirSync(m,{recursive:!0});const g=h.join(u,"components");E.mkdirSync(g,{recursive:!0});for(const{locale:f,slug:d,page:b}of p)await de(b,m,{getFilename:()=>`${ze(d)||"index"}.${f}.yml`,exportAssets:n});for(const f of a){const d=(F=t.components[f])==null?void 0:F.data;d&&await de(d,g,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:n})}const S=h.join(u,".blocklet/pages/pages.config.yml");E.mkdirSync(h.dirname(S),{recursive:!0});const j={pages:M(l.map(f=>{const d=t.pages[f];return d&&{id:f,slug:d.slug}})),components:M(a.map(f=>{var b;const d=(b=t.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...r?{resources:{components:M(Object.keys(((R=t.resources)==null?void 0:R.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=t.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};E.writeFileSync(S,J.stringify(j));const _=h.join(u,"config.source.json");if(o&&E.writeFileSync(_,JSON.stringify(o)),r){const f=h.join(u,"resources"),d=h.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=t==null?void 0:t.resources)==null?void 0:y.components)??{})){const k=(C=(O=(T=t.resources)==null?void 0:T.components)==null?void 0:O[b])==null?void 0:C.component;k&&await de(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:n})}}return u}async function Oe(t,{importAssets:n,includeResources:e}={}){var r,l,a;if(!E.existsSync(t))return null;let s,o=!1;try{E.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Je(),await St.x({file:t,C:s}));const i=fe.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&h.join(h.dirname(i),"../../pages"),p=i&&h.join(h.dirname(i),"../../components"),u=i&&h.join(h.dirname(i),"../../chunks");if(!i)return null;const m=J.parse(E.readFileSync(i).toString()),g=(y,T,O)=>{let C=h.join(y,`${T}${O?`.${O}`:""}.yml`);return(!E.existsSync(C)||!E.lstatSync(C).isFile())&&(C=h.join(y,T,`index${O?`.${O}`:""}.yml`),!E.existsSync(C)||!E.lstatSync(C))?null:J.parse(E.readFileSync(C).toString())},S=(y,T)=>{try{const O=fe.globSync(`*.${T}.yml`,{cwd:y,absolute:!0})[0];return O?J.parse(E.readFileSync(O).toString()):null}catch(O){I.error("parse component error",O)}return null},j=M(m.pages.map(({slug:y})=>{var f;const T=M(m.supportedLocales.map(({locale:d})=>{const b=c?g(c,ze(y),d):void 0;if(b)return{locale:d,page:b};const k=c?g(c,y,d):void 0;return k&&{locale:d,page:k}})),O=(f=T[0])==null?void 0:f.page;if(!O)return null;const C=O.sections.map(d=>{const b=d.id||ye();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,templateDescription:d.templateDescription,llmConfig:d.llmConfig,visibility:d.visibility,locales:Object.fromEntries(M(T.map(({locale:k,page:U})=>{const ve=U.sections.find(et=>et.id===b);return ve&&[k,ve.properties]})))}});return{id:O.id||ye(),createdAt:O.createdAt,updatedAt:O.updatedAt,publishedAt:O.publishedAt,isPublic:O.isPublic??!0,isTemplate:O.isTemplate??!1,slug:y,sections:Object.fromEntries(C.map(d=>[d.id,d])),sectionIds:C.map(d=>d.id),locales:Object.fromEntries(T.map(({locale:d,page:b})=>[d,b.meta]))}})),_=p?M(((r=m.components)==null?void 0:r.map(({id:y})=>S(p,y)))??[]):[];if(n){const y=(...T)=>{I.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...T)};try{y("wait image-bin api ready"),await Dt.default({resources:[`${be.getComponentWebEndpoint(kt)}/api/sdk/uploads`],validateStatus:C=>C>=200&&C<=500}),y("image-bin api is ready");const T={},O={};y("start to upload assets"),await Promise.allSettled([Re(_,T,{getFilePath:C=>p&&h.join(p,C),onFinish:C=>{y(`upload ${C.length} component assets`)}}),Re(j,O,{getFilePath:(C,f)=>{const d=N.get(j,f.slice(0,1));return c&&h.join(c,h.dirname(d.slug),C)},onFinish:C=>{y(`upload ${C.length} page assets`)}})]),y("upload assets done"),global.gc&&global.gc()}catch(T){y("Error during asset import:",T)}}const F={};if(e){const y=i&&h.join(h.dirname(i),"../../resources/components"),T=M(((a=(l=m.resources)==null?void 0:l.components)==null?void 0:a.map(({id:O})=>S(y,O)))??[]);T.length>0&&(F.components=Object.fromEntries(T.map((O,C)=>[O.id,{index:C,component:O}])))}const R={};if(u&&E.existsSync(u)){const y=E.readdirSync(u);for(const T of y)R[T]=h.join(u,T)}return{supportedLocales:m.supportedLocales,pageIds:j.map(y=>y.id),components:Object.fromEntries(_.map((y,T)=>[y.id,{index:T,data:y}])),pages:Object.fromEntries(j.map(y=>[y.id,y])),config:m.config||{},resources:F,chunks:R}}finally{o&&s&&E.rmSync(s,{force:!0,recursive:!0})}}async function we(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&$e(r)}catch(p){I.error("clear preload page cache error",{error:p})}const{pageIds:l,pages:a,supportedLocales:i}=t;for(const p of e??l){const u=a[p];if(!u){const m=n.pageIds.indexOf(p);m!==-1&&o&&(n.pageIds.splice(m,1),delete n.pages[p]);continue}if(n.pageIds.includes(u.id)){if(s==="replace")n.pages[u.id]=u;else if(s==="byUpdateTime"){const m=n.pages[u.id];(!m||u.updatedAt&&u.updatedAt>m.updatedAt)&&(n.pages[u.id]=u)}}else n.pageIds.push(u.id),n.pages[u.id]=u}if(o&&!e)for(const p of n.pageIds)t.pageIds.includes(p)||delete n.pages[p],n.pageIds=[...n.pageIds].filter(u=>t.pageIds.includes(u));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...N.cloneDeep(i)),o)for(const p of Object.keys(n.components))delete n.components[p];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([p,u])=>{const m=await Qe(u==null?void 0:u.data);return[p,{...u,data:m}]}))),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 Qe=H.memoize(async t=>{var n;if(!N.isEmpty(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 Ge(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){I.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=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});function as({state:t,pageIds:n=[],componentIds:e=[]}){var l;const s=(a,i=new Set)=>(Array.isArray(a)&&a.forEach(c=>s(c,i)),a&&typeof a=="object"&&(typeof a.componentId=="string"&&i.add(a.componentId),Object.values(a).forEach(c=>s(c,i))),i),o=new Set(e);for(const a of n){const i=t.pages[a];s(i,o)}const r=[...o];for(;r.length;){const a=r.shift();o.has(a)||o.add(a);const i=(l=t.components[a])==null?void 0:l.data;if(i)for(const c of s(i))o.has(c)||r.push(c)}return[...o]}let ae,V,Ce,Pe,je;function We(){return ae=(async()=>{const t=be.getResources({types:[{did:Te,type:ge},{did:Kt,type:ge}]});V=(await Promise.all(t.map(async e=>{const s=e.path?await Oe(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Ce=V.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=V.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await Qe(s.component);return[e,{...s,component:o}]}))),je=V.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),ae}function Xe(t){const n=N.debounce(async()=>{await We().catch(e=>{I.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:V,pages:Ce,components:Pe,chunks:je}))},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(he,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(he,n)}}const Ze=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),ne=globalThis;var Ne;(Ne=ne[Ze])==null||Ne.call(ne);ne[Ze]=Xe(async({pages:t,components:n})=>{const{projectIds:e}=W;I.info(`start update resource states projects(${e.length})`,e),await Promise.race([new Promise(s=>{setTimeout(()=>{I.error("update resource states timeout"),s({})},30*1e3)}),Promise.all(e.map(async s=>{const o=W.shared(s);o.syncedStore.resources.pages=t;const r=await $.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ce.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(s=>{I.error("update resource states failed:",s)})});async function is(){I.info("trigger reload all project resource"),w.default.events.emit(he)}async function Ae({ensureLoaded:t=!0}={}){return t&&(ae??(ae=We()),await ae),{states:V,pages:Ce,components:Pe,chunks:je}}exports.COMPONENT_DID=Te;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=Fe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=me;exports.PUBLISH_MODES=ts;exports.Project=$;exports.RESOURCE_TYPE=ge;exports.SITE_STATE_PATH=z;exports.STATE_MODES=es;exports.SiteState=W;exports.clearPreloadComponentsCache=qe;exports.clearPreloadComponentsCacheByMode=$e;exports.fromPackage=Oe;exports.getComponentFromState=Q;exports.getComponentFromStateByName=Gt;exports.getExportSchemaValueFromCode=Ge;exports.getMultiTenantAllProjectAccessPassports=Lt;exports.getPreloadComponent=He;exports.getPreloadComponents=Bt;exports.getPreloadComponentsCacheKey=Be;exports.getResourceStates=Ae;exports.initPackResourceStates=Xe;exports.isMultiTenant=Nt;exports.logger=I;exports.mergeState=we;exports.nextId=ye;exports.toPackage=Ye;exports.triggerReloadAllProjectResource=is;
@@ -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-DgIg3vfy.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-33ePZZrB.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-DgIg3vfy.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:"30 30 */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 r=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,r),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:!1,allowCrawler:q})),C.get("/:path(*)?",async(r,b,j)=>{var $,E,L;if(Y.some(c=>{var i;return(i=r.path)==null?void 0:i.startsWith(c)})){j();return}const y=performance.now(),v=()=>Math.round(performance.now()-y),x="production";let o,u,g=p;if(r.path.startsWith("/pages")){const c=r.params.lang,i=r.cookies.nf_lang,w=new Set([...d.default.env.languages.map(h=>h.code)]);let f=(c&&w.has(c)?c: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(l=>{const N=Object.values((l==null?void 0:l.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(l=>{setTimeout(()=>{k.logger.error("get preload components timeout"),l({})},90*1e3)});try{await Promise.race([H,k.getPreloadComponents({mode:x,req:r,state:t,locale:f,instances:h,module:W.PreloadComponentScriptModule.UMD_FN}).then(l=>{l&&(u=J.injectPreloadComponents(l))})])}catch(l){k.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),k.logger.warn(l)}}}try{const c=(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:c,description:i});g=X.default.render(p,{ogTitle:c,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=r.query.mode==="draft"||r.url.includes("preview"),m=I.load(g);m("head").find("#injected-head-elements").replaceWith(`
1
+ "use strict";const k=require("./_chunks/site-state-33ePZZrB.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:"30 30 */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 r=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,r),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:!1,allowCrawler:q})),C.get("/:path(*)?",async(r,b,j)=>{var $,E,L;if(Y.some(c=>{var i;return(i=r.path)==null?void 0:i.startsWith(c)})){j();return}const y=performance.now(),v=()=>Math.round(performance.now()-y),x="production";let o,u,g=p;if(r.path.startsWith("/pages")){const c=r.params.lang,i=r.cookies.nf_lang,w=new Set([...d.default.env.languages.map(h=>h.code)]);let f=(c&&w.has(c)?c: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(l=>{const N=Object.values((l==null?void 0:l.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(l=>{setTimeout(()=>{k.logger.error("get preload components timeout"),l({})},90*1e3)});try{await Promise.race([H,k.getPreloadComponents({mode:x,req:r,state:t,locale:f,instances:h,module:W.PreloadComponentScriptModule.UMD_FN}).then(l=>{l&&(u=J.injectPreloadComponents(l))})])}catch(l){k.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),k.logger.warn(l)}}}try{const c=(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:c,description:i});g=X.default.render(p,{ogTitle:c,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=r.query.mode==="draft"||r.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-DgIg3vfy.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),O=require("lodash"),b=require("path"),X=require("@blocklet/sdk/lib/middlewares/auth"),W=require("@blocklet/sdk/lib/component"),E=t=>t&&t.__esModule?t:{default:t},p=E(F),I=E(J),k=E(b),v=E(X);new M.AsyncLocalStorage;const $=async(t,e,o)=>{var n,s,r,a;try{const{projectId:u}=t.params;if(!u)return o();const f=await c.Project.findByPk(u);if(!f)return e==null?void 0:e.status(404).json({error:"Project not found"});const P=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!P)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===P,i=(a=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:a.call(r,h);if(!w&&!i)return e==null?void 0:e.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(h))return e==null?void 0:e.status(403).json({error:"No permission to access this project in single-tenant mode"});t.project=f,t.projectId=u,o()}catch(u){c.logger.error("Project middleware error:",u),e==null||e.status(500).json({error:"Internal server error"})}};function N(t,e){return new Promise((o,n)=>{const s=p.default.createReadStream(t),r=p.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await p.default.promises.mkdir(e,{recursive:!0});const o=await p.default.promises.readdir(t,{withFileTypes:!0});for(const n of o){const s=k.default.join(t,n.name),r=k.default.join(e,n.name);n.isDirectory()?await T(s,r):await N(s,r)}}async function G(t,e){(await p.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const D=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),K=(t,e)=>{const o=W.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",y=":",_="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(y),Y=t=>{const[e,o,n]=t.split(y);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(y),z=t=>{const[e,o,n]=t.split(y);if(e===q)return{componentId:n,projectId:o}},H=t=>[L,t].join(y),Q=t=>{const[e,o]=t.split(y);if(e===L)return o},V=t=>{try{return JSON.parse(t)}catch{}return{}};async function x(t){const e=await c.SiteState.shared(t).getState("production"),o=await c.Project.findByPk(t),n=e.pageIds.map(r=>{const a=e.pages[r];if(a)return{id:C({pageId:r,projectId:t}),name:a.slug}}).filter(Boolean),s=O.sortBy(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:H(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:_,projectId:t}),name:"Pages",children:n},{id:A({componentId:_,projectId:t}),name:"Components",children:s}]}}S.get("/resources",D,async(t,e)=>{const{projectId:o}=V(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await $(t,e,()=>{});const r=await x(o);e.json({resources:[r]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(r=>x(r.id)));e.json({resources:s})});const Z=I.default.object({projectId:I.default.string().required().min(1),releaseId:I.default.string().allow(""),resources:I.default.array().items(I.default.string()).required(),locale:I.default.string().allow("")});S.post("/resources",D,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await Z.validateAsync(t.body),r="production",a=[],u=[];for(const i of o){if(Q(i))continue;const{pageId:m,projectId:j}=Y(i)||{};if(m)m===_||m&&j&&a.push({pageId:m,projectId:j});else{const{componentId:l,projectId:d}=z(i)||{};l===_||l&&d&&u.push({componentId:l,projectId:d})}}const f=O.groupBy(a,"projectId"),P=O.groupBy(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(P)]),w=K(n,s);p.default.rmSync(w,{recursive:!0,force:!0}),p.default.mkdirSync(w,{recursive:!0});for(const i of h){const m=await c.SiteState.shared(i).getState(r),j=f[i],l=P[i],d=j==null?void 0:j.map(g=>g.pageId),R=l==null?void 0:l.map(g=>g.componentId);if(d!=null&&d.length||R!=null&&R.length){const g=await c.toPackage(m,{exportAssets:!0,pageIds:d,componentIds:R});await G(g,w),p.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${i}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",D,async(t,e)=>{const{states:o}=await c.getResourceStates(),n=o==null?void 0:o.map(s=>{const r={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(r.components=s.state.components),Object.keys(r.components).length!==0)return r}).filter(Boolean);e.json(n)});module.exports=S;
1
+ "use strict";const c=require("./_chunks/site-state-33ePZZrB.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),O=require("lodash"),b=require("path"),X=require("@blocklet/sdk/lib/middlewares/auth"),W=require("@blocklet/sdk/lib/component"),E=t=>t&&t.__esModule?t:{default:t},p=E(F),I=E(J),k=E(b),v=E(X);new M.AsyncLocalStorage;const $=async(t,e,o)=>{var n,s,r,a;try{const{projectId:u}=t.params;if(!u)return o();const f=await c.Project.findByPk(u);if(!f)return e==null?void 0:e.status(404).json({error:"Project not found"});const P=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!P)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===P,i=(a=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:a.call(r,h);if(!w&&!i)return e==null?void 0:e.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(h))return e==null?void 0:e.status(403).json({error:"No permission to access this project in single-tenant mode"});t.project=f,t.projectId=u,o()}catch(u){c.logger.error("Project middleware error:",u),e==null||e.status(500).json({error:"Internal server error"})}};function N(t,e){return new Promise((o,n)=>{const s=p.default.createReadStream(t),r=p.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await p.default.promises.mkdir(e,{recursive:!0});const o=await p.default.promises.readdir(t,{withFileTypes:!0});for(const n of o){const s=k.default.join(t,n.name),r=k.default.join(e,n.name);n.isDirectory()?await T(s,r):await N(s,r)}}async function G(t,e){(await p.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const D=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),K=(t,e)=>{const o=W.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",y=":",_="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(y),Y=t=>{const[e,o,n]=t.split(y);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(y),z=t=>{const[e,o,n]=t.split(y);if(e===q)return{componentId:n,projectId:o}},H=t=>[L,t].join(y),Q=t=>{const[e,o]=t.split(y);if(e===L)return o},V=t=>{try{return JSON.parse(t)}catch{}return{}};async function x(t){const e=await c.SiteState.shared(t).getState("production"),o=await c.Project.findByPk(t),n=e.pageIds.map(r=>{const a=e.pages[r];if(a)return{id:C({pageId:r,projectId:t}),name:a.slug}}).filter(Boolean),s=O.sortBy(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:H(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:_,projectId:t}),name:"Pages",children:n},{id:A({componentId:_,projectId:t}),name:"Components",children:s}]}}S.get("/resources",D,async(t,e)=>{const{projectId:o}=V(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await $(t,e,()=>{});const r=await x(o);e.json({resources:[r]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(r=>x(r.id)));e.json({resources:s})});const Z=I.default.object({projectId:I.default.string().required().min(1),releaseId:I.default.string().allow(""),resources:I.default.array().items(I.default.string()).required(),locale:I.default.string().allow("")});S.post("/resources",D,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await Z.validateAsync(t.body),r="production",a=[],u=[];for(const i of o){if(Q(i))continue;const{pageId:m,projectId:j}=Y(i)||{};if(m)m===_||m&&j&&a.push({pageId:m,projectId:j});else{const{componentId:l,projectId:d}=z(i)||{};l===_||l&&d&&u.push({componentId:l,projectId:d})}}const f=O.groupBy(a,"projectId"),P=O.groupBy(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(P)]),w=K(n,s);p.default.rmSync(w,{recursive:!0,force:!0}),p.default.mkdirSync(w,{recursive:!0});for(const i of h){const m=await c.SiteState.shared(i).getState(r),j=f[i],l=P[i],d=j==null?void 0:j.map(g=>g.pageId),R=l==null?void 0:l.map(g=>g.componentId);if(d!=null&&d.length||R!=null&&R.length){const g=await c.toPackage(m,{exportAssets:!0,pageIds:d,componentIds:R});await G(g,w),p.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${i}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",D,async(t,e)=>{const{states:o}=await c.getResourceStates(),n=o==null?void 0:o.map(s=>{const r={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(r.components=s.state.components),Object.keys(r.components).length!==0)return r}).filter(Boolean);e.json(n)});module.exports=S;
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_chunks/site-state-DgIg3vfy.js");require("@blocklet/quickjs");require("@blocklet/sdk/lib/component");require("@blocklet/sdk/lib/config");require("@reactivedata/reactive");require("@syncedstore/core");require("crypto");require("fs");require("glob");require("lib0/decoding");require("lib0/encoding");require("lodash");require("lru-cache");require("nanoid");require("p-limit");require("path");require("stream/promises");require("tar");require("ufo");require("wait-on");require("y-protocols/awareness");require("y-protocols/sync");require("yaml");require("yjs");exports.PUBLISH_MODES=e.PUBLISH_MODES;exports.SITE_STATE_PATH=e.SITE_STATE_PATH;exports.STATE_MODES=e.STATE_MODES;exports.default=e.SiteState;exports.fromPackage=e.fromPackage;exports.getResourceStates=e.getResourceStates;exports.initPackResourceStates=e.initPackResourceStates;exports.mergeState=e.mergeState;exports.nextId=e.nextId;exports.toPackage=e.toPackage;exports.triggerReloadAllProjectResource=e.triggerReloadAllProjectResource;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_chunks/site-state-33ePZZrB.js");require("@blocklet/quickjs");require("@blocklet/sdk/lib/component");require("@blocklet/sdk/lib/config");require("@reactivedata/reactive");require("@syncedstore/core");require("crypto");require("fs");require("glob");require("lib0/decoding");require("lib0/encoding");require("lodash");require("lru-cache");require("nanoid");require("p-limit");require("path");require("stream/promises");require("tar");require("ufo");require("wait-on");require("y-protocols/awareness");require("y-protocols/sync");require("yaml");require("yjs");exports.PUBLISH_MODES=e.PUBLISH_MODES;exports.SITE_STATE_PATH=e.SITE_STATE_PATH;exports.STATE_MODES=e.STATE_MODES;exports.default=e.SiteState;exports.fromPackage=e.fromPackage;exports.getResourceStates=e.getResourceStates;exports.initPackResourceStates=e.initPackResourceStates;exports.mergeState=e.mergeState;exports.nextId=e.nextId;exports.toPackage=e.toPackage;exports.triggerReloadAllProjectResource=e.triggerReloadAllProjectResource;
@@ -1,6 +1,6 @@
1
1
  var et = Object.defineProperty;
2
2
  var tt = (t, o, e) => o in t ? et(t, o, { enumerable: !0, configurable: !0, writable: !0, value: e }) : t[o] = e;
3
- var P = (t, o, e) => tt(t, typeof o != "symbol" ? o + "" : o, e);
3
+ var C = (t, o, e) => tt(t, typeof o != "symbol" ? o + "" : o, e);
4
4
  import { getComponentMountPoint as st } from "@blocklet/pages-kit/builtin/utils";
5
5
  import { PreloadComponentScriptModule as X } from "@blocklet/pages-kit/types";
6
6
  import { componentUMDName as ot, RenderNestedComponent as Oe, mergeComponent as nt } from "@blocklet/pages-kit/utils/property";
@@ -8,7 +8,7 @@ import { memoize as ae, Sandbox as _e, BuiltinModules as rt } from "@blocklet/qu
8
8
  import S from "@blocklet/sdk/lib/config";
9
9
  import { LRUCache as he } from "lru-cache";
10
10
  import at, { Headers as it } from "node-fetch";
11
- import { joinURL as _, getQuery as ct, withQuery as lt, parseURL as Ae, withHttps as pt } from "ufo";
11
+ import { joinURL as _, getQuery as ct, withQuery as lt, parseURL as Te, withHttps as pt } from "ufo";
12
12
  import { createHash as ie } from "crypto";
13
13
  import ut from "@blocklet/logger";
14
14
  import { BuiltinModules as dt } from "@blocklet/pages-kit/utils/builtin";
@@ -16,40 +16,40 @@ import { createBuiltinModuleTransformer as mt, isRelativeModule as ft } from "@b
16
16
  import { getResources as gt, getComponentWebEndpoint as ht, call as yt } from "@blocklet/sdk/lib/component";
17
17
  import St from "autoprefixer";
18
18
  import * as wt from "esbuild";
19
- import { readFileSync as H, existsSync as V, lstatSync as Z, readdirSync as Et, rmSync as $e, mkdtempSync as bt, renameSync as Te, mkdirSync as F, writeFileSync as te, createWriteStream as It } from "fs";
19
+ import { readFileSync as H, existsSync as G, lstatSync as Z, readdirSync as Et, rmSync as $e, mkdtempSync as bt, renameSync as ve, mkdirSync as F, writeFileSync as te, createWriteStream as It } from "fs";
20
20
  import Ot from "postcss";
21
- import At from "tailwindcss";
21
+ import Tt from "tailwindcss";
22
22
  import j from "typescript";
23
- import { reactive as Tt } from "@reactivedata/reactive";
24
- import { syncedStore as vt, getYjsValue as le } from "@syncedstore/core";
23
+ import { reactive as vt } from "@reactivedata/reactive";
24
+ import { syncedStore as At, getYjsValue as le } from "@syncedstore/core";
25
25
  import { globSync as me } from "glob";
26
26
  import * as pe from "lib0/decoding";
27
- import * as C from "lib0/encoding";
28
- import { get as ye, isEmpty as Pt, set as ve, pick as Ct, debounce as Fe, union as xt, cloneDeep as jt } from "lodash";
27
+ import * as P from "lib0/encoding";
28
+ import { get as ye, isEmpty as Ct, set as Ae, pick as Pt, debounce as Fe, union as xt, cloneDeep as jt } from "lodash";
29
29
  import { customAlphabet as kt } from "nanoid";
30
30
  import Dt from "p-limit";
31
- import Nt, { join as A, dirname as L, basename as J } from "path";
31
+ import Nt, { join as T, dirname as L, basename as J } from "path";
32
32
  import { pipeline as Lt } from "stream/promises";
33
33
  import { x as Rt } from "tar";
34
34
  import Ut from "wait-on";
35
- import { Awareness as Mt, encodeAwarenessUpdate as Pe, removeAwarenessStates as _t, applyAwarenessUpdate as $t } from "y-protocols/awareness";
36
- import { writeUpdate as Ft, writeSyncStep1 as Bt, readSyncMessage as Vt } from "y-protocols/sync";
37
- import * as z from "yaml";
35
+ import { Awareness as Mt, encodeAwarenessUpdate as Ce, removeAwarenessStates as _t, applyAwarenessUpdate as $t } from "y-protocols/awareness";
36
+ import { writeUpdate as Ft, writeSyncStep1 as Bt, readSyncMessage as Gt } from "y-protocols/sync";
37
+ import * as K from "yaml";
38
38
  import * as $ from "yjs";
39
- import Gt from "lodash/isNil";
40
- import { DataTypes as v, Sequelize as Jt, Model as Be, Op as Ht } from "sequelize";
39
+ import Vt from "lodash/isNil";
40
+ import { DataTypes as A, Sequelize as Jt, Model as Be, Op as Ht } from "sequelize";
41
41
  import "sqlite3";
42
42
  S.env.mode;
43
- const zt = "image-bin";
43
+ const Kt = "image-bin";
44
44
  S.env.INIT_TEMPLATE_PATH;
45
- const Kt = process.env.DATABASE_URL || Nt.join(S.env.dataDir, "db/pages-kit.db"), Ce = S, so = () => S.env.tenantMode === "multiple", oo = () => {
45
+ const zt = process.env.DATABASE_URL || Nt.join(S.env.dataDir, "db/pages-kit.db"), Pe = S, so = () => S.env.tenantMode === "multiple", oo = () => {
46
46
  var t;
47
- return (Gt(Ce.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = Ce.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
48
- }, I = ut("pages-kit"), Wt = v.sqlite.DATE.parse;
49
- v.sqlite.DATE.parse = (t, o) => typeof t == "number" ? new Date(t) : Wt(t, o);
50
- const Y = new Jt({
47
+ return (Vt(Pe.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = Pe.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
48
+ }, I = ut("pages-kit"), Yt = A.sqlite.DATE.parse;
49
+ A.sqlite.DATE.parse = (t, o) => typeof t == "number" ? new Date(t) : Yt(t, o);
50
+ const W = new Jt({
51
51
  dialect: "sqlite",
52
- storage: Kt,
52
+ storage: zt,
53
53
  benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
54
54
  retry: {
55
55
  match: [/SQLITE_BUSY/],
@@ -60,30 +60,30 @@ const Y = new Jt({
60
60
  logging: process.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
61
61
  // logQueryParameters: true,
62
62
  });
63
- Y.query("pragma journal_mode = WAL;");
64
- Y.query("pragma synchronous = normal;");
65
- Y.query("pragma journal_size_limit = 67108864;");
63
+ W.query("pragma journal_mode = WAL;");
64
+ W.query("pragma synchronous = normal;");
65
+ W.query("pragma journal_size_limit = 67108864;");
66
66
  class ce extends Be {
67
67
  // Foreign key to Component
68
68
  }
69
69
  ce.init(
70
70
  {
71
71
  id: {
72
- type: v.UUID,
72
+ type: A.UUID,
73
73
  allowNull: !1,
74
74
  primaryKey: !0,
75
- defaultValue: v.UUIDV4
75
+ defaultValue: A.UUIDV4
76
76
  },
77
77
  projectId: {
78
- type: v.UUID,
78
+ type: A.UUID,
79
79
  allowNull: !1
80
80
  },
81
81
  componentId: {
82
- type: v.STRING,
82
+ type: A.STRING,
83
83
  allowNull: !1
84
84
  }
85
85
  },
86
- { sequelize: Y, tableName: "ProjectComponents", timestamps: !1 }
86
+ { sequelize: W, tableName: "ProjectComponents", timestamps: !1 }
87
87
  );
88
88
  class B extends Be {
89
89
  static async getProjectByIdOrSlug(o) {
@@ -97,32 +97,32 @@ class B extends Be {
97
97
  B.init(
98
98
  {
99
99
  id: {
100
- type: v.UUID,
101
- defaultValue: v.UUIDV4,
100
+ type: A.UUID,
101
+ defaultValue: A.UUIDV4,
102
102
  primaryKey: !0
103
103
  },
104
104
  name: {
105
- type: v.STRING,
105
+ type: A.STRING,
106
106
  allowNull: !1
107
107
  },
108
- description: v.TEXT,
109
- createdAt: v.DATE,
110
- updatedAt: v.DATE,
108
+ description: A.TEXT,
109
+ createdAt: A.DATE,
110
+ updatedAt: A.DATE,
111
111
  createdBy: {
112
- type: v.STRING,
112
+ type: A.STRING,
113
113
  allowNull: !1
114
114
  },
115
115
  updatedBy: {
116
- type: v.STRING,
116
+ type: A.STRING,
117
117
  allowNull: !1
118
118
  },
119
- slug: v.STRING,
120
- icon: v.STRING,
121
- pinnedAt: v.DATE,
122
- useAllResources: v.BOOLEAN,
123
- npmSecret: v.STRING,
119
+ slug: A.STRING,
120
+ icon: A.STRING,
121
+ pinnedAt: A.DATE,
122
+ useAllResources: A.BOOLEAN,
123
+ npmSecret: A.STRING,
124
124
  relatedBlocklets: {
125
- type: v.JSON,
125
+ type: A.JSON,
126
126
  allowNull: !1,
127
127
  defaultValue: {},
128
128
  get() {
@@ -133,18 +133,18 @@ B.init(
133
133
  }
134
134
  }
135
135
  },
136
- { sequelize: Y, paranoid: !0 }
136
+ { sequelize: W, paranoid: !0 }
137
137
  );
138
138
  B.hasMany(ce, {
139
139
  foreignKey: "projectId",
140
140
  as: "components"
141
141
  });
142
- const Yt = async (t, { componentId: o }) => {
142
+ const Wt = async (t, { componentId: o }) => {
143
143
  const e = `@tailwind components;
144
144
  @tailwind utilities;
145
145
  `, s = `.CustomComponent_${o}`;
146
146
  return (await Ot([
147
- At({ content: [{ raw: t, extension: "tsx" }] }),
147
+ Tt({ content: [{ raw: t, extension: "tsx" }] }),
148
148
  St({
149
149
  overrideBrowserslist: ["> 1%", "last 2 versions"],
150
150
  stats: {}
@@ -158,7 +158,7 @@ const Yt = async (t, { componentId: o }) => {
158
158
  // cssnano({ preset: 'default' }),
159
159
  ]).process(e)).css;
160
160
  }, qt = async (t, { componentId: o }) => {
161
- const e = await Yt(t, { componentId: o });
161
+ const e = await Wt(t, { componentId: o });
162
162
  return `export const __PagesKit_CSS__ = ${JSON.stringify(e)};
163
163
 
164
164
  ${t}
@@ -244,7 +244,7 @@ ${t}
244
244
  return j.transpileModule(n, {
245
245
  compilerOptions: { module: j.ModuleKind.ESNext, target: j.ScriptTarget.ES2020 }
246
246
  }).outputText;
247
- }, Ve = ae(
247
+ }, Ge = ae(
248
248
  async (t, o) => {
249
249
  const e = await Qt(t, o);
250
250
  return new RegExp(`export\\s+\\{\\s+${o}\\s+\\}`, "m").test(e) ? e : void 0;
@@ -288,14 +288,14 @@ var ${t} = ${e ? "async" : ""} function () {
288
288
  return exports;
289
289
  };
290
290
  `;
291
- }, K = new he({
291
+ }, z = new he({
292
292
  max: 100
293
293
  }), Zt = 60 * 60, je = 60;
294
294
  function es(t) {
295
- I.info("clear preload components cache", { cacheKey: t }), K.delete(t);
295
+ I.info("clear preload components cache", { cacheKey: t }), z.delete(t);
296
296
  }
297
297
  function ts(t) {
298
- for (const o of K.keys())
298
+ for (const o of z.keys())
299
299
  o.includes(t) && (I.info("clear preload components cache", { cacheKey: o }), es(o));
300
300
  }
301
301
  function ss({
@@ -328,14 +328,14 @@ async function no({
328
328
  componentId: g.componentId,
329
329
  locale: s
330
330
  });
331
- if (t !== "draft" && g.useCache && K.has(y))
332
- return I.info(`get preload component from cache: ${y}`), K.get(y);
333
- const T = se({ state: e, componentId: g.componentId });
334
- if (!T) return null;
331
+ if (t !== "draft" && g.useCache && z.has(y))
332
+ return I.info(`get preload component from cache: ${y}`), z.get(y);
333
+ const v = se({ state: e, componentId: g.componentId });
334
+ if (!v) return null;
335
335
  const x = await os({
336
336
  req: o,
337
337
  state: e,
338
- componentId: T.id,
338
+ componentId: v.id,
339
339
  locale: s,
340
340
  defaultLocale: a,
341
341
  properties: g.properties
@@ -344,7 +344,7 @@ async function no({
344
344
  const U = { instanceId: g.id, preload: x };
345
345
  if (t !== "draft" && g.useCache) {
346
346
  let D = Zt;
347
- g.cacheDuration && (D = g.cacheDuration), I.info(`set preload component to cache(${D}s): ${y}`), K.set(y, U, {
347
+ g.cacheDuration && (D = g.cacheDuration), I.info(`set preload component to cache(${D}s): ${y}`), z.set(y, U, {
348
348
  ttl: D * 1e3
349
349
  });
350
350
  }
@@ -359,7 +359,7 @@ async function no({
359
359
  async function p() {
360
360
  const g = await Promise.all(
361
361
  c.map(async (y) => {
362
- const T = ot({ componentId: y.component.id }), x = r === X.ESM ? {
362
+ const v = ot({ componentId: y.component.id }), x = r === X.ESM ? {
363
363
  module: r,
364
364
  script: await xe(y.script, {
365
365
  componentId: y.component.id,
@@ -371,10 +371,10 @@ async function no({
371
371
  script: await xe(y.script, {
372
372
  componentId: y.component.id,
373
373
  module: r,
374
- moduleName: T,
374
+ moduleName: v,
375
375
  tailwind: t !== "draft"
376
376
  }),
377
- moduleName: T
377
+ moduleName: v
378
378
  };
379
379
  return [y.component.id, { component: y.component, script: x }];
380
380
  })
@@ -404,14 +404,14 @@ async function os({
404
404
  if (!a) return null;
405
405
  const i = l.some((p) => p.locale === s) ? s : n;
406
406
  if (!i) return null;
407
- const c = await Ge({ req: t, state: o, componentId: e, locale: i, defaultLocale: n, properties: r });
407
+ const c = await Ve({ req: t, state: o, componentId: e, locale: i, defaultLocale: n, properties: r });
408
408
  return c ? {
409
409
  component: a,
410
410
  ...c
411
411
  } : null;
412
412
  }
413
413
  const ns = 20;
414
- async function Ge({
414
+ async function Ve({
415
415
  req: t,
416
416
  depth: o = 0,
417
417
  state: e,
@@ -437,7 +437,7 @@ async function Ge({
437
437
  return await Promise.all(
438
438
  Object.entries(i).map(async ([p, u]) => {
439
439
  if ((u == null ? void 0 : u.type) === Oe) {
440
- const f = await Ge({
440
+ const f = await Ve({
441
441
  req: t,
442
442
  depth: o + 1,
443
443
  state: e,
@@ -497,7 +497,7 @@ async function as({
497
497
  }) {
498
498
  if (!(o != null && o.includes("getServerSideProps")))
499
499
  return null;
500
- const n = await Ve(o, "getServerSideProps");
500
+ const n = await Ge(o, "getServerSideProps");
501
501
  if (!n) return null;
502
502
  const r = new Promise((a) => {
503
503
  setTimeout(() => {
@@ -561,7 +561,7 @@ export { joinURL, withQuery, getQuery, getComponentMountPoint }
561
561
  location: { href: _(pt(s.hostname), s.originalUrl) },
562
562
  fetch: (a, { ...i } = {}) => {
563
563
  const c = typeof a == "string" && a.startsWith("/") ? _(S.env.appUrl, a) : a;
564
- if (typeof c == "string" && Ae(c).host === Ae(S.env.appUrl).host) {
564
+ if (typeof c == "string" && Te(c).host === Te(S.env.appUrl).host) {
565
565
  const p = s.get("cookie");
566
566
  if (p) {
567
567
  const u = new it(i.headers);
@@ -589,7 +589,7 @@ const is = ae(
589
589
  async (t, o, e) => {
590
590
  if (!(t != null && t.includes(o)))
591
591
  return null;
592
- const s = await Ve(t, o);
592
+ const s = await Ge(t, o);
593
593
  if (s)
594
594
  try {
595
595
  return await _e.callFunction({
@@ -618,7 +618,7 @@ const is = ae(
618
618
  ttl: 1e3 * 60 * 60
619
619
  }
620
620
  }
621
- ), cs = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", ke = "page", fe = "trigger-reload-project-resource", Je = cs, ls = "z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV", { uploadToMediaKit: ps } = require("@blocklet/uploader-server"), De = kt("abcdefghijklmnopqrstuvwxyz0123456789", 16), Se = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, W = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Ne = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, us = 1e4, ds = 3e4, q = 0, ue = 1, ms = 0, fs = 1, ge = S, Q = A(process.env.BLOCKLET_DATA_DIR, "site-state"), ao = ["production", "draft"], io = ["production"];
621
+ ), cs = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", ke = "page", fe = "trigger-reload-project-resource", Je = cs, ls = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM", { uploadToMediaKit: ps } = require("@blocklet/uploader-server"), De = kt("abcdefghijklmnopqrstuvwxyz0123456789", 16), Se = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, Y = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Ne = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, us = 1e4, ds = 3e4, q = 0, ue = 1, ms = 0, fs = 1, ge = S, Q = T(process.env.BLOCKLET_DATA_DIR, "site-state"), ao = ["production", "draft"], io = ["production"];
622
622
  function He(t) {
623
623
  return (t == null ? void 0 : t.replace(/\//g, "|")) || "";
624
624
  }
@@ -637,11 +637,11 @@ function gs() {
637
637
  const M = class M extends $.Doc {
638
638
  constructor(e) {
639
639
  super();
640
- P(this, "states", {});
641
- P(this, "syncedStore");
642
- P(this, "conns", /* @__PURE__ */ new Map());
643
- P(this, "awareness");
644
- P(this, "awarenessChangeHandler", ({ added: e, updated: s, removed: n }, r) => {
640
+ C(this, "states", {});
641
+ C(this, "syncedStore");
642
+ C(this, "conns", /* @__PURE__ */ new Map());
643
+ C(this, "awareness");
644
+ C(this, "awarenessChangeHandler", ({ added: e, updated: s, removed: n }, r) => {
645
645
  const l = e.concat(s, n);
646
646
  if (r !== null) {
647
647
  const c = this.conns.get(r);
@@ -651,18 +651,18 @@ const M = class M extends $.Doc {
651
651
  c.delete(p);
652
652
  }));
653
653
  }
654
- const a = C.createEncoder();
655
- C.writeVarUint(a, ue), C.writeVarUint8Array(a, Pe(this.awareness, l));
656
- const i = C.toUint8Array(a);
654
+ const a = P.createEncoder();
655
+ P.writeVarUint(a, ue), P.writeVarUint8Array(a, Ce(this.awareness, l));
656
+ const i = P.toUint8Array(a);
657
657
  this.conns.forEach((c, p) => this.send(p, i));
658
658
  });
659
- P(this, "updateHandler", (e) => {
660
- const s = C.createEncoder();
661
- C.writeVarUint(s, q), Ft(s, e);
662
- const n = C.toUint8Array(s);
659
+ C(this, "updateHandler", (e) => {
660
+ const s = P.createEncoder();
661
+ P.writeVarUint(s, q), Ft(s, e);
662
+ const n = P.toUint8Array(s);
663
663
  this.conns.forEach((r, l) => this.send(l, n));
664
664
  });
665
- P(this, "ensureDataStructure", () => {
665
+ C(this, "ensureDataStructure", () => {
666
666
  var l;
667
667
  const { supportedLocales: e, pages: s, pageIds: n, config: r } = this.syncedStore;
668
668
  {
@@ -683,7 +683,7 @@ const M = class M extends $.Doc {
683
683
  }
684
684
  }
685
685
  });
686
- P(this, "send", (e, s) => {
686
+ C(this, "send", (e, s) => {
687
687
  e.readyState !== ms && e.readyState !== fs && this.closeConn(e);
688
688
  try {
689
689
  e.send(s, (n) => {
@@ -693,27 +693,27 @@ const M = class M extends $.Doc {
693
693
  this.closeConn(e);
694
694
  }
695
695
  });
696
- P(this, "closeConn", (e) => {
696
+ C(this, "closeConn", (e) => {
697
697
  if (e.removeAllListeners(), this.conns.has(e)) {
698
698
  const s = this.conns.get(e);
699
699
  this.conns.delete(e), s && _t(this.awareness, Array.from(s), null);
700
700
  }
701
701
  e.close();
702
702
  });
703
- P(this, "autoSave", Fe(() => {
703
+ C(this, "autoSave", Fe(() => {
704
704
  F(L(this.draftYjsFilePath), { recursive: !0 }), te(this.draftYjsFilePath, $.encodeStateAsUpdate(this));
705
705
  }, us));
706
- P(this, "save", ({ flush: e = !1 } = {}) => {
706
+ C(this, "save", ({ flush: e = !1 } = {}) => {
707
707
  this.autoSave(), e && this.autoSave.flush();
708
708
  });
709
- P(this, "publish", async ({ mode: e, pages: s }) => {
709
+ C(this, "publish", async ({ mode: e, pages: s }) => {
710
710
  const n = await this.getState("draft"), r = await this.getState("production");
711
711
  await Ue(n, r, { pages: s, pageMergeMode: "replace", deletePages: !0, publishMode: e }), r.config.publishedAt = (/* @__PURE__ */ new Date()).getTime();
712
712
  for (const l of s || Object.keys(this.syncedStore.pages))
713
713
  this.syncedStore.pages[l] && (this.syncedStore.pages[l].publishedAt = (/* @__PURE__ */ new Date()).toISOString());
714
714
  await this.setState(e, r);
715
715
  });
716
- P(this, "mergeState", async (e, s) => {
716
+ C(this, "mergeState", async (e, s) => {
717
717
  var a, i, c;
718
718
  const n = JSON.parse(JSON.stringify(s));
719
719
  (a = e.config).fontFamily ?? (a.fontFamily = {});
@@ -729,7 +729,7 @@ const M = class M extends $.Doc {
729
729
  });
730
730
  });
731
731
  });
732
- P(this, "addConnection", (e) => {
732
+ C(this, "addConnection", (e) => {
733
733
  if (this.conns.has(e))
734
734
  return;
735
735
  e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (r) => this.messageListener(e, new Uint8Array(r)));
@@ -752,21 +752,21 @@ const M = class M extends $.Doc {
752
752
  s = !0;
753
753
  });
754
754
  {
755
- const r = C.createEncoder();
756
- C.writeVarUint(r, q), Bt(r, this), this.send(e, C.toUint8Array(r));
755
+ const r = P.createEncoder();
756
+ P.writeVarUint(r, q), Bt(r, this), this.send(e, P.toUint8Array(r));
757
757
  const l = this.awareness.getStates();
758
758
  if (l.size > 0) {
759
- const a = C.createEncoder();
760
- C.writeVarUint(a, ue), C.writeVarUint8Array(a, Pe(this.awareness, Array.from(l.keys()))), this.send(e, C.toUint8Array(a));
759
+ const a = P.createEncoder();
760
+ P.writeVarUint(a, ue), P.writeVarUint8Array(a, Ce(this.awareness, Array.from(l.keys()))), this.send(e, P.toUint8Array(a));
761
761
  }
762
762
  }
763
763
  });
764
- P(this, "messageListener", (e, s) => {
764
+ C(this, "messageListener", (e, s) => {
765
765
  try {
766
- const n = C.createEncoder(), r = pe.createDecoder(s), l = pe.readVarUint(r);
766
+ const n = P.createEncoder(), r = pe.createDecoder(s), l = pe.readVarUint(r);
767
767
  switch (l) {
768
768
  case q:
769
- C.writeVarUint(n, q), Vt(r, n, this, null), C.length(n) > 1 && (this.ensureDataStructure(), this.send(e, C.toUint8Array(n)));
769
+ P.writeVarUint(n, q), Gt(r, n, this, null), P.length(n) > 1 && (this.ensureDataStructure(), this.send(e, P.toUint8Array(n)));
770
770
  break;
771
771
  case ue: {
772
772
  $t(this.awareness, pe.readVarUint8Array(r), e);
@@ -780,8 +780,8 @@ const M = class M extends $.Doc {
780
780
  }
781
781
  this.save();
782
782
  });
783
- this.options = e, V(this.draftYjsFilePath) && $.applyUpdate(this, H(this.draftYjsFilePath)), this.syncedStore = Tt(
784
- vt(
783
+ this.options = e, G(this.draftYjsFilePath) && $.applyUpdate(this, H(this.draftYjsFilePath)), this.syncedStore = vt(
784
+ At(
785
785
  { pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
786
786
  this
787
787
  )
@@ -792,8 +792,8 @@ const M = class M extends $.Doc {
792
792
  if (!e)
793
793
  throw new Error("Should provide project context");
794
794
  try {
795
- const s = A(Q, e), n = A(Q, `@del-${e}`);
796
- Te(s, n);
795
+ const s = T(Q, e), n = T(Q, `@del-${e}`);
796
+ ve(s, n);
797
797
  } catch (s) {
798
798
  I.error("Failed to safe delete project state dir:", s);
799
799
  }
@@ -813,7 +813,7 @@ const M = class M extends $.Doc {
813
813
  throw new Error("Should provide project context");
814
814
  let s = this.sharedInstances.get(e);
815
815
  return s || (s = new M({
816
- path: A(Q, e)
816
+ path: T(Q, e)
817
817
  }), this.sharedInstances.set(e, s), s);
818
818
  }
819
819
  destroy() {
@@ -840,13 +840,13 @@ const M = class M extends $.Doc {
840
840
  });
841
841
  }
842
842
  get draftYjsFilePath() {
843
- return A(this.options.path, "draft.yjs");
843
+ return T(this.options.path, "draft.yjs");
844
844
  }
845
845
  async getState(e) {
846
846
  var s, n, r, l;
847
847
  if (e === "draft")
848
848
  return JSON.parse(JSON.stringify(this.syncedStore));
849
- if (!this.states[e] && (this.states[e] = await We(this.getPublishDir(e), { includeResources: !0 }) ?? gs(), !((n = (s = this.states[e]) == null ? void 0 : s.config) != null && n.defaultLocale))) {
849
+ if (!this.states[e] && (this.states[e] = await Ye(this.getPublishDir(e), { includeResources: !0 }) ?? gs(), !((n = (s = this.states[e]) == null ? void 0 : s.config) != null && n.defaultLocale))) {
850
850
  (r = this.states[e]).config ?? (r.config = {});
851
851
  const a = ge.env.languages.map((i) => ({ locale: i.code, name: i.name }));
852
852
  this.states[e].config.defaultLocale = (l = a[0]) == null ? void 0 : l.locale;
@@ -855,18 +855,18 @@ const M = class M extends $.Doc {
855
855
  ...this.states[e],
856
856
  resources: await Xe().then(async (a) => {
857
857
  var u, f, g, y;
858
- const { pages: i, components: c } = Ct(a, "pages", "components");
858
+ const { pages: i, components: c } = Pt(a, "pages", "components");
859
859
  let p = c;
860
860
  if ((f = (u = this.states[e]) == null ? void 0 : u.resources) != null && f.components)
861
861
  p = {
862
862
  ...(y = (g = this.states[e]) == null ? void 0 : g.resources) == null ? void 0 : y.components
863
863
  };
864
864
  else {
865
- const T = J(this.options.path), x = await B.findByPk(T);
865
+ const v = J(this.options.path), x = await B.findByPk(v);
866
866
  if (x != null && x.useAllResources)
867
867
  p = c;
868
868
  else {
869
- const D = (await ce.findAll({ where: { projectId: T } })).map((E) => E.componentId);
869
+ const D = (await ce.findAll({ where: { projectId: v } })).map((E) => E.componentId);
870
870
  p = Object.fromEntries(
871
871
  Object.entries(c || {}).filter(([E]) => D.includes(E))
872
872
  );
@@ -878,10 +878,10 @@ const M = class M extends $.Doc {
878
878
  }
879
879
  async setState(e, s) {
880
880
  const n = await ws(s, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(e);
881
- F(L(r), { recursive: !0 }), $e(r, { force: !0, recursive: !0 }), Te(n, r), this.states[e] = s;
881
+ F(L(r), { recursive: !0 }), $e(r, { force: !0, recursive: !0 }), ve(n, r), this.states[e] = s;
882
882
  }
883
883
  getPublishDir(e) {
884
- return A(this.options.path, e);
884
+ return T(this.options.path, e);
885
885
  }
886
886
  static async pageUrlMap(e) {
887
887
  const { projectIds: s } = this, n = {};
@@ -918,8 +918,8 @@ const M = class M extends $.Doc {
918
918
  mainPage: !0
919
919
  };
920
920
  for (const y of i) {
921
- const T = { ...g, locale: y };
922
- n[_("/", y, r, u)] = T, f && (n[_("/", y, f, u)] = T);
921
+ const v = { ...g, locale: y };
922
+ n[_("/", y, r, u)] = v, f && (n[_("/", y, f, u)] = v);
923
923
  }
924
924
  }
925
925
  }
@@ -942,8 +942,8 @@ const M = class M extends $.Doc {
942
942
  return e;
943
943
  }
944
944
  };
945
- P(M, "INSTANCE_TTL", 30 * 60 * 1e3), // 30 minutes
946
- P(M, "sharedInstances", new he({
945
+ C(M, "INSTANCE_TTL", 30 * 60 * 1e3), // 30 minutes
946
+ C(M, "sharedInstances", new he({
947
947
  max: 100,
948
948
  // Maximum number of instances to store
949
949
  ttl: M.INSTANCE_TTL,
@@ -952,8 +952,8 @@ P(M, "sharedInstances", new he({
952
952
  }
953
953
  }));
954
954
  let oe = M;
955
- function ze() {
956
- return bt(A(S.env.dataDir, "tmp-"));
955
+ function Ke() {
956
+ return bt(T(S.env.dataDir, "tmp-"));
957
957
  }
958
958
  function ne(t, o, e = []) {
959
959
  return Array.isArray(t) ? t.flatMap((s, n) => ne(s, o, [...e, n])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([s, n]) => ne(n, o, [...e, s])) : o(t) ? [e] : [];
@@ -962,7 +962,7 @@ function R(t) {
962
962
  return t.filter((o) => o != null);
963
963
  }
964
964
  async function hs(t, o, e) {
965
- if (!t || !V(t) || !Z(t).isFile())
965
+ if (!t || !G(t) || !Z(t).isFile())
966
966
  return null;
967
967
  let s = e[t];
968
968
  return s || (s = (async () => {
@@ -994,25 +994,25 @@ const ys = async (t, o) => {
994
994
  await Promise.all(
995
995
  t.map(async (e) => {
996
996
  try {
997
- await ys(e, A(o, J(e)));
997
+ await ys(e, T(o, J(e)));
998
998
  } catch (s) {
999
999
  I.error(`Failed to export assets: ${e}, ${s}`);
1000
1000
  }
1001
1001
  })
1002
1002
  );
1003
1003
  };
1004
- function Ke(t) {
1005
- return Se.test(t) ? [t] : W.test(t) ? (Ne.lastIndex = 0, Array.from(t.matchAll(Ne)).map((e) => e[1]).filter((e) => !!e)) : [];
1004
+ function ze(t) {
1005
+ return Se.test(t) ? [t] : Y.test(t) ? (Ne.lastIndex = 0, Array.from(t.matchAll(Ne)).map((e) => e[1]).filter((e) => !!e)) : [];
1006
1006
  }
1007
1007
  async function de(t, o, e) {
1008
- const { getFilename: s, exportAssets: n } = e, r = A(o, s(t));
1009
- if (F(L(r), { recursive: !0 }), te(r, z.stringify(t)), n) {
1008
+ const { getFilename: s, exportAssets: n } = e, r = T(o, s(t));
1009
+ if (F(L(r), { recursive: !0 }), te(r, K.stringify(t)), n) {
1010
1010
  const a = ne(
1011
1011
  t,
1012
- (i) => typeof i == "string" && (Se.test(i) || W.test(i))
1012
+ (i) => typeof i == "string" && (Se.test(i) || Y.test(i))
1013
1013
  ).map((i) => {
1014
1014
  const c = ye(t, i);
1015
- return Ke(c);
1015
+ return ze(c);
1016
1016
  }).flat().filter(Boolean);
1017
1017
  await Ss(a, L(r));
1018
1018
  }
@@ -1025,19 +1025,19 @@ async function Re(t, o, e) {
1025
1025
  var a;
1026
1026
  const s = ne(
1027
1027
  t,
1028
- (i) => typeof i == "string" && (Se.test(i) || W.test(i))
1028
+ (i) => typeof i == "string" && (Se.test(i) || Y.test(i))
1029
1029
  ), n = Dt(2), r = s.map(
1030
1030
  (i) => n(async () => {
1031
1031
  try {
1032
- const c = ye(t, i), p = Ke(c);
1032
+ const c = ye(t, i), p = ze(c);
1033
1033
  for (const u of p) {
1034
- const f = J(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f, T = Le.get(y);
1035
- if (T) {
1036
- W.test(c) || ve(t, i, T);
1034
+ const f = J(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f, v = Le.get(y);
1035
+ if (v) {
1036
+ Y.test(c) || Ae(t, i, v);
1037
1037
  return;
1038
1038
  }
1039
1039
  const x = await hs(g, f, o);
1040
- x && (W.test(c) || ve(t, i, x), Le.set(y, x));
1040
+ x && (Y.test(c) || Ae(t, i, x), Le.set(y, x));
1041
1041
  }
1042
1042
  } catch (c) {
1043
1043
  I.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
@@ -1099,9 +1099,9 @@ async function ws(t, {
1099
1099
  };
1100
1100
  })
1101
1101
  )
1102
- ), u = ze(), f = A(u, "pages");
1102
+ ), u = Ke(), f = T(u, "pages");
1103
1103
  F(f, { recursive: !0 });
1104
- const g = A(u, "components");
1104
+ const g = T(u, "components");
1105
1105
  F(g, { recursive: !0 });
1106
1106
  for (const { locale: m, slug: d, page: w } of p)
1107
1107
  await de(w, f, {
@@ -1115,9 +1115,9 @@ async function ws(t, {
1115
1115
  exportAssets: o
1116
1116
  });
1117
1117
  }
1118
- const y = A(u, ".blocklet/pages/pages.config.yml");
1118
+ const y = T(u, ".blocklet/pages/pages.config.yml");
1119
1119
  F(L(y), { recursive: !0 });
1120
- const T = {
1120
+ const v = {
1121
1121
  pages: R(
1122
1122
  l.map((m) => {
1123
1123
  const d = t.pages[m];
@@ -1150,10 +1150,10 @@ async function ws(t, {
1150
1150
  supportedLocales: t.supportedLocales,
1151
1151
  config: t.config
1152
1152
  };
1153
- te(y, z.stringify(T));
1154
- const x = A(u, "config.source.json");
1153
+ te(y, K.stringify(v));
1154
+ const x = T(u, "config.source.json");
1155
1155
  if (n && te(x, JSON.stringify(n)), r) {
1156
- const m = A(u, "resources"), d = A(m, "components");
1156
+ const m = T(u, "resources"), d = T(m, "components");
1157
1157
  F(d, { recursive: !0 });
1158
1158
  for (const w of Object.keys(((h = t == null ? void 0 : t.resources) == null ? void 0 : h.components) ?? {})) {
1159
1159
  const k = (O = (b = (E = t.resources) == null ? void 0 : E.components) == null ? void 0 : b[w]) == null ? void 0 : O.component;
@@ -1165,28 +1165,28 @@ async function ws(t, {
1165
1165
  }
1166
1166
  return u;
1167
1167
  }
1168
- async function We(t, { importAssets: o, includeResources: e } = {}) {
1168
+ async function Ye(t, { importAssets: o, includeResources: e } = {}) {
1169
1169
  var r, l, a;
1170
- if (!V(t))
1170
+ if (!G(t))
1171
1171
  return null;
1172
1172
  let s, n = !1;
1173
1173
  try {
1174
- Z(t).isDirectory() ? s = t : /\.(tgz|gz|tar)$/.test(t) && (n = !0, s = ze(), await Rt({ file: t, C: s }));
1175
- const i = me("**/.blocklet/pages/pages.config.yml", { cwd: s, absolute: !0 }).at(0), c = i && A(L(i), "../../pages"), p = i && A(L(i), "../../components"), u = i && A(L(i), "../../chunks");
1174
+ Z(t).isDirectory() ? s = t : /\.(tgz|gz|tar)$/.test(t) && (n = !0, s = Ke(), await Rt({ file: t, C: s }));
1175
+ const i = me("**/.blocklet/pages/pages.config.yml", { cwd: s, absolute: !0 }).at(0), c = i && T(L(i), "../../pages"), p = i && T(L(i), "../../components"), u = i && T(L(i), "../../chunks");
1176
1176
  if (!i)
1177
1177
  return null;
1178
- const f = z.parse(H(i).toString()), g = (h, E, b) => {
1179
- let O = A(h, `${E}${b ? `.${b}` : ""}.yml`);
1180
- return (!V(O) || !Z(O).isFile()) && (O = A(h, E, `index${b ? `.${b}` : ""}.yml`), !V(O) || !Z(O)) ? null : z.parse(H(O).toString());
1178
+ const f = K.parse(H(i).toString()), g = (h, E, b) => {
1179
+ let O = T(h, `${E}${b ? `.${b}` : ""}.yml`);
1180
+ return (!G(O) || !Z(O).isFile()) && (O = T(h, E, `index${b ? `.${b}` : ""}.yml`), !G(O) || !Z(O)) ? null : K.parse(H(O).toString());
1181
1181
  }, y = (h, E) => {
1182
1182
  try {
1183
1183
  const b = me(`*.${E}.yml`, { cwd: h, absolute: !0 })[0];
1184
- return b ? z.parse(H(b).toString()) : null;
1184
+ return b ? K.parse(H(b).toString()) : null;
1185
1185
  } catch (b) {
1186
1186
  I.error("parse component error", b);
1187
1187
  }
1188
1188
  return null;
1189
- }, T = R(
1189
+ }, v = R(
1190
1190
  f.pages.map(({ slug: h }) => {
1191
1191
  var m;
1192
1192
  const E = R(
@@ -1237,25 +1237,25 @@ async function We(t, { importAssets: o, includeResources: e } = {}) {
1237
1237
  ), x = p ? R(((r = f.components) == null ? void 0 : r.map(({ id: h }) => y(p, h))) ?? []) : [];
1238
1238
  if (o) {
1239
1239
  const h = (...E) => {
1240
- I.info(`[${n ? J(t) : J(A(t, "../../../../"))}] importAssets:`, ...E);
1240
+ I.info(`[${n ? J(t) : J(T(t, "../../../../"))}] importAssets:`, ...E);
1241
1241
  };
1242
1242
  try {
1243
1243
  h("wait image-bin api ready"), await Ut({
1244
- resources: [`${ht(zt)}/api/sdk/uploads`],
1244
+ resources: [`${ht(Kt)}/api/sdk/uploads`],
1245
1245
  validateStatus: (O) => O >= 200 && O <= 500
1246
1246
  }), h("image-bin api is ready");
1247
1247
  const E = {}, b = {};
1248
1248
  h("start to upload assets"), await Promise.allSettled([
1249
1249
  Re(x, E, {
1250
- getFilePath: (O) => p && A(p, O),
1250
+ getFilePath: (O) => p && T(p, O),
1251
1251
  onFinish: (O) => {
1252
1252
  h(`upload ${O.length} component assets`);
1253
1253
  }
1254
1254
  }),
1255
- Re(T, b, {
1255
+ Re(v, b, {
1256
1256
  getFilePath: (O, m) => {
1257
- const d = ye(T, m.slice(0, 1));
1258
- return c && A(c, L(d.slug), O);
1257
+ const d = ye(v, m.slice(0, 1));
1258
+ return c && T(c, L(d.slug), O);
1259
1259
  },
1260
1260
  onFinish: (O) => {
1261
1261
  h(`upload ${O.length} page assets`);
@@ -1268,7 +1268,7 @@ async function We(t, { importAssets: o, includeResources: e } = {}) {
1268
1268
  }
1269
1269
  const U = {};
1270
1270
  if (e) {
1271
- const h = i && A(L(i), "../../resources/components"), E = R(
1271
+ const h = i && T(L(i), "../../resources/components"), E = R(
1272
1272
  ((a = (l = f.resources) == null ? void 0 : l.components) == null ? void 0 : a.map(({ id: b }) => y(h, b))) ?? []
1273
1273
  );
1274
1274
  E.length > 0 && (U.components = Object.fromEntries(
@@ -1276,16 +1276,16 @@ async function We(t, { importAssets: o, includeResources: e } = {}) {
1276
1276
  ));
1277
1277
  }
1278
1278
  const D = {};
1279
- if (u && V(u)) {
1279
+ if (u && G(u)) {
1280
1280
  const h = Et(u);
1281
1281
  for (const E of h)
1282
- D[E] = A(u, E);
1282
+ D[E] = T(u, E);
1283
1283
  }
1284
1284
  return {
1285
1285
  supportedLocales: f.supportedLocales,
1286
- pageIds: T.map((h) => h.id),
1286
+ pageIds: v.map((h) => h.id),
1287
1287
  components: Object.fromEntries(x.map((h, E) => [h.id, { index: E, data: h }])),
1288
- pages: Object.fromEntries(T.map((h) => [h.id, h])),
1288
+ pages: Object.fromEntries(v.map((h) => [h.id, h])),
1289
1289
  config: f.config || {},
1290
1290
  resources: U,
1291
1291
  chunks: D
@@ -1333,7 +1333,7 @@ async function Ue(t, o, {
1333
1333
  c = Object.fromEntries(
1334
1334
  await Promise.all(
1335
1335
  Object.entries(c).map(async ([p, u]) => {
1336
- const f = await Ye(u == null ? void 0 : u.data);
1336
+ const f = await We(u == null ? void 0 : u.data);
1337
1337
  return [
1338
1338
  p,
1339
1339
  {
@@ -1345,10 +1345,10 @@ async function Ue(t, o, {
1345
1345
  )
1346
1346
  ), Object.assign(o.components, c), Object.assign(o.config, JSON.parse(JSON.stringify(t.config))), o.resources.components = JSON.parse(JSON.stringify(t.resources.components || {}));
1347
1347
  }
1348
- const Ye = ae(
1348
+ const We = ae(
1349
1349
  async (t) => {
1350
1350
  var o;
1351
- if (!Pt(t == null ? void 0 : t.properties))
1351
+ if (!Ct(t == null ? void 0 : t.properties))
1352
1352
  return t;
1353
1353
  if (((o = t == null ? void 0 : t.renderer) == null ? void 0 : o.type) === "react-component") {
1354
1354
  const { script: e } = (t == null ? void 0 : t.renderer) || {};
@@ -1401,7 +1401,7 @@ function Es({
1401
1401
  }
1402
1402
  return [...n];
1403
1403
  }
1404
- let re, G, we, Ee, be;
1404
+ let re, V, we, Ee, be;
1405
1405
  function qe() {
1406
1406
  return re = (async () => {
1407
1407
  const t = gt({
@@ -1410,12 +1410,12 @@ function qe() {
1410
1410
  { did: ls, type: ke }
1411
1411
  ]
1412
1412
  });
1413
- G = (await Promise.all(
1413
+ V = (await Promise.all(
1414
1414
  t.map(async (e) => {
1415
- const s = e.path ? await We(e.path, { importAssets: !1 }) : void 0;
1415
+ const s = e.path ? await Ye(e.path, { importAssets: !1 }) : void 0;
1416
1416
  return s ? { blockletId: e.did, state: s, blockletTitle: e.title } : void 0;
1417
1417
  })
1418
- )).filter((e) => !!e), we = G.reduce(
1418
+ )).filter((e) => !!e), we = V.reduce(
1419
1419
  (e, s) => Object.assign(
1420
1420
  e,
1421
1421
  Object.fromEntries(
@@ -1424,7 +1424,7 @@ function qe() {
1424
1424
  ),
1425
1425
  {}
1426
1426
  );
1427
- const o = G.reduce(
1427
+ const o = V.reduce(
1428
1428
  (e, s) => Object.assign(
1429
1429
  e,
1430
1430
  Object.fromEntries(
@@ -1436,7 +1436,7 @@ function qe() {
1436
1436
  Ee = Object.fromEntries(
1437
1437
  await Promise.all(
1438
1438
  Object.entries(o).map(async ([e, s]) => {
1439
- const n = await Ye(s.component);
1439
+ const n = await We(s.component);
1440
1440
  return [
1441
1441
  e,
1442
1442
  {
@@ -1446,7 +1446,7 @@ function qe() {
1446
1446
  ];
1447
1447
  })
1448
1448
  )
1449
- ), be = G.reduce((e, s) => Object.assign(e, s.state.chunks), {});
1449
+ ), be = V.reduce((e, s) => Object.assign(e, s.state.chunks), {});
1450
1450
  })(), re;
1451
1451
  }
1452
1452
  function bs(t) {
@@ -1455,7 +1455,7 @@ function bs(t) {
1455
1455
  await qe().catch((e) => {
1456
1456
  I.error("load resource states error", { error: e });
1457
1457
  }), await (t == null ? void 0 : t({
1458
- states: G,
1458
+ states: V,
1459
1459
  pages: we,
1460
1460
  components: Ee,
1461
1461
  chunks: be
@@ -1509,7 +1509,7 @@ async function co() {
1509
1509
  async function Xe({
1510
1510
  ensureLoaded: t = !0
1511
1511
  } = {}) {
1512
- return t && (re ?? (re = qe()), await re), { states: G, pages: we, components: Ee, chunks: be };
1512
+ return t && (re ?? (re = qe()), await re), { states: V, pages: we, components: Ee, chunks: be };
1513
1513
  }
1514
1514
  export {
1515
1515
  Je as C,
@@ -1534,7 +1534,7 @@ export {
1534
1534
  Q as o,
1535
1535
  ao as p,
1536
1536
  io as q,
1537
- We as r,
1537
+ Ye as r,
1538
1538
  Ue as s,
1539
1539
  ws as t,
1540
1540
  bs as u,
@@ -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-DYbvp514.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-AYUSPJ7w.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 { l as k, b as H } from "./_chunks/site-state-DYbvp514.js";
1
+ import { l as k, b as H } from "./_chunks/site-state-AYUSPJ7w.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-DYbvp514.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-AYUSPJ7w.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 x, o as D, p as H, S as M, r as O, a as j, u as q, s as v, n as B, t as L, v as U } from "./_chunks/site-state-DYbvp514.js";
1
+ import { q as x, o as D, p as H, S as M, r as O, a as j, u as q, s as v, n as B, t as L, v as U } from "./_chunks/site-state-AYUSPJ7w.js";
2
2
  import "@blocklet/quickjs";
3
3
  import "@blocklet/sdk/lib/component";
4
4
  import "@blocklet/sdk/lib/config";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blocklet/pages-kit-inner-components",
3
- "version": "0.4.71",
3
+ "version": "0.4.73",
4
4
  "description": "Pages Kit inner components library",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -67,21 +67,21 @@
67
67
  "dependencies": {
68
68
  "@arcblock/did-auth": "^1.19.15",
69
69
  "@arcblock/did-auth-storage-nedb": "^1.7.1",
70
- "@arcblock/did-connect": "^2.12.36",
71
- "@arcblock/react-hooks": "^2.12.36",
72
- "@arcblock/ux": "^2.12.36",
70
+ "@arcblock/did-connect": "^2.12.40",
71
+ "@arcblock/react-hooks": "^2.12.40",
72
+ "@arcblock/ux": "^2.12.40",
73
73
  "@blocklet/ai-kit": "^0.1.72",
74
- "@blocklet/ai-runtime": "^0.4.253",
75
- "@blocklet/code-editor": "^0.4.253",
76
- "@blocklet/crawler": "^2.1.212",
74
+ "@blocklet/ai-runtime": "^0.4.254",
75
+ "@blocklet/code-editor": "^0.4.254",
76
+ "@blocklet/crawler": "^2.1.217",
77
77
  "@blocklet/embed": "^0.2.3",
78
78
  "@blocklet/js-sdk": "^1.16.40",
79
79
  "@blocklet/logger": "1.16.36",
80
- "@blocklet/quickjs": "^0.4.253",
80
+ "@blocklet/quickjs": "^0.4.254",
81
81
  "@blocklet/sdk": "^1.16.40",
82
- "@blocklet/studio-ui": "^0.4.253",
82
+ "@blocklet/studio-ui": "^0.4.254",
83
83
  "@blocklet/tracker": "^1.16.40",
84
- "@blocklet/ui-react": "^2.12.36",
84
+ "@blocklet/ui-react": "^2.12.40",
85
85
  "@blocklet/uploader": "^0.1.79",
86
86
  "@blocklet/uploader-server": "^0.1.90",
87
87
  "@emotion/cache": "^11.13.1",
@@ -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.71",
206
- "@blocklet/pages-kit-block-studio": "^0.4.71"
205
+ "@blocklet/pages-kit": "^0.4.73",
206
+ "@blocklet/pages-kit-block-studio": "^0.4.73"
207
207
  },
208
208
  "devDependencies": {
209
209
  "@trivago/prettier-plugin-sort-imports": "^5.2.1",