@blocklet/pages-kit-inner-components 0.7.3 → 0.7.5
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/chunks/site-state-D9DYye_t.js +1 -0
- package/lib/cjs/locales.js +2 -2
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/chunks/site-state-Ct2OR_RE.js +1989 -0
- package/lib/es/locales.js +17 -1
- package/lib/es/resources.js +22 -20
- package/lib/es/site-state.js +1 -1
- package/package.json +3 -3
- package/lib/cjs/chunks/site-state-D5CfLsg2.js +0 -1
- package/lib/es/chunks/site-state-DY7YJ7F1.js +0 -1744
package/lib/es/locales.js
CHANGED
|
@@ -411,7 +411,15 @@ const t = e({
|
|
|
411
411
|
addParamOption: "Add parameter option",
|
|
412
412
|
errorEmptyValue: "Value cannot be empty",
|
|
413
413
|
errorContainsSlash: "Value cannot contain slash (/)",
|
|
414
|
-
errorInvalidChars: "Value contains invalid characters, please use only URL-safe characters"
|
|
414
|
+
errorInvalidChars: "Value contains invalid characters, please use only URL-safe characters",
|
|
415
|
+
initialConflictWarning: "This route path conflicts with {count} URL(s) from other projects",
|
|
416
|
+
urlConflictTitle: "URL Conflict Detected",
|
|
417
|
+
urlConflictAlertTitle: "Potential Routing Issue",
|
|
418
|
+
urlConflictDescription: "The route path you are trying to save conflicts with existing URLs from other projects. You can still save it, but this may cause routing issues.",
|
|
419
|
+
conflictingUrls: "Conflicting URLs",
|
|
420
|
+
conflictProject: "Project",
|
|
421
|
+
conflictPage: "Page",
|
|
422
|
+
saveAnyway: "Save Anyway"
|
|
415
423
|
},
|
|
416
424
|
datasource: {
|
|
417
425
|
autoSaveSuccess: "Auto save success"
|
|
@@ -1005,6 +1013,14 @@ const t = e({
|
|
|
1005
1013
|
errorEmptyValue: "值不能为空",
|
|
1006
1014
|
errorContainsSlash: "值不能包含斜杠 (/)",
|
|
1007
1015
|
errorInvalidChars: "值包含无效字符,请仅使用URL安全字符",
|
|
1016
|
+
initialConflictWarning: "此路由路径与其他项目的 {count} 个 URL 存在冲突",
|
|
1017
|
+
urlConflictTitle: "检测到 URL 冲突",
|
|
1018
|
+
urlConflictAlertTitle: "潜在路由问题",
|
|
1019
|
+
urlConflictDescription: "您要保存的路由路径与其他项目的现有 URL 冲突。您仍然可以保存,但这可能会导致路由问题。",
|
|
1020
|
+
conflictingUrls: "冲突的 URL",
|
|
1021
|
+
conflictProject: "项目",
|
|
1022
|
+
conflictPage: "页面",
|
|
1023
|
+
saveAnyway: "仍然保存",
|
|
1008
1024
|
templates: {
|
|
1009
1025
|
default: "默认模板",
|
|
1010
1026
|
blog: "博客模板",
|
package/lib/es/resources.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { i as
|
|
2
|
-
import { P as E, C as L, R as M, S as
|
|
1
|
+
import { i as b, a as T, l as x } from "./chunks/components-CcZk17uO.js";
|
|
2
|
+
import { P as E, C as L, R as M, S as A, t as F, c as J, g as X } from "./chunks/site-state-Ct2OR_RE.js";
|
|
3
3
|
import { Router as G } from "express";
|
|
4
4
|
import { rm as C, mkdir as K } from "fs/promises";
|
|
5
5
|
import u from "joi";
|
|
6
6
|
import O from "lodash/groupBy";
|
|
7
7
|
import W from "lodash/sortBy";
|
|
8
|
-
import { authMiddleware as
|
|
8
|
+
import { authMiddleware as S } from "@blocklet/sdk/lib/middlewares/auth";
|
|
9
9
|
import { getResourceExportDir as Y } from "@blocklet/sdk/lib/component";
|
|
10
10
|
import { join as $ } from "path";
|
|
11
11
|
const z = async (e, t, o) => {
|
|
@@ -13,13 +13,15 @@ const z = async (e, t, o) => {
|
|
|
13
13
|
const { projectId: s } = e.params;
|
|
14
14
|
if (!s)
|
|
15
15
|
return o();
|
|
16
|
-
const n = await E.findByPk(s
|
|
16
|
+
const n = await E.findByPk(s, {
|
|
17
|
+
attributes: { exclude: ["productionState", "relatedBlocklets"] }
|
|
18
|
+
});
|
|
17
19
|
if (!n)
|
|
18
20
|
return t?.status(404).json({ error: "Project not found" });
|
|
19
21
|
const r = e.user?.did, c = e.user?.role || "UNKNOWN_ROLE";
|
|
20
22
|
if (!r)
|
|
21
23
|
return t?.status(401).json({ error: "Authentication required" });
|
|
22
|
-
if (
|
|
24
|
+
if (b()) {
|
|
23
25
|
const j = n.createdBy === r, I = T()?.includes?.(c);
|
|
24
26
|
if (!j && !I)
|
|
25
27
|
return t?.status(403).json({ error: "No permission to access this project in multi-tenant mode" });
|
|
@@ -27,20 +29,20 @@ const z = async (e, t, o) => {
|
|
|
27
29
|
return t?.status(403).json({ error: "No permission to access this project in single-tenant mode" });
|
|
28
30
|
e.project = n, e.projectId = s, o();
|
|
29
31
|
} catch (s) {
|
|
30
|
-
|
|
32
|
+
x.error("Project middleware error:", s), t?.status(400).json({ error: "Internal server error" });
|
|
31
33
|
}
|
|
32
|
-
}, y = (e, t, o) =>
|
|
34
|
+
}, y = (e, t, o) => b() ? S()(e, t, o) : S({ roles: ["owner", "admin", "pagesEditor"] })(e, t, o), H = (e, t) => {
|
|
33
35
|
const o = Y({ projectId: e, releaseId: t });
|
|
34
36
|
return $(o, L, M);
|
|
35
|
-
}, w = G(),
|
|
37
|
+
}, w = G(), D = "@page", B = "@component", m = ":", g = "ALL", N = "@project", _ = ({ pageId: e, projectId: t }) => [D, t, e].join(m), Q = (e) => {
|
|
36
38
|
const [t, o, s] = e.split(m);
|
|
37
|
-
if (t ===
|
|
38
|
-
}, k = ({ componentId: e, projectId: t }) => [
|
|
39
|
+
if (t === D) return { pageId: s, projectId: o };
|
|
40
|
+
}, k = ({ componentId: e, projectId: t }) => [B, t, e].join(m), V = (e) => {
|
|
39
41
|
const [t, o, s] = e.split(m);
|
|
40
|
-
if (t ===
|
|
41
|
-
}, Z = (e) => [
|
|
42
|
+
if (t === B) return { componentId: s, projectId: o };
|
|
43
|
+
}, Z = (e) => [N, e].join(m), q = (e) => {
|
|
42
44
|
const [t, o] = e.split(m);
|
|
43
|
-
if (t ===
|
|
45
|
+
if (t === N) return o;
|
|
44
46
|
}, ee = (e) => {
|
|
45
47
|
try {
|
|
46
48
|
return JSON.parse(e);
|
|
@@ -49,10 +51,10 @@ const z = async (e, t, o) => {
|
|
|
49
51
|
return {};
|
|
50
52
|
};
|
|
51
53
|
async function v(e) {
|
|
52
|
-
const t = await
|
|
54
|
+
const t = await A.getStateByProjectId({ projectId: e, mode: "production" }), o = await E.findByPk(e), s = t.pageIds.map((r) => {
|
|
53
55
|
const c = t.pages[r];
|
|
54
56
|
if (c)
|
|
55
|
-
return { id:
|
|
57
|
+
return { id: _({ pageId: r, projectId: e }), name: c.slug };
|
|
56
58
|
}).filter(Boolean), n = W(Object.values(t.components), (r) => r.index).map(({ data: r }) => ({
|
|
57
59
|
id: k({ componentId: r.id, projectId: e }),
|
|
58
60
|
name: r.name || r.id
|
|
@@ -61,7 +63,7 @@ async function v(e) {
|
|
|
61
63
|
id: Z(e),
|
|
62
64
|
name: o?.name || "Unnamed Project",
|
|
63
65
|
children: [
|
|
64
|
-
{ id:
|
|
66
|
+
{ id: _({ pageId: g, projectId: e }), name: "Pages", children: s },
|
|
65
67
|
{
|
|
66
68
|
id: k({ componentId: g, projectId: e }),
|
|
67
69
|
name: "Components",
|
|
@@ -112,10 +114,10 @@ w.post("/resources", y, async (e, t) => {
|
|
|
112
114
|
});
|
|
113
115
|
}
|
|
114
116
|
}
|
|
115
|
-
const I = O(c, "projectId"), h = O(j, "projectId"),
|
|
117
|
+
const I = O(c, "projectId"), h = O(j, "projectId"), U = /* @__PURE__ */ new Set([...Object.keys(I), ...Object.keys(h)]), P = H(s, n);
|
|
116
118
|
await C(P, { recursive: !0, force: !0 }), await K(P, { recursive: !0 });
|
|
117
|
-
for (const i of
|
|
118
|
-
const a = await
|
|
119
|
+
for (const i of U) {
|
|
120
|
+
const a = await A.getStateByProjectId({ projectId: i, mode: r }), f = I[i], l = h[i], d = f?.map((p) => p.pageId), R = l?.map((p) => p.componentId);
|
|
119
121
|
if (d?.length || R?.length) {
|
|
120
122
|
const p = await F(a, {
|
|
121
123
|
exportAssets: !0,
|
|
@@ -124,7 +126,7 @@ w.post("/resources", y, async (e, t) => {
|
|
|
124
126
|
});
|
|
125
127
|
await J(p, P), await C(p, { recursive: !0, force: !0 });
|
|
126
128
|
}
|
|
127
|
-
|
|
129
|
+
x.info(`Exported resources for project ${i}`, {
|
|
128
130
|
pageIds: d,
|
|
129
131
|
componentIds: R
|
|
130
132
|
});
|
package/lib/es/site-state.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./chunks/components-CcZk17uO.js";
|
|
2
|
-
import { d as b, a as h, b as y, S as L, f as U, h as q, i as v, e as z, g as C, j as F, m as G, t as J, k as K, u as N } from "./chunks/site-state-
|
|
2
|
+
import { d as b, a as h, b as y, S as L, f as U, h as q, i as v, e as z, g as C, j as F, m as G, t as J, k as K, u as N } from "./chunks/site-state-Ct2OR_RE.js";
|
|
3
3
|
import { nextId as V } from "@blocklet/pages-kit/utils/common";
|
|
4
4
|
import "@blocklet/pages-kit/utils/page-model";
|
|
5
5
|
import "@blocklet/pages-kit/utils/property";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.5",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -201,8 +201,8 @@
|
|
|
201
201
|
"yaml": "^2.5.0",
|
|
202
202
|
"yjs": "^13.6.18",
|
|
203
203
|
"zustand": "^4.5.5",
|
|
204
|
-
"@blocklet/pages-kit": "^0.7.
|
|
205
|
-
"@blocklet/pages-kit-block-studio": "^0.7.
|
|
204
|
+
"@blocklet/pages-kit": "^0.7.5",
|
|
205
|
+
"@blocklet/pages-kit-block-studio": "^0.7.5"
|
|
206
206
|
},
|
|
207
207
|
"devDependencies": {
|
|
208
208
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const u=require("./components-CnPdZJ2Z.js"),G=require("@syncedstore/core"),rt=require("yjs"),it=require("@blocklet/pages-kit/utils/data-source"),ae=require("@blocklet/pages-kit/utils/route"),ct=require("lodash/cloneDeep"),lt=require("@blocklet/sdk/lib/config"),Z=require("fs"),f=require("path"),Me=require("@blocklet/pages-kit/utils/common"),ut=require("@blocklet/pages-kit/utils/page-model"),dt=require("@blocklet/pages-kit/utils/property"),Ae=require("@blocklet/sdk/lib/component"),pt=require("@reactivedata/reactive"),O=require("fs/promises"),se=require("glob"),ft=require("lib0/decoding"),gt=require("lib0/encoding"),mt=require("lodash/debounce"),ht=require("lodash/get"),yt=require("lodash/isEmpty"),St=require("lodash/set"),wt=require("lodash/union"),je=require("lru-cache"),It=require("p-limit"),A=require("sequelize"),bt=require("stream/promises"),Et=require("tar"),N=require("ufo"),Pt=require("wait-on"),H=require("y-protocols/awareness"),fe=require("y-protocols/sync"),At=require("yaml"),$e=require("./html-dP5_4zu1.js");require("sqlite3");require("@blocklet/pages-kit/types/state");const $=t=>t&&t.__esModule?t:{default:t};function ce(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const s=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(e,a,s.get?s:{enumerable:!0,get:()=>t[a]})}}return e.default=t,Object.freeze(e)}const F=ce(rt),Oe=$(ct),E=$(lt),V=$(Z),Ne=$(f),ge=ce(ft),k=ce(gt),Ce=$(mt),De=$(ht),Te=$(yt),Fe=$(St),jt=$(wt),Re=$(It),Ot=$(Pt),K=ce(At),Ct=A.DataTypes.sqlite.DATE.parse;A.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Ct(t,e);const B=new A.Sequelize({dialect:"sqlite",storage:u.databaseUrl,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});B.query("PRAGMA journal_mode = WAL;");B.query("PRAGMA synchronous = normal;");B.query("PRAGMA journal_size_limit = 67108864;");B.query("PRAGMA cache_size = 10000;");process.on("SIGINT",async()=>{await B.close(),process.exit(0)});process.on("SIGTERM",async()=>{await B.close(),process.exit(0)});async function Dt(t,e){try{if(t.getDialect()!=="sqlite")return;const[a]=await t.query("SELECT 1");if(!a||a.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(a){if(a.name==="SequelizeConnectionError"||a?.message&&/closed!/.test(a.message))return;console.error("Failed to cleanup SQLite memory",e,a)}}let Se=null;Se&&clearInterval(Se);Se=setInterval(async()=>{u.logger.info("Start cleanupSqliteMemory"),await Dt(B,u.databaseUrl),u.logger.info("End cleanupSqliteMemory")},60*1e3*10);const Tt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",we="page",Ie="trigger-reload-project-resource",ve=Tt,Rt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",vt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";class ke extends A.Model{}ke.init({id:{type:A.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:A.DataTypes.UUIDV4},projectId:{type:A.DataTypes.UUID,allowNull:!1},componentId:{type:A.DataTypes.STRING,allowNull:!1}},{sequelize:B,tableName:"ProjectComponents",timestamps:!1});const kt="SLUG_INVALID",J=t=>({error:"slugInvalid",code:kt,field:"slug",message:t}),_t={error:"slugRequired",code:"SLUG_REQUIRED",field:"slug",message:()=>"Project slug is required"},Lt={error:"slugAlreadyExists",code:"SLUG_EXISTS",field:"slug",message:t=>`Project slug "${t}" already exists`},Ut=[/\.\./,/<[^>]*>/,/%[0-9a-f]{2}/i,/[<>'"%;{}()\\]/,/\x00/,/\n|\r|\t|\v|\f/,/[^a-zA-Z0-9-_@/\\:]/],qe=t=>{if(!t)return"";if(t==="/")return"/";const e=N.withoutTrailingSlash(t);return N.withLeadingSlash(e)||"/"},Mt=t=>t.did===vt;class U extends A.Model{static async getProjectByIdOrSlug(e,a){return e?U.findOne({where:{[A.Op.or]:[{id:e},{slug:e}],...a?.createdBy?{createdBy:a.createdBy}:{}}}):null}static async validateProjectSlug({slug:e,projectId:a}){if(e==null)return null;if(e==="")return _t;const s=e==="/"?"/":N.withoutTrailingSlash(N.withLeadingSlash(e)),n=qe(s);if(s!=="/"&&s.endsWith("/"))return J(i=>`Project slug "${i}" cannot end with /`);if(/\/{2,}/.test(s))return J(i=>`Project slug "${i}" cannot contain consecutive /`);if(/\s/.test(s))return J(i=>`Project slug "${i}" cannot contain whitespace`);if(Ut.some(i=>i.test(s)))return J(i=>`Project slug "${i}" contains invalid characters`);if(E.default.components?.filter(i=>i.mountPoint&&!Mt(i)).some(i=>qe(i.mountPoint)===n))return J(i=>`Project slug "${i}" conflicts with existing blocklet`);const l=await U.findOne({where:{slug:s}});return l&&l?.id!==a?Lt:null}}U.init({id:{type:A.DataTypes.UUID,defaultValue:A.DataTypes.UUIDV4,primaryKey:!0},name:{type:A.DataTypes.STRING,allowNull:!1},description:A.DataTypes.TEXT,createdAt:A.DataTypes.DATE,updatedAt:A.DataTypes.DATE,createdBy:{type:A.DataTypes.STRING,allowNull:!1},updatedBy:{type:A.DataTypes.STRING,allowNull:!1},slug:A.DataTypes.STRING,icon:A.DataTypes.STRING,pinnedAt:A.DataTypes.DATE,useAllResources:A.DataTypes.BOOLEAN,npmSecret:A.DataTypes.STRING,relatedBlocklets:{type:A.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("relatedBlocklets");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return u.logger.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){u.logger.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:A.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("productionState");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return u.logger.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){u.logger.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}},meta:{type:A.DataTypes.JSON,allowNull:!0}},{sequelize:B,paranoid:!0,indexes:[{name:"projects_slug_unique",unique:!0,fields:["slug"]},{name:"projects_created_by",fields:["createdBy"]},{name:"projects_pinned_updated_meta_not_null",fields:[{name:"pinnedAt",order:"DESC"},{name:"updatedAt",order:"DESC"}],where:{meta:{[A.Op.ne]:null}}}]});U.hasMany(ke,{foreignKey:"projectId",as:"components"});async function q(t){try{return await V.default.promises.access(t,V.default.constants.F_OK),!0}catch{return!1}}function Ge(t,e){return new Promise((a,s)=>{const n=V.default.createReadStream(t),o=V.default.createWriteStream(e);n.on("error",s),o.on("error",s),o.on("finish",a),n.pipe(o)})}async function Ve(t,e){await V.default.promises.mkdir(e,{recursive:!0});const a=await V.default.promises.readdir(t,{withFileTypes:!0});for(const s of a){const n=Ne.default.join(t,s.name),o=Ne.default.join(e,s.name);s.isDirectory()?await Ve(n,o):await Ge(n,o)}}async function $t(t,e){(await V.default.promises.stat(t)).isDirectory()?await Ve(t,e):await Ge(t,e)}function ne(t){t.observeDeep(e=>{e.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function ze(){return Z.mkdtempSync(f.join(E.default.env.dataDir,"tmp-"))}function oe(t,e,a=[]){return Array.isArray(t)?t.flatMap((s,n)=>oe(s,e,[...a,n])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,n])=>oe(n,e,[...a,s])):e(t)?[a]:[]}function L(t){return t.filter(e=>e!=null)}function Nt(t){t.pages&&Object.keys(t.pages).forEach(a=>{const s=G.getYjsValue(t.pages[a]);s&&s instanceof F.Map&&ne(s)});const e=G.getYjsValue(t.pages);e&&e instanceof F.Map&&e.observe(a=>{a.changes.keys.forEach((s,n)=>{if(s.action==="add"){const o=G.getYjsValue(t.pages[n]);o&&o instanceof F.Map&&ne(o)}})})}function Ft(t){t.routes&&Object.keys(t.routes).forEach(a=>{const s=G.getYjsValue(t.routes?.[a]);s&&s instanceof F.Map&&ne(s)});const e=G.getYjsValue(t.routes);e&&e instanceof F.Map&&e.observe(a=>{a.changes.keys.forEach((s,n)=>{if(s.action==="add"){const o=G.getYjsValue(t.routes?.[n]);o&&o instanceof F.Map&&ne(o)}})})}function qt(t,e){for(const a of e||Object.keys(t.routes||{})){let s=a,n=[];if(a.includes("-")){const[o,...l]=a.split("-");s=o,n=l||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const o=t.routes[s];if(!o||!o.params||o.params.length===0)continue;if(a.includes("-")&&n.length>0){const l=ae.getRouteMetaDataByOptionIds(n,o);l&&(l.publishedAt=new Date().toISOString())}if(!e){const l=ae.generateParamCombinations({basePath:o.path,params:o.params,routeId:o.id,paramsOptions:o.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const i of l)i.routeMetaData??={},i.routeMetaData.publishedAt=new Date().toISOString()}}}}function me({page:t,route:e,state:a,routeId:s,routePathInfo:n}){u.logger.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(n)}`);const o={...Oe.default(t),id:s,slug:n?.path??e.path,createdAt:e.createdAt,updatedAt:n?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:n?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(n?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const l of a.supportedLocales){if(e.dataSource){let i=e.id;n&&(i=n.paramOptionIds.join("-"));const c=e.dataSource.pathDataMappings?.[i]?.dataCache?.[l.locale]??e.dataSource.pathDataMappings?.[i]?.dataCache?.[a.config.defaultLocale||"en"];if(!c)continue;it.setPageDataSource(o,a,l.locale,c)}n&&n.routeMetaData&&(n.routeMetaData.publishedAt=new Date().toISOString())}return o}["true","1","yes","y"].includes(process.env.USE_FS_CACHE_HTML??"");const Bt=60*60*1e3,W=new je.LRUCache({max:300,ttl:Bt,ttlResolution:10*1e3,allowStale:!0});function xt(t,e=[]){let a=0;const s=Array.from(W.keys()),n=t.map(o=>N.withoutTrailingSlash(o));for(const o of s)for(const l of n){if($e.matchCacheKey(o,{currentPath:l})){W.delete(o),a++,u.logger.info(`[Cache CLEAR] key: ${o}`);break}for(const i of e)if($e.matchCacheKey(o,{currentPath:`/${i}${l}`})){W.delete(o),a++,u.logger.info(`[Cache CLEAR] key: ${o}`);break}}return u.logger.info(`[Cache CLEAR] cleared ${a} entries for paths:`,n),a}function Gt(){const t=W.size;return W.clear(),u.logger.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}E.default.events.on(E.default.Events.envUpdate,Gt);const{uploadToMediaKit:Vt}=require("@blocklet/uploader-server"),_e=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,X=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Be=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,zt=1e4,Kt=3e4,ee=0,he=1,Yt=0,Ht=1,be=E.default,z=f.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Jt=["production","draft"],Wt=["production"];function re(t){return t?.replace(/\//g,"|")||""}function Ke(){const t=be.env.languages?.map(a=>({locale:a.code,name:a.name}))||[],e=t[0]?.locale||"en";return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class j extends F.Doc{constructor(e){super(),this.options=e,Z.existsSync(this.draftYjsFilePath)&&F.applyUpdate(this,Z.readFileSync(this.draftYjsFilePath)),this.syncedStore=pt.reactive(G.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new H.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new je.LRUCache({max:300,ttl:1e3*60*60*24});static periodicCheckTimer;static async safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const a=f.join(z,e),s=f.join(z,`@del-${e}`);await O.rename(a,s)}catch(a){u.logger.error("Failed to safe delete project state dir:",a)}}static async getProjectIds(){return(await U.findAll({attributes:["id"],raw:!0}))?.map(e=>e.id)}static get projectIds(){return se.globSync("*/",{cwd:z,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>j.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let a=j.sharedInstances[e];return a||(a=new j({path:f.join(z,e)}),j.sharedInstances[e]=a,a)}static async getProductionState(e){const a=await U.findByPk(e,{attributes:["productionState"]});if(Te.default(a?.productionState)){const s=f.join(z,e,"production"),n=await Le(s,{includeResources:!0})??Ke();if(!n?.config?.defaultLocale){n.config??={};const o=be.env.languages?.map(l=>({locale:l.code,name:l.name}))||[];n.config.defaultLocale=o[0]?.locale}return n}return a?.productionState}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((a,s)=>this.closeConn(s)),this.awareness.destroy();const e=f.basename(this.options.path);delete j.sharedInstances[e],super.destroy()}initObserver(){Nt(this.syncedStore),Ft(this.syncedStore)}get draftYjsFilePath(){return f.join(this.options.path,"draft.yjs")}static async getStateByProjectId({projectId:e,mode:a,clone:s=!0}){if(a==="draft"){const n=j.shared(e);return s?JSON.parse(JSON.stringify(n.syncedStore)):n.syncedStore}return j.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const a=f.basename(this.options.path);return j.getProductionState(a)}async setState(e,a){const s=await We(a,{exportAssets:!1,includeResources:!0}),n=this.getPublishDir(e);if(await O.mkdir(f.dirname(n),{recursive:!0}),await O.rm(n,{force:!0,recursive:!0}),await O.rename(s,n),e==="production"){const o=f.basename(this.options.path);j.pageUrlMapCache.delete(o);const l=Oe.default(a);await U.update({productionState:l},{where:{id:o}})}}getPublishDir(e){return f.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:a,removed:s},n)=>{const o=e.concat(a,s);if(n!==null){const c=this.conns.get(n);c&&(e.forEach(b=>{c.add(b)}),s.forEach(b=>{c.delete(b)}))}const l=k.createEncoder();k.writeVarUint(l,he),k.writeVarUint8Array(l,H.encodeAwarenessUpdate(this.awareness,o));const i=k.toUint8Array(l);this.conns.forEach((c,b)=>this.send(b,i))};updateHandler=e=>{const a=k.createEncoder();k.writeVarUint(a,ee),fe.writeUpdate(a,e);const s=k.toUint8Array(a);this.conns.forEach((n,o)=>this.send(o,s))};ensureDataStructure=()=>{this.transact(()=>{const{supportedLocales:e,pages:a,pageIds:s,config:n,routes:o,routeIds:l}=this.syncedStore;{const i=new Set(Object.keys(a));let c=0;for(;c<s.length;){const b=s[c];i.has(b)?(i.delete(b),c++):s.splice(c,1)}}{const i=new Set(Object.keys(o));let c=0;for(;c<l.length;){const b=l[c];i.has(b)?(i.delete(b),c++):l.splice(c,1)}}e.splice(0,e.length),e.push(...be.env.languages.map(i=>({locale:i.code,name:i.name}))),n.defaultLocale=e[0]?.locale;{let i=0;const c=new Set;for(;i<e.length;){const{locale:b}=e[i];c.has(b)?e.splice(i,1):(i++,c.add(b))}}})};send=(e,a)=>{e.readyState!==Yt&&e.readyState!==Ht&&this.closeConn(e);try{e.send(a,s=>{s&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const a=this.conns.get(e);this.conns.delete(e),a&&H.removeAwarenessStates(this.awareness,Array.from(a),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=f.basename(this.options.path);this.releaseTimer=setTimeout(()=>{u.logger.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),u.logger.info(`[SiteState] scheduled release for project ${e} in ${j.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=f.basename(this.options.path);u.logger.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Ce.default(async()=>{await O.mkdir(f.dirname(this.draftYjsFilePath),{recursive:!0}),await O.writeFile(this.draftYjsFilePath,F.encodeStateAsUpdate(this))},zt);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:a})=>{const s=f.basename(this.options.path);await nt(s);const n=await this.getState("draft"),o=await this.getState("production");await Pe(n,o,{routes:a,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),qt(this.syncedStore,a),await this.setState(e,o),await this.clearPageCacheForRoutes(a,o)};mergeState=async(e,a)=>{const s=JSON.parse(JSON.stringify(a));e.config.fontFamily??={};const n=s.config?.fontFamily,o=e.config?.fontFamily;e.config.fontFamily.title=n?.title||o?.title,e.config.fontFamily.description=n?.description||o?.description,await new Promise((l,i)=>{this.transact(async()=>{try{const c=await Pe(e,a);l(c)}catch(c){i(c)}})})};clearPageCacheForRoutes=async(e,a)=>{const s=f.basename(this.options.path),o=(await U.findByPk(s))?.slug||s;let l=e;(!l||l.length===0)&&(l=a.pageIds??[]),u.logger.info(`[SiteState] clearing page cache for project ${s}, routes:`,l||[]);const i=a.supportedLocales.map(C=>C.locale),c=[],b=l.filter(C=>a.pageIds?.includes(C));for(const C of b){const w=a.pages[C].slug;o&&o!==s&&(o==="/"?c.push(w):c.push(`/${o}${w}`)),c.push(`/${s}${w}`)}if(c.length>0)try{const C=xt(c,i);u.logger.info(`[SiteState] cleared ${C} page cache entries for project ${s}, routes:`,l)}catch{}j.pageUrlMapCache.delete(s)};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",n=>this.messageListener(e,new Uint8Array(n)));let a=!0;const s=setInterval(()=>{if(!a)this.conns.has(e)&&this.closeConn(e),clearInterval(s);else if(this.conns.has(e)){a=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(s)}}},Kt);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{a=!0});{const n=k.createEncoder();k.writeVarUint(n,ee),fe.writeSyncStep1(n,this),this.send(e,k.toUint8Array(n));const o=this.awareness.getStates();if(o.size>0){const l=k.createEncoder();k.writeVarUint(l,he),k.writeVarUint8Array(l,H.encodeAwarenessUpdate(this.awareness,Array.from(o.keys()))),this.send(e,k.toUint8Array(l))}}};messageListener=(e,a)=>{try{const s=k.createEncoder(),n=ge.createDecoder(a),o=ge.readVarUint(n);switch(o){case ee:k.writeVarUint(s,ee),fe.readSyncMessage(n,s,this,null),k.length(s)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(s)));break;case he:{H.applyAwarenessUpdate(this.awareness,ge.readVarUint8Array(n),e);break}default:u.logger.warn(`Unsupported messageType ${o}`)}}catch(s){u.logger.error(s)}this.save()};static async pageUrlMap(e,a){u.logger.info(`[SiteState] get pageUrlMap, mode: ${e}, projectId: ${a}`);let s=[];a?s=[a]:s=await this.getProjectIds();let n={};if(e==="production"&&s?.length){const o=new Map(s?.map(l=>[l,!0])||[]);for(const l of s){const i=j.pageUrlMapCache.get(l);i&&(Object.assign(n,i),o.delete(l))}s=Array.from(o.keys())}if(s?.length){u.logger.info("[SiteState] find project infos from database, projectIds: ",s);const o=30,l=Re.default(5);for(let i=0;i<s.length;i+=o){const c=s.slice(i,i+o);u.logger.info(`[SiteState] processing project batch ${i/o+1}, ids: `,c);const b=await U.findAll({where:{id:{[A.Op.in]:c}},attributes:{exclude:["relatedBlocklets"]}});await Promise.all(b?.map(C=>l(async()=>{const R=C.id,w=C.slug||R,g={},d=e==="production"&&C?.productionState?C.productionState:await j.getStateByProjectId({projectId:C.id,mode:e,clone:!1}),I=jt.default(E.default.env.languages?.map(P=>P.code)||[],d.supportedLocales?.map(P=>P.locale)||[]),D=(P,y)=>{w&&(g[N.joinURL("/",w,P)]={...y,shouldRedirect:!0,mainPage:!0}),g[N.joinURL("/",R,P)]={...y,shouldRedirect:!0,mainPage:!0};for(const v of I){const h={...y,locale:v};g[N.joinURL("/",v,R,P)]=h,w&&(g[N.joinURL("/",v,w,P)]=h)}};if(e==="draft")for(const P of d.routeIds||[]){const y=d?.routes?.[P];if(!y)continue;if(y.params&&y.params.length>0){const S=ae.generateParamCombinations({basePath:y.path,params:y.params,routeId:y.id,paramsOptions:y.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const r of S){const p=r.path,m={projectId:R,projectSlug:w,pageSlug:p,pageId:y.displayTemplateId||"",routeId:P,defaultLocale:I?.[0],locales:I,publishedAt:d.config.publishedAt,isPublic:y.isPublic&&r?.routeMetaData?.isPublic};D(p,m)}}const v=y.path,h={projectId:R,projectSlug:w,pageSlug:v,pageId:y.displayTemplateId||"",routeId:P,defaultLocale:I?.[0],locales:I,publishedAt:d.config.publishedAt,isPublic:y.isPublic};D(v,h)}for(const P of d.pageIds||[]){const y=d.pages[P];if(!y||e==="production"&&!y.isPublic)continue;const v=y.slug,h=C.slug||R,S={projectId:R,projectSlug:h,pageSlug:v,pageId:P,defaultLocale:I?.[0],locales:I,publishedAt:d.config.publishedAt,isPublic:y.isPublic,templateConfig:y.templateConfig};D(v,S)}e==="production"&&j.pageUrlMapCache.set(R,g),n={...n,...g}})))}}return u.logger.info("[SiteState] success get pageUrlMap"),n}getDocumentSize(){return F.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[a,s]of Object.entries(j.sharedInstances)){const n=s.getDocumentSize();e.push({projectId:a,sizeInBytes:n,sizeInMB:`${(n/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),u.logger.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,u.logger.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(j.sharedInstances).length,a=[],s=[];for(const[n,o]of Object.entries(j.sharedInstances))o.conns.size===0?a.push({projectId:n,instance:o}):s.push({projectId:n,connections:o.conns.size});if(u.logger.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${s.length}, without connections: ${a.length}`),a.length>0){u.logger.info(`[SiteState] releasing ${a.length} instances without connections:`,a.map(o=>o.projectId));let n=0;for(const{projectId:o,instance:l}of a)try{u.logger.info(`[SiteState] releasing instance due to periodic check: ${o}`),l.destroy(),n++}catch(i){u.logger.error(`[SiteState] failed to release instance ${o} during periodic check:`,i)}u.logger.info(`[SiteState] periodic check completed: ${n}/${a.length} instances released successfully`)}else e>0?u.logger.debug("[SiteState] periodic check: all instances have active connections"):u.logger.debug("[SiteState] periodic check: no instances exist")}}async function Xt(t,e,a){if(!t||!await q(t)||!(await O.lstat(t)).isFile())return null;let n=a[t];return n||(n=(async()=>{try{return(await Vt({filePath:t,fileName:e}))?.data?.filename}catch(o){return u.logger.error(`Failed to upload asset ${t}:`,o),null}})(),a[t]=n),n}const Ye=async(t,e)=>{const a=f.basename(t),s=await Ae.call({name:ve,path:N.joinURL("/uploads",a),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const n=Z.createWriteStream(e);await bt.pipeline(s.data,n)}else throw new Error(`download asset failed ${s.status}`)},He=async(t,e)=>{await Promise.all(t.map(async a=>{try{await Ye(a,f.join(e,f.basename(a)))}catch(s){u.logger.error(`Failed to export assets: ${a}, ${s}`)}}))};function Je(t){return _e.test(t)?[t]:X.test(t)?(Be.lastIndex=0,Array.from(t.matchAll(Be)).map(a=>a[1]).filter(a=>!!a)):[]}async function te(t,e,a){const{getFilename:s,exportAssets:n}=a,o=f.join(e,s(t));if(await O.mkdir(f.dirname(o),{recursive:!0}),await O.writeFile(o,K.stringify(t)),n){const i=oe(t,c=>typeof c=="string"&&(_e.test(c)||X.test(c))).map(c=>{const b=De.default(t,c);return Je(b)}).flat().filter(Boolean);await He(i,f.dirname(o))}}const Ee=new je.LRUCache({max:100,ttl:1*60*1e3});async function xe(t,e,a){const s=oe(t,i=>typeof i=="string"&&(_e.test(i)||X.test(i))),n=Re.default(2),o=s.map(i=>n(async()=>{try{const c=De.default(t,i),b=Je(c);for(const C of b){const R=f.basename(C),w=a.getFilePath(C,i),g=w?`${w}:${R}`:R,d=Ee.get(g);if(d){X.test(c)||Fe.default(t,i,d);return}const I=await Xt(w,R,e);I&&(X.test(c)||Fe.default(t,i,I),Ee.set(g,I))}}catch(c){u.logger.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(o);a.onFinish?.(l)}async function We(t,{exportAssets:e,pageIds:a="all",componentIds:s="all",rawConfig:n,includeResources:o=!1,routeIds:l="all"}={}){const i=a==="all"?t.pageIds:a,c=dt.getComponentDependencies({state:t,pageIds:i,componentIds:s==="all"?Object.keys(t.components):s});Object.entries(t.components).forEach(([r,p])=>{p.data?.renderer?.type==="component-template"&&c.push(r)});const b=l==="all"?t.routeIds:l,C=r=>({id:r.id,name:r.name,isTemplateSection:r.isTemplateSection??!1,templateDescription:r.templateDescription,component:r.component,config:r.config,visibility:r.visibility,sections:r?.sectionIds?L(r?.sectionIds?.map(p=>{const m=r.sections?.[p];return m&&C(m)})):void 0}),R=(r,p)=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,meta:r.locales?.[p]??{},sections:L(r.sectionIds.map(m=>{const T=r.sections[m];return T&&C(T)})),dataSource:Object.fromEntries(Object.entries(r.dataSource||{}).map(([m,T])=>[m,T?.[p]??{}]))}),w=r=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,path:r.path,handler:r.handler,isPublic:r.isPublic??!0,params:r.params??[],enabledGenerate:r.enabledGenerate??!1,displayTemplateId:r.displayTemplateId,dataSource:r.dataSource}),g=L(b.map(r=>{const p=t.routes[r];return p&&w(p)})),d=L(t.supportedLocales.map(r=>r.locale).flatMap(r=>i.map(p=>{const m=t.pages[p];return m&&{locale:r,slug:m.slug,page:R(m,r)}}))),I=ze(),D=f.join(I,"pages");await O.mkdir(D,{recursive:!0});const P=f.join(I,"components");await O.mkdir(P,{recursive:!0});const y=f.join(I,"routes");await O.mkdir(y,{recursive:!0});for(const{locale:r,slug:p,page:m}of d)await te(m,D,{getFilename:()=>`${re(p)||"index"}.${r}.yml`,exportAssets:e});for(const r of g)await te(r,y,{getFilename:()=>`${re(r.path)||"index"}.yml`,exportAssets:e});for(const r of c){const p=t.components[r]?.data;p&&await te(p,P,{getFilename:m=>`${m.name||"unnamed"}.${m.id}.yml`,exportAssets:e})}const v=f.join(I,".blocklet/pages/pages.config.yml");await O.mkdir(f.dirname(v),{recursive:!0});const h={pages:L(i.map(r=>{const p=t.pages[r];return p&&{id:r,slug:p.slug}})),routes:L(b.map(r=>{const p=t.routes[r];return p&&{id:r,path:p.path}})),components:L(c.map(r=>{const p=t.components[r]?.data;return p&&{id:r,name:p.name}})),...o?{resources:{components:L(Object.keys(t.resources?.components||{}).filter(r=>c.includes(r)).map(r=>({id:r,name:t.resources?.components?.[r]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};await O.writeFile(v,K.stringify(h));const S=f.join(I,"config.source.json");if(n&&await O.writeFile(S,JSON.stringify(n)),o){const r=f.join(I,"resources"),p=f.join(r,"components");await O.mkdir(p,{recursive:!0});for(const M of Object.keys(t?.resources?.components??{}).filter(_=>c.includes(_))){const _=t.resources?.components?.[M]?.component;_&&await te(_,p,{getFilename:x=>`${x.name||"unnamed"}.${x.id}.yml`,exportAssets:e})}const m=f.join(I,"chunks");await O.mkdir(m,{recursive:!0});const T=await Qt();for(const M of Object.keys(t?.resources?.components??{}).filter(_=>c.includes(_))){const _=t.resources?.components?.[M]?.component;if(_&&_.renderer?.type==="react-component"){const x=_.renderer?.chunks??[];if(x?.length>0)for(const Y of x){const Ue=f.join(m,Y),pe=T?.[Y];try{pe&&await q(pe)&&!await q(Ue)&&await O.copyFile(pe,Ue)}catch(ot){u.logger.error(`copy chunk ${Y} error`,ot.message)}}}}}return I}async function Le(t,{importAssets:e,includeResources:a}={}){if(!await q(t))return null;let s,n=!1;try{(await O.lstat(t)).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(n=!0,s=ze(),await Et.x({file:t,C:s}));const i=(await se.glob("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}))[0],c=i&&f.join(f.dirname(i),"../../pages"),b=i&&f.join(f.dirname(i),"../../components"),C=i&&f.join(f.dirname(i),"../../routes");if(!i)return null;const R=await O.readFile(i,"utf-8"),w=K.parse(R),g=async(h,S,r)=>{let p=f.join(h,`${S}${r?`.${r}`:""}.yml`);if(!await q(p)&&(p=f.join(h,S,`index${r?`.${r}`:""}.yml`),!await q(p))||!(await O.lstat(p)).isFile())return null;const T=await O.readFile(p,"utf-8");return K.parse(T)},d=async(h,S)=>{try{const p=(await se.glob(`*.${S}.yml`,{cwd:h,absolute:!0}))[0];if(!p)return null;const m=await O.readFile(p,"utf-8");return K.parse(m)}catch(r){u.logger.error("parse component error",r)}return null},I=async(h,S)=>{let r=f.join(h,`${S}.yml`);if(!await q(r)&&(r=f.join(h,S,"index.yml"),!await q(r))||!(await O.lstat(r)).isFile())return null;const m=await O.readFile(r,"utf-8");return K.parse(m)},D=L(await Promise.all(w.pages.map(async({slug:h})=>{const S=L(await Promise.all(w.supportedLocales.map(async({locale:m})=>{const T=c?await g(c,re(h),m):void 0;if(T)return{locale:m,page:T};const M=c?await g(c,h,m):void 0;return M&&{locale:m,page:M}}))),r=S[0]?.page;if(!r)return null;const p=r.sections.map(ut.unzipSection);return{id:r.id||Me.nextId(),createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,slug:h,sections:Object.fromEntries(p.map(m=>[m.id,m])),sectionIds:p.map(m=>m.id),locales:Object.fromEntries(S.map(({locale:m,page:T})=>[m,T.meta])),dataSource:r.dataSource?Object.fromEntries([...new Set(S.flatMap(({page:m})=>Object.keys(m.dataSource??{})))].map(m=>[m,Object.fromEntries(S.map(({locale:T,page:M})=>{const _=M.dataSource?.[m];return[T,_||{}]}))])):Object.fromEntries([...new Set(S.flatMap(({page:m})=>m.sections.map(T=>T.id)))].map(m=>[m,Object.fromEntries(S.map(({locale:T,page:M})=>{const _=M.dataSource?.[m];if(_)return[T,_];const x=M.sections.find(Y=>Y.id===m);return[T,x?.properties||{}]}))]))}}))),P=L(await Promise.all((w?.routes||[]).map(async({path:h})=>{const S=C?await I(C,re(h)):void 0;return{...S,id:S?.id||Me.nextId(),createdAt:S?.createdAt??new Date().toISOString(),updatedAt:S?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:S?.path??`/${S?.id}`,params:S?.params,handler:S?.handler??"Pages Kit",isPublic:S?.isPublic??!0,enabledGenerate:S?.enabledGenerate??!1,displayTemplateId:S?.displayTemplateId??void 0,dataSource:S?.dataSource??{}}}))),y=b?L(await Promise.all((w.components||[]).map(async({id:h})=>d(b,h)))):[];if(e){const h=(...S)=>{u.logger.info(`[${n?f.basename(t):f.basename(f.join(t,"../../../../"))}] importAssets:`,...S)};try{h("wait image-bin api ready"),await Ot.default({resources:[`${Ae.getComponentWebEndpoint(u.IMAGE_BIN_NAME)}/api/sdk/uploads`],validateStatus:p=>p>=200&&p<=500}),h("image-bin api is ready");const S={},r={};h("start to upload assets"),await Promise.allSettled([xe(y,S,{getFilePath:p=>b&&f.join(b,p),onFinish:p=>{h(`upload ${p.length} component assets`)}}),xe(D,r,{getFilePath:(p,m)=>{const T=De.default(D,m.slice(0,1));return c&&f.join(c,f.dirname(T.slug),p)},onFinish:p=>{h(`upload ${p.length} page assets`)}})]),h("upload assets done"),Ee.clear(),global.gc&&global.gc()}catch(S){h("Error during asset import:",S)}}const v={};if(a){const h=i&&f.join(f.dirname(i),"../../resources/components"),S=L(await Promise.all((w.resources?.components||[]).map(async({id:r})=>d(h,r))));S.length>0&&(v.components=Object.fromEntries(S.map((r,p)=>[r.id,{index:p,component:r}])))}return{supportedLocales:w.supportedLocales,pageIds:D.map(h=>h.id),components:Object.fromEntries(y.map((h,S)=>[h.id,{index:S,data:h}])),pages:Object.fromEntries(D.map(h=>[h.id,h])),config:w.config||{},resources:v,routeIds:P.map(h=>h.id),routes:Object.fromEntries(P.map(h=>[h.id,h])),dataSourceIds:[],dataSources:{}}}finally{n&&s&&await O.rm(s,{force:!0,recursive:!0})}}async function Pe(t,e,{routes:a,mergeMode:s="byUpdateTime",deleteRoutes:n=!1,publishMode:o=void 0}={}){try{o&&u.clearPreloadComponentsCacheByMode(o)}catch(w){u.logger.error("clear preload page cache error",{error:w})}const{pages:l,pageIds:i,routeIds:c,routes:b,supportedLocales:C}=t;if(o==="production"){let w=a??[],g=null;for(const d of c??[]){const I=b?.[d];if(I?.params&&I?.params.length>0&&I?.paramsOptions&&I?.paramsOptions.length>0){const D=ae.generateParamCombinations({basePath:I.path,params:I.params,routeId:I.id,paramsOptions:I.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),P=Object.fromEntries(D.map(y=>[`${d}-${y.paramOptionIds.join("-")}`,y]));g={...g||{},...P},a||(w=[...w,...D.map(y=>`${d}-${y.paramOptionIds.join("-")}`)])}else a||w.push(d)}u.logger.info("routeIds to be published: ",w);for(const d of w){let I=d;if(I.includes("-")){const[y]=I.split("-");I=y}const D=b?.[I];if(!D){const y=e.pageIds.indexOf(I);y!==-1&&n&&(e.pageIds.splice(y,1),delete e.pages[I]);for(const v of e.pageIds)v.includes(`${I}-`)&&(e.pageIds.splice(e.pageIds.indexOf(v),1),delete e.pages[v]);u.logger.info("delete main route page",I);continue}if(d.includes("-")&&!g?.[d]){const y=e.pageIds.indexOf(d);y!==-1&&n&&(e.pageIds.splice(y,1),delete e.pages[d]),u.logger.info("delete page",d);continue}if(!D.displayTemplateId){u.logger.info("no display template",d);continue}const P=l[D.displayTemplateId];if(!P){u.logger.info("no template page",d);continue}if(e.pageIds.includes(d)){if(u.logger.info("has need update page",d),s==="replace")e.pages[d]=me({page:P,route:D,state:t,routeId:d,routePathInfo:g?.[d]}),u.logger.info("replace page",d);else if(s==="byUpdateTime"){const y=e.pages[D.id];(!y||D.updatedAt&&D.updatedAt>y.updatedAt)&&(e.pages[d]=me({page:P,route:D,state:t,routeId:d,routePathInfo:g?.[d]}),u.logger.info("replace page by update time",d))}}else e.pageIds.push(d),e.pages[d]=me({page:P,route:D,state:t,routeId:d,routePathInfo:g?.[d]}),u.logger.info("add page",d)}if(n&&!a)for(const d of e.pageIds)w?.includes(d)||(delete e.pages[d],u.logger.info("delete page",d)),e.pageIds=[...e.pageIds].filter(I=>w?.includes(I))}else{for(const w of i){const g=l[w];if(g)if(e.pageIds.includes(g.id)){if(s==="replace")e.pages[g.id]=g;else if(s==="byUpdateTime"){const d=e.pages[g.id];(!d||g.updatedAt&&g.updatedAt>d.updatedAt)&&(e.pages[g.id]=g)}}else e.pageIds.push(g.id),e.pages[g.id]=g}for(const w of c){const g=b[w];if(g)if(e.routeIds.includes(g.id)){if(s==="replace")e.routes[g.id]=g;else if(s==="byUpdateTime"){const d=e.routes[g.id];(!d||g.updatedAt&&g.updatedAt>d.updatedAt)&&(e.routes[g.id]=g)}}else e.routeIds.push(g.id),e.routes[g.id]=g}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Oe.default(C)),n)for(const w of Object.keys(e.components))delete e.components[w];let R=JSON.parse(JSON.stringify(t.components));R=Object.fromEntries(await Promise.all(Object.entries(R).map(async([w,g])=>{const d=await Xe(g?.data);return[w,{...g,data:d}]}))),Object.assign(e.components,R),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Te.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const Xe=u.memoizeWithFs(async t=>{if(!Te.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:a}=t?.renderer||{};if(a||e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await u.getExportSchemaValueFromCode(e??"","PROPERTIES_SCHEMA",t.id,a);s&&s.length>0&&t&&(t.properties={},s.forEach((n,o)=>{t?.properties&&(t.properties[n.id]={index:o,data:n})}))}catch(s){u.logger.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ie,Q,le,ue;const Qe=()=>Ae.getResources({types:[{did:ve,type:we},{did:Rt,type:we}]}),Qt=async()=>{const t=Qe(),e={};for(const a of t){const n=(await se.glob("**/.blocklet/pages/pages.config.yml",{cwd:a.path,absolute:!0}))[0],o=n&&f.join(f.dirname(n),"../../chunks");if(o&&await q(o)){const l=await O.readdir(o);for(const i of l)e[i]=f.join(o,i)}}return e};function Ze(){return ie=(async()=>{const t=Qe();Q=(await Promise.all(t.map(async a=>{const s=a.path?await Le(a.path,{importAssets:!1}):void 0;return s?{blockletId:a.did,state:s,blockletTitle:a.title}:void 0}))).filter(a=>!!a),le=Q.reduce((a,s)=>Object.assign(a,Object.fromEntries(Object.values(s.state.pages).map(n=>n?[n?.id,{page:n,blockletId:s.blockletId}]:[]))),{});const e=Q.reduce((a,s)=>Object.assign(a,Object.fromEntries(Object.values(s.state.components).map(n=>[n.data.id,{blockletId:s.blockletId,component:n.data}]))),{});ue=Object.fromEntries(await Promise.all(Object.entries(e).map(async([a,s])=>{const n=await Xe(s.component);return[a,{...s,component:n}]})))})(),ie}function et(t){const e=Ce.default(async()=>{await Ze().catch(a=>{u.logger.error("load resource states error",{error:a})}),await t?.({states:Q,pages:le,components:ue})},3e3,{leading:!1,trailing:!0});return e(),E.default.events.on(E.default.Events.componentAdded,e),E.default.events.on(E.default.Events.componentRemoved,e),E.default.events.on(E.default.Events.componentStarted,e),E.default.events.on(E.default.Events.componentStopped,e),E.default.events.on(E.default.Events.componentUpdated,e),E.default.events.on(Ie,e),()=>{E.default.events.off(E.default.Events.componentAdded,e),E.default.events.off(E.default.Events.componentRemoved,e),E.default.events.off(E.default.Events.componentStarted,e),E.default.events.off(E.default.Events.componentStopped,e),E.default.events.off(E.default.Events.componentUpdated,e),E.default.events.off(Ie,e)}}const tt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),at=Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"),de=globalThis;de[tt]?.();de[tt]=et(async({pages:t,components:e})=>{const a=await j.getProjectIds();u.logger.info(`start update resource states projects(${a.length})`,a);const s=Re.default(10);await Promise.race([new Promise(n=>{setTimeout(()=>{n({})},30*1e3)}),Promise.all(a.map(n=>s(async()=>{st({projectId:n,pages:t,components:e})})))]).catch(n=>{u.logger.error("update resource states failed:",n)})});de[at]?.();de[at]=()=>{const t=()=>{j.pageUrlMapCache.clear(),u.logger.info("[Cache CLEAR ALL] clear all page url map cache by env update")};return E.default.events.on(E.default.Events.envUpdate,t),()=>{E.default.events.off(E.default.Events.envUpdate,t)}};j.startPeriodicCheck();process.on("beforeExit",()=>{j.stopPeriodicCheck()});process.on("SIGINT",()=>{j.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{j.stopPeriodicCheck(),process.exit(0)});async function st({projectId:t,pages:e,components:a}){const s=j.sharedInstances[t];if(!s){u.logger.info(`projectId: ${t} not found in sharedInstances`);return}s.transact(async()=>{if(s.syncedStore.resources.pages=e,(await U.findByPk(t))?.useAllResources)s.syncedStore.resources.components=a;else{const l=(await ke.findAll({where:{projectId:t}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(a||{}).filter(([c])=>l.includes(c)));s.syncedStore.resources.components=i}}),u.logger.info(`update [${t}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}const ye=new Map;async function nt(t){if(!ye.has(t)){const e=Ce.default(async a=>st({projectId:a,pages:le,components:ue}),3e3);ye.set(t,e)}return ye.get(t)(t)}async function Zt(){u.logger.info("trigger reload all project resource"),E.default.events.emit(Ie)}async function ea({ensureLoaded:t=!0}={}){return t&&(ie??=Ze(),await ie),{states:Q,pages:le,components:ue}}exports.COMPONENT_DID=ve;exports.PUBLISH_MODES=Wt;exports.Project=U;exports.RESOURCE_TYPE=we;exports.SITE_STATE_PATH=z;exports.STATE_MODES=Jt;exports.SiteState=j;exports.copyRecursive=$t;exports.downloadAsset=Ye;exports.downloadAssets=He;exports.fromPackage=Le;exports.getDefaultState=Ke;exports.getResourceStates=ea;exports.initPackResourceStates=et;exports.mergeState=Pe;exports.toPackage=We;exports.triggerReloadAllProjectResource=Zt;exports.updateResourceStatesByProjectId=nt;
|