@blocklet/pages-kit-inner-components 0.1.3 → 0.1.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,966 @@
1
+ import { l as D, c as Me, g as $e } from "./components-k4kCJg_V.js";
2
+ import { memoize as Be } from "@blocklet/quickjs";
3
+ import { getComponentWebEndpoint as xe, getResources as Ve, call as Ge } from "@blocklet/sdk/lib/component";
4
+ import h from "@blocklet/sdk/lib/config";
5
+ import { reactive as Je } from "@reactivedata/reactive";
6
+ import { syncedStore as qe, getYjsValue as se } from "@syncedstore/core";
7
+ import { mkdirSync as R, writeFileSync as X, existsSync as $, readFileSync as x, renameSync as me, rmSync as Te, lstatSync as Y, readdirSync as ze, mkdtempSync as Ke, createWriteStream as He } from "fs";
8
+ import { globSync as ae } from "glob";
9
+ import * as ne from "lib0/decoding";
10
+ import * as v from "lib0/encoding";
11
+ import { debounce as Oe, pick as Ye, union as We, get as le, cloneDeep as Xe, isEmpty as Qe, set as ge } from "lodash";
12
+ import { LRUCache as Pe } from "lru-cache";
13
+ import { customAlphabet as Ze } from "nanoid";
14
+ import et from "p-limit";
15
+ import tt, { join as A, dirname as k, basename as B } from "path";
16
+ import { pipeline as st } from "stream/promises";
17
+ import { x as nt } from "tar";
18
+ import { joinURL as V } from "ufo";
19
+ import rt from "wait-on";
20
+ import { encodeAwarenessUpdate as he, removeAwarenessStates as ot, applyAwarenessUpdate as at, Awareness as it } from "y-protocols/awareness";
21
+ import { writeUpdate as ct, writeSyncStep1 as lt, readSyncMessage as pt } from "y-protocols/sync";
22
+ import * as G from "yaml";
23
+ import * as M from "yjs";
24
+ import dt from "lodash/isNil";
25
+ import { DataTypes as b, Sequelize as ut, Model as De, Op as ft } from "sequelize";
26
+ import "sqlite3";
27
+ h.env.mode;
28
+ const mt = "image-bin";
29
+ h.env.INIT_TEMPLATE_PATH;
30
+ const gt = process.env.DATABASE_URL || tt.join(h.env.dataDir, "db/pages-kit.db"), ye = h, es = () => h.env.tenantMode === "multiple", ts = () => {
31
+ var t;
32
+ return (dt(ye.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = ye.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
33
+ }, ht = b.sqlite.DATE.parse;
34
+ b.sqlite.DATE.parse = (t, s) => typeof t == "number" ? new Date(t) : ht(t, s);
35
+ const z = new ut({
36
+ dialect: "sqlite",
37
+ storage: gt,
38
+ benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
39
+ retry: {
40
+ match: [/SQLITE_BUSY/],
41
+ name: "query",
42
+ max: 10
43
+ },
44
+ // eslint-disable-next-line no-console
45
+ logging: process.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
46
+ // logQueryParameters: true,
47
+ });
48
+ z.query("pragma journal_mode = WAL;");
49
+ z.query("pragma synchronous = normal;");
50
+ z.query("pragma journal_size_limit = 67108864;");
51
+ class te extends De {
52
+ // Foreign key to Component
53
+ }
54
+ te.init(
55
+ {
56
+ id: {
57
+ type: b.UUID,
58
+ allowNull: !1,
59
+ primaryKey: !0,
60
+ defaultValue: b.UUIDV4
61
+ },
62
+ projectId: {
63
+ type: b.UUID,
64
+ allowNull: !1
65
+ },
66
+ componentId: {
67
+ type: b.STRING,
68
+ allowNull: !1
69
+ }
70
+ },
71
+ { sequelize: z, tableName: "ProjectComponents", timestamps: !1 }
72
+ );
73
+ class F extends De {
74
+ static async getProjectByIdOrSlug(s) {
75
+ return F.findOne({
76
+ where: {
77
+ [ft.or]: [{ id: s }, { slug: s }]
78
+ }
79
+ });
80
+ }
81
+ }
82
+ F.init(
83
+ {
84
+ id: {
85
+ type: b.UUID,
86
+ defaultValue: b.UUIDV4,
87
+ primaryKey: !0
88
+ },
89
+ name: {
90
+ type: b.STRING,
91
+ allowNull: !1
92
+ },
93
+ description: b.TEXT,
94
+ createdAt: b.DATE,
95
+ updatedAt: b.DATE,
96
+ createdBy: {
97
+ type: b.STRING,
98
+ allowNull: !1
99
+ },
100
+ updatedBy: {
101
+ type: b.STRING,
102
+ allowNull: !1
103
+ },
104
+ slug: b.STRING,
105
+ icon: b.STRING,
106
+ pinnedAt: b.DATE,
107
+ useAllResources: b.BOOLEAN,
108
+ relatedBlocklets: {
109
+ type: b.JSON,
110
+ allowNull: !1,
111
+ defaultValue: {},
112
+ get() {
113
+ return this.getDataValue("relatedBlocklets") || {};
114
+ },
115
+ set(t) {
116
+ this.setDataValue("relatedBlocklets", JSON.stringify(t || {}));
117
+ }
118
+ }
119
+ },
120
+ { sequelize: z, paranoid: !0 }
121
+ );
122
+ F.hasMany(te, {
123
+ foreignKey: "projectId",
124
+ as: "components"
125
+ });
126
+ const yt = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", Se = "page", ie = "trigger-reload-project-resource", je = yt, St = "z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV", { uploadToMediaKit: wt } = require("@blocklet/uploader-server"), we = Ze("abcdefghijklmnopqrstuvwxyz0123456789", 16), pe = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, J = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Ee = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, Et = 1e4, At = 3e4, K = 0, re = 1, bt = 0, vt = 1, ce = h, H = A(process.env.BLOCKLET_DATA_DIR, "site-state"), ss = ["production", "draft"], ns = ["production"];
127
+ function ke(t) {
128
+ return (t == null ? void 0 : t.replace(/\//g, "|")) || "";
129
+ }
130
+ function It() {
131
+ var e;
132
+ const t = ce.env.languages.map((n) => ({ locale: n.code, name: n.name })), s = (e = t[0]) == null ? void 0 : e.locale;
133
+ return {
134
+ pageIds: [],
135
+ pages: {},
136
+ components: {},
137
+ supportedLocales: t,
138
+ config: { defaultLocale: s },
139
+ resources: {}
140
+ };
141
+ }
142
+ const U = class U extends M.Doc {
143
+ constructor(s) {
144
+ super(), this.options = s, this.states = {}, this.conns = /* @__PURE__ */ new Map(), this.awarenessChangeHandler = ({ added: e, updated: n, removed: r }, a) => {
145
+ const l = e.concat(n, r);
146
+ if (a !== null) {
147
+ const c = this.conns.get(a);
148
+ c && (e.forEach((f) => {
149
+ c.add(f);
150
+ }), r.forEach((f) => {
151
+ c.delete(f);
152
+ }));
153
+ }
154
+ const i = v.createEncoder();
155
+ v.writeVarUint(i, re), v.writeVarUint8Array(i, he(this.awareness, l));
156
+ const o = v.toUint8Array(i);
157
+ this.conns.forEach((c, f) => this.send(f, o));
158
+ }, this.updateHandler = (e) => {
159
+ const n = v.createEncoder();
160
+ v.writeVarUint(n, K), ct(n, e);
161
+ const r = v.toUint8Array(n);
162
+ this.conns.forEach((a, l) => this.send(l, r));
163
+ }, this.ensureDataStructure = () => {
164
+ var l;
165
+ const { supportedLocales: e, pages: n, pageIds: r, config: a } = this.syncedStore;
166
+ {
167
+ const i = new Set(Object.keys(n));
168
+ let o = 0;
169
+ for (; o < r.length; ) {
170
+ const c = r[o];
171
+ i.has(c) ? (i.delete(c), o++) : r.splice(o, 1);
172
+ }
173
+ }
174
+ e.splice(0, e.length), e.push(...ce.env.languages.map((i) => ({ locale: i.code, name: i.name }))), a.defaultLocale = (l = e[0]) == null ? void 0 : l.locale;
175
+ {
176
+ let i = 0;
177
+ const o = /* @__PURE__ */ new Set();
178
+ for (; i < e.length; ) {
179
+ const { locale: c } = e[i];
180
+ o.has(c) ? e.splice(i, 1) : (i++, o.add(c));
181
+ }
182
+ }
183
+ }, this.send = (e, n) => {
184
+ e.readyState !== bt && e.readyState !== vt && this.closeConn(e);
185
+ try {
186
+ e.send(n, (r) => {
187
+ r && this.closeConn(e);
188
+ });
189
+ } catch {
190
+ this.closeConn(e);
191
+ }
192
+ }, this.closeConn = (e) => {
193
+ if (e.removeAllListeners(), this.conns.has(e)) {
194
+ const n = this.conns.get(e);
195
+ this.conns.delete(e), n && ot(this.awareness, Array.from(n), null);
196
+ }
197
+ e.close();
198
+ }, this.autoSave = Oe(() => {
199
+ R(k(this.draftYjsFilePath), { recursive: !0 }), X(this.draftYjsFilePath, M.encodeStateAsUpdate(this));
200
+ }, Et), this.save = ({ flush: e = !1 } = {}) => {
201
+ this.autoSave(), e && this.autoSave.flush();
202
+ }, this.publish = async ({ mode: e, pages: n }) => {
203
+ const r = await this.getState("draft"), a = await this.getState("production");
204
+ await ve(r, a, { pages: n, pageMergeMode: "replace", deletePages: !0, publishMode: e }), a.config.publishedAt = (/* @__PURE__ */ new Date()).getTime();
205
+ for (const l of n || Object.keys(this.syncedStore.pages))
206
+ this.syncedStore.pages[l] && (this.syncedStore.pages[l].publishedAt = (/* @__PURE__ */ new Date()).toISOString());
207
+ await this.setState(e, a);
208
+ }, this.mergeState = async (e, n) => {
209
+ var i, o, c;
210
+ const r = JSON.parse(JSON.stringify(n));
211
+ (i = e.config).fontFamily ?? (i.fontFamily = {});
212
+ const a = (o = r.config) == null ? void 0 : o.fontFamily, l = (c = e.config) == null ? void 0 : c.fontFamily;
213
+ e.config.fontFamily.title = (a == null ? void 0 : a.title) || (l == null ? void 0 : l.title), e.config.fontFamily.description = (a == null ? void 0 : a.description) || (l == null ? void 0 : l.description), await new Promise((f, p) => {
214
+ this.transact(async () => {
215
+ try {
216
+ const g = await ve(e, n);
217
+ f(g);
218
+ } catch (g) {
219
+ p(g);
220
+ }
221
+ });
222
+ });
223
+ }, this.addConnection = (e) => {
224
+ if (this.conns.has(e))
225
+ return;
226
+ e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (a) => this.messageListener(e, new Uint8Array(a)));
227
+ let n = !0;
228
+ const r = setInterval(() => {
229
+ if (!n)
230
+ this.conns.has(e) && this.closeConn(e), clearInterval(r);
231
+ else if (this.conns.has(e)) {
232
+ n = !1;
233
+ try {
234
+ e.ping();
235
+ } catch {
236
+ this.closeConn(e), clearInterval(r);
237
+ }
238
+ }
239
+ }, At);
240
+ e.on("close", () => {
241
+ this.closeConn(e), clearInterval(r);
242
+ }), e.on("pong", () => {
243
+ n = !0;
244
+ });
245
+ {
246
+ const a = v.createEncoder();
247
+ v.writeVarUint(a, K), lt(a, this), this.send(e, v.toUint8Array(a));
248
+ const l = this.awareness.getStates();
249
+ if (l.size > 0) {
250
+ const i = v.createEncoder();
251
+ v.writeVarUint(i, re), v.writeVarUint8Array(i, he(this.awareness, Array.from(l.keys()))), this.send(e, v.toUint8Array(i));
252
+ }
253
+ }
254
+ }, this.messageListener = (e, n) => {
255
+ try {
256
+ const r = v.createEncoder(), a = ne.createDecoder(n), l = ne.readVarUint(a);
257
+ switch (l) {
258
+ case K:
259
+ v.writeVarUint(r, K), pt(a, r, this, null), v.length(r) > 1 && (this.ensureDataStructure(), this.send(e, v.toUint8Array(r)));
260
+ break;
261
+ case re: {
262
+ at(this.awareness, ne.readVarUint8Array(a), e);
263
+ break;
264
+ }
265
+ default:
266
+ D.warn(`Unsupported messageType ${l}`);
267
+ }
268
+ } catch (r) {
269
+ D.error(r);
270
+ }
271
+ this.save();
272
+ }, $(this.draftYjsFilePath) && M.applyUpdate(this, x(this.draftYjsFilePath)), this.syncedStore = Je(
273
+ qe(
274
+ { pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
275
+ this
276
+ )
277
+ ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new it(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
278
+ }
279
+ // safe delete project state dir
280
+ static safeDeleteProjectStateDir(s) {
281
+ if (!s)
282
+ throw new Error("Should provide project context");
283
+ try {
284
+ const e = A(H, s), n = A(H, `@del-${s}`);
285
+ me(e, n);
286
+ } catch (e) {
287
+ D.error("Failed to safe delete project state dir:", e);
288
+ }
289
+ }
290
+ static get projectIds() {
291
+ return ae("*/", {
292
+ cwd: H,
293
+ ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*"]
294
+ // Ignore temp directories and hidden files
295
+ });
296
+ }
297
+ static get allShared() {
298
+ return this.projectIds.map((s) => U.shared(s));
299
+ }
300
+ static shared(s) {
301
+ if (!s)
302
+ throw new Error("Should provide project context");
303
+ let e = this.sharedInstances.get(s);
304
+ return e || (e = new U({
305
+ path: A(H, s)
306
+ }), this.sharedInstances.set(s, e), e);
307
+ }
308
+ destroy() {
309
+ this.conns.forEach((s, e) => this.closeConn(e)), this.awareness.destroy(), super.destroy();
310
+ }
311
+ initObserver() {
312
+ const s = (n) => {
313
+ n.observeDeep((r) => {
314
+ r.some((a) => a.changes.keys.has("updatedAt") || a.changes.keys.has("publishedAt")) || n.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
315
+ });
316
+ };
317
+ this.syncedStore.pages && Object.keys(this.syncedStore.pages).forEach((n) => {
318
+ const r = se(this.syncedStore.pages[n]);
319
+ r && r instanceof M.Map && s(r);
320
+ });
321
+ const e = se(this.syncedStore.pages);
322
+ e && e instanceof M.Map && e.observe((n) => {
323
+ n.changes.keys.forEach((r, a) => {
324
+ if (r.action === "add") {
325
+ const l = se(this.syncedStore.pages[a]);
326
+ l && l instanceof M.Map && s(l);
327
+ }
328
+ });
329
+ });
330
+ }
331
+ get draftYjsFilePath() {
332
+ return A(this.options.path, "draft.yjs");
333
+ }
334
+ async getState(s) {
335
+ var e, n, r, a;
336
+ if (s === "draft")
337
+ return JSON.parse(JSON.stringify(this.syncedStore));
338
+ if (!this.states[s] && (this.states[s] = await Ue(this.getPublishDir(s), { includeResources: !0 }) ?? It(), !((n = (e = this.states[s]) == null ? void 0 : e.config) != null && n.defaultLocale))) {
339
+ (r = this.states[s]).config ?? (r.config = {});
340
+ const l = ce.env.languages.map((i) => ({ locale: i.code, name: i.name }));
341
+ this.states[s].config.defaultLocale = (a = l[0]) == null ? void 0 : a.locale;
342
+ }
343
+ return {
344
+ ...this.states[s],
345
+ resources: await Ct().then(async (l) => {
346
+ var f, p, g, I;
347
+ const { pages: i, components: o } = Ye(l, "pages", "components");
348
+ let c = o;
349
+ if ((p = (f = this.states[s]) == null ? void 0 : f.resources) != null && p.components)
350
+ c = {
351
+ ...(I = (g = this.states[s]) == null ? void 0 : g.resources) == null ? void 0 : I.components
352
+ };
353
+ else {
354
+ const T = B(this.options.path), O = await F.findByPk(T);
355
+ if (O != null && O.useAllResources)
356
+ c = o;
357
+ else {
358
+ const N = (await te.findAll({ where: { projectId: T } })).map((m) => m.componentId);
359
+ c = Object.fromEntries(
360
+ Object.entries(o || {}).filter(([m]) => N.includes(m))
361
+ );
362
+ }
363
+ }
364
+ return { pages: i, components: c };
365
+ }).catch(() => ({}))
366
+ };
367
+ }
368
+ async setState(s, e) {
369
+ const n = await Dt(e, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(s);
370
+ R(k(r), { recursive: !0 }), Te(r, { force: !0, recursive: !0 }), me(n, r), this.states[s] = e;
371
+ }
372
+ getPublishDir(s) {
373
+ return A(this.options.path, s);
374
+ }
375
+ static async pageUrlMap(s) {
376
+ const { projectIds: e } = this, n = {};
377
+ for (const r of e) {
378
+ const a = await F.findByPk(r);
379
+ if (!a) continue;
380
+ const l = await U.shared(r).getState(s), i = We(
381
+ h.env.languages.map((o) => o.code),
382
+ l.supportedLocales.map((o) => o.locale)
383
+ );
384
+ for (const o of l.pageIds) {
385
+ const c = l.pages[o];
386
+ if (!c || s === "production" && !c.isPublic)
387
+ continue;
388
+ const f = c.slug, p = a.slug || r, g = {
389
+ projectId: r,
390
+ projectSlug: p,
391
+ pageSlug: f,
392
+ pageId: o,
393
+ // default locale
394
+ defaultLocale: i == null ? void 0 : i[0],
395
+ locales: i,
396
+ publishedAt: l.config.publishedAt,
397
+ isPublic: c.isPublic,
398
+ isTemplate: c.isTemplate
399
+ };
400
+ p && (n[V("/", p, f)] = {
401
+ ...g,
402
+ shouldRedirect: !0,
403
+ mainPage: !0
404
+ }), n[V("/", r, f)] = {
405
+ ...g,
406
+ shouldRedirect: !0,
407
+ mainPage: !0
408
+ };
409
+ for (const I of i) {
410
+ const T = { ...g, locale: I };
411
+ n[V("/", I, r, f)] = T, p && (n[V("/", I, p, f)] = T);
412
+ }
413
+ }
414
+ }
415
+ return n;
416
+ }
417
+ };
418
+ U.INSTANCE_TTL = 30 * 60 * 1e3, U.sharedInstances = new Pe({
419
+ max: 100,
420
+ // Maximum number of instances to store
421
+ ttl: U.INSTANCE_TTL,
422
+ dispose: (s) => {
423
+ s.destroy();
424
+ }
425
+ });
426
+ let Q = U;
427
+ function Ce() {
428
+ return Ke(A(h.env.dataDir, "tmp-"));
429
+ }
430
+ function Z(t, s, e = []) {
431
+ return Array.isArray(t) ? t.flatMap((n, r) => Z(n, s, [...e, r])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([n, r]) => Z(r, s, [...e, n])) : s(t) ? [e] : [];
432
+ }
433
+ function C(t) {
434
+ return t.filter((s) => s != null);
435
+ }
436
+ async function Tt(t, s, e) {
437
+ if (!t || !$(t) || !Y(t).isFile())
438
+ return null;
439
+ let n = e[t];
440
+ return n || (n = (async () => (await wt({
441
+ filePath: t,
442
+ fileName: s
443
+ })).data.filename)(), e[t] = n), n;
444
+ }
445
+ const Ot = async (t, s) => {
446
+ const e = B(t), n = await Ge({
447
+ name: je,
448
+ path: V("/uploads", e),
449
+ responseType: "stream",
450
+ method: "GET"
451
+ });
452
+ if (n.status >= 200 && n.status < 400) {
453
+ const r = He(s);
454
+ await st(n.data, r);
455
+ } else
456
+ throw new Error(`download asset failed ${n.status}`);
457
+ }, Pt = async (t, s) => {
458
+ await Promise.all(
459
+ t.map(async (e) => {
460
+ try {
461
+ await Ot(e, A(s, B(e)));
462
+ } catch (n) {
463
+ D.error(`Failed to export assets: ${e}, ${n}`);
464
+ }
465
+ })
466
+ );
467
+ };
468
+ function Le(t) {
469
+ return pe.test(t) ? [t] : J.test(t) ? (Ee.lastIndex = 0, Array.from(t.matchAll(Ee)).map((e) => e[1]).filter((e) => !!e)) : [];
470
+ }
471
+ async function oe(t, s, e) {
472
+ const { getFilename: n, exportAssets: r } = e, a = A(s, n(t));
473
+ if (R(k(a), { recursive: !0 }), X(a, G.stringify(t)), r) {
474
+ const i = Z(
475
+ t,
476
+ (o) => typeof o == "string" && (pe.test(o) || J.test(o))
477
+ ).map((o) => {
478
+ const c = le(t, o);
479
+ return Le(c);
480
+ }).flat().filter(Boolean);
481
+ await Pt(i, k(a));
482
+ }
483
+ }
484
+ const Ae = new Pe({
485
+ max: 1e3,
486
+ ttl: 30 * 24 * 60 * 60 * 1e3
487
+ });
488
+ async function be(t, s, e) {
489
+ var i;
490
+ const n = Z(
491
+ t,
492
+ (o) => typeof o == "string" && (pe.test(o) || J.test(o))
493
+ ), r = et(2), a = n.map(
494
+ (o) => r(async () => {
495
+ try {
496
+ const c = le(t, o), f = Le(c);
497
+ for (const p of f) {
498
+ const g = B(p), I = e.getFilePath(p, o), T = I ? `${I}:${g}` : g, O = Ae.get(T);
499
+ if (O) {
500
+ J.test(c) || ge(t, o, O);
501
+ return;
502
+ }
503
+ const L = await Tt(I, g, s);
504
+ L && (J.test(c) || ge(t, o, L), Ae.set(T, L));
505
+ }
506
+ } catch (c) {
507
+ D.error(`Failed to process upload for path ${o.join(".")}:`, c.message || c.reason);
508
+ }
509
+ })
510
+ ), l = await Promise.allSettled(a);
511
+ (i = e.onFinish) == null || i.call(e, l);
512
+ }
513
+ async function Dt(t, {
514
+ exportAssets: s,
515
+ pageIds: e = "all",
516
+ componentIds: n = "all",
517
+ rawConfig: r,
518
+ includeResources: a = !1
519
+ } = {}) {
520
+ var N, _, m, w, S, E;
521
+ const l = e === "all" ? t.pageIds : e, i = jt({
522
+ state: t,
523
+ pageIds: l,
524
+ componentIds: n === "all" ? Object.keys(t.components) : n
525
+ }), o = (u, d) => {
526
+ var y;
527
+ return {
528
+ id: u.id,
529
+ name: u.name,
530
+ isTemplateSection: u.isTemplateSection ?? !1,
531
+ component: u.component,
532
+ config: u.config,
533
+ visibility: u.visibility,
534
+ properties: ((y = u.locales) == null ? void 0 : y[d]) ?? {}
535
+ };
536
+ }, c = (u, d) => {
537
+ var y;
538
+ return {
539
+ id: u.id,
540
+ createdAt: u.createdAt,
541
+ updatedAt: u.updatedAt,
542
+ publishedAt: u.publishedAt,
543
+ isPublic: u.isPublic ?? !0,
544
+ isTemplate: u.isTemplate ?? !1,
545
+ meta: ((y = u.locales) == null ? void 0 : y[d]) ?? {},
546
+ sections: C(
547
+ u.sectionIds.map((P) => {
548
+ const j = u.sections[P];
549
+ return j && o(j, d);
550
+ })
551
+ )
552
+ };
553
+ }, f = C(
554
+ t.supportedLocales.map((u) => u.locale).flatMap(
555
+ (u) => l.map((d) => {
556
+ const y = t.pages[d];
557
+ return y && {
558
+ locale: u,
559
+ slug: y.slug,
560
+ page: c(y, u)
561
+ };
562
+ })
563
+ )
564
+ ), p = Ce(), g = A(p, "pages");
565
+ R(g, { recursive: !0 });
566
+ const I = A(p, "components");
567
+ R(I, { recursive: !0 });
568
+ for (const { locale: u, slug: d, page: y } of f)
569
+ await oe(y, g, {
570
+ getFilename: () => `${ke(d) || "index"}.${u}.yml`,
571
+ exportAssets: s
572
+ });
573
+ for (const u of i) {
574
+ const d = (N = t.components[u]) == null ? void 0 : N.data;
575
+ d && await oe(d, I, {
576
+ getFilename: (y) => `${y.name || "unnamed"}.${y.id}.yml`,
577
+ exportAssets: s
578
+ });
579
+ }
580
+ const T = A(p, ".blocklet/pages/pages.config.yml");
581
+ R(k(T), { recursive: !0 });
582
+ const O = {
583
+ pages: C(
584
+ l.map((u) => {
585
+ const d = t.pages[u];
586
+ return d && { id: u, slug: d.slug };
587
+ })
588
+ ),
589
+ components: C(
590
+ i.map((u) => {
591
+ var y;
592
+ const d = (y = t.components[u]) == null ? void 0 : y.data;
593
+ return d && {
594
+ id: u,
595
+ name: d.name
596
+ };
597
+ })
598
+ ),
599
+ ...a ? {
600
+ resources: {
601
+ components: C(
602
+ Object.keys(((_ = t.resources) == null ? void 0 : _.components) || {}).map((u) => {
603
+ var d, y, P, j;
604
+ return {
605
+ id: u,
606
+ name: (j = (P = (y = (d = t.resources) == null ? void 0 : d.components) == null ? void 0 : y[u]) == null ? void 0 : P.component) == null ? void 0 : j.name
607
+ };
608
+ })
609
+ )
610
+ }
611
+ } : {},
612
+ supportedLocales: t.supportedLocales,
613
+ config: t.config
614
+ };
615
+ X(T, G.stringify(O));
616
+ const L = A(p, "config.source.json");
617
+ if (r && X(L, JSON.stringify(r)), a) {
618
+ const u = A(p, "resources"), d = A(u, "components");
619
+ R(d, { recursive: !0 });
620
+ for (const y of Object.keys(((m = t == null ? void 0 : t.resources) == null ? void 0 : m.components) ?? {})) {
621
+ const P = (E = (S = (w = t.resources) == null ? void 0 : w.components) == null ? void 0 : S[y]) == null ? void 0 : E.component;
622
+ P && await oe(P, d, {
623
+ getFilename: (j) => `${j.name || "unnamed"}.${j.id}.yml`,
624
+ exportAssets: s
625
+ });
626
+ }
627
+ }
628
+ return p;
629
+ }
630
+ async function Ue(t, { importAssets: s, includeResources: e } = {}) {
631
+ var a, l, i;
632
+ if (!$(t))
633
+ return null;
634
+ let n, r = !1;
635
+ try {
636
+ Y(t).isDirectory() ? n = t : /\.(tgz|gz|tar)$/.test(t) && (r = !0, n = Ce(), await nt({ file: t, C: n }));
637
+ const o = ae("**/.blocklet/pages/pages.config.yml", { cwd: n, absolute: !0 }).at(0), c = o && A(k(o), "../../pages"), f = o && A(k(o), "../../components"), p = o && A(k(o), "../../chunks");
638
+ if (!o)
639
+ return null;
640
+ const g = G.parse(x(o).toString()), I = (m, w, S) => {
641
+ let E = A(m, `${w}${S ? `.${S}` : ""}.yml`);
642
+ return (!$(E) || !Y(E).isFile()) && (E = A(m, w, `index${S ? `.${S}` : ""}.yml`), !$(E) || !Y(E)) ? null : G.parse(x(E).toString());
643
+ }, T = (m, w) => {
644
+ try {
645
+ const S = ae(`*.${w}.yml`, { cwd: m, absolute: !0 })[0];
646
+ return S ? G.parse(x(S).toString()) : null;
647
+ } catch (S) {
648
+ D.error("parse component error", S);
649
+ }
650
+ return null;
651
+ }, O = C(
652
+ g.pages.map(({ slug: m }) => {
653
+ var u;
654
+ const w = C(
655
+ g.supportedLocales.map(({ locale: d }) => {
656
+ const y = c ? I(c, ke(m), d) : void 0;
657
+ if (y)
658
+ return { locale: d, page: y };
659
+ const P = c ? I(c, m, d) : void 0;
660
+ return P && { locale: d, page: P };
661
+ })
662
+ ), S = (u = w[0]) == null ? void 0 : u.page;
663
+ if (!S)
664
+ return null;
665
+ const E = S.sections.map((d) => {
666
+ const y = d.id || we();
667
+ return {
668
+ id: y,
669
+ component: d.component,
670
+ config: d.config,
671
+ name: d.name,
672
+ isTemplateSection: d.isTemplateSection ?? !1,
673
+ visibility: d.visibility,
674
+ locales: Object.fromEntries(
675
+ C(
676
+ w.map(({ locale: P, page: j }) => {
677
+ const fe = j.sections.find((_e) => _e.id === y);
678
+ return fe && [P, fe.properties];
679
+ })
680
+ )
681
+ )
682
+ };
683
+ });
684
+ return {
685
+ id: S.id || we(),
686
+ createdAt: S.createdAt,
687
+ updatedAt: S.updatedAt,
688
+ publishedAt: S.publishedAt,
689
+ isPublic: S.isPublic ?? !0,
690
+ isTemplate: S.isTemplate ?? !1,
691
+ slug: m,
692
+ sections: Object.fromEntries(E.map((d) => [d.id, d])),
693
+ sectionIds: E.map((d) => d.id),
694
+ locales: Object.fromEntries(w.map(({ locale: d, page: y }) => [d, y.meta]))
695
+ };
696
+ })
697
+ ), L = f ? C(((a = g.components) == null ? void 0 : a.map(({ id: m }) => T(f, m))) ?? []) : [];
698
+ if (s) {
699
+ const m = (...w) => {
700
+ D.info(`[${r ? B(t) : B(A(t, "../../../../"))}] importAssets:`, ...w);
701
+ };
702
+ try {
703
+ m("wait image-bin api ready"), await rt({
704
+ resources: [`${xe(mt)}/api/sdk/uploads`],
705
+ validateStatus: (E) => E >= 200 && E <= 500
706
+ }), m("image-bin api is ready");
707
+ const w = {}, S = {};
708
+ m("start to upload assets"), await Promise.allSettled([
709
+ be(L, w, {
710
+ getFilePath: (E) => f && A(f, E),
711
+ onFinish: (E) => {
712
+ m(`upload ${E.length} component assets`);
713
+ }
714
+ }),
715
+ be(O, S, {
716
+ getFilePath: (E, u) => {
717
+ const d = le(O, u.slice(0, 1));
718
+ return c && A(c, k(d.slug), E);
719
+ },
720
+ onFinish: (E) => {
721
+ m(`upload ${E.length} page assets`);
722
+ }
723
+ })
724
+ ]), m("upload assets done"), global.gc && global.gc();
725
+ } catch (w) {
726
+ m("Error during asset import:", w);
727
+ }
728
+ }
729
+ const N = {};
730
+ if (e) {
731
+ const m = o && A(k(o), "../../resources/components"), w = C(
732
+ ((i = (l = g.resources) == null ? void 0 : l.components) == null ? void 0 : i.map(({ id: S }) => T(m, S))) ?? []
733
+ );
734
+ w.length > 0 && (N.components = Object.fromEntries(
735
+ w.map((S, E) => [S.id, { index: E, component: S }])
736
+ ));
737
+ }
738
+ const _ = {};
739
+ if (p && $(p)) {
740
+ const m = ze(p);
741
+ for (const w of m)
742
+ _[w] = x(A(p, w), "utf-8");
743
+ }
744
+ return {
745
+ supportedLocales: g.supportedLocales,
746
+ pageIds: O.map((m) => m.id),
747
+ components: Object.fromEntries(L.map((m, w) => [m.id, { index: w, data: m }])),
748
+ pages: Object.fromEntries(O.map((m) => [m.id, m])),
749
+ config: g.config || {},
750
+ resources: N,
751
+ chunks: _
752
+ };
753
+ } finally {
754
+ r && n && Te(n, { force: !0, recursive: !0 });
755
+ }
756
+ }
757
+ async function ve(t, s, {
758
+ pages: e,
759
+ pageMergeMode: n = "byUpdateTime",
760
+ deletePages: r = !1,
761
+ publishMode: a = void 0
762
+ } = {}) {
763
+ try {
764
+ a && Me(a);
765
+ } catch (f) {
766
+ D.error("clear preload page cache error", { error: f });
767
+ }
768
+ const { pageIds: l, pages: i, supportedLocales: o } = t;
769
+ for (const f of e ?? l) {
770
+ const p = i[f];
771
+ if (!p) {
772
+ const g = s.pageIds.indexOf(f);
773
+ g !== -1 && r && (s.pageIds.splice(g, 1), delete s.pages[f]);
774
+ continue;
775
+ }
776
+ if (s.pageIds.includes(p.id)) {
777
+ if (n === "replace")
778
+ s.pages[p.id] = p;
779
+ else if (n === "byUpdateTime") {
780
+ const g = s.pages[p.id];
781
+ (!g || p.updatedAt && p.updatedAt > g.updatedAt) && (s.pages[p.id] = p);
782
+ }
783
+ } else
784
+ s.pageIds.push(p.id), s.pages[p.id] = p;
785
+ }
786
+ if (r && !e)
787
+ for (const f of s.pageIds)
788
+ t.pageIds.includes(f) || delete s.pages[f], s.pageIds = [...s.pageIds].filter((p) => t.pageIds.includes(p));
789
+ if (s.supportedLocales.splice(0, s.supportedLocales.length), s.supportedLocales.push(...Xe(o)), r)
790
+ for (const f of Object.keys(s.components))
791
+ delete s.components[f];
792
+ let c = JSON.parse(JSON.stringify(t.components));
793
+ c = Object.fromEntries(
794
+ await Promise.all(
795
+ Object.entries(c).map(async ([f, p]) => {
796
+ const g = await Ne(p == null ? void 0 : p.data);
797
+ return [
798
+ f,
799
+ {
800
+ ...p,
801
+ data: g
802
+ }
803
+ ];
804
+ })
805
+ )
806
+ ), Object.assign(s.components, c), Object.assign(s.config, JSON.parse(JSON.stringify(t.config))), s.resources.components = JSON.parse(JSON.stringify(t.resources.components || {}));
807
+ }
808
+ const Ne = Be(
809
+ async (t) => {
810
+ var s;
811
+ if (!Qe(t == null ? void 0 : t.properties))
812
+ return t;
813
+ if (((s = t == null ? void 0 : t.renderer) == null ? void 0 : s.type) === "react-component") {
814
+ const { script: e } = (t == null ? void 0 : t.renderer) || {};
815
+ if (e)
816
+ try {
817
+ const n = await $e(e, "PROPERTIES_SCHEMA", t.id);
818
+ n && n.length > 0 && t && (t.properties = {}, n.forEach((r, a) => {
819
+ t != null && t.properties && (t.properties[r.id] = {
820
+ index: a,
821
+ data: r
822
+ });
823
+ }));
824
+ } catch (n) {
825
+ D.error("checkPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: n });
826
+ }
827
+ }
828
+ return t;
829
+ },
830
+ {
831
+ keyGenerator: (t) => JSON.stringify(["checkPropertiesFromCode", t])
832
+ }
833
+ );
834
+ function jt({
835
+ state: t,
836
+ pageIds: s = [],
837
+ componentIds: e = []
838
+ }) {
839
+ var l;
840
+ const n = (i, o = /* @__PURE__ */ new Set()) => (Array.isArray(i) && i.forEach((c) => n(c, o)), i && typeof i == "object" && (typeof i.componentId == "string" && o.add(i.componentId), Object.values(i).forEach((c) => n(c, o))), o), r = new Set(e);
841
+ for (const i of s) {
842
+ const o = t.pages[i];
843
+ n(o, r);
844
+ }
845
+ const a = [...r];
846
+ for (; a.length; ) {
847
+ const i = a.shift();
848
+ r.has(i) || r.add(i);
849
+ const o = (l = t.components[i]) == null ? void 0 : l.data;
850
+ if (o)
851
+ for (const c of n(o))
852
+ r.has(c) || a.push(c);
853
+ }
854
+ return [...r];
855
+ }
856
+ let ee, q, de, ue;
857
+ function Re() {
858
+ return ee = (async () => {
859
+ const t = Ve({
860
+ types: [
861
+ { did: je, type: Se },
862
+ { did: St, type: Se }
863
+ ]
864
+ });
865
+ q = (await Promise.all(
866
+ t.map(async (e) => {
867
+ const n = e.path ? await Ue(e.path, { importAssets: !1 }) : void 0;
868
+ return n ? { blockletId: e.did, state: n, blockletTitle: e.title } : void 0;
869
+ })
870
+ )).filter((e) => !!e), de = q.reduce(
871
+ (e, n) => Object.assign(
872
+ e,
873
+ Object.fromEntries(
874
+ Object.values(n.state.pages).map((r) => r ? [r == null ? void 0 : r.id, { page: r, blockletId: n.blockletId }] : [])
875
+ )
876
+ ),
877
+ {}
878
+ );
879
+ const s = q.reduce(
880
+ (e, n) => Object.assign(
881
+ e,
882
+ Object.fromEntries(
883
+ Object.values(n.state.components).map((r) => [r.data.id, { blockletId: n.blockletId, component: r.data }])
884
+ )
885
+ ),
886
+ {}
887
+ );
888
+ ue = Object.fromEntries(
889
+ await Promise.all(
890
+ Object.entries(s).map(async ([e, n]) => {
891
+ const r = await Ne(n.component);
892
+ return [
893
+ e,
894
+ {
895
+ ...n,
896
+ component: r
897
+ }
898
+ ];
899
+ })
900
+ )
901
+ );
902
+ })(), ee;
903
+ }
904
+ function kt(t) {
905
+ const s = Oe(
906
+ async () => {
907
+ await Re().catch((e) => {
908
+ D.error("load resource states error", { error: e });
909
+ }), await (t == null ? void 0 : t({ states: q, pages: de, components: ue }));
910
+ },
911
+ 3e3,
912
+ { leading: !1, trailing: !0 }
913
+ );
914
+ return s(), h.events.on(h.Events.componentAdded, s), h.events.on(h.Events.componentRemoved, s), h.events.on(h.Events.componentStarted, s), h.events.on(h.Events.componentStopped, s), h.events.on(h.Events.componentUpdated, s), h.events.on(ie, s), () => {
915
+ h.events.off(h.Events.componentAdded, s), h.events.off(h.Events.componentRemoved, s), h.events.off(h.Events.componentStarted, s), h.events.off(h.Events.componentStopped, s), h.events.off(h.Events.componentUpdated, s), h.events.off(ie, s);
916
+ };
917
+ }
918
+ const Fe = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), W = globalThis;
919
+ var Ie;
920
+ (Ie = W[Fe]) == null || Ie.call(W);
921
+ W[Fe] = kt(async ({ pages: t, components: s }) => {
922
+ const { projectIds: e } = Q;
923
+ await Promise.all(
924
+ e.map(async (n) => {
925
+ const r = Q.shared(n);
926
+ r.syncedStore.resources.pages = t;
927
+ const a = await F.findByPk(n);
928
+ if (a != null && a.useAllResources)
929
+ r.syncedStore.resources.components = s;
930
+ else {
931
+ const i = (await te.findAll({ where: { projectId: n } })).map((c) => c.componentId), o = Object.fromEntries(
932
+ Object.entries(s || {}).filter(([c]) => i.includes(c))
933
+ );
934
+ r.syncedStore.resources.components = o;
935
+ }
936
+ D.info(`update [${n}] resource states:`, {
937
+ pages: Object.keys(r.syncedStore.resources.pages || {}).length,
938
+ components: Object.keys(r.syncedStore.resources.components || {}).length
939
+ });
940
+ })
941
+ );
942
+ });
943
+ async function rs() {
944
+ D.info("trigger reload all project resource"), h.events.emit(ie);
945
+ }
946
+ async function Ct() {
947
+ return ee ?? (ee = Re()), await ee, { states: q, pages: de, components: ue };
948
+ }
949
+ export {
950
+ je as C,
951
+ F as P,
952
+ Se as R,
953
+ Q as S,
954
+ Ct as a,
955
+ H as b,
956
+ ss as c,
957
+ ns as d,
958
+ kt as e,
959
+ Ue as f,
960
+ ts as g,
961
+ rs as h,
962
+ es as i,
963
+ ve as m,
964
+ we as n,
965
+ Dt as t
966
+ };