@blocklet/pages-kit-inner-components 0.6.103 → 0.6.105

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.
Files changed (34) hide show
  1. package/lib/cjs/add-component.js +1 -1
  2. package/lib/cjs/chunks/components-BmFOXvb0.js +57 -0
  3. package/lib/cjs/chunks/{draft-data-CkVvOh60.js → draft-data-e1KnFlxv.js} +1 -1
  4. package/lib/cjs/chunks/{home-DdN3Z-6B.js → home-DHmHyTMb.js} +10 -10
  5. package/lib/cjs/chunks/{index-B-Wh6PRT.js → index-Cu2Jg8OH.js} +24 -24
  6. package/lib/cjs/chunks/{publish-button-BtLFUEny.js → publish-button-Do7oJLSH.js} +1 -1
  7. package/lib/cjs/chunks/site-state-BQySNTiP.js +1 -0
  8. package/lib/cjs/chunks/state-DU3L5Lve.js +1 -0
  9. package/lib/cjs/components.js +1 -1
  10. package/lib/cjs/home.js +1 -1
  11. package/lib/cjs/project-html.js +1 -1
  12. package/lib/cjs/resources.js +1 -1
  13. package/lib/cjs/setting.js +3 -3
  14. package/lib/cjs/site-state.js +1 -1
  15. package/lib/es/add-component.js +2 -2
  16. package/lib/es/chunks/components-DLjI_Xlm.js +615 -0
  17. package/lib/es/chunks/{draft-data-BOoVhbon.js → draft-data-DRdPzuGm.js} +1 -1
  18. package/lib/es/chunks/{home-DVTVPkSm.js → home-DajDpGXA.js} +123 -123
  19. package/lib/es/chunks/{index-DENjTU8O.js → index-BpP1FqET.js} +239 -238
  20. package/lib/es/chunks/{publish-button-BVcMw8Fh.js → publish-button-8kEbdc0k.js} +3 -3
  21. package/lib/es/chunks/site-state-DS7eIMFg.js +1684 -0
  22. package/lib/es/chunks/{state-DNdwHwty.js → state-qDCrgEMQ.js} +114 -113
  23. package/lib/es/components.js +14 -13
  24. package/lib/es/home.js +3 -3
  25. package/lib/es/project-html.js +1 -1
  26. package/lib/es/resources.js +2 -2
  27. package/lib/es/setting.js +415 -413
  28. package/lib/es/site-state.js +2 -2
  29. package/package.json +7 -7
  30. package/lib/cjs/chunks/components-DsHjikTX.js +0 -57
  31. package/lib/cjs/chunks/site-state-DlLhHuIr.js +0 -1
  32. package/lib/cjs/chunks/state-BdtFHk36.js +0 -1
  33. package/lib/es/chunks/components-BIhMGXjB.js +0 -610
  34. package/lib/es/chunks/site-state-CN4Kulgk.js +0 -1671
@@ -1,1671 +0,0 @@
1
- import { d as Fe, l as f, I as st, c as ot, m as at, b as nt } from "./components-BIhMGXjB.js";
2
- import { getYjsValue as V, syncedStore as rt } from "@syncedstore/core";
3
- import * as N from "yjs";
4
- import { setPageDataSource as it } from "@blocklet/pages-kit/utils/data-source";
5
- import { getRouteMetaDataByOptionIds as ct, generateParamCombinations as Ie } from "@blocklet/pages-kit/utils/route";
6
- import Ee from "lodash/cloneDeep";
7
- import E from "@blocklet/sdk/lib/config";
8
- import { mkdtempSync as lt, existsSync as $, readFileSync as J, renameSync as Re, mkdirSync as _, rmSync as Ge, writeFileSync as te, copyFileSync as pt, lstatSync as x, readdirSync as ut, createWriteStream as dt } from "fs";
9
- import { join as b, basename as k, dirname as L } from "path";
10
- import { nextId as De } from "@blocklet/pages-kit/utils/common";
11
- import { unzipSection as ft } from "@blocklet/pages-kit/utils/page-model";
12
- import { getComponentDependencies as mt } from "@blocklet/pages-kit/utils/property";
13
- import { getComponentWebEndpoint as gt, getResources as ht, call as yt } from "@blocklet/sdk/lib/component";
14
- import { reactive as St } from "@reactivedata/reactive";
15
- import { globSync as se } from "glob";
16
- import * as de from "lib0/decoding";
17
- import * as D from "lib0/encoding";
18
- import xe from "lodash/debounce";
19
- import be from "lodash/get";
20
- import Ae from "lodash/isEmpty";
21
- import Te from "lodash/set";
22
- import It from "lodash/union";
23
- import { LRUCache as we } from "lru-cache";
24
- import Be from "p-limit";
25
- import { DataTypes as R, Sequelize as Et, Model as Ve, Op as Pe } from "sequelize";
26
- import { pipeline as bt } from "stream/promises";
27
- import { x as At } from "tar";
28
- import { withoutTrailingSlash as Oe, withLeadingSlash as ze, joinURL as Y } from "ufo";
29
- import wt from "wait-on";
30
- import { Awareness as Pt, encodeAwarenessUpdate as ke, removeAwarenessStates as Ot, applyAwarenessUpdate as Ct } from "y-protocols/awareness";
31
- import { writeUpdate as vt, writeSyncStep1 as jt, readSyncMessage as Rt } from "y-protocols/sync";
32
- import * as B from "yaml";
33
- import { m as Le } from "./html-DOgzvdOd.js";
34
- import "sqlite3";
35
- import "@blocklet/pages-kit/types/state";
36
- const Dt = R.sqlite.DATE.parse;
37
- R.sqlite.DATE.parse = (t, e) => typeof t == "number" ? new Date(t) : Dt(t, e);
38
- const F = new Et({
39
- dialect: "sqlite",
40
- storage: Fe,
41
- benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
42
- retry: {
43
- match: [/SQLITE_BUSY/],
44
- name: "query",
45
- max: 10
46
- },
47
- // eslint-disable-next-line no-console
48
- logging: process.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
49
- // logQueryParameters: true,
50
- });
51
- F.query("PRAGMA journal_mode = WAL;");
52
- F.query("PRAGMA synchronous = normal;");
53
- F.query("PRAGMA journal_size_limit = 67108864;");
54
- F.query("PRAGMA cache_size = 10000;");
55
- process.on("SIGINT", async () => {
56
- await F.close(), process.exit(0);
57
- });
58
- process.on("SIGTERM", async () => {
59
- await F.close(), process.exit(0);
60
- });
61
- async function Tt(t, e) {
62
- try {
63
- if (t.getDialect() !== "sqlite")
64
- return;
65
- const [s] = await t.query("SELECT 1");
66
- if (!s || s.length === 0)
67
- return;
68
- await t.query("PRAGMA shrink_memory;");
69
- } catch (s) {
70
- if (s.name === "SequelizeConnectionError" || s?.message && /closed!/.test(s.message))
71
- return;
72
- console.error("Failed to cleanup SQLite memory", e, s);
73
- }
74
- }
75
- let ge = null;
76
- ge && clearInterval(ge);
77
- ge = setInterval(
78
- async () => {
79
- f.info("Start cleanupSqliteMemory"), await Tt(F, Fe), f.info("End cleanupSqliteMemory");
80
- },
81
- 60 * 1e3 * 10
82
- // 10 minutes
83
- );
84
- const kt = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", Ue = "page", he = "trigger-reload-project-resource", qe = kt, Lt = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM", Ut = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";
85
- class Ce extends Ve {
86
- // Foreign key to Component
87
- }
88
- Ce.init(
89
- {
90
- id: {
91
- type: R.UUID,
92
- allowNull: !1,
93
- primaryKey: !0,
94
- defaultValue: R.UUIDV4
95
- },
96
- projectId: {
97
- type: R.UUID,
98
- allowNull: !1
99
- },
100
- componentId: {
101
- type: R.STRING,
102
- allowNull: !1
103
- }
104
- },
105
- { sequelize: F, tableName: "ProjectComponents", timestamps: !1 }
106
- );
107
- const Mt = "SLUG_INVALID", K = (t) => ({
108
- error: "slugInvalid",
109
- code: Mt,
110
- field: "slug",
111
- message: t
112
- }), $t = {
113
- error: "slugRequired",
114
- code: "SLUG_REQUIRED",
115
- field: "slug",
116
- message: () => "Project slug is required"
117
- }, Nt = {
118
- error: "slugAlreadyExists",
119
- code: "SLUG_EXISTS",
120
- field: "slug",
121
- message: (t) => `Project slug "${t}" already exists`
122
- }, _t = [
123
- /\.\./,
124
- // Directory traversal
125
- /<[^>]*>/,
126
- // HTML/XML tags
127
- /%[0-9a-f]{2}/i,
128
- // Percent encoding
129
- /[<>'"%;{}()\\]/,
130
- // Special characters
131
- // eslint-disable-next-line no-control-regex
132
- /\x00/,
133
- // Null byte
134
- /\n|\r|\t|\v|\f/,
135
- // Control characters
136
- /[^a-zA-Z0-9-_@/\\:]/
137
- // Only allow specific characters
138
- ], Me = (t) => {
139
- if (!t) return "";
140
- if (t === "/") return "/";
141
- const e = Oe(t);
142
- return ze(e) || "/";
143
- }, Ft = (t) => t.did === Ut;
144
- class U extends Ve {
145
- static async getProjectByIdOrSlug(e, s) {
146
- return e ? U.findOne({
147
- where: {
148
- [Pe.or]: [{ id: e }, { slug: e }],
149
- ...s?.createdBy ? { createdBy: s.createdBy } : {}
150
- }
151
- }) : null;
152
- }
153
- static async validateProjectSlug({
154
- slug: e,
155
- projectId: s
156
- }) {
157
- if (e == null)
158
- return null;
159
- if (e === "")
160
- return $t;
161
- const o = e === "/" ? "/" : Oe(ze(e)), a = Me(o);
162
- if (o !== "/" && o.endsWith("/"))
163
- return K((r) => `Project slug "${r}" cannot end with /`);
164
- if (/\/{2,}/.test(o))
165
- return K((r) => `Project slug "${r}" cannot contain consecutive /`);
166
- if (/\s/.test(o))
167
- return K((r) => `Project slug "${r}" cannot contain whitespace`);
168
- if (_t.some((r) => r.test(o)))
169
- return K((r) => `Project slug "${r}" contains invalid characters`);
170
- if (E.components?.filter((r) => r.mountPoint && !Ft(r)).some((r) => Me(r.mountPoint) === a))
171
- return K((r) => `Project slug "${r}" conflicts with existing blocklet`);
172
- const c = await U.findOne({
173
- where: { slug: o }
174
- });
175
- return c && c?.id !== s ? Nt : null;
176
- }
177
- }
178
- U.init(
179
- {
180
- id: {
181
- type: R.UUID,
182
- defaultValue: R.UUIDV4,
183
- primaryKey: !0
184
- },
185
- name: {
186
- type: R.STRING,
187
- allowNull: !1
188
- },
189
- description: R.TEXT,
190
- createdAt: R.DATE,
191
- updatedAt: R.DATE,
192
- createdBy: {
193
- type: R.STRING,
194
- allowNull: !1
195
- },
196
- updatedBy: {
197
- type: R.STRING,
198
- allowNull: !1
199
- },
200
- slug: R.STRING,
201
- icon: R.STRING,
202
- pinnedAt: R.DATE,
203
- useAllResources: R.BOOLEAN,
204
- npmSecret: R.STRING,
205
- relatedBlocklets: {
206
- type: R.JSON,
207
- allowNull: !1,
208
- defaultValue: {},
209
- get() {
210
- const t = this.getDataValue("relatedBlocklets");
211
- if (typeof t == "object")
212
- return t ?? {};
213
- try {
214
- return t ? JSON.parse(t) : {};
215
- } catch (e) {
216
- return f.error("Failed to parse relatedBlocklets", { error: e, rawValue: t }), {};
217
- }
218
- },
219
- set(t) {
220
- try {
221
- this.setDataValue("relatedBlocklets", t ? JSON.stringify(t) : "{}");
222
- } catch (e) {
223
- f.error("Failed to set relatedBlocklets", { error: e, value: t }), this.setDataValue("relatedBlocklets", "{}");
224
- }
225
- }
226
- },
227
- productionState: {
228
- type: R.JSON,
229
- allowNull: !1,
230
- defaultValue: {},
231
- get() {
232
- const t = this.getDataValue("productionState");
233
- if (typeof t == "object")
234
- return t ?? {};
235
- try {
236
- return t ? JSON.parse(t) : {};
237
- } catch (e) {
238
- return f.error("Failed to parse productionState", { error: e, rawValue: t }), {};
239
- }
240
- },
241
- set(t) {
242
- try {
243
- this.setDataValue("productionState", t ? JSON.stringify(t) : "{}");
244
- } catch (e) {
245
- f.error("Failed to set productionState", { error: e, value: t }), this.setDataValue("productionState", "{}");
246
- }
247
- }
248
- },
249
- meta: {
250
- type: R.JSON,
251
- allowNull: !0
252
- }
253
- },
254
- {
255
- sequelize: F,
256
- paranoid: !0,
257
- indexes: [
258
- {
259
- name: "projects_slug_unique",
260
- unique: !0,
261
- fields: ["slug"]
262
- },
263
- {
264
- name: "projects_created_by",
265
- fields: ["createdBy"]
266
- },
267
- {
268
- name: "projects_pinned_updated_meta_not_null",
269
- fields: [
270
- { name: "pinnedAt", order: "DESC" },
271
- { name: "updatedAt", order: "DESC" }
272
- ],
273
- where: {
274
- meta: {
275
- [Pe.ne]: null
276
- }
277
- }
278
- }
279
- ]
280
- }
281
- );
282
- U.hasMany(Ce, {
283
- foreignKey: "projectId",
284
- as: "components"
285
- });
286
- function oe(t) {
287
- t.observeDeep((e) => {
288
- e.some((s) => s.changes.keys.has("updatedAt") || s.changes.keys.has("publishedAt")) || t.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
289
- });
290
- }
291
- function Ke() {
292
- return lt(b(E.env.dataDir, "tmp-"));
293
- }
294
- function ae(t, e, s = []) {
295
- return Array.isArray(t) ? t.flatMap((o, a) => ae(o, e, [...s, a])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([o, a]) => ae(a, e, [...s, o])) : e(t) ? [s] : [];
296
- }
297
- function T(t) {
298
- return t.filter((e) => e != null);
299
- }
300
- function Gt(t) {
301
- t.pages && Object.keys(t.pages).forEach((s) => {
302
- const o = V(t.pages[s]);
303
- o && o instanceof N.Map && oe(o);
304
- });
305
- const e = V(t.pages);
306
- e && e instanceof N.Map && e.observe((s) => {
307
- s.changes.keys.forEach((o, a) => {
308
- if (o.action === "add") {
309
- const n = V(t.pages[a]);
310
- n && n instanceof N.Map && oe(n);
311
- }
312
- });
313
- });
314
- }
315
- function xt(t) {
316
- t.routes && Object.keys(t.routes).forEach((s) => {
317
- const o = V(t.routes?.[s]);
318
- o && o instanceof N.Map && oe(o);
319
- });
320
- const e = V(t.routes);
321
- e && e instanceof N.Map && e.observe((s) => {
322
- s.changes.keys.forEach((o, a) => {
323
- if (o.action === "add") {
324
- const n = V(t.routes?.[a]);
325
- n && n instanceof N.Map && oe(n);
326
- }
327
- });
328
- });
329
- }
330
- function Bt(t, e) {
331
- for (const s of e || Object.keys(t.routes || {})) {
332
- let o = s, a = [];
333
- if (s.includes("-")) {
334
- const [n, ...c] = s.split("-");
335
- o = n, a = c || [];
336
- }
337
- if (t.routes?.[o] !== void 0) {
338
- t.routes[o].publishedAt = (/* @__PURE__ */ new Date()).toISOString();
339
- const n = t.routes[o];
340
- if (!n || !n.params || n.params.length === 0)
341
- continue;
342
- if (s.includes("-") && a.length > 0) {
343
- const c = ct(a, n);
344
- c && (c.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
345
- }
346
- if (!e) {
347
- const c = Ie({
348
- basePath: n.path,
349
- params: n.params,
350
- routeId: n.id,
351
- paramsOptions: n.paramsOptions,
352
- currentIndex: 0,
353
- currentParams: [],
354
- currentOptionIds: [],
355
- result: []
356
- });
357
- for (const r of c)
358
- r.routeMetaData ??= {}, r.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString();
359
- }
360
- }
361
- }
362
- }
363
- function fe({
364
- page: t,
365
- route: e,
366
- state: s,
367
- routeId: o,
368
- routePathInfo: a
369
- }) {
370
- f.info(
371
- `Executing datasource data assembly, routeId: ${o}, routePathInfo: ${JSON.stringify(a)}`
372
- );
373
- const n = {
374
- ...Ee(t),
375
- id: o,
376
- slug: a?.path ?? e.path,
377
- createdAt: e.createdAt,
378
- updatedAt: a?.routeMetaData?.updatedAt ?? e.updatedAt,
379
- publishedAt: a?.routeMetaData?.publishedAt ?? e.publishedAt,
380
- isPublic: (a?.routeMetaData?.isPublic ?? e.isPublic) && e.isPublic
381
- };
382
- for (const c of s.supportedLocales) {
383
- if (e.dataSource) {
384
- let r = e.id;
385
- a && (r = a.paramOptionIds.join("-"));
386
- const l = e.dataSource.pathDataMappings?.[r]?.dataCache?.[c.locale] ?? e.dataSource.pathDataMappings?.[r]?.dataCache?.[s.config.defaultLocale || "en"];
387
- if (!l)
388
- continue;
389
- it(n, s, c.locale, l);
390
- }
391
- a && a.routeMetaData && (a.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
392
- }
393
- return n;
394
- }
395
- ["true", "1", "yes", "y"].includes(process.env.USE_FS_CACHE_HTML ?? "");
396
- const Vt = 60 * 60 * 1e3, W = new we({
397
- max: 300,
398
- ttl: Vt,
399
- ttlResolution: 10 * 1e3,
400
- // 10 seconds
401
- allowStale: !0
402
- });
403
- function zt(t, e = []) {
404
- let s = 0;
405
- const o = Array.from(W.keys()), a = t.map((n) => Oe(n));
406
- for (const n of o)
407
- for (const c of a) {
408
- if (Le(n, { currentPath: c })) {
409
- W.delete(n), s++, f.info(`[Cache CLEAR] key: ${n}`);
410
- break;
411
- }
412
- for (const r of e)
413
- if (Le(n, { currentPath: `/${r}${c}` })) {
414
- W.delete(n), s++, f.info(`[Cache CLEAR] key: ${n}`);
415
- break;
416
- }
417
- }
418
- return f.info(`[Cache CLEAR] cleared ${s} entries for paths:`, a), s;
419
- }
420
- function qt() {
421
- const t = W.size;
422
- return W.clear(), f.info(`[Cache CLEAR ALL] cleared ${t} entries`), t;
423
- }
424
- E.events.on(E.Events.envUpdate, qt);
425
- const { uploadToMediaKit: Kt } = require("@blocklet/uploader-server"), ve = /^\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, $e = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, Ht = 1e4, Jt = 3e4, Z = 0, me = 1, Yt = 0, Wt = 1, ye = E, H = b(process.env.BLOCKLET_DATA_DIR, "site-state"), $s = ["production", "draft"], Ns = ["production"];
426
- function ne(t) {
427
- return t?.replace(/\//g, "|") || "";
428
- }
429
- function Xt() {
430
- const t = ye.env.languages?.map((s) => ({ locale: s.code, name: s.name })) || [], e = t[0]?.locale || "en";
431
- return {
432
- pageIds: [],
433
- pages: {},
434
- routeIds: [],
435
- routes: {},
436
- dataSourceIds: [],
437
- dataSources: {},
438
- components: {},
439
- supportedLocales: t,
440
- config: { defaultLocale: e },
441
- resources: {}
442
- };
443
- }
444
- class C extends N.Doc {
445
- constructor(e) {
446
- super(), this.options = e, $(this.draftYjsFilePath) && N.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore = St(
447
- rt(
448
- {
449
- pages: {},
450
- pageIds: [],
451
- components: {},
452
- supportedLocales: [],
453
- config: {},
454
- resources: {},
455
- routeIds: [],
456
- routes: {},
457
- dataSourceIds: [],
458
- dataSources: {}
459
- },
460
- this
461
- )
462
- ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new Pt(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
463
- }
464
- // 延迟释放时间:5 分钟
465
- static RELEASE_DELAY = 5 * 60 * 1e3;
466
- // 定期检查间隔:2 小时
467
- static PERIODIC_CHECK_INTERVAL = 2 * 60 * 60 * 1e3;
468
- // 2 hours
469
- static sharedInstances = {};
470
- static pageUrlMapCache = new we({
471
- max: 300,
472
- ttl: 1e3 * 60 * 60 * 24
473
- // 1 day
474
- });
475
- // 定期检查定时器
476
- static periodicCheckTimer;
477
- // safe delete project state dir
478
- static safeDeleteProjectStateDir(e) {
479
- if (!e)
480
- throw new Error("Should provide project context");
481
- try {
482
- const s = b(H, e), o = b(H, `@del-${e}`);
483
- Re(s, o);
484
- } catch (s) {
485
- f.error("Failed to safe delete project state dir:", s);
486
- }
487
- }
488
- static async getProjectIds() {
489
- return (await U.findAll({ attributes: ["id"], raw: !0 }))?.map((e) => e.id);
490
- }
491
- /** @deprecated 不再使用这个 getter 了,仅作为兼容性处理,请使用 getProjectIds 代替 */
492
- static get projectIds() {
493
- return se("*/", {
494
- cwd: H,
495
- ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*", "undefined"]
496
- // Ignore temp directories and hidden files
497
- });
498
- }
499
- /** @deprecated 不再使用这个 getter 了,仅作为兼容性处理 */
500
- static get allShared() {
501
- return this.projectIds.map((e) => C.shared(e));
502
- }
503
- static shared(e) {
504
- if (!e)
505
- throw new Error("Should provide project context");
506
- let s = C.sharedInstances[e];
507
- return s || (s = new C({
508
- path: b(H, e)
509
- }), C.sharedInstances[e] = s, s);
510
- }
511
- // 轻量级 production 状态获取,不加载 draft 数据
512
- static async getProductionState(e) {
513
- const s = await U.findByPk(e, {
514
- attributes: ["productionState"]
515
- });
516
- if (Ae(s?.productionState)) {
517
- const o = b(H, e, "production"), a = await Je(o, { includeResources: !0 }) ?? Xt();
518
- if (!a?.config?.defaultLocale) {
519
- a.config ??= {};
520
- const n = ye.env.languages?.map((c) => ({ locale: c.code, name: c.name })) || [];
521
- a.config.defaultLocale = n[0]?.locale;
522
- }
523
- return a;
524
- }
525
- return s?.productionState;
526
- }
527
- destroy() {
528
- this.cancelRelease(), this.save({ flush: !0 }), this.conns.forEach((s, o) => this.closeConn(o)), this.awareness.destroy();
529
- const e = k(this.options.path);
530
- delete C.sharedInstances[e], super.destroy();
531
- }
532
- initObserver() {
533
- Gt(this.syncedStore), xt(this.syncedStore);
534
- }
535
- get draftYjsFilePath() {
536
- return b(this.options.path, "draft.yjs");
537
- }
538
- static async getStateByProjectId(e, s) {
539
- if (s === "draft") {
540
- const o = C.shared(e);
541
- return JSON.parse(JSON.stringify(o.syncedStore));
542
- }
543
- return C.getProductionState(e);
544
- }
545
- async getState(e) {
546
- if (e === "draft")
547
- return JSON.parse(JSON.stringify(this.syncedStore));
548
- const s = k(this.options.path);
549
- return C.getProductionState(s);
550
- }
551
- async setState(e, s) {
552
- const o = await ts(s, { exportAssets: !1, includeResources: !0 }), a = this.getPublishDir(e);
553
- if (_(L(a), { recursive: !0 }), Ge(a, { force: !0, recursive: !0 }), Re(o, a), e === "production") {
554
- const n = k(this.options.path);
555
- C.pageUrlMapCache.delete(n);
556
- const c = Ee(s);
557
- await U.update({ productionState: c }, { where: { id: n } });
558
- }
559
- }
560
- getPublishDir(e) {
561
- return b(this.options.path, e);
562
- }
563
- syncedStore;
564
- conns = /* @__PURE__ */ new Map();
565
- awareness;
566
- // 延迟释放定时器
567
- releaseTimer;
568
- awarenessChangeHandler = ({ added: e, updated: s, removed: o }, a) => {
569
- const n = e.concat(s, o);
570
- if (a !== null) {
571
- const l = this.conns.get(a);
572
- l && (e.forEach((y) => {
573
- l.add(y);
574
- }), o.forEach((y) => {
575
- l.delete(y);
576
- }));
577
- }
578
- const c = D.createEncoder();
579
- D.writeVarUint(c, me), D.writeVarUint8Array(c, ke(this.awareness, n));
580
- const r = D.toUint8Array(c);
581
- this.conns.forEach((l, y) => this.send(y, r));
582
- };
583
- updateHandler = (e) => {
584
- const s = D.createEncoder();
585
- D.writeVarUint(s, Z), vt(s, e);
586
- const o = D.toUint8Array(s);
587
- this.conns.forEach((a, n) => this.send(n, o));
588
- };
589
- ensureDataStructure = () => {
590
- const { supportedLocales: e, pages: s, pageIds: o, config: a, routes: n, routeIds: c } = this.syncedStore;
591
- {
592
- const r = new Set(Object.keys(s));
593
- let l = 0;
594
- for (; l < o.length; ) {
595
- const y = o[l];
596
- r.has(y) ? (r.delete(y), l++) : o.splice(l, 1);
597
- }
598
- }
599
- {
600
- const r = new Set(Object.keys(n));
601
- let l = 0;
602
- for (; l < c.length; ) {
603
- const y = c[l];
604
- r.has(y) ? (r.delete(y), l++) : c.splice(l, 1);
605
- }
606
- }
607
- e.splice(0, e.length), e.push(...ye.env.languages.map((r) => ({ locale: r.code, name: r.name }))), a.defaultLocale = e[0]?.locale;
608
- {
609
- let r = 0;
610
- const l = /* @__PURE__ */ new Set();
611
- for (; r < e.length; ) {
612
- const { locale: y } = e[r];
613
- l.has(y) ? e.splice(r, 1) : (r++, l.add(y));
614
- }
615
- }
616
- };
617
- send = (e, s) => {
618
- e.readyState !== Yt && e.readyState !== Wt && this.closeConn(e);
619
- try {
620
- e.send(s, (o) => {
621
- o && this.closeConn(e);
622
- });
623
- } catch {
624
- this.closeConn(e);
625
- }
626
- };
627
- closeConn = (e) => {
628
- if (e.removeAllListeners(), this.conns.has(e)) {
629
- const s = this.conns.get(e);
630
- this.conns.delete(e), s && Ot(this.awareness, Array.from(s), null);
631
- }
632
- e.close(), this.checkAndScheduleRelease();
633
- };
634
- // 检查并调度延迟释放
635
- checkAndScheduleRelease() {
636
- this.conns.size === 0 && this.scheduleRelease();
637
- }
638
- // 调度延迟释放
639
- scheduleRelease() {
640
- this.cancelRelease();
641
- const e = k(this.options.path);
642
- this.releaseTimer = setTimeout(() => {
643
- f.info(`[SiteState] releasing instance due to no active connections: ${e}`), this.conns.size === 0 && (this.releaseTimer = void 0, this.destroy());
644
- }, C.RELEASE_DELAY), f.info(`[SiteState] scheduled release for project ${e} in ${C.RELEASE_DELAY / 1e3}s`);
645
- }
646
- // 取消延迟释放
647
- cancelRelease() {
648
- if (this.releaseTimer) {
649
- clearTimeout(this.releaseTimer), this.releaseTimer = void 0;
650
- const e = k(this.options.path);
651
- f.info(`[SiteState] cancelled scheduled release for project ${e}`);
652
- }
653
- }
654
- autoSave = xe(() => {
655
- _(L(this.draftYjsFilePath), { recursive: !0 }), te(this.draftYjsFilePath, N.encodeStateAsUpdate(this));
656
- }, Ht);
657
- save = ({ flush: e = !1 } = {}) => {
658
- this.autoSave(), e && this.autoSave.flush();
659
- };
660
- publish = async ({ mode: e, routes: s }) => {
661
- const o = k(this.options.path);
662
- await as(o);
663
- const a = await this.getState("draft"), n = await this.getState("production");
664
- await _e(a, n, { routes: s, mergeMode: "replace", deleteRoutes: !0, publishMode: e }), n.config.publishedAt = (/* @__PURE__ */ new Date()).getTime(), Bt(this.syncedStore, s), await this.setState(e, n), await this.clearPageCacheForRoutes(s, n);
665
- };
666
- mergeState = async (e, s) => {
667
- const o = JSON.parse(JSON.stringify(s));
668
- e.config.fontFamily ??= {};
669
- const a = o.config?.fontFamily, n = e.config?.fontFamily;
670
- e.config.fontFamily.title = a?.title || n?.title, e.config.fontFamily.description = a?.description || n?.description, await new Promise((c, r) => {
671
- this.transact(async () => {
672
- try {
673
- const l = await _e(e, s);
674
- c(l);
675
- } catch (l) {
676
- r(l);
677
- }
678
- });
679
- });
680
- };
681
- clearPageCacheForRoutes = async (e, s) => {
682
- const o = k(this.options.path), n = (await U.findByPk(o))?.slug || o;
683
- let c = e;
684
- (!c || c.length === 0) && (c = s.pageIds ?? []), f.info(`[SiteState] clearing page cache for project ${o}, routes:`, c || []);
685
- const r = s.supportedLocales.map((O) => O.locale), l = [], y = c.filter((O) => s.pageIds?.includes(O));
686
- for (const O of y) {
687
- const S = s.pages[O].slug;
688
- n && n !== o && (n === "/" ? l.push(S) : l.push(`/${n}${S}`)), l.push(`/${o}${S}`);
689
- }
690
- if (l.length > 0)
691
- try {
692
- const O = zt(l, r);
693
- f.info(`[SiteState] cleared ${O} page cache entries for project ${o}, routes:`, c);
694
- } catch {
695
- }
696
- C.pageUrlMapCache.delete(o);
697
- };
698
- addConnection = (e) => {
699
- if (this.conns.has(e))
700
- return;
701
- this.cancelRelease(), e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (a) => this.messageListener(e, new Uint8Array(a)));
702
- let s = !0;
703
- const o = setInterval(() => {
704
- if (!s)
705
- this.conns.has(e) && this.closeConn(e), clearInterval(o);
706
- else if (this.conns.has(e)) {
707
- s = !1;
708
- try {
709
- e.ping();
710
- } catch {
711
- this.closeConn(e), clearInterval(o);
712
- }
713
- }
714
- }, Jt);
715
- e.on("close", () => {
716
- this.closeConn(e), clearInterval(o);
717
- }), e.on("pong", () => {
718
- s = !0;
719
- });
720
- {
721
- const a = D.createEncoder();
722
- D.writeVarUint(a, Z), jt(a, this), this.send(e, D.toUint8Array(a));
723
- const n = this.awareness.getStates();
724
- if (n.size > 0) {
725
- const c = D.createEncoder();
726
- D.writeVarUint(c, me), D.writeVarUint8Array(c, ke(this.awareness, Array.from(n.keys()))), this.send(e, D.toUint8Array(c));
727
- }
728
- }
729
- };
730
- messageListener = (e, s) => {
731
- try {
732
- const o = D.createEncoder(), a = de.createDecoder(s), n = de.readVarUint(a);
733
- switch (n) {
734
- case Z:
735
- D.writeVarUint(o, Z), Rt(a, o, this, null), D.length(o) > 1 && (this.ensureDataStructure(), this.send(e, D.toUint8Array(o)));
736
- break;
737
- case me: {
738
- Ct(this.awareness, de.readVarUint8Array(a), e);
739
- break;
740
- }
741
- default:
742
- f.warn(`Unsupported messageType ${n}`);
743
- }
744
- } catch (o) {
745
- f.error(o);
746
- }
747
- this.save();
748
- };
749
- // 这个方法还是需要动态的,因为可能会动态修改 projectSlug、语言之类的
750
- static async pageUrlMap(e, s) {
751
- f.info(`[SiteState] get pageUrlMap, mode: ${e}, projectId: ${s}`);
752
- let o = [];
753
- s ? o = [s] : o = await this.getProjectIds();
754
- let a = {};
755
- if (e === "production" && o?.length) {
756
- const n = new Map(o?.map((c) => [c, !0]) || []);
757
- for (const c of o) {
758
- const r = C.pageUrlMapCache.get(c);
759
- r && (f.info(`[SiteState] get pageUrlMap from cache, projectId: ${c}`), a = { ...a, ...r }, n.delete(c));
760
- }
761
- o = Array.from(n.keys());
762
- }
763
- if (o?.length) {
764
- const n = await U.findAll({
765
- where: {
766
- id: {
767
- [Pe.in]: o
768
- }
769
- }
770
- }), c = Be(10);
771
- await Promise.all(
772
- n?.map(
773
- (r) => c(async () => {
774
- const l = r.id, y = r.slug || l, O = {}, j = e === "production" && r?.productionState ? r.productionState : await C.getStateByProjectId(r.id, e), S = It(
775
- E.env.languages?.map((p) => p.code) || [],
776
- j.supportedLocales?.map((p) => p.locale) || []
777
- ), g = (p, d) => {
778
- y && (O[Y("/", y, p)] = {
779
- ...d,
780
- shouldRedirect: !0,
781
- mainPage: !0
782
- }), O[Y("/", l, p)] = {
783
- ...d,
784
- shouldRedirect: !0,
785
- mainPage: !0
786
- };
787
- for (const A of S) {
788
- const m = { ...d, locale: A };
789
- O[Y("/", A, l, p)] = m, y && (O[Y("/", A, y, p)] = m);
790
- }
791
- };
792
- if (e === "draft")
793
- for (const p of j.routeIds || []) {
794
- const d = j?.routes?.[p];
795
- if (!d) continue;
796
- if (d.params && d.params.length > 0) {
797
- const u = Ie({
798
- basePath: d.path,
799
- params: d.params,
800
- routeId: d.id,
801
- paramsOptions: d.paramsOptions,
802
- currentIndex: 0,
803
- currentParams: [],
804
- currentOptionIds: [],
805
- result: []
806
- });
807
- for (const h of u) {
808
- const P = h.path, w = {
809
- projectId: l,
810
- projectSlug: y,
811
- pageSlug: P,
812
- pageId: d.displayTemplateId || "",
813
- routeId: p,
814
- // default locale
815
- defaultLocale: S?.[0],
816
- locales: S,
817
- publishedAt: j.config.publishedAt,
818
- isPublic: d.isPublic && h?.routeMetaData?.isPublic
819
- };
820
- g(P, w);
821
- }
822
- }
823
- const A = d.path, m = {
824
- projectId: l,
825
- projectSlug: y,
826
- pageSlug: A,
827
- pageId: d.displayTemplateId || "",
828
- routeId: p,
829
- // default locale
830
- defaultLocale: S?.[0],
831
- locales: S,
832
- publishedAt: j.config.publishedAt,
833
- isPublic: d.isPublic
834
- };
835
- g(A, m);
836
- }
837
- for (const p of j.pageIds || []) {
838
- const d = j.pages[p];
839
- if (!d || e === "production" && !d.isPublic)
840
- continue;
841
- const A = d.slug, m = r.slug || l, u = {
842
- projectId: l,
843
- projectSlug: m,
844
- pageSlug: A,
845
- pageId: p,
846
- // default locale
847
- defaultLocale: S?.[0],
848
- locales: S,
849
- publishedAt: j.config.publishedAt,
850
- isPublic: d.isPublic,
851
- templateConfig: d.templateConfig
852
- };
853
- g(A, u);
854
- }
855
- e === "production" && (C.pageUrlMapCache.set(l, O), f.info(`[SiteState] set pageUrlMap to cache, projectId: ${l}`)), a = { ...a, ...O };
856
- })
857
- )
858
- );
859
- }
860
- return f.info("[SiteState] success get pageUrlMap"), a;
861
- }
862
- getDocumentSize() {
863
- return N.encodeStateAsUpdate(this).byteLength;
864
- }
865
- static getInstancesSizeInfo() {
866
- const e = [];
867
- for (const [s, o] of Object.entries(C.sharedInstances)) {
868
- const a = o.getDocumentSize();
869
- e.push({
870
- projectId: s,
871
- sizeInBytes: a,
872
- sizeInMB: `${(a / (1024 * 1024)).toFixed(2)} MB`,
873
- activeConnections: o.conns.size
874
- });
875
- }
876
- return e;
877
- }
878
- // 启动定期检查
879
- static startPeriodicCheck() {
880
- this.periodicCheckTimer || (this.periodicCheckTimer = setInterval(() => {
881
- this.performPeriodicCheck();
882
- }, this.PERIODIC_CHECK_INTERVAL), f.info(
883
- `[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL / (60 * 60 * 1e3)} hours`
884
- ));
885
- }
886
- // 停止定期检查
887
- static stopPeriodicCheck() {
888
- this.periodicCheckTimer && (clearInterval(this.periodicCheckTimer), this.periodicCheckTimer = void 0, f.info("[SiteState] periodic check stopped"));
889
- }
890
- // 执行定期检查
891
- static performPeriodicCheck() {
892
- const e = Object.keys(C.sharedInstances).length, s = [], o = [];
893
- for (const [a, n] of Object.entries(C.sharedInstances))
894
- n.conns.size === 0 ? s.push({ projectId: a, instance: n }) : o.push({ projectId: a, connections: n.conns.size });
895
- if (f.info(
896
- `[SiteState] periodic check summary: total instances: ${e}, with connections: ${o.length}, without connections: ${s.length}`
897
- ), s.length > 0) {
898
- f.info(
899
- `[SiteState] releasing ${s.length} instances without connections:`,
900
- s.map((n) => n.projectId)
901
- );
902
- let a = 0;
903
- for (const { projectId: n, instance: c } of s)
904
- try {
905
- f.info(`[SiteState] releasing instance due to periodic check: ${n}`), c.destroy(), a++;
906
- } catch (r) {
907
- f.error(`[SiteState] failed to release instance ${n} during periodic check:`, r);
908
- }
909
- f.info(
910
- `[SiteState] periodic check completed: ${a}/${s.length} instances released successfully`
911
- );
912
- } else e > 0 ? f.debug("[SiteState] periodic check: all instances have active connections") : f.debug("[SiteState] periodic check: no instances exist");
913
- }
914
- }
915
- async function Qt(t, e, s) {
916
- if (!t || !$(t) || !x(t).isFile())
917
- return null;
918
- let o = s[t];
919
- return o || (o = (async () => {
920
- try {
921
- return (await Kt({
922
- filePath: t,
923
- fileName: e
924
- }))?.data?.filename;
925
- } catch (a) {
926
- return f.error(`Failed to upload asset ${t}:`, a), null;
927
- }
928
- })(), s[t] = o), o;
929
- }
930
- const Zt = async (t, e) => {
931
- const s = k(t), o = await yt({
932
- name: qe,
933
- path: Y("/uploads", s),
934
- responseType: "stream",
935
- method: "GET"
936
- });
937
- if (o.status >= 200 && o.status < 400) {
938
- const a = dt(e);
939
- await bt(o.data, a);
940
- } else
941
- throw new Error(`download asset failed ${o.status}`);
942
- }, es = async (t, e) => {
943
- await Promise.all(
944
- t.map(async (s) => {
945
- try {
946
- await Zt(s, b(e, k(s)));
947
- } catch (o) {
948
- f.error(`Failed to export assets: ${s}, ${o}`);
949
- }
950
- })
951
- );
952
- };
953
- function He(t) {
954
- return ve.test(t) ? [t] : X.test(t) ? ($e.lastIndex = 0, Array.from(t.matchAll($e)).map((s) => s[1]).filter((s) => !!s)) : [];
955
- }
956
- async function ee(t, e, s) {
957
- const { getFilename: o, exportAssets: a } = s, n = b(e, o(t));
958
- if (_(L(n), { recursive: !0 }), te(n, B.stringify(t)), a) {
959
- const r = ae(
960
- t,
961
- (l) => typeof l == "string" && (ve.test(l) || X.test(l))
962
- ).map((l) => {
963
- const y = be(t, l);
964
- return He(y);
965
- }).flat().filter(Boolean);
966
- await es(r, L(n));
967
- }
968
- }
969
- const Se = new we({
970
- max: 100,
971
- ttl: 1 * 60 * 1e3
972
- // 1 minute
973
- });
974
- async function Ne(t, e, s) {
975
- const o = ae(
976
- t,
977
- (r) => typeof r == "string" && (ve.test(r) || X.test(r))
978
- ), a = Be(2), n = o.map(
979
- (r) => a(async () => {
980
- try {
981
- const l = be(t, r), y = He(l);
982
- for (const O of y) {
983
- const j = k(O), S = s.getFilePath(O, r), g = S ? `${S}:${j}` : j, p = Se.get(g);
984
- if (p) {
985
- X.test(l) || Te(t, r, p);
986
- return;
987
- }
988
- const d = await Qt(S, j, e);
989
- d && (X.test(l) || Te(t, r, d), Se.set(g, d));
990
- }
991
- } catch (l) {
992
- f.error(`Failed to process upload for path ${r.join(".")}:`, l.message || l.reason);
993
- }
994
- })
995
- ), c = await Promise.allSettled(n);
996
- s.onFinish?.(c);
997
- }
998
- async function ts(t, {
999
- exportAssets: e,
1000
- pageIds: s = "all",
1001
- componentIds: o = "all",
1002
- rawConfig: a,
1003
- includeResources: n = !1,
1004
- routeIds: c = "all"
1005
- } = {}) {
1006
- const r = s === "all" ? t.pageIds : s, l = mt({
1007
- state: t,
1008
- pageIds: r,
1009
- componentIds: o === "all" ? Object.keys(t.components) : o
1010
- });
1011
- Object.entries(t.components).forEach(([i, I]) => {
1012
- I.data?.renderer?.type === "component-template" && l.push(i);
1013
- });
1014
- const y = c === "all" ? t.routeIds : c, O = (i) => ({
1015
- id: i.id,
1016
- name: i.name,
1017
- isTemplateSection: i.isTemplateSection ?? !1,
1018
- templateDescription: i.templateDescription,
1019
- /** @deprecated 已经废弃,llmConfig 从 component / resources.component 中获取 */
1020
- // llmConfig: section.llmConfig,
1021
- component: i.component,
1022
- config: i.config,
1023
- visibility: i.visibility,
1024
- sections: i?.sectionIds ? T(
1025
- i?.sectionIds?.map((I) => {
1026
- const v = i.sections?.[I];
1027
- return v && O(v);
1028
- })
1029
- ) : void 0
1030
- /** @deprecated 已经废弃,数据在 page.dataSource 中管理 */
1031
- // properties: section.locales?.[locale] ?? {},
1032
- }), j = (i, I) => ({
1033
- id: i.id,
1034
- createdAt: i.createdAt,
1035
- updatedAt: i.updatedAt,
1036
- publishedAt: i.publishedAt,
1037
- isPublic: i.isPublic ?? !0,
1038
- templateConfig: i.templateConfig,
1039
- meta: i.locales?.[I] ?? {},
1040
- sections: T(
1041
- i.sectionIds.map((v) => {
1042
- const G = i.sections[v];
1043
- return G && O(G);
1044
- })
1045
- ),
1046
- // 将 dataSource.sectionId.locale 转换为 dataSource.sectionId
1047
- dataSource: Object.fromEntries(
1048
- Object.entries(i.dataSource || {}).map(([v, G]) => [v, G?.[I] ?? {}])
1049
- )
1050
- }), S = (i) => ({
1051
- id: i.id,
1052
- createdAt: i.createdAt,
1053
- updatedAt: i.updatedAt,
1054
- publishedAt: i.publishedAt,
1055
- path: i.path,
1056
- handler: i.handler,
1057
- isPublic: i.isPublic ?? !0,
1058
- params: i.params ?? [],
1059
- enabledGenerate: i.enabledGenerate ?? !1,
1060
- displayTemplateId: i.displayTemplateId,
1061
- dataSource: i.dataSource
1062
- }), g = T(
1063
- y.map((i) => {
1064
- const I = t.routes[i];
1065
- return I && S(I);
1066
- })
1067
- ), p = T(
1068
- t.supportedLocales.map((i) => i.locale).flatMap(
1069
- (i) => r.map((I) => {
1070
- const v = t.pages[I];
1071
- return v && {
1072
- locale: i,
1073
- slug: v.slug,
1074
- page: j(v, i)
1075
- };
1076
- })
1077
- )
1078
- ), d = Ke(), A = b(d, "pages");
1079
- _(A, { recursive: !0 });
1080
- const m = b(d, "components");
1081
- _(m, { recursive: !0 });
1082
- const u = b(d, "routes");
1083
- _(u, { recursive: !0 });
1084
- for (const { locale: i, slug: I, page: v } of p)
1085
- await ee(v, A, {
1086
- getFilename: () => `${ne(I) || "index"}.${i}.yml`,
1087
- exportAssets: e
1088
- });
1089
- for (const i of g)
1090
- await ee(i, u, {
1091
- // getFilename: () => `${sanitizeSlug(route.path)}.yml`,
1092
- getFilename: () => `${ne(i.path) || "index"}.yml`,
1093
- exportAssets: e
1094
- });
1095
- for (const i of l) {
1096
- const I = t.components[i]?.data;
1097
- I && await ee(I, m, {
1098
- getFilename: (v) => `${v.name || "unnamed"}.${v.id}.yml`,
1099
- exportAssets: e
1100
- });
1101
- }
1102
- const h = b(d, ".blocklet/pages/pages.config.yml");
1103
- _(L(h), { recursive: !0 });
1104
- const P = {
1105
- pages: T(
1106
- r.map((i) => {
1107
- const I = t.pages[i];
1108
- return I && { id: i, slug: I.slug };
1109
- })
1110
- ),
1111
- routes: T(
1112
- y.map((i) => {
1113
- const I = t.routes[i];
1114
- return I && { id: i, path: I.path };
1115
- })
1116
- ),
1117
- components: T(
1118
- l.map((i) => {
1119
- const I = t.components[i]?.data;
1120
- return I && {
1121
- id: i,
1122
- name: I.name
1123
- };
1124
- })
1125
- ),
1126
- ...n ? {
1127
- resources: {
1128
- components: T(
1129
- Object.keys(t.resources?.components || {}).filter((i) => l.includes(i)).map((i) => ({
1130
- id: i,
1131
- name: t.resources?.components?.[i]?.component?.name
1132
- }))
1133
- )
1134
- }
1135
- } : {},
1136
- supportedLocales: t.supportedLocales,
1137
- config: t.config
1138
- };
1139
- te(h, B.stringify(P));
1140
- const w = b(d, "config.source.json");
1141
- if (a && te(w, JSON.stringify(a)), n) {
1142
- const i = b(d, "resources"), I = b(i, "components");
1143
- _(I, { recursive: !0 });
1144
- for (const z of Object.keys(t?.resources?.components ?? {}).filter(
1145
- (M) => l.includes(M)
1146
- )) {
1147
- const M = t.resources?.components?.[z]?.component;
1148
- M && await ee(M, I, {
1149
- getFilename: (q) => `${q.name || "unnamed"}.${q.id}.yml`,
1150
- exportAssets: e
1151
- });
1152
- }
1153
- const v = b(d, "chunks");
1154
- _(v, { recursive: !0 });
1155
- const G = ss();
1156
- for (const z of Object.keys(t?.resources?.components ?? {}).filter(
1157
- (M) => l.includes(M)
1158
- )) {
1159
- const M = t.resources?.components?.[z]?.component;
1160
- if (M && M.renderer?.type === "react-component") {
1161
- const q = M.renderer?.chunks ?? [];
1162
- if (q?.length > 0)
1163
- for (const pe of q) {
1164
- const je = b(v, pe), ue = G?.[pe];
1165
- try {
1166
- ue && $(ue) && !$(je) && pt(ue, je);
1167
- } catch (tt) {
1168
- f.error(`copy chunk ${pe} error`, tt.message);
1169
- }
1170
- }
1171
- }
1172
- }
1173
- }
1174
- return d;
1175
- }
1176
- async function Je(t, { importAssets: e, includeResources: s } = {}) {
1177
- if (!$(t))
1178
- return null;
1179
- let o, a = !1;
1180
- try {
1181
- x(t).isDirectory() ? o = t : /\.(tgz|gz|tar)$/.test(t) && (a = !0, o = Ke(), await At({ file: t, C: o }));
1182
- const n = se("**/.blocklet/pages/pages.config.yml", { cwd: o, absolute: !0 }).at(0), c = n && b(L(n), "../../pages"), r = n && b(L(n), "../../components"), l = n && b(L(n), "../../routes");
1183
- if (!n)
1184
- return null;
1185
- const y = B.parse(J(n).toString()), O = (m, u, h) => {
1186
- let P = b(m, `${u}${h ? `.${h}` : ""}.yml`);
1187
- return (!$(P) || !x(P).isFile()) && (P = b(m, u, `index${h ? `.${h}` : ""}.yml`), !$(P) || !x(P)) ? null : B.parse(J(P).toString());
1188
- }, j = (m, u) => {
1189
- try {
1190
- const h = se(`*.${u}.yml`, { cwd: m, absolute: !0 })[0];
1191
- return h ? B.parse(J(h).toString()) : null;
1192
- } catch (h) {
1193
- f.error("parse component error", h);
1194
- }
1195
- return null;
1196
- }, S = (m, u) => {
1197
- let h = b(m, `${u}.yml`);
1198
- return (!$(h) || !x(h).isFile()) && (h = b(m, u, "index.yml"), !$(h) || !x(h)) ? null : B.parse(J(h).toString());
1199
- }, g = T(
1200
- y.pages.map(({ slug: m }) => {
1201
- const u = T(
1202
- y.supportedLocales.map(({ locale: w }) => {
1203
- const i = c ? O(c, ne(m), w) : void 0;
1204
- if (i)
1205
- return { locale: w, page: i };
1206
- const I = c ? O(c, m, w) : void 0;
1207
- return I && { locale: w, page: I };
1208
- })
1209
- ), h = u[0]?.page;
1210
- if (!h)
1211
- return null;
1212
- const P = h.sections.map(ft);
1213
- return {
1214
- id: h.id || De(),
1215
- createdAt: h.createdAt,
1216
- updatedAt: h.updatedAt,
1217
- publishedAt: h.publishedAt,
1218
- isPublic: h.isPublic ?? !0,
1219
- templateConfig: h.templateConfig,
1220
- slug: m,
1221
- sections: Object.fromEntries(P.map((w) => [w.id, w])),
1222
- sectionIds: P.map((w) => w.id),
1223
- locales: Object.fromEntries(u.map(({ locale: w, page: i }) => [w, i.meta])),
1224
- dataSource: h.dataSource ? Object.fromEntries(
1225
- // 获取 dataSource 中所有 section ID
1226
- [...new Set(u.flatMap(({ page: w }) => Object.keys(w.dataSource ?? {})))].map((w) => [
1227
- w,
1228
- Object.fromEntries(
1229
- u.map(({ locale: i, page: I }) => {
1230
- const v = I.dataSource?.[w];
1231
- return [i, v || {}];
1232
- })
1233
- )
1234
- ])
1235
- ) : Object.fromEntries(
1236
- // 获取所有 section ID
1237
- [...new Set(u.flatMap(({ page: w }) => w.sections.map((i) => i.id)))].map((w) => [
1238
- w,
1239
- Object.fromEntries(
1240
- u.map(({ locale: i, page: I }) => {
1241
- const v = I.dataSource?.[w];
1242
- if (v)
1243
- return [i, v];
1244
- const G = I.sections.find((z) => z.id === w);
1245
- return [i, G?.properties || {}];
1246
- })
1247
- )
1248
- ])
1249
- )
1250
- };
1251
- })
1252
- ), p = T(
1253
- y?.routes?.map(({ path: m }) => {
1254
- const u = l ? S(l, ne(m)) : void 0;
1255
- return {
1256
- ...u,
1257
- id: u?.id || De(),
1258
- createdAt: u?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1259
- updatedAt: u?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1260
- publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
1261
- path: u?.path ?? `/${u?.id}`,
1262
- params: u?.params,
1263
- handler: u?.handler ?? "Pages Kit",
1264
- isPublic: u?.isPublic ?? !0,
1265
- enabledGenerate: u?.enabledGenerate ?? !1,
1266
- displayTemplateId: u?.displayTemplateId ?? void 0,
1267
- dataSource: u?.dataSource ?? {}
1268
- };
1269
- }) ?? []
1270
- ), d = r ? T(y.components?.map(({ id: m }) => j(r, m)) ?? []) : [];
1271
- if (e) {
1272
- const m = (...u) => {
1273
- f.info(`[${a ? k(t) : k(b(t, "../../../../"))}] importAssets:`, ...u);
1274
- };
1275
- try {
1276
- m("wait image-bin api ready"), await wt({
1277
- resources: [`${gt(st)}/api/sdk/uploads`],
1278
- validateStatus: (P) => P >= 200 && P <= 500
1279
- }), m("image-bin api is ready");
1280
- const u = {}, h = {};
1281
- m("start to upload assets"), await Promise.allSettled([
1282
- Ne(d, u, {
1283
- getFilePath: (P) => r && b(r, P),
1284
- onFinish: (P) => {
1285
- m(`upload ${P.length} component assets`);
1286
- }
1287
- }),
1288
- Ne(g, h, {
1289
- getFilePath: (P, w) => {
1290
- const i = be(g, w.slice(0, 1));
1291
- return c && b(c, L(i.slug), P);
1292
- },
1293
- onFinish: (P) => {
1294
- m(`upload ${P.length} page assets`);
1295
- }
1296
- })
1297
- ]), m("upload assets done"), Se.clear(), global.gc && global.gc();
1298
- } catch (u) {
1299
- m("Error during asset import:", u);
1300
- }
1301
- }
1302
- const A = {};
1303
- if (s) {
1304
- const m = n && b(L(n), "../../resources/components"), u = T(
1305
- y.resources?.components?.map(({ id: h }) => j(m, h)) ?? []
1306
- );
1307
- u.length > 0 && (A.components = Object.fromEntries(
1308
- u.map((h, P) => [h.id, { index: P, component: h }])
1309
- ));
1310
- }
1311
- return {
1312
- supportedLocales: y.supportedLocales,
1313
- pageIds: g.map((m) => m.id),
1314
- components: Object.fromEntries(d.map((m, u) => [m.id, { index: u, data: m }])),
1315
- pages: Object.fromEntries(g.map((m) => [m.id, m])),
1316
- config: y.config || {},
1317
- resources: A,
1318
- routeIds: p.map((m) => m.id),
1319
- routes: Object.fromEntries(p.map((m) => [m.id, m])),
1320
- dataSourceIds: [],
1321
- dataSources: {}
1322
- };
1323
- } finally {
1324
- a && o && Ge(o, { force: !0, recursive: !0 });
1325
- }
1326
- }
1327
- async function _e(t, e, {
1328
- routes: s,
1329
- mergeMode: o = "byUpdateTime",
1330
- deleteRoutes: a = !1,
1331
- publishMode: n = void 0
1332
- } = {}) {
1333
- try {
1334
- n && ot(n);
1335
- } catch (S) {
1336
- f.error("clear preload page cache error", { error: S });
1337
- }
1338
- const { pages: c, pageIds: r, routeIds: l, routes: y, supportedLocales: O } = t;
1339
- if (n === "production") {
1340
- let S = s ?? [], g = null;
1341
- for (const p of l ?? []) {
1342
- const d = y?.[p];
1343
- if (d?.params && d?.params.length > 0 && d?.paramsOptions && d?.paramsOptions.length > 0) {
1344
- const A = Ie({
1345
- basePath: d.path,
1346
- params: d.params,
1347
- routeId: d.id,
1348
- paramsOptions: d.paramsOptions,
1349
- currentIndex: 0,
1350
- currentParams: [],
1351
- currentOptionIds: [],
1352
- result: []
1353
- }), m = Object.fromEntries(A.map((u) => [`${p}-${u.paramOptionIds.join("-")}`, u]));
1354
- g = { ...g || {}, ...m }, s || (S = [...S, ...A.map((u) => `${p}-${u.paramOptionIds.join("-")}`)]);
1355
- } else s || S.push(p);
1356
- }
1357
- f.info("routeIds to be published: ", S);
1358
- for (const p of S) {
1359
- let d = p;
1360
- if (d.includes("-")) {
1361
- const [u] = d.split("-");
1362
- d = u;
1363
- }
1364
- const A = y?.[d];
1365
- if (!A) {
1366
- const u = e.pageIds.indexOf(d);
1367
- u !== -1 && a && (e.pageIds.splice(u, 1), delete e.pages[d]);
1368
- for (const h of e.pageIds)
1369
- h.includes(`${d}-`) && (e.pageIds.splice(e.pageIds.indexOf(h), 1), delete e.pages[h]);
1370
- f.info("delete main route page", d);
1371
- continue;
1372
- }
1373
- if (p.includes("-") && !g?.[p]) {
1374
- const u = e.pageIds.indexOf(p);
1375
- u !== -1 && a && (e.pageIds.splice(u, 1), delete e.pages[p]), f.info("delete page", p);
1376
- continue;
1377
- }
1378
- if (!A.displayTemplateId) {
1379
- f.info("no display template", p);
1380
- continue;
1381
- }
1382
- const m = c[A.displayTemplateId];
1383
- if (!m) {
1384
- f.info("no template page", p);
1385
- continue;
1386
- }
1387
- if (e.pageIds.includes(p)) {
1388
- if (f.info("has need update page", p), o === "replace")
1389
- e.pages[p] = fe({
1390
- page: m,
1391
- route: A,
1392
- state: t,
1393
- routeId: p,
1394
- routePathInfo: g?.[p]
1395
- }), f.info("replace page", p);
1396
- else if (o === "byUpdateTime") {
1397
- const u = e.pages[A.id];
1398
- (!u || A.updatedAt && A.updatedAt > u.updatedAt) && (e.pages[p] = fe({
1399
- page: m,
1400
- route: A,
1401
- state: t,
1402
- routeId: p,
1403
- routePathInfo: g?.[p]
1404
- }), f.info("replace page by update time", p));
1405
- }
1406
- } else
1407
- e.pageIds.push(p), e.pages[p] = fe({
1408
- page: m,
1409
- route: A,
1410
- state: t,
1411
- routeId: p,
1412
- routePathInfo: g?.[p]
1413
- }), f.info("add page", p);
1414
- }
1415
- if (a && !s)
1416
- for (const p of e.pageIds)
1417
- S?.includes(p) || (delete e.pages[p], f.info("delete page", p)), e.pageIds = [...e.pageIds].filter((d) => S?.includes(d));
1418
- } else {
1419
- for (const S of r) {
1420
- const g = c[S];
1421
- if (g)
1422
- if (e.pageIds.includes(g.id)) {
1423
- if (o === "replace")
1424
- e.pages[g.id] = g;
1425
- else if (o === "byUpdateTime") {
1426
- const p = e.pages[g.id];
1427
- (!p || g.updatedAt && g.updatedAt > p.updatedAt) && (e.pages[g.id] = g);
1428
- }
1429
- } else
1430
- e.pageIds.push(g.id), e.pages[g.id] = g;
1431
- }
1432
- for (const S of l) {
1433
- const g = y[S];
1434
- if (g)
1435
- if (e.routeIds.includes(g.id)) {
1436
- if (o === "replace")
1437
- e.routes[g.id] = g;
1438
- else if (o === "byUpdateTime") {
1439
- const p = e.routes[g.id];
1440
- (!p || g.updatedAt && g.updatedAt > p.updatedAt) && (e.routes[g.id] = g);
1441
- }
1442
- } else
1443
- e.routeIds.push(g.id), e.routes[g.id] = g;
1444
- }
1445
- }
1446
- if (e.supportedLocales.splice(0, e.supportedLocales.length), e.supportedLocales.push(...Ee(O)), a)
1447
- for (const S of Object.keys(e.components))
1448
- delete e.components[S];
1449
- let j = JSON.parse(JSON.stringify(t.components));
1450
- j = Object.fromEntries(
1451
- await Promise.all(
1452
- Object.entries(j).map(async ([S, g]) => {
1453
- const p = await Ye(g?.data);
1454
- return [
1455
- S,
1456
- {
1457
- ...g,
1458
- data: p
1459
- }
1460
- ];
1461
- })
1462
- )
1463
- ), Object.assign(e.components, j), Object.assign(e.config, JSON.parse(JSON.stringify(t.config))), Ae(t.resources.components) || (e.resources.components = JSON.parse(JSON.stringify(t.resources.components || {})));
1464
- }
1465
- const Ye = at(
1466
- async (t) => {
1467
- if (!Ae(t?.properties))
1468
- return t;
1469
- if (t?.renderer?.type === "react-component") {
1470
- const { script: e, PROPERTIES_SCHEMA: s } = t?.renderer || {};
1471
- if (s || e && e.includes("PROPERTIES_SCHEMA"))
1472
- try {
1473
- const o = await nt(
1474
- e ?? "",
1475
- "PROPERTIES_SCHEMA",
1476
- t.id,
1477
- s
1478
- );
1479
- o && o.length > 0 && t && (t.properties = {}, o.forEach((a, n) => {
1480
- t?.properties && (t.properties[a.id] = {
1481
- index: n,
1482
- data: a
1483
- });
1484
- }));
1485
- } catch (o) {
1486
- f.error("getPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: o });
1487
- }
1488
- }
1489
- return t;
1490
- },
1491
- {
1492
- subdir: "getPropertiesFromCode"
1493
- }
1494
- );
1495
- let re, Q, ie, ce;
1496
- const We = () => ht({
1497
- types: [
1498
- { did: qe, type: Ue },
1499
- { did: Lt, type: Ue }
1500
- ]
1501
- }), ss = () => {
1502
- const t = We(), e = {};
1503
- return t.forEach((s) => {
1504
- const o = se("**/.blocklet/pages/pages.config.yml", { cwd: s.path, absolute: !0 }).at(0), a = o && b(L(o), "../../chunks");
1505
- if (a && $(a)) {
1506
- const n = ut(a);
1507
- for (const c of n)
1508
- e[c] = b(a, c);
1509
- }
1510
- }), e;
1511
- };
1512
- function Xe() {
1513
- return re = (async () => {
1514
- const t = We();
1515
- Q = (await Promise.all(
1516
- t.map(async (s) => {
1517
- const o = s.path ? await Je(s.path, { importAssets: !1 }) : void 0;
1518
- return o ? { blockletId: s.did, state: o, blockletTitle: s.title } : void 0;
1519
- })
1520
- )).filter((s) => !!s), ie = Q.reduce(
1521
- (s, o) => Object.assign(
1522
- s,
1523
- Object.fromEntries(
1524
- Object.values(o.state.pages).map((a) => a ? [a?.id, { page: a, blockletId: o.blockletId }] : [])
1525
- )
1526
- ),
1527
- {}
1528
- );
1529
- const e = Q.reduce(
1530
- (s, o) => Object.assign(
1531
- s,
1532
- Object.fromEntries(
1533
- Object.values(o.state.components).map((a) => [a.data.id, { blockletId: o.blockletId, component: a.data }])
1534
- )
1535
- ),
1536
- {}
1537
- );
1538
- ce = Object.fromEntries(
1539
- await Promise.all(
1540
- Object.entries(e).map(async ([s, o]) => {
1541
- const a = await Ye(o.component);
1542
- return [
1543
- s,
1544
- {
1545
- ...o,
1546
- component: a
1547
- }
1548
- ];
1549
- })
1550
- )
1551
- );
1552
- })(), re;
1553
- }
1554
- function os(t) {
1555
- const e = xe(
1556
- async () => {
1557
- await Xe().catch((s) => {
1558
- f.error("load resource states error", { error: s });
1559
- }), await t?.({
1560
- states: Q,
1561
- pages: ie,
1562
- components: ce
1563
- });
1564
- },
1565
- 3e3,
1566
- // 3s
1567
- { leading: !1, trailing: !0 }
1568
- );
1569
- return e(), E.events.on(E.Events.componentAdded, e), E.events.on(E.Events.componentRemoved, e), E.events.on(E.Events.componentStarted, e), E.events.on(E.Events.componentStopped, e), E.events.on(E.Events.componentUpdated, e), E.events.on(he, e), () => {
1570
- E.events.off(E.Events.componentAdded, e), E.events.off(E.Events.componentRemoved, e), E.events.off(E.Events.componentStarted, e), E.events.off(E.Events.componentStopped, e), E.events.off(E.Events.componentUpdated, e), E.events.off(he, e);
1571
- };
1572
- }
1573
- const Qe = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), Ze = Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"), le = globalThis;
1574
- le[Qe]?.();
1575
- le[Qe] = os(async ({ pages: t, components: e }) => {
1576
- const s = await C.getProjectIds();
1577
- f.info(`start update resource states projects(${s.length})`, s), await Promise.race([
1578
- new Promise((o) => {
1579
- setTimeout(() => {
1580
- o({});
1581
- }, 30 * 1e3);
1582
- }),
1583
- Promise.all(
1584
- s.map(async (o) => {
1585
- et({
1586
- projectId: o,
1587
- pages: t,
1588
- components: e
1589
- });
1590
- })
1591
- )
1592
- ]).catch((o) => {
1593
- f.error("update resource states failed:", o);
1594
- });
1595
- });
1596
- le[Ze]?.();
1597
- le[Ze] = () => {
1598
- const t = () => {
1599
- C.pageUrlMapCache.clear(), f.info("[Cache CLEAR ALL] clear all page url map cache by env update");
1600
- };
1601
- return E.events.on(E.Events.envUpdate, t), () => {
1602
- E.events.off(E.Events.envUpdate, t);
1603
- };
1604
- };
1605
- C.startPeriodicCheck();
1606
- process.on("beforeExit", () => {
1607
- C.stopPeriodicCheck();
1608
- });
1609
- process.on("SIGINT", () => {
1610
- C.stopPeriodicCheck(), process.exit(0);
1611
- });
1612
- process.on("SIGTERM", () => {
1613
- C.stopPeriodicCheck(), process.exit(0);
1614
- });
1615
- async function et({
1616
- projectId: t,
1617
- pages: e,
1618
- components: s
1619
- }) {
1620
- const o = C.sharedInstances[t];
1621
- if (!o) {
1622
- f.info(`projectId: ${t} not found in sharedInstances`);
1623
- return;
1624
- }
1625
- if (o.syncedStore.resources.pages = e, (await U.findByPk(t))?.useAllResources)
1626
- o.syncedStore.resources.components = s;
1627
- else {
1628
- const c = (await Ce.findAll({ where: { projectId: t } })).map((l) => l.componentId), r = Object.fromEntries(
1629
- Object.entries(s || {}).filter(([l]) => c.includes(l))
1630
- );
1631
- o.syncedStore.resources.components = r;
1632
- }
1633
- f.info(`update [${t}] resource states:`, {
1634
- pages: Object.keys(o.syncedStore.resources.pages || {}).length,
1635
- components: Object.keys(o.syncedStore.resources.components || {}).length
1636
- });
1637
- }
1638
- async function as(t) {
1639
- return et({
1640
- projectId: t,
1641
- pages: ie,
1642
- components: ce
1643
- });
1644
- }
1645
- async function _s() {
1646
- f.info("trigger reload all project resource"), E.events.emit(he);
1647
- }
1648
- async function Fs({
1649
- ensureLoaded: t = !0
1650
- } = {}) {
1651
- return t && (re ??= Xe(), await re), { states: Q, pages: ie, components: ce };
1652
- }
1653
- export {
1654
- qe as C,
1655
- U as P,
1656
- Ue as R,
1657
- C as S,
1658
- H as a,
1659
- $s as b,
1660
- Ns as c,
1661
- Xt as d,
1662
- Zt as e,
1663
- es as f,
1664
- Fs as g,
1665
- Je as h,
1666
- os as i,
1667
- _s as j,
1668
- _e as m,
1669
- ts as t,
1670
- as as u
1671
- };