@blocklet/pages-kit-inner-components 0.4.22 → 0.4.24

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,1490 @@
1
+ import ee from "vite-plugin-node-polyfills/shims/process";
2
+ import Oe from "vite-plugin-node-polyfills/shims/global";
3
+ import { getComponentMountPoint as ot } from "@blocklet/pages-kit/builtin/utils";
4
+ import { PreloadComponentScriptModule as Q } from "@blocklet/pages-kit/types";
5
+ import { componentUMDName as nt, RenderNestedComponent as Ae, mergeComponent as rt } from "@blocklet/pages-kit/utils/property";
6
+ import { memoize as ae, Sandbox as $e, BuiltinModules as at } from "@blocklet/quickjs";
7
+ import w from "@blocklet/sdk/lib/config";
8
+ import { LRUCache as he } from "lru-cache";
9
+ import it, { Headers as ct } from "node-fetch";
10
+ import { joinURL as U, parseURL as ve, withHttps as lt, getQuery as pt, withQuery as ut } from "ufo";
11
+ import { createHash as ie } from "crypto";
12
+ import dt from "@blocklet/logger";
13
+ import mt from "vite-plugin-node-polyfills/shims/buffer";
14
+ import { BuiltinModules as ft } from "@blocklet/pages-kit/utils/builtin";
15
+ import { createBuiltinModuleTransformer as gt, isRelativeModule as Te } from "@blocklet/pages-kit/utils/typescript/builtin-module-transformer";
16
+ import { call as Be, getResources as ht, getComponentWebEndpoint as yt } from "@blocklet/sdk/lib/component";
17
+ import wt from "autoprefixer";
18
+ import * as St from "esbuild";
19
+ import { readFileSync as J, existsSync as B, lstatSync as X, readdirSync as Et, rmSync as Ve, mkdtempSync as bt, mkdirSync as M, writeFileSync as te, renameSync as Ce, createWriteStream as It } from "fs";
20
+ import Ot from "postcss";
21
+ import At from "tailwindcss";
22
+ import x from "typescript";
23
+ import { reactive as vt } from "@reactivedata/reactive";
24
+ import { syncedStore as Tt, getYjsValue as le } from "@syncedstore/core";
25
+ import { globSync as me } from "glob";
26
+ import * as pe from "lib0/decoding";
27
+ import * as C from "lib0/encoding";
28
+ import { get as ye, isEmpty as Ct, set as Pe, debounce as Ge, pick as Pt, union as xt, cloneDeep as jt } from "lodash";
29
+ import { customAlphabet as kt } from "nanoid";
30
+ import Nt from "p-limit";
31
+ import Dt, { join as O, dirname as L, basename as G } from "path";
32
+ import { pipeline as Lt } from "stream/promises";
33
+ import { x as Rt } from "tar";
34
+ import Ut from "wait-on";
35
+ import { encodeAwarenessUpdate as xe, removeAwarenessStates as _t, applyAwarenessUpdate as Mt, Awareness as Ft } from "y-protocols/awareness";
36
+ import { writeUpdate as $t, writeSyncStep1 as Bt, readSyncMessage as Vt } from "y-protocols/sync";
37
+ import * as H from "yaml";
38
+ import * as $ from "yjs";
39
+ import Gt from "lodash/isNil";
40
+ import { DataTypes as T, Sequelize as Jt, Model as Je, Op as Ht } from "sequelize";
41
+ import "sqlite3";
42
+ w.env.mode;
43
+ const Kt = "image-bin";
44
+ w.env.INIT_TEMPLATE_PATH;
45
+ const Wt = ee.env.DATABASE_URL || Dt.join(w.env.dataDir, "db/pages-kit.db"), je = w, no = () => w.env.tenantMode === "multiple", ro = () => {
46
+ var t;
47
+ return (Gt(je.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = je.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
48
+ }, A = dt("pages-kit"), zt = T.sqlite.DATE.parse;
49
+ T.sqlite.DATE.parse = (t, s) => typeof t == "number" ? new Date(t) : zt(t, s);
50
+ const z = new Jt({
51
+ dialect: "sqlite",
52
+ storage: Wt,
53
+ benchmark: ee.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
54
+ retry: {
55
+ match: [/SQLITE_BUSY/],
56
+ name: "query",
57
+ max: 10
58
+ },
59
+ // eslint-disable-next-line no-console
60
+ logging: ee.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
61
+ // logQueryParameters: true,
62
+ });
63
+ z.query("pragma journal_mode = WAL;");
64
+ z.query("pragma synchronous = normal;");
65
+ z.query("pragma journal_size_limit = 67108864;");
66
+ class ce extends Je {
67
+ // Foreign key to Component
68
+ }
69
+ ce.init(
70
+ {
71
+ id: {
72
+ type: T.UUID,
73
+ allowNull: !1,
74
+ primaryKey: !0,
75
+ defaultValue: T.UUIDV4
76
+ },
77
+ projectId: {
78
+ type: T.UUID,
79
+ allowNull: !1
80
+ },
81
+ componentId: {
82
+ type: T.STRING,
83
+ allowNull: !1
84
+ }
85
+ },
86
+ { sequelize: z, tableName: "ProjectComponents", timestamps: !1 }
87
+ );
88
+ class F extends Je {
89
+ static async getProjectByIdOrSlug(s) {
90
+ return F.findOne({
91
+ where: {
92
+ [Ht.or]: [{ id: s }, { slug: s }]
93
+ }
94
+ });
95
+ }
96
+ }
97
+ F.init(
98
+ {
99
+ id: {
100
+ type: T.UUID,
101
+ defaultValue: T.UUIDV4,
102
+ primaryKey: !0
103
+ },
104
+ name: {
105
+ type: T.STRING,
106
+ allowNull: !1
107
+ },
108
+ description: T.TEXT,
109
+ createdAt: T.DATE,
110
+ updatedAt: T.DATE,
111
+ createdBy: {
112
+ type: T.STRING,
113
+ allowNull: !1
114
+ },
115
+ updatedBy: {
116
+ type: T.STRING,
117
+ allowNull: !1
118
+ },
119
+ slug: T.STRING,
120
+ icon: T.STRING,
121
+ pinnedAt: T.DATE,
122
+ useAllResources: T.BOOLEAN,
123
+ relatedBlocklets: {
124
+ type: T.JSON,
125
+ allowNull: !1,
126
+ defaultValue: {},
127
+ get() {
128
+ return this.getDataValue("relatedBlocklets") || {};
129
+ },
130
+ set(t) {
131
+ this.setDataValue("relatedBlocklets", JSON.stringify(t || {}));
132
+ }
133
+ }
134
+ },
135
+ { sequelize: z, paranoid: !0 }
136
+ );
137
+ F.hasMany(ce, {
138
+ foreignKey: "projectId",
139
+ as: "components"
140
+ });
141
+ const Yt = async (t, { componentId: s }) => {
142
+ const e = `@tailwind components;
143
+ @tailwind utilities;
144
+ `, o = `.CustomComponent_${s}`;
145
+ return (await Ot([
146
+ At({ content: [{ raw: t, extension: "tsx" }] }),
147
+ wt({
148
+ overrideBrowserslist: ["> 1%", "last 2 versions"],
149
+ stats: {}
150
+ }),
151
+ (a) => {
152
+ a.walkRules((l) => {
153
+ l.selectors = l.selectors.map((r) => r.replace(/\.(.+)/g, `${o}.$1,${o} .$1`));
154
+ });
155
+ }
156
+ // FIXME: cssnano use browserslist, it is not working with the fs isolation
157
+ // cssnano({ preset: 'default' }),
158
+ ]).process(e)).css;
159
+ }, qt = async (t, { componentId: s }) => {
160
+ const e = await Yt(t, { componentId: s });
161
+ return `export const __PagesKit_CSS__ = ${JSON.stringify(e)};
162
+
163
+ ${t}
164
+ `;
165
+ }, ke = ae(
166
+ async (t, s) => {
167
+ let e = x.transpileModule(t, {
168
+ compilerOptions: {
169
+ jsx: x.JsxEmit.React,
170
+ target: x.ScriptTarget.ES2016,
171
+ module: x.ModuleKind.ESNext
172
+ },
173
+ transformers: {
174
+ before: [gt(x)]
175
+ }
176
+ }).outputText;
177
+ if (s.tailwind && (e = await qt(e, { componentId: s.componentId })), s.module === Q.ESM) return e;
178
+ const o = x.transpileModule(e, {
179
+ compilerOptions: {
180
+ jsx: x.JsxEmit.React,
181
+ target: x.ScriptTarget.ES2016,
182
+ module: x.ModuleKind.CommonJS,
183
+ moduleResolution: x.ModuleResolutionKind.Node16
184
+ }
185
+ }).outputText;
186
+ return s.module === Q.CJS ? o : Xt(s.moduleName, o);
187
+ },
188
+ {
189
+ keyGenerator: (t, s) => {
190
+ const e = ie("md5").update(t).digest("hex"), o = {
191
+ ...s,
192
+ componentId: s.componentId,
193
+ module: s.module,
194
+ ...s.module !== Q.ESM ? { moduleName: s.moduleName } : {},
195
+ tailwind: s.tailwind
196
+ };
197
+ return JSON.stringify(["transpileModule", e, o]);
198
+ },
199
+ lruOptions: {
200
+ max: 100,
201
+ // 限制缓存项数量为100
202
+ ttl: 1e3 * 60 * 60
203
+ // 1小时过期时间
204
+ }
205
+ }
206
+ ), Qt = async (t, s) => {
207
+ var l, r;
208
+ const o = (r = (l = (await St.build({
209
+ entryPoints: ["index.tsx"],
210
+ external: Object.keys(ft),
211
+ format: "esm",
212
+ target: "esnext",
213
+ bundle: !0,
214
+ write: !1,
215
+ plugins: [
216
+ {
217
+ name: "vfs",
218
+ setup(i) {
219
+ let c = null;
220
+ i.onResolve({ filter: /.*/ }, (p) => p.path === "index.tsx" ? { path: "index.tsx", namespace: "vfs" } : p.path === "./component" ? { path: "component.tsx", namespace: "vfs" } : Te(p.path) ? { path: p.path, namespace: "vfs" } : null), i.onLoad({ filter: /.*/, namespace: "vfs" }, async (p) => {
221
+ var u;
222
+ if (p.path === "index.tsx")
223
+ return { contents: `export { ${s} } from './component'`, loader: "tsx" };
224
+ if (p.path === "component.tsx")
225
+ return { contents: t, loader: "tsx" };
226
+ if (Te(p.path)) {
227
+ c || (c = await tt({ ensureLoaded: !1 }));
228
+ const f = p.path.split("/").pop();
229
+ if ((u = c == null ? void 0 : c.chunks) != null && u[f])
230
+ return { contents: J(c.chunks[f], "utf-8"), loader: "js" };
231
+ const g = U("chunks", f), { data: y } = await Be({
232
+ name: "pages-kit",
233
+ method: "GET",
234
+ path: g
235
+ });
236
+ return { contents: y, loader: "js" };
237
+ }
238
+ return null;
239
+ });
240
+ }
241
+ }
242
+ ]
243
+ })).outputFiles) == null ? void 0 : l[0]) == null ? void 0 : r.contents;
244
+ if (!o) throw new Error("Failed to build server code");
245
+ const n = mt.from(o).toString();
246
+ return x.transpileModule(n, {
247
+ compilerOptions: { module: x.ModuleKind.ESNext, target: x.ScriptTarget.ES2020 }
248
+ }).outputText;
249
+ }, He = ae(
250
+ async (t, s) => {
251
+ const e = await Qt(t, s);
252
+ return new RegExp(`export\\s+\\{\\s+${s}\\s+\\}`, "m").test(e) ? e : void 0;
253
+ },
254
+ {
255
+ keyGenerator: (t, s) => {
256
+ const e = ie("md5").update(t).digest("hex");
257
+ return JSON.stringify(["extractExportValueSchema", e, s]);
258
+ },
259
+ lruOptions: {
260
+ max: 100,
261
+ ttl: 1e3 * 60 * 60
262
+ }
263
+ }
264
+ ), Xt = (t, s) => {
265
+ const e = /\bawait\b/.test(s);
266
+ return `// GENERATED FILE. DO NOT EDIT.
267
+ var ${t} = ${e ? "async" : ""} function () {
268
+
269
+ const exports = {};
270
+ let moduleExports = null;
271
+
272
+ // add commonjs module compatibility layer
273
+ const module = { exports: moduleExports };
274
+
275
+ // execute component code
276
+ ${s}
277
+
278
+ // handle possible module.exports
279
+ if (module.exports && module.exports !== moduleExports) {
280
+ // if module.exports is used, use it first
281
+ return typeof module.exports === 'object' ? module.exports : { default: module.exports };
282
+ }
283
+
284
+ // ensure a default export
285
+ if (!('default' in exports) && Object.keys(exports).length === 0) {
286
+ // module has no exports, return null to indicate invalid
287
+ return null;
288
+ }
289
+
290
+ return exports;
291
+ };
292
+ `;
293
+ }, K = new he({
294
+ max: 100
295
+ }), Zt = 60 * 60, Ne = 60;
296
+ function es(t) {
297
+ A.info("clear preload components cache", { cacheKey: t }), K.delete(t);
298
+ }
299
+ function ts(t) {
300
+ for (const s of K.keys())
301
+ s.includes(t) && (A.info("clear preload components cache", { cacheKey: s }), es(s));
302
+ }
303
+ function ss({
304
+ mode: t,
305
+ instanceId: s,
306
+ componentId: e,
307
+ locale: o
308
+ }) {
309
+ return ["getPreloadComponents", t, s, e, o].join("-");
310
+ }
311
+ async function ao({
312
+ mode: t,
313
+ req: s,
314
+ state: e,
315
+ locale: o,
316
+ instances: n,
317
+ module: a
318
+ }) {
319
+ const {
320
+ supportedLocales: l,
321
+ config: { defaultLocale: r }
322
+ } = e;
323
+ if (!r) return null;
324
+ const i = (await Promise.all(
325
+ n.map(async (g) => {
326
+ try {
327
+ const y = ss({
328
+ mode: t,
329
+ instanceId: g.id,
330
+ componentId: g.componentId,
331
+ locale: o
332
+ });
333
+ if (t !== "draft" && g.useCache && K.has(y))
334
+ return A.info(`get preload component from cache: ${y}`), K.get(y);
335
+ const v = se({ state: e, componentId: g.componentId });
336
+ if (!v) return null;
337
+ const P = await os({
338
+ req: s,
339
+ state: e,
340
+ componentId: v.id,
341
+ locale: o,
342
+ defaultLocale: r,
343
+ properties: g.properties
344
+ });
345
+ if (!P) return null;
346
+ const k = { instanceId: g.id, preload: P };
347
+ if (t !== "draft" && g.useCache) {
348
+ let N = Zt;
349
+ g.cacheDuration && (N = g.cacheDuration), A.info(`set preload component to cache(${N}s): ${y}`), K.set(y, k, {
350
+ ttl: N * 1e3
351
+ });
352
+ }
353
+ return k;
354
+ } catch (y) {
355
+ return A.error("get preload component error", { instanceId: g.id, componentId: g.componentId }, { error: y }), null;
356
+ }
357
+ })
358
+ )).filter((g) => !!g), c = Object.values(
359
+ i.reduce((g, y) => ({ ...g, ...y.preload.components }), {})
360
+ );
361
+ async function p() {
362
+ const g = await Promise.all(
363
+ c.map(async (y) => {
364
+ const v = nt({ componentId: y.component.id }), P = a === Q.ESM ? {
365
+ module: a,
366
+ script: await ke(y.script, {
367
+ componentId: y.component.id,
368
+ module: a,
369
+ tailwind: t !== "draft"
370
+ })
371
+ } : {
372
+ module: a,
373
+ script: await ke(y.script, {
374
+ componentId: y.component.id,
375
+ module: a,
376
+ moduleName: v,
377
+ tailwind: t !== "draft"
378
+ }),
379
+ moduleName: v
380
+ };
381
+ return [y.component.id, { component: y.component, script: P }];
382
+ })
383
+ );
384
+ return Object.fromEntries(g);
385
+ }
386
+ const u = await p();
387
+ return {
388
+ config: { defaultLocale: r, supportedLocales: l },
389
+ components: u,
390
+ instances: i.map((g) => ({
391
+ id: g.instanceId,
392
+ componentId: g.preload.component.id,
393
+ locales: { [g.preload.locale]: { props: g.preload.props } }
394
+ }))
395
+ };
396
+ }
397
+ async function os({
398
+ req: t,
399
+ state: s,
400
+ componentId: e,
401
+ locale: o,
402
+ defaultLocale: n,
403
+ properties: a
404
+ }) {
405
+ const { supportedLocales: l } = s, r = se({ state: s, componentId: e });
406
+ if (!r) return null;
407
+ const i = l.some((p) => p.locale === o) ? o : n;
408
+ if (!i) return null;
409
+ const c = await Ke({ req: t, state: s, componentId: e, locale: i, defaultLocale: n, properties: a });
410
+ return c ? {
411
+ component: r,
412
+ ...c
413
+ } : null;
414
+ }
415
+ const ns = 20;
416
+ async function Ke({
417
+ req: t,
418
+ depth: s = 0,
419
+ state: e,
420
+ componentId: o,
421
+ locale: n,
422
+ defaultLocale: a,
423
+ properties: l
424
+ }) {
425
+ if (s > ns) throw new RangeError("max component depth exceeded");
426
+ const r = rs({ state: e, componentId: o, properties: l, locale: n });
427
+ if (!r) return null;
428
+ const { props: i } = r, c = {
429
+ locale: n || a,
430
+ components: { [r.component.id]: { component: r.component, script: r.script } },
431
+ props: { ...i }
432
+ };
433
+ try {
434
+ const p = await as({ ...r, req: t });
435
+ p != null && p.props && Object.assign(c.props, p.props);
436
+ } catch (p) {
437
+ A.error("preload data at server side error", { componentId: o, name: r.component.name }, { error: p });
438
+ }
439
+ return await Promise.all(
440
+ Object.entries(i).map(async ([p, u]) => {
441
+ if ((u == null ? void 0 : u.type) === Ae) {
442
+ const f = await Ke({
443
+ req: t,
444
+ depth: s + 1,
445
+ state: e,
446
+ componentId: u.componentId,
447
+ locale: n,
448
+ defaultLocale: a,
449
+ properties: u.properties
450
+ });
451
+ f && (Object.assign(c.components, f.components), Object.assign(c.props, {
452
+ [p]: {
453
+ type: Ae,
454
+ componentId: u.componentId,
455
+ props: f.props
456
+ }
457
+ }));
458
+ }
459
+ })
460
+ ), c;
461
+ }
462
+ function rs({
463
+ state: t,
464
+ componentId: s,
465
+ locale: e,
466
+ properties: o
467
+ }) {
468
+ const n = se({ state: t, componentId: s });
469
+ if (!n) return null;
470
+ const a = rt({
471
+ componentId: s,
472
+ getComponent: (l) => se({ state: t, componentId: l }),
473
+ locale: e,
474
+ defaultLocale: t.config.defaultLocale,
475
+ properties: o
476
+ });
477
+ return a ? { component: n, script: a.script, props: { locale: e, ...a.properties } } : null;
478
+ }
479
+ function se({ state: t, componentId: s }) {
480
+ var e, o, n;
481
+ return ((e = t.components[s]) == null ? void 0 : e.data) ?? ((n = (o = t.resources.components) == null ? void 0 : o[s]) == null ? void 0 : n.component);
482
+ }
483
+ function io({ state: t, name: s }) {
484
+ var o, n;
485
+ const e = s.toLowerCase();
486
+ return ((o = Object.values(t.components).find((a) => {
487
+ var l;
488
+ return ((l = a.data.name) == null ? void 0 : l.toLowerCase()) === e;
489
+ })) == null ? void 0 : o.data) ?? ((n = t.resources.components && Object.values(t.resources.components).find((a) => {
490
+ var l;
491
+ return ((l = a.component.name) == null ? void 0 : l.toLowerCase()) === e;
492
+ })) == null ? void 0 : n.component);
493
+ }
494
+ async function as({
495
+ component: t,
496
+ script: s,
497
+ props: e,
498
+ req: o
499
+ }) {
500
+ const n = await He(s, "getServerSideProps");
501
+ if (!n) return null;
502
+ let a = new AbortController();
503
+ const l = new Promise((r, i) => {
504
+ setTimeout(() => {
505
+ i(new Error("getServerSideProps timeout in promise race")), a && (a.abort(), a = null);
506
+ }, Ne * 1e3);
507
+ });
508
+ try {
509
+ return await Promise.race([
510
+ l,
511
+ $e.callFunction({
512
+ code: `${n}
513
+
514
+ export async function getServerSidePropsWrapper(props) {
515
+ const { location, fetch } = props;
516
+ // 使用局部变量而不是全局变量
517
+ const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
518
+ const originalFetch = globalThis.fetch;
519
+
520
+ try {
521
+ globalThis.location = location;
522
+ globalThis.fetch = fetch;
523
+ return await getServerSideProps(props);
524
+ } finally {
525
+ // 清理全局状态
526
+ if (originalLocation) globalThis.location = originalLocation;
527
+ if (originalFetch) globalThis.fetch = originalFetch;
528
+ }
529
+ }`,
530
+ filename: `${t.name || t.id}.js`,
531
+ moduleLoader: (r) => {
532
+ if (r === "@blocklet/pages-kit/builtin/utils")
533
+ return `const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
534
+ export { joinURL, withQuery, getQuery, getComponentMountPoint }
535
+ `;
536
+ if (r === "@blocklet/pages-kit/builtin/dayjs")
537
+ return at.dayjs;
538
+ },
539
+ global: {
540
+ console: {
541
+ // NOTE: do not return logger.xxx result, it will cause memory leak
542
+ // eslint-disable-next-line prettier/prettier
543
+ log: (...r) => {
544
+ A.info(...r);
545
+ },
546
+ warn: (...r) => {
547
+ A.warn(...r);
548
+ },
549
+ error: (...r) => {
550
+ A.error(...r);
551
+ }
552
+ },
553
+ getComponentMountPoint: ot,
554
+ joinURL: U,
555
+ withQuery: ut,
556
+ getQuery: pt
557
+ },
558
+ functionName: "getServerSidePropsWrapper",
559
+ args: [
560
+ {
561
+ // NOTE: IMPORTANT! place location and fetch (has side effect) at the args not global
562
+ // because the global is shared between all runtime and just init once
563
+ location: { href: U(lt(o.hostname), o.originalUrl) },
564
+ fetch: (r, { ...i } = {}) => {
565
+ const c = typeof r == "string" && r.startsWith("/") ? U(w.env.appUrl, r) : r;
566
+ if (typeof c == "string" && ve(c).host === ve(w.env.appUrl).host) {
567
+ const p = o.get("cookie");
568
+ if (p) {
569
+ const u = new ct(i.headers);
570
+ u.set("cookie", p), i.headers = u;
571
+ }
572
+ }
573
+ return it(c, {
574
+ ...i,
575
+ timeout: Ne * 1e3
576
+ }).then((p) => ({
577
+ ok: p.ok,
578
+ status: p.status,
579
+ statusText: p.statusText,
580
+ headers: Object.fromEntries(p.headers.entries()),
581
+ json: () => p.json()
582
+ }));
583
+ },
584
+ props: e
585
+ }
586
+ ]
587
+ })
588
+ ]);
589
+ } finally {
590
+ a = null;
591
+ }
592
+ }
593
+ const is = ae(
594
+ async (t, s, e) => {
595
+ const o = await He(t, s);
596
+ if (o)
597
+ try {
598
+ return await $e.callFunction({
599
+ code: `
600
+ ${o}
601
+
602
+ export function get${s}SchemaWrapper() {
603
+ return ${s};
604
+ }
605
+ `,
606
+ filename: `${e}.js`,
607
+ functionName: `get${s}SchemaWrapper`
608
+ });
609
+ } catch (n) {
610
+ return A.error(`获取 ${s} 失败`, { componentId: e, error: n }), null;
611
+ }
612
+ return null;
613
+ },
614
+ {
615
+ keyGenerator: (t, s, e) => {
616
+ const o = ie("md5").update(t).digest("hex");
617
+ return JSON.stringify(["getExportSchemaValueFromCode", o, s, e]);
618
+ },
619
+ lruOptions: {
620
+ max: 100,
621
+ ttl: 1e3 * 60 * 60
622
+ }
623
+ }
624
+ ), cs = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", De = "page", fe = "trigger-reload-project-resource", We = cs, ls = "z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV", { uploadToMediaKit: ps } = require("@blocklet/uploader-server"), Le = kt("abcdefghijklmnopqrstuvwxyz0123456789", 16), we = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, W = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Re = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, us = 1e4, ds = 3e4, Y = 0, ue = 1, ms = 0, fs = 1, ge = w, q = O(ee.env.BLOCKLET_DATA_DIR, "site-state"), co = ["production", "draft"], lo = ["production"];
625
+ function ze(t) {
626
+ return (t == null ? void 0 : t.replace(/\//g, "|")) || "";
627
+ }
628
+ function gs() {
629
+ var e;
630
+ const t = ge.env.languages.map((o) => ({ locale: o.code, name: o.name })), s = (e = t[0]) == null ? void 0 : e.locale;
631
+ return {
632
+ pageIds: [],
633
+ pages: {},
634
+ components: {},
635
+ supportedLocales: t,
636
+ config: { defaultLocale: s },
637
+ resources: {}
638
+ };
639
+ }
640
+ const _ = class _ extends $.Doc {
641
+ constructor(s) {
642
+ super(), this.options = s, this.states = {}, this.conns = /* @__PURE__ */ new Map(), this.awarenessChangeHandler = ({ added: e, updated: o, removed: n }, a) => {
643
+ const l = e.concat(o, n);
644
+ if (a !== null) {
645
+ const c = this.conns.get(a);
646
+ c && (e.forEach((p) => {
647
+ c.add(p);
648
+ }), n.forEach((p) => {
649
+ c.delete(p);
650
+ }));
651
+ }
652
+ const r = C.createEncoder();
653
+ C.writeVarUint(r, ue), C.writeVarUint8Array(r, xe(this.awareness, l));
654
+ const i = C.toUint8Array(r);
655
+ this.conns.forEach((c, p) => this.send(p, i));
656
+ }, this.updateHandler = (e) => {
657
+ const o = C.createEncoder();
658
+ C.writeVarUint(o, Y), $t(o, e);
659
+ const n = C.toUint8Array(o);
660
+ this.conns.forEach((a, l) => this.send(l, n));
661
+ }, this.ensureDataStructure = () => {
662
+ var l;
663
+ const { supportedLocales: e, pages: o, pageIds: n, config: a } = this.syncedStore;
664
+ {
665
+ const r = new Set(Object.keys(o));
666
+ let i = 0;
667
+ for (; i < n.length; ) {
668
+ const c = n[i];
669
+ r.has(c) ? (r.delete(c), i++) : n.splice(i, 1);
670
+ }
671
+ }
672
+ e.splice(0, e.length), e.push(...ge.env.languages.map((r) => ({ locale: r.code, name: r.name }))), a.defaultLocale = (l = e[0]) == null ? void 0 : l.locale;
673
+ {
674
+ let r = 0;
675
+ const i = /* @__PURE__ */ new Set();
676
+ for (; r < e.length; ) {
677
+ const { locale: c } = e[r];
678
+ i.has(c) ? e.splice(r, 1) : (r++, i.add(c));
679
+ }
680
+ }
681
+ }, this.send = (e, o) => {
682
+ e.readyState !== ms && e.readyState !== fs && this.closeConn(e);
683
+ try {
684
+ e.send(o, (n) => {
685
+ n && this.closeConn(e);
686
+ });
687
+ } catch {
688
+ this.closeConn(e);
689
+ }
690
+ }, this.closeConn = (e) => {
691
+ if (e.removeAllListeners(), this.conns.has(e)) {
692
+ const o = this.conns.get(e);
693
+ this.conns.delete(e), o && _t(this.awareness, Array.from(o), null);
694
+ }
695
+ e.close();
696
+ }, this.autoSave = Ge(() => {
697
+ M(L(this.draftYjsFilePath), { recursive: !0 }), te(this.draftYjsFilePath, $.encodeStateAsUpdate(this));
698
+ }, us), this.save = ({ flush: e = !1 } = {}) => {
699
+ this.autoSave(), e && this.autoSave.flush();
700
+ }, this.publish = async ({ mode: e, pages: o }) => {
701
+ const n = await this.getState("draft"), a = await this.getState("production");
702
+ await Me(n, a, { pages: o, pageMergeMode: "replace", deletePages: !0, publishMode: e }), a.config.publishedAt = (/* @__PURE__ */ new Date()).getTime();
703
+ for (const l of o || Object.keys(this.syncedStore.pages))
704
+ this.syncedStore.pages[l] && (this.syncedStore.pages[l].publishedAt = (/* @__PURE__ */ new Date()).toISOString());
705
+ await this.setState(e, a);
706
+ }, this.mergeState = async (e, o) => {
707
+ var r, i, c;
708
+ const n = JSON.parse(JSON.stringify(o));
709
+ (r = e.config).fontFamily ?? (r.fontFamily = {});
710
+ const a = (i = n.config) == null ? void 0 : i.fontFamily, l = (c = e.config) == null ? void 0 : c.fontFamily;
711
+ 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((p, u) => {
712
+ this.transact(async () => {
713
+ try {
714
+ const f = await Me(e, o);
715
+ p(f);
716
+ } catch (f) {
717
+ u(f);
718
+ }
719
+ });
720
+ });
721
+ }, this.addConnection = (e) => {
722
+ if (this.conns.has(e))
723
+ return;
724
+ e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (a) => this.messageListener(e, new Uint8Array(a)));
725
+ let o = !0;
726
+ const n = setInterval(() => {
727
+ if (!o)
728
+ this.conns.has(e) && this.closeConn(e), clearInterval(n);
729
+ else if (this.conns.has(e)) {
730
+ o = !1;
731
+ try {
732
+ e.ping();
733
+ } catch {
734
+ this.closeConn(e), clearInterval(n);
735
+ }
736
+ }
737
+ }, ds);
738
+ e.on("close", () => {
739
+ this.closeConn(e), clearInterval(n);
740
+ }), e.on("pong", () => {
741
+ o = !0;
742
+ });
743
+ {
744
+ const a = C.createEncoder();
745
+ C.writeVarUint(a, Y), Bt(a, this), this.send(e, C.toUint8Array(a));
746
+ const l = this.awareness.getStates();
747
+ if (l.size > 0) {
748
+ const r = C.createEncoder();
749
+ C.writeVarUint(r, ue), C.writeVarUint8Array(r, xe(this.awareness, Array.from(l.keys()))), this.send(e, C.toUint8Array(r));
750
+ }
751
+ }
752
+ }, this.messageListener = (e, o) => {
753
+ try {
754
+ const n = C.createEncoder(), a = pe.createDecoder(o), l = pe.readVarUint(a);
755
+ switch (l) {
756
+ case Y:
757
+ C.writeVarUint(n, Y), Vt(a, n, this, null), C.length(n) > 1 && (this.ensureDataStructure(), this.send(e, C.toUint8Array(n)));
758
+ break;
759
+ case ue: {
760
+ Mt(this.awareness, pe.readVarUint8Array(a), e);
761
+ break;
762
+ }
763
+ default:
764
+ A.warn(`Unsupported messageType ${l}`);
765
+ }
766
+ } catch (n) {
767
+ A.error(n);
768
+ }
769
+ this.save();
770
+ }, B(this.draftYjsFilePath) && $.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore = vt(
771
+ Tt(
772
+ { pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
773
+ this
774
+ )
775
+ ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new Ft(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
776
+ }
777
+ // safe delete project state dir
778
+ static safeDeleteProjectStateDir(s) {
779
+ if (!s)
780
+ throw new Error("Should provide project context");
781
+ try {
782
+ const e = O(q, s), o = O(q, `@del-${s}`);
783
+ Ce(e, o);
784
+ } catch (e) {
785
+ A.error("Failed to safe delete project state dir:", e);
786
+ }
787
+ }
788
+ static get projectIds() {
789
+ return me("*/", {
790
+ cwd: q,
791
+ ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*"]
792
+ // Ignore temp directories and hidden files
793
+ });
794
+ }
795
+ static get allShared() {
796
+ return this.projectIds.map((s) => _.shared(s));
797
+ }
798
+ static shared(s) {
799
+ if (!s)
800
+ throw new Error("Should provide project context");
801
+ let e = this.sharedInstances.get(s);
802
+ return e || (e = new _({
803
+ path: O(q, s)
804
+ }), this.sharedInstances.set(s, e), e);
805
+ }
806
+ destroy() {
807
+ this.conns.forEach((s, e) => this.closeConn(e)), this.awareness.destroy(), super.destroy();
808
+ }
809
+ initObserver() {
810
+ const s = (o) => {
811
+ o.observeDeep((n) => {
812
+ n.some((a) => a.changes.keys.has("updatedAt") || a.changes.keys.has("publishedAt")) || o.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
813
+ });
814
+ };
815
+ this.syncedStore.pages && Object.keys(this.syncedStore.pages).forEach((o) => {
816
+ const n = le(this.syncedStore.pages[o]);
817
+ n && n instanceof $.Map && s(n);
818
+ });
819
+ const e = le(this.syncedStore.pages);
820
+ e && e instanceof $.Map && e.observe((o) => {
821
+ o.changes.keys.forEach((n, a) => {
822
+ if (n.action === "add") {
823
+ const l = le(this.syncedStore.pages[a]);
824
+ l && l instanceof $.Map && s(l);
825
+ }
826
+ });
827
+ });
828
+ }
829
+ get draftYjsFilePath() {
830
+ return O(this.options.path, "draft.yjs");
831
+ }
832
+ async getState(s) {
833
+ var e, o, n, a;
834
+ if (s === "draft")
835
+ return JSON.parse(JSON.stringify(this.syncedStore));
836
+ if (!this.states[s] && (this.states[s] = await Qe(this.getPublishDir(s), { includeResources: !0 }) ?? gs(), !((o = (e = this.states[s]) == null ? void 0 : e.config) != null && o.defaultLocale))) {
837
+ (n = this.states[s]).config ?? (n.config = {});
838
+ const l = ge.env.languages.map((r) => ({ locale: r.code, name: r.name }));
839
+ this.states[s].config.defaultLocale = (a = l[0]) == null ? void 0 : a.locale;
840
+ }
841
+ return {
842
+ ...this.states[s],
843
+ resources: await tt().then(async (l) => {
844
+ var p, u, f, g;
845
+ const { pages: r, components: i } = Pt(l, "pages", "components");
846
+ let c = i;
847
+ if ((u = (p = this.states[s]) == null ? void 0 : p.resources) != null && u.components)
848
+ c = {
849
+ ...(g = (f = this.states[s]) == null ? void 0 : f.resources) == null ? void 0 : g.components
850
+ };
851
+ else {
852
+ const y = G(this.options.path), v = await F.findByPk(y);
853
+ if (v != null && v.useAllResources)
854
+ c = i;
855
+ else {
856
+ const k = (await ce.findAll({ where: { projectId: y } })).map((h) => h.componentId);
857
+ c = Object.fromEntries(
858
+ Object.entries(i || {}).filter(([h]) => k.includes(h))
859
+ );
860
+ }
861
+ }
862
+ return { pages: r, components: c };
863
+ }).catch(() => ({}))
864
+ };
865
+ }
866
+ async setState(s, e) {
867
+ const o = await Ss(e, { exportAssets: !1, includeResources: !0 }), n = this.getPublishDir(s);
868
+ M(L(n), { recursive: !0 }), Ve(n, { force: !0, recursive: !0 }), Ce(o, n), this.states[s] = e;
869
+ }
870
+ getPublishDir(s) {
871
+ return O(this.options.path, s);
872
+ }
873
+ static async pageUrlMap(s) {
874
+ const { projectIds: e } = this, o = {};
875
+ for (const n of e) {
876
+ const a = await F.findByPk(n);
877
+ if (!a) continue;
878
+ const l = await _.shared(n).getState(s), r = xt(
879
+ w.env.languages.map((i) => i.code),
880
+ l.supportedLocales.map((i) => i.locale)
881
+ );
882
+ for (const i of l.pageIds) {
883
+ const c = l.pages[i];
884
+ if (!c || s === "production" && !c.isPublic)
885
+ continue;
886
+ const p = c.slug, u = a.slug || n, f = {
887
+ projectId: n,
888
+ projectSlug: u,
889
+ pageSlug: p,
890
+ pageId: i,
891
+ // default locale
892
+ defaultLocale: r == null ? void 0 : r[0],
893
+ locales: r,
894
+ publishedAt: l.config.publishedAt,
895
+ isPublic: c.isPublic,
896
+ isTemplate: c.isTemplate
897
+ };
898
+ u && (o[U("/", u, p)] = {
899
+ ...f,
900
+ shouldRedirect: !0,
901
+ mainPage: !0
902
+ }), o[U("/", n, p)] = {
903
+ ...f,
904
+ shouldRedirect: !0,
905
+ mainPage: !0
906
+ };
907
+ for (const g of r) {
908
+ const y = { ...f, locale: g };
909
+ o[U("/", g, n, p)] = y, u && (o[U("/", g, u, p)] = y);
910
+ }
911
+ }
912
+ }
913
+ return o;
914
+ }
915
+ };
916
+ _.INSTANCE_TTL = 30 * 60 * 1e3, _.sharedInstances = new he({
917
+ max: 100,
918
+ // Maximum number of instances to store
919
+ ttl: _.INSTANCE_TTL,
920
+ dispose: (s) => {
921
+ s.destroy();
922
+ }
923
+ });
924
+ let oe = _;
925
+ function Ye() {
926
+ return bt(O(w.env.dataDir, "tmp-"));
927
+ }
928
+ function ne(t, s, e = []) {
929
+ return Array.isArray(t) ? t.flatMap((o, n) => ne(o, s, [...e, n])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([o, n]) => ne(n, s, [...e, o])) : s(t) ? [e] : [];
930
+ }
931
+ function R(t) {
932
+ return t.filter((s) => s != null);
933
+ }
934
+ async function hs(t, s, e) {
935
+ if (!t || !B(t) || !X(t).isFile())
936
+ return null;
937
+ let o = e[t];
938
+ return o || (o = (async () => (await ps({
939
+ filePath: t,
940
+ fileName: s
941
+ })).data.filename)(), e[t] = o), o;
942
+ }
943
+ const ys = async (t, s) => {
944
+ const e = G(t), o = await Be({
945
+ name: We,
946
+ path: U("/uploads", e),
947
+ responseType: "stream",
948
+ method: "GET"
949
+ });
950
+ if (o.status >= 200 && o.status < 400) {
951
+ const n = It(s);
952
+ await Lt(o.data, n);
953
+ } else
954
+ throw new Error(`download asset failed ${o.status}`);
955
+ }, ws = async (t, s) => {
956
+ await Promise.all(
957
+ t.map(async (e) => {
958
+ try {
959
+ await ys(e, O(s, G(e)));
960
+ } catch (o) {
961
+ A.error(`Failed to export assets: ${e}, ${o}`);
962
+ }
963
+ })
964
+ );
965
+ };
966
+ function qe(t) {
967
+ return we.test(t) ? [t] : W.test(t) ? (Re.lastIndex = 0, Array.from(t.matchAll(Re)).map((e) => e[1]).filter((e) => !!e)) : [];
968
+ }
969
+ async function de(t, s, e) {
970
+ const { getFilename: o, exportAssets: n } = e, a = O(s, o(t));
971
+ if (M(L(a), { recursive: !0 }), te(a, H.stringify(t)), n) {
972
+ const r = ne(
973
+ t,
974
+ (i) => typeof i == "string" && (we.test(i) || W.test(i))
975
+ ).map((i) => {
976
+ const c = ye(t, i);
977
+ return qe(c);
978
+ }).flat().filter(Boolean);
979
+ await ws(r, L(a));
980
+ }
981
+ }
982
+ const Ue = new he({
983
+ max: 1e3,
984
+ ttl: 30 * 24 * 60 * 60 * 1e3
985
+ });
986
+ async function _e(t, s, e) {
987
+ var r;
988
+ const o = ne(
989
+ t,
990
+ (i) => typeof i == "string" && (we.test(i) || W.test(i))
991
+ ), n = Nt(2), a = o.map(
992
+ (i) => n(async () => {
993
+ try {
994
+ const c = ye(t, i), p = qe(c);
995
+ for (const u of p) {
996
+ const f = G(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f, v = Ue.get(y);
997
+ if (v) {
998
+ W.test(c) || Pe(t, i, v);
999
+ return;
1000
+ }
1001
+ const P = await hs(g, f, s);
1002
+ P && (W.test(c) || Pe(t, i, P), Ue.set(y, P));
1003
+ }
1004
+ } catch (c) {
1005
+ A.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
1006
+ }
1007
+ })
1008
+ ), l = await Promise.allSettled(a);
1009
+ (r = e.onFinish) == null || r.call(e, l);
1010
+ }
1011
+ async function Ss(t, {
1012
+ exportAssets: s,
1013
+ pageIds: e = "all",
1014
+ componentIds: o = "all",
1015
+ rawConfig: n,
1016
+ includeResources: a = !1
1017
+ } = {}) {
1018
+ var k, N, h, b, E, I;
1019
+ const l = e === "all" ? t.pageIds : e, r = Es({
1020
+ state: t,
1021
+ pageIds: l,
1022
+ componentIds: o === "all" ? Object.keys(t.components) : o
1023
+ }), i = (m, d) => {
1024
+ var S;
1025
+ return {
1026
+ id: m.id,
1027
+ name: m.name,
1028
+ isTemplateSection: m.isTemplateSection ?? !1,
1029
+ component: m.component,
1030
+ config: m.config,
1031
+ visibility: m.visibility,
1032
+ properties: ((S = m.locales) == null ? void 0 : S[d]) ?? {}
1033
+ };
1034
+ }, c = (m, d) => {
1035
+ var S;
1036
+ return {
1037
+ id: m.id,
1038
+ createdAt: m.createdAt,
1039
+ updatedAt: m.updatedAt,
1040
+ publishedAt: m.publishedAt,
1041
+ isPublic: m.isPublic ?? !0,
1042
+ isTemplate: m.isTemplate ?? !1,
1043
+ meta: ((S = m.locales) == null ? void 0 : S[d]) ?? {},
1044
+ sections: R(
1045
+ m.sectionIds.map((j) => {
1046
+ const D = m.sections[j];
1047
+ return D && i(D, d);
1048
+ })
1049
+ )
1050
+ };
1051
+ }, p = R(
1052
+ t.supportedLocales.map((m) => m.locale).flatMap(
1053
+ (m) => l.map((d) => {
1054
+ const S = t.pages[d];
1055
+ return S && {
1056
+ locale: m,
1057
+ slug: S.slug,
1058
+ page: c(S, m)
1059
+ };
1060
+ })
1061
+ )
1062
+ ), u = Ye(), f = O(u, "pages");
1063
+ M(f, { recursive: !0 });
1064
+ const g = O(u, "components");
1065
+ M(g, { recursive: !0 });
1066
+ for (const { locale: m, slug: d, page: S } of p)
1067
+ await de(S, f, {
1068
+ getFilename: () => `${ze(d) || "index"}.${m}.yml`,
1069
+ exportAssets: s
1070
+ });
1071
+ for (const m of r) {
1072
+ const d = (k = t.components[m]) == null ? void 0 : k.data;
1073
+ d && await de(d, g, {
1074
+ getFilename: (S) => `${S.name || "unnamed"}.${S.id}.yml`,
1075
+ exportAssets: s
1076
+ });
1077
+ }
1078
+ const y = O(u, ".blocklet/pages/pages.config.yml");
1079
+ M(L(y), { recursive: !0 });
1080
+ const v = {
1081
+ pages: R(
1082
+ l.map((m) => {
1083
+ const d = t.pages[m];
1084
+ return d && { id: m, slug: d.slug };
1085
+ })
1086
+ ),
1087
+ components: R(
1088
+ r.map((m) => {
1089
+ var S;
1090
+ const d = (S = t.components[m]) == null ? void 0 : S.data;
1091
+ return d && {
1092
+ id: m,
1093
+ name: d.name
1094
+ };
1095
+ })
1096
+ ),
1097
+ ...a ? {
1098
+ resources: {
1099
+ components: R(
1100
+ Object.keys(((N = t.resources) == null ? void 0 : N.components) || {}).map((m) => {
1101
+ var d, S, j, D;
1102
+ return {
1103
+ id: m,
1104
+ name: (D = (j = (S = (d = t.resources) == null ? void 0 : d.components) == null ? void 0 : S[m]) == null ? void 0 : j.component) == null ? void 0 : D.name
1105
+ };
1106
+ })
1107
+ )
1108
+ }
1109
+ } : {},
1110
+ supportedLocales: t.supportedLocales,
1111
+ config: t.config
1112
+ };
1113
+ te(y, H.stringify(v));
1114
+ const P = O(u, "config.source.json");
1115
+ if (n && te(P, JSON.stringify(n)), a) {
1116
+ const m = O(u, "resources"), d = O(m, "components");
1117
+ M(d, { recursive: !0 });
1118
+ for (const S of Object.keys(((h = t == null ? void 0 : t.resources) == null ? void 0 : h.components) ?? {})) {
1119
+ const j = (I = (E = (b = t.resources) == null ? void 0 : b.components) == null ? void 0 : E[S]) == null ? void 0 : I.component;
1120
+ j && await de(j, d, {
1121
+ getFilename: (D) => `${D.name || "unnamed"}.${D.id}.yml`,
1122
+ exportAssets: s
1123
+ });
1124
+ }
1125
+ }
1126
+ return u;
1127
+ }
1128
+ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
1129
+ var a, l, r;
1130
+ if (!B(t))
1131
+ return null;
1132
+ let o, n = !1;
1133
+ try {
1134
+ X(t).isDirectory() ? o = t : /\.(tgz|gz|tar)$/.test(t) && (n = !0, o = Ye(), await Rt({ file: t, C: o }));
1135
+ const i = me("**/.blocklet/pages/pages.config.yml", { cwd: o, absolute: !0 }).at(0), c = i && O(L(i), "../../pages"), p = i && O(L(i), "../../components"), u = i && O(L(i), "../../chunks");
1136
+ if (!i)
1137
+ return null;
1138
+ const f = H.parse(J(i).toString()), g = (h, b, E) => {
1139
+ let I = O(h, `${b}${E ? `.${E}` : ""}.yml`);
1140
+ return (!B(I) || !X(I).isFile()) && (I = O(h, b, `index${E ? `.${E}` : ""}.yml`), !B(I) || !X(I)) ? null : H.parse(J(I).toString());
1141
+ }, y = (h, b) => {
1142
+ try {
1143
+ const E = me(`*.${b}.yml`, { cwd: h, absolute: !0 })[0];
1144
+ return E ? H.parse(J(E).toString()) : null;
1145
+ } catch (E) {
1146
+ A.error("parse component error", E);
1147
+ }
1148
+ return null;
1149
+ }, v = R(
1150
+ f.pages.map(({ slug: h }) => {
1151
+ var m;
1152
+ const b = R(
1153
+ f.supportedLocales.map(({ locale: d }) => {
1154
+ const S = c ? g(c, ze(h), d) : void 0;
1155
+ if (S)
1156
+ return { locale: d, page: S };
1157
+ const j = c ? g(c, h, d) : void 0;
1158
+ return j && { locale: d, page: j };
1159
+ })
1160
+ ), E = (m = b[0]) == null ? void 0 : m.page;
1161
+ if (!E)
1162
+ return null;
1163
+ const I = E.sections.map((d) => {
1164
+ const S = d.id || Le();
1165
+ return {
1166
+ id: S,
1167
+ component: d.component,
1168
+ config: d.config,
1169
+ name: d.name,
1170
+ isTemplateSection: d.isTemplateSection ?? !1,
1171
+ visibility: d.visibility,
1172
+ locales: Object.fromEntries(
1173
+ R(
1174
+ b.map(({ locale: j, page: D }) => {
1175
+ const Ie = D.sections.find((st) => st.id === S);
1176
+ return Ie && [j, Ie.properties];
1177
+ })
1178
+ )
1179
+ )
1180
+ };
1181
+ });
1182
+ return {
1183
+ id: E.id || Le(),
1184
+ createdAt: E.createdAt,
1185
+ updatedAt: E.updatedAt,
1186
+ publishedAt: E.publishedAt,
1187
+ isPublic: E.isPublic ?? !0,
1188
+ isTemplate: E.isTemplate ?? !1,
1189
+ slug: h,
1190
+ sections: Object.fromEntries(I.map((d) => [d.id, d])),
1191
+ sectionIds: I.map((d) => d.id),
1192
+ locales: Object.fromEntries(b.map(({ locale: d, page: S }) => [d, S.meta]))
1193
+ };
1194
+ })
1195
+ ), P = p ? R(((a = f.components) == null ? void 0 : a.map(({ id: h }) => y(p, h))) ?? []) : [];
1196
+ if (s) {
1197
+ const h = (...b) => {
1198
+ A.info(`[${n ? G(t) : G(O(t, "../../../../"))}] importAssets:`, ...b);
1199
+ };
1200
+ try {
1201
+ h("wait image-bin api ready"), await Ut({
1202
+ resources: [`${yt(Kt)}/api/sdk/uploads`],
1203
+ validateStatus: (I) => I >= 200 && I <= 500
1204
+ }), h("image-bin api is ready");
1205
+ const b = {}, E = {};
1206
+ h("start to upload assets"), await Promise.allSettled([
1207
+ _e(P, b, {
1208
+ getFilePath: (I) => p && O(p, I),
1209
+ onFinish: (I) => {
1210
+ h(`upload ${I.length} component assets`);
1211
+ }
1212
+ }),
1213
+ _e(v, E, {
1214
+ getFilePath: (I, m) => {
1215
+ const d = ye(v, m.slice(0, 1));
1216
+ return c && O(c, L(d.slug), I);
1217
+ },
1218
+ onFinish: (I) => {
1219
+ h(`upload ${I.length} page assets`);
1220
+ }
1221
+ })
1222
+ ]), h("upload assets done"), Oe.gc && Oe.gc();
1223
+ } catch (b) {
1224
+ h("Error during asset import:", b);
1225
+ }
1226
+ }
1227
+ const k = {};
1228
+ if (e) {
1229
+ const h = i && O(L(i), "../../resources/components"), b = R(
1230
+ ((r = (l = f.resources) == null ? void 0 : l.components) == null ? void 0 : r.map(({ id: E }) => y(h, E))) ?? []
1231
+ );
1232
+ b.length > 0 && (k.components = Object.fromEntries(
1233
+ b.map((E, I) => [E.id, { index: I, component: E }])
1234
+ ));
1235
+ }
1236
+ const N = {};
1237
+ if (u && B(u)) {
1238
+ const h = Et(u);
1239
+ for (const b of h)
1240
+ N[b] = O(u, b);
1241
+ }
1242
+ return {
1243
+ supportedLocales: f.supportedLocales,
1244
+ pageIds: v.map((h) => h.id),
1245
+ components: Object.fromEntries(P.map((h, b) => [h.id, { index: b, data: h }])),
1246
+ pages: Object.fromEntries(v.map((h) => [h.id, h])),
1247
+ config: f.config || {},
1248
+ resources: k,
1249
+ chunks: N
1250
+ };
1251
+ } finally {
1252
+ n && o && Ve(o, { force: !0, recursive: !0 });
1253
+ }
1254
+ }
1255
+ async function Me(t, s, {
1256
+ pages: e,
1257
+ pageMergeMode: o = "byUpdateTime",
1258
+ deletePages: n = !1,
1259
+ publishMode: a = void 0
1260
+ } = {}) {
1261
+ try {
1262
+ a && ts(a);
1263
+ } catch (p) {
1264
+ A.error("clear preload page cache error", { error: p });
1265
+ }
1266
+ const { pageIds: l, pages: r, supportedLocales: i } = t;
1267
+ for (const p of e ?? l) {
1268
+ const u = r[p];
1269
+ if (!u) {
1270
+ const f = s.pageIds.indexOf(p);
1271
+ f !== -1 && n && (s.pageIds.splice(f, 1), delete s.pages[p]);
1272
+ continue;
1273
+ }
1274
+ if (s.pageIds.includes(u.id)) {
1275
+ if (o === "replace")
1276
+ s.pages[u.id] = u;
1277
+ else if (o === "byUpdateTime") {
1278
+ const f = s.pages[u.id];
1279
+ (!f || u.updatedAt && u.updatedAt > f.updatedAt) && (s.pages[u.id] = u);
1280
+ }
1281
+ } else
1282
+ s.pageIds.push(u.id), s.pages[u.id] = u;
1283
+ }
1284
+ if (n && !e)
1285
+ for (const p of s.pageIds)
1286
+ t.pageIds.includes(p) || delete s.pages[p], s.pageIds = [...s.pageIds].filter((u) => t.pageIds.includes(u));
1287
+ if (s.supportedLocales.splice(0, s.supportedLocales.length), s.supportedLocales.push(...jt(i)), n)
1288
+ for (const p of Object.keys(s.components))
1289
+ delete s.components[p];
1290
+ let c = JSON.parse(JSON.stringify(t.components));
1291
+ c = Object.fromEntries(
1292
+ await Promise.all(
1293
+ Object.entries(c).map(async ([p, u]) => {
1294
+ const f = await Xe(u == null ? void 0 : u.data);
1295
+ return [
1296
+ p,
1297
+ {
1298
+ ...u,
1299
+ data: f
1300
+ }
1301
+ ];
1302
+ })
1303
+ )
1304
+ ), 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 || {}));
1305
+ }
1306
+ const Xe = ae(
1307
+ async (t) => {
1308
+ var s;
1309
+ if (!Ct(t == null ? void 0 : t.properties))
1310
+ return t;
1311
+ if (((s = t == null ? void 0 : t.renderer) == null ? void 0 : s.type) === "react-component") {
1312
+ const { script: e } = (t == null ? void 0 : t.renderer) || {};
1313
+ if (e)
1314
+ try {
1315
+ const o = await is(e, "PROPERTIES_SCHEMA", t.id);
1316
+ o && o.length > 0 && t && (t.properties = {}, o.forEach((n, a) => {
1317
+ t != null && t.properties && (t.properties[n.id] = {
1318
+ index: a,
1319
+ data: n
1320
+ });
1321
+ }));
1322
+ } catch (o) {
1323
+ A.error("checkPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: o });
1324
+ }
1325
+ }
1326
+ return t;
1327
+ },
1328
+ {
1329
+ keyGenerator: (t) => {
1330
+ var l;
1331
+ const s = (t == null ? void 0 : t.id) || "", e = (t == null ? void 0 : t.name) || "", o = ((l = t == null ? void 0 : t.renderer) == null ? void 0 : l.type) || "", n = (t == null ? void 0 : t.properties) || {}, a = ie("md5").update(JSON.stringify(n)).digest("hex");
1332
+ return JSON.stringify(["checkPropertiesFromCode", s, e, o, a]);
1333
+ },
1334
+ lruOptions: {
1335
+ max: 100,
1336
+ ttl: 1e3 * 60 * 60
1337
+ }
1338
+ }
1339
+ );
1340
+ function Es({
1341
+ state: t,
1342
+ pageIds: s = [],
1343
+ componentIds: e = []
1344
+ }) {
1345
+ var l;
1346
+ const o = (r, i = /* @__PURE__ */ new Set()) => (Array.isArray(r) && r.forEach((c) => o(c, i)), r && typeof r == "object" && (typeof r.componentId == "string" && i.add(r.componentId), Object.values(r).forEach((c) => o(c, i))), i), n = new Set(e);
1347
+ for (const r of s) {
1348
+ const i = t.pages[r];
1349
+ o(i, n);
1350
+ }
1351
+ const a = [...n];
1352
+ for (; a.length; ) {
1353
+ const r = a.shift();
1354
+ n.has(r) || n.add(r);
1355
+ const i = (l = t.components[r]) == null ? void 0 : l.data;
1356
+ if (i)
1357
+ for (const c of o(i))
1358
+ n.has(c) || a.push(c);
1359
+ }
1360
+ return [...n];
1361
+ }
1362
+ let re, V, Se, Ee, be;
1363
+ function Ze() {
1364
+ return re = (async () => {
1365
+ const t = ht({
1366
+ types: [
1367
+ { did: We, type: De },
1368
+ { did: ls, type: De }
1369
+ ]
1370
+ });
1371
+ V = (await Promise.all(
1372
+ t.map(async (e) => {
1373
+ const o = e.path ? await Qe(e.path, { importAssets: !1 }) : void 0;
1374
+ return o ? { blockletId: e.did, state: o, blockletTitle: e.title } : void 0;
1375
+ })
1376
+ )).filter((e) => !!e), Se = V.reduce(
1377
+ (e, o) => Object.assign(
1378
+ e,
1379
+ Object.fromEntries(
1380
+ Object.values(o.state.pages).map((n) => n ? [n == null ? void 0 : n.id, { page: n, blockletId: o.blockletId }] : [])
1381
+ )
1382
+ ),
1383
+ {}
1384
+ );
1385
+ const s = V.reduce(
1386
+ (e, o) => Object.assign(
1387
+ e,
1388
+ Object.fromEntries(
1389
+ Object.values(o.state.components).map((n) => [n.data.id, { blockletId: o.blockletId, component: n.data }])
1390
+ )
1391
+ ),
1392
+ {}
1393
+ );
1394
+ Ee = Object.fromEntries(
1395
+ await Promise.all(
1396
+ Object.entries(s).map(async ([e, o]) => {
1397
+ const n = await Xe(o.component);
1398
+ return [
1399
+ e,
1400
+ {
1401
+ ...o,
1402
+ component: n
1403
+ }
1404
+ ];
1405
+ })
1406
+ )
1407
+ ), be = V.reduce((e, o) => Object.assign(e, o.state.chunks), {});
1408
+ })(), re;
1409
+ }
1410
+ function bs(t) {
1411
+ const s = Ge(
1412
+ async () => {
1413
+ await Ze().catch((e) => {
1414
+ A.error("load resource states error", { error: e });
1415
+ }), await (t == null ? void 0 : t({
1416
+ states: V,
1417
+ pages: Se,
1418
+ components: Ee,
1419
+ chunks: be
1420
+ }));
1421
+ },
1422
+ 3e3,
1423
+ { leading: !1, trailing: !0 }
1424
+ );
1425
+ return s(), w.events.on(w.Events.componentAdded, s), w.events.on(w.Events.componentRemoved, s), w.events.on(w.Events.componentStarted, s), w.events.on(w.Events.componentStopped, s), w.events.on(w.Events.componentUpdated, s), w.events.on(fe, s), () => {
1426
+ w.events.off(w.Events.componentAdded, s), w.events.off(w.Events.componentRemoved, s), w.events.off(w.Events.componentStarted, s), w.events.off(w.Events.componentStopped, s), w.events.off(w.Events.componentUpdated, s), w.events.off(fe, s);
1427
+ };
1428
+ }
1429
+ const et = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), Z = globalThis;
1430
+ var Fe;
1431
+ (Fe = Z[et]) == null || Fe.call(Z);
1432
+ Z[et] = bs(async ({ pages: t, components: s }) => {
1433
+ const { projectIds: e } = oe;
1434
+ await Promise.all(
1435
+ e.map(async (o) => {
1436
+ const n = oe.shared(o);
1437
+ n.syncedStore.resources.pages = t;
1438
+ const a = await F.findByPk(o);
1439
+ if (a != null && a.useAllResources)
1440
+ n.syncedStore.resources.components = s;
1441
+ else {
1442
+ const r = (await ce.findAll({ where: { projectId: o } })).map((c) => c.componentId), i = Object.fromEntries(
1443
+ Object.entries(s || {}).filter(([c]) => r.includes(c))
1444
+ );
1445
+ n.syncedStore.resources.components = i;
1446
+ }
1447
+ A.info(`update [${o}] resource states:`, {
1448
+ pages: Object.keys(n.syncedStore.resources.pages || {}).length,
1449
+ components: Object.keys(n.syncedStore.resources.components || {}).length
1450
+ });
1451
+ })
1452
+ );
1453
+ });
1454
+ async function po() {
1455
+ A.info("trigger reload all project resource"), w.events.emit(fe);
1456
+ }
1457
+ async function tt({
1458
+ ensureLoaded: t = !0
1459
+ } = {}) {
1460
+ return t && (re ?? (re = Ze()), await re), { states: V, pages: Se, components: Ee, chunks: be };
1461
+ }
1462
+ export {
1463
+ We as C,
1464
+ Ne as G,
1465
+ F as P,
1466
+ De as R,
1467
+ oe as S,
1468
+ tt as a,
1469
+ ao as b,
1470
+ Zt as c,
1471
+ es as d,
1472
+ ts as e,
1473
+ ss as f,
1474
+ ro as g,
1475
+ os as h,
1476
+ no as i,
1477
+ se as j,
1478
+ io as k,
1479
+ A as l,
1480
+ is as m,
1481
+ Le as n,
1482
+ q as o,
1483
+ co as p,
1484
+ lo as q,
1485
+ Qe as r,
1486
+ Me as s,
1487
+ Ss as t,
1488
+ bs as u,
1489
+ po as v
1490
+ };