@blocklet/pages-kit-inner-components 0.5.29 → 0.5.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/add-component.js +47 -23
- package/lib/cjs/chunks/array-BH41o7C6.js +475 -0
- package/lib/cjs/chunks/{config-string-C4Q0hgG0.js → config-string-B3JoYJVu.js} +1 -1
- package/lib/cjs/chunks/{draft-data-Cu9gua-P.js → draft-data-hZaTeHgL.js} +1 -1
- package/lib/cjs/chunks/home-B6E0yAU3.js +38 -0
- package/lib/cjs/chunks/{publish-button-DvwoFH1F.js → publish-button-CO_WU_f5.js} +1 -1
- package/lib/cjs/chunks/site-state-D5jk8eJT.js +57 -0
- package/lib/cjs/chunks/state-DxOb57hO.js +1 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/locales.js +3 -1
- package/lib/cjs/project-html.js +2 -2
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/add-component.js +795 -749
- package/lib/es/chunks/array-NLDZzhVt.js +2224 -0
- package/lib/es/chunks/{config-string-CNLg1EYu.js → config-string-DutyRoOh.js} +1 -1
- package/lib/es/chunks/{draft-data-hSHLdxKp.js → draft-data-DjX0kpDC.js} +1 -1
- package/lib/es/chunks/{home-CNk6U8FU.js → home-CxRa0eKd.js} +112 -96
- package/lib/es/chunks/{publish-button-BftBlabj.js → publish-button-1bl_Nuva.js} +3 -3
- package/lib/es/chunks/site-state-DEduMTrY.js +2073 -0
- package/lib/es/chunks/state-C02ZI8vz.js +605 -0
- package/lib/es/components.js +1 -1
- package/lib/es/home.js +3 -3
- package/lib/es/locales.js +44 -6
- package/lib/es/project-html.js +43 -42
- package/lib/es/resources.js +51 -51
- package/lib/es/setting.js +2 -2
- package/lib/es/site-state.js +1 -1
- package/package.json +10 -10
- package/lib/cjs/chunks/array-CJC7ex3i.js +0 -467
- package/lib/cjs/chunks/home-CimGvyT9.js +0 -38
- package/lib/cjs/chunks/site-state-JgP3yURe.js +0 -57
- package/lib/cjs/chunks/state-jCG5gSUJ.js +0 -1
- package/lib/es/chunks/array-9j8tOSbO.js +0 -1993
- package/lib/es/chunks/site-state-BB9-Tm4i.js +0 -1930
- package/lib/es/chunks/state-D5BnGunt.js +0 -483
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";var Pt=Object.defineProperty;var _t=(e,s,t)=>s in e?Pt(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var x=(e,s,t)=>_t(e,typeof s!="symbol"?s+"":s,t);const jt=require("@blocklet/pages-kit/builtin/utils"),ye=require("@blocklet/pages-kit/types"),re=require("@blocklet/pages-kit/utils/property"),ie=require("@blocklet/quickjs"),Dt=require("@blocklet/sdk/lib/config"),qe=require("lru-cache"),at=require("node-fetch"),M=require("ufo"),W=require("crypto"),vt=require("@blocklet/logger"),S=require("fs"),w=require("path"),xt=require("lodash/isNil"),kt=require("@blocklet/pages-kit/utils/builtin"),ot=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),$e=require("@blocklet/sdk/lib/component"),Nt=require("autoprefixer"),Rt=require("esbuild"),Lt=require("postcss"),Mt=require("tailwindcss"),Ut=require("typescript"),Q=require("@syncedstore/core"),Ft=require("yjs"),qt=require("@blocklet/pages-kit/utils/data-source"),be=require("@blocklet/pages-kit/utils/route"),$t=require("lodash"),Bt=require("@reactivedata/reactive"),ke=require("glob"),Ht=require("lib0/decoding"),Gt=require("lib0/encoding"),Vt=require("lodash/cloneDeep"),Jt=require("lodash/debounce"),zt=require("lodash/get"),Kt=require("lodash/isEmpty"),Yt=require("lodash/pick"),Wt=require("lodash/set"),Qt=require("lodash/union"),Xt=require("nanoid"),Zt=require("p-limit"),es=require("stream/promises"),ts=require("tar"),ss=require("wait-on"),se=require("y-protocols/awareness"),je=require("y-protocols/sync"),ns=require("yaml"),j=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const N=e=>e&&e.__esModule?e:{default:e};function de(e){if(e&&e.__esModule)return e;const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,n.get?n:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const I=N(Dt),as=N(at),os=N(vt),rt=N(w),rs=N(xt),is=N(Nt),cs=de(Rt),ls=N(Lt),ds=N(Mt),L=N(Ut),B=de(Ft),De=de(Ht),k=de(Gt),us=N(Vt),it=N(Jt),Be=N(zt),ps=N(Kt),fs=N(Yt),Qe=N(Wt),ms=N(Qt),gs=N(Zt),hs=N(ss),X=de(ns);I.default.env.mode;I.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;I.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;I.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;I.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const ys="image-bin";I.default.env.INIT_TEMPLATE_PATH;const Ss=process.env.DATABASE_URL||rt.default.join(I.default.env.dataDir,"db/pages-kit.db"),Xe=I.default,ws=()=>I.default.env.tenantMode==="multiple",bs=()=>{var e;return(rs.default(Xe.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=Xe.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},Es=rt.default.join(I.default.env.dataDir,"fs-memoize-cache"),Is=I.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",O=os.default("pages-kit"),Os=j.DataTypes.sqlite.DATE.parse;j.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):Os(e,s);const ue=new j.Sequelize({dialect:"sqlite",storage:Ss,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});ue.query("pragma journal_mode = WAL;");ue.query("pragma synchronous = normal;");ue.query("pragma journal_size_limit = 67108864;");class Te extends j.Model{}Te.init({id:{type:j.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:j.DataTypes.UUIDV4},projectId:{type:j.DataTypes.UUID,allowNull:!1},componentId:{type:j.DataTypes.STRING,allowNull:!1}},{sequelize:ue,tableName:"ProjectComponents",timestamps:!1});class J extends j.Model{static async getProjectByIdOrSlug(s){return J.findOne({where:{[j.Op.or]:[{id:s},{slug:s}]}})}}J.init({id:{type:j.DataTypes.UUID,defaultValue:j.DataTypes.UUIDV4,primaryKey:!0},name:{type:j.DataTypes.STRING,allowNull:!1},description:j.DataTypes.TEXT,createdAt:j.DataTypes.DATE,updatedAt:j.DataTypes.DATE,createdBy:{type:j.DataTypes.STRING,allowNull:!1},updatedBy:{type:j.DataTypes.STRING,allowNull:!1},slug:j.DataTypes.STRING,icon:j.DataTypes.STRING,pinnedAt:j.DataTypes.DATE,useAllResources:j.DataTypes.BOOLEAN,npmSecret:j.DataTypes.STRING,relatedBlocklets:{type:j.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:ue,paranoid:!0});J.hasMany(Te,{foreignKey:"projectId",as:"components"});const As=Es,Ts=Is,Ne=7*24*60*60*1e3,Cs=24*60*60*1e3,ct=async(e="")=>{const s=w.join(As,e);try{if(!(await S.promises.stat(s)).isDirectory())throw new Error(`${s} is not a directory`)}catch{await S.promises.mkdir(s,{recursive:!0})}return s},Ps=(e,s)=>{const t=W.createHash("md5").update(s).digest("hex");return w.join(e,`${Ts}-${t}.json`)},_s=async(e="")=>{const s=await ct(e),t=Date.now();try{const n=await S.promises.readdir(s);await Promise.all(n.filter(a=>a.endsWith(".json")).map(async a=>{const o=w.join(s,a);try{const d=await S.promises.readFile(o,"utf-8"),i=JSON.parse(d);i.createdAt&&t-i.createdAt>Ne&&await S.promises.unlink(o)}catch{try{const i=await S.promises.stat(o);t-i.mtimeMs>Ne&&await S.promises.unlink(o)}catch{}}}))}catch(n){console.error(`Failed to cleanup cache in ${s}:`,n)}},js=(()=>{const e=new Set;return setInterval(async()=>{await Promise.all(Array.from(e).map(n=>_s(n)))},Cs).unref(),n=>{e.add(n)}})();function He(e,s){return s.subdir&&js(s.subdir),ie.memoize(async(...n)=>{const a=await ct(s.subdir||""),o=s.keyGenerator?s.keyGenerator(...n):JSON.stringify(n),d=Ps(a,o);try{const i=await S.promises.readFile(d,"utf-8"),{value:p,createdAt:r}=JSON.parse(i);if(r&&Date.now()-r>Ne)throw await S.promises.unlink(d).catch(()=>{}),new Error("Cache expired");return p}catch{const p=await e(...n),r=JSON.stringify({value:p,createdAt:Date.now()});return S.promises.writeFile(d,r,"utf-8").catch(u=>{console.error("Failed to write fs cache:",u)}),p}},{keyGenerator:s.keyGenerator,lruOptions:s.lruOptions})}const Ds=async(e,{componentId:s})=>{const t=`@tailwind components;
|
|
2
|
-
@tailwind utilities;
|
|
3
|
-
`,n=`.CustomComponent_${s}`;return(await ls.default([ds.default({content:[{raw:e,extension:"tsx"}]}),is.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),o=>{o.walkRules(d=>{d.selectors=d.selectors.map(i=>i.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},vs=async(e,{componentId:s})=>{const t=await Ds(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
|
|
4
|
-
|
|
5
|
-
${e}
|
|
6
|
-
`},Ze=He(async(e,s)=>{let t=L.default.transpileModule(e,{compilerOptions:{jsx:L.default.JsxEmit.React,target:L.default.ScriptTarget.ES2016,module:L.default.ModuleKind.ESNext},transformers:{before:[ot.createBuiltinModuleTransformer(L.default)]}}).outputText;if(s.tailwind&&(t=await vs(t,{componentId:s.componentId})),s.module===ye.PreloadComponentScriptModule.ESM)return t;const n=L.default.transpileModule(t,{compilerOptions:{jsx:L.default.JsxEmit.React,target:L.default.ScriptTarget.ES2016,module:L.default.ModuleKind.CommonJS,moduleResolution:L.default.ModuleResolutionKind.Node16}}).outputText;return s.module===ye.PreloadComponentScriptModule.CJS?n:ks(s.moduleName,n)},{keyGenerator:(e,s)=>{const t=W.createHash("md5").update(e).digest("hex"),n={...s,componentId:s.componentId,module:s.module,...s.module!==ye.PreloadComponentScriptModule.ESM?{moduleName:s.moduleName}:{},tailwind:s.tailwind};return JSON.stringify(["transpileModule",t,n])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"transpileModule"}),xs=async(e,s)=>{var d,i;const n=(i=(d=(await cs.build({entryPoints:["index.tsx"],external:Object.keys(kt.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(p){let r=null;p.onResolve({filter:/.*/},u=>u.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:u.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),p.onLoad({filter:/.*/,namespace:"vfs"},async u=>{var g;if(u.path==="index.tsx")return{contents:`export { ${s} } from './component'`,loader:"tsx"};if(u.path==="component.tsx")return{contents:e,loader:"tsx"};if(ot.isRelativeModule(u.path)){const y=u.path.split("/").pop();if(r||(r=await Ce({ensureLoaded:!1})),(g=r==null?void 0:r.chunks)!=null&&g[y])try{const c=S.readFileSync(r.chunks[y],"utf-8");return O.info("get chunk from local file system",y),{contents:c,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:d[0])==null?void 0:i.contents;if(!n)throw new Error("Failed to build server code");const a=Buffer.from(n).toString();return L.default.transpileModule(a,{compilerOptions:{module:L.default.ModuleKind.ESNext,target:L.default.ScriptTarget.ES2020}}).outputText},lt=He(async(e,s)=>{const t=await xs(e,s);return new RegExp(`export\\s+\\{\\s+${s}\\s+\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,s)=>{const t=W.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,s])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"extractExportValueSchema"}),ks=(e,s)=>`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
-
var ${e} = async function () {
|
|
8
|
-
|
|
9
|
-
const exports = {};
|
|
10
|
-
let moduleExports = null;
|
|
11
|
-
|
|
12
|
-
// add commonjs module compatibility layer
|
|
13
|
-
const module = { exports: moduleExports };
|
|
14
|
-
|
|
15
|
-
// execute component code
|
|
16
|
-
${s}
|
|
17
|
-
|
|
18
|
-
// handle possible module.exports
|
|
19
|
-
if (module.exports && module.exports !== moduleExports) {
|
|
20
|
-
// if module.exports is used, use it first
|
|
21
|
-
return typeof module.exports === 'object' ? module.exports : { default: module.exports };
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// ensure a default export
|
|
25
|
-
if (!('default' in exports) && Object.keys(exports).length === 0) {
|
|
26
|
-
// module has no exports, return null to indicate invalid
|
|
27
|
-
return null;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
return exports;
|
|
31
|
-
};
|
|
32
|
-
`,ae=new qe.LRUCache({max:100}),dt=60*60,Re=60;function ut(e){O.info("clear preload components cache",{cacheKey:e}),ae.delete(e)}function pt(e){for(const s of ae.keys())s.includes(e)&&(O.info("clear preload components cache",{cacheKey:s}),ut(s))}function ft({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ns({mode:e,req:s,state:t,locale:n,instances:a,module:o}){const{supportedLocales:d,config:{defaultLocale:i}}=t;if(!i)return null;const p=(await Promise.all(a.map(async c=>{try{const l=ft({mode:e,instanceId:c.id,componentId:c.componentId,locale:n});if(e!=="draft"&&c.useCache&&ae.has(l))return O.info(`get preload component from cache: ${l}`),ae.get(l);const f=ce({state:t,componentId:c.componentId});if(!f)return null;const E=await mt({req:s,state:t,componentId:f.id,locale:n,defaultLocale:i,properties:c.properties});if(!E)return null;const v={instanceId:c.id,preload:E};if(e!=="draft"&&c.useCache){let T=dt;c.cacheDuration&&(T=c.cacheDuration),O.info(`set preload component to cache(${T}s): ${l}`),ae.set(l,v,{ttl:T*1e3})}return v}catch(l){return O.error("get preload component error",{instanceId:c.id,componentId:c.componentId},{error:l}),null}}))).filter(c=>!!c),r=Object.values(p.reduce((c,l)=>({...c,...l.preload.components}),{}));async function u(){const c=await Promise.all(r.map(async l=>{const f=re.componentUMDName({componentId:l.component.id}),E=o===ye.PreloadComponentScriptModule.ESM?{module:o,script:await Ze(l.script,{componentId:l.component.id,module:o,tailwind:e!=="draft"})}:{module:o,script:await Ze(l.script,{componentId:l.component.id,module:o,moduleName:f,tailwind:e!=="draft"}),moduleName:f};return[l.component.id,{component:l.component,script:E}]}));return Object.fromEntries(c)}const g=await u();return{config:{defaultLocale:i,supportedLocales:d},components:g,instances:p.map(c=>({id:c.instanceId,componentId:c.preload.component.id,locales:{[c.preload.locale]:{props:c.preload.props}}}))}}async function mt({req:e,state:s,componentId:t,locale:n,defaultLocale:a,properties:o}){const{supportedLocales:d}=s,i=ce({state:s,componentId:t});if(!i)return null;const p=d.some(u=>u.locale===n)?n:a;if(!p)return null;const r=await gt({req:e,state:s,componentId:t,locale:p,defaultLocale:a,properties:o});return r?{component:i,...r}:null}const Rs=20;async function gt({req:e,depth:s=0,state:t,componentId:n,locale:a,defaultLocale:o,properties:d}){if(s>Rs)throw new RangeError("max component depth exceeded");const i=Ls({state:t,componentId:n,properties:d,locale:a});if(!i)return null;const{props:p}=i,r={locale:a||o,components:{[i.component.id]:{component:i.component,script:i.script}},props:{...p}};try{const u=await Us({...i,req:e});u!=null&&u.props&&Object.assign(r.props,u.props)}catch(u){O.error("preload data at server side error",{componentId:n,name:i.component.name},{error:u})}return await Promise.all(Object.entries(p).map(async([u,g])=>{if((g==null?void 0:g.type)===re.RenderNestedComponent){const y=await gt({req:e,depth:s+1,state:t,componentId:g.componentId,locale:a,defaultLocale:o,properties:g.properties});y&&(Object.assign(r.components,y.components),Object.assign(r.props,{[u]:{type:re.RenderNestedComponent,componentId:g.componentId,props:y.props}}))}})),r}function Ls({state:e,componentId:s,locale:t,properties:n}){const a=ce({state:e,componentId:s});if(!a)return null;const o=re.mergeComponent({componentId:s,getComponent:d=>ce({state:e,componentId:d}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return o?{component:a,script:o.script,props:{locale:t,...o.props}}:null}function ce({state:e,componentId:s}){var t,n,a;return((t=e.components[s])==null?void 0:t.data)??((a=(n=e.resources.components)==null?void 0:n[s])==null?void 0:a.component)}function Ms({state:e,name:s}){var n,a;const t=s.toLowerCase();return((n=Object.values(e.components).find(o=>{var d;return((d=o.data.name)==null?void 0:d.toLowerCase())===t}))==null?void 0:n.data)??((a=e.resources.components&&Object.values(e.resources.components).find(o=>{var d;return((d=o.component.name)==null?void 0:d.toLowerCase())===t}))==null?void 0:a.component)}async function Us({component:e,script:s,props:t,req:n}){if(!(s!=null&&s.includes("getServerSideProps")))return null;const a=await lt(s,"getServerSideProps");if(!a)return null;const o=new Promise(i=>{setTimeout(()=>{i({})},Re*1e3)});return await Promise.race([o,ie.Sandbox.callFunction({code:`${a}
|
|
33
|
-
|
|
34
|
-
export async function getServerSidePropsWrapper(props) {
|
|
35
|
-
const { location, fetch, props: componentProps } = props;
|
|
36
|
-
// 使用局部变量而不是全局变量
|
|
37
|
-
const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
|
|
38
|
-
const originalFetch = globalThis.fetch;
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
globalThis.location = location;
|
|
42
|
-
globalThis.fetch = fetch;
|
|
43
|
-
return await getServerSideProps(componentProps);
|
|
44
|
-
} finally {
|
|
45
|
-
// 清理全局状态
|
|
46
|
-
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
-
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
-
}
|
|
49
|
-
}`,filename:`${e.name||e.id}.js`,moduleLoader:i=>{if(i==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
-
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(i==="@blocklet/pages-kit/builtin/dayjs")return ie.BuiltinModules.dayjs},global:{console:{log:(...i)=>{O.info(...i)},warn:(...i)=>{O.warn(...i)},error:(...i)=>{O.error(...i)}},getComponentMountPoint:jt.getComponentMountPoint,joinURL:M.joinURL,withQuery:M.withQuery,getQuery:M.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:M.joinURL(M.withHttps(n.hostname),n.originalUrl)},fetch:(i,{...p}={})=>{const r=typeof i=="string"&&i.startsWith("/")?M.joinURL(I.default.env.appUrl,i):i;if(typeof r=="string"&&M.parseURL(r).host===M.parseURL(I.default.env.appUrl).host){const u=n.get("cookie");if(u){const g=new at.Headers(p.headers);g.set("cookie",u),p.headers=g}}return as.default(r,{...p,timeout:Re*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:t}]})])}const ht=ie.memoize(async(e,s,t)=>{if(!(e!=null&&e.includes(s)))return null;const n=await lt(e,s);if(n)try{return await ie.Sandbox.callFunction({code:`
|
|
52
|
-
${n}
|
|
53
|
-
|
|
54
|
-
export function get${s}SchemaWrapper() {
|
|
55
|
-
return ${s};
|
|
56
|
-
}
|
|
57
|
-
`,filename:`${t}.js`,functionName:`get${s}SchemaWrapper`})}catch(a){return O.error(`获取 ${s} 失败`,{componentId:t,error:a}),null}return null},{keyGenerator:(e,s,t)=>{const n=W.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Fs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Le="page",Me="trigger-reload-project-resource",Ge=Fs,qs="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function Ee(e){e.observeDeep(s=>{s.some(t=>t.changes.keys.has("updatedAt")||t.changes.keys.has("publishedAt"))||e.set("updatedAt",new Date().toISOString())})}function yt(){return S.mkdtempSync(w.join(I.default.env.dataDir,"tmp-"))}function Ie(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,a)=>Ie(n,s,[...t,a])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,a])=>Ie(a,s,[...t,n])):s(e)?[t]:[]}function U(e){return e.filter(s=>s!=null)}function $s(e){e.pages&&Object.keys(e.pages).forEach(t=>{const n=Q.getYjsValue(e.pages[t]);n&&n instanceof B.Map&&Ee(n)});const s=Q.getYjsValue(e.pages);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,a)=>{if(n.action==="add"){const o=Q.getYjsValue(e.pages[a]);o&&o instanceof B.Map&&Ee(o)}})})}function Bs(e){e.routes&&Object.keys(e.routes).forEach(t=>{var a;const n=Q.getYjsValue((a=e.routes)==null?void 0:a[t]);n&&n instanceof B.Map&&Ee(n)});const s=Q.getYjsValue(e.routes);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,a)=>{var o;if(n.action==="add"){const d=Q.getYjsValue((o=e.routes)==null?void 0:o[a]);d&&d instanceof B.Map&&Ee(d)}})})}function Hs(e,s){var t;for(const n of s||Object.keys(e.routes||{})){let a=n,o=[];if(n.includes("-")){const[d,...i]=n.split("-");a=d,o=i||[]}if(((t=e.routes)==null?void 0:t[a])!==void 0){e.routes[a].publishedAt=new Date().toISOString();const d=e.routes[a];if(!d||!d.params||d.params.length===0)continue;if(n.includes("-")&&o.length>0){const i=be.getRouteMetaDataByOptionIds(o,d);i&&(i.publishedAt=new Date().toISOString())}if(!s){const i=be.generateParamCombinations({basePath:d.path,params:d.params,routeId:d.id,paramsOptions:d.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const p of i)p.routeMetaData??(p.routeMetaData={}),p.routeMetaData.publishedAt=new Date().toISOString()}}}}function ve({page:e,route:s,state:t,routeId:n,routePathInfo:a}){var d,i,p,r,u,g,y,c,l;O.info(`Executing datasource data assembly, routeId: ${n}, routePathInfo: ${JSON.stringify(a)}`);const o={...$t.cloneDeep(e),id:n,slug:(a==null?void 0:a.path)??s.path,createdAt:s.createdAt,updatedAt:((d=a==null?void 0:a.routeMetaData)==null?void 0:d.updatedAt)??s.updatedAt,publishedAt:((i=a==null?void 0:a.routeMetaData)==null?void 0:i.publishedAt)??s.publishedAt,isPublic:(((p=a==null?void 0:a.routeMetaData)==null?void 0:p.isPublic)??s.isPublic)&&s.isPublic};for(const f of t.supportedLocales){if(s.dataSource){let E=s.id;a&&(E=a.paramOptionIds.join("-"));const v=((g=(u=(r=s.dataSource.pathDataMappings)==null?void 0:r[E])==null?void 0:u.dataCache)==null?void 0:g[f.locale])??((l=(c=(y=s.dataSource.pathDataMappings)==null?void 0:y[E])==null?void 0:c.dataCache)==null?void 0:l[t.config.defaultLocale||"en"]);if(!v)continue;qt.setPageDataSource(o,t,f.locale,v)}a&&a.routeMetaData&&(a.routeMetaData.publishedAt=new Date().toISOString())}return o}const{uploadToMediaKit:Gs}=require("@blocklet/uploader-server"),Se=Xt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,oe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,et=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Vs=1e4,Js=3e4,ge=0,xe=1,zs=0,Ks=1,Ue=I.default,ne=w.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Ys=["production","draft"],Ws=["production"];function Oe(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function Qs(){var t;const e=Ue.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const V=class V extends B.Doc{constructor(t){super();x(this,"states",{});x(this,"syncedStore");x(this,"conns",new Map);x(this,"awareness");x(this,"awarenessChangeHandler",({added:t,updated:n,removed:a},o)=>{const d=t.concat(n,a);if(o!==null){const r=this.conns.get(o);r&&(t.forEach(u=>{r.add(u)}),a.forEach(u=>{r.delete(u)}))}const i=k.createEncoder();k.writeVarUint(i,xe),k.writeVarUint8Array(i,se.encodeAwarenessUpdate(this.awareness,d));const p=k.toUint8Array(i);this.conns.forEach((r,u)=>this.send(u,p))});x(this,"updateHandler",t=>{const n=k.createEncoder();k.writeVarUint(n,ge),je.writeUpdate(n,t);const a=k.toUint8Array(n);this.conns.forEach((o,d)=>this.send(d,a))});x(this,"ensureDataStructure",()=>{var p;const{supportedLocales:t,pages:n,pageIds:a,config:o,routes:d,routeIds:i}=this.syncedStore;{const r=new Set(Object.keys(n));let u=0;for(;u<a.length;){const g=a[u];r.has(g)?(r.delete(g),u++):a.splice(u,1)}}{const r=new Set(Object.keys(d));let u=0;for(;u<i.length;){const g=i[u];r.has(g)?(r.delete(g),u++):i.splice(u,1)}}t.splice(0,t.length),t.push(...Ue.env.languages.map(r=>({locale:r.code,name:r.name}))),o.defaultLocale=(p=t[0])==null?void 0:p.locale;{let r=0;const u=new Set;for(;r<t.length;){const{locale:g}=t[r];u.has(g)?t.splice(r,1):(r++,u.add(g))}}});x(this,"send",(t,n)=>{t.readyState!==zs&&t.readyState!==Ks&&this.closeConn(t);try{t.send(n,a=>{a&&this.closeConn(t)})}catch{this.closeConn(t)}});x(this,"closeConn",t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&se.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()});x(this,"autoSave",it.default(()=>{S.mkdirSync(w.dirname(this.draftYjsFilePath),{recursive:!0}),S.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Vs));x(this,"save",({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()});x(this,"publish",async({mode:t,routes:n})=>{const a=await this.getState("draft"),o=await this.getState("production");await Fe(a,o,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:t}),o.config.publishedAt=new Date().getTime(),Hs(this.syncedStore,n),await this.setState(t,o)});x(this,"mergeState",async(t,n)=>{var i,p,r;const a=JSON.parse(JSON.stringify(n));(i=t.config).fontFamily??(i.fontFamily={});const o=(p=a.config)==null?void 0:p.fontFamily,d=(r=t.config)==null?void 0:r.fontFamily;t.config.fontFamily.title=(o==null?void 0:o.title)||(d==null?void 0:d.title),t.config.fontFamily.description=(o==null?void 0:o.description)||(d==null?void 0:d.description),await new Promise((u,g)=>{this.transact(async()=>{try{const y=await Fe(t,n);u(y)}catch(y){g(y)}})})});x(this,"addConnection",t=>{if(this.conns.has(t))return;t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",o=>this.messageListener(t,new Uint8Array(o)));let n=!0;const a=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(a);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(a)}}},Js);t.on("close",()=>{this.closeConn(t),clearInterval(a)}),t.on("pong",()=>{n=!0});{const o=k.createEncoder();k.writeVarUint(o,ge),je.writeSyncStep1(o,this),this.send(t,k.toUint8Array(o));const d=this.awareness.getStates();if(d.size>0){const i=k.createEncoder();k.writeVarUint(i,xe),k.writeVarUint8Array(i,se.encodeAwarenessUpdate(this.awareness,Array.from(d.keys()))),this.send(t,k.toUint8Array(i))}}});x(this,"messageListener",(t,n)=>{try{const a=k.createEncoder(),o=De.createDecoder(n),d=De.readVarUint(o);switch(d){case ge:k.writeVarUint(a,ge),je.readSyncMessage(o,a,this,null),k.length(a)>1&&(this.ensureDataStructure(),this.send(t,k.toUint8Array(a)));break;case xe:{se.applyAwarenessUpdate(this.awareness,De.readVarUint8Array(o),t);break}default:O.warn(`Unsupported messageType ${d}`)}}catch(a){O.error(a)}this.save()});this.options=t,S.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,S.readFileSync(this.draftYjsFilePath)),this.syncedStore=Bt.reactive(Q.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new se.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(t){if(!t)throw new Error("Should provide project context");try{const n=w.join(ne,t),a=w.join(ne,`@del-${t}`);S.renameSync(n,a)}catch(n){O.error("Failed to safe delete project state dir:",n)}}static get projectIds(){return ke.globSync("*/",{cwd:ne,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(t=>V.shared(t))}static shared(t){if(!t)throw new Error("Should provide project context");let n=this.sharedInstances.get(t);return n||(n=new V({path:w.join(ne,t)}),this.sharedInstances.set(t,n),n)}destroy(){this.conns.forEach((t,n)=>this.closeConn(n)),this.awareness.destroy(),super.destroy()}initObserver(){$s(this.syncedStore),Bs(this.syncedStore)}get draftYjsFilePath(){return w.join(this.options.path,"draft.yjs")}async getState(t){var n,a,o,d;if(t==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[t]&&(this.states[t]=await Je(this.getPublishDir(t),{includeResources:!0})??Qs(),!((a=(n=this.states[t])==null?void 0:n.config)!=null&&a.defaultLocale))){(o=this.states[t]).config??(o.config={});const i=Ue.env.languages.map(p=>({locale:p.code,name:p.name}));this.states[t].config.defaultLocale=(d=i[0])==null?void 0:d.locale}return{...this.states[t],resources:await Ce().then(async i=>{var c,l,f,E;const{pages:p,components:r}=fs.default(i,"pages","components");let u=r;const g=w.basename(this.options.path),y=await J.findByPk(g);if(y!=null&&y.useAllResources)u=r;else{const T=(await Te.findAll({where:{projectId:g}})).map(F=>F.componentId);u=Object.fromEntries(Object.entries(r||{}).filter(([F])=>T.includes(F)))}return Object.keys(((l=(c=this.states[t])==null?void 0:c.resources)==null?void 0:l.components)||{}).length>0&&(u={...u,...(E=(f=this.states[t])==null?void 0:f.resources)==null?void 0:E.components}),{pages:p,components:u}}).catch(()=>({}))}}async setState(t,n){const a=await Et(n,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(t);S.mkdirSync(w.dirname(o),{recursive:!0}),S.rmSync(o,{force:!0,recursive:!0}),S.renameSync(a,o),this.states[t]=n}getPublishDir(t){return w.join(this.options.path,t)}static async pageUrlMap(t){var o,d;const{projectIds:n}=this,a={};for(const i of n){const p=await J.findByPk(i);if(!p)continue;const r=await V.shared(i).getState(t),u=p.slug||i,g=ms.default(I.default.env.languages.map(c=>c.code),r.supportedLocales.map(c=>c.locale)),y=(c,l)=>{u&&(a[M.joinURL("/",u,c)]={...l,shouldRedirect:!0,mainPage:!0}),a[M.joinURL("/",i,c)]={...l,shouldRedirect:!0,mainPage:!0};for(const f of g){const E={...l,locale:f};a[M.joinURL("/",f,i,c)]=E,u&&(a[M.joinURL("/",f,u,c)]=E)}};if(t==="draft")for(const c of r.routeIds||[]){const l=(o=r==null?void 0:r.routes)==null?void 0:o[c];if(!l)continue;if(l.params&&l.params.length>0){const v=be.generateParamCombinations({basePath:l.path,params:l.params,routeId:l.id,paramsOptions:l.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const T of v){const R=T.path,F={projectId:i,projectSlug:u,pageSlug:R,pageId:l.displayTemplateId||"",routeId:c,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:r.config.publishedAt,isPublic:l.isPublic&&((d=T==null?void 0:T.routeMetaData)==null?void 0:d.isPublic)};y(R,F)}}const f=l.path,E={projectId:i,projectSlug:u,pageSlug:f,pageId:l.displayTemplateId||"",routeId:c,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:r.config.publishedAt,isPublic:l.isPublic};y(f,E)}for(const c of r.pageIds){const l=r.pages[c];if(!l||t==="production"&&!l.isPublic)continue;const f=l.slug,E=p.slug||i,v={projectId:i,projectSlug:E,pageSlug:f,pageId:c,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:r.config.publishedAt,isPublic:l.isPublic,templateConfig:l.templateConfig};y(f,v)}}return a}getDocumentSize(){return B.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const t=[];for(const[n,a]of this.sharedInstances.entries()){const o=a.getDocumentSize();t.push({projectId:n,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:a.conns.size})}return t}};x(V,"INSTANCE_TTL",30*60*1e3),x(V,"sharedInstances",new qe.LRUCache({max:100,ttl:V.INSTANCE_TTL,dispose:t=>{t.destroy()}}));let le=V;async function Xs(e,s,t){if(!e||!S.existsSync(e)||!S.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>{var a;try{const o=(a=await Gs({filePath:e,fileName:s}))==null?void 0:a.data;return o==null?void 0:o.filename}catch(o){return O.error(`Failed to upload asset ${e}:`,o),null}})(),t[e]=n),n}const St=async(e,s)=>{const t=w.basename(e),n=await $e.call({name:Ge,path:M.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const a=S.createWriteStream(s);await es.pipeline(n.data,a)}else throw new Error(`download asset failed ${n.status}`)},wt=async(e,s)=>{await Promise.all(e.map(async t=>{try{await St(t,w.join(s,w.basename(t)))}catch(n){O.error(`Failed to export assets: ${t}, ${n}`)}}))};function bt(e){return Ve.test(e)?[e]:oe.test(e)?(et.lastIndex=0,Array.from(e.matchAll(et)).map(t=>t[1]).filter(t=>!!t)):[]}async function he(e,s,t){const{getFilename:n,exportAssets:a}=t,o=w.join(s,n(e));if(S.mkdirSync(w.dirname(o),{recursive:!0}),S.writeFileSync(o,X.stringify(e)),a){const i=Ie(e,p=>typeof p=="string"&&(Ve.test(p)||oe.test(p))).map(p=>{const r=Be.default(e,p);return bt(r)}).flat().filter(Boolean);await wt(i,w.dirname(o))}}const tt=new qe.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function st(e,s,t){var i;const n=Ie(e,p=>typeof p=="string"&&(Ve.test(p)||oe.test(p))),a=gs.default(2),o=n.map(p=>a(async()=>{try{const r=Be.default(e,p),u=bt(r);for(const g of u){const y=w.basename(g),c=t.getFilePath(g,p),l=c?`${c}:${y}`:y,f=tt.get(l);if(f){oe.test(r)||Qe.default(e,p,f);return}const E=await Xs(c,y,s);E&&(oe.test(r)||Qe.default(e,p,E),tt.set(l,E))}}catch(r){O.error(`Failed to process upload for path ${p.join(".")}:`,r.message||r.reason)}})),d=await Promise.allSettled(o);(i=t.onFinish)==null||i.call(t,d)}async function Et(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:a,includeResources:o=!1,routeIds:d="all"}={}){var ee,b,m,A,P,z,_,q,K,fe,te,me;const i=t==="all"?e.pageIds:t,p=re.getComponentDependencies({state:e,pageIds:i,componentIds:n==="all"?Object.keys(e.components):n}),r=d==="all"?e.routeIds:d,u=(h,C)=>{var D;return{id:h.id,name:h.name,isTemplateSection:h.isTemplateSection??!1,templateDescription:h.templateDescription,llmConfig:h.llmConfig,component:h.component,config:h.config,visibility:h.visibility,properties:((D=h.locales)==null?void 0:D[C])??{}}},g=(h,C)=>{var D;return{id:h.id,createdAt:h.createdAt,updatedAt:h.updatedAt,publishedAt:h.publishedAt,isPublic:h.isPublic??!0,templateConfig:h.templateConfig,meta:((D=h.locales)==null?void 0:D[C])??{},sections:U(h.sectionIds.map(G=>{const H=h.sections[G];return H&&u(H,C)}))}},y=h=>({id:h.id,createdAt:h.createdAt,updatedAt:h.updatedAt,publishedAt:h.publishedAt,path:h.path,handler:h.handler,isPublic:h.isPublic??!0,params:h.params??[],enabledGenerate:h.enabledGenerate??!1,displayTemplateId:h.displayTemplateId,dataSource:h.dataSource}),c=U(r.map(h=>{const C=e.routes[h];return C&&y(C)})),l=U(e.supportedLocales.map(h=>h.locale).flatMap(h=>i.map(C=>{const D=e.pages[C];return D&&{locale:h,slug:D.slug,page:g(D,h)}}))),f=yt(),E=w.join(f,"pages");S.mkdirSync(E,{recursive:!0});const v=w.join(f,"components");S.mkdirSync(v,{recursive:!0});const T=w.join(f,"routes");S.mkdirSync(T,{recursive:!0});for(const{locale:h,slug:C,page:D}of l)await he(D,E,{getFilename:()=>`${Oe(C)||"index"}.${h}.yml`,exportAssets:s});for(const h of c)await he(h,T,{getFilename:()=>`${Oe(h.path)||"index"}.yml`,exportAssets:s});for(const h of p){const C=(ee=e.components[h])==null?void 0:ee.data;C&&await he(C,v,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:s})}const R=w.join(f,".blocklet/pages/pages.config.yml");S.mkdirSync(w.dirname(R),{recursive:!0});const F={pages:U(i.map(h=>{const C=e.pages[h];return C&&{id:h,slug:C.slug}})),routes:U(r.map(h=>{const C=e.routes[h];return C&&{id:h,path:C.path}})),components:U(p.map(h=>{var D;const C=(D=e.components[h])==null?void 0:D.data;return C&&{id:h,name:C.name}})),...o?{resources:{components:U(Object.keys(((b=e.resources)==null?void 0:b.components)||{}).filter(h=>p.includes(h)).map(h=>{var C,D,G,H;return{id:h,name:(H=(G=(D=(C=e.resources)==null?void 0:C.components)==null?void 0:D[h])==null?void 0:G.component)==null?void 0:H.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};S.writeFileSync(R,X.stringify(F));const pe=w.join(f,"config.source.json");if(a&&S.writeFileSync(pe,JSON.stringify(a)),o){const h=w.join(f,"resources"),C=w.join(h,"components");S.mkdirSync(C,{recursive:!0});for(const H of Object.keys(((m=e==null?void 0:e.resources)==null?void 0:m.components)??{}).filter($=>p.includes($))){const $=(z=(P=(A=e.resources)==null?void 0:A.components)==null?void 0:P[H])==null?void 0:z.component;$&&await he($,C,{getFilename:Y=>`${Y.name||"unnamed"}.${Y.id}.yml`,exportAssets:s})}const D=w.join(f,"chunks");S.mkdirSync(D,{recursive:!0});const{chunks:G}=await Ce();for(const H of Object.keys(((_=e==null?void 0:e.resources)==null?void 0:_.components)??{}).filter($=>p.includes($))){const $=(fe=(K=(q=e.resources)==null?void 0:q.components)==null?void 0:K[H])==null?void 0:fe.component;if($&&((te=$.renderer)==null?void 0:te.type)==="react-component"){const Y=((me=$.renderer)==null?void 0:me.chunks)??[];if((Y==null?void 0:Y.length)>0)for(const Pe of Y){const We=w.join(D,Pe),_e=G==null?void 0:G[Pe];try{_e&&S.existsSync(_e)&&!S.existsSync(We)&&S.copyFileSync(_e,We)}catch(Ct){O.error(`copy chunk ${Pe} error`,Ct.message)}}}}}return f}async function Je(e,{importAssets:s,includeResources:t}={}){var o,d,i,p;if(!S.existsSync(e))return null;let n,a=!1;try{S.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(a=!0,n=yt(),await ts.x({file:e,C:n}));const r=ke.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),u=r&&w.join(w.dirname(r),"../../pages"),g=r&&w.join(w.dirname(r),"../../components"),y=r&&w.join(w.dirname(r),"../../chunks"),c=r&&w.join(w.dirname(r),"../../routes");if(!r)return null;const l=X.parse(S.readFileSync(r).toString()),f=(b,m,A)=>{let P=w.join(b,`${m}${A?`.${A}`:""}.yml`);return(!S.existsSync(P)||!S.lstatSync(P).isFile())&&(P=w.join(b,m,`index${A?`.${A}`:""}.yml`),!S.existsSync(P)||!S.lstatSync(P))?null:X.parse(S.readFileSync(P).toString())},E=(b,m)=>{try{const A=ke.globSync(`*.${m}.yml`,{cwd:b,absolute:!0})[0];return A?X.parse(S.readFileSync(A).toString()):null}catch(A){O.error("parse component error",A)}return null},v=(b,m)=>{let A=w.join(b,`${m}.yml`);return(!S.existsSync(A)||!S.lstatSync(A).isFile())&&(A=w.join(b,m,"index.yml"),!S.existsSync(A)||!S.lstatSync(A))?null:X.parse(S.readFileSync(A).toString())},T=U(l.pages.map(({slug:b})=>{var z;const m=U(l.supportedLocales.map(({locale:_})=>{const q=u?f(u,Oe(b),_):void 0;if(q)return{locale:_,page:q};const K=u?f(u,b,_):void 0;return K&&{locale:_,page:K}})),A=(z=m[0])==null?void 0:z.page;if(!A)return null;const P=A.sections.map(_=>{const q=_.id||Se();return{id:q,component:_.component,config:_.config,name:_.name,isTemplateSection:_.isTemplateSection??!1,templateDescription:_.templateDescription,llmConfig:_.llmConfig,visibility:_.visibility,locales:Object.fromEntries(U(m.map(({locale:K,page:fe})=>{const te=fe.sections.find(me=>me.id===q);return te&&[K,te.properties]})))}});return{id:A.id||Se(),createdAt:A.createdAt,updatedAt:A.updatedAt,publishedAt:A.publishedAt,isPublic:A.isPublic??!0,templateConfig:A.templateConfig,slug:b,sections:Object.fromEntries(P.map(_=>[_.id,_])),sectionIds:P.map(_=>_.id),locales:Object.fromEntries(m.map(({locale:_,page:q})=>[_,q.meta]))}})),R=U(((o=l==null?void 0:l.routes)==null?void 0:o.map(({path:b})=>{const m=c?v(c,Oe(b)):void 0;return{...m,id:(m==null?void 0:m.id)||Se(),createdAt:(m==null?void 0:m.createdAt)??new Date().toISOString(),updatedAt:(m==null?void 0:m.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(m==null?void 0:m.path)??`/${m==null?void 0:m.id}`,params:m==null?void 0:m.params,handler:(m==null?void 0:m.handler)??"Pages Kit",isPublic:(m==null?void 0:m.isPublic)??!0,enabledGenerate:(m==null?void 0:m.enabledGenerate)??!1,displayTemplateId:(m==null?void 0:m.displayTemplateId)??void 0,dataSource:(m==null?void 0:m.dataSource)??{}}}))??[]),F=g?U(((d=l.components)==null?void 0:d.map(({id:b})=>E(g,b)))??[]):[];if(s){const b=(...m)=>{O.info(`[${a?w.basename(e):w.basename(w.join(e,"../../../../"))}] importAssets:`,...m)};try{b("wait image-bin api ready"),await hs.default({resources:[`${$e.getComponentWebEndpoint(ys)}/api/sdk/uploads`],validateStatus:P=>P>=200&&P<=500}),b("image-bin api is ready");const m={},A={};b("start to upload assets"),await Promise.allSettled([st(F,m,{getFilePath:P=>g&&w.join(g,P),onFinish:P=>{b(`upload ${P.length} component assets`)}}),st(T,A,{getFilePath:(P,z)=>{const _=Be.default(T,z.slice(0,1));return u&&w.join(u,w.dirname(_.slug),P)},onFinish:P=>{b(`upload ${P.length} page assets`)}})]),b("upload assets done"),global.gc&&global.gc()}catch(m){b("Error during asset import:",m)}}const pe={};if(t){const b=r&&w.join(w.dirname(r),"../../resources/components"),m=U(((p=(i=l.resources)==null?void 0:i.components)==null?void 0:p.map(({id:A})=>E(b,A)))??[]);m.length>0&&(pe.components=Object.fromEntries(m.map((A,P)=>[A.id,{index:P,component:A}])))}const ee={};if(y&&S.existsSync(y)){const b=S.readdirSync(y);for(const m of b)ee[m]=w.join(y,m)}return{supportedLocales:l.supportedLocales,pageIds:T.map(b=>b.id),components:Object.fromEntries(F.map((b,m)=>[b.id,{index:m,data:b}])),pages:Object.fromEntries(T.map(b=>[b.id,b])),config:l.config||{},resources:pe,chunks:ee,routeIds:R.map(b=>b.id),routes:Object.fromEntries(R.map(b=>[b.id,b])),dataSourceIds:[],dataSources:{}}}finally{a&&n&&S.rmSync(n,{force:!0,recursive:!0})}}async function Fe(e,s,{routes:t,mergeMode:n="byUpdateTime",deleteRoutes:a=!1,publishMode:o=void 0}={}){try{o&&pt(o)}catch(y){O.error("clear preload page cache error",{error:y})}const{pages:d,pageIds:i,routeIds:p,routes:r,supportedLocales:u}=e;if(o==="production"){let y=t??[],c=null;for(const l of p??[]){const f=r==null?void 0:r[l];if(f!=null&&f.params&&(f==null?void 0:f.params.length)>0&&(f!=null&&f.paramsOptions)&&(f==null?void 0:f.paramsOptions.length)>0){const E=be.generateParamCombinations({basePath:f.path,params:f.params,routeId:f.id,paramsOptions:f.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),v=Object.fromEntries(E.map(T=>[`${l}-${T.paramOptionIds.join("-")}`,T]));c={...c||{},...v},t||(y=[...y,...E.map(T=>`${l}-${T.paramOptionIds.join("-")}`)])}else t||y.push(l)}O.info("routeIds to be published: ",y);for(const l of y){let f=l;if(f.includes("-")){const[T]=f.split("-");f=T}const E=r==null?void 0:r[f];if(!E){const T=s.pageIds.indexOf(f);T!==-1&&a&&(s.pageIds.splice(T,1),delete s.pages[f]);for(const R of s.pageIds)R.includes(`${f}-`)&&(s.pageIds.splice(s.pageIds.indexOf(R),1),delete s.pages[R]);O.info("delete main route page",f);continue}if(l.includes("-")&&!(c!=null&&c[l])){const T=s.pageIds.indexOf(l);T!==-1&&a&&(s.pageIds.splice(T,1),delete s.pages[l]),O.info("delete page",l);continue}if(!E.displayTemplateId){O.info("no display template",l);continue}const v=d[E.displayTemplateId];if(!v){O.info("no template page",l);continue}if(s.pageIds.includes(l)){if(O.info("has need update page",l),n==="replace")s.pages[l]=ve({page:v,route:E,state:e,routeId:l,routePathInfo:c==null?void 0:c[l]}),O.info("replace page",l);else if(n==="byUpdateTime"){const T=s.pages[E.id];(!T||E.updatedAt&&E.updatedAt>T.updatedAt)&&(s.pages[l]=ve({page:v,route:E,state:e,routeId:l,routePathInfo:c==null?void 0:c[l]}),O.info("replace page by update time",l))}}else s.pageIds.push(l),s.pages[l]=ve({page:v,route:E,state:e,routeId:l,routePathInfo:c==null?void 0:c[l]}),O.info("add page",l)}if(a&&!t)for(const l of s.pageIds)y!=null&&y.includes(l)||(delete s.pages[l],O.info("delete page",l)),s.pageIds=[...s.pageIds].filter(f=>y==null?void 0:y.includes(f))}else{for(const y of i){const c=d[y];if(c)if(s.pageIds.includes(c.id)){if(n==="replace")s.pages[c.id]=c;else if(n==="byUpdateTime"){const l=s.pages[c.id];(!l||c.updatedAt&&c.updatedAt>l.updatedAt)&&(s.pages[c.id]=c)}}else s.pageIds.push(c.id),s.pages[c.id]=c}for(const y of p){const c=r[y];if(c)if(s.routeIds.includes(c.id)){if(n==="replace")s.routes[c.id]=c;else if(n==="byUpdateTime"){const l=s.routes[c.id];(!l||c.updatedAt&&c.updatedAt>l.updatedAt)&&(s.routes[c.id]=c)}}else s.routeIds.push(c.id),s.routes[c.id]=c}}if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...us.default(u)),a)for(const y of Object.keys(s.components))delete s.components[y];let g=JSON.parse(JSON.stringify(e.components));g=Object.fromEntries(await Promise.all(Object.entries(g).map(async([y,c])=>{const l=await It(c==null?void 0:c.data);return[y,{...c,data:l}]}))),Object.assign(s.components,g),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const It=He(async e=>{var s;if(!ps.default(e==null?void 0:e.properties))return e;if(((s=e==null?void 0:e.renderer)==null?void 0:s.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t&&t.includes("PROPERTIES_SCHEMA"))try{const n=await ht(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((a,o)=>{e!=null&&e.properties&&(e.properties[a.id]={index:o,data:a})}))}catch(n){O.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var r,u,g,y;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((r=e==null?void 0:e.renderer)==null?void 0:r.type)||"",a=(e==null?void 0:e.properties)||{},o=(e==null?void 0:e.updatedAt)||"",d=W.createHash("md5").update(JSON.stringify(a)).digest("hex");let i="",p="";return((u=e==null?void 0:e.renderer)==null?void 0:u.type)==="react-component"&&(i=W.createHash("md5").update(((g=e==null?void 0:e.renderer)==null?void 0:g.script)||"").digest("hex"),p=W.createHash("md5").update(((y=e==null?void 0:e.renderer)==null?void 0:y.editComponent)||"").digest("hex")),JSON.stringify(["checkPropertiesFromCode",s,t,n,d,o,i,p])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"checkPropertiesFromCode"});let Ae,Z,ze,Ke,Ye;function Ot(){return Ae=(async()=>{const e=$e.getResources({types:[{did:Ge,type:Le},{did:qs,type:Le}]});Z=(await Promise.all(e.map(async t=>{const n=t.path?await Je(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),ze=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(a=>a?[a==null?void 0:a.id,{page:a,blockletId:n.blockletId}]:[]))),{});const s=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(a=>[a.data.id,{blockletId:n.blockletId,component:a.data}]))),{});Ke=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const a=await It(n.component);return[t,{...n,component:a}]}))),Ye=Z.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),Ae}function At(e){const s=it.default(async()=>{await Ot().catch(t=>{O.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:Z,pages:ze,components:Ke,chunks:Ye}))},3e3,{leading:!1,trailing:!0});return s(),I.default.events.on(I.default.Events.componentAdded,s),I.default.events.on(I.default.Events.componentRemoved,s),I.default.events.on(I.default.Events.componentStarted,s),I.default.events.on(I.default.Events.componentStopped,s),I.default.events.on(I.default.Events.componentUpdated,s),I.default.events.on(Me,s),()=>{I.default.events.off(I.default.Events.componentAdded,s),I.default.events.off(I.default.Events.componentRemoved,s),I.default.events.off(I.default.Events.componentStarted,s),I.default.events.off(I.default.Events.componentStopped,s),I.default.events.off(I.default.Events.componentUpdated,s),I.default.events.off(Me,s)}}const Tt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),we=globalThis;var nt;(nt=we[Tt])==null||nt.call(we);we[Tt]=At(async({pages:e,components:s})=>{const{projectIds:t}=le;O.info(`start update resource states projects(${t.length})`,t),await Promise.race([new Promise(n=>{setTimeout(()=>{n({})},30*1e3)}),Promise.all(t.map(async n=>{const a=le.shared(n);a.syncedStore.resources.pages=e;const o=await J.findByPk(n);if(o!=null&&o.useAllResources)a.syncedStore.resources.components=s;else{const i=(await Te.findAll({where:{projectId:n}})).map(r=>r.componentId),p=Object.fromEntries(Object.entries(s||{}).filter(([r])=>i.includes(r)));a.syncedStore.resources.components=p}O.info(`update [${n}] resource states:`,{pages:Object.keys(a.syncedStore.resources.pages||{}).length,components:Object.keys(a.syncedStore.resources.components||{}).length})}))]).catch(n=>{O.error("update resource states failed:",n)})});async function Zs(){O.info("trigger reload all project resource"),I.default.events.emit(Me)}async function Ce({ensureLoaded:e=!0}={}){return e&&(Ae??(Ae=Ot()),await Ae),{states:Z,pages:ze,components:Ke,chunks:Ye}}exports.COMPONENT_DID=Ge;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=dt;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Re;exports.PUBLISH_MODES=Ws;exports.Project=J;exports.RESOURCE_TYPE=Le;exports.SITE_STATE_PATH=ne;exports.STATE_MODES=Ys;exports.SiteState=le;exports.clearPreloadComponentsCache=ut;exports.clearPreloadComponentsCacheByMode=pt;exports.downloadAsset=St;exports.downloadAssets=wt;exports.fromPackage=Je;exports.getComponentFromState=ce;exports.getComponentFromStateByName=Ms;exports.getExportSchemaValueFromCode=ht;exports.getMultiTenantAllProjectAccessPassports=bs;exports.getPreloadComponent=mt;exports.getPreloadComponents=Ns;exports.getPreloadComponentsCacheKey=ft;exports.getResourceStates=Ce;exports.initPackResourceStates=At;exports.isMultiTenant=ws;exports.logger=O;exports.mergeState=Fe;exports.nextId=Se;exports.toPackage=Et;exports.triggerReloadAllProjectResource=Zs;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const E=require("react/jsx-runtime"),$=require("@mui/material"),b=require("ufo"),Z=require("@blocklet/js-sdk"),H=require("lodash/isEmpty"),ee=require("yaml"),te=require("@arcblock/ux/lib/Locale/context"),N=require("@syncedstore/core"),ne=require("@syncedstore/react"),oe=require("ahooks"),C=require("immer"),re=require("lodash/debounce"),se=require("nanoid"),u=require("react"),V=require("react-router-dom"),ce=require("y-indexeddb"),ie=require("y-websocket"),ae=require("yjs");require("@blocklet/pages-kit/types");const _=t=>t&&t.__esModule?t:{default:t};function de(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const i in t)if(i!=="default"){const S=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,S.get?S:{enumerable:!0,get:()=>t[i]})}}return n.default=t,Object.freeze(n)}const ue=_(H),le=de(ee),fe=_(N),W=_(re),me=t=>{const n=blocklet==null?void 0:blocklet.componentMountPoints.find(i=>i.name===t);return n?n.mountPoint:"/"};function J(){const{pathname:t}=window.location,n=t.match(/\/admin\/(maker|previewer)\/([^/]+)/),i=n==null?void 0:n[2],S=window.__PROJECT_ID__;if(!i&&!S)throw new Error("Unable to get projectId from pathname");return i||S}function Se(t){return`${t}:pages:version`}function we(t,n){return n==="yaml"?ue.default(t)?"":le.stringify(t,{indent:2}):n==="json"?JSON.parse(JSON.stringify(t||{})):n==="array"?JSON.parse(JSON.stringify(t||[])):t}function pe({error:t}){return E.jsx($.Box,{children:E.jsx($.Alert,{severity:"error",children:t.message})})}var G;const A=((G=window.blocklet)==null?void 0:G.prefix)||"/",L=Z.createAxios({timeout:200*1e3}),Pe=window.location.protocol==="https:"?"wss":"ws",Ie=t=>b.joinURL(`${Pe}://${window.location.hostname}`,A,`api/${t}/ws/pages`),ge="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var F;(F=blocklet==null?void 0:blocklet.componentMountPoints.find(t=>t.did===ge))!=null&&F.mountPoint||b.joinURL(A,"/image-bin");function je(t){return t&&!/^(https?:\/\/|\/)/.test(t)?window.location.origin+b.joinURL(A,"uploads",t):t}const ye=window.innerWidth<=750;function Ce(t,n,i){if(!t||/\.gif/.test(t))return t;const S=(ye?n/1.5:n)*(i==="quality"?1.5:1);return be(t,{imageFilter:"resize",w:S,f:"webp"})}function be(t,n){return!t||!n?t:b.withQuery(t,n)}async function he(t){return L.get(`/api/projects/${t}`).then(n=>n.data)}async function ve(t){return L.post(`/api/projects/${t.id}/update`,t).then(n=>n.data)}const xe=500,x=se.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),z=u.createContext(null);function Oe({url:t,name:n,children:i,waitingSynced:S}){const[g,P]=u.useState(!1),{locale:j}=te.useLocaleContext(),w=R(),e=`${w}:MakerLocalState`,o=`${w}:${n}`,[s,r]=oe.useLocalStorageState(e,{defaultValue:{},listenStorageChange:!0}),c=u.useRef(s);c.current=s;const a=u.useMemo(()=>fe.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),d=u.useMemo(()=>N.getYjsDoc(a),[a]);u.useMemo(()=>new ce.IndexeddbPersistence(o,d),[o,d]);const p=u.useMemo(()=>new ie.WebsocketProvider(t,o,d,{params:{},resyncInterval:5*60*1e3}),[t,o,d]),h=u.useCallback(()=>{p&&(p.disconnect(),p.connect())},[p]),y=u.useMemo(()=>new ae.UndoManager([d.getArray("pageIds"),d.getMap("pages"),d.getArray("supportedLocales"),d.getMap("config"),d.getMap("dataSources"),d.getArray("dataSourceIds"),d.getArray("routeIds"),d.getMap("routes")],{doc:d}),[d]),[v,O]=u.useState(null),[M,k]=u.useState(!1),[q,D]=u.useState(void 0),U=u.useCallback(async()=>{if(w){k(!0);try{const l=await he(w);O(l)}catch(l){console.error("Failed to fetch project:",l)}finally{k(!1)}}},[w]),T=u.useCallback(async(l,f)=>{var I;if(D(void 0),!!w){f!=null&&f.optimisticUpdate&&v&&O(m=>({...m,...l}));try{const m=await ve({...l});O(m)}catch(m){console.error("Failed to update project:",m),f!=null&&f.optimisticUpdate&&O(v),D((I=m==null?void 0:m.response)==null?void 0:I.data)}}},[w,v]);u.useEffect(()=>{w&&U()},[w,U]);const Y=u.useMemo(()=>({doc:d,state:a,localState:{...s,currentLocale:j},setLocalState:l=>r(typeof l=="function"?f=>l(f??{}):l),undoManager:y,projectState:{project:v,isLoadingProject:M,error:q},updateProject:T,forceSync:h}),[d,a,JSON.stringify(s),r,y,v,M,T,q,j,h]);return u.useEffect(()=>{y.on("stack-item-added",({stackItem:l})=>{const{currentPageId:f,currentLocale:I,pages:m}=c.current;l.meta.set("localState",{currentPageId:f,currentLocale:I,pages:m})}),y.on("stack-item-popped",({stackItem:l})=>{const f=l.meta.get("localState");f&&r(I=>({...I,...f}))})},[y,r]),u.useEffect(()=>{p.awareness.setLocalState(s)},[p,s]),u.useEffect(()=>{p.once("synced",()=>P(!0));const l=()=>{r(m=>({...m,networkStatus:void 0}))},f=()=>{r(m=>({...m,networkStatus:"offline"}))},I=W.default(({status:m})=>{m==="connected"?l():m==="disconnected"&&f()},xe);return p.on("status",I),window.addEventListener("online",l),window.addEventListener("offline",f),()=>{p.off("status",I),window.removeEventListener("online",l),window.removeEventListener("offline",f)}},[p,r]),S&&!g?null:E.jsx(z.Provider,{value:Y,children:i})}const B=()=>{const t=u.useContext(z);if(!t)throw new Error("Context is null");const n=ne.useSyncedStore(t.state),{setLocalState:i,localState:S}=t,g=V.useNavigate(),P=R(),j=u.useMemo(()=>({setCurrentSectionId:(e,o)=>{var s,r;e===S.currentPageId&&o===((r=(s=S.pages)==null?void 0:s[e])==null?void 0:r.currentSectionId)||(g(b.joinURL("/admin/maker",P??"","pages",e)),i(c=>C.produce(c,a=>{var d;a.currentPageId=e,a.currentComponentId=void 0,a.customComponentPreviewerProperties={},o!==void 0&&(a.pages??(a.pages={}),(d=a.pages)[e]??(d[e]={}),a.pages[e].currentSectionId=o??void 0),o?window.sessionStorage.setItem("iframe_show_id",`"${o}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{e!==S.currentComponentId&&(g(b.joinURL("/admin/maker",P??"","components",e)),i(o=>C.produce(o,s=>{s.currentComponentId=e,s.customComponentPreviewerProperties={}})))},setCurrentRouteId:({routeId:e,dynamicParams:o})=>{i(s=>C.produce(s,r=>{r.currentRouteId=e,r.currentDynamicParams=o}))},setCustomComponentPreviewerProperties:(()=>{const e={},o=W.default(()=>{i(s=>C.produce(s,r=>{r.customComponentPreviewerProperties={...r==null?void 0:r.customComponentPreviewerProperties,...e},Object.keys(e).forEach(c=>delete e[c])}))},5);return s=>{Object.assign(e,s),o()}})(),setRouteGenerateProcess:e=>{i(o=>C.produce(o,s=>{e?s.routeGenerateProcess={...s.routeGenerateProcess,...e}:s.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{i(e=>C.produce(e,o=>{o.routeGenerateProcess={progress:"complete"}}))}}),[i,g,P]),w=u.useMemo(()=>({addPage:(e,o)=>{var c,a,d,p,h,y;const s=(e==null?void 0:e.id)??x(),r={...e,id:s,createdAt:(e==null?void 0:e.createdAt)??new Date().toISOString(),updatedAt:(e==null?void 0:e.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:(e==null?void 0:e.slug)??`/${s}`,sections:(e==null?void 0:e.sections)??{},sectionIds:(e==null?void 0:e.sectionIds)??[],isPublic:(e==null?void 0:e.isPublic)??!0,templateConfig:(e==null?void 0:e.templateConfig)??{isTemplate:((c=e==null?void 0:e.templateConfig)==null?void 0:c.isTemplate)??!0,displayTemplateId:((a=e==null?void 0:e.templateConfig)==null?void 0:a.displayTemplateId)??void 0,dataSourceIds:((d=e==null?void 0:e.templateConfig)==null?void 0:d.dataSourceIds)??void 0,dataSourceParameters:((p=e==null?void 0:e.templateConfig)==null?void 0:p.dataSourceParameters)??{},enabledGenerate:((h=e==null?void 0:e.templateConfig)==null?void 0:h.enabledGenerate)??!1,agentId:((y=e==null?void 0:e.templateConfig)==null?void 0:y.agentId)??void 0}};return t.doc.transact(()=>{n.pages[r.id]=r,n.pageIds.splice(o??n.pageIds.length,0,r.id)}),r},addRoute:(e,o)=>{const s=(e==null?void 0:e.id)??x(),r={...e,id:s,createdAt:(e==null?void 0:e.createdAt)??new Date().toISOString(),updatedAt:(e==null?void 0:e.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(e==null?void 0:e.path)??`/${s}`,handler:(e==null?void 0:e.handler)??"Pages Kit",isPublic:(e==null?void 0:e.isPublic)??!0,params:(e==null?void 0:e.params)??[],enabledGenerate:(e==null?void 0:e.enabledGenerate)??!1,displayTemplateId:(e==null?void 0:e.displayTemplateId)??void 0,dataSource:(e==null?void 0:e.dataSource)??{}};return t.doc.transact(()=>{n.routes??(n.routes={}),n.routeIds??(n.routeIds=[]),n.routes[r.id]=r,n.routeIds.splice(o??n.routeIds.length,0,r.id)}),r},deleteRoute:e=>{var s;if(!e)return;const o=(s=n.routeIds)==null?void 0:s.indexOf(e);o!==void 0&&o!==-1&&t.doc.transact(()=>{var r,c;(r=n.routeIds)==null||r.splice(o,1),(c=n.routes)==null||delete c[e]})},deletePage:e=>{const o=n.pageIds.indexOf(e);o!==-1&&t.doc.transact(()=>{n.pageIds.splice(o,1),delete n.pages[e]})},movePage:(e,o)=>{const{pageIds:s}=n,r=s.indexOf(e);r>=0&&s.splice(o,0,...s.splice(r,1))},addSection:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const c={...o,id:o.id??x(),isTemplateSection:o.isTemplateSection??!0,llmConfig:o.llmConfig??{}};return t.doc.transact(()=>{r.sections[c.id]=c,r.sectionIds.splice(s??r.sectionIds.length,0,c.id)}),c},deleteSection:(e,o)=>{const s=n.pages[e];if(!s)throw new Error(`Page ${e} is not exists`);const r=s.sectionIds.indexOf(o);r!==-1&&t.doc.transact(()=>{s.sectionIds.splice(r,1),delete s.sections[o]})},toggleSectionVisibility:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const c=r.sections[o];c&&(c.visibility=s)},moveSection:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const{sectionIds:c}=r,a=c.indexOf(o);a>=0&&c.splice(s,0,...c.splice(a,1))},addDataSource:e=>{const o=e.id??x(),s={...e??{},id:o,createdAt:new Date().toISOString()};return t.doc.transact(()=>{n.dataSourceIds??(n.dataSourceIds=[]),n.dataSources??(n.dataSources={}),n.dataSourceIds.push(o),n.dataSources[o]=s}),n.dataSources[o]},deleteDataSource:e=>{const o=n.dataSourceIds.indexOf(e);o!==-1&&t.doc.transact(()=>{n.dataSourceIds.splice(o,1),delete n.dataSources[e]})}}),[n,t.doc]);return{...t,state:n,actions:w,localActions:j,get currentPage(){const{localState:{currentPageId:e}}=t;return e?n.pages[e]:void 0},get currentSection(){var r,c,a;const{localState:{currentPageId:e,...o}}=t;if(!e)return;const s=(c=(r=o.pages)==null?void 0:r[e])==null?void 0:c.currentSectionId;if(s)return(a=n.pages[e])==null?void 0:a.sections[s]},get currentRoute(){var o;const{localState:{currentRouteId:e}}=t;return e?(o=n.routes)==null?void 0:o[e]:void 0}}},R=()=>{const{projectId:t}=V.useParams();return t??J()??""},Ee=()=>window.__PROJECT_SLUG__??"";function K(t){var S,g;const{resources:n}=t;if(!n.components)return{};const i={};return(g=(S=window==null?void 0:window.blocklet)==null?void 0:S.componentMountPoints)==null||g.forEach(P=>{i[P.did]=P}),Object.fromEntries(Object.entries(n.components).map(([P,{blockletId:j,component:w}])=>{var e;return[P,{data:w,blockletId:j,blockletTitle:((e=i[j])==null?void 0:e.title)||j}]}))}function Q(t){const{components:n}=t;return n||{}}function X(t){return{...K(t),...Q(t)}}const _e=()=>X(B().state);exports.ErrorView=pe;exports.StoreProvider=Oe;exports.api=L;exports.autoResizeImage=Ce;exports.getAllComponents=X;exports.getCustomComponents=Q;exports.getImageAbsoluteUrl=je;exports.getMountPoint=me;exports.getProjectIdFromPathnameOrWindow=J;exports.getProjectPageVersionKey=Se;exports.getResourceComponents=K;exports.getWssURL=Ie;exports.nextId=x;exports.transformValue=we;exports.useAllComponents=_e;exports.useProjectId=R;exports.useProjectSlug=Ee;exports.useStore=B;
|