@blocklet/pages-kit-inner-components 0.6.102 → 0.6.104

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.
@@ -1,1668 +0,0 @@
1
- import { d as Fe, l as f, I as tt, c as st, m as ot, b as at } from "./components-DLwSTd_N.js";
2
- import { getYjsValue as V, syncedStore as nt } from "@syncedstore/core";
3
- import * as N from "yjs";
4
- import { setPageDataSource as rt } from "@blocklet/pages-kit/utils/data-source";
5
- import { getRouteMetaDataByOptionIds as it, 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 ct, existsSync as $, readFileSync as J, renameSync as je, mkdirSync as _, rmSync as Ge, writeFileSync as te, copyFileSync as lt, lstatSync as x, readdirSync as pt, createWriteStream as ut } 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 dt } from "@blocklet/pages-kit/utils/page-model";
12
- import { getComponentDependencies as ft } from "@blocklet/pages-kit/utils/property";
13
- import { getComponentWebEndpoint as mt, getResources as gt, call as ht } from "@blocklet/sdk/lib/component";
14
- import { reactive as yt } 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 St from "lodash/union";
23
- import { LRUCache as we } from "lru-cache";
24
- import It from "p-limit";
25
- import { DataTypes as R, Sequelize as Et, Model as Be, 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 Ve, 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 Rt, readSyncMessage as jt } 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", ze = kt, Lt = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM", Ut = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";
85
- class Ce extends Be {
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 Ve(e) || "/";
143
- }, Ft = (t) => t.did === Ut;
144
- class U extends Be {
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(Ve(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 qe() {
292
- return ct(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 = it(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 p = e.dataSource.pathDataMappings?.[r]?.dataCache?.[c.locale] ?? e.dataSource.pathDataMappings?.[r]?.dataCache?.[s.config.defaultLocale || "en"];
387
- if (!p)
388
- continue;
389
- rt(n, s, c.locale, p);
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: 100,
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 O extends N.Doc {
445
- constructor(e) {
446
- super(), this.options = e, $(this.draftYjsFilePath) && N.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore = yt(
447
- nt(
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: 100,
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
- je(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) => O.shared(e));
502
- }
503
- static shared(e) {
504
- if (!e)
505
- throw new Error("Should provide project context");
506
- let s = O.sharedInstances[e];
507
- return s || (s = new O({
508
- path: b(H, e)
509
- }), O.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 He(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 O.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 = O.shared(e);
541
- return JSON.parse(JSON.stringify(o.syncedStore));
542
- }
543
- return O.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 O.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 }), je(o, a), e === "production") {
554
- const n = k(this.options.path);
555
- O.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 p = this.conns.get(a);
572
- p && (e.forEach((y) => {
573
- p.add(y);
574
- }), o.forEach((y) => {
575
- p.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((p, 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 p = 0;
594
- for (; p < o.length; ) {
595
- const y = o[p];
596
- r.has(y) ? (r.delete(y), p++) : o.splice(p, 1);
597
- }
598
- }
599
- {
600
- const r = new Set(Object.keys(n));
601
- let p = 0;
602
- for (; p < c.length; ) {
603
- const y = c[p];
604
- r.has(y) ? (r.delete(y), p++) : c.splice(p, 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 p = /* @__PURE__ */ new Set();
611
- for (; r < e.length; ) {
612
- const { locale: y } = e[r];
613
- p.has(y) ? e.splice(r, 1) : (r++, p.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
- }, O.RELEASE_DELAY), f.info(`[SiteState] scheduled release for project ${e} in ${O.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 p = await _e(e, s);
674
- c(p);
675
- } catch (p) {
676
- r(p);
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((A) => A.locale), p = [], y = c.filter((A) => s.pageIds?.includes(A));
686
- for (const A of y) {
687
- const I = s.pages[A].slug;
688
- n && n !== o && (n === "/" ? p.push(I) : p.push(`/${n}${I}`)), p.push(`/${o}${I}`);
689
- }
690
- if (p.length > 0)
691
- try {
692
- const A = zt(p, r);
693
- f.info(`[SiteState] cleared ${A} page cache entries for project ${o}, routes:`, c);
694
- } catch {
695
- }
696
- O.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), Rt(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), jt(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
- let o = [];
752
- s ? o = [s] : o = await this.getProjectIds();
753
- let a = {};
754
- if (e === "production" && o?.length) {
755
- const n = new Map(o?.map((c) => [c, !0]) || []);
756
- for (const c of o) {
757
- const r = O.pageUrlMapCache.get(c);
758
- r && (a = { ...a, ...r }, n.delete(c));
759
- }
760
- o = Array.from(n.keys());
761
- }
762
- if (o?.length) {
763
- const n = await U.findAll({
764
- where: {
765
- id: {
766
- [Pe.in]: o
767
- }
768
- }
769
- });
770
- await Promise.all(
771
- n?.map(async (c) => {
772
- const r = c.id, p = c.slug || r, y = {}, A = e === "production" && c?.productionState ? c.productionState : await O.getStateByProjectId(c.id, e), j = St(
773
- E.env.languages?.map((u) => u.code) || [],
774
- A.supportedLocales?.map((u) => u.locale) || []
775
- ), I = (u, l) => {
776
- p && (y[Y("/", p, u)] = {
777
- ...l,
778
- shouldRedirect: !0,
779
- mainPage: !0
780
- }), y[Y("/", r, u)] = {
781
- ...l,
782
- shouldRedirect: !0,
783
- mainPage: !0
784
- };
785
- for (const g of j) {
786
- const C = { ...l, locale: g };
787
- y[Y("/", g, r, u)] = C, p && (y[Y("/", g, p, u)] = C);
788
- }
789
- };
790
- if (e === "draft")
791
- for (const u of A.routeIds || []) {
792
- const l = A?.routes?.[u];
793
- if (!l) continue;
794
- if (l.params && l.params.length > 0) {
795
- const m = Ie({
796
- basePath: l.path,
797
- params: l.params,
798
- routeId: l.id,
799
- paramsOptions: l.paramsOptions,
800
- currentIndex: 0,
801
- currentParams: [],
802
- currentOptionIds: [],
803
- result: []
804
- });
805
- for (const d of m) {
806
- const h = d.path, w = {
807
- projectId: r,
808
- projectSlug: p,
809
- pageSlug: h,
810
- pageId: l.displayTemplateId || "",
811
- routeId: u,
812
- // default locale
813
- defaultLocale: j?.[0],
814
- locales: j,
815
- publishedAt: A.config.publishedAt,
816
- isPublic: l.isPublic && d?.routeMetaData?.isPublic
817
- };
818
- I(h, w);
819
- }
820
- }
821
- const g = l.path, C = {
822
- projectId: r,
823
- projectSlug: p,
824
- pageSlug: g,
825
- pageId: l.displayTemplateId || "",
826
- routeId: u,
827
- // default locale
828
- defaultLocale: j?.[0],
829
- locales: j,
830
- publishedAt: A.config.publishedAt,
831
- isPublic: l.isPublic
832
- };
833
- I(g, C);
834
- }
835
- for (const u of A.pageIds || []) {
836
- const l = A.pages[u];
837
- if (!l || e === "production" && !l.isPublic)
838
- continue;
839
- const g = l.slug, C = c.slug || r, m = {
840
- projectId: r,
841
- projectSlug: C,
842
- pageSlug: g,
843
- pageId: u,
844
- // default locale
845
- defaultLocale: j?.[0],
846
- locales: j,
847
- publishedAt: A.config.publishedAt,
848
- isPublic: l.isPublic,
849
- templateConfig: l.templateConfig
850
- };
851
- I(g, m);
852
- }
853
- e === "production" && O.pageUrlMapCache.set(r, y), a = { ...a, ...y };
854
- })
855
- );
856
- }
857
- return a;
858
- }
859
- getDocumentSize() {
860
- return N.encodeStateAsUpdate(this).byteLength;
861
- }
862
- static getInstancesSizeInfo() {
863
- const e = [];
864
- for (const [s, o] of Object.entries(O.sharedInstances)) {
865
- const a = o.getDocumentSize();
866
- e.push({
867
- projectId: s,
868
- sizeInBytes: a,
869
- sizeInMB: `${(a / (1024 * 1024)).toFixed(2)} MB`,
870
- activeConnections: o.conns.size
871
- });
872
- }
873
- return e;
874
- }
875
- // 启动定期检查
876
- static startPeriodicCheck() {
877
- this.periodicCheckTimer || (this.periodicCheckTimer = setInterval(() => {
878
- this.performPeriodicCheck();
879
- }, this.PERIODIC_CHECK_INTERVAL), f.info(
880
- `[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL / (60 * 60 * 1e3)} hours`
881
- ));
882
- }
883
- // 停止定期检查
884
- static stopPeriodicCheck() {
885
- this.periodicCheckTimer && (clearInterval(this.periodicCheckTimer), this.periodicCheckTimer = void 0, f.info("[SiteState] periodic check stopped"));
886
- }
887
- // 执行定期检查
888
- static performPeriodicCheck() {
889
- const e = Object.keys(O.sharedInstances).length, s = [], o = [];
890
- for (const [a, n] of Object.entries(O.sharedInstances))
891
- n.conns.size === 0 ? s.push({ projectId: a, instance: n }) : o.push({ projectId: a, connections: n.conns.size });
892
- if (f.info(
893
- `[SiteState] periodic check summary: total instances: ${e}, with connections: ${o.length}, without connections: ${s.length}`
894
- ), s.length > 0) {
895
- f.info(
896
- `[SiteState] releasing ${s.length} instances without connections:`,
897
- s.map((n) => n.projectId)
898
- );
899
- let a = 0;
900
- for (const { projectId: n, instance: c } of s)
901
- try {
902
- f.info(`[SiteState] releasing instance due to periodic check: ${n}`), c.destroy(), a++;
903
- } catch (r) {
904
- f.error(`[SiteState] failed to release instance ${n} during periodic check:`, r);
905
- }
906
- f.info(
907
- `[SiteState] periodic check completed: ${a}/${s.length} instances released successfully`
908
- );
909
- } else e > 0 ? f.debug("[SiteState] periodic check: all instances have active connections") : f.debug("[SiteState] periodic check: no instances exist");
910
- }
911
- }
912
- async function Qt(t, e, s) {
913
- if (!t || !$(t) || !x(t).isFile())
914
- return null;
915
- let o = s[t];
916
- return o || (o = (async () => {
917
- try {
918
- return (await Kt({
919
- filePath: t,
920
- fileName: e
921
- }))?.data?.filename;
922
- } catch (a) {
923
- return f.error(`Failed to upload asset ${t}:`, a), null;
924
- }
925
- })(), s[t] = o), o;
926
- }
927
- const Zt = async (t, e) => {
928
- const s = k(t), o = await ht({
929
- name: ze,
930
- path: Y("/uploads", s),
931
- responseType: "stream",
932
- method: "GET"
933
- });
934
- if (o.status >= 200 && o.status < 400) {
935
- const a = ut(e);
936
- await bt(o.data, a);
937
- } else
938
- throw new Error(`download asset failed ${o.status}`);
939
- }, es = async (t, e) => {
940
- await Promise.all(
941
- t.map(async (s) => {
942
- try {
943
- await Zt(s, b(e, k(s)));
944
- } catch (o) {
945
- f.error(`Failed to export assets: ${s}, ${o}`);
946
- }
947
- })
948
- );
949
- };
950
- function Ke(t) {
951
- return ve.test(t) ? [t] : X.test(t) ? ($e.lastIndex = 0, Array.from(t.matchAll($e)).map((s) => s[1]).filter((s) => !!s)) : [];
952
- }
953
- async function ee(t, e, s) {
954
- const { getFilename: o, exportAssets: a } = s, n = b(e, o(t));
955
- if (_(L(n), { recursive: !0 }), te(n, B.stringify(t)), a) {
956
- const r = ae(
957
- t,
958
- (p) => typeof p == "string" && (ve.test(p) || X.test(p))
959
- ).map((p) => {
960
- const y = be(t, p);
961
- return Ke(y);
962
- }).flat().filter(Boolean);
963
- await es(r, L(n));
964
- }
965
- }
966
- const Se = new we({
967
- max: 100,
968
- ttl: 1 * 60 * 1e3
969
- // 1 minute
970
- });
971
- async function Ne(t, e, s) {
972
- const o = ae(
973
- t,
974
- (r) => typeof r == "string" && (ve.test(r) || X.test(r))
975
- ), a = It(2), n = o.map(
976
- (r) => a(async () => {
977
- try {
978
- const p = be(t, r), y = Ke(p);
979
- for (const A of y) {
980
- const j = k(A), I = s.getFilePath(A, r), u = I ? `${I}:${j}` : j, l = Se.get(u);
981
- if (l) {
982
- X.test(p) || Te(t, r, l);
983
- return;
984
- }
985
- const g = await Qt(I, j, e);
986
- g && (X.test(p) || Te(t, r, g), Se.set(u, g));
987
- }
988
- } catch (p) {
989
- f.error(`Failed to process upload for path ${r.join(".")}:`, p.message || p.reason);
990
- }
991
- })
992
- ), c = await Promise.allSettled(n);
993
- s.onFinish?.(c);
994
- }
995
- async function ts(t, {
996
- exportAssets: e,
997
- pageIds: s = "all",
998
- componentIds: o = "all",
999
- rawConfig: a,
1000
- includeResources: n = !1,
1001
- routeIds: c = "all"
1002
- } = {}) {
1003
- const r = s === "all" ? t.pageIds : s, p = ft({
1004
- state: t,
1005
- pageIds: r,
1006
- componentIds: o === "all" ? Object.keys(t.components) : o
1007
- });
1008
- Object.entries(t.components).forEach(([i, S]) => {
1009
- S.data?.renderer?.type === "component-template" && p.push(i);
1010
- });
1011
- const y = c === "all" ? t.routeIds : c, A = (i) => ({
1012
- id: i.id,
1013
- name: i.name,
1014
- isTemplateSection: i.isTemplateSection ?? !1,
1015
- templateDescription: i.templateDescription,
1016
- /** @deprecated 已经废弃,llmConfig 从 component / resources.component 中获取 */
1017
- // llmConfig: section.llmConfig,
1018
- component: i.component,
1019
- config: i.config,
1020
- visibility: i.visibility,
1021
- sections: i?.sectionIds ? T(
1022
- i?.sectionIds?.map((S) => {
1023
- const v = i.sections?.[S];
1024
- return v && A(v);
1025
- })
1026
- ) : void 0
1027
- /** @deprecated 已经废弃,数据在 page.dataSource 中管理 */
1028
- // properties: section.locales?.[locale] ?? {},
1029
- }), j = (i, S) => ({
1030
- id: i.id,
1031
- createdAt: i.createdAt,
1032
- updatedAt: i.updatedAt,
1033
- publishedAt: i.publishedAt,
1034
- isPublic: i.isPublic ?? !0,
1035
- templateConfig: i.templateConfig,
1036
- meta: i.locales?.[S] ?? {},
1037
- sections: T(
1038
- i.sectionIds.map((v) => {
1039
- const G = i.sections[v];
1040
- return G && A(G);
1041
- })
1042
- ),
1043
- // 将 dataSource.sectionId.locale 转换为 dataSource.sectionId
1044
- dataSource: Object.fromEntries(
1045
- Object.entries(i.dataSource || {}).map(([v, G]) => [v, G?.[S] ?? {}])
1046
- )
1047
- }), I = (i) => ({
1048
- id: i.id,
1049
- createdAt: i.createdAt,
1050
- updatedAt: i.updatedAt,
1051
- publishedAt: i.publishedAt,
1052
- path: i.path,
1053
- handler: i.handler,
1054
- isPublic: i.isPublic ?? !0,
1055
- params: i.params ?? [],
1056
- enabledGenerate: i.enabledGenerate ?? !1,
1057
- displayTemplateId: i.displayTemplateId,
1058
- dataSource: i.dataSource
1059
- }), u = T(
1060
- y.map((i) => {
1061
- const S = t.routes[i];
1062
- return S && I(S);
1063
- })
1064
- ), l = T(
1065
- t.supportedLocales.map((i) => i.locale).flatMap(
1066
- (i) => r.map((S) => {
1067
- const v = t.pages[S];
1068
- return v && {
1069
- locale: i,
1070
- slug: v.slug,
1071
- page: j(v, i)
1072
- };
1073
- })
1074
- )
1075
- ), g = qe(), C = b(g, "pages");
1076
- _(C, { recursive: !0 });
1077
- const m = b(g, "components");
1078
- _(m, { recursive: !0 });
1079
- const d = b(g, "routes");
1080
- _(d, { recursive: !0 });
1081
- for (const { locale: i, slug: S, page: v } of l)
1082
- await ee(v, C, {
1083
- getFilename: () => `${ne(S) || "index"}.${i}.yml`,
1084
- exportAssets: e
1085
- });
1086
- for (const i of u)
1087
- await ee(i, d, {
1088
- // getFilename: () => `${sanitizeSlug(route.path)}.yml`,
1089
- getFilename: () => `${ne(i.path) || "index"}.yml`,
1090
- exportAssets: e
1091
- });
1092
- for (const i of p) {
1093
- const S = t.components[i]?.data;
1094
- S && await ee(S, m, {
1095
- getFilename: (v) => `${v.name || "unnamed"}.${v.id}.yml`,
1096
- exportAssets: e
1097
- });
1098
- }
1099
- const h = b(g, ".blocklet/pages/pages.config.yml");
1100
- _(L(h), { recursive: !0 });
1101
- const w = {
1102
- pages: T(
1103
- r.map((i) => {
1104
- const S = t.pages[i];
1105
- return S && { id: i, slug: S.slug };
1106
- })
1107
- ),
1108
- routes: T(
1109
- y.map((i) => {
1110
- const S = t.routes[i];
1111
- return S && { id: i, path: S.path };
1112
- })
1113
- ),
1114
- components: T(
1115
- p.map((i) => {
1116
- const S = t.components[i]?.data;
1117
- return S && {
1118
- id: i,
1119
- name: S.name
1120
- };
1121
- })
1122
- ),
1123
- ...n ? {
1124
- resources: {
1125
- components: T(
1126
- Object.keys(t.resources?.components || {}).filter((i) => p.includes(i)).map((i) => ({
1127
- id: i,
1128
- name: t.resources?.components?.[i]?.component?.name
1129
- }))
1130
- )
1131
- }
1132
- } : {},
1133
- supportedLocales: t.supportedLocales,
1134
- config: t.config
1135
- };
1136
- te(h, B.stringify(w));
1137
- const P = b(g, "config.source.json");
1138
- if (a && te(P, JSON.stringify(a)), n) {
1139
- const i = b(g, "resources"), S = b(i, "components");
1140
- _(S, { recursive: !0 });
1141
- for (const z of Object.keys(t?.resources?.components ?? {}).filter(
1142
- (M) => p.includes(M)
1143
- )) {
1144
- const M = t.resources?.components?.[z]?.component;
1145
- M && await ee(M, S, {
1146
- getFilename: (q) => `${q.name || "unnamed"}.${q.id}.yml`,
1147
- exportAssets: e
1148
- });
1149
- }
1150
- const v = b(g, "chunks");
1151
- _(v, { recursive: !0 });
1152
- const G = ss();
1153
- for (const z of Object.keys(t?.resources?.components ?? {}).filter(
1154
- (M) => p.includes(M)
1155
- )) {
1156
- const M = t.resources?.components?.[z]?.component;
1157
- if (M && M.renderer?.type === "react-component") {
1158
- const q = M.renderer?.chunks ?? [];
1159
- if (q?.length > 0)
1160
- for (const pe of q) {
1161
- const Re = b(v, pe), ue = G?.[pe];
1162
- try {
1163
- ue && $(ue) && !$(Re) && lt(ue, Re);
1164
- } catch (et) {
1165
- f.error(`copy chunk ${pe} error`, et.message);
1166
- }
1167
- }
1168
- }
1169
- }
1170
- }
1171
- return g;
1172
- }
1173
- async function He(t, { importAssets: e, includeResources: s } = {}) {
1174
- if (!$(t))
1175
- return null;
1176
- let o, a = !1;
1177
- try {
1178
- x(t).isDirectory() ? o = t : /\.(tgz|gz|tar)$/.test(t) && (a = !0, o = qe(), await At({ file: t, C: o }));
1179
- 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"), p = n && b(L(n), "../../routes");
1180
- if (!n)
1181
- return null;
1182
- const y = B.parse(J(n).toString()), A = (m, d, h) => {
1183
- let w = b(m, `${d}${h ? `.${h}` : ""}.yml`);
1184
- return (!$(w) || !x(w).isFile()) && (w = b(m, d, `index${h ? `.${h}` : ""}.yml`), !$(w) || !x(w)) ? null : B.parse(J(w).toString());
1185
- }, j = (m, d) => {
1186
- try {
1187
- const h = se(`*.${d}.yml`, { cwd: m, absolute: !0 })[0];
1188
- return h ? B.parse(J(h).toString()) : null;
1189
- } catch (h) {
1190
- f.error("parse component error", h);
1191
- }
1192
- return null;
1193
- }, I = (m, d) => {
1194
- let h = b(m, `${d}.yml`);
1195
- return (!$(h) || !x(h).isFile()) && (h = b(m, d, "index.yml"), !$(h) || !x(h)) ? null : B.parse(J(h).toString());
1196
- }, u = T(
1197
- y.pages.map(({ slug: m }) => {
1198
- const d = T(
1199
- y.supportedLocales.map(({ locale: P }) => {
1200
- const i = c ? A(c, ne(m), P) : void 0;
1201
- if (i)
1202
- return { locale: P, page: i };
1203
- const S = c ? A(c, m, P) : void 0;
1204
- return S && { locale: P, page: S };
1205
- })
1206
- ), h = d[0]?.page;
1207
- if (!h)
1208
- return null;
1209
- const w = h.sections.map(dt);
1210
- return {
1211
- id: h.id || De(),
1212
- createdAt: h.createdAt,
1213
- updatedAt: h.updatedAt,
1214
- publishedAt: h.publishedAt,
1215
- isPublic: h.isPublic ?? !0,
1216
- templateConfig: h.templateConfig,
1217
- slug: m,
1218
- sections: Object.fromEntries(w.map((P) => [P.id, P])),
1219
- sectionIds: w.map((P) => P.id),
1220
- locales: Object.fromEntries(d.map(({ locale: P, page: i }) => [P, i.meta])),
1221
- dataSource: h.dataSource ? Object.fromEntries(
1222
- // 获取 dataSource 中所有 section ID
1223
- [...new Set(d.flatMap(({ page: P }) => Object.keys(P.dataSource ?? {})))].map((P) => [
1224
- P,
1225
- Object.fromEntries(
1226
- d.map(({ locale: i, page: S }) => {
1227
- const v = S.dataSource?.[P];
1228
- return [i, v || {}];
1229
- })
1230
- )
1231
- ])
1232
- ) : Object.fromEntries(
1233
- // 获取所有 section ID
1234
- [...new Set(d.flatMap(({ page: P }) => P.sections.map((i) => i.id)))].map((P) => [
1235
- P,
1236
- Object.fromEntries(
1237
- d.map(({ locale: i, page: S }) => {
1238
- const v = S.dataSource?.[P];
1239
- if (v)
1240
- return [i, v];
1241
- const G = S.sections.find((z) => z.id === P);
1242
- return [i, G?.properties || {}];
1243
- })
1244
- )
1245
- ])
1246
- )
1247
- };
1248
- })
1249
- ), l = T(
1250
- y?.routes?.map(({ path: m }) => {
1251
- const d = p ? I(p, ne(m)) : void 0;
1252
- return {
1253
- ...d,
1254
- id: d?.id || De(),
1255
- createdAt: d?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1256
- updatedAt: d?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1257
- publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
1258
- path: d?.path ?? `/${d?.id}`,
1259
- params: d?.params,
1260
- handler: d?.handler ?? "Pages Kit",
1261
- isPublic: d?.isPublic ?? !0,
1262
- enabledGenerate: d?.enabledGenerate ?? !1,
1263
- displayTemplateId: d?.displayTemplateId ?? void 0,
1264
- dataSource: d?.dataSource ?? {}
1265
- };
1266
- }) ?? []
1267
- ), g = r ? T(y.components?.map(({ id: m }) => j(r, m)) ?? []) : [];
1268
- if (e) {
1269
- const m = (...d) => {
1270
- f.info(`[${a ? k(t) : k(b(t, "../../../../"))}] importAssets:`, ...d);
1271
- };
1272
- try {
1273
- m("wait image-bin api ready"), await wt({
1274
- resources: [`${mt(tt)}/api/sdk/uploads`],
1275
- validateStatus: (w) => w >= 200 && w <= 500
1276
- }), m("image-bin api is ready");
1277
- const d = {}, h = {};
1278
- m("start to upload assets"), await Promise.allSettled([
1279
- Ne(g, d, {
1280
- getFilePath: (w) => r && b(r, w),
1281
- onFinish: (w) => {
1282
- m(`upload ${w.length} component assets`);
1283
- }
1284
- }),
1285
- Ne(u, h, {
1286
- getFilePath: (w, P) => {
1287
- const i = be(u, P.slice(0, 1));
1288
- return c && b(c, L(i.slug), w);
1289
- },
1290
- onFinish: (w) => {
1291
- m(`upload ${w.length} page assets`);
1292
- }
1293
- })
1294
- ]), m("upload assets done"), Se.clear(), global.gc && global.gc();
1295
- } catch (d) {
1296
- m("Error during asset import:", d);
1297
- }
1298
- }
1299
- const C = {};
1300
- if (s) {
1301
- const m = n && b(L(n), "../../resources/components"), d = T(
1302
- y.resources?.components?.map(({ id: h }) => j(m, h)) ?? []
1303
- );
1304
- d.length > 0 && (C.components = Object.fromEntries(
1305
- d.map((h, w) => [h.id, { index: w, component: h }])
1306
- ));
1307
- }
1308
- return {
1309
- supportedLocales: y.supportedLocales,
1310
- pageIds: u.map((m) => m.id),
1311
- components: Object.fromEntries(g.map((m, d) => [m.id, { index: d, data: m }])),
1312
- pages: Object.fromEntries(u.map((m) => [m.id, m])),
1313
- config: y.config || {},
1314
- resources: C,
1315
- routeIds: l.map((m) => m.id),
1316
- routes: Object.fromEntries(l.map((m) => [m.id, m])),
1317
- dataSourceIds: [],
1318
- dataSources: {}
1319
- };
1320
- } finally {
1321
- a && o && Ge(o, { force: !0, recursive: !0 });
1322
- }
1323
- }
1324
- async function _e(t, e, {
1325
- routes: s,
1326
- mergeMode: o = "byUpdateTime",
1327
- deleteRoutes: a = !1,
1328
- publishMode: n = void 0
1329
- } = {}) {
1330
- try {
1331
- n && st(n);
1332
- } catch (I) {
1333
- f.error("clear preload page cache error", { error: I });
1334
- }
1335
- const { pages: c, pageIds: r, routeIds: p, routes: y, supportedLocales: A } = t;
1336
- if (n === "production") {
1337
- let I = s ?? [], u = null;
1338
- for (const l of p ?? []) {
1339
- const g = y?.[l];
1340
- if (g?.params && g?.params.length > 0 && g?.paramsOptions && g?.paramsOptions.length > 0) {
1341
- const C = Ie({
1342
- basePath: g.path,
1343
- params: g.params,
1344
- routeId: g.id,
1345
- paramsOptions: g.paramsOptions,
1346
- currentIndex: 0,
1347
- currentParams: [],
1348
- currentOptionIds: [],
1349
- result: []
1350
- }), m = Object.fromEntries(C.map((d) => [`${l}-${d.paramOptionIds.join("-")}`, d]));
1351
- u = { ...u || {}, ...m }, s || (I = [...I, ...C.map((d) => `${l}-${d.paramOptionIds.join("-")}`)]);
1352
- } else s || I.push(l);
1353
- }
1354
- f.info("routeIds to be published: ", I);
1355
- for (const l of I) {
1356
- let g = l;
1357
- if (g.includes("-")) {
1358
- const [d] = g.split("-");
1359
- g = d;
1360
- }
1361
- const C = y?.[g];
1362
- if (!C) {
1363
- const d = e.pageIds.indexOf(g);
1364
- d !== -1 && a && (e.pageIds.splice(d, 1), delete e.pages[g]);
1365
- for (const h of e.pageIds)
1366
- h.includes(`${g}-`) && (e.pageIds.splice(e.pageIds.indexOf(h), 1), delete e.pages[h]);
1367
- f.info("delete main route page", g);
1368
- continue;
1369
- }
1370
- if (l.includes("-") && !u?.[l]) {
1371
- const d = e.pageIds.indexOf(l);
1372
- d !== -1 && a && (e.pageIds.splice(d, 1), delete e.pages[l]), f.info("delete page", l);
1373
- continue;
1374
- }
1375
- if (!C.displayTemplateId) {
1376
- f.info("no display template", l);
1377
- continue;
1378
- }
1379
- const m = c[C.displayTemplateId];
1380
- if (!m) {
1381
- f.info("no template page", l);
1382
- continue;
1383
- }
1384
- if (e.pageIds.includes(l)) {
1385
- if (f.info("has need update page", l), o === "replace")
1386
- e.pages[l] = fe({
1387
- page: m,
1388
- route: C,
1389
- state: t,
1390
- routeId: l,
1391
- routePathInfo: u?.[l]
1392
- }), f.info("replace page", l);
1393
- else if (o === "byUpdateTime") {
1394
- const d = e.pages[C.id];
1395
- (!d || C.updatedAt && C.updatedAt > d.updatedAt) && (e.pages[l] = fe({
1396
- page: m,
1397
- route: C,
1398
- state: t,
1399
- routeId: l,
1400
- routePathInfo: u?.[l]
1401
- }), f.info("replace page by update time", l));
1402
- }
1403
- } else
1404
- e.pageIds.push(l), e.pages[l] = fe({
1405
- page: m,
1406
- route: C,
1407
- state: t,
1408
- routeId: l,
1409
- routePathInfo: u?.[l]
1410
- }), f.info("add page", l);
1411
- }
1412
- if (a && !s)
1413
- for (const l of e.pageIds)
1414
- I?.includes(l) || (delete e.pages[l], f.info("delete page", l)), e.pageIds = [...e.pageIds].filter((g) => I?.includes(g));
1415
- } else {
1416
- for (const I of r) {
1417
- const u = c[I];
1418
- if (u)
1419
- if (e.pageIds.includes(u.id)) {
1420
- if (o === "replace")
1421
- e.pages[u.id] = u;
1422
- else if (o === "byUpdateTime") {
1423
- const l = e.pages[u.id];
1424
- (!l || u.updatedAt && u.updatedAt > l.updatedAt) && (e.pages[u.id] = u);
1425
- }
1426
- } else
1427
- e.pageIds.push(u.id), e.pages[u.id] = u;
1428
- }
1429
- for (const I of p) {
1430
- const u = y[I];
1431
- if (u)
1432
- if (e.routeIds.includes(u.id)) {
1433
- if (o === "replace")
1434
- e.routes[u.id] = u;
1435
- else if (o === "byUpdateTime") {
1436
- const l = e.routes[u.id];
1437
- (!l || u.updatedAt && u.updatedAt > l.updatedAt) && (e.routes[u.id] = u);
1438
- }
1439
- } else
1440
- e.routeIds.push(u.id), e.routes[u.id] = u;
1441
- }
1442
- }
1443
- if (e.supportedLocales.splice(0, e.supportedLocales.length), e.supportedLocales.push(...Ee(A)), a)
1444
- for (const I of Object.keys(e.components))
1445
- delete e.components[I];
1446
- let j = JSON.parse(JSON.stringify(t.components));
1447
- j = Object.fromEntries(
1448
- await Promise.all(
1449
- Object.entries(j).map(async ([I, u]) => {
1450
- const l = await Je(u?.data);
1451
- return [
1452
- I,
1453
- {
1454
- ...u,
1455
- data: l
1456
- }
1457
- ];
1458
- })
1459
- )
1460
- ), 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 || {})));
1461
- }
1462
- const Je = ot(
1463
- async (t) => {
1464
- if (!Ae(t?.properties))
1465
- return t;
1466
- if (t?.renderer?.type === "react-component") {
1467
- const { script: e, PROPERTIES_SCHEMA: s } = t?.renderer || {};
1468
- if (s || e && e.includes("PROPERTIES_SCHEMA"))
1469
- try {
1470
- const o = await at(
1471
- e ?? "",
1472
- "PROPERTIES_SCHEMA",
1473
- t.id,
1474
- s
1475
- );
1476
- o && o.length > 0 && t && (t.properties = {}, o.forEach((a, n) => {
1477
- t?.properties && (t.properties[a.id] = {
1478
- index: n,
1479
- data: a
1480
- });
1481
- }));
1482
- } catch (o) {
1483
- f.error("getPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: o });
1484
- }
1485
- }
1486
- return t;
1487
- },
1488
- {
1489
- subdir: "getPropertiesFromCode"
1490
- }
1491
- );
1492
- let re, Q, ie, ce;
1493
- const Ye = () => gt({
1494
- types: [
1495
- { did: ze, type: Ue },
1496
- { did: Lt, type: Ue }
1497
- ]
1498
- }), ss = () => {
1499
- const t = Ye(), e = {};
1500
- return t.forEach((s) => {
1501
- const o = se("**/.blocklet/pages/pages.config.yml", { cwd: s.path, absolute: !0 }).at(0), a = o && b(L(o), "../../chunks");
1502
- if (a && $(a)) {
1503
- const n = pt(a);
1504
- for (const c of n)
1505
- e[c] = b(a, c);
1506
- }
1507
- }), e;
1508
- };
1509
- function We() {
1510
- return re = (async () => {
1511
- const t = Ye();
1512
- Q = (await Promise.all(
1513
- t.map(async (s) => {
1514
- const o = s.path ? await He(s.path, { importAssets: !1 }) : void 0;
1515
- return o ? { blockletId: s.did, state: o, blockletTitle: s.title } : void 0;
1516
- })
1517
- )).filter((s) => !!s), ie = Q.reduce(
1518
- (s, o) => Object.assign(
1519
- s,
1520
- Object.fromEntries(
1521
- Object.values(o.state.pages).map((a) => a ? [a?.id, { page: a, blockletId: o.blockletId }] : [])
1522
- )
1523
- ),
1524
- {}
1525
- );
1526
- const e = Q.reduce(
1527
- (s, o) => Object.assign(
1528
- s,
1529
- Object.fromEntries(
1530
- Object.values(o.state.components).map((a) => [a.data.id, { blockletId: o.blockletId, component: a.data }])
1531
- )
1532
- ),
1533
- {}
1534
- );
1535
- ce = Object.fromEntries(
1536
- await Promise.all(
1537
- Object.entries(e).map(async ([s, o]) => {
1538
- const a = await Je(o.component);
1539
- return [
1540
- s,
1541
- {
1542
- ...o,
1543
- component: a
1544
- }
1545
- ];
1546
- })
1547
- )
1548
- );
1549
- })(), re;
1550
- }
1551
- function os(t) {
1552
- const e = xe(
1553
- async () => {
1554
- await We().catch((s) => {
1555
- f.error("load resource states error", { error: s });
1556
- }), await t?.({
1557
- states: Q,
1558
- pages: ie,
1559
- components: ce
1560
- });
1561
- },
1562
- 3e3,
1563
- // 3s
1564
- { leading: !1, trailing: !0 }
1565
- );
1566
- 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), () => {
1567
- 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);
1568
- };
1569
- }
1570
- const Xe = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), Qe = Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"), le = globalThis;
1571
- le[Xe]?.();
1572
- le[Xe] = os(async ({ pages: t, components: e }) => {
1573
- const s = await O.getProjectIds();
1574
- f.info(`start update resource states projects(${s.length})`, s), await Promise.race([
1575
- new Promise((o) => {
1576
- setTimeout(() => {
1577
- o({});
1578
- }, 30 * 1e3);
1579
- }),
1580
- Promise.all(
1581
- s.map(async (o) => {
1582
- Ze({
1583
- projectId: o,
1584
- pages: t,
1585
- components: e
1586
- });
1587
- })
1588
- )
1589
- ]).catch((o) => {
1590
- f.error("update resource states failed:", o);
1591
- });
1592
- });
1593
- le[Qe]?.();
1594
- le[Qe] = () => {
1595
- const t = () => {
1596
- O.pageUrlMapCache.clear(), f.info("[Cache CLEAR ALL] clear all page url map cache by env update");
1597
- };
1598
- return E.events.on(E.Events.envUpdate, t), () => {
1599
- E.events.off(E.Events.envUpdate, t);
1600
- };
1601
- };
1602
- O.startPeriodicCheck();
1603
- process.on("beforeExit", () => {
1604
- O.stopPeriodicCheck();
1605
- });
1606
- process.on("SIGINT", () => {
1607
- O.stopPeriodicCheck(), process.exit(0);
1608
- });
1609
- process.on("SIGTERM", () => {
1610
- O.stopPeriodicCheck(), process.exit(0);
1611
- });
1612
- async function Ze({
1613
- projectId: t,
1614
- pages: e,
1615
- components: s
1616
- }) {
1617
- const o = O.sharedInstances[t];
1618
- if (!o) {
1619
- f.info(`projectId: ${t} not found in sharedInstances`);
1620
- return;
1621
- }
1622
- if (o.syncedStore.resources.pages = e, (await U.findByPk(t))?.useAllResources)
1623
- o.syncedStore.resources.components = s;
1624
- else {
1625
- const c = (await Ce.findAll({ where: { projectId: t } })).map((p) => p.componentId), r = Object.fromEntries(
1626
- Object.entries(s || {}).filter(([p]) => c.includes(p))
1627
- );
1628
- o.syncedStore.resources.components = r;
1629
- }
1630
- f.info(`update [${t}] resource states:`, {
1631
- pages: Object.keys(o.syncedStore.resources.pages || {}).length,
1632
- components: Object.keys(o.syncedStore.resources.components || {}).length
1633
- });
1634
- }
1635
- async function as(t) {
1636
- return Ze({
1637
- projectId: t,
1638
- pages: ie,
1639
- components: ce
1640
- });
1641
- }
1642
- async function _s() {
1643
- f.info("trigger reload all project resource"), E.events.emit(he);
1644
- }
1645
- async function Fs({
1646
- ensureLoaded: t = !0
1647
- } = {}) {
1648
- return t && (re ??= We(), await re), { states: Q, pages: ie, components: ce };
1649
- }
1650
- export {
1651
- ze as C,
1652
- U as P,
1653
- Ue as R,
1654
- O as S,
1655
- H as a,
1656
- $s as b,
1657
- Ns as c,
1658
- Xt as d,
1659
- Zt as e,
1660
- es as f,
1661
- Fs as g,
1662
- He as h,
1663
- os as i,
1664
- _s as j,
1665
- _e as m,
1666
- ts as t,
1667
- as as u
1668
- };