@blocklet/pages-kit-inner-components 0.7.4 → 0.7.6

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,1936 +0,0 @@
1
- import { d as Je, l as u, 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 Pe } from "@blocklet/pages-kit/utils/route";
6
- import be from "lodash/cloneDeep";
7
- import { DataTypes as P, Sequelize as ht, Model as Ae, Op as Ee } from "sequelize";
8
- import "sqlite3";
9
- import E from "@blocklet/sdk/lib/config";
10
- import { withoutTrailingSlash as Oe, withLeadingSlash as He, joinURL as G } 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 Ce from "p-limit";
15
- import Ne, { join as A, basename as N, dirname as M } from "path";
16
- import { nextId as $e } 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 Ct } from "@blocklet/sdk/lib/component";
20
- import { reactive as Rt } from "@reactivedata/reactive";
21
- import { rename as Ue, mkdir as x, rm as Ke, writeFile as oe, lstat as se, readFile as Z, copyFile as jt, readdir as Dt } from "fs/promises";
22
- import { globSync as kt, glob as he } from "glob";
23
- import * as de from "lib0/decoding";
24
- import * as v from "lib0/encoding";
25
- import Re 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 Nt from "wait-on";
34
- import { Awareness as $t, encodeAwarenessUpdate as _e, removeAwarenessStates as Ut, 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 ye = null;
79
- ye && clearInterval(ye);
80
- ye = setInterval(
81
- async () => {
82
- u.info("Start cleanupSqliteMemory"), await Gt(_, Je), u.info("End cleanupSqliteMemory");
83
- },
84
- 60 * 1e3 * 10
85
- // 10 minutes
86
- );
87
- const Vt = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", xe = "page", Se = "trigger-reload-project-resource", Ye = Vt, zt = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM", qt = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";
88
- class ke extends Ae {
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 $ extends Ae {
148
- static async getProjectByIdOrSlug(e, s) {
149
- return e ? $.findOne({
150
- where: {
151
- [Ee.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 $.findOne({
176
- where: { slug: a }
177
- });
178
- return l && l?.id !== s ? Kt : null;
179
- }
180
- }
181
- $.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 u.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
- u.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 u.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
- u.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
- [Ee.ne]: null
279
- }
280
- }
281
- }
282
- ]
283
- }
284
- );
285
- $.hasMany(ke, {
286
- foreignKey: "projectId",
287
- as: "components"
288
- });
289
- async function B(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 = Ne.join(t, a.name), n = Ne.join(e, a.name);
307
- a.isDirectory() ? await Qe(o, n) : await Xe(o, n);
308
- }
309
- }
310
- async function Xs(t, e) {
311
- (await z.promises.stat(t)).isDirectory() ? await Qe(t, e) : await Xe(t, e);
312
- }
313
- class ae extends Ae {
314
- }
315
- ae.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, m) => {
418
- o && (l[G("/", o, i)] = {
419
- ...m,
420
- shouldRedirect: !0,
421
- mainPage: !0
422
- }), l[G("/", e, i)] = {
423
- ...m,
424
- shouldRedirect: !0,
425
- mainPage: !0
426
- };
427
- for (const b of n) {
428
- const O = { ...m, locale: b };
429
- l[G("/", b, e, i)] = O, o && (l[G("/", b, o, i)] = O);
430
- }
431
- };
432
- for (const i of a.pageIds || []) {
433
- const m = a.pages?.[i];
434
- if (!m || !m.isPublic)
435
- continue;
436
- const b = {
437
- projectId: e,
438
- projectSlug: o,
439
- pageSlug: m.slug,
440
- pageId: i,
441
- defaultLocale: n?.[0],
442
- locales: n,
443
- publishedAt: a.config?.publishedAt,
444
- isPublic: m.isPublic
445
- };
446
- r(m.slug, b);
447
- }
448
- return l;
449
- }
450
- function ne(t) {
451
- t.observeDeep((e) => {
452
- e.some((s) => s.changes.keys.has("updatedAt") || s.changes.keys.has("publishedAt")) || t.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
453
- });
454
- }
455
- function Ze() {
456
- return St(A(E.env.dataDir, "tmp-"));
457
- }
458
- function re(t, e, s = []) {
459
- return Array.isArray(t) ? t.flatMap((a, o) => re(a, e, [...s, o])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([a, o]) => re(o, e, [...s, a])) : e(t) ? [s] : [];
460
- }
461
- function L(t) {
462
- return t.filter((e) => e != null);
463
- }
464
- function Ge(t, e) {
465
- if (t === e) return !0;
466
- if (!t || !e) return t === e;
467
- const s = Object.keys(t), a = Object.keys(e);
468
- if (s.length !== a.length) return !1;
469
- if (s.length < 10) {
470
- for (const l of s) {
471
- if (!(l in e)) return !1;
472
- const r = t[l], i = e[l];
473
- 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)
474
- return !1;
475
- }
476
- return !0;
477
- }
478
- 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");
479
- return o === n;
480
- }
481
- function Qt(t) {
482
- t.pages && Object.keys(t.pages).forEach((s) => {
483
- const a = J(t.pages[s]);
484
- a && a instanceof F.Map && ne(a);
485
- });
486
- const e = J(t.pages);
487
- e && e instanceof F.Map && e.observe((s) => {
488
- s.changes.keys.forEach((a, o) => {
489
- if (a.action === "add") {
490
- const n = J(t.pages[o]);
491
- n && n instanceof F.Map && ne(n);
492
- }
493
- });
494
- });
495
- }
496
- function Zt(t) {
497
- t.routes && Object.keys(t.routes).forEach((s) => {
498
- const a = J(t.routes?.[s]);
499
- a && a instanceof F.Map && ne(a);
500
- });
501
- const e = J(t.routes);
502
- e && e instanceof F.Map && e.observe((s) => {
503
- s.changes.keys.forEach((a, o) => {
504
- if (a.action === "add") {
505
- const n = J(t.routes?.[o]);
506
- n && n instanceof F.Map && ne(n);
507
- }
508
- });
509
- });
510
- }
511
- function es(t, e) {
512
- for (const s of e || Object.keys(t.routes || {})) {
513
- let a = s, o = [];
514
- if (s.includes("-")) {
515
- const [n, ...l] = s.split("-");
516
- a = n, o = l || [];
517
- }
518
- if (t.routes?.[a] !== void 0) {
519
- t.routes[a].publishedAt = (/* @__PURE__ */ new Date()).toISOString();
520
- const n = t.routes[a];
521
- if (!n || !n.params || n.params.length === 0)
522
- continue;
523
- if (s.includes("-") && o.length > 0) {
524
- const l = gt(o, n);
525
- l && (l.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
526
- }
527
- if (!e) {
528
- const l = Pe({
529
- basePath: n.path,
530
- params: n.params,
531
- routeId: n.id,
532
- paramsOptions: n.paramsOptions,
533
- currentIndex: 0,
534
- currentParams: [],
535
- currentOptionIds: [],
536
- result: []
537
- });
538
- for (const r of l)
539
- r.routeMetaData ??= {}, r.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString();
540
- }
541
- }
542
- }
543
- }
544
- function fe({
545
- page: t,
546
- route: e,
547
- state: s,
548
- routeId: a,
549
- routePathInfo: o
550
- }) {
551
- u.info(
552
- `Executing datasource data assembly, routeId: ${a}, routePathInfo: ${JSON.stringify(o)}`
553
- );
554
- const n = {
555
- ...be(t),
556
- id: a,
557
- slug: o?.path ?? e.path,
558
- createdAt: e.createdAt,
559
- updatedAt: o?.routeMetaData?.updatedAt ?? e.updatedAt,
560
- publishedAt: o?.routeMetaData?.publishedAt ?? e.publishedAt,
561
- isPublic: (o?.routeMetaData?.isPublic ?? e.isPublic) && e.isPublic
562
- };
563
- for (const l of s.supportedLocales) {
564
- if (e.dataSource) {
565
- let r = e.id;
566
- o && (r = o.paramOptionIds.join("-"));
567
- const i = e.dataSource.pathDataMappings?.[r]?.dataCache?.[l.locale] ?? e.dataSource.pathDataMappings?.[r]?.dataCache?.[s.config.defaultLocale || "en"];
568
- if (!i)
569
- continue;
570
- mt(n, s, l.locale, i);
571
- }
572
- o && o.routeMetaData && (o.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
573
- }
574
- return n;
575
- }
576
- ["true", "1", "yes", "y"].includes(process.env.USE_FS_CACHE_HTML ?? "");
577
- const ts = 60 * 60 * 1e3, Y = new We({
578
- max: 300,
579
- ttl: ts,
580
- ttlResolution: 10 * 1e3,
581
- // 10 seconds
582
- allowStale: !0
583
- });
584
- function ss(t, e = []) {
585
- let s = 0;
586
- const a = Array.from(Y.keys()), o = t.map((n) => Oe(n));
587
- for (const n of a)
588
- for (const l of o) {
589
- if (Fe(n, { currentPath: l })) {
590
- Y.delete(n), s++, u.info(`[Cache CLEAR] key: ${n}`);
591
- break;
592
- }
593
- for (const r of e)
594
- if (Fe(n, { currentPath: `/${r}${l}` })) {
595
- Y.delete(n), s++, u.info(`[Cache CLEAR] key: ${n}`);
596
- break;
597
- }
598
- }
599
- return u.info(`[Cache CLEAR] cleared ${s} entries for paths:`, o), s;
600
- }
601
- function as() {
602
- const t = Y.size;
603
- return Y.clear(), u.info(`[Cache CLEAR ALL] cleared ${t} entries`), t;
604
- }
605
- E.events.on(E.Events.envUpdate, as);
606
- const { uploadToMediaKit: os } = 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, ns = 1e4, rs = 3e4, ee = 0, me = 1, is = 0, cs = 1, we = E, W = A(process.env.BLOCKLET_DATA_DIR, "site-state"), Qs = ["production", "draft"], Zs = ["production"];
607
- function ie(t) {
608
- return t?.replace(/\//g, "|") || "";
609
- }
610
- function ls() {
611
- const t = we.env.languages?.map((s) => ({ locale: s.code, name: s.name })) || [], e = t[0]?.locale || "en";
612
- return {
613
- pageIds: [],
614
- pages: {},
615
- routeIds: [],
616
- routes: {},
617
- dataSourceIds: [],
618
- dataSources: {},
619
- components: {},
620
- supportedLocales: t,
621
- config: { defaultLocale: e },
622
- resources: {}
623
- };
624
- }
625
- class D extends F.Doc {
626
- constructor(e) {
627
- super(), this.options = e, wt(this.draftYjsFilePath) && F.applyUpdate(this, It(this.draftYjsFilePath)), this.syncedStore = Rt(
628
- ft(
629
- {
630
- pages: {},
631
- pageIds: [],
632
- components: {},
633
- supportedLocales: [],
634
- config: {},
635
- resources: {},
636
- routeIds: [],
637
- routes: {},
638
- dataSourceIds: [],
639
- dataSources: {}
640
- },
641
- this
642
- )
643
- ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new $t(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
644
- }
645
- // 延迟释放时间:5 分钟
646
- static RELEASE_DELAY = 5 * 60 * 1e3;
647
- // 定期检查间隔:2 小时
648
- static PERIODIC_CHECK_INTERVAL = 2 * 60 * 60 * 1e3;
649
- // 2 hours
650
- static sharedInstances = {};
651
- // 定期检查定时器
652
- static periodicCheckTimer;
653
- // safe delete project state dir
654
- static async safeDeleteProjectStateDir(e) {
655
- if (!e)
656
- throw new Error("Should provide project context");
657
- try {
658
- const s = A(W, e), a = A(W, `@del-${e}`);
659
- await Ue(s, a);
660
- } catch (s) {
661
- u.error("Failed to safe delete project state dir:", s);
662
- }
663
- }
664
- static async getProjectIds() {
665
- return (await $.findAll({ attributes: ["id"], raw: !0 }))?.map((e) => e.id);
666
- }
667
- /** @deprecated 不再使用这个 getter 了,仅作为兼容性处理,请使用 getProjectIds 代替 */
668
- static get projectIds() {
669
- return kt("*/", {
670
- cwd: W,
671
- ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*", "undefined"]
672
- // Ignore temp directories and hidden files
673
- });
674
- }
675
- /** @deprecated 不再使用这个 getter 了,仅作为兼容性处理 */
676
- static get allShared() {
677
- return this.projectIds.map((e) => D.shared(e));
678
- }
679
- static shared(e) {
680
- if (!e)
681
- throw new Error("Should provide project context");
682
- let s = D.sharedInstances[e];
683
- return s || (s = new D({
684
- path: A(W, e)
685
- }), D.sharedInstances[e] = s, s);
686
- }
687
- // 轻量级 production 状态获取,不加载 draft 数据
688
- static async getProductionState(e) {
689
- const s = await $.findByPk(e, {
690
- attributes: ["productionState"]
691
- });
692
- if (De(s?.productionState)) {
693
- const a = A(W, e, "production"), o = await tt(a, { includeResources: !0 }) ?? ls();
694
- if (!o?.config?.defaultLocale) {
695
- o.config ??= {};
696
- const n = we.env.languages?.map((l) => ({ locale: l.code, name: l.name })) || [];
697
- o.config.defaultLocale = n[0]?.locale;
698
- }
699
- return o;
700
- }
701
- return s?.productionState;
702
- }
703
- destroy() {
704
- this.cancelRelease(), this.save({ flush: !0 }), this.conns.forEach((s, a) => this.closeConn(a)), this.awareness.destroy();
705
- const e = N(this.options.path);
706
- delete D.sharedInstances[e], super.destroy();
707
- }
708
- initObserver() {
709
- Qt(this.syncedStore), Zt(this.syncedStore);
710
- }
711
- get draftYjsFilePath() {
712
- return A(this.options.path, "draft.yjs");
713
- }
714
- static async getStateByProjectId({
715
- projectId: e,
716
- mode: s,
717
- clone: a = !0
718
- }) {
719
- if (s === "draft") {
720
- const o = D.shared(e);
721
- return a ? JSON.parse(JSON.stringify(o.syncedStore)) : o.syncedStore;
722
- }
723
- return D.getProductionState(e);
724
- }
725
- async getState(e) {
726
- if (e === "draft")
727
- return JSON.parse(JSON.stringify(this.syncedStore));
728
- const s = N(this.options.path);
729
- return D.getProductionState(s);
730
- }
731
- async setState(e, s) {
732
- const a = await fs(s, { exportAssets: !1, includeResources: !0 }), o = this.getPublishDir(e);
733
- if (await x(M(o), { recursive: !0 }), await Ke(o, { force: !0, recursive: !0 }), await Ue(a, o), e === "production") {
734
- const n = N(this.options.path), l = be(s);
735
- await _.transaction(async (r) => {
736
- await $.update({ productionState: l }, { where: { id: n }, transaction: r });
737
- const i = await $.findByPk(n, {
738
- attributes: ["slug"],
739
- transaction: r
740
- }), m = Xt({
741
- projectId: n,
742
- projectSlug: i?.slug,
743
- state: s
744
- });
745
- await ae.destroy({
746
- where: { projectId: n },
747
- transaction: r
748
- });
749
- const b = Object.entries(m).map(([O, p]) => ({
750
- projectId: n,
751
- urlPath: O,
752
- projectSlug: p.projectSlug,
753
- pageSlug: p.pageSlug,
754
- pageId: p.pageId,
755
- routeId: p.routeId,
756
- locale: p.locale,
757
- defaultLocale: p.defaultLocale,
758
- shouldRedirect: p.shouldRedirect,
759
- mainPage: p.mainPage,
760
- isPublic: p.isPublic,
761
- publishedAt: p.publishedAt,
762
- locales: p.locales
763
- }));
764
- if (b.length > 0)
765
- for (let p = 0; p < b.length; p += 100)
766
- await ae.bulkCreate(b.slice(p, p + 100), { transaction: r });
767
- u.info(`[SiteState] saved ${b.length} URL mappings for project ${n}`);
768
- });
769
- }
770
- }
771
- getPublishDir(e) {
772
- return A(this.options.path, e);
773
- }
774
- syncedStore;
775
- conns = /* @__PURE__ */ new Map();
776
- awareness;
777
- // 延迟释放定时器
778
- releaseTimer;
779
- awarenessChangeHandler = ({ added: e, updated: s, removed: a }, o) => {
780
- const n = e.concat(s, a);
781
- if (o !== null) {
782
- const i = this.conns.get(o);
783
- i && (e.forEach((m) => {
784
- i.add(m);
785
- }), a.forEach((m) => {
786
- i.delete(m);
787
- }));
788
- }
789
- const l = v.createEncoder();
790
- v.writeVarUint(l, me), v.writeVarUint8Array(l, _e(this.awareness, n));
791
- const r = v.toUint8Array(l);
792
- this.conns.forEach((i, m) => this.send(m, r));
793
- };
794
- updateHandler = (e) => {
795
- const s = v.createEncoder();
796
- v.writeVarUint(s, ee), _t(s, e);
797
- const a = v.toUint8Array(s);
798
- this.conns.forEach((o, n) => this.send(n, a));
799
- };
800
- ensureDataStructure = () => {
801
- this.transact(() => {
802
- const { supportedLocales: e, pages: s, pageIds: a, config: o, routes: n, routeIds: l } = this.syncedStore;
803
- {
804
- const r = new Set(Object.keys(s));
805
- let i = 0;
806
- for (; i < a.length; ) {
807
- const m = a[i];
808
- r.has(m) ? (r.delete(m), i++) : a.splice(i, 1);
809
- }
810
- }
811
- {
812
- const r = new Set(Object.keys(n));
813
- let i = 0;
814
- for (; i < l.length; ) {
815
- const m = l[i];
816
- r.has(m) ? (r.delete(m), i++) : l.splice(i, 1);
817
- }
818
- }
819
- e.splice(0, e.length), e.push(...we.env.languages.map((r) => ({ locale: r.code, name: r.name }))), o.defaultLocale = e[0]?.locale;
820
- {
821
- let r = 0;
822
- const i = /* @__PURE__ */ new Set();
823
- for (; r < e.length; ) {
824
- const { locale: m } = e[r];
825
- i.has(m) ? e.splice(r, 1) : (r++, i.add(m));
826
- }
827
- }
828
- });
829
- };
830
- send = (e, s) => {
831
- e.readyState !== is && e.readyState !== cs && this.closeConn(e);
832
- try {
833
- e.send(s, (a) => {
834
- a && this.closeConn(e);
835
- });
836
- } catch {
837
- this.closeConn(e);
838
- }
839
- };
840
- closeConn = (e) => {
841
- if (e.removeAllListeners(), this.conns.has(e)) {
842
- const s = this.conns.get(e);
843
- this.conns.delete(e), s && Ut(this.awareness, Array.from(s), null);
844
- }
845
- e.close(), this.checkAndScheduleRelease();
846
- };
847
- // 检查并调度延迟释放
848
- checkAndScheduleRelease() {
849
- this.conns.size === 0 && this.scheduleRelease();
850
- }
851
- // 调度延迟释放
852
- scheduleRelease() {
853
- this.cancelRelease();
854
- const e = N(this.options.path);
855
- this.releaseTimer = setTimeout(() => {
856
- u.info(`[SiteState] releasing instance due to no active connections: ${e}`), this.conns.size === 0 && (this.releaseTimer = void 0, this.destroy());
857
- }, D.RELEASE_DELAY), u.info(`[SiteState] scheduled release for project ${e} in ${D.RELEASE_DELAY / 1e3}s`);
858
- }
859
- // 取消延迟释放
860
- cancelRelease() {
861
- if (this.releaseTimer) {
862
- clearTimeout(this.releaseTimer), this.releaseTimer = void 0;
863
- const e = N(this.options.path);
864
- u.info(`[SiteState] cancelled scheduled release for project ${e}`);
865
- }
866
- }
867
- autoSave = Re(async () => {
868
- await x(M(this.draftYjsFilePath), { recursive: !0 }), await oe(this.draftYjsFilePath, F.encodeStateAsUpdate(this));
869
- }, ns);
870
- save = ({ flush: e = !1 } = {}) => {
871
- this.autoSave(), e && this.autoSave.flush();
872
- };
873
- publish = async ({ mode: e, routes: s }) => {
874
- const a = N(this.options.path);
875
- await hs(a);
876
- const o = await this.getState("draft"), n = await this.getState("production");
877
- await qe(o, n, { routes: s, mergeMode: "replace", deleteRoutes: !0, publishMode: e }), n.config.publishedAt = (/* @__PURE__ */ new Date()).getTime(), es(this.syncedStore, s), await this.setState(e, n), await this.clearPageCacheForRoutes(s, n);
878
- };
879
- mergeState = async (e, s) => {
880
- const a = JSON.parse(JSON.stringify(s));
881
- e.config.fontFamily ??= {};
882
- const o = a.config?.fontFamily, n = e.config?.fontFamily;
883
- e.config.fontFamily.title = o?.title || n?.title, e.config.fontFamily.description = o?.description || n?.description, await new Promise((l, r) => {
884
- this.transact(async () => {
885
- try {
886
- const i = await qe(e, s);
887
- l(i);
888
- } catch (i) {
889
- r(i);
890
- }
891
- });
892
- });
893
- };
894
- clearPageCacheForRoutes = async (e, s) => {
895
- const a = N(this.options.path), n = (await $.findByPk(a))?.slug || a;
896
- let l = e;
897
- (!l || l.length === 0) && (l = s.pageIds ?? []), u.info(`[SiteState] clearing page cache for project ${a}, routes:`, l || []);
898
- const r = s.supportedLocales.map((b) => b.locale), i = [], m = l.filter((b) => s.pageIds?.includes(b));
899
- for (const b of m) {
900
- const p = s.pages[b].slug;
901
- n && n !== a && (n === "/" ? i.push(p) : i.push(`/${n}${p}`)), i.push(`/${a}${p}`);
902
- }
903
- if (i.length > 0)
904
- try {
905
- const b = ss(i, r);
906
- u.info(`[SiteState] cleared ${b} page cache entries for project ${a}, routes:`, l);
907
- } catch {
908
- }
909
- };
910
- addConnection = (e) => {
911
- if (this.conns.has(e))
912
- return;
913
- this.cancelRelease(), e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (o) => this.messageListener(e, new Uint8Array(o)));
914
- let s = !0;
915
- const a = setInterval(() => {
916
- if (!s)
917
- this.conns.has(e) && this.closeConn(e), clearInterval(a);
918
- else if (this.conns.has(e)) {
919
- s = !1;
920
- try {
921
- e.ping();
922
- } catch {
923
- this.closeConn(e), clearInterval(a);
924
- }
925
- }
926
- }, rs);
927
- e.on("close", () => {
928
- this.closeConn(e), clearInterval(a);
929
- }), e.on("pong", () => {
930
- s = !0;
931
- });
932
- {
933
- const o = v.createEncoder();
934
- v.writeVarUint(o, ee), Ft(o, this), this.send(e, v.toUint8Array(o));
935
- const n = this.awareness.getStates();
936
- if (n.size > 0) {
937
- const l = v.createEncoder();
938
- v.writeVarUint(l, me), v.writeVarUint8Array(l, _e(this.awareness, Array.from(n.keys()))), this.send(e, v.toUint8Array(l));
939
- }
940
- }
941
- };
942
- messageListener = (e, s) => {
943
- try {
944
- const a = v.createEncoder(), o = de.createDecoder(s), n = de.readVarUint(o);
945
- switch (n) {
946
- case ee:
947
- v.writeVarUint(a, ee), xt(o, a, this, null), v.length(a) > 1 && (this.ensureDataStructure(), this.send(e, v.toUint8Array(a)));
948
- break;
949
- case me: {
950
- Mt(this.awareness, de.readVarUint8Array(o), e);
951
- break;
952
- }
953
- default:
954
- u.warn(`Unsupported messageType ${n}`);
955
- }
956
- } catch (a) {
957
- u.error(a);
958
- }
959
- this.save();
960
- };
961
- // 这个方法还是需要动态的,因为可能会动态修改 projectSlug、语言之类的
962
- static async pageUrlMap(e, s) {
963
- if (u.info(`[SiteState] get pageUrlMap, mode: ${e}, projectId: ${s}`), e === "production") {
964
- const n = s ? { projectId: s } : {}, l = await ae.findAll({
965
- where: n,
966
- raw: !0
967
- }), r = {};
968
- for (const i of l)
969
- r[i.urlPath] = {
970
- projectId: i.projectId,
971
- projectSlug: i.projectSlug,
972
- pageSlug: i.pageSlug,
973
- pageId: i.pageId,
974
- routeId: i.routeId,
975
- locale: i.locale,
976
- defaultLocale: i.defaultLocale,
977
- shouldRedirect: i.shouldRedirect,
978
- mainPage: i.mainPage,
979
- isPublic: i.isPublic,
980
- publishedAt: i.publishedAt,
981
- locales: i.locales
982
- };
983
- return u.info(`[SiteState] loaded ${l.length} URL mappings from database`), r;
984
- }
985
- let a = [];
986
- s ? a = [s] : a = await this.getProjectIds();
987
- let o = {};
988
- if (a?.length) {
989
- u.info("[SiteState] find project infos from database, projectIds: ", a);
990
- const n = 30, l = Ce(5);
991
- for (let r = 0; r < a.length; r += n) {
992
- const i = a.slice(r, r + n);
993
- u.info(`[SiteState] processing project batch ${r / n + 1}, ids: `, i);
994
- const m = await $.findAll({
995
- where: {
996
- id: {
997
- [Ee.in]: i
998
- }
999
- },
1000
- attributes: {
1001
- exclude: ["relatedBlocklets"]
1002
- }
1003
- });
1004
- await Promise.all(
1005
- m?.map(
1006
- (b) => l(async () => {
1007
- const O = b.id, p = b.slug || O, h = {}, d = await D.getStateByProjectId({ projectId: b.id, mode: e, clone: !1 }), I = vt(
1008
- E.env.languages?.map((C) => C.code) || [],
1009
- d.supportedLocales?.map((C) => C.locale) || []
1010
- ), R = (C, w) => {
1011
- p && (h[G("/", p, C)] = {
1012
- ...w,
1013
- shouldRedirect: !0,
1014
- mainPage: !0
1015
- }), h[G("/", O, C)] = {
1016
- ...w,
1017
- shouldRedirect: !0,
1018
- mainPage: !0
1019
- };
1020
- for (const k of I) {
1021
- const y = { ...w, locale: k };
1022
- h[G("/", k, O, C)] = y, p && (h[G("/", k, p, C)] = y);
1023
- }
1024
- };
1025
- if (e === "draft")
1026
- for (const C of d.routeIds || []) {
1027
- const w = d?.routes?.[C];
1028
- if (!w) continue;
1029
- if (w.params && w.params.length > 0) {
1030
- const S = Pe({
1031
- basePath: w.path,
1032
- params: w.params,
1033
- routeId: w.id,
1034
- paramsOptions: w.paramsOptions,
1035
- currentIndex: 0,
1036
- currentParams: [],
1037
- currentOptionIds: [],
1038
- result: []
1039
- });
1040
- for (const c of S) {
1041
- const f = c.path, g = {
1042
- projectId: O,
1043
- projectSlug: p,
1044
- pageSlug: f,
1045
- pageId: w.displayTemplateId || "",
1046
- routeId: C,
1047
- // default locale
1048
- defaultLocale: I?.[0],
1049
- locales: I,
1050
- publishedAt: d.config.publishedAt,
1051
- isPublic: w.isPublic && c?.routeMetaData?.isPublic
1052
- };
1053
- R(f, g);
1054
- }
1055
- }
1056
- const k = w.path, y = {
1057
- projectId: O,
1058
- projectSlug: p,
1059
- pageSlug: k,
1060
- pageId: w.displayTemplateId || "",
1061
- routeId: C,
1062
- // default locale
1063
- defaultLocale: I?.[0],
1064
- locales: I,
1065
- publishedAt: d.config.publishedAt,
1066
- isPublic: w.isPublic
1067
- };
1068
- R(k, y);
1069
- }
1070
- for (const C of d.pageIds || []) {
1071
- const w = d.pages[C];
1072
- if (!w) continue;
1073
- const k = w.slug, y = b.slug || O, S = {
1074
- projectId: O,
1075
- projectSlug: y,
1076
- pageSlug: k,
1077
- pageId: C,
1078
- // default locale
1079
- defaultLocale: I?.[0],
1080
- locales: I,
1081
- publishedAt: d.config.publishedAt,
1082
- isPublic: w.isPublic,
1083
- templateConfig: w.templateConfig
1084
- };
1085
- R(k, S);
1086
- }
1087
- o = { ...o, ...h };
1088
- })
1089
- )
1090
- );
1091
- }
1092
- }
1093
- return u.info("[SiteState] success get pageUrlMap"), o;
1094
- }
1095
- getDocumentSize() {
1096
- return F.encodeStateAsUpdate(this).byteLength;
1097
- }
1098
- static getInstancesSizeInfo() {
1099
- const e = [];
1100
- for (const [s, a] of Object.entries(D.sharedInstances)) {
1101
- const o = a.getDocumentSize();
1102
- e.push({
1103
- projectId: s,
1104
- sizeInBytes: o,
1105
- sizeInMB: `${(o / (1024 * 1024)).toFixed(2)} MB`,
1106
- activeConnections: a.conns.size
1107
- });
1108
- }
1109
- return e;
1110
- }
1111
- // 启动定期检查
1112
- static startPeriodicCheck() {
1113
- this.periodicCheckTimer || (this.periodicCheckTimer = setInterval(() => {
1114
- this.performPeriodicCheck();
1115
- }, this.PERIODIC_CHECK_INTERVAL), u.info(
1116
- `[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL / (60 * 60 * 1e3)} hours`
1117
- ));
1118
- }
1119
- // 停止定期检查
1120
- static stopPeriodicCheck() {
1121
- this.periodicCheckTimer && (clearInterval(this.periodicCheckTimer), this.periodicCheckTimer = void 0, u.info("[SiteState] periodic check stopped"));
1122
- }
1123
- // 执行定期检查
1124
- static performPeriodicCheck() {
1125
- const e = Object.keys(D.sharedInstances).length, s = [], a = [];
1126
- for (const [o, n] of Object.entries(D.sharedInstances))
1127
- n.conns.size === 0 ? s.push({ projectId: o, instance: n }) : a.push({ projectId: o, connections: n.conns.size });
1128
- if (u.info(
1129
- `[SiteState] periodic check summary: total instances: ${e}, with connections: ${a.length}, without connections: ${s.length}`
1130
- ), s.length > 0) {
1131
- u.info(
1132
- `[SiteState] releasing ${s.length} instances without connections:`,
1133
- s.map((n) => n.projectId)
1134
- );
1135
- let o = 0;
1136
- for (const { projectId: n, instance: l } of s)
1137
- try {
1138
- u.info(`[SiteState] releasing instance due to periodic check: ${n}`), l.destroy(), o++;
1139
- } catch (r) {
1140
- u.error(`[SiteState] failed to release instance ${n} during periodic check:`, r);
1141
- }
1142
- u.info(
1143
- `[SiteState] periodic check completed: ${o}/${s.length} instances released successfully`
1144
- );
1145
- } else e > 0 ? u.debug("[SiteState] periodic check: all instances have active connections") : u.debug("[SiteState] periodic check: no instances exist");
1146
- }
1147
- }
1148
- async function ps(t, e, s) {
1149
- if (!t || !await B(t) || !(await se(t)).isFile())
1150
- return null;
1151
- let o = s[t];
1152
- return o || (o = (async () => {
1153
- try {
1154
- return (await os({
1155
- filePath: t,
1156
- fileName: e
1157
- }))?.data?.filename;
1158
- } catch (n) {
1159
- return u.error(`Failed to upload asset ${t}:`, n), null;
1160
- }
1161
- })(), s[t] = o), o;
1162
- }
1163
- const us = async (t, e) => {
1164
- const s = N(t), a = await Ct({
1165
- name: Ye,
1166
- path: G("/uploads", s),
1167
- responseType: "stream",
1168
- method: "GET"
1169
- });
1170
- if (a.status >= 200 && a.status < 400) {
1171
- const o = Pt(e);
1172
- await Tt(a.data, o);
1173
- } else
1174
- throw new Error(`download asset failed ${a.status}`);
1175
- }, ds = async (t, e) => {
1176
- await Promise.all(
1177
- t.map(async (s) => {
1178
- try {
1179
- await us(s, A(e, N(s)));
1180
- } catch (a) {
1181
- u.error(`Failed to export assets: ${s}, ${a}`);
1182
- }
1183
- })
1184
- );
1185
- };
1186
- function et(t) {
1187
- return ve.test(t) ? [t] : X.test(t) ? (Ve.lastIndex = 0, Array.from(t.matchAll(Ve)).map((s) => s[1]).filter((s) => !!s)) : [];
1188
- }
1189
- async function te(t, e, s) {
1190
- const { getFilename: a, exportAssets: o } = s, n = A(e, a(t));
1191
- if (await x(M(n), { recursive: !0 }), await oe(n, q.stringify(t)), o) {
1192
- const r = re(
1193
- t,
1194
- (i) => typeof i == "string" && (ve.test(i) || X.test(i))
1195
- ).map((i) => {
1196
- const m = je(t, i);
1197
- return et(m);
1198
- }).flat().filter(Boolean);
1199
- await ds(r, M(n));
1200
- }
1201
- }
1202
- const Ie = new We({
1203
- max: 100,
1204
- ttl: 1 * 60 * 1e3
1205
- // 1 minute
1206
- });
1207
- async function ze(t, e, s) {
1208
- const a = re(
1209
- t,
1210
- (r) => typeof r == "string" && (ve.test(r) || X.test(r))
1211
- ), o = Ce(2), n = a.map(
1212
- (r) => o(async () => {
1213
- try {
1214
- const i = je(t, r), m = et(i);
1215
- for (const b of m) {
1216
- const O = N(b), p = s.getFilePath(b, r), h = p ? `${p}:${O}` : O, d = Ie.get(h);
1217
- if (d) {
1218
- X.test(i) || Me(t, r, d);
1219
- return;
1220
- }
1221
- const I = await ps(p, O, e);
1222
- I && (X.test(i) || Me(t, r, I), Ie.set(h, I));
1223
- }
1224
- } catch (i) {
1225
- u.error(`Failed to process upload for path ${r.join(".")}:`, i.message || i.reason);
1226
- }
1227
- })
1228
- ), l = await Promise.allSettled(n);
1229
- s.onFinish?.(l);
1230
- }
1231
- async function fs(t, {
1232
- exportAssets: e,
1233
- pageIds: s = "all",
1234
- componentIds: a = "all",
1235
- rawConfig: o,
1236
- includeResources: n = !1,
1237
- routeIds: l = "all"
1238
- } = {}) {
1239
- const r = s === "all" ? t.pageIds : s, i = At({
1240
- state: t,
1241
- pageIds: r,
1242
- componentIds: a === "all" ? Object.keys(t.components) : a
1243
- });
1244
- Object.entries(t.components).forEach(([c, f]) => {
1245
- f.data?.renderer?.type === "component-template" && i.push(c);
1246
- });
1247
- const m = l === "all" ? t.routeIds : l, b = (c) => ({
1248
- id: c.id,
1249
- name: c.name,
1250
- isTemplateSection: c.isTemplateSection ?? !1,
1251
- templateDescription: c.templateDescription,
1252
- /** @deprecated 已经废弃,llmConfig 从 component / resources.component 中获取 */
1253
- // llmConfig: section.llmConfig,
1254
- component: c.component,
1255
- config: c.config,
1256
- visibility: c.visibility,
1257
- sections: c?.sectionIds ? L(
1258
- c?.sectionIds?.map((f) => {
1259
- const g = c.sections?.[f];
1260
- return g && b(g);
1261
- })
1262
- ) : void 0
1263
- /** @deprecated 已经废弃,数据在 page.dataSource 中管理 */
1264
- // properties: section.locales?.[locale] ?? {},
1265
- }), O = (c, f) => ({
1266
- id: c.id,
1267
- createdAt: c.createdAt,
1268
- updatedAt: c.updatedAt,
1269
- publishedAt: c.publishedAt,
1270
- isPublic: c.isPublic ?? !0,
1271
- templateConfig: c.templateConfig,
1272
- meta: c.locales?.[f] ?? {},
1273
- sections: L(
1274
- c.sectionIds.map((g) => {
1275
- const j = c.sections[g];
1276
- return j && b(j);
1277
- })
1278
- ),
1279
- // 将 dataSource.sectionId.locale 转换为 dataSource.sectionId
1280
- dataSource: Object.fromEntries(
1281
- Object.entries(c.dataSource || {}).map(([g, j]) => [g, j?.[f] ?? {}])
1282
- )
1283
- }), p = (c) => ({
1284
- id: c.id,
1285
- createdAt: c.createdAt,
1286
- updatedAt: c.updatedAt,
1287
- publishedAt: c.publishedAt,
1288
- path: c.path,
1289
- handler: c.handler,
1290
- isPublic: c.isPublic ?? !0,
1291
- params: c.params ?? [],
1292
- enabledGenerate: c.enabledGenerate ?? !1,
1293
- displayTemplateId: c.displayTemplateId,
1294
- dataSource: c.dataSource
1295
- }), h = L(
1296
- m.map((c) => {
1297
- const f = t.routes[c];
1298
- return f && p(f);
1299
- })
1300
- ), d = L(
1301
- t.supportedLocales.map((c) => c.locale).flatMap(
1302
- (c) => r.map((f) => {
1303
- const g = t.pages[f];
1304
- return g && {
1305
- locale: c,
1306
- slug: g.slug,
1307
- page: O(g, c)
1308
- };
1309
- })
1310
- )
1311
- ), I = Ze(), R = A(I, "pages");
1312
- await x(R, { recursive: !0 });
1313
- const C = A(I, "components");
1314
- await x(C, { recursive: !0 });
1315
- const w = A(I, "routes");
1316
- await x(w, { recursive: !0 });
1317
- for (const { locale: c, slug: f, page: g } of d)
1318
- await te(g, R, {
1319
- getFilename: () => `${ie(f) || "index"}.${c}.yml`,
1320
- exportAssets: e
1321
- });
1322
- for (const c of h)
1323
- await te(c, w, {
1324
- // getFilename: () => `${sanitizeSlug(route.path)}.yml`,
1325
- getFilename: () => `${ie(c.path) || "index"}.yml`,
1326
- exportAssets: e
1327
- });
1328
- for (const c of i) {
1329
- const f = t.components[c]?.data;
1330
- f && await te(f, C, {
1331
- getFilename: (g) => `${g.name || "unnamed"}.${g.id}.yml`,
1332
- exportAssets: e
1333
- });
1334
- }
1335
- const k = A(I, ".blocklet/pages/pages.config.yml");
1336
- await x(M(k), { recursive: !0 });
1337
- const y = {
1338
- pages: L(
1339
- r.map((c) => {
1340
- const f = t.pages[c];
1341
- return f && { id: c, slug: f.slug };
1342
- })
1343
- ),
1344
- routes: L(
1345
- m.map((c) => {
1346
- const f = t.routes[c];
1347
- return f && { id: c, path: f.path };
1348
- })
1349
- ),
1350
- components: L(
1351
- i.map((c) => {
1352
- const f = t.components[c]?.data;
1353
- return f && {
1354
- id: c,
1355
- name: f.name
1356
- };
1357
- })
1358
- ),
1359
- ...n ? {
1360
- resources: {
1361
- components: L(
1362
- Object.keys(t.resources?.components || {}).filter((c) => i.includes(c)).map((c) => ({
1363
- id: c,
1364
- name: t.resources?.components?.[c]?.component?.name
1365
- }))
1366
- )
1367
- }
1368
- } : {},
1369
- supportedLocales: t.supportedLocales,
1370
- config: t.config
1371
- };
1372
- await oe(k, q.stringify(y));
1373
- const S = A(I, "config.source.json");
1374
- if (o && await oe(S, JSON.stringify(o)), n) {
1375
- const c = A(I, "resources"), f = A(c, "components");
1376
- await x(f, { recursive: !0 });
1377
- for (const U of Object.keys(t?.resources?.components ?? {}).filter(
1378
- (T) => i.includes(T)
1379
- )) {
1380
- const T = t.resources?.components?.[U]?.component;
1381
- T && await te(T, f, {
1382
- getFilename: (V) => `${V.name || "unnamed"}.${V.id}.yml`,
1383
- exportAssets: e
1384
- });
1385
- }
1386
- const g = A(I, "chunks");
1387
- await x(g, { recursive: !0 });
1388
- const j = await ms();
1389
- for (const U of Object.keys(t?.resources?.components ?? {}).filter(
1390
- (T) => i.includes(T)
1391
- )) {
1392
- const T = t.resources?.components?.[U]?.component;
1393
- if (T && T.renderer?.type === "react-component") {
1394
- const V = T.renderer?.chunks ?? [];
1395
- if (V?.length > 0)
1396
- for (const H of V) {
1397
- const Te = A(g, H), ue = j?.[H];
1398
- try {
1399
- ue && await B(ue) && !await B(Te) && await jt(ue, Te);
1400
- } catch (ct) {
1401
- u.error(`copy chunk ${H} error`, ct.message);
1402
- }
1403
- }
1404
- }
1405
- }
1406
- }
1407
- return I;
1408
- }
1409
- async function tt(t, { importAssets: e, includeResources: s } = {}) {
1410
- if (!await B(t))
1411
- return null;
1412
- let a, o = !1;
1413
- try {
1414
- (await se(t)).isDirectory() ? a = t : /\.(tgz|gz|tar)$/.test(t) && (o = !0, a = Ze(), await Lt({ file: t, C: a }));
1415
- const r = (await he("**/.blocklet/pages/pages.config.yml", { cwd: a, absolute: !0 }))[0], i = r && A(M(r), "../../pages"), m = r && A(M(r), "../../components"), b = r && A(M(r), "../../routes");
1416
- if (!r)
1417
- return null;
1418
- const O = await Z(r, "utf-8"), p = q.parse(O), h = async (y, S, c) => {
1419
- let f = A(y, `${S}${c ? `.${c}` : ""}.yml`);
1420
- if (!await B(f) && (f = A(y, S, `index${c ? `.${c}` : ""}.yml`), !await B(f)) || !(await se(f)).isFile())
1421
- return null;
1422
- const j = await Z(f, "utf-8");
1423
- return q.parse(j);
1424
- }, d = async (y, S) => {
1425
- try {
1426
- const f = (await he(`*.${S}.yml`, { cwd: y, absolute: !0 }))[0];
1427
- if (!f) return null;
1428
- const g = await Z(f, "utf-8");
1429
- return q.parse(g);
1430
- } catch (c) {
1431
- u.error("parse component error", c);
1432
- }
1433
- return null;
1434
- }, I = async (y, S) => {
1435
- let c = A(y, `${S}.yml`);
1436
- if (!await B(c) && (c = A(y, S, "index.yml"), !await B(c)) || !(await se(c)).isFile())
1437
- return null;
1438
- const g = await Z(c, "utf-8");
1439
- return q.parse(g);
1440
- }, R = L(
1441
- await Promise.all(
1442
- p.pages.map(async ({ slug: y }) => {
1443
- const S = L(
1444
- await Promise.all(
1445
- p.supportedLocales.map(async ({ locale: g }) => {
1446
- const j = i ? await h(i, ie(y), g) : void 0;
1447
- if (j)
1448
- return { locale: g, page: j };
1449
- const U = i ? await h(i, y, g) : void 0;
1450
- return U && { locale: g, page: U };
1451
- })
1452
- )
1453
- ), c = S[0]?.page;
1454
- if (!c)
1455
- return null;
1456
- const f = c.sections.map(bt);
1457
- return {
1458
- id: c.id || $e(),
1459
- createdAt: c.createdAt,
1460
- updatedAt: c.updatedAt,
1461
- publishedAt: c.publishedAt,
1462
- isPublic: c.isPublic ?? !0,
1463
- templateConfig: c.templateConfig,
1464
- slug: y,
1465
- sections: Object.fromEntries(f.map((g) => [g.id, g])),
1466
- sectionIds: f.map((g) => g.id),
1467
- locales: Object.fromEntries(S.map(({ locale: g, page: j }) => [g, j.meta])),
1468
- dataSource: c.dataSource ? Object.fromEntries(
1469
- // 获取 dataSource 中所有 section ID
1470
- [...new Set(S.flatMap(({ page: g }) => Object.keys(g.dataSource ?? {})))].map((g) => [
1471
- g,
1472
- Object.fromEntries(
1473
- S.map(({ locale: j, page: U }) => {
1474
- const T = U.dataSource?.[g];
1475
- return [j, T || {}];
1476
- })
1477
- )
1478
- ])
1479
- ) : Object.fromEntries(
1480
- // 获取所有 section ID
1481
- [...new Set(S.flatMap(({ page: g }) => g.sections.map((j) => j.id)))].map((g) => [
1482
- g,
1483
- Object.fromEntries(
1484
- S.map(({ locale: j, page: U }) => {
1485
- const T = U.dataSource?.[g];
1486
- if (T)
1487
- return [j, T];
1488
- const V = U.sections.find((H) => H.id === g);
1489
- return [j, V?.properties || {}];
1490
- })
1491
- )
1492
- ])
1493
- )
1494
- };
1495
- })
1496
- )
1497
- ), C = L(
1498
- await Promise.all(
1499
- (p?.routes || []).map(async ({ path: y }) => {
1500
- const S = b ? await I(b, ie(y)) : void 0;
1501
- return {
1502
- ...S,
1503
- id: S?.id || $e(),
1504
- createdAt: S?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1505
- updatedAt: S?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1506
- publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
1507
- path: S?.path ?? `/${S?.id}`,
1508
- params: S?.params,
1509
- handler: S?.handler ?? "Pages Kit",
1510
- isPublic: S?.isPublic ?? !0,
1511
- enabledGenerate: S?.enabledGenerate ?? !1,
1512
- displayTemplateId: S?.displayTemplateId ?? void 0,
1513
- dataSource: S?.dataSource ?? {}
1514
- };
1515
- })
1516
- )
1517
- ), w = m ? L(
1518
- await Promise.all((p.components || []).map(async ({ id: y }) => d(m, y)))
1519
- ) : [];
1520
- if (e) {
1521
- const y = (...S) => {
1522
- u.info(`[${o ? N(t) : N(A(t, "../../../../"))}] importAssets:`, ...S);
1523
- };
1524
- try {
1525
- y("wait image-bin api ready"), await Nt({
1526
- resources: [`${Et(ut)}/api/sdk/uploads`],
1527
- validateStatus: (f) => f >= 200 && f <= 500
1528
- }), y("image-bin api is ready");
1529
- const S = {}, c = {};
1530
- y("start to upload assets"), await Promise.allSettled([
1531
- ze(w, S, {
1532
- getFilePath: (f) => m && A(m, f),
1533
- onFinish: (f) => {
1534
- y(`upload ${f.length} component assets`);
1535
- }
1536
- }),
1537
- ze(R, c, {
1538
- getFilePath: (f, g) => {
1539
- const j = je(R, g.slice(0, 1));
1540
- return i && A(i, M(j.slug), f);
1541
- },
1542
- onFinish: (f) => {
1543
- y(`upload ${f.length} page assets`);
1544
- }
1545
- })
1546
- ]), y("upload assets done"), Ie.clear(), global.gc && global.gc();
1547
- } catch (S) {
1548
- y("Error during asset import:", S);
1549
- }
1550
- }
1551
- const k = {};
1552
- if (s) {
1553
- const y = r && A(M(r), "../../resources/components"), S = L(
1554
- await Promise.all(
1555
- (p.resources?.components || []).map(async ({ id: c }) => d(y, c))
1556
- )
1557
- );
1558
- S.length > 0 && (k.components = Object.fromEntries(
1559
- S.map((c, f) => [c.id, { index: f, component: c }])
1560
- ));
1561
- }
1562
- return {
1563
- supportedLocales: p.supportedLocales,
1564
- pageIds: R.map((y) => y.id),
1565
- components: Object.fromEntries(w.map((y, S) => [y.id, { index: S, data: y }])),
1566
- pages: Object.fromEntries(R.map((y) => [y.id, y])),
1567
- config: p.config || {},
1568
- resources: k,
1569
- routeIds: C.map((y) => y.id),
1570
- routes: Object.fromEntries(C.map((y) => [y.id, y])),
1571
- dataSourceIds: [],
1572
- dataSources: {}
1573
- };
1574
- } finally {
1575
- o && a && await Ke(a, { force: !0, recursive: !0 });
1576
- }
1577
- }
1578
- async function qe(t, e, {
1579
- routes: s,
1580
- mergeMode: a = "byUpdateTime",
1581
- deleteRoutes: o = !1,
1582
- publishMode: n = void 0
1583
- } = {}) {
1584
- try {
1585
- n && dt(n);
1586
- } catch (p) {
1587
- u.error("clear preload page cache error", { error: p });
1588
- }
1589
- const { pages: l, pageIds: r, routeIds: i, routes: m, supportedLocales: b } = t;
1590
- if (n === "production") {
1591
- let p = s ?? [], h = null;
1592
- for (const d of i ?? []) {
1593
- const I = m?.[d];
1594
- if (I?.params && I?.params.length > 0 && I?.paramsOptions && I?.paramsOptions.length > 0) {
1595
- const R = Pe({
1596
- basePath: I.path,
1597
- params: I.params,
1598
- routeId: I.id,
1599
- paramsOptions: I.paramsOptions,
1600
- currentIndex: 0,
1601
- currentParams: [],
1602
- currentOptionIds: [],
1603
- result: []
1604
- }), C = Object.fromEntries(R.map((w) => [`${d}-${w.paramOptionIds.join("-")}`, w]));
1605
- h = { ...h || {}, ...C }, s || (p = [...p, ...R.map((w) => `${d}-${w.paramOptionIds.join("-")}`)]);
1606
- } else s || p.push(d);
1607
- }
1608
- u.info("routeIds to be published: ", p);
1609
- for (const d of p) {
1610
- let I = d;
1611
- if (I.includes("-")) {
1612
- const [w] = I.split("-");
1613
- I = w;
1614
- }
1615
- const R = m?.[I];
1616
- if (!R) {
1617
- const w = e.pageIds.indexOf(I);
1618
- w !== -1 && o && (e.pageIds.splice(w, 1), delete e.pages[I]);
1619
- for (const k of e.pageIds)
1620
- k.includes(`${I}-`) && (e.pageIds.splice(e.pageIds.indexOf(k), 1), delete e.pages[k]);
1621
- u.info("delete main route page", I);
1622
- continue;
1623
- }
1624
- if (d.includes("-") && !h?.[d]) {
1625
- const w = e.pageIds.indexOf(d);
1626
- w !== -1 && o && (e.pageIds.splice(w, 1), delete e.pages[d]), u.info("delete page", d);
1627
- continue;
1628
- }
1629
- if (!R.displayTemplateId) {
1630
- u.info("no display template", d);
1631
- continue;
1632
- }
1633
- const C = l[R.displayTemplateId];
1634
- if (!C) {
1635
- u.info("no template page", d);
1636
- continue;
1637
- }
1638
- if (e.pageIds.includes(d)) {
1639
- if (u.info("has need update page", d), a === "replace")
1640
- e.pages[d] = fe({
1641
- page: C,
1642
- route: R,
1643
- state: t,
1644
- routeId: d,
1645
- routePathInfo: h?.[d]
1646
- }), u.info("replace page", d);
1647
- else if (a === "byUpdateTime") {
1648
- const w = e.pages[R.id];
1649
- (!w || R.updatedAt && R.updatedAt > w.updatedAt) && (e.pages[d] = fe({
1650
- page: C,
1651
- route: R,
1652
- state: t,
1653
- routeId: d,
1654
- routePathInfo: h?.[d]
1655
- }), u.info("replace page by update time", d));
1656
- }
1657
- } else
1658
- e.pageIds.push(d), e.pages[d] = fe({
1659
- page: C,
1660
- route: R,
1661
- state: t,
1662
- routeId: d,
1663
- routePathInfo: h?.[d]
1664
- }), u.info("add page", d);
1665
- }
1666
- if (o && !s)
1667
- for (const d of e.pageIds)
1668
- p?.includes(d) || (delete e.pages[d], u.info("delete page", d)), e.pageIds = [...e.pageIds].filter((I) => p?.includes(I));
1669
- } else {
1670
- for (const p of r) {
1671
- const h = l[p];
1672
- if (h)
1673
- if (e.pageIds.includes(h.id)) {
1674
- if (a === "replace")
1675
- e.pages[h.id] = h;
1676
- else if (a === "byUpdateTime") {
1677
- const d = e.pages[h.id];
1678
- (!d || h.updatedAt && h.updatedAt > d.updatedAt) && (e.pages[h.id] = h);
1679
- }
1680
- } else
1681
- e.pageIds.push(h.id), e.pages[h.id] = h;
1682
- }
1683
- for (const p of i) {
1684
- const h = m[p];
1685
- if (h)
1686
- if (e.routeIds.includes(h.id)) {
1687
- if (a === "replace")
1688
- e.routes[h.id] = h;
1689
- else if (a === "byUpdateTime") {
1690
- const d = e.routes[h.id];
1691
- (!d || h.updatedAt && h.updatedAt > d.updatedAt) && (e.routes[h.id] = h);
1692
- }
1693
- } else
1694
- e.routeIds.push(h.id), e.routes[h.id] = h;
1695
- }
1696
- }
1697
- if (e.supportedLocales.splice(0, e.supportedLocales.length), e.supportedLocales.push(...be(b)), o)
1698
- for (const p of Object.keys(e.components))
1699
- delete e.components[p];
1700
- let O = JSON.parse(JSON.stringify(t.components));
1701
- O = Object.fromEntries(
1702
- await Promise.all(
1703
- Object.entries(O).map(async ([p, h]) => {
1704
- const d = await st(h?.data);
1705
- return [
1706
- p,
1707
- {
1708
- ...h,
1709
- data: d
1710
- }
1711
- ];
1712
- })
1713
- )
1714
- ), Object.assign(e.components, O), Object.assign(e.config, JSON.parse(JSON.stringify(t.config))), De(t.resources.components) || (e.resources.components = JSON.parse(JSON.stringify(t.resources.components || {})));
1715
- }
1716
- const st = lt(
1717
- async (t) => {
1718
- if (!De(t?.properties))
1719
- return t;
1720
- if (t?.renderer?.type === "react-component") {
1721
- const { script: e, PROPERTIES_SCHEMA: s } = t?.renderer || {};
1722
- if (s || e && e.includes("PROPERTIES_SCHEMA"))
1723
- try {
1724
- const a = await pt(
1725
- e ?? "",
1726
- "PROPERTIES_SCHEMA",
1727
- t.id,
1728
- s
1729
- );
1730
- a && a.length > 0 && t && (t.properties = {}, a.forEach((o, n) => {
1731
- t?.properties && (t.properties[o.id] = {
1732
- index: n,
1733
- data: o
1734
- });
1735
- }));
1736
- } catch (a) {
1737
- u.error("getPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: a });
1738
- }
1739
- }
1740
- return t;
1741
- },
1742
- {
1743
- subdir: "getPropertiesFromCode"
1744
- }
1745
- );
1746
- let ce, Q, le, pe;
1747
- const at = () => Ot({
1748
- types: [
1749
- { did: Ye, type: xe },
1750
- { did: zt, type: xe }
1751
- ]
1752
- }), ms = async () => {
1753
- const t = at(), e = {};
1754
- for (const s of t) {
1755
- const o = (await he("**/.blocklet/pages/pages.config.yml", {
1756
- cwd: s.path,
1757
- absolute: !0
1758
- }))[0], n = o && A(M(o), "../../chunks");
1759
- if (n && await B(n)) {
1760
- const l = await Dt(n);
1761
- for (const r of l)
1762
- e[r] = A(n, r);
1763
- }
1764
- }
1765
- return e;
1766
- };
1767
- function ot() {
1768
- return ce = (async () => {
1769
- const t = at();
1770
- Q = (await Promise.all(
1771
- t.map(async (s) => {
1772
- const a = s.path ? await tt(s.path, { importAssets: !1 }) : void 0;
1773
- return a ? { blockletId: s.did, state: a, blockletTitle: s.title } : void 0;
1774
- })
1775
- )).filter((s) => !!s), le = Q.reduce(
1776
- (s, a) => Object.assign(
1777
- s,
1778
- Object.fromEntries(
1779
- Object.values(a.state.pages).map((o) => o ? [o?.id, { page: o, blockletId: a.blockletId }] : [])
1780
- )
1781
- ),
1782
- {}
1783
- );
1784
- const e = Q.reduce(
1785
- (s, a) => Object.assign(
1786
- s,
1787
- Object.fromEntries(
1788
- Object.values(a.state.components).map((o) => [o.data.id, { blockletId: a.blockletId, component: o.data }])
1789
- )
1790
- ),
1791
- {}
1792
- );
1793
- pe = Object.fromEntries(
1794
- await Promise.all(
1795
- Object.entries(e).map(async ([s, a]) => {
1796
- const o = await st(a.component);
1797
- return [
1798
- s,
1799
- {
1800
- ...a,
1801
- component: o
1802
- }
1803
- ];
1804
- })
1805
- )
1806
- );
1807
- })(), ce;
1808
- }
1809
- function gs(t) {
1810
- const e = Re(
1811
- async () => {
1812
- await ot().catch((s) => {
1813
- u.error("load resource states error", { error: s });
1814
- }), await t?.({
1815
- states: Q,
1816
- pages: le,
1817
- components: pe
1818
- });
1819
- },
1820
- 3e3,
1821
- // 3s
1822
- { leading: !1, trailing: !0 }
1823
- );
1824
- 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(Se, e), () => {
1825
- 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(Se, e);
1826
- };
1827
- }
1828
- const nt = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), rt = globalThis;
1829
- rt[nt]?.();
1830
- rt[nt] = gs(async ({ pages: t, components: e }) => {
1831
- const s = await D.getProjectIds();
1832
- u.info(`start update resource states projects(${s.length})`, s);
1833
- const a = Ce(10);
1834
- await Promise.race([
1835
- new Promise((o) => {
1836
- setTimeout(() => {
1837
- o({});
1838
- }, 30 * 1e3);
1839
- }),
1840
- Promise.all(
1841
- s.map(
1842
- (o) => a(async () => {
1843
- it({
1844
- projectId: o,
1845
- pages: t,
1846
- components: e
1847
- });
1848
- })
1849
- )
1850
- )
1851
- ]).catch((o) => {
1852
- u.error("update resource states failed:", o);
1853
- });
1854
- });
1855
- D.startPeriodicCheck();
1856
- process.on("beforeExit", () => {
1857
- D.stopPeriodicCheck();
1858
- });
1859
- process.on("SIGINT", () => {
1860
- D.stopPeriodicCheck(), process.exit(0);
1861
- });
1862
- process.on("SIGTERM", () => {
1863
- D.stopPeriodicCheck(), process.exit(0);
1864
- });
1865
- async function it({
1866
- projectId: t,
1867
- pages: e,
1868
- components: s
1869
- }) {
1870
- const a = D.sharedInstances[t];
1871
- if (!a) {
1872
- u.info(`projectId: ${t} not found in sharedInstances`);
1873
- return;
1874
- }
1875
- const o = a.syncedStore.resources.pages, n = a.syncedStore.resources.components, l = await $.findByPk(t, {
1876
- attributes: { exclude: ["productionState", "relatedBlocklets"] }
1877
- });
1878
- let r;
1879
- if (l?.useAllResources)
1880
- r = s;
1881
- else {
1882
- const O = (await ke.findAll({ where: { projectId: t } })).map((p) => p.componentId);
1883
- r = Object.fromEntries(Object.entries(s || {}).filter(([p]) => O.includes(p)));
1884
- }
1885
- const i = !Ge(o, e), m = !Ge(n, r);
1886
- i || m ? a.transact(() => {
1887
- i && (a.syncedStore.resources.pages = e, u.info(`[${t}] pages resources updated: ${Object.keys(e || {}).length} pages`)), m && (a.syncedStore.resources.components = r, u.info(
1888
- `[${t}] components resources updated: ${Object.keys(r || {}).length} components`
1889
- ));
1890
- }) : u.info(`[${t}] resource states unchanged, skipping update`), u.info(`update [${t}] resource states summary:`, {
1891
- pages: Object.keys(a.syncedStore.resources.pages || {}).length,
1892
- components: Object.keys(a.syncedStore.resources.components || {}).length,
1893
- pagesChanged: i,
1894
- componentsChanged: m
1895
- });
1896
- }
1897
- const ge = /* @__PURE__ */ new Map();
1898
- async function hs(t) {
1899
- if (!ge.has(t)) {
1900
- const e = Re(async (s) => it({
1901
- projectId: s,
1902
- pages: le,
1903
- components: pe
1904
- }), 3e3);
1905
- ge.set(t, e);
1906
- }
1907
- return ge.get(t)(t);
1908
- }
1909
- async function ea() {
1910
- u.info("trigger reload all project resource"), E.events.emit(Se);
1911
- }
1912
- async function ta({
1913
- ensureLoaded: t = !0
1914
- } = {}) {
1915
- return t && (ce ??= ot(), await ce), { states: Q, pages: le, components: pe };
1916
- }
1917
- export {
1918
- Ye as C,
1919
- $ as P,
1920
- xe as R,
1921
- D as S,
1922
- W as a,
1923
- Qs as b,
1924
- Xs as c,
1925
- Zs as d,
1926
- ls as e,
1927
- us as f,
1928
- ta as g,
1929
- ds as h,
1930
- tt as i,
1931
- gs as j,
1932
- ea as k,
1933
- qe as m,
1934
- fs as t,
1935
- hs as u
1936
- };