@blocklet/pages-kit-inner-components 0.1.0 → 0.1.2
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/home.js +1 -1
- package/lib/cjs/locales.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +4 -4
- package/lib/cjs/site-state.js +1 -1
- package/lib/cjs/theme.js +239 -0
- package/lib/{draft-data-BR6QMafP.mjs → draft-data-Bbv-4GaF.mjs} +1 -1
- package/lib/{draft-data-DY34VJHh.js → draft-data-CgY7-dem.js} +1 -1
- package/lib/es/home.js +10 -8
- package/lib/es/locales.js +16 -4
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +946 -821
- package/lib/es/site-state.js +1 -1
- package/lib/es/theme.js +767 -0
- package/lib/home-D7i9eFDB.js +542 -0
- package/lib/{home-eQg2nzvF.mjs → home-DSngH2He.mjs} +698 -682
- package/lib/{publish-button-CKgx9XuN.mjs → publish-button-B0t_3Z4M.mjs} +2 -2
- package/lib/{publish-button-B-kvMf2a.js → publish-button-CrxBSa6-.js} +1 -1
- package/lib/{site-state-CrZeDXXY.mjs → site-state-BcfhbQn3.mjs} +304 -294
- package/lib/site-state-kBaXBQhY.js +1 -0
- package/lib/state-BQClQU2N.js +1 -0
- package/lib/state-C0vjPuun.mjs +407 -0
- package/package.json +26 -22
- package/lib/home-DhKwQuXD.js +0 -542
- package/lib/site-state-Ur6wK5g3.js +0 -1
- package/lib/state-BfVA6vd8.mjs +0 -378
- package/lib/state-C6F-M3XT.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const P=require("./components-DITf866E.js"),ke=require("@blocklet/quickjs"),ue=require("@blocklet/sdk/lib/component"),Re=require("@blocklet/sdk/lib/config"),Ue=require("@reactivedata/reactive"),H=require("@syncedstore/core"),h=require("fs"),re=require("glob"),Ce=require("lib0/decoding"),Ne=require("lib0/encoding"),_=require("lodash"),Ae=require("lru-cache"),Fe=require("nanoid"),qe=require("p-limit"),d=require("path"),Me=require("stream/promises"),xe=require("tar"),x=require("ufo"),Be=require("wait-on"),M=require("y-protocols/awareness"),te=require("y-protocols/sync"),Ve=require("yaml"),$e=require("yjs"),Ge=require("lodash/isNil"),j=require("sequelize");require("sqlite3");const Y=t=>t&&t.__esModule?t:{default:t};function Z(t){if(t&&t.__esModule)return t;const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,n.get?n:{enumerable:!0,get:()=>t[e]})}}return s.default=t,Object.freeze(s)}const y=Y(Re),se=Z(Ce),v=Z(Ne),Je=Y(qe),Ye=Y(d),ze=Y(Be),V=Z(Ve),q=Z($e),He=Y(Ge);y.default.env.mode;const Ke="image-bin";y.default.env.INIT_TEMPLATE_PATH;const We=process.env.DATABASE_URL||Ye.default.join(y.default.env.dataDir,"db/pages-kit.db"),he=y.default,Xe=()=>y.default.env.tenantMode==="multiple",Qe=()=>{var t;return(He.default(he.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=he.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},Ze=j.DataTypes.sqlite.DATE.parse;j.DataTypes.sqlite.DATE.parse=(t,s)=>typeof t=="number"?new Date(t):Ze(t,s);const z=new j.Sequelize({dialect:"sqlite",storage:We,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 ee extends j.Model{}ee.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:z,tableName:"ProjectComponents",timestamps:!1});class N extends j.Model{static async getProjectByIdOrSlug(s){return N.findOne({where:{[j.Op.or]:[{id:s},{slug:s}]}})}}N.init({id:{type:j.DataTypes.UUID,defaultValue:j.DataTypes.UUIDV4,primaryKey:!0},name:{type:j.DataTypes.STRING,allowNull:!1},description:j.DataTypes.TEXT,createdAt:j.DataTypes.DATE,updatedAt:j.DataTypes.DATE,createdBy:{type:j.DataTypes.STRING,allowNull:!1},updatedBy:{type:j.DataTypes.STRING,allowNull:!1},slug:j.DataTypes.STRING,icon:j.DataTypes.STRING,pinnedAt:j.DataTypes.DATE,useAllResources:j.DataTypes.BOOLEAN,relatedBlocklets:{type:j.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:z,paranoid:!0});N.hasMany(ee,{foreignKey:"projectId",as:"components"});const et="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",oe="page",ie="trigger-reload-project-resource",de=et,tt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:st}=require("@blocklet/uploader-server"),ce=Fe.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),fe=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,$=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Se=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,nt=1e4,at=3e4,K=0,ne=1,rt=0,ot=1,le=y.default,B=d.join(process.env.BLOCKLET_DATA_DIR,"site-state"),it=["production","draft"],ct=["production"];function Te(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function lt(){var e;const t=le.env.languages.map(n=>({locale:n.code,name:n.name})),s=(e=t[0])==null?void 0:e.locale;return{pageIds:[],pages:{},components:{},supportedLocales:t,config:{defaultLocale:s},resources:{}}}const C=class C extends q.Doc{constructor(s){super(),this.options=s,this.states={},this.conns=new Map,this.awarenessChangeHandler=({added:e,updated:n,removed:a},o)=>{const l=e.concat(n,a);if(o!==null){const c=this.conns.get(o);c&&(e.forEach(f=>{c.add(f)}),a.forEach(f=>{c.delete(f)}))}const i=v.createEncoder();v.writeVarUint(i,ne),v.writeVarUint8Array(i,M.encodeAwarenessUpdate(this.awareness,l));const r=v.toUint8Array(i);this.conns.forEach((c,f)=>this.send(f,r))},this.updateHandler=e=>{const n=v.createEncoder();v.writeVarUint(n,K),te.writeUpdate(n,e);const a=v.toUint8Array(n);this.conns.forEach((o,l)=>this.send(l,a))},this.ensureDataStructure=()=>{var l;const{supportedLocales:e,pages:n,pageIds:a,config:o}=this.syncedStore;{const i=new Set(Object.keys(n));let r=0;for(;r<a.length;){const c=a[r];i.has(c)?(i.delete(c),r++):a.splice(r,1)}}e.splice(0,e.length),e.push(...le.env.languages.map(i=>({locale:i.code,name:i.name}))),o.defaultLocale=(l=e[0])==null?void 0:l.locale;{let i=0;const r=new Set;for(;i<e.length;){const{locale:c}=e[i];r.has(c)?e.splice(i,1):(i++,r.add(c))}}},this.send=(e,n)=>{e.readyState!==rt&&e.readyState!==ot&&this.closeConn(e);try{e.send(n,a=>{a&&this.closeConn(e)})}catch{this.closeConn(e)}},this.closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const n=this.conns.get(e);this.conns.delete(e),n&&M.removeAwarenessStates(this.awareness,Array.from(n),null)}e.close()},this.autoSave=_.debounce(()=>{h.mkdirSync(d.dirname(this.draftYjsFilePath),{recursive:!0}),h.writeFileSync(this.draftYjsFilePath,q.encodeStateAsUpdate(this))},nt),this.save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()},this.publish=async({mode:e,pages:n})=>{const a=await this.getState("draft"),o=await this.getState("production");await pe(a,o,{pages:n,pageMergeMode:"replace",deletePages:!0,publishMode:e}),o.config.publishedAt=new Date().getTime();for(const l of n||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(e,o)},this.mergeState=async(e,n)=>{var i,r,c;const a=JSON.parse(JSON.stringify(n));(i=e.config).fontFamily??(i.fontFamily={});const o=(r=a.config)==null?void 0:r.fontFamily,l=(c=e.config)==null?void 0:c.fontFamily;e.config.fontFamily.title=(o==null?void 0:o.title)||(l==null?void 0:l.title),e.config.fontFamily.description=(o==null?void 0:o.description)||(l==null?void 0:l.description),await new Promise((f,p)=>{this.transact(async()=>{try{const S=await pe(e,n);f(S)}catch(S){p(S)}})})},this.addConnection=e=>{if(this.conns.has(e))return;e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",o=>this.messageListener(e,new Uint8Array(o)));let n=!0;const a=setInterval(()=>{if(!n)this.conns.has(e)&&this.closeConn(e),clearInterval(a);else if(this.conns.has(e)){n=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(a)}}},at);e.on("close",()=>{this.closeConn(e),clearInterval(a)}),e.on("pong",()=>{n=!0});{const o=v.createEncoder();v.writeVarUint(o,K),te.writeSyncStep1(o,this),this.send(e,v.toUint8Array(o));const l=this.awareness.getStates();if(l.size>0){const i=v.createEncoder();v.writeVarUint(i,ne),v.writeVarUint8Array(i,M.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,v.toUint8Array(i))}}},this.messageListener=(e,n)=>{try{const a=v.createEncoder(),o=se.createDecoder(n),l=se.readVarUint(o);switch(l){case K:v.writeVarUint(a,K),te.readSyncMessage(o,a,this,null),v.length(a)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(a)));break;case ne:{M.applyAwarenessUpdate(this.awareness,se.readVarUint8Array(o),e);break}default:P.logger.warn(`Unsupported messageType ${l}`)}}catch(a){P.logger.error(a)}this.save()},h.existsSync(this.draftYjsFilePath)&&q.applyUpdate(this,h.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ue.reactive(H.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new M.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(s){if(!s)throw new Error("Should provide project context");try{const e=d.join(B,s),n=d.join(B,`@del-${s}`);h.renameSync(e,n)}catch(e){P.logger.error("Failed to safe delete project state dir:",e)}}static get projectIds(){return re.globSync("*/",{cwd:B,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(s=>C.shared(s))}static shared(s){if(!s)throw new Error("Should provide project context");let e=this.sharedInstances.get(s);return e||(e=new C({path:d.join(B,s)}),this.sharedInstances.set(s,e),e)}destroy(){this.conns.forEach((s,e)=>this.closeConn(e)),this.awareness.destroy(),super.destroy()}initObserver(){const s=n=>{n.observeDeep(a=>{a.some(o=>o.changes.keys.has("updatedAt")||o.changes.keys.has("publishedAt"))||n.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(n=>{const a=H.getYjsValue(this.syncedStore.pages[n]);a&&a instanceof q.Map&&s(a)});const e=H.getYjsValue(this.syncedStore.pages);e&&e instanceof q.Map&&e.observe(n=>{n.changes.keys.forEach((a,o)=>{if(a.action==="add"){const l=H.getYjsValue(this.syncedStore.pages[o]);l&&l instanceof q.Map&&s(l)}})})}get draftYjsFilePath(){return d.join(this.options.path,"draft.yjs")}async getState(s){var e,n,a,o;if(s==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[s]&&(this.states[s]=await ge(this.getPublishDir(s),{includeResources:!0})??lt(),!((n=(e=this.states[s])==null?void 0:e.config)!=null&&n.defaultLocale))){(a=this.states[s]).config??(a.config={});const l=le.env.languages.map(i=>({locale:i.code,name:i.name}));this.states[s].config.defaultLocale=(o=l[0])==null?void 0:o.locale}return{...this.states[s],resources:await Le().then(async l=>{var f,p,S,I;const{pages:i,components:r}=_.pick(l,"pages","components");let c=r;if((p=(f=this.states[s])==null?void 0:f.resources)!=null&&p.components)c={...(I=(S=this.states[s])==null?void 0:S.resources)==null?void 0:I.components};else{const O=d.basename(this.options.path),D=await N.findByPk(O);if(D!=null&&D.useAllResources)c=r;else{const g=(await ee.findAll({where:{projectId:O}})).map(m=>m.componentId);c=Object.fromEntries(Object.entries(r||{}).filter(([m])=>g.includes(m)))}}return{pages:i,components:c}}).catch(()=>({}))}}async setState(s,e){const n=await Ie(e,{exportAssets:!1,includeResources:!0}),a=this.getPublishDir(s);h.mkdirSync(d.dirname(a),{recursive:!0}),h.rmSync(a,{force:!0,recursive:!0}),h.renameSync(n,a),this.states[s]=e}getPublishDir(s){return d.join(this.options.path,s)}static async pageUrlMap(s){const{projectIds:e}=this,n={};for(const a of e){const o=await N.findByPk(a);if(!o)continue;const l=await C.shared(a).getState(s),i=_.union(y.default.env.languages.map(r=>r.code),l.supportedLocales.map(r=>r.locale));for(const r of l.pageIds){const c=l.pages[r];if(!c||s==="production"&&!c.isPublic)continue;const f=c.slug,p=o.slug||a,S={projectId:a,projectSlug:p,pageSlug:f,pageId:r,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:l.config.publishedAt,isPublic:c.isPublic,isTemplate:c.isTemplate};p&&(n[x.joinURL("/",p,f)]={...S,shouldRedirect:!0,mainPage:!0}),n[x.joinURL("/",a,f)]={...S,shouldRedirect:!0,mainPage:!0};for(const I of i){const O={...S,locale:I};n[x.joinURL("/",I,a,f)]=O,p&&(n[x.joinURL("/",I,p,f)]=O)}}}return n}};C.INSTANCE_TTL=30*60*1e3,C.sharedInstances=new Ae.LRUCache({max:100,ttl:C.INSTANCE_TTL,dispose:s=>{s.destroy()}});let J=C;function je(){return h.mkdtempSync(d.join(y.default.env.dataDir,"tmp-"))}function X(t,s,e=[]){return Array.isArray(t)?t.flatMap((n,a)=>X(n,s,[...e,a])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([n,a])=>X(a,s,[...e,n])):s(t)?[e]:[]}function R(t){return t.filter(s=>s!=null)}async function pt(t,s,e){if(!t||!h.existsSync(t)||!h.lstatSync(t).isFile())return null;let n=e[t];return n||(n=(async()=>(await st({filePath:t,fileName:s})).data.filename)(),e[t]=n),n}const ut=async(t,s)=>{const e=d.basename(t),n=await ue.call({name:de,path:x.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const a=h.createWriteStream(s);await Me.pipeline(n.data,a)}else throw new Error(`download asset failed ${n.status}`)},dt=async(t,s)=>{await Promise.all(t.map(async e=>{try{await ut(e,d.join(s,d.basename(e)))}catch(n){P.logger.error(`Failed to export assets: ${e}, ${n}`)}}))};function ve(t){return fe.test(t)?[t]:$.test(t)?(Se.lastIndex=0,Array.from(t.matchAll(Se)).map(e=>e[1]).filter(e=>!!e)):[]}async function ae(t,s,e){const{getFilename:n,exportAssets:a}=e,o=d.join(s,n(t));if(h.mkdirSync(d.dirname(o),{recursive:!0}),h.writeFileSync(o,V.stringify(t)),a){const i=X(t,r=>typeof r=="string"&&(fe.test(r)||$.test(r))).map(r=>{const c=_.get(t,r);return ve(c)}).flat().filter(Boolean);await dt(i,d.dirname(o))}}const we=new Ae.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Ee(t,s,e){var i;const n=X(t,r=>typeof r=="string"&&(fe.test(r)||$.test(r))),a=Je.default(2),o=n.map(r=>a(async()=>{try{const c=_.get(t,r),f=ve(c);for(const p of f){const S=d.basename(p),I=e.getFilePath(p,r),O=I?`${I}:${S}`:S,D=we.get(O);if(D){$.test(c)||_.set(t,r,D);return}const U=await pt(I,S,s);U&&($.test(c)||_.set(t,r,U),we.set(O,U))}}catch(c){P.logger.error(`Failed to process upload for path ${r.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(o);(i=e.onFinish)==null||i.call(e,l)}async function Ie(t,{exportAssets:s,pageIds:e="all",componentIds:n="all",rawConfig:a,includeResources:o=!1}={}){var g,A,m,E,F,T;const l=e==="all"?t.pageIds:e,i=ft({state:t,pageIds:l,componentIds:n==="all"?Object.keys(t.components):n}),r=(u,w)=>{var b;return{id:u.id,name:u.name,isTemplateSection:u.isTemplateSection??!1,component:u.component,config:u.config,visibility:u.visibility,properties:((b=u.locales)==null?void 0:b[w])??{}}},c=(u,w)=>{var b;return{id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,isPublic:u.isPublic??!0,isTemplate:u.isTemplate??!1,meta:((b=u.locales)==null?void 0:b[w])??{},sections:R(u.sectionIds.map(L=>{const k=u.sections[L];return k&&r(k,w)}))}},f=R(t.supportedLocales.map(u=>u.locale).flatMap(u=>l.map(w=>{const b=t.pages[w];return b&&{locale:u,slug:b.slug,page:c(b,u)}}))),p=je(),S=d.join(p,"pages");h.mkdirSync(S,{recursive:!0});const I=d.join(p,"components");h.mkdirSync(I,{recursive:!0});for(const{locale:u,slug:w,page:b}of f)await ae(b,S,{getFilename:()=>`${Te(w)||"index"}.${u}.yml`,exportAssets:s});for(const u of i){const w=(g=t.components[u])==null?void 0:g.data;w&&await ae(w,I,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:s})}const O=d.join(p,".blocklet/pages/pages.config.yml");h.mkdirSync(d.dirname(O),{recursive:!0});const D={pages:R(l.map(u=>{const w=t.pages[u];return w&&{id:u,slug:w.slug}})),components:R(i.map(u=>{var b;const w=(b=t.components[u])==null?void 0:b.data;return w&&{id:u,name:w.name}})),...o?{resources:{components:R(Object.keys(((A=t.resources)==null?void 0:A.components)||{}).map(u=>{var w,b,L,k;return{id:u,name:(k=(L=(b=(w=t.resources)==null?void 0:w.components)==null?void 0:b[u])==null?void 0:L.component)==null?void 0:k.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};h.writeFileSync(O,V.stringify(D));const U=d.join(p,"config.source.json");if(a&&h.writeFileSync(U,JSON.stringify(a)),o){const u=d.join(p,"resources"),w=d.join(u,"components");h.mkdirSync(w,{recursive:!0});for(const b of Object.keys(((m=t==null?void 0:t.resources)==null?void 0:m.components)??{})){const L=(T=(F=(E=t.resources)==null?void 0:E.components)==null?void 0:F[b])==null?void 0:T.component;L&&await ae(L,w,{getFilename:k=>`${k.name||"unnamed"}.${k.id}.yml`,exportAssets:s})}}return p}async function ge(t,{importAssets:s,includeResources:e}={}){var o,l,i;if(!h.existsSync(t))return null;let n,a=!1;try{h.lstatSync(t).isDirectory()?n=t:/\.(tgz|gz|tar)$/.test(t)&&(a=!0,n=je(),await xe.x({file:t,C:n}));const r=re.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),c=r&&d.join(d.dirname(r),"../../pages"),f=r&&d.join(d.dirname(r),"../../components");if(!r)return null;const p=V.parse(h.readFileSync(r).toString()),S=(g,A,m)=>{let E=d.join(g,`${A}${m?`.${m}`:""}.yml`);return(!h.existsSync(E)||!h.lstatSync(E).isFile())&&(E=d.join(g,A,`index${m?`.${m}`:""}.yml`),!h.existsSync(E)||!h.lstatSync(E))?null:V.parse(h.readFileSync(E).toString())},I=(g,A)=>{try{const m=re.globSync(`*.${A}.yml`,{cwd:g,absolute:!0})[0];return m?V.parse(h.readFileSync(m).toString()):null}catch(m){P.logger.error("parse component error",m)}return null},O=R(p.pages.map(({slug:g})=>{var F;const A=R(p.supportedLocales.map(({locale:T})=>{const u=c?S(c,Te(g),T):void 0;if(u)return{locale:T,page:u};const w=c?S(c,g,T):void 0;return w&&{locale:T,page:w}})),m=(F=A[0])==null?void 0:F.page;if(!m)return null;const E=m.sections.map(T=>{const u=T.id||ce();return{id:u,component:T.component,config:T.config,name:T.name,isTemplateSection:T.isTemplateSection??!1,visibility:T.visibility,locales:Object.fromEntries(R(A.map(({locale:w,page:b})=>{const L=b.sections.find(k=>k.id===u);return L&&[w,L.properties]})))}});return{id:m.id||ce(),createdAt:m.createdAt,updatedAt:m.updatedAt,publishedAt:m.publishedAt,isPublic:m.isPublic??!0,isTemplate:m.isTemplate??!1,slug:g,sections:Object.fromEntries(E.map(T=>[T.id,T])),sectionIds:E.map(T=>T.id),locales:Object.fromEntries(A.map(({locale:T,page:u})=>[T,u.meta]))}})),D=f?R(((o=p.components)==null?void 0:o.map(({id:g})=>I(f,g)))??[]):[];if(s){const g=(...A)=>{P.logger.info(`[${a?d.basename(t):d.basename(d.join(t,"../../../../"))}] importAssets:`,...A)};try{g("wait image-bin api ready"),await ze.default({resources:[`${ue.getComponentWebEndpoint(Ke)}/api/sdk/uploads`],validateStatus:E=>E>=200&&E<=500}),g("image-bin api is ready");const A={},m={};g("start to upload assets"),await Promise.allSettled([Ee(D,A,{getFilePath:E=>f&&d.join(f,E),onFinish:E=>{g(`upload ${E.length} component assets`)}}),Ee(O,m,{getFilePath:(E,F)=>{const T=_.get(O,F.slice(0,1));return c&&d.join(c,d.dirname(T.slug),E)},onFinish:E=>{g(`upload ${E.length} page assets`)}})]),g("upload assets done"),global.gc&&global.gc()}catch(A){g("Error during asset import:",A)}}const U={};if(e){const g=r&&d.join(d.dirname(r),"../../resources/components"),A=R(((i=(l=p.resources)==null?void 0:l.components)==null?void 0:i.map(({id:m})=>I(g,m)))??[]);A.length>0&&(U.components=Object.fromEntries(A.map((m,E)=>[m.id,{index:E,component:m}])))}return{supportedLocales:p.supportedLocales,pageIds:O.map(g=>g.id),components:Object.fromEntries(D.map((g,A)=>[g.id,{index:A,data:g}])),pages:Object.fromEntries(O.map(g=>[g.id,g])),config:p.config||{},resources:U}}finally{a&&n&&h.rmSync(n,{force:!0,recursive:!0})}}async function pe(t,s,{pages:e,pageMergeMode:n="byUpdateTime",deletePages:a=!1,publishMode:o=void 0}={}){try{o&&P.clearPreloadComponentsCacheByMode(o)}catch(f){P.logger.error("clear preload page cache error",{error:f})}const{pageIds:l,pages:i,supportedLocales:r}=t;for(const f of e??l){const p=i[f];if(!p){const S=s.pageIds.indexOf(f);S!==-1&&a&&(s.pageIds.splice(S,1),delete s.pages[f]);continue}if(s.pageIds.includes(p.id)){if(n==="replace")s.pages[p.id]=p;else if(n==="byUpdateTime"){const S=s.pages[p.id];(!S||p.updatedAt&&p.updatedAt>S.updatedAt)&&(s.pages[p.id]=p)}}else s.pageIds.push(p.id),s.pages[p.id]=p}if(a&&!e)for(const f of s.pageIds)t.pageIds.includes(f)||delete s.pages[f],s.pageIds=[...s.pageIds].filter(p=>t.pageIds.includes(p));if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(..._.cloneDeep(r)),a)for(const f of Object.keys(s.components))delete s.components[f];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([f,p])=>{const S=await Oe(p==null?void 0:p.data);return[f,{...p,data:S}]}))),Object.assign(s.components,c),Object.assign(s.config,JSON.parse(JSON.stringify(t.config))),s.resources.components=JSON.parse(JSON.stringify(t.resources.components||{}))}const Oe=ke.memoize(async t=>{var s;if(!_.isEmpty(t==null?void 0:t.properties))return t;if(((s=t==null?void 0:t.renderer)==null?void 0:s.type)==="react-component"){const{script:e}=(t==null?void 0:t.renderer)||{};if(e)try{const n=await P.getExportSchemaValueFromCode(e,"PROPERTIES_SCHEMA",t.id);n&&n.length>0&&t&&(t.properties={},n.forEach((a,o)=>{t!=null&&t.properties&&(t.properties[a.id]={index:o,data:a})}))}catch(n){P.logger.error("checkPropertiesFromCode error",{componentId:t.id,name:t.name},{error:n})}}return t},{keyGenerator:t=>JSON.stringify(["checkPropertiesFromCode",t])});function ft({state:t,pageIds:s=[],componentIds:e=[]}){var l;const n=(i,r=new Set)=>(Array.isArray(i)&&i.forEach(c=>n(c,r)),i&&typeof i=="object"&&(typeof i.componentId=="string"&&r.add(i.componentId),Object.values(i).forEach(c=>n(c,r))),r),a=new Set(e);for(const i of s){const r=t.pages[i];n(r,a)}const o=[...a];for(;o.length;){const i=o.shift();a.has(i)||a.add(i);const r=(l=t.components[i])==null?void 0:l.data;if(r)for(const c of n(r))a.has(c)||o.push(c)}return[...a]}let Q,G,me,ye;function Pe(){return Q=(async()=>{const t=ue.getResources({types:[{did:de,type:oe},{did:tt,type:oe}]});G=(await Promise.all(t.map(async e=>{const n=e.path?await ge(e.path,{importAssets:!1}):void 0;return n?{blockletId:e.did,state:n,blockletTitle:e.title}:void 0}))).filter(e=>!!e),me=G.reduce((e,n)=>Object.assign(e,Object.fromEntries(Object.values(n.state.pages).map(a=>a?[a==null?void 0:a.id,{page:a,blockletId:n.blockletId}]:[]))),{});const s=G.reduce((e,n)=>Object.assign(e,Object.fromEntries(Object.values(n.state.components).map(a=>[a.data.id,{blockletId:n.blockletId,component:a.data}]))),{});ye=Object.fromEntries(await Promise.all(Object.entries(s).map(async([e,n])=>{const a=await Oe(n.component);return[e,{...n,component:a}]})))})(),Q}function De(t){const s=_.debounce(async()=>{await Pe().catch(e=>{P.logger.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:G,pages:me,components:ye}))},3e3,{leading:!1,trailing:!0});return s(),y.default.events.on(y.default.Events.componentAdded,s),y.default.events.on(y.default.Events.componentRemoved,s),y.default.events.on(y.default.Events.componentStarted,s),y.default.events.on(y.default.Events.componentStopped,s),y.default.events.on(y.default.Events.componentUpdated,s),y.default.events.on(ie,s),()=>{y.default.events.off(y.default.Events.componentAdded,s),y.default.events.off(y.default.Events.componentRemoved,s),y.default.events.off(y.default.Events.componentStarted,s),y.default.events.off(y.default.Events.componentStopped,s),y.default.events.off(y.default.Events.componentUpdated,s),y.default.events.off(ie,s)}}const _e=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),W=globalThis;var be;(be=W[_e])==null||be.call(W);W[_e]=De(async({pages:t,components:s})=>{const{projectIds:e}=J;await Promise.all(e.map(async n=>{const a=J.shared(n);a.syncedStore.resources.pages=t;const o=await N.findByPk(n);if(o!=null&&o.useAllResources)a.syncedStore.resources.components=s;else{const i=(await ee.findAll({where:{projectId:n}})).map(c=>c.componentId),r=Object.fromEntries(Object.entries(s||{}).filter(([c])=>i.includes(c)));a.syncedStore.resources.components=r}P.logger.info(`update [${n}] resource states:`,{pages:Object.keys(a.syncedStore.resources.pages||{}).length,components:Object.keys(a.syncedStore.resources.components||{}).length})}))});async function gt(){P.logger.info("trigger reload all project resource"),y.default.events.emit(ie)}async function Le(){return Q??(Q=Pe()),await Q,{states:G,pages:me,components:ye}}exports.COMPONENT_DID=de;exports.PUBLISH_MODES=ct;exports.Project=N;exports.RESOURCE_TYPE=oe;exports.SITE_STATE_PATH=B;exports.STATE_MODES=it;exports.SiteState=J;exports.fromPackage=ge;exports.getMultiTenantAllProjectAccessPassports=Qe;exports.getResourceStates=Le;exports.initPackResourceStates=De;exports.isMultiTenant=Xe;exports.mergeState=pe;exports.nextId=ce;exports.toPackage=Ie;exports.triggerReloadAllProjectResource=gt;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const P=require("react/jsx-runtime"),y=require("@mui/material"),Q=require("gradient-parser"),X=require("tinycolor2"),j=require("ufo"),Y=require("@blocklet/js-sdk"),W=require("@syncedstore/core"),Z=require("@syncedstore/react"),H=require("ahooks"),v=require("immer"),ee=require("js-cookie"),te=require("lodash/debounce"),ne=require("nanoid"),a=require("react"),F=require("react-router-dom"),oe=require("y-indexeddb"),se=require("y-websocket"),re=require("yjs"),C=e=>e&&e.__esModule?e:{default:e},ce=C(Q),ie=C(X),ae=C(W),ue=C(ee),B=C(te);function N(){const{pathname:e}=window.location,n=e.match(/\/admin\/(maker|previewer)\/([^/]+)/),l=n==null?void 0:n[2],u=window.__PROJECT_ID__;if(!l&&!u)throw new Error("Unable to get projectId from pathname");return l||u}function de(e){return`${e}:pages:version`}function le({error:e}){return P.jsx(y.Box,{children:P.jsx(y.Alert,{severity:"error",children:e.message})})}var T;const _=((T=window.blocklet)==null?void 0:T.prefix)||"/",L=Y.createAxios({timeout:200*1e3}),fe=window.location.protocol==="https:"?"wss":"ws",me=e=>j.joinURL(`${fe}://${window.location.hostname}`,_,`api/${e}/ws/pages`),pe="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var $;($=blocklet==null?void 0:blocklet.componentMountPoints.find(e=>e.did===pe))!=null&&$.mountPoint||j.joinURL(_,"/image-bin");function ge(e){return e&&!/^(https?:\/\/|\/)/.test(e)?window.location.origin+j.joinURL(_,"uploads",e):e}const Se=window.innerWidth<=750;function we(e,n,l){if(!e||/\.gif/.test(e))return e;const u=(Se?n/1.5:n)*(l==="quality"?1.5:1);return he(e,{imageFilter:"resize",w:u,f:"webp"})}function he(e,n){return!e||!n?e:j.withQuery(e,n)}function V(e){if(e!=null&&e.trim())try{return ce.default.parse(e),!0}catch{return!1}return!1}function Pe(e){return typeof e!="string"?!1:!!(V(e)||ie.default(e).isValid())}async function je(e){return L.get(`/api/projects/${e}`).then(n=>n.data)}async function ke(e){return L.post(`/api/projects/${e.id}/update`,e).then(n=>n.data)}const Ie=500,b=ne.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),z=a.createContext(null);function xe({url:e,name:n,children:l,waitingSynced:u}){const[f,d]=a.useState(!1),S=A(),k=`${S}:MakerLocalState`,t=`${S}:${n}`,[s,o]=H.useLocalStorageState(k,{defaultValue:{},listenStorageChange:!0}),r=a.useRef(s);r.current=s;const i=a.useMemo(()=>ae.default({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),c=a.useMemo(()=>W.getYjsDoc(i),[i]);a.useMemo(()=>new oe.IndexeddbPersistence(t,c),[t,c]);const w=a.useMemo(()=>new se.WebsocketProvider(e,t,c,{params:{token:ue.default.get("login_token")}}),[e,t,c]),I=a.useMemo(()=>new re.UndoManager([c.getArray("pageIds"),c.getMap("pages"),c.getArray("supportedLocales"),c.getMap("config")],{doc:c}),[c]),[x,E]=a.useState(null),[q,O]=a.useState(!1),[R,M]=a.useState(void 0),U=a.useCallback(async()=>{if(S){O(!0);try{const m=await je(S);E(m)}catch(m){console.error("Failed to fetch project:",m)}finally{O(!1)}}},[S]),D=a.useCallback(async(m,p)=>{var h;if(M(void 0),!!S){p!=null&&p.optimisticUpdate&&x&&E(g=>({...g,...m}));try{const g=await ke({...m});E(g)}catch(g){console.error("Failed to update project:",g),p!=null&&p.optimisticUpdate&&E(x),M((h=g==null?void 0:g.response)==null?void 0:h.data)}}},[S,x]);a.useEffect(()=>{S&&U()},[S,U]);const J=a.useMemo(()=>({doc:c,state:i,localState:s,setLocalState:m=>o(typeof m=="function"?p=>m(p??{}):m),undoManager:I,projectState:{project:x,isLoadingProject:q,error:R},updateProject:D}),[c,i,JSON.stringify(s),o,I,x,q,D,R]);return a.useEffect(()=>{I.on("stack-item-added",({stackItem:m})=>{const{currentPageId:p,currentLocale:h,pages:g}=r.current;m.meta.set("localState",{currentPageId:p,currentLocale:h,pages:g})}),I.on("stack-item-popped",({stackItem:m})=>{const p=m.meta.get("localState");p&&o(h=>({...h,...p}))})},[I,o]),a.useEffect(()=>{w.awareness.setLocalState(s)},[w,s]),a.useEffect(()=>{w.once("synced",()=>d(!0));const m=()=>{o(g=>({...g,networkStatus:void 0}))},p=()=>{o(g=>({...g,networkStatus:"offline"}))},h=B.default(({status:g})=>{g==="connected"?m():g==="disconnected"&&p()},Ie);return w.on("status",h),window.addEventListener("online",m),window.addEventListener("offline",p),()=>{w.off("status",h),window.removeEventListener("online",m),window.removeEventListener("offline",p)}},[w,o]),u&&!f?null:P.jsx(z.Provider,{value:J,children:l})}const G=()=>{const e=a.useContext(z);if(!e)throw new Error("Context is null");const n=Z.useSyncedStore(e.state),{setLocalState:l,localState:u}=e,f=F.useNavigate(),d=A(),S=a.useMemo(()=>({setCurrentSectionId:(t,s)=>{var o,r;t===u.currentPageId&&s===((r=(o=u.pages)==null?void 0:o[t])==null?void 0:r.currentSectionId)||(f(j.joinURL("/admin/maker",d??"","pages",t)),l(i=>v.produce(i,c=>{var w;c.currentPageId=t,c.currentComponentId=void 0,c.componentDebugProps={},s!==void 0&&(c.pages??(c.pages={}),(w=c.pages)[t]??(w[t]={}),c.pages[t].currentSectionId=s??void 0),s?window.sessionStorage.setItem("iframe_show_id",`"${s}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:t=>{t!==u.currentComponentId&&(f(j.joinURL("/admin/maker",d??"","components",t)),l(s=>v.produce(s,o=>{o.currentComponentId=t,o.componentDebugProps={}})))},setComponentDebugProps:(()=>{const t={},s=B.default(()=>{l(o=>v.produce(o,r=>{r.componentDebugProps={...r==null?void 0:r.componentDebugProps,...t},Object.keys(t).forEach(i=>delete t[i])}))},5);return o=>{Object.assign(t,o),s()}})()}),[l,f,d]),k=a.useMemo(()=>({addPage:(t,s)=>{const o=(t==null?void 0:t.id)??b(),r={...t,id:o,createdAt:(t==null?void 0:t.createdAt)??new Date().toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:(t==null?void 0:t.slug)??`/${o}`,sections:(t==null?void 0:t.sections)??{},sectionIds:(t==null?void 0:t.sectionIds)??[],isPublic:(t==null?void 0:t.isPublic)??!0,isTemplate:(t==null?void 0:t.isTemplate)??!1};return e.doc.transact(()=>{n.pages[r.id]=r,n.pageIds.splice(s??n.pageIds.length,0,r.id)}),r},deletePage:t=>{const s=n.pageIds.indexOf(t);s!==-1&&e.doc.transact(()=>{n.pageIds.splice(s,1),delete n.pages[t]})},movePage:(t,s)=>{const{pageIds:o}=n,r=o.indexOf(t);r>=0&&o.splice(s,0,...o.splice(r,1))},addSection:(t,s,o)=>{const r=n.pages[t];if(!r)throw new Error(`Page ${t} is not exists`);const i={...s,id:s.id??b(),isTemplateSection:s.isTemplateSection??!1};return e.doc.transact(()=>{r.sections[i.id]=i,r.sectionIds.splice(o??r.sectionIds.length,0,i.id)}),i},deleteSection:(t,s)=>{const o=n.pages[t];if(!o)throw new Error(`Page ${t} is not exists`);const r=o.sectionIds.indexOf(s);r!==-1&&e.doc.transact(()=>{o.sectionIds.splice(r,1),delete o.sections[s]})},toggleSectionVisibility:(t,s,o)=>{const r=n.pages[t];if(!r)throw new Error(`Page ${t} is not exists`);const i=r.sections[s];i&&(i.visibility=o)},moveSection:(t,s,o)=>{const r=n.pages[t];if(!r)throw new Error(`Page ${t} is not exists`);const{sectionIds:i}=r,c=i.indexOf(s);c>=0&&i.splice(o,0,...i.splice(c,1))}}),[n,e.doc]);return{...e,state:n,actions:k,localActions:S,get currentPage(){const{localState:{currentPageId:t}}=e;return t?n.pages[t]:void 0},get currentSection(){var r,i,c;const{localState:{currentPageId:t,...s}}=e;if(!t)return;const o=(i=(r=s.pages)==null?void 0:r[t])==null?void 0:i.currentSectionId;if(o)return(c=n.pages[t])==null?void 0:c.sections[o]}}},A=()=>{const{projectId:e}=F.useParams();return e??N()};function ye(e){var u,f;const{resources:n}=e;if(!n.components)return{};const l={};return(f=(u=window==null?void 0:window.blocklet)==null?void 0:u.componentMountPoints)==null||f.forEach(d=>{l[d.did]=d}),Object.fromEntries(Object.entries(n.components).map(([d,{blockletId:S,component:k}])=>{var t;return[d,{data:k,blockletId:S,blockletTitle:((t=l[S])==null?void 0:t.title)||S}]}))}function Ce(e){const{components:n}=e;return n||{}}function K(e){return{...ye(e),...Ce(e)}}const Ee=()=>K(G().state),ve=[/\.\./,/<[^>]*>/,/%[0-9a-f]{2}/i,/[<>'"%;{}()\\]/,/\x00/,/\n|\r|\t|\v|\f/,/[^a-zA-Z0-9-_@/]/];function be(e,n,l){const u=[];{let f;n.slug?n.slug.startsWith("/")?n.slug!=="/"&&n.slug.endsWith("/")?f=e("maker.properties.pathCheckEndWithoutSlash"):/\/{2,}/.test(n.slug)?f=e("maker.properties.pathCheckConsecutiveSlash"):/\s/.test(n.slug)?f=e("maker.properties.pathCheckWhitespace"):ve.some(d=>d.test(n.slug))?f=e("maker.properties.pathCheckInvalid"):Object.values(l.pages).some(d=>(d==null?void 0:d.id)!==n.id&&(d==null?void 0:d.slug)===n.slug)&&(f=e("maker.properties.pathCheckAlreadyExist")):f=e("maker.properties.pathCheckStartWithSlash"):f=e("maker.properties.pathCheckRequired"),f&&u.push({path:["path"],message:f})}return u.length>0?u:null}function _e({errors:e,...n}){return e!=null&&e.length?P.jsx(y.Tooltip,{...n,title:P.jsx(y.Box,{children:e.map((l,u)=>P.jsx(y.Box,{children:l.message},u))})}):null}exports.ErrorView=le;exports.PageErrorTip=_e;exports.StoreProvider=xe;exports.api=L;exports.autoResizeImage=we;exports.checkPage=be;exports.getAllComponents=K;exports.getImageAbsoluteUrl=ge;exports.getProjectIdFromPathnameOrWindow=N;exports.getProjectPageVersionKey=de;exports.getWssURL=me;exports.isColorString=Pe;exports.isGradient=V;exports.nextId=b;exports.useAllComponents=Ee;exports.useProjectId=A;exports.useStore=G;
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { jsx as P } from "react/jsx-runtime";
|
|
2
|
+
import { Box as x, Alert as V, Tooltip as q } from "@mui/material";
|
|
3
|
+
import K from "gradient-parser";
|
|
4
|
+
import J from "tinycolor2";
|
|
5
|
+
import { joinURL as I, withQuery as Q } from "ufo";
|
|
6
|
+
import { createAxios as X } from "@blocklet/js-sdk";
|
|
7
|
+
import Z, { getYjsDoc as Y } from "@syncedstore/core";
|
|
8
|
+
import { useSyncedStore as H } from "@syncedstore/react";
|
|
9
|
+
import { useLocalStorageState as ee } from "ahooks";
|
|
10
|
+
import { produce as b } from "immer";
|
|
11
|
+
import te from "js-cookie";
|
|
12
|
+
import F from "lodash/debounce";
|
|
13
|
+
import { customAlphabet as oe } from "nanoid";
|
|
14
|
+
import { createContext as ne, useState as C, useRef as re, useMemo as g, useCallback as U, useEffect as E, useContext as se } from "react";
|
|
15
|
+
import { useParams as ie, useNavigate as ce } from "react-router-dom";
|
|
16
|
+
import { IndexeddbPersistence as ae } from "y-indexeddb";
|
|
17
|
+
import { WebsocketProvider as ue } from "y-websocket";
|
|
18
|
+
import { UndoManager as de } from "yjs";
|
|
19
|
+
function le() {
|
|
20
|
+
const { pathname: t } = window.location, o = t.match(/\/admin\/(maker|previewer)\/([^/]+)/), d = o == null ? void 0 : o[2], a = window.__PROJECT_ID__;
|
|
21
|
+
if (!d && !a)
|
|
22
|
+
throw new Error("Unable to get projectId from pathname");
|
|
23
|
+
return d || a;
|
|
24
|
+
}
|
|
25
|
+
function Be(t) {
|
|
26
|
+
return `${t}:pages:version`;
|
|
27
|
+
}
|
|
28
|
+
function Ge({ error: t }) {
|
|
29
|
+
return /* @__PURE__ */ P(x, { children: /* @__PURE__ */ P(V, { severity: "error", children: t.message }) });
|
|
30
|
+
}
|
|
31
|
+
var M;
|
|
32
|
+
const A = ((M = window.blocklet) == null ? void 0 : M.prefix) || "/", N = X({
|
|
33
|
+
timeout: 200 * 1e3
|
|
34
|
+
}), fe = window.location.protocol === "https:" ? "wss" : "ws", Ve = (t) => I(`${fe}://${window.location.hostname}`, A, `api/${t}/ws/pages`), me = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
|
|
35
|
+
var W;
|
|
36
|
+
(W = blocklet == null ? void 0 : blocklet.componentMountPoints.find((t) => t.did === me)) != null && W.mountPoint || I(A, "/image-bin");
|
|
37
|
+
function qe(t) {
|
|
38
|
+
return t && !/^(https?:\/\/|\/)/.test(t) ? window.location.origin + I(A, "uploads", t) : t;
|
|
39
|
+
}
|
|
40
|
+
const pe = window.innerWidth <= 750;
|
|
41
|
+
function Ke(t, o, d) {
|
|
42
|
+
if (!t || /\.gif/.test(t)) return t;
|
|
43
|
+
const a = (pe ? o / 1.5 : o) * (d === "quality" ? 1.5 : 1);
|
|
44
|
+
return we(t, { imageFilter: "resize", w: a, f: "webp" });
|
|
45
|
+
}
|
|
46
|
+
function we(t, o) {
|
|
47
|
+
return !t || !o ? t : Q(t, o);
|
|
48
|
+
}
|
|
49
|
+
function he(t) {
|
|
50
|
+
if (t != null && t.trim())
|
|
51
|
+
try {
|
|
52
|
+
return K.parse(t), !0;
|
|
53
|
+
} catch {
|
|
54
|
+
return !1;
|
|
55
|
+
}
|
|
56
|
+
return !1;
|
|
57
|
+
}
|
|
58
|
+
function Je(t) {
|
|
59
|
+
return typeof t != "string" ? !1 : !!(he(t) || J(t).isValid());
|
|
60
|
+
}
|
|
61
|
+
async function Se(t) {
|
|
62
|
+
return N.get(`/api/projects/${t}`).then((o) => o.data);
|
|
63
|
+
}
|
|
64
|
+
async function ge(t) {
|
|
65
|
+
return N.post(`/api/projects/${t.id}/update`, t).then((o) => o.data);
|
|
66
|
+
}
|
|
67
|
+
const Pe = 500, R = oe("abcdefghijklmnopqrstuvwxyz0123456789", 16), z = ne(null);
|
|
68
|
+
function Qe({
|
|
69
|
+
url: t,
|
|
70
|
+
name: o,
|
|
71
|
+
children: d,
|
|
72
|
+
waitingSynced: a
|
|
73
|
+
}) {
|
|
74
|
+
const [l, u] = C(!1), w = B(), k = `${w}:MakerLocalState`, e = `${w}:${o}`, [r, n] = ee(k, {
|
|
75
|
+
defaultValue: {},
|
|
76
|
+
listenStorageChange: !0
|
|
77
|
+
}), s = re(r);
|
|
78
|
+
s.current = r;
|
|
79
|
+
const c = g(
|
|
80
|
+
() => Z({
|
|
81
|
+
pages: {},
|
|
82
|
+
pageIds: [],
|
|
83
|
+
components: {},
|
|
84
|
+
supportedLocales: [],
|
|
85
|
+
config: {},
|
|
86
|
+
resources: {}
|
|
87
|
+
}),
|
|
88
|
+
[]
|
|
89
|
+
), i = g(() => Y(c), [c]);
|
|
90
|
+
g(() => new ae(e, i), [e, i]);
|
|
91
|
+
const h = g(
|
|
92
|
+
() => new ue(t, e, i, { params: { token: te.get("login_token") } }),
|
|
93
|
+
[t, e, i]
|
|
94
|
+
), j = g(
|
|
95
|
+
() => new de(
|
|
96
|
+
[i.getArray("pageIds"), i.getMap("pages"), i.getArray("supportedLocales"), i.getMap("config")],
|
|
97
|
+
{ doc: i }
|
|
98
|
+
),
|
|
99
|
+
[i]
|
|
100
|
+
), [v, y] = C(null), [L, O] = C(!1), [_, $] = C(void 0), D = U(async () => {
|
|
101
|
+
if (w) {
|
|
102
|
+
O(!0);
|
|
103
|
+
try {
|
|
104
|
+
const f = await Se(w);
|
|
105
|
+
y(f);
|
|
106
|
+
} catch (f) {
|
|
107
|
+
console.error("Failed to fetch project:", f);
|
|
108
|
+
} finally {
|
|
109
|
+
O(!1);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}, [w]), T = U(
|
|
113
|
+
async (f, m) => {
|
|
114
|
+
var S;
|
|
115
|
+
if ($(void 0), !!w) {
|
|
116
|
+
m != null && m.optimisticUpdate && v && y((p) => ({
|
|
117
|
+
...p,
|
|
118
|
+
...f
|
|
119
|
+
}));
|
|
120
|
+
try {
|
|
121
|
+
const p = await ge({
|
|
122
|
+
...f
|
|
123
|
+
});
|
|
124
|
+
y(p);
|
|
125
|
+
} catch (p) {
|
|
126
|
+
console.error("Failed to update project:", p), m != null && m.optimisticUpdate && y(v), $((S = p == null ? void 0 : p.response) == null ? void 0 : S.data);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
[w, v]
|
|
131
|
+
);
|
|
132
|
+
E(() => {
|
|
133
|
+
w && D();
|
|
134
|
+
}, [w, D]);
|
|
135
|
+
const G = g(
|
|
136
|
+
() => ({
|
|
137
|
+
doc: i,
|
|
138
|
+
state: c,
|
|
139
|
+
localState: r,
|
|
140
|
+
setLocalState: (f) => n(typeof f == "function" ? (m) => f(m ?? {}) : f),
|
|
141
|
+
undoManager: j,
|
|
142
|
+
projectState: {
|
|
143
|
+
project: v,
|
|
144
|
+
isLoadingProject: L,
|
|
145
|
+
error: _
|
|
146
|
+
},
|
|
147
|
+
updateProject: T
|
|
148
|
+
}),
|
|
149
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
150
|
+
[
|
|
151
|
+
i,
|
|
152
|
+
c,
|
|
153
|
+
JSON.stringify(r),
|
|
154
|
+
// resolve the problem of react warning
|
|
155
|
+
n,
|
|
156
|
+
j,
|
|
157
|
+
v,
|
|
158
|
+
L,
|
|
159
|
+
T,
|
|
160
|
+
_
|
|
161
|
+
]
|
|
162
|
+
);
|
|
163
|
+
return E(() => {
|
|
164
|
+
j.on("stack-item-added", ({ stackItem: f }) => {
|
|
165
|
+
const { currentPageId: m, currentLocale: S, pages: p } = s.current;
|
|
166
|
+
f.meta.set("localState", { currentPageId: m, currentLocale: S, pages: p });
|
|
167
|
+
}), j.on("stack-item-popped", ({ stackItem: f }) => {
|
|
168
|
+
const m = f.meta.get("localState");
|
|
169
|
+
m && n((S) => ({ ...S, ...m }));
|
|
170
|
+
});
|
|
171
|
+
}, [j, n]), E(() => {
|
|
172
|
+
h.awareness.setLocalState(r);
|
|
173
|
+
}, [h, r]), E(() => {
|
|
174
|
+
h.once("synced", () => u(!0));
|
|
175
|
+
const f = () => {
|
|
176
|
+
n((p) => ({
|
|
177
|
+
...p,
|
|
178
|
+
networkStatus: void 0
|
|
179
|
+
}));
|
|
180
|
+
}, m = () => {
|
|
181
|
+
n((p) => ({
|
|
182
|
+
...p,
|
|
183
|
+
networkStatus: "offline"
|
|
184
|
+
}));
|
|
185
|
+
}, S = F(({ status: p }) => {
|
|
186
|
+
p === "connected" ? f() : p === "disconnected" && m();
|
|
187
|
+
}, Pe);
|
|
188
|
+
return h.on("status", S), window.addEventListener("online", f), window.addEventListener("offline", m), () => {
|
|
189
|
+
h.off("status", S), window.removeEventListener("online", f), window.removeEventListener("offline", m);
|
|
190
|
+
};
|
|
191
|
+
}, [h, n]), a && !l ? null : /* @__PURE__ */ P(z.Provider, { value: G, children: d });
|
|
192
|
+
}
|
|
193
|
+
const ke = () => {
|
|
194
|
+
const t = se(z);
|
|
195
|
+
if (!t)
|
|
196
|
+
throw new Error("Context is null");
|
|
197
|
+
const o = H(t.state), { setLocalState: d, localState: a } = t, l = ce(), u = B(), w = g(
|
|
198
|
+
() => ({
|
|
199
|
+
setCurrentSectionId: (e, r) => {
|
|
200
|
+
var n, s;
|
|
201
|
+
e === a.currentPageId && r === ((s = (n = a.pages) == null ? void 0 : n[e]) == null ? void 0 : s.currentSectionId) || (l(I("/admin/maker", u ?? "", "pages", e)), d(
|
|
202
|
+
(c) => b(c, (i) => {
|
|
203
|
+
var h;
|
|
204
|
+
i.currentPageId = e, i.currentComponentId = void 0, i.componentDebugProps = {}, r !== void 0 && (i.pages ?? (i.pages = {}), (h = i.pages)[e] ?? (h[e] = {}), i.pages[e].currentSectionId = r ?? void 0), r ? window.sessionStorage.setItem("iframe_show_id", `"${r}"`) : window.sessionStorage.removeItem("iframe_show_id");
|
|
205
|
+
})
|
|
206
|
+
));
|
|
207
|
+
},
|
|
208
|
+
setCurrentComponentId: (e) => {
|
|
209
|
+
e !== a.currentComponentId && (l(I("/admin/maker", u ?? "", "components", e)), d(
|
|
210
|
+
(r) => b(r, (n) => {
|
|
211
|
+
n.currentComponentId = e, n.componentDebugProps = {};
|
|
212
|
+
})
|
|
213
|
+
));
|
|
214
|
+
},
|
|
215
|
+
setComponentDebugProps: (() => {
|
|
216
|
+
const e = {}, r = F(() => {
|
|
217
|
+
d(
|
|
218
|
+
(n) => b(n, (s) => {
|
|
219
|
+
s.componentDebugProps = {
|
|
220
|
+
...s == null ? void 0 : s.componentDebugProps,
|
|
221
|
+
...e
|
|
222
|
+
}, Object.keys(e).forEach((c) => delete e[c]);
|
|
223
|
+
})
|
|
224
|
+
);
|
|
225
|
+
}, 5);
|
|
226
|
+
return (n) => {
|
|
227
|
+
Object.assign(e, n), r();
|
|
228
|
+
};
|
|
229
|
+
})()
|
|
230
|
+
}),
|
|
231
|
+
[d, l, u]
|
|
232
|
+
), k = g(
|
|
233
|
+
() => ({
|
|
234
|
+
addPage: (e, r) => {
|
|
235
|
+
const n = (e == null ? void 0 : e.id) ?? R(), s = {
|
|
236
|
+
...e,
|
|
237
|
+
id: n,
|
|
238
|
+
createdAt: (e == null ? void 0 : e.createdAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
239
|
+
updatedAt: (e == null ? void 0 : e.updatedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
240
|
+
publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
241
|
+
slug: (e == null ? void 0 : e.slug) ?? `/${n}`,
|
|
242
|
+
sections: (e == null ? void 0 : e.sections) ?? {},
|
|
243
|
+
sectionIds: (e == null ? void 0 : e.sectionIds) ?? [],
|
|
244
|
+
isPublic: (e == null ? void 0 : e.isPublic) ?? !0,
|
|
245
|
+
isTemplate: (e == null ? void 0 : e.isTemplate) ?? !1
|
|
246
|
+
};
|
|
247
|
+
return t.doc.transact(() => {
|
|
248
|
+
o.pages[s.id] = s, o.pageIds.splice(r ?? o.pageIds.length, 0, s.id);
|
|
249
|
+
}), s;
|
|
250
|
+
},
|
|
251
|
+
deletePage: (e) => {
|
|
252
|
+
const r = o.pageIds.indexOf(e);
|
|
253
|
+
r !== -1 && t.doc.transact(() => {
|
|
254
|
+
o.pageIds.splice(r, 1), delete o.pages[e];
|
|
255
|
+
});
|
|
256
|
+
},
|
|
257
|
+
movePage: (e, r) => {
|
|
258
|
+
const { pageIds: n } = o, s = n.indexOf(e);
|
|
259
|
+
s >= 0 && n.splice(r, 0, ...n.splice(s, 1));
|
|
260
|
+
},
|
|
261
|
+
addSection: (e, r, n) => {
|
|
262
|
+
const s = o.pages[e];
|
|
263
|
+
if (!s)
|
|
264
|
+
throw new Error(`Page ${e} is not exists`);
|
|
265
|
+
const c = {
|
|
266
|
+
...r,
|
|
267
|
+
id: r.id ?? R(),
|
|
268
|
+
isTemplateSection: r.isTemplateSection ?? !1
|
|
269
|
+
};
|
|
270
|
+
return t.doc.transact(() => {
|
|
271
|
+
s.sections[c.id] = c, s.sectionIds.splice(n ?? s.sectionIds.length, 0, c.id);
|
|
272
|
+
}), c;
|
|
273
|
+
},
|
|
274
|
+
deleteSection: (e, r) => {
|
|
275
|
+
const n = o.pages[e];
|
|
276
|
+
if (!n)
|
|
277
|
+
throw new Error(`Page ${e} is not exists`);
|
|
278
|
+
const s = n.sectionIds.indexOf(r);
|
|
279
|
+
s !== -1 && t.doc.transact(() => {
|
|
280
|
+
n.sectionIds.splice(s, 1), delete n.sections[r];
|
|
281
|
+
});
|
|
282
|
+
},
|
|
283
|
+
toggleSectionVisibility: (e, r, n) => {
|
|
284
|
+
const s = o.pages[e];
|
|
285
|
+
if (!s)
|
|
286
|
+
throw new Error(`Page ${e} is not exists`);
|
|
287
|
+
const c = s.sections[r];
|
|
288
|
+
c && (c.visibility = n);
|
|
289
|
+
},
|
|
290
|
+
moveSection: (e, r, n) => {
|
|
291
|
+
const s = o.pages[e];
|
|
292
|
+
if (!s)
|
|
293
|
+
throw new Error(`Page ${e} is not exists`);
|
|
294
|
+
const { sectionIds: c } = s, i = c.indexOf(r);
|
|
295
|
+
i >= 0 && c.splice(n, 0, ...c.splice(i, 1));
|
|
296
|
+
}
|
|
297
|
+
}),
|
|
298
|
+
[o, t.doc]
|
|
299
|
+
);
|
|
300
|
+
return {
|
|
301
|
+
...t,
|
|
302
|
+
state: o,
|
|
303
|
+
actions: k,
|
|
304
|
+
localActions: w,
|
|
305
|
+
get currentPage() {
|
|
306
|
+
const {
|
|
307
|
+
localState: { currentPageId: e }
|
|
308
|
+
} = t;
|
|
309
|
+
return e ? o.pages[e] : void 0;
|
|
310
|
+
},
|
|
311
|
+
get currentSection() {
|
|
312
|
+
var s, c, i;
|
|
313
|
+
const {
|
|
314
|
+
localState: { currentPageId: e, ...r }
|
|
315
|
+
} = t;
|
|
316
|
+
if (!e)
|
|
317
|
+
return;
|
|
318
|
+
const n = (c = (s = r.pages) == null ? void 0 : s[e]) == null ? void 0 : c.currentSectionId;
|
|
319
|
+
if (n)
|
|
320
|
+
return (i = o.pages[e]) == null ? void 0 : i.sections[n];
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}, B = () => {
|
|
324
|
+
const { projectId: t } = ie();
|
|
325
|
+
return t ?? le();
|
|
326
|
+
};
|
|
327
|
+
function je(t) {
|
|
328
|
+
var a, l;
|
|
329
|
+
const { resources: o } = t;
|
|
330
|
+
if (!o.components)
|
|
331
|
+
return {};
|
|
332
|
+
const d = {};
|
|
333
|
+
return (l = (a = window == null ? void 0 : window.blocklet) == null ? void 0 : a.componentMountPoints) == null || l.forEach((u) => {
|
|
334
|
+
d[u.did] = u;
|
|
335
|
+
}), Object.fromEntries(
|
|
336
|
+
Object.entries(o.components).map(([u, { blockletId: w, component: k }]) => {
|
|
337
|
+
var e;
|
|
338
|
+
return [
|
|
339
|
+
u,
|
|
340
|
+
{ data: k, blockletId: w, blockletTitle: ((e = d[w]) == null ? void 0 : e.title) || w }
|
|
341
|
+
];
|
|
342
|
+
})
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
function ve(t) {
|
|
346
|
+
const { components: o } = t;
|
|
347
|
+
return o || {};
|
|
348
|
+
}
|
|
349
|
+
function Ie(t) {
|
|
350
|
+
return {
|
|
351
|
+
...je(t),
|
|
352
|
+
...ve(t)
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
const Xe = () => Ie(ke().state), ye = [
|
|
356
|
+
/\.\./,
|
|
357
|
+
// Directory traversal
|
|
358
|
+
/<[^>]*>/,
|
|
359
|
+
// HTML/XML tags
|
|
360
|
+
/%[0-9a-f]{2}/i,
|
|
361
|
+
// Percent encoding
|
|
362
|
+
/[<>'"%;{}()\\]/,
|
|
363
|
+
// Special characters
|
|
364
|
+
// eslint-disable-next-line no-control-regex
|
|
365
|
+
/\x00/,
|
|
366
|
+
// Null byte
|
|
367
|
+
/\n|\r|\t|\v|\f/,
|
|
368
|
+
// Control characters
|
|
369
|
+
/[^a-zA-Z0-9-_@/]/
|
|
370
|
+
// Disallow any characters except alphanumeric, dash, underscore and forward slash
|
|
371
|
+
];
|
|
372
|
+
function Ze(t, o, d) {
|
|
373
|
+
const a = [];
|
|
374
|
+
{
|
|
375
|
+
let l;
|
|
376
|
+
o.slug ? o.slug.startsWith("/") ? o.slug !== "/" && o.slug.endsWith("/") ? l = t("maker.properties.pathCheckEndWithoutSlash") : /\/{2,}/.test(o.slug) ? l = t("maker.properties.pathCheckConsecutiveSlash") : /\s/.test(o.slug) ? l = t("maker.properties.pathCheckWhitespace") : ye.some((u) => u.test(o.slug)) ? l = t("maker.properties.pathCheckInvalid") : Object.values(d.pages).some((u) => (u == null ? void 0 : u.id) !== o.id && (u == null ? void 0 : u.slug) === o.slug) && (l = t("maker.properties.pathCheckAlreadyExist")) : l = t("maker.properties.pathCheckStartWithSlash") : l = t("maker.properties.pathCheckRequired"), l && a.push({ path: ["path"], message: l });
|
|
377
|
+
}
|
|
378
|
+
return a.length > 0 ? a : null;
|
|
379
|
+
}
|
|
380
|
+
function Ye({ errors: t, ...o }) {
|
|
381
|
+
return t != null && t.length ? /* @__PURE__ */ P(
|
|
382
|
+
q,
|
|
383
|
+
{
|
|
384
|
+
...o,
|
|
385
|
+
title: /* @__PURE__ */ P(x, { children: t.map((d, a) => /* @__PURE__ */ P(x, { children: d.message }, a)) })
|
|
386
|
+
}
|
|
387
|
+
) : null;
|
|
388
|
+
}
|
|
389
|
+
export {
|
|
390
|
+
Ge as E,
|
|
391
|
+
Ye as P,
|
|
392
|
+
Qe as S,
|
|
393
|
+
Ke as a,
|
|
394
|
+
Je as b,
|
|
395
|
+
N as c,
|
|
396
|
+
le as d,
|
|
397
|
+
Ie as e,
|
|
398
|
+
Be as f,
|
|
399
|
+
qe as g,
|
|
400
|
+
ke as h,
|
|
401
|
+
he as i,
|
|
402
|
+
Xe as j,
|
|
403
|
+
Ve as k,
|
|
404
|
+
Ze as l,
|
|
405
|
+
R as n,
|
|
406
|
+
B as u
|
|
407
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -43,6 +43,10 @@
|
|
|
43
43
|
"./uploader": {
|
|
44
44
|
"import": "./lib/es/uploader.js",
|
|
45
45
|
"require": "./lib/cjs/uploader.js"
|
|
46
|
+
},
|
|
47
|
+
"./theme": {
|
|
48
|
+
"import": "./lib/es/theme.js",
|
|
49
|
+
"require": "./lib/cjs/theme.js"
|
|
46
50
|
}
|
|
47
51
|
},
|
|
48
52
|
"files": [
|
|
@@ -57,25 +61,25 @@
|
|
|
57
61
|
"url": "git+https://github.com/blocklet/pages-kit.git"
|
|
58
62
|
},
|
|
59
63
|
"dependencies": {
|
|
60
|
-
"@arcblock/did-auth": "^1.19.
|
|
64
|
+
"@arcblock/did-auth": "^1.19.12",
|
|
61
65
|
"@arcblock/did-auth-storage-nedb": "^1.7.1",
|
|
62
|
-
"@arcblock/did-connect": "^2.11.
|
|
63
|
-
"@arcblock/react-hooks": "^2.11.
|
|
64
|
-
"@arcblock/ux": "^2.11.
|
|
65
|
-
"@blocklet/ai-kit": "^0.1.
|
|
66
|
-
"@blocklet/ai-runtime": "^0.4.
|
|
67
|
-
"@blocklet/code-editor": "^0.4.
|
|
68
|
-
"@blocklet/crawler": "^2.1.
|
|
66
|
+
"@arcblock/did-connect": "^2.11.48",
|
|
67
|
+
"@arcblock/react-hooks": "^2.11.48",
|
|
68
|
+
"@arcblock/ux": "^2.11.48",
|
|
69
|
+
"@blocklet/ai-kit": "^0.1.71",
|
|
70
|
+
"@blocklet/ai-runtime": "^0.4.241",
|
|
71
|
+
"@blocklet/code-editor": "^0.4.241",
|
|
72
|
+
"@blocklet/crawler": "^2.1.170",
|
|
69
73
|
"@blocklet/embed": "^0.2.3",
|
|
70
|
-
"@blocklet/js-sdk": "^1.16.
|
|
74
|
+
"@blocklet/js-sdk": "^1.16.39",
|
|
71
75
|
"@blocklet/logger": "1.16.36",
|
|
72
|
-
"@blocklet/quickjs": "^0.4.
|
|
73
|
-
"@blocklet/sdk": "^1.16.
|
|
74
|
-
"@blocklet/studio-ui": "^0.4.
|
|
75
|
-
"@blocklet/tracker": "^1.16.
|
|
76
|
-
"@blocklet/ui-react": "^2.11.
|
|
77
|
-
"@blocklet/uploader": "^0.1.
|
|
78
|
-
"@blocklet/uploader-server": "^0.1.
|
|
76
|
+
"@blocklet/quickjs": "^0.4.241",
|
|
77
|
+
"@blocklet/sdk": "^1.16.39",
|
|
78
|
+
"@blocklet/studio-ui": "^0.4.241",
|
|
79
|
+
"@blocklet/tracker": "^1.16.39",
|
|
80
|
+
"@blocklet/ui-react": "^2.11.48",
|
|
81
|
+
"@blocklet/uploader": "^0.1.71",
|
|
82
|
+
"@blocklet/uploader-server": "^0.1.85",
|
|
79
83
|
"@emotion/cache": "^11.13.1",
|
|
80
84
|
"@emotion/css": "^11.13.0",
|
|
81
85
|
"@emotion/react": "^11.13.0",
|
|
@@ -94,9 +98,9 @@
|
|
|
94
98
|
"@mui/styles": "^5.16.7",
|
|
95
99
|
"@mui/utils": "^5.16.6",
|
|
96
100
|
"@mui/x-date-pickers": "^7.13.0",
|
|
97
|
-
"@ocap/client": "^1.19.
|
|
98
|
-
"@ocap/mcrypto": "^1.19.
|
|
99
|
-
"@ocap/wallet": "^1.19.
|
|
101
|
+
"@ocap/client": "^1.19.12",
|
|
102
|
+
"@ocap/mcrypto": "^1.19.12",
|
|
103
|
+
"@ocap/wallet": "^1.19.12",
|
|
100
104
|
"@reactivedata/reactive": "^0.2.2",
|
|
101
105
|
"@syncedstore/core": "^0.6.0",
|
|
102
106
|
"@syncedstore/react": "^0.6.0",
|
|
@@ -194,8 +198,8 @@
|
|
|
194
198
|
"yaml": "^2.5.0",
|
|
195
199
|
"yjs": "^13.6.18",
|
|
196
200
|
"zustand": "^4.5.5",
|
|
197
|
-
"@blocklet/pages-kit": "^0.4.
|
|
198
|
-
"@blocklet/pages-kit-block-studio": "^0.1.
|
|
201
|
+
"@blocklet/pages-kit": "^0.4.13-beta.20250227",
|
|
202
|
+
"@blocklet/pages-kit-block-studio": "^0.1.24"
|
|
199
203
|
},
|
|
200
204
|
"devDependencies": {
|
|
201
205
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|