@finesoft/front 0.1.3 → 0.1.12

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,1214 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/browser.ts
21
+ var browser_exports = {};
22
+ __export(browser_exports, {
23
+ ACTION_KINDS: () => ACTION_KINDS,
24
+ ActionDispatcher: () => ActionDispatcher,
25
+ BaseController: () => BaseController,
26
+ BaseLogger: () => BaseLogger,
27
+ CompositeLogger: () => CompositeLogger,
28
+ CompositeLoggerFactory: () => CompositeLoggerFactory,
29
+ ConsoleLogger: () => ConsoleLogger,
30
+ ConsoleLoggerFactory: () => ConsoleLoggerFactory,
31
+ Container: () => Container,
32
+ DEP_KEYS: () => DEP_KEYS,
33
+ Framework: () => Framework,
34
+ History: () => History,
35
+ HttpClient: () => HttpClient,
36
+ HttpError: () => HttpError,
37
+ IntentDispatcher: () => IntentDispatcher,
38
+ LruMap: () => LruMap,
39
+ PrefetchedIntents: () => PrefetchedIntents,
40
+ Router: () => Router,
41
+ buildUrl: () => buildUrl,
42
+ createPrefetchedIntentsFromDom: () => createPrefetchedIntentsFromDom,
43
+ defineRoutes: () => defineRoutes,
44
+ deserializeServerData: () => deserializeServerData,
45
+ generateUuid: () => generateUuid,
46
+ getBaseUrl: () => getBaseUrl,
47
+ isCompoundAction: () => isCompoundAction,
48
+ isExternalUrlAction: () => isExternalUrlAction,
49
+ isFlowAction: () => isFlowAction,
50
+ isNone: () => isNone,
51
+ isSome: () => isSome,
52
+ makeDependencies: () => makeDependencies,
53
+ makeExternalUrlAction: () => makeExternalUrlAction,
54
+ makeFlowAction: () => makeFlowAction,
55
+ mapEach: () => mapEach,
56
+ pipe: () => pipe,
57
+ pipeAsync: () => pipeAsync,
58
+ registerActionHandlers: () => registerActionHandlers,
59
+ registerExternalUrlHandler: () => registerExternalUrlHandler,
60
+ registerFlowActionHandler: () => registerFlowActionHandler,
61
+ removeHost: () => removeHost,
62
+ removeQueryParams: () => removeQueryParams,
63
+ removeScheme: () => removeScheme,
64
+ resetFilterCache: () => resetFilterCache,
65
+ shouldLog: () => shouldLog,
66
+ stableStringify: () => stableStringify,
67
+ startBrowserApp: () => startBrowserApp,
68
+ tryScroll: () => tryScroll
69
+ });
70
+ module.exports = __toCommonJS(browser_exports);
71
+
72
+ // ../core/src/actions/types.ts
73
+ var ACTION_KINDS = {
74
+ FLOW: "flow",
75
+ EXTERNAL_URL: "externalUrl",
76
+ COMPOUND: "compound"
77
+ };
78
+ function isFlowAction(action) {
79
+ return action.kind === ACTION_KINDS.FLOW;
80
+ }
81
+ function isExternalUrlAction(action) {
82
+ return action.kind === ACTION_KINDS.EXTERNAL_URL;
83
+ }
84
+ function isCompoundAction(action) {
85
+ return action.kind === ACTION_KINDS.COMPOUND;
86
+ }
87
+ function makeFlowAction(url, presentationContext) {
88
+ return { kind: ACTION_KINDS.FLOW, url, presentationContext };
89
+ }
90
+ function makeExternalUrlAction(url) {
91
+ return { kind: ACTION_KINDS.EXTERNAL_URL, url };
92
+ }
93
+
94
+ // ../core/src/actions/dispatcher.ts
95
+ var ActionDispatcher = class {
96
+ handlers = /* @__PURE__ */ new Map();
97
+ wiredActions = /* @__PURE__ */ new Set();
98
+ /** 注册指定 kind 的 handler(防止重复注册) */
99
+ onAction(kind, handler) {
100
+ if (this.wiredActions.has(kind)) {
101
+ console.warn(
102
+ `[ActionDispatcher] kind="${kind}" already registered, skipping`
103
+ );
104
+ return;
105
+ }
106
+ this.wiredActions.add(kind);
107
+ this.handlers.set(kind, handler);
108
+ }
109
+ /** 执行一个 Action(CompoundAction 递归展开) */
110
+ async perform(action) {
111
+ if (isCompoundAction(action)) {
112
+ for (const subAction of action.actions) {
113
+ await this.perform(subAction);
114
+ }
115
+ return;
116
+ }
117
+ const handler = this.handlers.get(action.kind);
118
+ if (!handler) {
119
+ console.warn(
120
+ `[ActionDispatcher] No handler for kind="${action.kind}"`
121
+ );
122
+ return;
123
+ }
124
+ await handler(action);
125
+ }
126
+ };
127
+
128
+ // ../core/src/intents/dispatcher.ts
129
+ var IntentDispatcher = class {
130
+ controllers = /* @__PURE__ */ new Map();
131
+ /** 注册一个 IntentController */
132
+ register(controller) {
133
+ this.controllers.set(controller.intentId, controller);
134
+ }
135
+ /** 分发 Intent 到对应 Controller */
136
+ async dispatch(intent, container) {
137
+ const controller = this.controllers.get(intent.id);
138
+ if (!controller) {
139
+ throw new Error(
140
+ `[IntentDispatcher] No controller for "${intent.id}". Registered: [${Array.from(this.controllers.keys()).join(", ")}]`
141
+ );
142
+ }
143
+ return controller.perform(intent, container);
144
+ }
145
+ /** 检查是否已注册某个 Intent */
146
+ has(intentId) {
147
+ return this.controllers.has(intentId);
148
+ }
149
+ };
150
+
151
+ // ../core/src/dependencies/container.ts
152
+ var Container = class {
153
+ registrations = /* @__PURE__ */ new Map();
154
+ /** 注册依赖(默认单例) */
155
+ register(key, factory, singleton = true) {
156
+ this.registrations.set(key, { factory, singleton });
157
+ return this;
158
+ }
159
+ /** 解析依赖 */
160
+ resolve(key) {
161
+ const reg = this.registrations.get(key);
162
+ if (!reg) {
163
+ throw new Error(`[Container] No registration for key: "${key}"`);
164
+ }
165
+ if (reg.singleton) {
166
+ if (reg.instance === void 0) {
167
+ reg.instance = reg.factory();
168
+ }
169
+ return reg.instance;
170
+ }
171
+ return reg.factory();
172
+ }
173
+ /** 检查是否已注册 */
174
+ has(key) {
175
+ return this.registrations.has(key);
176
+ }
177
+ /** 销毁容器,清除所有缓存 */
178
+ dispose() {
179
+ for (const reg of this.registrations.values()) {
180
+ reg.instance = void 0;
181
+ }
182
+ this.registrations.clear();
183
+ }
184
+ };
185
+
186
+ // ../core/src/logger/base.ts
187
+ var BaseLogger = class {
188
+ category;
189
+ constructor(category) {
190
+ this.category = category;
191
+ }
192
+ };
193
+
194
+ // ../core/src/logger/local-storage-filter.ts
195
+ var LEVEL_TO_NUM = {
196
+ "*": 4,
197
+ debug: 4,
198
+ info: 3,
199
+ warn: 2,
200
+ error: 1,
201
+ off: 0,
202
+ "": 0
203
+ };
204
+ var cachedRules;
205
+ var cachedRaw;
206
+ function parseRules() {
207
+ if (typeof globalThis.localStorage === "undefined") {
208
+ return {};
209
+ }
210
+ let raw;
211
+ try {
212
+ raw = globalThis.localStorage.getItem("onyxLog");
213
+ } catch {
214
+ return {};
215
+ }
216
+ if (!raw) return {};
217
+ if (raw === cachedRaw && cachedRules) return cachedRules;
218
+ cachedRaw = raw;
219
+ const rules = {};
220
+ const parts = raw.split(",");
221
+ for (const part of parts) {
222
+ const [name, level] = part.trim().split("=");
223
+ if (!name || level === void 0) continue;
224
+ const num = LEVEL_TO_NUM[level.toLowerCase()] ?? void 0;
225
+ if (num === void 0) continue;
226
+ if (name === "*") {
227
+ rules.defaultLevel = num;
228
+ } else {
229
+ rules.named ??= {};
230
+ rules.named[name] = num;
231
+ }
232
+ }
233
+ cachedRules = rules;
234
+ return rules;
235
+ }
236
+ function shouldLog(name, level) {
237
+ const rules = parseRules();
238
+ if (rules.defaultLevel === void 0 && !rules.named) {
239
+ return true;
240
+ }
241
+ const currentNum = LEVEL_TO_NUM[level] ?? 4;
242
+ if (rules.named?.[name] !== void 0) {
243
+ return currentNum <= rules.named[name];
244
+ }
245
+ if (rules.defaultLevel !== void 0) {
246
+ return currentNum <= rules.defaultLevel;
247
+ }
248
+ return true;
249
+ }
250
+ function resetFilterCache() {
251
+ cachedRules = void 0;
252
+ cachedRaw = void 0;
253
+ }
254
+
255
+ // ../core/src/logger/console.ts
256
+ var ConsoleLogger = class extends BaseLogger {
257
+ debug(...args) {
258
+ if (shouldLog(this.category, "debug")) {
259
+ console.debug(`[${this.category}]`, ...args);
260
+ }
261
+ return "";
262
+ }
263
+ info(...args) {
264
+ if (shouldLog(this.category, "info")) {
265
+ console.info(`[${this.category}]`, ...args);
266
+ }
267
+ return "";
268
+ }
269
+ warn(...args) {
270
+ if (shouldLog(this.category, "warn")) {
271
+ console.warn(`[${this.category}]`, ...args);
272
+ }
273
+ return "";
274
+ }
275
+ error(...args) {
276
+ console.error(`[${this.category}]`, ...args);
277
+ return "";
278
+ }
279
+ };
280
+ var ConsoleLoggerFactory = class {
281
+ loggerFor(category) {
282
+ return new ConsoleLogger(category);
283
+ }
284
+ };
285
+
286
+ // ../core/src/dependencies/make-dependencies.ts
287
+ var DEP_KEYS = {
288
+ LOGGER: "logger",
289
+ LOGGER_FACTORY: "loggerFactory",
290
+ NET: "net",
291
+ LOCALE: "locale",
292
+ STORAGE: "storage",
293
+ FEATURE_FLAGS: "featureFlags",
294
+ METRICS: "metrics",
295
+ FETCH: "fetch"
296
+ };
297
+ var DefaultLocale = class {
298
+ language = "en";
299
+ storefront = "us";
300
+ setActiveLocale(language, storefront) {
301
+ this.language = language;
302
+ this.storefront = storefront;
303
+ }
304
+ };
305
+ var MemoryStorage = class {
306
+ store = /* @__PURE__ */ new Map();
307
+ get(key) {
308
+ return this.store.get(key);
309
+ }
310
+ set(key, value) {
311
+ this.store.set(key, value);
312
+ }
313
+ delete(key) {
314
+ this.store.delete(key);
315
+ }
316
+ };
317
+ var DefaultFeatureFlags = class {
318
+ flags;
319
+ constructor(flags = {}) {
320
+ this.flags = flags;
321
+ }
322
+ isEnabled(key) {
323
+ return this.flags[key] === true;
324
+ }
325
+ getString(key) {
326
+ const v = this.flags[key];
327
+ return typeof v === "string" ? v : void 0;
328
+ }
329
+ getNumber(key) {
330
+ const v = this.flags[key];
331
+ return typeof v === "number" ? v : void 0;
332
+ }
333
+ };
334
+ var ConsoleMetrics = class {
335
+ recordPageView(page, fields) {
336
+ console.info(`[Metrics:PageView] ${page}`, fields ?? "");
337
+ }
338
+ recordEvent(name, fields) {
339
+ console.info(`[Metrics:Event] ${name}`, fields ?? "");
340
+ }
341
+ };
342
+ function makeDependencies(container, options = {}) {
343
+ const {
344
+ fetch: fetchFn = globalThis.fetch?.bind(globalThis),
345
+ language = "en",
346
+ storefront = "us",
347
+ featureFlags = {}
348
+ } = options;
349
+ const loggerFactory = new ConsoleLoggerFactory();
350
+ container.register(
351
+ DEP_KEYS.LOGGER_FACTORY,
352
+ () => loggerFactory
353
+ );
354
+ container.register(
355
+ DEP_KEYS.LOGGER,
356
+ () => loggerFactory.loggerFor("framework")
357
+ );
358
+ container.register(DEP_KEYS.NET, () => ({
359
+ fetch: (url, opts) => fetchFn(url, opts)
360
+ }));
361
+ container.register(DEP_KEYS.LOCALE, () => {
362
+ const locale = new DefaultLocale();
363
+ locale.setActiveLocale(language, storefront);
364
+ return locale;
365
+ });
366
+ container.register(DEP_KEYS.STORAGE, () => new MemoryStorage());
367
+ container.register(
368
+ DEP_KEYS.FEATURE_FLAGS,
369
+ () => new DefaultFeatureFlags(featureFlags)
370
+ );
371
+ container.register(
372
+ DEP_KEYS.METRICS,
373
+ () => new ConsoleMetrics()
374
+ );
375
+ container.register(DEP_KEYS.FETCH, () => fetchFn);
376
+ }
377
+
378
+ // ../core/src/router/router.ts
379
+ var Router = class {
380
+ routes = [];
381
+ /** 添加路由规则 */
382
+ add(pattern, intentId) {
383
+ const paramNames = [];
384
+ const regexStr = pattern.replace(
385
+ /\/:(\w+)(\?)?/g,
386
+ (_, name, optional) => {
387
+ paramNames.push(name);
388
+ return optional ? "(?:/([^/]+))?" : "/([^/]+)";
389
+ }
390
+ );
391
+ this.routes.push({
392
+ pattern,
393
+ intentId,
394
+ regex: new RegExp(`^${regexStr}/?$`),
395
+ paramNames
396
+ });
397
+ return this;
398
+ }
399
+ /** 解析 URL → RouteMatch */
400
+ resolve(urlOrPath) {
401
+ const path = this.extractPath(urlOrPath);
402
+ const queryParams = this.extractQueryParams(urlOrPath);
403
+ for (const route of this.routes) {
404
+ const match = path.match(route.regex);
405
+ if (match) {
406
+ const params = {};
407
+ route.paramNames.forEach((name, index) => {
408
+ const value = match[index + 1];
409
+ if (value) params[name] = value;
410
+ });
411
+ for (const [k, v] of Object.entries(queryParams)) {
412
+ if (!(k in params)) params[k] = v;
413
+ }
414
+ return {
415
+ intent: { id: route.intentId, params },
416
+ action: makeFlowAction(urlOrPath)
417
+ };
418
+ }
419
+ }
420
+ return null;
421
+ }
422
+ /** 获取所有已注册的路由 */
423
+ getRoutes() {
424
+ return this.routes.map((r) => `${r.pattern} \u2192 ${r.intentId}`);
425
+ }
426
+ extractPath(url) {
427
+ try {
428
+ const parsed = new URL(url, "http://localhost");
429
+ return parsed.pathname;
430
+ } catch {
431
+ return url.split("?")[0].split("#")[0];
432
+ }
433
+ }
434
+ extractQueryParams(url) {
435
+ try {
436
+ const parsed = new URL(url, "http://localhost");
437
+ const params = {};
438
+ parsed.searchParams.forEach((v, k) => {
439
+ params[k] = v;
440
+ });
441
+ return params;
442
+ } catch {
443
+ return {};
444
+ }
445
+ }
446
+ };
447
+
448
+ // ../core/src/logger/composite.ts
449
+ var CompositeLoggerFactory = class {
450
+ constructor(factories) {
451
+ this.factories = factories;
452
+ }
453
+ loggerFor(name) {
454
+ return new CompositeLogger(
455
+ this.factories.map((f) => f.loggerFor(name))
456
+ );
457
+ }
458
+ };
459
+ var CompositeLogger = class {
460
+ constructor(loggers) {
461
+ this.loggers = loggers;
462
+ }
463
+ debug(...args) {
464
+ return this.callAll("debug", args);
465
+ }
466
+ info(...args) {
467
+ return this.callAll("info", args);
468
+ }
469
+ warn(...args) {
470
+ return this.callAll("warn", args);
471
+ }
472
+ error(...args) {
473
+ return this.callAll("error", args);
474
+ }
475
+ callAll(method, args) {
476
+ for (const logger of this.loggers) {
477
+ logger[method](...args);
478
+ }
479
+ return "";
480
+ }
481
+ };
482
+
483
+ // ../core/src/prefetched-intents/stable-stringify.ts
484
+ function stableStringify(obj) {
485
+ if (obj === null || obj === void 0) return String(obj);
486
+ if (typeof obj !== "object") return JSON.stringify(obj);
487
+ if (Array.isArray(obj)) {
488
+ return "[" + obj.map(stableStringify).join(",") + "]";
489
+ }
490
+ const keys = Object.keys(obj).sort();
491
+ const parts = keys.filter((k) => obj[k] !== void 0).map(
492
+ (k) => JSON.stringify(k) + ":" + stableStringify(obj[k])
493
+ );
494
+ return "{" + parts.join(",") + "}";
495
+ }
496
+
497
+ // ../core/src/prefetched-intents/prefetched-intents.ts
498
+ var PrefetchedIntents = class _PrefetchedIntents {
499
+ intents;
500
+ constructor(intents) {
501
+ this.intents = intents;
502
+ }
503
+ /** 从 PrefetchedIntent 数组创建缓存实例 */
504
+ static fromArray(items) {
505
+ const map = /* @__PURE__ */ new Map();
506
+ for (const item of items) {
507
+ if (item.intent && item.data !== void 0) {
508
+ const key = stableStringify(item.intent);
509
+ map.set(key, item.data);
510
+ }
511
+ }
512
+ return new _PrefetchedIntents(map);
513
+ }
514
+ /** 创建空缓存实例 */
515
+ static empty() {
516
+ return new _PrefetchedIntents(/* @__PURE__ */ new Map());
517
+ }
518
+ /**
519
+ * 获取缓存的 Intent 结果(一次性使用)。
520
+ * 命中后从缓存中删除。
521
+ */
522
+ get(intent) {
523
+ const key = stableStringify(intent);
524
+ const data = this.intents.get(key);
525
+ if (data !== void 0) {
526
+ this.intents.delete(key);
527
+ return data;
528
+ }
529
+ return void 0;
530
+ }
531
+ /** 检查缓存中是否有某个 Intent 的数据 */
532
+ has(intent) {
533
+ return this.intents.has(stableStringify(intent));
534
+ }
535
+ /** 缓存中的条目数 */
536
+ get size() {
537
+ return this.intents.size;
538
+ }
539
+ };
540
+
541
+ // ../core/src/framework.ts
542
+ var Framework = class _Framework {
543
+ container;
544
+ intentDispatcher;
545
+ actionDispatcher;
546
+ router;
547
+ prefetchedIntents;
548
+ constructor(container, prefetchedIntents) {
549
+ this.container = container;
550
+ this.intentDispatcher = new IntentDispatcher();
551
+ this.actionDispatcher = new ActionDispatcher();
552
+ this.router = new Router();
553
+ this.prefetchedIntents = prefetchedIntents;
554
+ }
555
+ /** 创建并初始化 Framework 实例 */
556
+ static create(config = {}) {
557
+ const container = new Container();
558
+ makeDependencies(container, config);
559
+ const fw = new _Framework(
560
+ container,
561
+ config.prefetchedIntents ?? PrefetchedIntents.empty()
562
+ );
563
+ config.setupRoutes?.(fw.router);
564
+ return fw;
565
+ }
566
+ /** 分发 Intent — 获取页面数据 */
567
+ async dispatch(intent) {
568
+ const logger = this.container.resolve(DEP_KEYS.LOGGER);
569
+ const cached = this.prefetchedIntents.get(intent);
570
+ if (cached !== void 0) {
571
+ logger.debug(
572
+ `[Framework] re-using prefetched intent response for: ${intent.id}`,
573
+ intent.params
574
+ );
575
+ return cached;
576
+ }
577
+ logger.debug(
578
+ `[Framework] dispatch intent: ${intent.id}`,
579
+ intent.params
580
+ );
581
+ return this.intentDispatcher.dispatch(intent, this.container);
582
+ }
583
+ /** 执行 Action — 处理用户交互 */
584
+ async perform(action) {
585
+ const logger = this.container.resolve(DEP_KEYS.LOGGER);
586
+ logger.debug(`[Framework] perform action: ${action.kind}`);
587
+ return this.actionDispatcher.perform(action);
588
+ }
589
+ /** 路由 URL — 将 URL 解析为 Intent + Action */
590
+ routeUrl(url) {
591
+ return this.router.resolve(url);
592
+ }
593
+ /** 记录页面访问事件 */
594
+ didEnterPage(page) {
595
+ const metrics = this.container.resolve(
596
+ DEP_KEYS.METRICS
597
+ );
598
+ metrics.recordPageView(page.pageType, {
599
+ pageId: page.id,
600
+ title: page.title
601
+ });
602
+ }
603
+ /** 注册 Action 处理器 */
604
+ onAction(kind, handler) {
605
+ this.actionDispatcher.onAction(kind, handler);
606
+ }
607
+ /** 注册 Intent Controller */
608
+ registerIntent(controller) {
609
+ this.intentDispatcher.register(controller);
610
+ }
611
+ /** 销毁 Framework 实例 */
612
+ dispose() {
613
+ this.container.dispose();
614
+ }
615
+ };
616
+
617
+ // ../core/src/http/client.ts
618
+ var HttpError = class extends Error {
619
+ constructor(status, statusText, body) {
620
+ super(`HTTP ${status}: ${statusText}`);
621
+ this.status = status;
622
+ this.statusText = statusText;
623
+ this.body = body;
624
+ this.name = "HttpError";
625
+ }
626
+ };
627
+ var HttpClient = class {
628
+ baseUrl;
629
+ defaultHeaders;
630
+ fetchFn;
631
+ constructor(config) {
632
+ this.baseUrl = config.baseUrl;
633
+ this.defaultHeaders = config.defaultHeaders ?? {};
634
+ this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
635
+ }
636
+ /** GET 请求,返回解析后的 JSON */
637
+ async get(path, params) {
638
+ return this.request("GET", path, { params });
639
+ }
640
+ /** POST 请求,自动序列化 body 为 JSON */
641
+ async post(path, body, params) {
642
+ return this.request("POST", path, { body, params });
643
+ }
644
+ /** PUT 请求 */
645
+ async put(path, body, params) {
646
+ return this.request("PUT", path, { body, params });
647
+ }
648
+ /** DELETE 请求 */
649
+ async del(path, params) {
650
+ return this.request("DELETE", path, { params });
651
+ }
652
+ /**
653
+ * 底层请求方法 — 子类可覆写以自定义行为
654
+ *
655
+ * 自动处理:
656
+ * - URL 拼接 (baseUrl + path + params)
657
+ * - 默认 headers 合并
658
+ * - JSON body 序列化
659
+ * - 响应 JSON 解析
660
+ * - 非 2xx 状态码抛出 HttpError
661
+ */
662
+ async request(method, path, options) {
663
+ const url = this.buildUrl(path, options?.params);
664
+ const headers = {
665
+ ...this.defaultHeaders,
666
+ ...options?.headers
667
+ };
668
+ const init = { method, headers };
669
+ if (options?.body !== void 0) {
670
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
671
+ init.body = JSON.stringify(options.body);
672
+ }
673
+ const response = await this.fetchFn(url, init);
674
+ if (!response.ok) {
675
+ const body = await response.text().catch(() => void 0);
676
+ throw new HttpError(response.status, response.statusText, body);
677
+ }
678
+ return response.json();
679
+ }
680
+ /** 构建完整 URL — 子类可覆写以自定义 URL 拼接逻辑 */
681
+ buildUrl(path, params) {
682
+ const base = this.baseUrl.endsWith("/") ? this.baseUrl.slice(0, -1) : this.baseUrl;
683
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
684
+ const url = new URL(`${base}${normalizedPath}`, "http://placeholder");
685
+ if (params) {
686
+ for (const [k, v] of Object.entries(params)) {
687
+ url.searchParams.set(k, v);
688
+ }
689
+ }
690
+ if (this.baseUrl.startsWith("http")) {
691
+ return url.toString();
692
+ }
693
+ return `${url.pathname}${url.search}`;
694
+ }
695
+ };
696
+
697
+ // ../core/src/intents/base-controller.ts
698
+ var BaseController = class {
699
+ /**
700
+ * 错误回退 — 子类可选覆写
701
+ *
702
+ * 当 execute() 抛出异常时调用。
703
+ * 默认行为: 重新抛出原始错误。
704
+ *
705
+ * @param params - Intent 参数
706
+ * @param error - execute() 抛出的错误
707
+ * @returns 回退数据
708
+ */
709
+ fallback(params, error) {
710
+ throw error;
711
+ }
712
+ /**
713
+ * IntentController.perform() 实现
714
+ *
715
+ * 自动 try/catch → fallback 模式。
716
+ */
717
+ async perform(intent, container) {
718
+ const params = intent.params ?? {};
719
+ try {
720
+ return await this.execute(params, container);
721
+ } catch (e) {
722
+ return this.fallback(
723
+ params,
724
+ e instanceof Error ? e : new Error(String(e))
725
+ );
726
+ }
727
+ }
728
+ };
729
+
730
+ // ../core/src/data/mapper.ts
731
+ function pipe(...mappers) {
732
+ return (input) => mappers.reduce((acc, mapper) => mapper(acc), input);
733
+ }
734
+ function pipeAsync(...mappers) {
735
+ return async (input) => {
736
+ let acc = input;
737
+ for (const mapper of mappers) {
738
+ acc = await mapper(acc);
739
+ }
740
+ return acc;
741
+ };
742
+ }
743
+ function mapEach(mapper) {
744
+ return (items) => items.map(mapper);
745
+ }
746
+
747
+ // ../core/src/bootstrap/define-routes.ts
748
+ function defineRoutes(framework, definitions) {
749
+ const registeredIntents = /* @__PURE__ */ new Set();
750
+ for (const def of definitions) {
751
+ if (def.controller && !registeredIntents.has(def.intentId)) {
752
+ framework.registerIntent(def.controller);
753
+ registeredIntents.add(def.intentId);
754
+ }
755
+ framework.router.add(def.path, def.intentId);
756
+ }
757
+ }
758
+
759
+ // ../core/src/utils/lru-map.ts
760
+ var LruMap = class {
761
+ map = /* @__PURE__ */ new Map();
762
+ capacity;
763
+ constructor(capacity) {
764
+ this.capacity = capacity;
765
+ }
766
+ get(key) {
767
+ const value = this.map.get(key);
768
+ if (value !== void 0) {
769
+ this.map.delete(key);
770
+ this.map.set(key, value);
771
+ }
772
+ return value;
773
+ }
774
+ set(key, value) {
775
+ if (this.map.has(key)) {
776
+ this.map.delete(key);
777
+ } else if (this.map.size >= this.capacity) {
778
+ const oldest = this.map.keys().next().value;
779
+ if (oldest !== void 0) {
780
+ this.map.delete(oldest);
781
+ }
782
+ }
783
+ this.map.set(key, value);
784
+ }
785
+ has(key) {
786
+ return this.map.has(key);
787
+ }
788
+ delete(key) {
789
+ return this.map.delete(key);
790
+ }
791
+ get size() {
792
+ return this.map.size;
793
+ }
794
+ clear() {
795
+ this.map.clear();
796
+ }
797
+ };
798
+
799
+ // ../core/src/utils/optional.ts
800
+ function isSome(value) {
801
+ return value !== null && value !== void 0;
802
+ }
803
+ function isNone(value) {
804
+ return value === null || value === void 0;
805
+ }
806
+
807
+ // ../core/src/utils/url.ts
808
+ function removeScheme(url) {
809
+ return url.replace(/^https?:\/\//, "");
810
+ }
811
+ function removeHost(url) {
812
+ try {
813
+ const parsed = new URL(url);
814
+ return parsed.pathname + parsed.search + parsed.hash;
815
+ } catch {
816
+ return url;
817
+ }
818
+ }
819
+ function removeQueryParams(url) {
820
+ return url.split("?")[0];
821
+ }
822
+ function getBaseUrl(url) {
823
+ return url.split("?")[0].split("#")[0];
824
+ }
825
+ function buildUrl(path, params) {
826
+ if (!params) return path;
827
+ const searchParams = new URLSearchParams();
828
+ for (const [key, value] of Object.entries(params)) {
829
+ if (value !== void 0) {
830
+ searchParams.set(key, value);
831
+ }
832
+ }
833
+ const qs = searchParams.toString();
834
+ return qs ? `${path}?${qs}` : path;
835
+ }
836
+
837
+ // ../core/src/utils/uuid.ts
838
+ function generateUuid() {
839
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
840
+ return crypto.randomUUID();
841
+ }
842
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
843
+ const r = Math.random() * 16 | 0;
844
+ const v = c === "x" ? r : r & 3 | 8;
845
+ return v.toString(16);
846
+ });
847
+ }
848
+
849
+ // ../browser/src/action-handlers/external-url-action.ts
850
+ function registerExternalUrlHandler(deps) {
851
+ const { framework, log } = deps;
852
+ framework.onAction(
853
+ ACTION_KINDS.EXTERNAL_URL,
854
+ (action) => {
855
+ log.debug(`ExternalUrlAction \u2192 ${action.url}`);
856
+ window.open(action.url, "_blank", "noopener,noreferrer");
857
+ }
858
+ );
859
+ }
860
+
861
+ // ../browser/src/utils/try-scroll.ts
862
+ var MAX_TRIES = 100;
863
+ var FUDGE = 16;
864
+ var pendingFrame = null;
865
+ function tryScroll(log, getScrollableElement, scrollY) {
866
+ if (pendingFrame !== null) {
867
+ cancelAnimationFrame(pendingFrame);
868
+ pendingFrame = null;
869
+ }
870
+ let tries = 0;
871
+ pendingFrame = requestAnimationFrame(function attempt() {
872
+ if (++tries >= MAX_TRIES) {
873
+ log.warn(
874
+ `tryScroll: gave up after ${MAX_TRIES} frames, target=${scrollY}`
875
+ );
876
+ pendingFrame = null;
877
+ return;
878
+ }
879
+ const el = getScrollableElement();
880
+ if (!el) {
881
+ log.warn(
882
+ "could not restore scroll: the scrollable element is missing"
883
+ );
884
+ return;
885
+ }
886
+ const { scrollHeight, offsetHeight } = el;
887
+ const canScroll = scrollY + offsetHeight <= scrollHeight + FUDGE;
888
+ if (!canScroll) {
889
+ log.info("page is not tall enough for scroll yet", {
890
+ scrollHeight,
891
+ offsetHeight
892
+ });
893
+ pendingFrame = requestAnimationFrame(attempt);
894
+ return;
895
+ }
896
+ el.scrollTop = scrollY;
897
+ log.info("scroll restored to", scrollY);
898
+ pendingFrame = null;
899
+ });
900
+ }
901
+
902
+ // ../browser/src/utils/history.ts
903
+ var HISTORY_SIZE_LIMIT = 10;
904
+ var History = class {
905
+ entries;
906
+ log;
907
+ getScrollablePageElement;
908
+ currentStateId;
909
+ constructor(log, options, sizeLimit = HISTORY_SIZE_LIMIT) {
910
+ this.entries = new LruMap(sizeLimit);
911
+ this.log = log;
912
+ this.getScrollablePageElement = options.getScrollablePageElement;
913
+ }
914
+ replaceState(state, url) {
915
+ const id = generateUuid();
916
+ window.history.replaceState({ id }, "", url);
917
+ this.currentStateId = id;
918
+ this.entries.set(id, { state, scrollY: 0 });
919
+ this.scrollTop = 0;
920
+ this.log.info("replaceState", state, url, id);
921
+ }
922
+ pushState(state, url) {
923
+ const id = generateUuid();
924
+ window.history.pushState({ id }, "", url);
925
+ this.currentStateId = id;
926
+ this.entries.set(id, { state, scrollY: 0 });
927
+ this.scrollTop = 0;
928
+ this.log.info("pushState", state, url, id);
929
+ }
930
+ beforeTransition() {
931
+ const { state } = window.history;
932
+ if (!state) return;
933
+ const oldEntry = this.entries.get(state.id);
934
+ if (!oldEntry) {
935
+ this.log.info(
936
+ "current history state evicted from LRU, not saving scroll position"
937
+ );
938
+ return;
939
+ }
940
+ const { scrollTop } = this;
941
+ this.entries.set(state.id, { ...oldEntry, scrollY: scrollTop });
942
+ this.log.info("saving scroll position", scrollTop);
943
+ }
944
+ onPopState(listener) {
945
+ window.addEventListener("popstate", (event) => {
946
+ this.currentStateId = event.state?.id;
947
+ if (!this.currentStateId) {
948
+ this.log.warn(
949
+ "encountered a null event.state.id in onPopState event:",
950
+ window.location.href
951
+ );
952
+ }
953
+ this.log.info("popstate", this.entries, this.currentStateId);
954
+ const entry = this.currentStateId ? this.entries.get(this.currentStateId) : void 0;
955
+ listener(window.location.href, entry?.state);
956
+ if (!entry) {
957
+ return;
958
+ }
959
+ const { scrollY } = entry;
960
+ this.log.info("restoring scroll to", scrollY);
961
+ tryScroll(this.log, () => this.getScrollablePageElement(), scrollY);
962
+ });
963
+ }
964
+ updateState(update) {
965
+ if (!this.currentStateId) {
966
+ this.log.warn(
967
+ "failed: encountered a null currentStateId inside updateState"
968
+ );
969
+ return;
970
+ }
971
+ const currentState = this.entries.get(this.currentStateId);
972
+ const newState = update(currentState?.state);
973
+ this.log.info("updateState", newState, this.currentStateId);
974
+ this.entries.set(this.currentStateId, {
975
+ ...currentState,
976
+ state: newState
977
+ });
978
+ }
979
+ get scrollTop() {
980
+ return this.getScrollablePageElement()?.scrollTop || 0;
981
+ }
982
+ set scrollTop(scrollTop) {
983
+ const element = this.getScrollablePageElement();
984
+ if (element) {
985
+ element.scrollTop = scrollTop;
986
+ }
987
+ }
988
+ };
989
+
990
+ // ../browser/src/action-handlers/flow-action.ts
991
+ function registerFlowActionHandler(deps) {
992
+ const { framework, log, callbacks, updateApp } = deps;
993
+ let isFirstPage = true;
994
+ const history = new History(log, {
995
+ getScrollablePageElement: () => document.getElementById("scrollable-page-override") || document.getElementById("scrollable-page") || document.documentElement
996
+ });
997
+ framework.onAction(ACTION_KINDS.FLOW, async (action) => {
998
+ const flowAction = action;
999
+ const url = flowAction.url;
1000
+ log.debug(`FlowAction \u2192 ${url}`);
1001
+ if (flowAction.presentationContext === "modal") {
1002
+ const match2 = framework.routeUrl(url);
1003
+ if (match2) {
1004
+ const page = await framework.dispatch(
1005
+ match2.intent
1006
+ );
1007
+ callbacks.onModal(page);
1008
+ }
1009
+ return;
1010
+ }
1011
+ const shouldReplace = isFirstPage;
1012
+ const match = framework.routeUrl(url);
1013
+ if (!match) {
1014
+ log.warn(`FlowAction: no route for ${url}`);
1015
+ return;
1016
+ }
1017
+ const pagePromise = framework.dispatch(
1018
+ match.intent
1019
+ );
1020
+ await Promise.race([
1021
+ pagePromise,
1022
+ new Promise((r) => setTimeout(r, 500))
1023
+ ]).catch(() => {
1024
+ });
1025
+ history.beforeTransition();
1026
+ updateApp({
1027
+ page: pagePromise.then((page) => {
1028
+ const canonicalURL = url;
1029
+ if (shouldReplace) {
1030
+ history.replaceState({ page }, canonicalURL);
1031
+ } else {
1032
+ history.pushState({ page }, canonicalURL);
1033
+ }
1034
+ callbacks.onNavigate(
1035
+ new URL(canonicalURL, window.location.origin).pathname
1036
+ );
1037
+ didEnterPage(page);
1038
+ return page;
1039
+ }),
1040
+ isFirstPage
1041
+ });
1042
+ isFirstPage = false;
1043
+ });
1044
+ history.onPopState(async (url, cachedState) => {
1045
+ log.debug(`popstate \u2192 ${url}, cached=${!!cachedState}`);
1046
+ callbacks.onNavigate(new URL(url).pathname);
1047
+ if (cachedState) {
1048
+ const { page } = cachedState;
1049
+ didEnterPage(page);
1050
+ updateApp({ page, isFirstPage });
1051
+ return;
1052
+ }
1053
+ const parsed = new URL(url);
1054
+ const routeMatch = framework.routeUrl(parsed.pathname + parsed.search);
1055
+ if (!routeMatch) {
1056
+ log.error(
1057
+ "received popstate without data, but URL was unroutable:",
1058
+ url
1059
+ );
1060
+ didEnterPage(null);
1061
+ updateApp({
1062
+ page: Promise.reject(new Error("404")),
1063
+ isFirstPage
1064
+ });
1065
+ return;
1066
+ }
1067
+ const pagePromise = framework.dispatch(
1068
+ routeMatch.intent
1069
+ );
1070
+ await Promise.race([
1071
+ pagePromise,
1072
+ new Promise((r) => setTimeout(r, 500))
1073
+ ]).catch(() => {
1074
+ });
1075
+ updateApp({
1076
+ page: pagePromise.then((page) => {
1077
+ didEnterPage(page);
1078
+ return page;
1079
+ }),
1080
+ isFirstPage
1081
+ });
1082
+ });
1083
+ function didEnterPage(page) {
1084
+ (async () => {
1085
+ try {
1086
+ if (page) {
1087
+ await framework.didEnterPage(page);
1088
+ }
1089
+ } catch (e) {
1090
+ log.error("didEnterPage error:", e);
1091
+ }
1092
+ })();
1093
+ }
1094
+ }
1095
+
1096
+ // ../browser/src/action-handlers/register.ts
1097
+ function registerActionHandlers(deps) {
1098
+ const { framework, log, callbacks, updateApp } = deps;
1099
+ registerFlowActionHandler({
1100
+ framework,
1101
+ log,
1102
+ callbacks,
1103
+ updateApp
1104
+ });
1105
+ registerExternalUrlHandler({ framework, log });
1106
+ }
1107
+
1108
+ // ../browser/src/server-data.ts
1109
+ var SERVER_DATA_ID = "serialized-server-data";
1110
+ function deserializeServerData() {
1111
+ const script = document.getElementById(SERVER_DATA_ID);
1112
+ if (!script?.textContent) return void 0;
1113
+ script.parentNode?.removeChild(script);
1114
+ try {
1115
+ return JSON.parse(script.textContent);
1116
+ } catch {
1117
+ return void 0;
1118
+ }
1119
+ }
1120
+ function createPrefetchedIntentsFromDom() {
1121
+ const data = deserializeServerData();
1122
+ if (!data || !Array.isArray(data)) {
1123
+ return PrefetchedIntents.empty();
1124
+ }
1125
+ return PrefetchedIntents.fromArray(data);
1126
+ }
1127
+
1128
+ // ../browser/src/start-app.ts
1129
+ async function startBrowserApp(config) {
1130
+ const {
1131
+ bootstrap,
1132
+ defaultLocale = "en",
1133
+ mountId = "app",
1134
+ mount,
1135
+ callbacks
1136
+ } = config;
1137
+ const prefetchedIntents = createPrefetchedIntentsFromDom();
1138
+ const framework = Framework.create({ prefetchedIntents });
1139
+ bootstrap(framework);
1140
+ const loggerFactory = framework.container.resolve(
1141
+ DEP_KEYS.LOGGER_FACTORY
1142
+ );
1143
+ const log = loggerFactory.loggerFor("browser");
1144
+ const initialAction = framework.routeUrl(
1145
+ window.location.pathname + window.location.search
1146
+ );
1147
+ const locale = document.documentElement.lang || defaultLocale;
1148
+ const target = document.getElementById(mountId);
1149
+ const updateApp = mount(target, { framework, locale });
1150
+ registerActionHandlers({
1151
+ framework,
1152
+ log,
1153
+ callbacks,
1154
+ updateApp
1155
+ });
1156
+ if (initialAction) {
1157
+ await framework.perform(initialAction.action);
1158
+ } else {
1159
+ updateApp({
1160
+ page: Promise.reject(new Error("404")),
1161
+ isFirstPage: true
1162
+ });
1163
+ }
1164
+ }
1165
+ // Annotate the CommonJS export names for ESM import in node:
1166
+ 0 && (module.exports = {
1167
+ ACTION_KINDS,
1168
+ ActionDispatcher,
1169
+ BaseController,
1170
+ BaseLogger,
1171
+ CompositeLogger,
1172
+ CompositeLoggerFactory,
1173
+ ConsoleLogger,
1174
+ ConsoleLoggerFactory,
1175
+ Container,
1176
+ DEP_KEYS,
1177
+ Framework,
1178
+ History,
1179
+ HttpClient,
1180
+ HttpError,
1181
+ IntentDispatcher,
1182
+ LruMap,
1183
+ PrefetchedIntents,
1184
+ Router,
1185
+ buildUrl,
1186
+ createPrefetchedIntentsFromDom,
1187
+ defineRoutes,
1188
+ deserializeServerData,
1189
+ generateUuid,
1190
+ getBaseUrl,
1191
+ isCompoundAction,
1192
+ isExternalUrlAction,
1193
+ isFlowAction,
1194
+ isNone,
1195
+ isSome,
1196
+ makeDependencies,
1197
+ makeExternalUrlAction,
1198
+ makeFlowAction,
1199
+ mapEach,
1200
+ pipe,
1201
+ pipeAsync,
1202
+ registerActionHandlers,
1203
+ registerExternalUrlHandler,
1204
+ registerFlowActionHandler,
1205
+ removeHost,
1206
+ removeQueryParams,
1207
+ removeScheme,
1208
+ resetFilterCache,
1209
+ shouldLog,
1210
+ stableStringify,
1211
+ startBrowserApp,
1212
+ tryScroll
1213
+ });
1214
+ //# sourceMappingURL=browser.cjs.map