@blocklet/pages-kit-inner-components 0.5.41 → 0.5.43
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 +1 -1
- package/lib/cjs/chunks/{array-Cr5KF-hM.js → array-Cip5uTnI.js} +1 -1
- package/lib/cjs/chunks/{config-string-BYZ5HfyY.js → config-string-CEipCOnU.js} +1 -1
- package/lib/cjs/chunks/{draft-data-6zW9mu28.js → draft-data-F0V4PcIs.js} +1 -1
- package/lib/cjs/chunks/{home-DryEAaN4.js → home-BCFoaIEZ.js} +3 -3
- package/lib/cjs/chunks/{publish-button-oe4N0mbK.js → publish-button-Bbd4z1_d.js} +1 -1
- package/lib/cjs/chunks/site-state-CeQEnrvX.js +57 -0
- package/lib/cjs/chunks/state-UwRWAZRe.js +1 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/project-html.js +3 -3
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +2 -2
- package/lib/cjs/site-state.js +1 -1
- package/lib/cjs/theme.js +1 -1
- package/lib/es/add-component.js +3 -3
- package/lib/es/chunks/{array-D34Qpnhk.js → array-DM0x2Sjw.js} +1 -1
- package/lib/es/chunks/{config-string-DgK7ETCs.js → config-string-Dw6sJMn_.js} +1 -1
- package/lib/es/chunks/{draft-data-B5kzDvTI.js → draft-data-sTSk4UTm.js} +1 -1
- package/lib/es/chunks/{home-DZ0sRPEQ.js → home-ClxOpmCx.js} +4 -4
- package/lib/es/chunks/{publish-button-Ctl_bvtq.js → publish-button-CKXdANG9.js} +3 -3
- package/lib/es/chunks/{site-state-YSH6XJUc.js → site-state-BeEHvakk.js} +408 -397
- package/lib/es/chunks/{state-BzwEX9VC.js → state-COB6reM7.js} +98 -103
- package/lib/es/components.js +1 -1
- package/lib/es/home.js +3 -3
- package/lib/es/project-html.js +70 -70
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +1188 -924
- package/lib/es/site-state.js +1 -1
- package/lib/es/theme.js +14 -11
- package/package.json +7 -7
- package/lib/cjs/chunks/site-state-B8sLWiY2.js +0 -57
- package/lib/cjs/chunks/state-BWuBNdK8.js +0 -1
package/lib/es/site-state.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { q as j, o as q, p as v, S as B, r as L, s as U, u as h, b as y, w as z, v as C, n as F, t as G, x as J } from "./chunks/site-state-
|
|
1
|
+
import { q as j, o as q, p as v, S as B, r as L, s as U, u as h, b as y, w as z, v as C, n as F, t as G, x as J } from "./chunks/site-state-BeEHvakk.js";
|
|
2
2
|
import "@blocklet/pages-kit/utils/property";
|
|
3
3
|
import "@blocklet/pages-kit/utils/route";
|
|
4
4
|
import "@blocklet/sdk/lib/component";
|
package/lib/es/theme.js
CHANGED
|
@@ -2,7 +2,7 @@ import { jsx as s } from "react/jsx-runtime";
|
|
|
2
2
|
import { ConfigProvider as f } from "@arcblock/ux/lib/Config";
|
|
3
3
|
import { Icon as y } from "@iconify-icon/react";
|
|
4
4
|
import g from "@iconify-icons/tabler/chevron-down";
|
|
5
|
-
import { listItemIconClasses as
|
|
5
|
+
import { listItemIconClasses as z, switchClasses as S, svgIconClasses as n, sliderClasses as l, outlinedInputClasses as d, inputBaseClasses as t, filledInputClasses as m, inputLabelClasses as i, inputClasses as a, selectClasses as v, autocompleteClasses as p, Box as M } from "@mui/material";
|
|
6
6
|
import { S as b } from "./chunks/session-CVblGhSp.js";
|
|
7
7
|
import { translations as c } from "./locales.js";
|
|
8
8
|
var x;
|
|
@@ -111,7 +111,7 @@ const I = {
|
|
|
111
111
|
height: 28,
|
|
112
112
|
width: 48,
|
|
113
113
|
padding: 8,
|
|
114
|
-
[`&.${
|
|
114
|
+
[`&.${S.sizeSmall}`]: {
|
|
115
115
|
height: 26,
|
|
116
116
|
width: 40,
|
|
117
117
|
padding: 8
|
|
@@ -161,7 +161,7 @@ const I = {
|
|
|
161
161
|
[`.${t.input}`]: {
|
|
162
162
|
height: "1.5rem"
|
|
163
163
|
},
|
|
164
|
-
[`&.${
|
|
164
|
+
[`&.${a.multiline}`]: {
|
|
165
165
|
pl: 0,
|
|
166
166
|
pr: 0,
|
|
167
167
|
pt: "16px",
|
|
@@ -171,12 +171,12 @@ const I = {
|
|
|
171
171
|
}
|
|
172
172
|
},
|
|
173
173
|
// standard
|
|
174
|
-
[`.${
|
|
174
|
+
[`.${a.root}`]: {
|
|
175
175
|
mt: 1.5,
|
|
176
176
|
[`&.${t.hiddenLabel}`]: {
|
|
177
177
|
mt: 0,
|
|
178
178
|
pt: 0,
|
|
179
|
-
[`.${v.select}.${
|
|
179
|
+
[`.${v.select}.${a.input}:focus`]: {
|
|
180
180
|
bgcolor: "transparent"
|
|
181
181
|
}
|
|
182
182
|
}
|
|
@@ -205,7 +205,10 @@ const I = {
|
|
|
205
205
|
},
|
|
206
206
|
[`&.${t.inputSizeSmall}`]: {
|
|
207
207
|
pb: 0.25,
|
|
208
|
-
pt: r != null && r.label ? 1.25 : 0.25
|
|
208
|
+
pt: r != null && r.label ? 1.25 : 0.25,
|
|
209
|
+
...r != null && r.multiline ? {
|
|
210
|
+
pt: 0
|
|
211
|
+
} : {}
|
|
209
212
|
},
|
|
210
213
|
[`&.${t.inputHiddenLabel}`]: {
|
|
211
214
|
py: 0.5,
|
|
@@ -299,7 +302,7 @@ const I = {
|
|
|
299
302
|
select: {
|
|
300
303
|
display: "flex",
|
|
301
304
|
alignItems: "center",
|
|
302
|
-
[`.${
|
|
305
|
+
[`.${z.root}`]: {
|
|
303
306
|
minWidth: 20
|
|
304
307
|
}
|
|
305
308
|
}
|
|
@@ -344,16 +347,16 @@ const I = {
|
|
|
344
347
|
props: {},
|
|
345
348
|
style: ({ theme: e }) => e.unstable_sx({
|
|
346
349
|
height: 3,
|
|
347
|
-
[`.${
|
|
350
|
+
[`.${l.track}`]: {
|
|
348
351
|
borderWidth: 0
|
|
349
352
|
},
|
|
350
|
-
[`.${
|
|
353
|
+
[`.${l.thumb}`]: {
|
|
351
354
|
width: 16,
|
|
352
355
|
height: 16
|
|
353
356
|
},
|
|
354
|
-
[`&.${
|
|
357
|
+
[`&.${l.sizeSmall}`]: {
|
|
355
358
|
height: 2,
|
|
356
|
-
[`.${
|
|
359
|
+
[`.${l.thumb}`]: {
|
|
357
360
|
width: 12,
|
|
358
361
|
height: 12
|
|
359
362
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.43",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -71,9 +71,9 @@
|
|
|
71
71
|
"dependencies": {
|
|
72
72
|
"@arcblock/did-auth": "^1.20.14",
|
|
73
73
|
"@arcblock/did-auth-storage-nedb": "^1.7.1",
|
|
74
|
-
"@arcblock/did-connect": "^2.13.
|
|
75
|
-
"@arcblock/react-hooks": "^2.13.
|
|
76
|
-
"@arcblock/ux": "^2.13.
|
|
74
|
+
"@arcblock/did-connect": "^2.13.67",
|
|
75
|
+
"@arcblock/react-hooks": "^2.13.67",
|
|
76
|
+
"@arcblock/ux": "^2.13.67",
|
|
77
77
|
"@blocklet/ai-kit": "^0.1.79",
|
|
78
78
|
"@blocklet/ai-runtime": "^0.4.274",
|
|
79
79
|
"@blocklet/code-editor": "^0.4.274",
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"@blocklet/sdk": "^1.16.44",
|
|
85
85
|
"@blocklet/studio-ui": "^0.4.274",
|
|
86
86
|
"@blocklet/tracker": "^1.16.44",
|
|
87
|
-
"@blocklet/ui-react": "^2.13.
|
|
87
|
+
"@blocklet/ui-react": "^2.13.67",
|
|
88
88
|
"@blocklet/uploader": "^0.1.95",
|
|
89
89
|
"@blocklet/uploader-server": "^0.1.101",
|
|
90
90
|
"@emotion/cache": "^11.13.1",
|
|
@@ -204,8 +204,8 @@
|
|
|
204
204
|
"yaml": "^2.5.0",
|
|
205
205
|
"yjs": "^13.6.18",
|
|
206
206
|
"zustand": "^4.5.5",
|
|
207
|
-
"@blocklet/pages-kit
|
|
208
|
-
"@blocklet/pages-kit": "^0.5.
|
|
207
|
+
"@blocklet/pages-kit": "^0.5.43",
|
|
208
|
+
"@blocklet/pages-kit-block-studio": "^0.5.43"
|
|
209
209
|
},
|
|
210
210
|
"devDependencies": {
|
|
211
211
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";var _t=Object.defineProperty;var kt=(e,n,t)=>n in e?_t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var v=(e,n,t)=>kt(e,typeof n!="symbol"?n+"":n,t);const vt=require("@blocklet/pages-kit/builtin/utils"),ye=require("@blocklet/pages-kit/types"),de=require("@blocklet/pages-kit/utils/property"),pe=require("@blocklet/quickjs"),Rt=require("@blocklet/sdk/lib/config"),Pe=require("lru-cache"),at=require("node-fetch"),F=require("ufo"),Z=require("crypto"),xt=require("@blocklet/logger"),w=require("fs"),S=require("path"),Lt=require("lodash/isNil"),Nt=require("@blocklet/pages-kit/utils/builtin"),rt=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),Ge=require("@blocklet/sdk/lib/component"),Mt=require("autoprefixer"),$t=require("esbuild"),Ut=require("postcss"),Ft=require("tailwindcss"),qt=require("typescript"),ee=require("@syncedstore/core"),Bt=require("yjs"),Ht=require("@blocklet/pages-kit/utils/data-source"),we=require("@blocklet/pages-kit/utils/route"),Gt=require("lodash"),Vt=require("@reactivedata/reactive"),Me=require("glob"),Jt=require("lib0/decoding"),Kt=require("lib0/encoding"),zt=require("lodash/cloneDeep"),Yt=require("lodash/debounce"),Wt=require("lodash/get"),Qt=require("lodash/isEmpty"),Xt=require("lodash/pick"),Zt=require("lodash/set"),es=require("lodash/union"),ts=require("nanoid"),ss=require("p-limit"),ns=require("stream/promises"),os=require("tar"),as=require("wait-on"),ie=require("y-protocols/awareness"),Re=require("y-protocols/sync"),rs=require("yaml"),k=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const L=e=>e&&e.__esModule?e:{default:e};function fe(e){if(e&&e.__esModule)return e;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,s.get?s:{enumerable:!0,get:()=>e[t]})}}return n.default=e,Object.freeze(n)}const C=L(Rt),is=L(at),cs=L(xt),it=L(S),ls=L(Lt),ds=L(Mt),ps=fe($t),us=L(Ut),fs=L(Ft),U=L(qt),V=fe(Bt),xe=fe(Jt),x=fe(Kt),ms=L(zt),ct=L(Yt),Ve=L(Wt),lt=L(Qt),hs=L(Xt),Xe=L(Zt),gs=L(es),ys=L(ss),Ss=L(as),ne=fe(rs);C.default.env.mode;C.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;C.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;C.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;C.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const Es="image-bin";C.default.env.INIT_TEMPLATE_PATH;const ws=process.env.DATABASE_URL||it.default.join(C.default.env.dataDir,"db/pages-kit.db"),Ze=C.default,bs=()=>C.default.env.tenantMode==="multiple",Is=()=>{var e;return(ls.default(Ze.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=Ze.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},Cs=it.default.join(C.default.env.dataDir,"fs-memoize-cache"),Os=C.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",y=cs.default("pages-kit"),As=k.DataTypes.sqlite.DATE.parse;k.DataTypes.sqlite.DATE.parse=(e,n)=>typeof e=="number"?new Date(e):As(e,n);const me=new k.Sequelize({dialect:"sqlite",storage:ws,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});me.query("pragma journal_mode = WAL;");me.query("pragma synchronous = normal;");me.query("pragma journal_size_limit = 67108864;");class Te extends k.Model{}Te.init({id:{type:k.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:k.DataTypes.UUIDV4},projectId:{type:k.DataTypes.UUID,allowNull:!1},componentId:{type:k.DataTypes.STRING,allowNull:!1}},{sequelize:me,tableName:"ProjectComponents",timestamps:!1});class K extends k.Model{static async getProjectByIdOrSlug(n){return K.findOne({where:{[k.Op.or]:[{id:n},{slug:n}]}})}}K.init({id:{type:k.DataTypes.UUID,defaultValue:k.DataTypes.UUIDV4,primaryKey:!0},name:{type:k.DataTypes.STRING,allowNull:!1},description:k.DataTypes.TEXT,createdAt:k.DataTypes.DATE,updatedAt:k.DataTypes.DATE,createdBy:{type:k.DataTypes.STRING,allowNull:!1},updatedBy:{type:k.DataTypes.STRING,allowNull:!1},slug:k.DataTypes.STRING,icon:k.DataTypes.STRING,pinnedAt:k.DataTypes.DATE,useAllResources:k.DataTypes.BOOLEAN,npmSecret:k.DataTypes.STRING,relatedBlocklets:{type:k.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:me,paranoid:!0});K.hasMany(Te,{foreignKey:"projectId",as:"components"});const Ps=Cs,Ts=Os,$e=7*24*60*60*1e3,js=24*60*60*1e3,dt=async(e="")=>{const n=S.join(Ps,e);try{if(!(await w.promises.stat(n)).isDirectory())throw new Error(`${n} is not a directory`)}catch{await w.promises.mkdir(n,{recursive:!0})}return n},Ds=(e,n)=>{const t=Z.createHash("md5").update(n).digest("hex");return S.join(e,`${Ts}-${t}.json`)},_s=async(e="")=>{const n=await dt(e),t=Date.now();try{const s=await w.promises.readdir(n);await Promise.all(s.filter(o=>o.endsWith(".json")).map(async o=>{const a=S.join(n,o);try{const r=await w.promises.readFile(a,"utf-8"),u=JSON.parse(r);u.createdAt&&t-u.createdAt>$e&&await w.promises.unlink(a)}catch{try{const u=await w.promises.stat(a);t-u.mtimeMs>$e&&await w.promises.unlink(a)}catch{}}}))}catch(s){console.error(`Failed to cleanup cache in ${n}:`,s)}},ks=(()=>{const e=new Set;return setInterval(async()=>{await Promise.all(Array.from(e).map(s=>_s(s)))},js).unref(),s=>{e.add(s)}})();function Je(e,n){return n.subdir&&ks(n.subdir),pe.memoize(async(...s)=>{const o=await dt(n.subdir||""),a=n.keyGenerator?n.keyGenerator(...s):JSON.stringify(s),r=Ds(o,a);try{const u=await w.promises.readFile(r,"utf-8"),{value:c,createdAt:i}=JSON.parse(u);if(i&&Date.now()-i>$e)throw await w.promises.unlink(r).catch(()=>{}),new Error("Cache expired");return c}catch{const c=await e(...s),i=JSON.stringify({value:c,createdAt:Date.now()});return w.promises.writeFile(r,i,"utf-8").catch(d=>{console.error("Failed to write fs cache:",d)}),c}},{keyGenerator:n.keyGenerator,lruOptions:n.lruOptions})}const vs=async(e,{componentId:n})=>{const t=`@tailwind components;
|
|
2
|
-
@tailwind utilities;
|
|
3
|
-
`,s=`.CustomComponent_${n}`;return(await us.default([fs.default({content:[{raw:e,extension:"tsx"}]}),ds.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(r=>{r.selectors=r.selectors.map(u=>u.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(t)).css},Rs=async(e,{componentId:n})=>{const t=await vs(e,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
|
|
4
|
-
|
|
5
|
-
${e}
|
|
6
|
-
`},et=Je(async(e,n)=>{let t=U.default.transpileModule(e,{compilerOptions:{jsx:U.default.JsxEmit.React,target:U.default.ScriptTarget.ES2016,module:U.default.ModuleKind.ESNext},transformers:{before:[rt.createBuiltinModuleTransformer(U.default)]}}).outputText;if(n.tailwind&&(t=await Rs(t,{componentId:n.componentId})),n.module===ye.PreloadComponentScriptModule.ESM)return t;const s=U.default.transpileModule(t,{compilerOptions:{jsx:U.default.JsxEmit.React,target:U.default.ScriptTarget.ES2016,module:U.default.ModuleKind.CommonJS,moduleResolution:U.default.ModuleResolutionKind.Node16}}).outputText;return n.module===ye.PreloadComponentScriptModule.CJS?s:Ls(n.moduleName,s)},{keyGenerator:(e,n)=>{const t=Z.createHash("md5").update(e).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==ye.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",t,s])},lruOptions:{max:100,ttl:1e3*60*60*24*7},subdir:"transpileModule"}),xs=async(e,n)=>{var r,u;const s=(u=(r=(await ps.build({entryPoints:["index.tsx"],external:Object.keys(Nt.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(c){let i=null;c.onResolve({filter:/.*/},d=>d.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:d.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),c.onLoad({filter:/.*/,namespace:"vfs"},async d=>{var E;if(d.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(d.path==="component.tsx")return{contents:e,loader:"tsx"};if(rt.isRelativeModule(d.path)){const f=d.path.split("/").pop();if(i||(i=await _e({ensureLoaded:!1})),(E=i==null?void 0:i.chunks)!=null&&E[f])try{const p=w.readFileSync(i.chunks[f],"utf-8");return y.info("get chunk from local file system",f),{contents:p,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:r[0])==null?void 0:u.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return U.default.transpileModule(o,{compilerOptions:{module:U.default.ModuleKind.ESNext,target:U.default.ScriptTarget.ES2020}}).outputText},pt=Je(async(e,n)=>{const t=await xs(e,n);return new RegExp(`export\\s+\\{[^}]*(?:\\w+\\s+as\\s+${n}\\b|\\b${n}\\b)[^}]*\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,n)=>{const t=Z.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,n])},lruOptions:{max:100,ttl:1e3*60*60*24*7},subdir:"extractExportValueSchema"}),Ls=(e,n)=>`// 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
|
-
${n}
|
|
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
|
-
`,ce=new Pe.LRUCache({max:100}),ut=60*60,Ue=60;function ft(e){y.info("clear preload components cache",{cacheKey:e}),ce.delete(e)}function mt(e){for(const n of ce.keys())n.includes(e)&&(y.info("clear preload components cache",{cacheKey:n}),ft(n))}function ht({mode:e,instanceId:n,componentId:t,locale:s}){return["getPreloadComponents",e,n,t,s].join("-")}async function Ns({mode:e,req:n,state:t,locale:s,instances:o,module:a}){const{supportedLocales:r,config:{defaultLocale:u}}=t;if(!u)return null;const c=(await Promise.all(o.map(async p=>{try{const l=ht({mode:e,instanceId:p.id,componentId:p.componentId,locale:s});if(e!=="draft"&&p.useCache&&ce.has(l))return y.info(`get preload component from cache: ${l}`),ce.get(l);const m=ue({state:t,componentId:p.componentId});if(!m)return null;const b=await gt({req:n,state:t,componentId:m.id,locale:s,defaultLocale:u,properties:p.properties});if(!b)return null;const _={instanceId:p.id,preload:b};if(e!=="draft"&&p.useCache){let P=ut;p.cacheDuration&&(P=p.cacheDuration),y.info(`set preload component to cache(${P}s): ${l}`),ce.set(l,_,{ttl:P*1e3})}return _}catch(l){return y.error("get preload component error",{instanceId:p.id,componentId:p.componentId},{error:l}),null}}))).filter(p=>!!p),i=Object.values(c.reduce((p,l)=>({...p,...l.preload.components}),{}));async function d(){const p=await Promise.all(i.map(async l=>{const m=de.componentUMDName({componentId:l.component.id}),b=a===ye.PreloadComponentScriptModule.ESM?{module:a,script:await et(l.script,{componentId:l.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await et(l.script,{componentId:l.component.id,module:a,moduleName:m,tailwind:e!=="draft"}),moduleName:m};return[l.component.id,{component:l.component,script:b}]}));return Object.fromEntries(p)}const E=await d();return{config:{defaultLocale:u,supportedLocales:r},components:E,instances:c.map(p=>({id:p.instanceId,componentId:p.preload.component.id,locales:{[p.preload.locale]:{props:p.preload.props}}}))}}async function gt({req:e,state:n,componentId:t,locale:s,defaultLocale:o,properties:a}){const{supportedLocales:r}=n,u=ue({state:n,componentId:t});if(!u)return null;const c=r.some(d=>d.locale===s)?s:o;if(!c)return null;const i=await yt({req:e,state:n,componentId:t,locale:c,defaultLocale:o,properties:a});return i?{component:u,...i}:null}const Ms=20;async function yt({req:e,depth:n=0,state:t,componentId:s,locale:o,defaultLocale:a,properties:r}){if(n>Ms)throw new RangeError("max component depth exceeded");const u=$s({state:t,componentId:s,properties:r,locale:o});if(!u)return null;const{props:c}=u,i={locale:o||a,components:{[u.component.id]:{component:u.component,script:u.script}},props:{...c}};try{const d=await Fs({...u,req:e});d!=null&&d.props&&Object.assign(i.props,d.props)}catch(d){y.error("preload data at server side error",{componentId:s,name:u.component.name},{error:d})}return await Promise.all(Object.entries(c).map(async([d,E])=>{if((E==null?void 0:E.type)===de.RenderNestedComponent){const f=await yt({req:e,depth:n+1,state:t,componentId:E.componentId,locale:o,defaultLocale:a,properties:E.properties});f&&(Object.assign(i.components,f.components),Object.assign(i.props,{[d]:{type:de.RenderNestedComponent,componentId:E.componentId,props:f.props}}))}})),i}function $s({state:e,componentId:n,locale:t,properties:s}){const o=ue({state:e,componentId:n});if(!o)return null;const a=de.mergeComponent({componentId:n,getComponent:r=>ue({state:e,componentId:r}),locale:t,defaultLocale:e.config.defaultLocale,properties:s});return a?{component:o,script:a.script,props:{locale:t,...a.props}}:null}function ue({state:e,componentId:n}){var t,s,o;return((t=e.components[n])==null?void 0:t.data)??((o=(s=e.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function Us({state:e,name:n}){var s,o;const t=n.toLowerCase();return((s=Object.values(e.components).find(a=>{var r;return((r=a.data.name)==null?void 0:r.toLowerCase())===t}))==null?void 0:s.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var r;return((r=a.component.name)==null?void 0:r.toLowerCase())===t}))==null?void 0:o.component)}async function Fs({component:e,script:n,props:t,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await pt(n,"getServerSideProps");if(!o)return null;const a=o.match(/export\s*{\s*(\w+)\s+as\s+getServerSideProps\s*}/)||o.match(/export\s*{\s*getServerSideProps\s*}/),r=(a==null?void 0:a[1])||"getServerSideProps",u=new Promise(i=>{setTimeout(()=>{i({})},Ue*1e3)});return await Promise.race([u,pe.Sandbox.callFunction({code:`${o}
|
|
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 ${r}(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 pe.BuiltinModules.dayjs},global:{console:{log:(...i)=>{y.info(...i)},warn:(...i)=>{y.warn(...i)},error:(...i)=>{y.error(...i)}},getComponentMountPoint:vt.getComponentMountPoint,joinURL:F.joinURL,withQuery:F.withQuery,getQuery:F.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:F.joinURL(F.withHttps(s.hostname),s.originalUrl)},fetch:(i,{...d}={})=>{const E=typeof i=="string"&&i.startsWith("/")?F.joinURL(C.default.env.appUrl,i):i;if(typeof E=="string"&&F.parseURL(E).host===F.parseURL(C.default.env.appUrl).host){const f=s.get("cookie");if(f){const p=new at.Headers(d.headers);p.set("cookie",f),d.headers=p}}return is.default(E,{...d,timeout:Ue*1e3}).then(f=>({ok:f.ok,status:f.status,statusText:f.statusText,headers:Object.fromEntries(f.headers.entries()),json:()=>f.json()}))},props:t}]})])}const St=pe.memoize(async(e,n,t)=>{if(!(e!=null&&e.includes(n)))return null;const s=await pt(e,n);if(s)try{return await pe.Sandbox.callFunction({code:`
|
|
52
|
-
${s}
|
|
53
|
-
|
|
54
|
-
export function get${n}SchemaWrapper() {
|
|
55
|
-
return ${n};
|
|
56
|
-
}
|
|
57
|
-
`,filename:`${t}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return y.error(`获取 ${n} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,n,t)=>{const s=Z.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,t])},lruOptions:{max:100,ttl:1e3*60*60}}),qs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Fe="page",qe="trigger-reload-project-resource",Ke=qs,Bs="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function be(e){e.observeDeep(n=>{n.some(t=>t.changes.keys.has("updatedAt")||t.changes.keys.has("publishedAt"))||e.set("updatedAt",new Date().toISOString())})}function Et(){return w.mkdtempSync(S.join(C.default.env.dataDir,"tmp-"))}function Ie(e,n,t=[]){return Array.isArray(e)?e.flatMap((s,o)=>Ie(s,n,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([s,o])=>Ie(o,n,[...t,s])):n(e)?[t]:[]}function q(e){return e.filter(n=>n!=null)}function Hs(e){e.pages&&Object.keys(e.pages).forEach(t=>{const s=ee.getYjsValue(e.pages[t]);s&&s instanceof V.Map&&be(s)});const n=ee.getYjsValue(e.pages);n&&n instanceof V.Map&&n.observe(t=>{t.changes.keys.forEach((s,o)=>{if(s.action==="add"){const a=ee.getYjsValue(e.pages[o]);a&&a instanceof V.Map&&be(a)}})})}function Gs(e){e.routes&&Object.keys(e.routes).forEach(t=>{var o;const s=ee.getYjsValue((o=e.routes)==null?void 0:o[t]);s&&s instanceof V.Map&&be(s)});const n=ee.getYjsValue(e.routes);n&&n instanceof V.Map&&n.observe(t=>{t.changes.keys.forEach((s,o)=>{var a;if(s.action==="add"){const r=ee.getYjsValue((a=e.routes)==null?void 0:a[o]);r&&r instanceof V.Map&&be(r)}})})}function Vs(e,n){var t;for(const s of n||Object.keys(e.routes||{})){let o=s,a=[];if(s.includes("-")){const[r,...u]=s.split("-");o=r,a=u||[]}if(((t=e.routes)==null?void 0:t[o])!==void 0){e.routes[o].publishedAt=new Date().toISOString();const r=e.routes[o];if(!r||!r.params||r.params.length===0)continue;if(s.includes("-")&&a.length>0){const u=we.getRouteMetaDataByOptionIds(a,r);u&&(u.publishedAt=new Date().toISOString())}if(!n){const u=we.generateParamCombinations({basePath:r.path,params:r.params,routeId:r.id,paramsOptions:r.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const c of u)c.routeMetaData??(c.routeMetaData={}),c.routeMetaData.publishedAt=new Date().toISOString()}}}}function Le({page:e,route:n,state:t,routeId:s,routePathInfo:o}){var r,u,c,i,d,E,f,p,l;y.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const a={...Gt.cloneDeep(e),id:s,slug:(o==null?void 0:o.path)??n.path,createdAt:n.createdAt,updatedAt:((r=o==null?void 0:o.routeMetaData)==null?void 0:r.updatedAt)??n.updatedAt,publishedAt:((u=o==null?void 0:o.routeMetaData)==null?void 0:u.publishedAt)??n.publishedAt,isPublic:(((c=o==null?void 0:o.routeMetaData)==null?void 0:c.isPublic)??n.isPublic)&&n.isPublic};for(const m of t.supportedLocales){if(n.dataSource){let b=n.id;o&&(b=o.paramOptionIds.join("-"));const _=((E=(d=(i=n.dataSource.pathDataMappings)==null?void 0:i[b])==null?void 0:d.dataCache)==null?void 0:E[m.locale])??((l=(p=(f=n.dataSource.pathDataMappings)==null?void 0:f[b])==null?void 0:p.dataCache)==null?void 0:l[t.config.defaultLocale||"en"]);if(!_)continue;Ht.setPageDataSource(a,t,m.locale,_)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return a}const Ce=new Pe.LRUCache({max:20,ttl:10*60*1e3});function Js(e,n=[]){let t=0;const s=Array.from(Ce.keys()),o=[];for(const a of e){o.push(`page-html:prod:${a}:lang-path=none`);for(const r of n)o.push(`page-html:prod:/${r}${a}:lang-path=${r}`)}for(const a of s){const r=a.split(":lang-path=")[0]||"";for(const u of o){const i=(u.split(":lang-path=")[0]||"").replace(/\/:[^/]+/g,"");if(r.startsWith(i)){Ce.delete(a),t++,y.info(`[Cache CLEAR] key: ${a}`);break}}}return y.info(`[Cache CLEAR] cleared ${t} entries for patterns:`,o),t}function Ks({projectId:e,projectSlug:n,supportedLocales:t=[]}){let s=0;const o=Array.from(Ce.keys()),a=[];a.push(`page-html:prod:/${e}`),n&&n!==e&&a.push(`page-html:prod:/${n}`);for(const r of t)a.push(`page-html:prod:/${r}/${e}`),n&&n!==e&&(n!=="/"?a.push(`page-html:prod:/${r}/${n}`):a.push(`page-html:prod:/${r}`));for(const r of o)for(const u of a)if(r.startsWith(u)){Ce.delete(r),s++,y.info(`[Cache CLEAR PROJECT] key: ${r}`);break}return y.info(`[Cache CLEAR PROJECT] cleared ${s} entries for project ${e}${n?` (slug: ${n})`:""}`),s}const{uploadToMediaKit:zs}=require("@blocklet/uploader-server"),Se=ts.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),ze=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,le=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,tt=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Ys=1e4,Ws=3e4,he=0,Ne=1,Qs=0,Xs=1,Be=C.default,se=S.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Zs=["production","draft"],en=["production"];function Oe(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function tn(){var t;const e=Be.env.languages.map(s=>({locale:s.code,name:s.name})),n=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:e,config:{defaultLocale:n},resources:{}}}const j=class j extends V.Doc{constructor(t){super();v(this,"syncedStore");v(this,"conns",new Map);v(this,"awareness");v(this,"releaseTimer");v(this,"awarenessChangeHandler",({added:t,updated:s,removed:o},a)=>{const r=t.concat(s,o);if(a!==null){const i=this.conns.get(a);i&&(t.forEach(d=>{i.add(d)}),o.forEach(d=>{i.delete(d)}))}const u=x.createEncoder();x.writeVarUint(u,Ne),x.writeVarUint8Array(u,ie.encodeAwarenessUpdate(this.awareness,r));const c=x.toUint8Array(u);this.conns.forEach((i,d)=>this.send(d,c))});v(this,"updateHandler",t=>{const s=x.createEncoder();x.writeVarUint(s,he),Re.writeUpdate(s,t);const o=x.toUint8Array(s);this.conns.forEach((a,r)=>this.send(r,o))});v(this,"ensureDataStructure",()=>{var c;const{supportedLocales:t,pages:s,pageIds:o,config:a,routes:r,routeIds:u}=this.syncedStore;{const i=new Set(Object.keys(s));let d=0;for(;d<o.length;){const E=o[d];i.has(E)?(i.delete(E),d++):o.splice(d,1)}}{const i=new Set(Object.keys(r));let d=0;for(;d<u.length;){const E=u[d];i.has(E)?(i.delete(E),d++):u.splice(d,1)}}t.splice(0,t.length),t.push(...Be.env.languages.map(i=>({locale:i.code,name:i.name}))),a.defaultLocale=(c=t[0])==null?void 0:c.locale;{let i=0;const d=new Set;for(;i<t.length;){const{locale:E}=t[i];d.has(E)?t.splice(i,1):(i++,d.add(E))}}});v(this,"send",(t,s)=>{t.readyState!==Qs&&t.readyState!==Xs&&this.closeConn(t);try{t.send(s,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}});v(this,"closeConn",t=>{if(t.removeAllListeners(),this.conns.has(t)){const s=this.conns.get(t);this.conns.delete(t),s&&ie.removeAwarenessStates(this.awareness,Array.from(s),null)}t.close(),this.checkAndScheduleRelease()});v(this,"autoSave",ct.default(()=>{w.mkdirSync(S.dirname(this.draftYjsFilePath),{recursive:!0}),w.writeFileSync(this.draftYjsFilePath,V.encodeStateAsUpdate(this))},Ys));v(this,"save",({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()});v(this,"publish",async({mode:t,routes:s})=>{const o=await this.getState("draft"),a=await this.getState("production");await He(o,a,{routes:s,mergeMode:"replace",deleteRoutes:!0,publishMode:t}),a.config.publishedAt=new Date().getTime(),Vs(this.syncedStore,s),await this.setState(t,a),await this.clearPageCacheForRoutes(s,a)});v(this,"mergeState",async(t,s)=>{var u,c,i;const o=JSON.parse(JSON.stringify(s));(u=t.config).fontFamily??(u.fontFamily={});const a=(c=o.config)==null?void 0:c.fontFamily,r=(i=t.config)==null?void 0:i.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(r==null?void 0:r.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(r==null?void 0:r.description),await new Promise((d,E)=>{this.transact(async()=>{try{const f=await He(t,s);d(f)}catch(f){E(f)}})})});v(this,"clearPageCacheForRoutes",async(t,s)=>{const o=S.basename(this.options.path),a=await K.findByPk(o),r=(a==null?void 0:a.slug)||o;if(y.info(`[SiteState] clearing page cache for project ${o}, routes:`,t||[]),!t||t.length===0){Ks({projectId:o,projectSlug:r,supportedLocales:s.supportedLocales.map(d=>d.locale)});return}const u=s.supportedLocales.map(d=>d.locale),c=[],i=t.filter(d=>s.pages[d]);for(const d of i){const f=s.pages[d].slug;r&&r!==o&&(r==="/"?c.push(f):c.push(`/${r}${f}`)),c.push(`/${o}${f}`)}if(y.info(`[SiteState] clearing page cache for project ${o}, pathPatterns:`,c),c.length>0){const d=Js(c,u);y.info(`[SiteState] cleared ${d} page cache entries for project ${o}, routes:`,t)}});v(this,"addConnection",t=>{if(this.conns.has(t))return;this.cancelRelease(),t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",a=>this.messageListener(t,new Uint8Array(a)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){s=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},Ws);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{s=!0});{const a=x.createEncoder();x.writeVarUint(a,he),Re.writeSyncStep1(a,this),this.send(t,x.toUint8Array(a));const r=this.awareness.getStates();if(r.size>0){const u=x.createEncoder();x.writeVarUint(u,Ne),x.writeVarUint8Array(u,ie.encodeAwarenessUpdate(this.awareness,Array.from(r.keys()))),this.send(t,x.toUint8Array(u))}}});v(this,"messageListener",(t,s)=>{try{const o=x.createEncoder(),a=xe.createDecoder(s),r=xe.readVarUint(a);switch(r){case he:x.writeVarUint(o,he),Re.readSyncMessage(a,o,this,null),x.length(o)>1&&(this.ensureDataStructure(),this.send(t,x.toUint8Array(o)));break;case Ne:{ie.applyAwarenessUpdate(this.awareness,xe.readVarUint8Array(a),t);break}default:y.warn(`Unsupported messageType ${r}`)}}catch(o){y.error(o)}this.save()});this.options=t,w.existsSync(this.draftYjsFilePath)&&V.applyUpdate(this,w.readFileSync(this.draftYjsFilePath)),this.syncedStore=Vt.reactive(ee.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new ie.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(t){if(!t)throw new Error("Should provide project context");try{const s=S.join(se,t),o=S.join(se,`@del-${t}`);w.renameSync(s,o)}catch(s){y.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return Me.globSync("*/",{cwd:se,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(t=>j.shared(t))}static shared(t){if(!t)throw new Error("Should provide project context");let s=j.sharedInstances[t];return s||(s=new j({path:S.join(se,t)}),j.sharedInstances[t]=s,jt({projectId:t,pages:je,components:De}),s)}static async getProductionState(t){var o,a;let s=j.productionStates.get(t);if(!s){const r=S.join(se,t,"production");if(s=await Ye(r,{includeResources:!0})??tn(),!((o=s==null?void 0:s.config)!=null&&o.defaultLocale)){s.config??(s.config={});const u=Be.env.languages.map(c=>({locale:c.code,name:c.name}));s.config.defaultLocale=(a=u[0])==null?void 0:a.locale}j.productionStates.set(t,s)}return{...s,resources:await _e().then(async r=>{var E,f;const{pages:u,components:c}=hs.default(r,"pages","components");let i=c;const d=await K.findByPk(t);if(d!=null&&d.useAllResources)i=c;else{const l=(await Te.findAll({where:{projectId:t}})).map(b=>b.componentId);i=Object.fromEntries(Object.entries(c||{}).filter(([b])=>l.includes(b)))}return Object.keys(((E=s==null?void 0:s.resources)==null?void 0:E.components)||{}).length>0&&(i={...i,...(f=s==null?void 0:s.resources)==null?void 0:f.components}),{pages:u,components:i}}).catch(()=>({}))}}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((s,o)=>this.closeConn(o)),this.awareness.destroy();const t=S.basename(this.options.path);delete j.sharedInstances[t],super.destroy()}initObserver(){Hs(this.syncedStore),Gs(this.syncedStore)}get draftYjsFilePath(){return S.join(this.options.path,"draft.yjs")}static async getStateByProjectId(t,s){if(s==="draft"){const o=j.shared(t);return JSON.parse(JSON.stringify(o.syncedStore))}return j.getProductionState(t)}async getState(t){if(t==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const s=S.basename(this.options.path);return j.getProductionState(s)}async setState(t,s){const o=await Ct(s,{exportAssets:!1,includeResources:!0}),a=this.getPublishDir(t);if(w.mkdirSync(S.dirname(a),{recursive:!0}),w.rmSync(a,{force:!0,recursive:!0}),w.renameSync(o,a),t==="production"){const r=S.basename(this.options.path);j.productionStates.set(r,s)}}getPublishDir(t){return S.join(this.options.path,t)}checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const t=S.basename(this.options.path);this.releaseTimer=setTimeout(()=>{y.info(`[SiteState] releasing instance due to no active connections: ${t}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),y.info(`[SiteState] scheduled release for project ${t} in ${j.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const t=S.basename(this.options.path);y.info(`[SiteState] cancelled scheduled release for project ${t}`)}}static async pageUrlMap(t,s){var r,u;let{projectIds:o}=this;s&&(o=[s]);const a={};for(const c of o){const i=await K.findByPk(c);if(!i)continue;const d=await j.getStateByProjectId(c,t),E=i.slug||c,f=gs.default(C.default.env.languages.map(l=>l.code),d.supportedLocales.map(l=>l.locale)),p=(l,m)=>{E&&(a[F.joinURL("/",E,l)]={...m,shouldRedirect:!0,mainPage:!0}),a[F.joinURL("/",c,l)]={...m,shouldRedirect:!0,mainPage:!0};for(const b of f){const _={...m,locale:b};a[F.joinURL("/",b,c,l)]=_,E&&(a[F.joinURL("/",b,E,l)]=_)}};if(t==="draft")for(const l of d.routeIds||[]){const m=(r=d==null?void 0:d.routes)==null?void 0:r[l];if(!m)continue;if(m.params&&m.params.length>0){const P=we.generateParamCombinations({basePath:m.path,params:m.params,routeId:m.id,paramsOptions:m.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const M of P){const Y=M.path,te={projectId:c,projectSlug:E,pageSlug:Y,pageId:m.displayTemplateId||"",routeId:l,defaultLocale:f==null?void 0:f[0],locales:f,publishedAt:d.config.publishedAt,isPublic:m.isPublic&&((u=M==null?void 0:M.routeMetaData)==null?void 0:u.isPublic)};p(Y,te)}}const b=m.path,_={projectId:c,projectSlug:E,pageSlug:b,pageId:m.displayTemplateId||"",routeId:l,defaultLocale:f==null?void 0:f[0],locales:f,publishedAt:d.config.publishedAt,isPublic:m.isPublic};p(b,_)}for(const l of d.pageIds){const m=d.pages[l];if(!m||t==="production"&&!m.isPublic)continue;const b=m.slug,_=i.slug||c,P={projectId:c,projectSlug:_,pageSlug:b,pageId:l,defaultLocale:f==null?void 0:f[0],locales:f,publishedAt:d.config.publishedAt,isPublic:m.isPublic,templateConfig:m.templateConfig};p(b,P)}}return a}getDocumentSize(){return V.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const t=[];for(const[s,o]of Object.entries(j.sharedInstances)){const a=o.getDocumentSize();t.push({projectId:s,sizeInBytes:a,sizeInMB:`${(a/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return t}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),y.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,y.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const t=Object.keys(j.sharedInstances).length,s=[],o=[];for(const[a,r]of Object.entries(j.sharedInstances))r.conns.size===0?s.push({projectId:a,instance:r}):o.push({projectId:a,connections:r.conns.size});if(y.info(`[SiteState] periodic check summary: total instances: ${t}, with connections: ${o.length}, without connections: ${s.length}`),s.length>0){y.info(`[SiteState] releasing ${s.length} instances without connections:`,s.map(r=>r.projectId));let a=0;for(const{projectId:r,instance:u}of s)try{y.info(`[SiteState] releasing instance due to periodic check: ${r}`),u.destroy(),a++}catch(c){y.error(`[SiteState] failed to release instance ${r} during periodic check:`,c)}y.info(`[SiteState] periodic check completed: ${a}/${s.length} instances released successfully`)}else t>0?y.debug("[SiteState] periodic check: all instances have active connections"):y.debug("[SiteState] periodic check: no instances exist")}};v(j,"PRODUCTION_CACHE_TTL",7*24*60*60*1e3),v(j,"RELEASE_DELAY",5*60*1e3),v(j,"PERIODIC_CHECK_INTERVAL",2*60*60*1e3),v(j,"sharedInstances",{}),v(j,"productionStates",new Pe.LRUCache({max:100,ttl:j.PRODUCTION_CACHE_TTL})),v(j,"periodicCheckTimer");let z=j;async function sn(e,n,t){if(!e||!w.existsSync(e)||!w.lstatSync(e).isFile())return null;let s=t[e];return s||(s=(async()=>{var o;try{const a=(o=await zs({filePath:e,fileName:n}))==null?void 0:o.data;return a==null?void 0:a.filename}catch(a){return y.error(`Failed to upload asset ${e}:`,a),null}})(),t[e]=s),s}const wt=async(e,n)=>{const t=S.basename(e),s=await Ge.call({name:Ke,path:F.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=w.createWriteStream(n);await ns.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},bt=async(e,n)=>{await Promise.all(e.map(async t=>{try{await wt(t,S.join(n,S.basename(t)))}catch(s){y.error(`Failed to export assets: ${t}, ${s}`)}}))};function It(e){return ze.test(e)?[e]:le.test(e)?(tt.lastIndex=0,Array.from(e.matchAll(tt)).map(t=>t[1]).filter(t=>!!t)):[]}async function ge(e,n,t){const{getFilename:s,exportAssets:o}=t,a=S.join(n,s(e));if(w.mkdirSync(S.dirname(a),{recursive:!0}),w.writeFileSync(a,ne.stringify(e)),o){const u=Ie(e,c=>typeof c=="string"&&(ze.test(c)||le.test(c))).map(c=>{const i=Ve.default(e,c);return It(i)}).flat().filter(Boolean);await bt(u,S.dirname(a))}}const st=new Pe.LRUCache({max:20,ttl:30*24*60*60*1e3});async function nt(e,n,t){var u;const s=Ie(e,c=>typeof c=="string"&&(ze.test(c)||le.test(c))),o=ys.default(2),a=s.map(c=>o(async()=>{try{const i=Ve.default(e,c),d=It(i);for(const E of d){const f=S.basename(E),p=t.getFilePath(E,c),l=p?`${p}:${f}`:f,m=st.get(l);if(m){le.test(i)||Xe.default(e,c,m);return}const b=await sn(p,f,n);b&&(le.test(i)||Xe.default(e,c,b),st.set(l,b))}}catch(i){y.error(`Failed to process upload for path ${c.join(".")}:`,i.message||i.reason)}})),r=await Promise.allSettled(a);(u=t.onFinish)==null||u.call(t,r)}async function Ct(e,{exportAssets:n,pageIds:t="all",componentIds:s="all",rawConfig:o,includeResources:a=!1,routeIds:r="all"}={}){var ae,I,h,A,D,W,O,N,B,Q,J,re;const u=t==="all"?e.pageIds:t,c=de.getComponentDependencies({state:e,pageIds:u,componentIds:s==="all"?Object.keys(e.components):s}),i=r==="all"?e.routeIds:r,d=g=>({id:g.id,name:g.name,isTemplateSection:g.isTemplateSection??!1,templateDescription:g.templateDescription,llmConfig:g.llmConfig,component:g.component,config:g.config,visibility:g.visibility,sections:g.sections,sectionIds:g.sectionIds}),E=(g,T)=>{var R;return{id:g.id,createdAt:g.createdAt,updatedAt:g.updatedAt,publishedAt:g.publishedAt,isPublic:g.isPublic??!0,templateConfig:g.templateConfig,meta:((R=g.locales)==null?void 0:R[T])??{},sections:q(g.sectionIds.map(H=>{const $=g.sections[H];return $&&d($)})),dataSource:Object.fromEntries(Object.entries(g.dataSource||{}).map(([H,$])=>[H,($==null?void 0:$[T])??{}]))}},f=g=>({id:g.id,createdAt:g.createdAt,updatedAt:g.updatedAt,publishedAt:g.publishedAt,path:g.path,handler:g.handler,isPublic:g.isPublic??!0,params:g.params??[],enabledGenerate:g.enabledGenerate??!1,displayTemplateId:g.displayTemplateId,dataSource:g.dataSource}),p=q(i.map(g=>{const T=e.routes[g];return T&&f(T)})),l=q(e.supportedLocales.map(g=>g.locale).flatMap(g=>u.map(T=>{const R=e.pages[T];return R&&{locale:g,slug:R.slug,page:E(R,g)}}))),m=Et(),b=S.join(m,"pages");w.mkdirSync(b,{recursive:!0});const _=S.join(m,"components");w.mkdirSync(_,{recursive:!0});const P=S.join(m,"routes");w.mkdirSync(P,{recursive:!0});for(const{locale:g,slug:T,page:R}of l)await ge(R,b,{getFilename:()=>`${Oe(T)||"index"}.${g}.yml`,exportAssets:n});for(const g of p)await ge(g,P,{getFilename:()=>`${Oe(g.path)||"index"}.yml`,exportAssets:n});for(const g of c){const T=(ae=e.components[g])==null?void 0:ae.data;T&&await ge(T,_,{getFilename:R=>`${R.name||"unnamed"}.${R.id}.yml`,exportAssets:n})}const M=S.join(m,".blocklet/pages/pages.config.yml");w.mkdirSync(S.dirname(M),{recursive:!0});const Y={pages:q(u.map(g=>{const T=e.pages[g];return T&&{id:g,slug:T.slug}})),routes:q(i.map(g=>{const T=e.routes[g];return T&&{id:g,path:T.path}})),components:q(c.map(g=>{var R;const T=(R=e.components[g])==null?void 0:R.data;return T&&{id:g,name:T.name}})),...a?{resources:{components:q(Object.keys(((I=e.resources)==null?void 0:I.components)||{}).filter(g=>c.includes(g)).map(g=>{var T,R,H,$;return{id:g,name:($=(H=(R=(T=e.resources)==null?void 0:T.components)==null?void 0:R[g])==null?void 0:H.component)==null?void 0:$.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};w.writeFileSync(M,ne.stringify(Y));const te=S.join(m,"config.source.json");if(o&&w.writeFileSync(te,JSON.stringify(o)),a){const g=S.join(m,"resources"),T=S.join(g,"components");w.mkdirSync(T,{recursive:!0});for(const $ of Object.keys(((h=e==null?void 0:e.resources)==null?void 0:h.components)??{}).filter(G=>c.includes(G))){const G=(W=(D=(A=e.resources)==null?void 0:A.components)==null?void 0:D[$])==null?void 0:W.component;G&&await ge(G,T,{getFilename:X=>`${X.name||"unnamed"}.${X.id}.yml`,exportAssets:n})}const R=S.join(m,"chunks");w.mkdirSync(R,{recursive:!0});const{chunks:H}=await _e();for(const $ of Object.keys(((O=e==null?void 0:e.resources)==null?void 0:O.components)??{}).filter(G=>c.includes(G))){const G=(Q=(B=(N=e.resources)==null?void 0:N.components)==null?void 0:B[$])==null?void 0:Q.component;if(G&&((J=G.renderer)==null?void 0:J.type)==="react-component"){const X=((re=G.renderer)==null?void 0:re.chunks)??[];if((X==null?void 0:X.length)>0)for(const ke of X){const Qe=S.join(R,ke),ve=H==null?void 0:H[ke];try{ve&&w.existsSync(ve)&&!w.existsSync(Qe)&&w.copyFileSync(ve,Qe)}catch(Dt){y.error(`copy chunk ${ke} error`,Dt.message)}}}}}return m}async function Ye(e,{importAssets:n,includeResources:t}={}){var a,r,u,c;if(!w.existsSync(e))return null;let s,o=!1;try{w.lstatSync(e).isDirectory()?s=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,s=Et(),await os.x({file:e,C:s}));const i=Me.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),d=i&&S.join(S.dirname(i),"../../pages"),E=i&&S.join(S.dirname(i),"../../components"),f=i&&S.join(S.dirname(i),"../../chunks"),p=i&&S.join(S.dirname(i),"../../routes");if(!i)return null;const l=ne.parse(w.readFileSync(i).toString()),m=(I,h,A)=>{let D=S.join(I,`${h}${A?`.${A}`:""}.yml`);return(!w.existsSync(D)||!w.lstatSync(D).isFile())&&(D=S.join(I,h,`index${A?`.${A}`:""}.yml`),!w.existsSync(D)||!w.lstatSync(D))?null:ne.parse(w.readFileSync(D).toString())},b=(I,h)=>{try{const A=Me.globSync(`*.${h}.yml`,{cwd:I,absolute:!0})[0];return A?ne.parse(w.readFileSync(A).toString()):null}catch(A){y.error("parse component error",A)}return null},_=(I,h)=>{let A=S.join(I,`${h}.yml`);return(!w.existsSync(A)||!w.lstatSync(A).isFile())&&(A=S.join(I,h,"index.yml"),!w.existsSync(A)||!w.lstatSync(A))?null:ne.parse(w.readFileSync(A).toString())},P=q(l.pages.map(({slug:I})=>{var W;const h=q(l.supportedLocales.map(({locale:O})=>{const N=d?m(d,Oe(I),O):void 0;if(N)return{locale:O,page:N};const B=d?m(d,I,O):void 0;return B&&{locale:O,page:B}})),A=(W=h[0])==null?void 0:W.page;if(!A)return null;const D=A.sections.map(O=>({id:O.id||Se(),component:O.component,config:O.config,name:O.name,isTemplateSection:O.isTemplateSection??!1,templateDescription:O.templateDescription,llmConfig:O.llmConfig,visibility:O.visibility,sections:O.sections,sectionIds:O.sectionIds}));return{id:A.id||Se(),createdAt:A.createdAt,updatedAt:A.updatedAt,publishedAt:A.publishedAt,isPublic:A.isPublic??!0,templateConfig:A.templateConfig,slug:I,sections:Object.fromEntries(D.map(O=>[O.id,O])),sectionIds:D.map(O=>O.id),locales:Object.fromEntries(h.map(({locale:O,page:N})=>[O,N.meta])),dataSource:A.dataSource?Object.fromEntries([...new Set(h.flatMap(({page:O})=>Object.keys(O.dataSource??{})))].map(O=>[O,Object.fromEntries(h.map(({locale:N,page:B})=>{var J;const Q=(J=B.dataSource)==null?void 0:J[O];return[N,Q||{}]}))])):Object.fromEntries([...new Set(h.flatMap(({page:O})=>O.sections.map(N=>N.id)))].map(O=>[O,Object.fromEntries(h.map(({locale:N,page:B})=>{var re;const Q=(re=B.dataSource)==null?void 0:re[O];if(Q)return[N,Q];const J=B.sections.find(g=>g.id===O);return[N,(J==null?void 0:J.properties)||{}]}))]))}})),M=q(((a=l==null?void 0:l.routes)==null?void 0:a.map(({path:I})=>{const h=p?_(p,Oe(I)):void 0;return{...h,id:(h==null?void 0:h.id)||Se(),createdAt:(h==null?void 0:h.createdAt)??new Date().toISOString(),updatedAt:(h==null?void 0:h.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(h==null?void 0:h.path)??`/${h==null?void 0:h.id}`,params:h==null?void 0:h.params,handler:(h==null?void 0:h.handler)??"Pages Kit",isPublic:(h==null?void 0:h.isPublic)??!0,enabledGenerate:(h==null?void 0:h.enabledGenerate)??!1,displayTemplateId:(h==null?void 0:h.displayTemplateId)??void 0,dataSource:(h==null?void 0:h.dataSource)??{}}}))??[]),Y=E?q(((r=l.components)==null?void 0:r.map(({id:I})=>b(E,I)))??[]):[];if(n){const I=(...h)=>{y.info(`[${o?S.basename(e):S.basename(S.join(e,"../../../../"))}] importAssets:`,...h)};try{I("wait image-bin api ready"),await Ss.default({resources:[`${Ge.getComponentWebEndpoint(Es)}/api/sdk/uploads`],validateStatus:D=>D>=200&&D<=500}),I("image-bin api is ready");const h={},A={};I("start to upload assets"),await Promise.allSettled([nt(Y,h,{getFilePath:D=>E&&S.join(E,D),onFinish:D=>{I(`upload ${D.length} component assets`)}}),nt(P,A,{getFilePath:(D,W)=>{const O=Ve.default(P,W.slice(0,1));return d&&S.join(d,S.dirname(O.slug),D)},onFinish:D=>{I(`upload ${D.length} page assets`)}})]),I("upload assets done"),global.gc&&global.gc()}catch(h){I("Error during asset import:",h)}}const te={};if(t){const I=i&&S.join(S.dirname(i),"../../resources/components"),h=q(((c=(u=l.resources)==null?void 0:u.components)==null?void 0:c.map(({id:A})=>b(I,A)))??[]);h.length>0&&(te.components=Object.fromEntries(h.map((A,D)=>[A.id,{index:D,component:A}])))}const ae={};if(f&&w.existsSync(f)){const I=w.readdirSync(f);for(const h of I)ae[h]=S.join(f,h)}return{supportedLocales:l.supportedLocales,pageIds:P.map(I=>I.id),components:Object.fromEntries(Y.map((I,h)=>[I.id,{index:h,data:I}])),pages:Object.fromEntries(P.map(I=>[I.id,I])),config:l.config||{},resources:te,chunks:ae,routeIds:M.map(I=>I.id),routes:Object.fromEntries(M.map(I=>[I.id,I])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&w.rmSync(s,{force:!0,recursive:!0})}}async function He(e,n,{routes:t,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:a=void 0}={}){try{a&&mt(a)}catch(f){y.error("clear preload page cache error",{error:f})}const{pages:r,pageIds:u,routeIds:c,routes:i,supportedLocales:d}=e;if(a==="production"){let f=t??[],p=null;for(const l of c??[]){const m=i==null?void 0:i[l];if(m!=null&&m.params&&(m==null?void 0:m.params.length)>0&&(m!=null&&m.paramsOptions)&&(m==null?void 0:m.paramsOptions.length)>0){const b=we.generateParamCombinations({basePath:m.path,params:m.params,routeId:m.id,paramsOptions:m.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),_=Object.fromEntries(b.map(P=>[`${l}-${P.paramOptionIds.join("-")}`,P]));p={...p||{},..._},t||(f=[...f,...b.map(P=>`${l}-${P.paramOptionIds.join("-")}`)])}else t||f.push(l)}y.info("routeIds to be published: ",f);for(const l of f){let m=l;if(m.includes("-")){const[P]=m.split("-");m=P}const b=i==null?void 0:i[m];if(!b){const P=n.pageIds.indexOf(m);P!==-1&&o&&(n.pageIds.splice(P,1),delete n.pages[m]);for(const M of n.pageIds)M.includes(`${m}-`)&&(n.pageIds.splice(n.pageIds.indexOf(M),1),delete n.pages[M]);y.info("delete main route page",m);continue}if(l.includes("-")&&!(p!=null&&p[l])){const P=n.pageIds.indexOf(l);P!==-1&&o&&(n.pageIds.splice(P,1),delete n.pages[l]),y.info("delete page",l);continue}if(!b.displayTemplateId){y.info("no display template",l);continue}const _=r[b.displayTemplateId];if(!_){y.info("no template page",l);continue}if(n.pageIds.includes(l)){if(y.info("has need update page",l),s==="replace")n.pages[l]=Le({page:_,route:b,state:e,routeId:l,routePathInfo:p==null?void 0:p[l]}),y.info("replace page",l);else if(s==="byUpdateTime"){const P=n.pages[b.id];(!P||b.updatedAt&&b.updatedAt>P.updatedAt)&&(n.pages[l]=Le({page:_,route:b,state:e,routeId:l,routePathInfo:p==null?void 0:p[l]}),y.info("replace page by update time",l))}}else n.pageIds.push(l),n.pages[l]=Le({page:_,route:b,state:e,routeId:l,routePathInfo:p==null?void 0:p[l]}),y.info("add page",l)}if(o&&!t)for(const l of n.pageIds)f!=null&&f.includes(l)||(delete n.pages[l],y.info("delete page",l)),n.pageIds=[...n.pageIds].filter(m=>f==null?void 0:f.includes(m))}else{for(const f of u){const p=r[f];if(p)if(n.pageIds.includes(p.id)){if(s==="replace")n.pages[p.id]=p;else if(s==="byUpdateTime"){const l=n.pages[p.id];(!l||p.updatedAt&&p.updatedAt>l.updatedAt)&&(n.pages[p.id]=p)}}else n.pageIds.push(p.id),n.pages[p.id]=p}for(const f of c){const p=i[f];if(p)if(n.routeIds.includes(p.id)){if(s==="replace")n.routes[p.id]=p;else if(s==="byUpdateTime"){const l=n.routes[p.id];(!l||p.updatedAt&&p.updatedAt>l.updatedAt)&&(n.routes[p.id]=p)}}else n.routeIds.push(p.id),n.routes[p.id]=p}}if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...ms.default(d)),o)for(const f of Object.keys(n.components))delete n.components[f];let E=JSON.parse(JSON.stringify(e.components));E=Object.fromEntries(await Promise.all(Object.entries(E).map(async([f,p])=>{const l=await Ot(p==null?void 0:p.data);return[f,{...p,data:l}]}))),Object.assign(n.components,E),Object.assign(n.config,JSON.parse(JSON.stringify(e.config))),lt.default(e.resources.components)||(n.resources.components=JSON.parse(JSON.stringify(e.resources.components||{})))}const Ot=Je(async e=>{var n;if(!lt.default(e==null?void 0:e.properties))return e;if(((n=e==null?void 0:e.renderer)==null?void 0:n.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t&&t.includes("PROPERTIES_SCHEMA"))try{const s=await St(t,"PROPERTIES_SCHEMA",e.id);s&&s.length>0&&e&&(e.properties={},s.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(s){y.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:s})}}return e},{keyGenerator:e=>{var i,d,E,f;const n=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",s=((i=e==null?void 0:e.renderer)==null?void 0:i.type)||"",o=(e==null?void 0:e.properties)||{},a=(e==null?void 0:e.updatedAt)||"",r=Z.createHash("md5").update(JSON.stringify(o)).digest("hex");let u="",c="";return((d=e==null?void 0:e.renderer)==null?void 0:d.type)==="react-component"&&(u=Z.createHash("md5").update(((E=e==null?void 0:e.renderer)==null?void 0:E.script)||"").digest("hex"),c=Z.createHash("md5").update(((f=e==null?void 0:e.renderer)==null?void 0:f.editComponent)||"").digest("hex")),JSON.stringify(["checkPropertiesFromCode",n,t,s,r,a,u,c])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"checkPropertiesFromCode"});let Ae,oe,je,De,We;function At(){return Ae=(async()=>{const e=Ge.getResources({types:[{did:Ke,type:Fe},{did:Bs,type:Fe}]});oe=(await Promise.all(e.map(async t=>{const s=t.path?await Ye(t.path,{importAssets:!1}):void 0;return s?{blockletId:t.did,state:s,blockletTitle:t.title}:void 0}))).filter(t=>!!t),je=oe.reduce((t,s)=>Object.assign(t,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=oe.reduce((t,s)=>Object.assign(t,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});De=Object.fromEntries(await Promise.all(Object.entries(n).map(async([t,s])=>{const o=await Ot(s.component);return[t,{...s,component:o}]}))),We=oe.reduce((t,s)=>Object.assign(t,s.state.chunks),{})})(),Ae}function Pt(e){const n=ct.default(async()=>{await At().catch(t=>{y.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:oe,pages:je,components:De,chunks:We}))},3e3,{leading:!1,trailing:!0});return n(),C.default.events.on(C.default.Events.componentAdded,n),C.default.events.on(C.default.Events.componentRemoved,n),C.default.events.on(C.default.Events.componentStarted,n),C.default.events.on(C.default.Events.componentStopped,n),C.default.events.on(C.default.Events.componentUpdated,n),C.default.events.on(qe,n),()=>{C.default.events.off(C.default.Events.componentAdded,n),C.default.events.off(C.default.Events.componentRemoved,n),C.default.events.off(C.default.Events.componentStarted,n),C.default.events.off(C.default.Events.componentStopped,n),C.default.events.off(C.default.Events.componentUpdated,n),C.default.events.off(qe,n)}}const Tt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),Ee=globalThis;var ot;(ot=Ee[Tt])==null||ot.call(Ee);Ee[Tt]=Pt(async({pages:e,components:n})=>{const{projectIds:t}=z;y.info(`start update resource states projects(${t.length})`,t),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(t.map(async s=>{jt({projectId:s,pages:e,components:n})}))]).catch(s=>{y.error("update resource states failed:",s)})});z.startPeriodicCheck();process.on("beforeExit",()=>{z.stopPeriodicCheck()});process.on("SIGINT",()=>{z.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{z.stopPeriodicCheck(),process.exit(0)});async function jt({projectId:e,pages:n,components:t}){const s=z.sharedInstances[e];if(!s){y.info(`projectId: ${e} not found in sharedInstances`);return}s.syncedStore.resources.pages=n;const o=await K.findByPk(e);if(o!=null&&o.useAllResources)s.syncedStore.resources.components=t;else{const r=(await Te.findAll({where:{projectId:e}})).map(c=>c.componentId),u=Object.fromEntries(Object.entries(t||{}).filter(([c])=>r.includes(c)));s.syncedStore.resources.components=u}y.info(`update [${e}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}async function nn(){y.info("trigger reload all project resource"),C.default.events.emit(qe)}async function _e({ensureLoaded:e=!0}={}){return e&&(Ae??(Ae=At()),await Ae),{states:oe,pages:je,components:De,chunks:We}}exports.COMPONENT_DID=Ke;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=ut;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ue;exports.PUBLISH_MODES=en;exports.Project=K;exports.RESOURCE_TYPE=Fe;exports.SITE_STATE_PATH=se;exports.STATE_MODES=Zs;exports.SiteState=z;exports.clearPreloadComponentsCache=ft;exports.clearPreloadComponentsCacheByMode=mt;exports.downloadAsset=wt;exports.downloadAssets=bt;exports.fromPackage=Ye;exports.getComponentFromState=ue;exports.getComponentFromStateByName=Us;exports.getExportSchemaValueFromCode=St;exports.getMultiTenantAllProjectAccessPassports=Is;exports.getPreloadComponent=gt;exports.getPreloadComponents=Ns;exports.getPreloadComponentsCacheKey=ht;exports.getResourceStates=_e;exports.initPackResourceStates=Pt;exports.isMultiTenant=bs;exports.logger=y;exports.mergeState=He;exports.nextId=Se;exports.toPackage=Ct;exports.triggerReloadAllProjectResource=nn;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const D=require("react/jsx-runtime"),U=require("@mui/material"),R=require("ufo"),ee=require("@blocklet/js-sdk"),te=require("lodash/isEmpty"),oe=require("yaml"),ne=require("@arcblock/ux/lib/Locale/context"),J=require("@blocklet/pages-kit-core"),W=require("@syncedstore/core"),re=require("@syncedstore/react"),ce=require("ahooks"),x=require("immer"),se=require("lodash/cloneDeep"),ie=require("lodash/debounce"),ae=require("nanoid"),m=require("react"),V=require("react-router-dom"),de=require("y-indexeddb"),le=require("y-websocket"),ue=require("yjs");require("@blocklet/pages-kit/types");const A=o=>o&&o.__esModule?o:{default:o};function fe(o){if(o&&o.__esModule)return o;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const l in o)if(l!=="default"){const P=Object.getOwnPropertyDescriptor(o,l);Object.defineProperty(n,l,P.get?P:{enumerable:!0,get:()=>o[l]})}}return n.default=o,Object.freeze(n)}const me=A(te),Se=fe(oe),pe=A(W),G=A(se),K=A(ie),ge=o=>{const n=blocklet==null?void 0:blocklet.componentMountPoints.find(l=>l.name===o);return n?n.mountPoint:"/"};function N(){const{pathname:o}=window.location,n=o.match(/\/admin\/(maker|previewer)\/([^/]+)/),l=n==null?void 0:n[2],P=window.__PROJECT_ID__;if(!l&&!P)throw new Error("Unable to get projectId from pathname");return l||P}function Pe(o){return`${o}:pages:version`}function we(o,n){return n==="yaml"?me.default(o)?"":Se.stringify(o,{indent:2}):n==="json"?JSON.parse(JSON.stringify(o||{})):n==="array"?JSON.parse(JSON.stringify(o||[])):o}function Ie({error:o}){return D.jsx(U.Box,{children:D.jsx(U.Alert,{severity:"error",children:o.message})})}var B;const q=((B=window.blocklet)==null?void 0:B.prefix)||"/",T=ee.createAxios({timeout:200*1e3}),ye=window.location.protocol==="https:"?"wss":"ws",he=o=>R.joinURL(`${ye}://${window.location.hostname}`,q,`api/${o}/ws/pages`),Ce="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var F;(F=blocklet==null?void 0:blocklet.componentMountPoints.find(o=>o.did===Ce))!=null&&F.mountPoint||R.joinURL(q,"/image-bin");function je(o){return o&&!/^(https?:\/\/|\/)/.test(o)?window.location.origin+R.joinURL(q,"uploads",o):o}const ve=window.innerWidth<=750;function be(o,n,l){if(!o||/\.gif/.test(o))return o;const P=(ve?n/1.5:n)*(l==="quality"?1.5:1);return Oe(o,{imageFilter:"resize",w:P,f:"webp"})}function Oe(o,n){return!o||!n?o:R.withQuery(o,n)}async function Ee(o){return T.get(`/api/projects/${o}`).then(n=>n.data)}async function Le(o){return T.post(`/api/projects/${o.id}/update`,o).then(n=>n.data)}const Me=500,k=ae.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),z=m.createContext(null);function _e({url:o,name:n,children:l,waitingSynced:P}){const[L,O]=m.useState(!1),{locale:p}=ne.useLocaleContext(),j=$(),_=`${j}:MakerLocalState`,e=`${j}:${n}`,[t,s]=ce.useLocalStorageState(_,{defaultValue:{},listenStorageChange:!0}),c=m.useRef(t);c.current=t;const i=m.useMemo(()=>pe.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),r=m.useMemo(()=>W.getYjsDoc(i),[i]);m.useMemo(()=>new de.IndexeddbPersistence(e,r),[e,r]);const a=m.useMemo(()=>new le.WebsocketProvider(o,e,r,{params:{},resyncInterval:5*60*1e3}),[o,e,r]),d=m.useCallback(()=>{a&&(a.disconnect(),a.connect())},[a]),u=m.useMemo(()=>new ue.UndoManager([r.getArray("pageIds"),r.getMap("pages"),r.getArray("supportedLocales"),r.getMap("config"),r.getMap("dataSources"),r.getArray("dataSourceIds"),r.getArray("routeIds"),r.getMap("routes")],{doc:r}),[r]),[f,S]=m.useState(null),[M,I]=m.useState(!1),[y,v]=m.useState(void 0),g=m.useCallback(async()=>{if(j){I(!0);try{const w=await Ee(j);S(w)}catch(w){console.error("Failed to fetch project:",w)}finally{I(!1)}}},[j]),b=m.useCallback(async(w,h)=>{var E;if(v(void 0),!!j){h!=null&&h.optimisticUpdate&&f&&S(C=>({...C,...w}));try{const C=await Le({...w});S(C)}catch(C){console.error("Failed to update project:",C),h!=null&&h.optimisticUpdate&&S(f),v((E=C==null?void 0:C.response)==null?void 0:E.data)}}},[j,f]);m.useEffect(()=>{j&&g()},[j,g]);const Z=m.useMemo(()=>({doc:r,state:i,localState:{...t,currentLocale:p},setLocalState:w=>s(typeof w=="function"?h=>w(h??{}):w),undoManager:u,projectState:{project:f,isLoadingProject:M,error:y},updateProject:b,forceSync:d}),[r,i,JSON.stringify(t),s,u,f,M,b,y,p,d]);return m.useEffect(()=>{u.on("stack-item-added",({stackItem:w})=>{const{currentPageId:h,currentLocale:E,pages:C}=c.current;w.meta.set("localState",{currentPageId:h,currentLocale:E,pages:C})}),u.on("stack-item-popped",({stackItem:w})=>{const h=w.meta.get("localState");h&&s(E=>({...E,...h}))})},[u,s]),m.useEffect(()=>{a.awareness.setLocalState(t)},[a,t]),m.useEffect(()=>{a.once("synced",()=>O(!0));const w=()=>{s(C=>({...C,networkStatus:void 0}))},h=()=>{s(C=>({...C,networkStatus:"offline"}))},E=K.default(({status:C})=>{C==="connected"?w():C==="disconnected"&&h()},Me);return a.on("status",E),window.addEventListener("online",w),window.addEventListener("offline",h),()=>{a.off("status",E),window.removeEventListener("online",w),window.removeEventListener("offline",h)}},[a,s]),P&&!L?null:D.jsx(z.Provider,{value:Z,children:l})}const Q=()=>{const o=m.useContext(z);if(!o)throw new Error("Context is null");const n=re.useSyncedStore(o.state),{setLocalState:l,localState:P}=o,L=V.useNavigate(),O=$(),p=m.useMemo(()=>({get currentPage(){const{localState:{currentPageId:e}}=o;return e?n.pages[e]:void 0},get currentSection(){var c,i,r,a,d;const{localState:{currentPageId:e,...t}}=o;if(!e)return;const s=(i=(c=t.pages)==null?void 0:c[e])==null?void 0:i.currentSectionId;if(s)return((r=n.pages[e])==null?void 0:r.sections[s])??((d=(a=this.currentPageModel)==null?void 0:a.getComponentById(s))==null?void 0:d.model)},get currentSectionProperties(){var r,a,d,u;const{localState:{currentPageId:e,...t}}=o;if(!e)return;const s=(a=(r=t.pages)==null?void 0:r[e])==null?void 0:a.currentSectionId;if(!s)return;const c=(u=(d=n.pages[e])==null?void 0:d.dataSource)==null?void 0:u[s];if(!c)return;const{currentLocale:i}=this.currentLocaleMap;return i?c[i]:void 0},get currentSectionPropertiesWithFallback(){var d,u,f,S;const{localState:{currentPageId:e,...t}}=o;if(!e)return;const s=(u=(d=t.pages)==null?void 0:d[e])==null?void 0:u.currentSectionId;if(!s)return;const c=(S=(f=n.pages[e])==null?void 0:f.dataSource)==null?void 0:S[s];if(!c)return;const{currentLocale:i,defaultLocale:r,fallbackLocale:a}=this.currentLocaleMap;if(i&&c[i])return c[i];if(r&&c[r])return c[r];if(a&&c[a])return c[a]},get currentLocaleMap(){var c;const{localState:{currentLocale:e},state:{supportedLocales:t,config:{defaultLocale:s}}}=o;return{currentLocale:e,defaultLocale:s,fallbackLocale:((c=t==null?void 0:t[0])==null?void 0:c.locale)??"en"}},get currentRoute(){var t;const{localState:{currentRouteId:e}}=o;return e?(t=n.routes)==null?void 0:t[e]:void 0},get currentPageModel(){const e=this.currentPage??null;if(e){const t=new J.TemplateModel({childrenProperties:J.PAGES_KIT_CHILDREN_PROPERTIES,locale:P.currentLocale});return t.parse(e),t}}}),[JSON.stringify(P),n]),j=m.useMemo(()=>({setCurrentSectionId:(e,t)=>{var s,c;e===P.currentPageId&&t===((c=(s=P.pages)==null?void 0:s[e])==null?void 0:c.currentSectionId)||(L(R.joinURL("/admin/maker",O??"","pages",e)),l(i=>x.produce(i,r=>{var a;r.currentPageId=e,r.currentComponentId=void 0,t!==void 0&&(r.pages??(r.pages={}),(a=r.pages)[e]??(a[e]={}),r.pages[e].currentSectionId=t??void 0),t?window.sessionStorage.setItem("iframe_show_id",`"${t}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{e!==P.currentComponentId&&(L(R.joinURL("/admin/maker",O??"","components",e)),l(t=>x.produce(t,s=>{s.currentComponentId=e})))},setCurrentRouteId:({routeId:e,dynamicParams:t})=>{l(s=>x.produce(s,c=>{c.currentRouteId=e,c.currentDynamicParams=t}))},setCustomComponentPreviewerProperties:(()=>{const e={};let t="";const s=K.default(()=>{l(c=>x.produce(c,i=>{i.customComponentPreviewerProperties??(i.customComponentPreviewerProperties={}),i.customComponentPreviewerProperties[t]={...i.customComponentPreviewerProperties[t],...G.default(e[t])},delete e[t]}))},5);return(c,i)=>{const r=e[c]??{};Object.assign(r,i),e[c]=r,t=c,s()}})(),setRouteGenerateProcess:e=>{l(t=>x.produce(t,s=>{e?s.routeGenerateProcess={...s.routeGenerateProcess,...e}:s.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{l(e=>x.produce(e,t=>{t.routeGenerateProcess={progress:"complete"}}))}}),[l,L,O,p]),_=m.useMemo(()=>({addPage:(e,t)=>{var i,r,a,d,u,f;const s=(e==null?void 0:e.id)??k(),c={...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:((i=e==null?void 0:e.templateConfig)==null?void 0:i.isTemplate)??!0,displayTemplateId:((r=e==null?void 0:e.templateConfig)==null?void 0:r.displayTemplateId)??void 0,dataSourceIds:((a=e==null?void 0:e.templateConfig)==null?void 0:a.dataSourceIds)??void 0,dataSourceParameters:((d=e==null?void 0:e.templateConfig)==null?void 0:d.dataSourceParameters)??{},enabledGenerate:((u=e==null?void 0:e.templateConfig)==null?void 0:u.enabledGenerate)??!1,agentId:((f=e==null?void 0:e.templateConfig)==null?void 0:f.agentId)??void 0}};return o.doc.transact(()=>{n.pages[c.id]=c,n.pageIds.splice(t??n.pageIds.length,0,c.id)}),c},addRoute:(e,t)=>{const s=(e==null?void 0:e.id)??k(),c={...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 o.doc.transact(()=>{n.routes??(n.routes={}),n.routeIds??(n.routeIds=[]),n.routes[c.id]=c,n.routeIds.splice(t??n.routeIds.length,0,c.id)}),c},deleteRoute:e=>{var s;if(!e)return;const t=(s=n.routeIds)==null?void 0:s.indexOf(e);t!==void 0&&t!==-1&&o.doc.transact(()=>{var c,i;(c=n.routeIds)==null||c.splice(t,1),(i=n.routes)==null||delete i[e]})},deletePage:e=>{const t=n.pageIds.indexOf(e);t!==-1&&o.doc.transact(()=>{n.pageIds.splice(t,1),delete n.pages[e]})},movePage:(e,t)=>{const{pageIds:s}=n,c=s.indexOf(e);c>=0&&s.splice(t,0,...s.splice(c,1))},addSection:(e,t,s,c)=>{const i=n.pages[e];if(!i)throw new Error(`Page ${e} is not exists`);const r={...t,id:t.id??k(),isTemplateSection:t.isTemplateSection??!0,llmConfig:t.llmConfig??{}},a=G.default(r.locales);return delete r.locales,o.doc.transact(()=>{var d,u,f;if(c&&c.component==="layout-block"){const S=(d=p.currentPageModel)==null?void 0:d.getComponentById(c.id);S&&((u=S.model).sections??(u.sections={}),S.model.sections[r.id]=r,(f=S.model).sectionIds??(f.sectionIds=[]),S.model.sectionIds.push(r.id))}else i.sections[r.id]=r,i.sectionIds.splice(s??i.sectionIds.length,0,r.id);a&&(i.dataSource??(i.dataSource={}),i.dataSource[r.id]=a)}),r},deleteSection:(e,t)=>{const s=n.pages[e];if(!s)throw new Error(`Page ${e} is not exists`);o.doc.transact(()=>{var a,d,u,f,S,M;const c=[],i=(a=p.currentPageModel)==null?void 0:a.getComponentById(t),r=i==null?void 0:i.parent;if(i&&(c.push(i.model.id,...i.all().map(I=>I.model.id)),(r==null?void 0:r.model.component)==="layout-block")){const I=(d=r.model.sectionIds)==null?void 0:d.indexOf(t);I!==void 0&&I!==-1&&((u=r.model.sectionIds)==null||u.splice(I,1),(f=r.model.sections)==null||delete f[t]),(S=r.model.config)!=null&&S.gridSettings&&Object.keys(r.model.config.gridSettings).forEach(y=>{var v;try{(v=r.model.config.gridSettings[y])==null||delete v[t]}catch{}}),((M=r.model.config)==null?void 0:M.backgroundSectionId)===t&&(r.model.config.backgroundSectionId=void 0)}c.forEach(I=>{var v,g;const y=s.sectionIds.indexOf(I);y!==-1&&s.sectionIds.splice(y,1),s.sections[I]&&delete s.sections[I],(v=s.dataSource)!=null&&v[I]&&((g=s.dataSource)==null||delete g[I])})})},lockSection:(e,t)=>{var i,r;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);const c=(r=(i=p.currentPageModel)==null?void 0:i.getComponentById(t))==null?void 0:r.model;c&&(c.locked=!c.locked)},toggleSectionVisibility:(e,t,s)=>{var r,a;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);const i=(a=(r=p.currentPageModel)==null?void 0:r.getComponentById(t))==null?void 0:a.model;i&&(i.visibility=s)},moveSection:(e,t,s,c)=>{var r,a,d,u,f,S,M,I;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);if(c&&c!==t){const y=(r=p.currentPageModel)==null?void 0:r.getComponentById(t),v=(a=p.currentPageModel)==null?void 0:a.getComponentById(c),g=y==null?void 0:y.parent,b=v==null?void 0:v.parent;b&&g&&((d=b==null?void 0:b.model)==null?void 0:d.id)===((u=g==null?void 0:g.model)==null?void 0:u.id)?o.doc.transact(()=>{g.model.sectionIds.splice(y.getIndex(),1),g.model.sectionIds.splice(v.getIndex(),0,t)}):b&&g&&((f=b==null?void 0:b.model)==null?void 0:f.id)!==((S=g==null?void 0:g.model)==null?void 0:S.id)&&t!==c&&!((I=(M=y==null?void 0:y.model)==null?void 0:M.sectionIds)!=null&&I.includes(c))&&o.doc.transact(()=>{b.model.sections[t]=JSON.parse(JSON.stringify(y.model)),b.model.sectionIds.splice(v.getIndex(),0,t),g.model.sectionIds.splice(y.getIndex(),1),delete g.model.sections[t]})}},copySection:(e,t)=>{var u,f,S;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);const c=(u=p.currentPageModel)==null?void 0:u.getComponentById(t);if(!(c!=null&&c.model))throw new Error(`Section ${t} is not exists`);const i=JSON.parse(JSON.stringify(c.model)),r=Re(i),a=r.id,d=c==null?void 0:c.parent;return d&&(d.model.sections[a]=r,d.model.sectionIds.push(a),j.setCurrentSectionId(e,a),(S=(f=p.currentPage)==null?void 0:f.dataSource)!=null&&S[t]&&(p.currentPage.dataSource[a]=JSON.parse(JSON.stringify(p.currentPage.dataSource[t])))),r},addDataSource:e=>{const t=e.id??k(),s={...e??{},id:t,createdAt:new Date().toISOString()};return o.doc.transact(()=>{n.dataSourceIds??(n.dataSourceIds=[]),n.dataSources??(n.dataSources={}),n.dataSourceIds.push(t),n.dataSources[t]=s}),n.dataSources[t]},deleteDataSource:e=>{const t=n.dataSourceIds.indexOf(e);t!==-1&&o.doc.transact(()=>{n.dataSourceIds.splice(t,1),delete n.dataSources[e]})}}),[n,o.doc,p]);return{...o,state:n,actions:_,localActions:j,...p}},$=()=>{const{projectId:o}=V.useParams();return o??N()??""},xe=()=>window.__PROJECT_SLUG__??"";function X(o){var P,L;const{resources:n}=o;if(!n.components)return{};const l={};return(L=(P=window==null?void 0:window.blocklet)==null?void 0:P.componentMountPoints)==null||L.forEach(O=>{l[O.did]=O}),Object.fromEntries(Object.entries(n.components).map(([O,{blockletId:p,component:j}])=>{var _;return[O,{data:j,blockletId:p,blockletTitle:((_=l[p])==null?void 0:_.title)||p}]}))}function Y(o){const{components:n}=o;return n||{}}function H(o){return{...X(o),...Y(o)}}const ke=()=>H(Q().state);function Re(o){const n=JSON.parse(JSON.stringify(o)),l=k();return{...n,id:l}}exports.ErrorView=Ie;exports.StoreProvider=_e;exports.api=T;exports.autoResizeImage=be;exports.getAllComponents=H;exports.getCustomComponents=Y;exports.getImageAbsoluteUrl=je;exports.getMountPoint=ge;exports.getProjectIdFromPathnameOrWindow=N;exports.getProjectPageVersionKey=Pe;exports.getResourceComponents=X;exports.getWssURL=he;exports.nextId=k;exports.transformValue=we;exports.useAllComponents=ke;exports.useProjectId=$;exports.useProjectSlug=xe;exports.useStore=Q;
|