@blocklet/pages-kit-inner-components 0.7.3 → 0.7.5

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