@blocklet/pages-kit-inner-components 0.5.56 → 0.6.1

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