@lark-apaas/client-toolkit-lite 1.1.7-alpha.2 → 1.1.7-alpha.21

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.
package/dist/index.js CHANGED
@@ -6,7 +6,8 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // src/components/AppContainer/index.tsx
9
- import React4, { useEffect as useEffect4 } from "react";
9
+ import React4, { useEffect as useEffect5 } from "react";
10
+ import { MiaodaInspector } from "@lark-apaas/miaoda-inspector";
10
11
 
11
12
  // src/runtime/react-devtools-hook.ts
12
13
  if (typeof window !== "undefined" && process.env.NODE_ENV !== "production") {
@@ -62,15 +63,15 @@ function initAxiosConfig(axiosInstance2) {
62
63
  if (!axiosInstance2) {
63
64
  axiosInstance2 = axios;
64
65
  }
65
- axiosInstance2.interceptors.request.use((config) => {
66
+ axiosInstance2.interceptors.request.use((config2) => {
66
67
  const csrfToken = getCsrfToken();
67
68
  if (csrfToken) {
68
- config.headers["X-Suda-Csrf-Token"] = csrfToken;
69
+ config2.headers["X-Suda-Csrf-Token"] = csrfToken;
69
70
  }
70
71
  if (typeof window !== "undefined") {
71
- config.headers["X-Page-Route"] = window.location.pathname;
72
+ config2.headers["X-Page-Route"] = window.location.pathname;
72
73
  }
73
- return config;
74
+ return config2;
74
75
  }, (error) => Promise.reject(error));
75
76
  axiosInstance2.interceptors.response.use((response) => response, (error) => {
76
77
  if (process.env.NODE_ENV !== "production") {
@@ -81,10 +82,982 @@ function initAxiosConfig(axiosInstance2) {
81
82
  }
82
83
  __name(initAxiosConfig, "initAxiosConfig");
83
84
 
85
+ // src/logger/logger.ts
86
+ import { observable } from "@lark-apaas/observable-web";
87
+
88
+ // src/logger/intercept-global-error.ts
89
+ import { slardar } from "@lark-apaas/internal-slardar";
90
+
91
+ // src/utils/hmr-api.ts
92
+ function createWebpackHmrApi(hot) {
93
+ return {
94
+ onSuccess(callback) {
95
+ let lastStatus = null;
96
+ const handler = /* @__PURE__ */ __name((status) => {
97
+ if (status === "idle" && lastStatus === "apply") {
98
+ try {
99
+ callback();
100
+ } catch (e) {
101
+ console.error("[HMR] Success callback error:", e);
102
+ }
103
+ }
104
+ lastStatus = status;
105
+ }, "handler");
106
+ hot.addStatusHandler(handler);
107
+ return () => hot.removeStatusHandler(handler);
108
+ },
109
+ onError(callback) {
110
+ const handler = /* @__PURE__ */ __name((status) => {
111
+ if (status === "fail" || status === "abort") {
112
+ try {
113
+ callback(new Error(`HMR ${status}`));
114
+ } catch (e) {
115
+ console.error("[HMR] Error callback error:", e);
116
+ }
117
+ }
118
+ }, "handler");
119
+ hot.addStatusHandler(handler);
120
+ return () => hot.removeStatusHandler(handler);
121
+ }
122
+ };
123
+ }
124
+ __name(createWebpackHmrApi, "createWebpackHmrApi");
125
+ function getHmrApi() {
126
+ if (process.env.NODE_ENV === "production") return null;
127
+ if (import.meta.webpackHot) {
128
+ return createWebpackHmrApi(import.meta.webpackHot);
129
+ }
130
+ if (typeof module !== "undefined" && module.hot) {
131
+ return createWebpackHmrApi(module.hot);
132
+ }
133
+ if (window.__VITE_HMR__) {
134
+ return window.__VITE_HMR__;
135
+ }
136
+ return null;
137
+ }
138
+ __name(getHmrApi, "getHmrApi");
139
+
140
+ // src/utils/postMessage.ts
141
+ var PARENT_ORIGIN_KEY = "__parentOrigin";
142
+ function getParentOriginFromParams() {
143
+ try {
144
+ const params = new URLSearchParams(window.location.search);
145
+ const origin = params.get(PARENT_ORIGIN_KEY);
146
+ if (origin) {
147
+ sessionStorage.setItem(PARENT_ORIGIN_KEY, origin);
148
+ return origin;
149
+ }
150
+ } catch {
151
+ }
152
+ try {
153
+ return sessionStorage.getItem(PARENT_ORIGIN_KEY) || void 0;
154
+ } catch {
155
+ return void 0;
156
+ }
157
+ }
158
+ __name(getParentOriginFromParams, "getParentOriginFromParams");
159
+ function getLegacyParentOrigin() {
160
+ const { origin } = window.location;
161
+ if (origin.includes("force.feishuapp.net")) {
162
+ return "https://force.feishu.cn";
163
+ }
164
+ if (origin.includes("force-pre.feishuapp.net")) {
165
+ return "https://force.feishu-pre.cn";
166
+ }
167
+ if (origin.includes("force.byted.org")) {
168
+ return "https://force.feishu-boe.cn";
169
+ }
170
+ if (origin.includes("feishuapp.cn") || origin.includes("miaoda.feishuapp.net")) {
171
+ return "https://miaoda.feishu.cn";
172
+ }
173
+ if (origin.includes("fsapp.kundou.cn") || origin.includes("miaoda-pre.feishuapp.net")) {
174
+ return "https://miaoda.feishu-pre.cn";
175
+ }
176
+ return "https://miaoda.feishu-boe.cn";
177
+ }
178
+ __name(getLegacyParentOrigin, "getLegacyParentOrigin");
179
+ function resolveParentOrigin() {
180
+ try {
181
+ if (document.referrer) {
182
+ const referrerOrigin = new URL(document.referrer).origin;
183
+ if (referrerOrigin.startsWith("http://localhost") || referrerOrigin.startsWith("http://127.0.0.1")) {
184
+ return referrerOrigin;
185
+ }
186
+ }
187
+ } catch {
188
+ }
189
+ const paramOrigin = getParentOriginFromParams();
190
+ if (paramOrigin) return paramOrigin;
191
+ return process.env?.FORCE_FRAMEWORK_DOMAIN_MAIN ?? getLegacyParentOrigin();
192
+ }
193
+ __name(resolveParentOrigin, "resolveParentOrigin");
194
+ function submitPostMessage(message, targetOrigin) {
195
+ try {
196
+ const parentOrigin = resolveParentOrigin();
197
+ const origin = targetOrigin ?? parentOrigin;
198
+ if (!origin) return;
199
+ window.parent.postMessage(message, origin);
200
+ } catch (e) {
201
+ console.error("postMessage error", e);
202
+ }
203
+ }
204
+ __name(submitPostMessage, "submitPostMessage");
205
+
206
+ // src/logger/log-types.ts
207
+ var LOG_LEVELS = [
208
+ "debug",
209
+ "info",
210
+ "warn",
211
+ "error",
212
+ "success"
213
+ ];
214
+ function isLogLevel(value) {
215
+ return typeof value === "string" && LOG_LEVELS.includes(value);
216
+ }
217
+ __name(isLogLevel, "isLogLevel");
218
+
219
+ // src/logger/intercept-global-error.ts
220
+ var devServerDisconnectInfo = null;
221
+ var retryCount = 0;
222
+ function processDevServerLog(log) {
223
+ if (!log) return;
224
+ const devFlag = log.includes("[webpack-dev-server]") || log.includes("[vite]");
225
+ if (devFlag && log.includes("Disconnected")) {
226
+ const time = Date.now();
227
+ devServerDisconnectInfo = {
228
+ time
229
+ };
230
+ submitPostMessage({
231
+ type: "DevServerMessage",
232
+ data: {
233
+ type: "devServer-status",
234
+ status: "disconnected"
235
+ }
236
+ });
237
+ slardar.sendEvent({
238
+ name: "sandbox-devServer",
239
+ metrics: {
240
+ time
241
+ },
242
+ categories: {
243
+ type: "disconnected"
244
+ }
245
+ });
246
+ return;
247
+ }
248
+ if (!devServerDisconnectInfo) {
249
+ return;
250
+ }
251
+ if (devFlag && log.includes("Trying to reconnect")) {
252
+ if (retryCount) {
253
+ slardar.sendEvent({
254
+ name: "sandbox-devServer",
255
+ metrics: {
256
+ retryCount: retryCount + 1
257
+ },
258
+ categories: {
259
+ type: "reconnect-failed"
260
+ }
261
+ });
262
+ }
263
+ retryCount++;
264
+ return;
265
+ }
266
+ const hmrFlag = log.includes("[HMR]");
267
+ if (hmrFlag || devFlag && (log.includes("Socket connected") || log.includes("App updated") || log.includes("App hot update") || log.includes("connected"))) {
268
+ submitPostMessage({
269
+ type: "DevServerMessage",
270
+ data: {
271
+ type: "devServer-status",
272
+ status: "connected"
273
+ }
274
+ });
275
+ const startTime = devServerDisconnectInfo.time;
276
+ const duration = Date.now() - startTime;
277
+ slardar.sendEvent({
278
+ name: "sandbox-devServer",
279
+ metrics: {
280
+ startTime,
281
+ duration
282
+ },
283
+ categories: {
284
+ type: "devServer-reconnected"
285
+ }
286
+ });
287
+ devServerDisconnectInfo = null;
288
+ retryCount = 0;
289
+ }
290
+ }
291
+ __name(processDevServerLog, "processDevServerLog");
292
+ function listenModuleHmr() {
293
+ const hmr = getHmrApi();
294
+ if (hmr) {
295
+ hmr.onSuccess(() => {
296
+ submitPostMessage({
297
+ type: "DevServerMessage",
298
+ data: {
299
+ type: "devServer-status",
300
+ status: "hmr-apply-success"
301
+ }
302
+ });
303
+ });
304
+ hmr.onError((error) => {
305
+ console.warn("hmr apply failed", error);
306
+ slardar.sendEvent({
307
+ name: "sandbox-devServer",
308
+ categories: {
309
+ type: "hmr-apply-failed",
310
+ error: String(error)
311
+ }
312
+ });
313
+ });
314
+ }
315
+ }
316
+ __name(listenModuleHmr, "listenModuleHmr");
317
+ var PROXY_CONSOLE_METHOD = [
318
+ "log",
319
+ "info",
320
+ "warn",
321
+ "error"
322
+ ];
323
+ function interceptErrors() {
324
+ window.addEventListener("error", (event) => {
325
+ logger.error(event.error);
326
+ });
327
+ window.addEventListener("unhandledrejection", (event) => {
328
+ logger.error(event.reason);
329
+ });
330
+ listenModuleHmr();
331
+ PROXY_CONSOLE_METHOD.forEach((method) => {
332
+ const originalMethod = window.console[method];
333
+ window.console[method] = (...args) => {
334
+ originalMethod(...args);
335
+ const level = method === "log" ? "info" : method;
336
+ const first = args[0];
337
+ if (typeof first === "string") {
338
+ processDevServerLog(first);
339
+ }
340
+ if (typeof first === "string" && first.startsWith("[Dataloom]") && isLogLevel(level)) {
341
+ logger.log({
342
+ level,
343
+ args
344
+ });
345
+ submitPostMessage({
346
+ type: "Console",
347
+ method,
348
+ data: args
349
+ });
350
+ }
351
+ };
352
+ });
353
+ }
354
+ __name(interceptErrors, "interceptErrors");
355
+
356
+ // src/utils/safeStringify.ts
357
+ function safeStringify(obj) {
358
+ const seen = /* @__PURE__ */ new Set();
359
+ try {
360
+ return JSON.stringify(obj, (_key, value) => {
361
+ if (typeof value === "object" && value !== null) {
362
+ if (seen.has(value)) {
363
+ return "[Circular]";
364
+ }
365
+ seen.add(value);
366
+ }
367
+ if (typeof value === "bigint") {
368
+ return value.toString();
369
+ }
370
+ if (value instanceof Date) {
371
+ return value.toISOString();
372
+ }
373
+ if (value instanceof Map) {
374
+ return Object.fromEntries(value);
375
+ }
376
+ if (value instanceof Set) {
377
+ return Array.from(value);
378
+ }
379
+ if (value instanceof Error) {
380
+ return {
381
+ name: value.name,
382
+ message: value.message,
383
+ stack: value.stack
384
+ };
385
+ }
386
+ if (typeof value === "undefined") {
387
+ return "undefined";
388
+ }
389
+ if (typeof value === "symbol") {
390
+ return value.toString();
391
+ }
392
+ return value;
393
+ });
394
+ } catch {
395
+ return "";
396
+ } finally {
397
+ seen.clear();
398
+ }
399
+ }
400
+ __name(safeStringify, "safeStringify");
401
+ function processLogParams(args) {
402
+ return args.map((arg) => {
403
+ if (typeof arg === "string") return arg;
404
+ if (arg instanceof Error) {
405
+ return `${arg.name}: ${arg.message}
406
+ ${arg.stack ?? ""}`;
407
+ }
408
+ if (typeof arg === "object" && arg !== null) {
409
+ return safeStringify(arg);
410
+ }
411
+ return String(arg);
412
+ });
413
+ }
414
+ __name(processLogParams, "processLogParams");
415
+ function mapLogLevel(level) {
416
+ if (level === "warn") return "WARN";
417
+ if (level === "error") return "ERROR";
418
+ return "INFO";
419
+ }
420
+ __name(mapLogLevel, "mapLogLevel");
421
+
422
+ // src/logger/selected-logs.ts
423
+ import StackTrace from "stacktrace-js";
424
+
425
+ // src/logger/batch-logger.ts
426
+ var BatchLogger = class {
427
+ static {
428
+ __name(this, "BatchLogger");
429
+ }
430
+ config;
431
+ logQueue = [];
432
+ flushTimer = null;
433
+ isProcessing = false;
434
+ originConsole;
435
+ constructor(console1, config2) {
436
+ this.originConsole = {
437
+ ...console1
438
+ };
439
+ const { userId = "", tenantId = "", appId = "" } = window || {};
440
+ this.config = {
441
+ userId,
442
+ tenantId,
443
+ appId,
444
+ // 需要加请求路径前缀
445
+ endpoint: (process.env.CLIENT_BASE_PATH || "") + "/dev/logs/collect-batch",
446
+ sizeThreshold: 20,
447
+ flushInterval: 1e3,
448
+ maxRetries: 3,
449
+ retryDelay: 500,
450
+ headers: {
451
+ "Content-Type": "application/json"
452
+ },
453
+ ...config2 || {}
454
+ };
455
+ this.startFlushTimer();
456
+ this.setupBeforeUnloadHandler();
457
+ }
458
+ /**
459
+ * 批量记录日志(对外暴露的唯一方法)
460
+ */
461
+ batchLog(level, message, source) {
462
+ const logEntry = {
463
+ id: this.generateId(),
464
+ level,
465
+ message,
466
+ source,
467
+ timestamp: Date.now()
468
+ };
469
+ this.logQueue.push(logEntry);
470
+ if (this.logQueue.length >= this.config.sizeThreshold) {
471
+ this.flush();
472
+ }
473
+ }
474
+ /**
475
+ * 刷新日志队列,全部发送
476
+ */
477
+ async flush() {
478
+ if (this.isProcessing || this.logQueue.length === 0) {
479
+ return;
480
+ }
481
+ this.isProcessing = true;
482
+ const logsToSend = this.logQueue.splice(0, this.logQueue.length);
483
+ try {
484
+ await this.sendBatch(logsToSend);
485
+ } catch (error) {
486
+ this.logQueue.unshift(...logsToSend);
487
+ } finally {
488
+ this.isProcessing = false;
489
+ }
490
+ }
491
+ /**
492
+ * 发送日志批次到后端
493
+ */
494
+ async sendBatch(logs) {
495
+ const collectLogs = logs.map((log) => ({
496
+ level: log.level,
497
+ message: log.message,
498
+ time: new Date(log.timestamp).toISOString(),
499
+ source: log.source,
500
+ user_id: this.config.userId,
501
+ tenant_id: this.config.tenantId,
502
+ app_id: this.config.appId
503
+ }));
504
+ let retries = 0;
505
+ while (retries <= this.config.maxRetries) {
506
+ try {
507
+ await this.execFetch(this.config.endpoint, {
508
+ method: "POST",
509
+ headers: this.config.headers,
510
+ body: JSON.stringify(collectLogs)
511
+ });
512
+ return;
513
+ } catch (error) {
514
+ retries++;
515
+ if (retries > this.config.maxRetries) {
516
+ this.originConsole.error(`Failed to send logs (attempt ${retries}), retrying in ${this.config.retryDelay}ms...`);
517
+ } else {
518
+ this.originConsole.warn(`Failed to send logs (attempt ${retries}), retrying in ${this.config.retryDelay}ms...`);
519
+ }
520
+ await this.delay(this.config.retryDelay * retries);
521
+ }
522
+ }
523
+ }
524
+ /**
525
+ * 执行实际的fetch请求
526
+ */
527
+ async execFetch(url, options) {
528
+ return fetch(url, options);
529
+ }
530
+ /**
531
+ * 启动自动刷新定时器
532
+ */
533
+ startFlushTimer() {
534
+ if (this.flushTimer) {
535
+ clearInterval(this.flushTimer);
536
+ }
537
+ this.flushTimer = setInterval(() => {
538
+ if (this.logQueue.length > 0) {
539
+ this.flush();
540
+ }
541
+ }, this.config.flushInterval);
542
+ }
543
+ /**
544
+ * 设置页面卸载时的处理
545
+ */
546
+ setupBeforeUnloadHandler() {
547
+ if (typeof window !== "undefined") {
548
+ window.addEventListener("beforeunload", () => {
549
+ this.flush().finally(() => {
550
+ this.destroy();
551
+ });
552
+ });
553
+ }
554
+ }
555
+ /**
556
+ * 延迟函数
557
+ */
558
+ delay(ms) {
559
+ return new Promise((resolve) => setTimeout(resolve, ms));
560
+ }
561
+ /**
562
+ * 生成唯一ID
563
+ */
564
+ generateId() {
565
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
566
+ }
567
+ /**
568
+ * 销毁资源
569
+ */
570
+ async destroy() {
571
+ if (this.flushTimer) {
572
+ clearInterval(this.flushTimer);
573
+ this.flushTimer = null;
574
+ }
575
+ if (this.logQueue.length > 0) {
576
+ await this.flush();
577
+ }
578
+ }
579
+ /**
580
+ * 获取队列大小
581
+ */
582
+ getQueueSize() {
583
+ return this.logQueue.length;
584
+ }
585
+ /**
586
+ * 更新配置
587
+ */
588
+ updateConfig(newConfig) {
589
+ this.config = {
590
+ ...this.config,
591
+ ...newConfig
592
+ };
593
+ this.startFlushTimer();
594
+ }
595
+ };
596
+ var defaultBatchLogger = null;
597
+ function batchLogInfo(level, message, source) {
598
+ if (!defaultBatchLogger) {
599
+ return;
600
+ }
601
+ defaultBatchLogger.batchLog(level, message, source);
602
+ }
603
+ __name(batchLogInfo, "batchLogInfo");
604
+ if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
605
+ defaultBatchLogger = new BatchLogger(console);
606
+ }
607
+
608
+ // src/logger/selected-logs.ts
609
+ function mapStacktrace(stacktrace) {
610
+ return stacktrace.map((frame) => ({
611
+ functionName: frame.functionName || "",
612
+ fileName: frame.fileName || "",
613
+ lineNumber: frame.lineNumber || 0,
614
+ columnNumber: frame.columnNumber || 0
615
+ }));
616
+ }
617
+ __name(mapStacktrace, "mapStacktrace");
618
+ function reportStacktraceParseError(e, context) {
619
+ if (window.parent === window) return;
620
+ try {
621
+ submitPostMessage({
622
+ type: "STACKTRACE_PARSE_ERROR",
623
+ payload: {
624
+ error: e instanceof Error ? e.message : String(e),
625
+ context
626
+ }
627
+ });
628
+ } catch {
629
+ }
630
+ }
631
+ __name(reportStacktraceParseError, "reportStacktraceParseError");
632
+ async function getStacktrace() {
633
+ const stacktrace = await StackTrace.get();
634
+ return mapStacktrace(stacktrace);
635
+ }
636
+ __name(getStacktrace, "getStacktrace");
637
+ function errorReplacer(_key, value) {
638
+ if (value instanceof Error) {
639
+ return {
640
+ message: value.message,
641
+ stack: value.stack,
642
+ name: value.name
643
+ };
644
+ }
645
+ return value;
646
+ }
647
+ __name(errorReplacer, "errorReplacer");
648
+ function generateLogId() {
649
+ try {
650
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
651
+ return crypto.randomUUID();
652
+ }
653
+ } catch {
654
+ }
655
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
656
+ }
657
+ __name(generateLogId, "generateLogId");
658
+ var lastLogInfo = null;
659
+ async function sendSelectedLog(logWithoutID) {
660
+ try {
661
+ const log = {
662
+ ...logWithoutID,
663
+ id: generateLogId()
664
+ };
665
+ const newParts = [];
666
+ for (let i = 0; i < log.args.length; i++) {
667
+ const item = log.args[i];
668
+ if (item instanceof Error) {
669
+ const newError = {
670
+ message: item.message,
671
+ stack: item.stack,
672
+ name: item.name
673
+ };
674
+ if (!log.meta.stacktrace) {
675
+ try {
676
+ const stacktrace = await StackTrace.fromError(item);
677
+ log.meta.stacktrace = mapStacktrace(stacktrace);
678
+ } catch (e) {
679
+ reportStacktraceParseError(e, "StackTrace.fromError");
680
+ }
681
+ }
682
+ newParts.push(newError.message, newError);
683
+ } else {
684
+ newParts.push(item);
685
+ }
686
+ }
687
+ log.args = newParts;
688
+ if (!log.meta.stacktrace) {
689
+ try {
690
+ const frames = await getStacktrace();
691
+ const firstFrameIndex = frames.findIndex((frame) => !frame.fileName.includes("client-toolkit-lite/dist/logger"));
692
+ log.meta.stacktrace = firstFrameIndex === -1 ? [] : frames.slice(firstFrameIndex);
693
+ } catch (e) {
694
+ reportStacktraceParseError(e, "getStacktrace");
695
+ }
696
+ }
697
+ if (log.meta.skipFrame === void 0) {
698
+ log.meta.skipFrame = 2;
699
+ }
700
+ const logJSON = JSON.stringify(log, errorReplacer);
701
+ const logForDedup = {
702
+ ...log
703
+ };
704
+ delete logForDedup.id;
705
+ const logContentForDedup = JSON.stringify(logForDedup, errorReplacer);
706
+ if (lastLogInfo && lastLogInfo.content === logContentForDedup) {
707
+ lastLogInfo.count++;
708
+ log.meta.isDuplicate = true;
709
+ log.meta.duplicateCount = lastLogInfo.count;
710
+ log.meta.duplicateOfId = lastLogInfo.id;
711
+ const updatedJSON = JSON.stringify(log, errorReplacer);
712
+ try {
713
+ batchLogInfo("info", updatedJSON);
714
+ } catch {
715
+ }
716
+ if (window.parent !== window) {
717
+ try {
718
+ submitPostMessage({
719
+ type: "SELECTED_LOG",
720
+ payload: updatedJSON
721
+ });
722
+ } catch {
723
+ }
724
+ }
725
+ return;
726
+ }
727
+ lastLogInfo = {
728
+ content: logContentForDedup,
729
+ id: log.id,
730
+ count: 1
731
+ };
732
+ try {
733
+ batchLogInfo("info", logJSON);
734
+ } catch {
735
+ }
736
+ if (window.parent !== window) {
737
+ try {
738
+ submitPostMessage({
739
+ type: "SELECTED_LOG",
740
+ payload: logJSON
741
+ });
742
+ } catch {
743
+ }
744
+ }
745
+ } catch {
746
+ }
747
+ }
748
+ __name(sendSelectedLog, "sendSelectedLog");
749
+ function sendTypedLogV2(logWithMeta) {
750
+ void sendSelectedLog({
751
+ type: "typedLogV2",
752
+ level: logWithMeta.level,
753
+ args: logWithMeta.args,
754
+ meta: logWithMeta.meta ?? {}
755
+ });
756
+ }
757
+ __name(sendTypedLogV2, "sendTypedLogV2");
758
+ var typedLogInterceptor = /* @__PURE__ */ __name((originLogger) => ({
759
+ debug: /* @__PURE__ */ __name((message, ...args) => {
760
+ try {
761
+ originLogger.debug(message, ...args);
762
+ } catch {
763
+ }
764
+ sendTypedLogV2({
765
+ level: "info",
766
+ args: [
767
+ message,
768
+ ...args
769
+ ],
770
+ meta: {}
771
+ });
772
+ }, "debug"),
773
+ info: /* @__PURE__ */ __name((message, ...args) => {
774
+ try {
775
+ originLogger.info(message, ...args);
776
+ } catch {
777
+ }
778
+ sendTypedLogV2({
779
+ level: "info",
780
+ args: [
781
+ message,
782
+ ...args
783
+ ],
784
+ meta: {}
785
+ });
786
+ }, "info"),
787
+ warn: /* @__PURE__ */ __name((message, ...args) => {
788
+ try {
789
+ originLogger.warn(message, ...args);
790
+ } catch {
791
+ }
792
+ sendTypedLogV2({
793
+ level: "warn",
794
+ args: [
795
+ message,
796
+ ...args
797
+ ],
798
+ meta: {}
799
+ });
800
+ }, "warn"),
801
+ error: /* @__PURE__ */ __name((message, ...args) => {
802
+ try {
803
+ originLogger.error(message, ...args);
804
+ } catch {
805
+ }
806
+ sendTypedLogV2({
807
+ level: "error",
808
+ args: [
809
+ message,
810
+ ...args
811
+ ],
812
+ meta: {}
813
+ });
814
+ }, "error"),
815
+ success: /* @__PURE__ */ __name((message, ...args) => {
816
+ try {
817
+ originLogger.success(message, ...args);
818
+ } catch {
819
+ }
820
+ sendTypedLogV2({
821
+ level: "success",
822
+ args: [
823
+ message,
824
+ ...args
825
+ ],
826
+ meta: {}
827
+ });
828
+ }, "success"),
829
+ log: /* @__PURE__ */ __name(({ level, args, meta }) => {
830
+ try {
831
+ originLogger.log({
832
+ level,
833
+ args,
834
+ meta
835
+ });
836
+ } catch {
837
+ }
838
+ sendTypedLogV2({
839
+ level,
840
+ args,
841
+ meta: meta ?? {}
842
+ });
843
+ }, "log")
844
+ }), "typedLogInterceptor");
845
+ var interceptors = [
846
+ typedLogInterceptor
847
+ ];
848
+
849
+ // src/logger/logger.ts
850
+ var shouldReportToObservable = process.env.NODE_ENV === "production";
851
+ var ORDERED_LEVELS = [
852
+ "debug",
853
+ "info",
854
+ "warn",
855
+ "error"
856
+ ];
857
+ var defaultConfig = {
858
+ showLevel: false,
859
+ showTimestamp: false,
860
+ level: "info",
861
+ prefix: ""
862
+ };
863
+ var config = {
864
+ ...defaultConfig
865
+ };
866
+ function configureLogger(options) {
867
+ config = {
868
+ ...defaultConfig,
869
+ ...options
870
+ };
871
+ }
872
+ __name(configureLogger, "configureLogger");
873
+ function shouldLog(level) {
874
+ return ORDERED_LEVELS.indexOf(level) >= ORDERED_LEVELS.indexOf(config.level);
875
+ }
876
+ __name(shouldLog, "shouldLog");
877
+ function getFormattedPrefix(level) {
878
+ const parts = [];
879
+ if (config.prefix) {
880
+ parts.push(`[${config.prefix}]`);
881
+ }
882
+ if (config.showLevel) {
883
+ parts.push(`[${level.toUpperCase()}]`);
884
+ }
885
+ return parts;
886
+ }
887
+ __name(getFormattedPrefix, "getFormattedPrefix");
888
+ configureLogger({
889
+ showLevel: true,
890
+ showTimestamp: false,
891
+ level: process.env.NODE_ENV === "development" ? "debug" : "error",
892
+ prefix: "MiaoDa"
893
+ });
894
+ var logger = {
895
+ debug(message, ...args) {
896
+ if (shouldLog("debug")) {
897
+ console.log(...getFormattedPrefix("debug"), message, ...args);
898
+ }
899
+ },
900
+ info(message, ...args) {
901
+ if (shouldLog("info")) {
902
+ console.log(...getFormattedPrefix("info"), message, ...args);
903
+ }
904
+ if (shouldReportToObservable) {
905
+ observable.log("INFO", processLogParams([
906
+ message,
907
+ ...args
908
+ ]).join(" "));
909
+ }
910
+ },
911
+ warn(message, ...args) {
912
+ if (shouldLog("warn")) {
913
+ console.log(...getFormattedPrefix("warn"), message, ...args);
914
+ }
915
+ if (shouldReportToObservable) {
916
+ observable.log("WARN", processLogParams([
917
+ message,
918
+ ...args
919
+ ]).join(" "));
920
+ }
921
+ },
922
+ error(message, ...args) {
923
+ if (shouldLog("error")) {
924
+ console.error(...getFormattedPrefix("error"), message, ...args);
925
+ }
926
+ if (shouldReportToObservable) {
927
+ observable.log("ERROR", processLogParams([
928
+ message,
929
+ ...args
930
+ ]).join(" "));
931
+ }
932
+ },
933
+ success(message, ...args) {
934
+ if (shouldLog("info")) {
935
+ console.log(...getFormattedPrefix("success"), message, ...args);
936
+ }
937
+ if (shouldReportToObservable) {
938
+ observable.log("INFO", processLogParams([
939
+ message,
940
+ ...args
941
+ ]).join(" "));
942
+ }
943
+ },
944
+ log({ level, args }) {
945
+ if (shouldLog(level)) {
946
+ console.log(...getFormattedPrefix(level), ...args);
947
+ }
948
+ if (shouldReportToObservable && level !== "debug") {
949
+ observable.log(mapLogLevel(level), processLogParams(args).join(" "));
950
+ }
951
+ }
952
+ };
953
+ if (process.env.NODE_ENV !== "production") {
954
+ window.__RUNTIME_LOGGER__ = {
955
+ get() {
956
+ return logger;
957
+ }
958
+ };
959
+ }
960
+ for (const interceptor of interceptors) {
961
+ logger = interceptor(logger);
962
+ }
963
+ if (process.env.NODE_ENV !== "production") {
964
+ interceptErrors();
965
+ }
966
+
967
+ // src/runtime/iframe-bridge.ts
968
+ import { connectToParent } from "penpal";
969
+
970
+ // src/utils/utils.ts
971
+ import { clsx } from "clsx";
972
+ import { twMerge } from "tailwind-merge";
973
+ function clsxWithTw(...inputs) {
974
+ return twMerge(clsx(inputs));
975
+ }
976
+ __name(clsxWithTw, "clsxWithTw");
977
+ function isPreview() {
978
+ return window.IS_MIAODA_PREVIEW;
979
+ }
980
+ __name(isPreview, "isPreview");
981
+ function normalizeBasePath(basePath) {
982
+ if (!basePath || basePath === "/") {
983
+ return "";
984
+ }
985
+ return basePath.replace(/\/+$/, "");
986
+ }
987
+ __name(normalizeBasePath, "normalizeBasePath");
988
+ function getWsPath() {
989
+ const rawBasePath = process.env.CLIENT_BASE_PATH || "/";
990
+ const normalizedBasePath = rawBasePath.startsWith("/") ? rawBasePath : `/${rawBasePath}`;
991
+ const basePathWithoutTrailingSlash = normalizedBasePath.endsWith("/") ? normalizedBasePath.slice(0, -1) : normalizedBasePath;
992
+ return `${basePathWithoutTrailingSlash}/ws`;
993
+ }
994
+ __name(getWsPath, "getWsPath");
995
+ function isSparkRuntime() {
996
+ return window._IS_Spark_RUNTIME ?? process.env.runtimeMode === "fullstack";
997
+ }
998
+ __name(isSparkRuntime, "isSparkRuntime");
999
+
1000
+ // src/components/AppContainer/utils/childApi.ts
1001
+ async function getRoutes() {
1002
+ let routes = [
1003
+ {
1004
+ path: "/"
1005
+ }
1006
+ ];
1007
+ try {
1008
+ const basePath = normalizeBasePath(process.env.CLIENT_BASE_PATH);
1009
+ const res = await fetch(`${basePath}/routes.json`);
1010
+ routes = await res.json();
1011
+ } catch (error) {
1012
+ console.warn("get routes.json error", error);
1013
+ }
1014
+ return routes;
1015
+ }
1016
+ __name(getRoutes, "getRoutes");
1017
+ var childApi = {
1018
+ getRoutes,
1019
+ updateAppInfo: /* @__PURE__ */ __name((appInfo) => {
1020
+ dispatchEvent(new CustomEvent("MiaoDaMetaInfoChanged", {
1021
+ detail: appInfo
1022
+ }));
1023
+ }, "updateAppInfo")
1024
+ };
1025
+
1026
+ // src/runtime/iframe-bridge.ts
1027
+ async function connectParent() {
1028
+ submitPostMessage({
1029
+ type: "PreviewReady",
1030
+ data: {}
1031
+ });
1032
+ batchLogInfo("info", JSON.stringify({
1033
+ type: "PreviewReady",
1034
+ timestamp: Date.now(),
1035
+ url: window.location.href
1036
+ }));
1037
+ const parentOrigin = resolveParentOrigin();
1038
+ if (!parentOrigin) return;
1039
+ const connection = connectToParent({
1040
+ parentOrigin,
1041
+ methods: {
1042
+ ...childApi
1043
+ }
1044
+ });
1045
+ await connection.promise;
1046
+ }
1047
+ __name(connectParent, "connectParent");
1048
+ function initIframeBridge() {
1049
+ if (window.parent === window) return;
1050
+ connectParent();
1051
+ }
1052
+ __name(initIframeBridge, "initIframeBridge");
1053
+
84
1054
  // src/runtime/index.ts
85
1055
  if (!window.__FULLSTACK_RUNTIME_INITIALIZED__) {
86
1056
  window.__FULLSTACK_RUNTIME_INITIALIZED__ = true;
87
1057
  initAxiosConfig();
1058
+ if (process.env.NODE_ENV !== "production") {
1059
+ initIframeBridge();
1060
+ }
88
1061
  }
89
1062
 
90
1063
  // src/components/AppContainer/safety.tsx
@@ -159,36 +1132,6 @@ function getInitialInfo(refresh = false) {
159
1132
  }
160
1133
  __name(getInitialInfo, "getInitialInfo");
161
1134
 
162
- // src/utils/utils.ts
163
- import { clsx } from "clsx";
164
- import { twMerge } from "tailwind-merge";
165
- function clsxWithTw(...inputs) {
166
- return twMerge(clsx(inputs));
167
- }
168
- __name(clsxWithTw, "clsxWithTw");
169
- function isPreview() {
170
- return window.IS_MIAODA_PREVIEW;
171
- }
172
- __name(isPreview, "isPreview");
173
- function normalizeBasePath(basePath) {
174
- if (!basePath || basePath === "/") {
175
- return "";
176
- }
177
- return basePath.replace(/\/+$/, "");
178
- }
179
- __name(normalizeBasePath, "normalizeBasePath");
180
- function getWsPath() {
181
- const rawBasePath = process.env.CLIENT_BASE_PATH || "/";
182
- const normalizedBasePath = rawBasePath.startsWith("/") ? rawBasePath : `/${rawBasePath}`;
183
- const basePathWithoutTrailingSlash = normalizedBasePath.endsWith("/") ? normalizedBasePath.slice(0, -1) : normalizedBasePath;
184
- return `${basePathWithoutTrailingSlash}/ws`;
185
- }
186
- __name(getWsPath, "getWsPath");
187
- function isSparkRuntime() {
188
- return window._IS_Spark_RUNTIME ?? process.env.runtimeMode === "fullstack";
189
- }
190
- __name(isSparkRuntime, "isSparkRuntime");
191
-
192
1135
  // src/integrations/getAppInfo.ts
193
1136
  async function getAppInfo(refresh = false) {
194
1137
  let appInfo = typeof window !== "undefined" ? window._appInfo : void 0;
@@ -275,7 +1218,6 @@ var useAppInfo = /* @__PURE__ */ __name(() => {
275
1218
 
276
1219
  // src/hooks/useCurrentUserProfile.tsx
277
1220
  import { useEffect as useEffect2, useState as useState2 } from "react";
278
- import { authClient } from "@lark-apaas/auth-sdk";
279
1221
 
280
1222
  // src/integrations/getCurrentUserProfile.ts
281
1223
  function getCurrentUserProfile() {
@@ -283,6 +1225,69 @@ function getCurrentUserProfile() {
283
1225
  }
284
1226
  __name(getCurrentUserProfile, "getCurrentUserProfile");
285
1227
 
1228
+ // src/utils/url.ts
1229
+ function splitWorkspaceUrl(fullUrl) {
1230
+ try {
1231
+ const url = new URL(fullUrl);
1232
+ const pathParts = url.pathname.split("/");
1233
+ const workspacesIndex = pathParts.findIndex((part) => part === "workspaces");
1234
+ if (workspacesIndex === -1) {
1235
+ throw new Error("Invalid workspace URL format");
1236
+ }
1237
+ const basePathParts = pathParts.slice(0, workspacesIndex);
1238
+ const workspace = pathParts[workspacesIndex + 1];
1239
+ return {
1240
+ baseUrl: `${url.origin}${basePathParts.join("/")}`,
1241
+ workspace
1242
+ };
1243
+ } catch (error) {
1244
+ console.error("Error splitting workspace URL:", error);
1245
+ }
1246
+ return {
1247
+ baseUrl: fullUrl,
1248
+ // 兜底给一个,不要给空字符串,不然 createClient 都直接挂了,页面会白屏,体感不太好
1249
+ workspace: "workspace"
1250
+ };
1251
+ }
1252
+ __name(splitWorkspaceUrl, "splitWorkspaceUrl");
1253
+
1254
+ // src/integrations/dataloom.ts
1255
+ import { createClient } from "@lark-apaas/dataloom";
1256
+ var createDataLoomClient = /* @__PURE__ */ __name((url, pat) => {
1257
+ const { baseUrl } = url ? splitWorkspaceUrl(url) : {
1258
+ baseUrl: ""
1259
+ };
1260
+ const appId = getAppId() ?? "";
1261
+ return createClient(baseUrl, pat ?? "", {
1262
+ global: {
1263
+ enableDataloomLog: process.env.NODE_ENV !== "production",
1264
+ requestRateLimit: process.env.NODE_ENV !== "production" ? 100 : void 0,
1265
+ brandName: "miaoda",
1266
+ appId
1267
+ }
1268
+ });
1269
+ }, "createDataLoomClient");
1270
+ var dataloom = null;
1271
+ var pendingPromise2 = null;
1272
+ function getDataloom() {
1273
+ if (dataloom) {
1274
+ return Promise.resolve(dataloom);
1275
+ }
1276
+ if (pendingPromise2) {
1277
+ return pendingPromise2;
1278
+ }
1279
+ pendingPromise2 = getInitialInfo().then((info) => {
1280
+ const DATALOOM_CLIENT_URL = info?.app_runtime_extra?.url;
1281
+ const DATALOOM_PAT = info?.app_runtime_extra?.token;
1282
+ dataloom = createDataLoomClient(DATALOOM_CLIENT_URL, DATALOOM_PAT);
1283
+ return dataloom;
1284
+ }).finally(() => {
1285
+ pendingPromise2 = null;
1286
+ });
1287
+ return pendingPromise2;
1288
+ }
1289
+ __name(getDataloom, "getDataloom");
1290
+
286
1291
  // src/hooks/useCurrentUserProfile.tsx
287
1292
  function getNameFromArray(nameArray) {
288
1293
  if (!nameArray || nameArray.length === 0) {
@@ -307,7 +1312,8 @@ var useCurrentUserProfile = /* @__PURE__ */ __name(() => {
307
1312
  useEffect2(() => {
308
1313
  let cancelled = false;
309
1314
  const fetchAndSetUserInfo = /* @__PURE__ */ __name(async () => {
310
- const result = await authClient.session.getUserInfo();
1315
+ const dataloom2 = await getDataloom();
1316
+ const result = await dataloom2?.service?.session?.getUserInfo();
311
1317
  if (cancelled) return;
312
1318
  const info = result?.data?.user_info;
313
1319
  const userName = getNameFromArray(info?.name);
@@ -371,7 +1377,6 @@ __name(useIsMobile, "useIsMobile");
371
1377
 
372
1378
  // src/hooks/useLogout.ts
373
1379
  import { useState as useState3 } from "react";
374
- import { authClient as authClient2 } from "@lark-apaas/auth-sdk";
375
1380
  function useLogout() {
376
1381
  const [isLoading, setIsLoading] = useState3(false);
377
1382
  async function handlerLogout() {
@@ -381,7 +1386,8 @@ function useLogout() {
381
1386
  }
382
1387
  setIsLoading(true);
383
1388
  try {
384
- await authClient2.session.signOut();
1389
+ const dataloom2 = await getDataloom();
1390
+ await dataloom2.service.session.signOut();
385
1391
  } catch (error) {
386
1392
  console.error("\u767B\u51FA\u5931\u8D25", error);
387
1393
  } finally {
@@ -814,6 +1820,7 @@ var Safety = /* @__PURE__ */ __name(() => {
814
1820
  isMobile2
815
1821
  ]);
816
1822
  if (process.env.NODE_ENV !== "production") return null;
1823
+ if (String(process.env.MIAODA_APP_TYPE) === "7") return null;
817
1824
  if (!badgeLoaded) return null;
818
1825
  if (!showBadge) return null;
819
1826
  if (!visible) return null;
@@ -1008,6 +2015,92 @@ var QueryProvider = /* @__PURE__ */ __name(({ children, client }) => {
1008
2015
  }, "QueryProvider");
1009
2016
  var QueryProvider_default = QueryProvider;
1010
2017
 
2018
+ // src/components/AppContainer/IframeBridge.tsx
2019
+ import { useEffect as useEffect4, useCallback, useRef as useRef3, useMemo, createElement } from "react";
2020
+ import { useLocation, useNavigate } from "react-router-dom";
2021
+
2022
+ // src/hooks/useUpdatingRef.ts
2023
+ import { useRef as useRef2 } from "react";
2024
+ function useUpdatingRef(value) {
2025
+ const ref = useRef2(value);
2026
+ ref.current = value;
2027
+ return ref;
2028
+ }
2029
+ __name(useUpdatingRef, "useUpdatingRef");
2030
+
2031
+ // src/components/AppContainer/IframeBridge.tsx
2032
+ var RouteMessageType = /* @__PURE__ */ (function(RouteMessageType2) {
2033
+ RouteMessageType2["RouteChange"] = "RouteChange";
2034
+ RouteMessageType2["RouteBack"] = "RouteBack";
2035
+ RouteMessageType2["RouteForward"] = "RouteForward";
2036
+ return RouteMessageType2;
2037
+ })(RouteMessageType || {});
2038
+ function isRouteMessageType(type) {
2039
+ return Object.values(RouteMessageType).includes(type);
2040
+ }
2041
+ __name(isRouteMessageType, "isRouteMessageType");
2042
+ function IframeBridge() {
2043
+ const location = useLocation();
2044
+ const navigate = useNavigate();
2045
+ const navigateRef = useUpdatingRef(navigate);
2046
+ const isActive = useRef3(false);
2047
+ const historyBack = useCallback((_payload) => {
2048
+ navigateRef.current(-1);
2049
+ isActive.current = true;
2050
+ }, [
2051
+ navigateRef
2052
+ ]);
2053
+ const historyForward = useCallback((_payload) => {
2054
+ navigateRef.current(1);
2055
+ isActive.current = true;
2056
+ }, [
2057
+ navigateRef
2058
+ ]);
2059
+ const operatorMessage = useMemo(() => ({
2060
+ ["RouteBack"]: historyBack,
2061
+ ["RouteForward"]: historyForward,
2062
+ ["RouteChange"]: navigateRef.current
2063
+ }), [
2064
+ historyBack,
2065
+ historyForward,
2066
+ navigateRef
2067
+ ]);
2068
+ useEffect4(() => {
2069
+ if (isActive.current) {
2070
+ isActive.current = false;
2071
+ return;
2072
+ }
2073
+ submitPostMessage({
2074
+ type: "ChildLocationChange",
2075
+ data: location
2076
+ });
2077
+ }, [
2078
+ location
2079
+ ]);
2080
+ const handleMessage = useCallback((event) => {
2081
+ const data = event.data ?? {};
2082
+ if (typeof data.type === "string" && isRouteMessageType(data.type)) {
2083
+ operatorMessage[data.type](data.data);
2084
+ }
2085
+ }, [
2086
+ operatorMessage
2087
+ ]);
2088
+ useEffect4(() => {
2089
+ window.addEventListener("message", handleMessage);
2090
+ return () => {
2091
+ window.removeEventListener("message", handleMessage);
2092
+ };
2093
+ }, [
2094
+ handleMessage
2095
+ ]);
2096
+ return /* @__PURE__ */ createElement("div", {
2097
+ style: {
2098
+ display: "none"
2099
+ }
2100
+ });
2101
+ }
2102
+ __name(IframeBridge, "IframeBridge");
2103
+
1011
2104
  // src/components/AppContainer/utils/tea.ts
1012
2105
  import md5 from "blueimp-md5";
1013
2106
  import sha1 from "crypto-js/sha1";
@@ -1119,6 +2212,31 @@ var reportTeaEvent = /* @__PURE__ */ __name(async ({ trackKey, trackParams = {}
1119
2212
  }
1120
2213
  }, "reportTeaEvent");
1121
2214
 
2215
+ // src/components/AppContainer/utils/observable.ts
2216
+ import { observable as observable2, AppEnv } from "@lark-apaas/observable-web";
2217
+ var initObservable = /* @__PURE__ */ __name(() => {
2218
+ try {
2219
+ const appId = window.appId;
2220
+ observable2.start({
2221
+ serviceName: "app",
2222
+ env: process.env.NODE_ENV === "development" ? AppEnv.Dev : AppEnv.Prod,
2223
+ collectorUrl: isNewPathEnabled() ? {
2224
+ log: `/app/${appId}/__runtime__/api/v1/observability/logs/collect`,
2225
+ trace: `/app/${appId}/__runtime__/api/v1/observability/traces/collect`,
2226
+ metric: `/app/${appId}/__runtime__/api/v1/observability/metrics/collect`,
2227
+ time: `/app/${appId}/__runtime__/api/v1/observability/current_server_timestamp`
2228
+ } : {
2229
+ log: `/spark/app/${appId}/runtime/api/v1/observability/logs/collect`,
2230
+ trace: `/spark/app/${appId}/runtime/api/v1/observability/traces/collect`,
2231
+ metric: `/spark/app/${appId}/runtime/api/v1/observability/metrics/collect`,
2232
+ time: `/spark/api/v1/observability/app/${appId}/current_server_timestamp`
2233
+ }
2234
+ });
2235
+ } catch (error) {
2236
+ console.error("Failed to start WebObservableSdk:", error);
2237
+ }
2238
+ }, "initObservable");
2239
+
1122
2240
  // src/types/tea.ts
1123
2241
  var TrackKey = /* @__PURE__ */ (function(TrackKey2) {
1124
2242
  TrackKey2["VIEW"] = "aily_agent_artifact_page_view";
@@ -1128,7 +2246,10 @@ var TrackKey = /* @__PURE__ */ (function(TrackKey2) {
1128
2246
  // src/components/AppContainer/index.tsx
1129
2247
  var AppContainer = /* @__PURE__ */ __name(({ children }) => {
1130
2248
  useAppInfo();
1131
- useEffect4(() => {
2249
+ useEffect5(() => {
2250
+ initObservable();
2251
+ }, []);
2252
+ useEffect5(() => {
1132
2253
  if (process.env.NODE_ENV === "production") {
1133
2254
  reportTeaEvent({
1134
2255
  trackKey: TrackKey.VIEW,
@@ -1140,7 +2261,7 @@ var AppContainer = /* @__PURE__ */ __name(({ children }) => {
1140
2261
  });
1141
2262
  }
1142
2263
  }, []);
1143
- return /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement(safety_default, null), /* @__PURE__ */ React4.createElement(QueryProvider_default, null, children));
2264
+ return /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement(safety_default, null), process.env.NODE_ENV !== "production" && /* @__PURE__ */ React4.createElement(MiaodaInspector, null), process.env.NODE_ENV !== "production" && /* @__PURE__ */ React4.createElement(IframeBridge, null), /* @__PURE__ */ React4.createElement(QueryProvider_default, null, children));
1144
2265
  }, "AppContainer");
1145
2266
  var AppContainer_default = AppContainer;
1146
2267
 
@@ -1231,13 +2352,67 @@ var PagePlaceholder = /* @__PURE__ */ __name(({ title = "\u9875\u9762\u5F85\u5F0
1231
2352
  }, "PagePlaceholder");
1232
2353
  var PagePlaceholder_default = PagePlaceholder;
1233
2354
 
2355
+ // src/components/ErrorRender/index.tsx
2356
+ import React7, { useEffect as useEffect6 } from "react";
2357
+ var ErrorRender = /* @__PURE__ */ __name((props) => {
2358
+ const { error, resetErrorBoundary } = props;
2359
+ useEffect6(() => {
2360
+ if (error) {
2361
+ submitPostMessage({
2362
+ type: "RenderError",
2363
+ data: error
2364
+ });
2365
+ logger.log({
2366
+ level: "error",
2367
+ args: [
2368
+ "Render Error",
2369
+ error
2370
+ ],
2371
+ meta: {
2372
+ type: "render-error",
2373
+ repairMessage: "\u9875\u9762\u6E32\u67D3\u65F6\u62A5\u9519\uFF0C\u8BF7\u6839\u636E\u9519\u8BEF\u4FE1\u606F\u4FEE\u590D\u5BF9\u5E94\u9875\u9762\u7684\u4EE3\u7801"
2374
+ }
2375
+ });
2376
+ }
2377
+ }, [
2378
+ error
2379
+ ]);
2380
+ useEffect6(() => {
2381
+ if (!resetErrorBoundary) return;
2382
+ const hmr = getHmrApi();
2383
+ if (!hmr) return;
2384
+ return hmr.onSuccess(() => {
2385
+ const isVite = typeof window !== "undefined" && Boolean(window.__VITE_HMR__);
2386
+ if (isVite) {
2387
+ window.location.reload();
2388
+ } else {
2389
+ resetErrorBoundary();
2390
+ }
2391
+ });
2392
+ }, [
2393
+ resetErrorBoundary
2394
+ ]);
2395
+ return /* @__PURE__ */ React7.createElement("div", {
2396
+ className: "min-h-screen flex items-center justify-center bg-white"
2397
+ }, /* @__PURE__ */ React7.createElement("div", {
2398
+ className: "flex flex-col justify-center items-center text-center"
2399
+ }, /* @__PURE__ */ React7.createElement("img", {
2400
+ src: "https://lf3-static.bytednsdoc.com/obj/eden-cn/ylcylz_fsph_ryhs/ljhwZthlaukjlkulzlp/feisuda/template/illustration_empty_negative_error.svg",
2401
+ alt: "render error",
2402
+ className: "mb-3 w-[100px]"
2403
+ }), /* @__PURE__ */ React7.createElement("p", {
2404
+ className: "text-l/[22px] text-[14px] text-[#1F2329] font-medium"
2405
+ }, "\u9875\u9762\u51FA\u9519\u4E86")));
2406
+ }, "ErrorRender");
2407
+ var ErrorRender_default = ErrorRender;
2408
+
1234
2409
  // src/route-components/ActiveLink.tsx
1235
- import React7, { forwardRef, useEffect as useEffect5, useState as useState5 } from "react";
2410
+ import React8, { forwardRef, useEffect as useEffect7, useState as useState5 } from "react";
1236
2411
  import { NavLink } from "react-router-dom";
1237
2412
  var ActiveLink = /* @__PURE__ */ forwardRef(({ to, onClick, className, style, children, ...rest }, ref) => {
1238
2413
  const [currentHash, setCurrentHash] = useState5(() => typeof window !== "undefined" ? window.location.hash : "");
1239
2414
  const isHashRoute = typeof to === "string" && to.startsWith("#");
1240
- useEffect5(() => {
2415
+ useEffect7(() => {
1241
2416
  if (!isHashRoute) return;
1242
2417
  const handleHashChange = /* @__PURE__ */ __name(() => {
1243
2418
  setCurrentHash(window.location.hash);
@@ -1249,7 +2424,7 @@ var ActiveLink = /* @__PURE__ */ forwardRef(({ to, onClick, className, style, ch
1249
2424
  ]);
1250
2425
  const isActive = isHashRoute && currentHash === to;
1251
2426
  if (!isHashRoute) {
1252
- return /* @__PURE__ */ React7.createElement(NavLink, {
2427
+ return /* @__PURE__ */ React8.createElement(NavLink, {
1253
2428
  ref,
1254
2429
  to,
1255
2430
  onClick,
@@ -1290,7 +2465,7 @@ var ActiveLink = /* @__PURE__ */ forwardRef(({ to, onClick, className, style, ch
1290
2465
  isPending: false,
1291
2466
  isTransitioning: false
1292
2467
  }) : children;
1293
- return /* @__PURE__ */ React7.createElement("a", {
2468
+ return /* @__PURE__ */ React8.createElement("a", {
1294
2469
  ref,
1295
2470
  href: to,
1296
2471
  onClick: handleHashClick,
@@ -1302,12 +2477,12 @@ var ActiveLink = /* @__PURE__ */ forwardRef(({ to, onClick, className, style, ch
1302
2477
  ActiveLink.displayName = "ActiveLink";
1303
2478
 
1304
2479
  // src/route-components/NavLink.tsx
1305
- import * as React8 from "react";
1306
- import { NavLink as OriginalNavLink, useLocation, useNavigate } from "react-router-dom";
1307
- var NavLink2 = /* @__PURE__ */ React8.forwardRef(({ to, children, className, style, ...props }, ref) => {
2480
+ import * as React9 from "react";
2481
+ import { NavLink as OriginalNavLink, useLocation as useLocation2, useNavigate as useNavigate2 } from "react-router-dom";
2482
+ var NavLink2 = /* @__PURE__ */ React9.forwardRef(({ to, children, className, style, ...props }, ref) => {
1308
2483
  const isHashLink = typeof to === "string" && to.startsWith("#");
1309
- const location = useLocation();
1310
- const navigate = useNavigate();
2484
+ const location = useLocation2();
2485
+ const navigate = useNavigate2();
1311
2486
  if (isHashLink) {
1312
2487
  const handleClick = /* @__PURE__ */ __name((e) => {
1313
2488
  e.preventDefault();
@@ -1328,7 +2503,7 @@ var NavLink2 = /* @__PURE__ */ React8.forwardRef(({ to, children, className, sty
1328
2503
  const resolvedClassName = typeof className === "function" ? className(renderProps) : className;
1329
2504
  const resolvedStyle = typeof style === "function" ? style(renderProps) : style;
1330
2505
  const { caseSensitive, end, replace, state, preventScrollReset, relative, viewTransition, ...restProps } = props;
1331
- return /* @__PURE__ */ React8.createElement("a", {
2506
+ return /* @__PURE__ */ React9.createElement("a", {
1332
2507
  href: to,
1333
2508
  onClick: handleClick,
1334
2509
  ref,
@@ -1337,7 +2512,7 @@ var NavLink2 = /* @__PURE__ */ React8.forwardRef(({ to, children, className, sty
1337
2512
  ...restProps
1338
2513
  }, typeof children === "function" ? children(renderProps) : children);
1339
2514
  }
1340
- return /* @__PURE__ */ React8.createElement(OriginalNavLink, {
2515
+ return /* @__PURE__ */ React9.createElement(OriginalNavLink, {
1341
2516
  to,
1342
2517
  ref,
1343
2518
  className,
@@ -1352,7 +2527,7 @@ var NavLink2 = /* @__PURE__ */ React8.forwardRef(({ to, children, className, sty
1352
2527
  NavLink2.displayName = "NavLink";
1353
2528
 
1354
2529
  // src/route-components/UniversalLink.tsx
1355
- import React9 from "react";
2530
+ import React10 from "react";
1356
2531
  import { Link as RouterLink } from "react-router-dom";
1357
2532
  function isInternalRoute(to) {
1358
2533
  return !to.startsWith("#") && !to.startsWith("http://") && !to.startsWith("https://") && !to.startsWith("//");
@@ -1362,15 +2537,15 @@ function isExternalLink(to) {
1362
2537
  return to.startsWith("http://") || to.startsWith("https://") || to.startsWith("//");
1363
2538
  }
1364
2539
  __name(isExternalLink, "isExternalLink");
1365
- var UniversalLink = /* @__PURE__ */ React9.forwardRef(/* @__PURE__ */ __name(function UniversalLink2({ to, ...props }, ref) {
2540
+ var UniversalLink = /* @__PURE__ */ React10.forwardRef(/* @__PURE__ */ __name(function UniversalLink2({ to, ...props }, ref) {
1366
2541
  if (isInternalRoute(to)) {
1367
- return /* @__PURE__ */ React9.createElement(RouterLink, {
2542
+ return /* @__PURE__ */ React10.createElement(RouterLink, {
1368
2543
  to,
1369
2544
  ref,
1370
2545
  ...props
1371
2546
  });
1372
2547
  }
1373
- return /* @__PURE__ */ React9.createElement("a", {
2548
+ return /* @__PURE__ */ React10.createElement("a", {
1374
2549
  href: to,
1375
2550
  ref,
1376
2551
  ...props,
@@ -1516,45 +2691,6 @@ function getEnvPath() {
1516
2691
  }
1517
2692
  __name(getEnvPath, "getEnvPath");
1518
2693
 
1519
- // src/utils/safeStringify.ts
1520
- function safeStringify(obj) {
1521
- const seen = /* @__PURE__ */ new Set();
1522
- try {
1523
- return JSON.stringify(obj, (_key, value) => {
1524
- if (typeof value === "object" && value !== null) {
1525
- if (seen.has(value)) {
1526
- return "[Circular]";
1527
- }
1528
- seen.add(value);
1529
- }
1530
- if (typeof value === "bigint") {
1531
- return value.toString();
1532
- }
1533
- if (value instanceof Date) {
1534
- return value.toISOString();
1535
- }
1536
- if (value instanceof Map) {
1537
- return Object.fromEntries(value);
1538
- }
1539
- if (value instanceof Set) {
1540
- return Array.from(value);
1541
- }
1542
- if (typeof value === "undefined") {
1543
- return "undefined";
1544
- }
1545
- if (typeof value === "symbol") {
1546
- return value.toString();
1547
- }
1548
- return value;
1549
- });
1550
- } catch {
1551
- return "";
1552
- } finally {
1553
- seen.clear();
1554
- }
1555
- }
1556
- __name(safeStringify, "safeStringify");
1557
-
1558
2694
  // src/utils/getAxiosForBackend.ts
1559
2695
  import axios2 from "axios";
1560
2696
  var axiosInstance;
@@ -1634,73 +2770,26 @@ function getAxiosForBackend() {
1634
2770
  __name(getAxiosForBackend, "getAxiosForBackend");
1635
2771
  var axiosForBackend = getAxiosForBackend();
1636
2772
 
1637
- // src/utils/url.ts
1638
- function splitWorkspaceUrl(fullUrl) {
1639
- try {
1640
- const url = new URL(fullUrl);
1641
- const pathParts = url.pathname.split("/");
1642
- const workspacesIndex = pathParts.findIndex((part) => part === "workspaces");
1643
- if (workspacesIndex === -1) {
1644
- throw new Error("Invalid workspace URL format");
1645
- }
1646
- const basePathParts = pathParts.slice(0, workspacesIndex);
1647
- const workspace = pathParts[workspacesIndex + 1];
1648
- return {
1649
- baseUrl: `${url.origin}${basePathParts.join("/")}`,
1650
- workspace
1651
- };
1652
- } catch (error) {
1653
- console.error("Error splitting workspace URL:", error);
1654
- }
1655
- return {
1656
- baseUrl: fullUrl,
1657
- // 兜底给一个,不要给空字符串,不然 createClient 都直接挂了,页面会白屏,体感不太好
1658
- workspace: "workspace"
1659
- };
1660
- }
1661
- __name(splitWorkspaceUrl, "splitWorkspaceUrl");
1662
-
1663
- // src/integrations/dataloom.ts
1664
- import { createClient } from "@lark-apaas/dataloom";
1665
- import { authClient as authClient3 } from "@lark-apaas/auth-sdk";
1666
- var createDataLoomClient = /* @__PURE__ */ __name((url, pat) => {
1667
- const { baseUrl } = url ? splitWorkspaceUrl(url) : {
1668
- baseUrl: ""
1669
- };
1670
- const appId = getAppId() ?? "";
1671
- return createClient(baseUrl, pat ?? "", {
1672
- global: {
1673
- enableDataloomLog: process.env.NODE_ENV !== "production",
1674
- requestRateLimit: process.env.NODE_ENV !== "production" ? 100 : void 0,
1675
- brandName: "miaoda",
1676
- appId,
1677
- accountServices: {
1678
- user: authClient3.user,
1679
- session: authClient3.session
1680
- }
2773
+ // src/integrations/capabilityClient.ts
2774
+ import { createClient as createClient2 } from "@lark-apaas/client-capability";
2775
+ var _appId = getAppId();
2776
+ var _acquireUploadUrl = isNewPathEnabled() ? `/app/${_appId}/__runtime__/api/v1/studio/plugins/tmp_files/acquire_upload_url` : `/af/api/v1/studio/plugins/tmp_files/acquire_upload_url`;
2777
+ var _acquireDownloadUrl = isNewPathEnabled() ? `/app/${_appId}/__runtime__/api/v1/studio/plugins/tmp_files/acquire_download_url` : `/af/api/v1/studio/plugins/tmp_files/acquire_download_url`;
2778
+ var capabilityClient = createClient2({
2779
+ baseURL: normalizeBasePath(process.env.CLIENT_BASE_PATH ?? "/"),
2780
+ acquireUploadUrl: _acquireUploadUrl,
2781
+ acquireDownloadUrl: _acquireDownloadUrl,
2782
+ fetchOptions: {
2783
+ headers: {
2784
+ "X-Suda-Csrf-Token": window.csrfToken ?? ""
1681
2785
  }
1682
- });
1683
- }, "createDataLoomClient");
1684
- var dataloom = null;
1685
- var pendingPromise2 = null;
1686
- function getDataloom() {
1687
- if (dataloom) {
1688
- return Promise.resolve(dataloom);
1689
- }
1690
- if (pendingPromise2) {
1691
- return pendingPromise2;
2786
+ },
2787
+ central: {
2788
+ enabled: true,
2789
+ // window.appId 由妙搭沙箱 / 线上环境注入;非妙搭场景下 capability 调用本身不可用
2790
+ appId: _appId ?? ""
1692
2791
  }
1693
- pendingPromise2 = getInitialInfo().then((info) => {
1694
- const DATALOOM_CLIENT_URL = info?.app_runtime_extra?.url;
1695
- const DATALOOM_PAT = info?.app_runtime_extra?.token;
1696
- dataloom = createDataLoomClient(DATALOOM_CLIENT_URL, DATALOOM_PAT);
1697
- return dataloom;
1698
- }).finally(() => {
1699
- pendingPromise2 = null;
1700
- });
1701
- return pendingPromise2;
1702
- }
1703
- __name(getDataloom, "getDataloom");
2792
+ });
1704
2793
 
1705
2794
  // src/constants/img-resources/avatar.ts
1706
2795
  var avatar_exports = {};
@@ -1861,6 +2950,7 @@ var abstractArt3dRenderingCoverImg6 = "https://lf3-static.bytednsdoc.com/obj/ede
1861
2950
  export {
1862
2951
  ActiveLink,
1863
2952
  AppContainer_default as AppContainer,
2953
+ ErrorRender_default as ErrorRender,
1864
2954
  NavLink2 as NavLink,
1865
2955
  PagePlaceholder_default as PagePlaceholder,
1866
2956
  QueryProvider_default as QueryProvider,
@@ -1870,6 +2960,7 @@ export {
1870
2960
  avatar_exports as avatarImages,
1871
2961
  axiosForBackend,
1872
2962
  banner_exports as bannerImages,
2963
+ capabilityClient,
1873
2964
  clsxWithTw,
1874
2965
  copyToClipboard,
1875
2966
  cover_exports as coverImages,
@@ -1886,6 +2977,7 @@ export {
1886
2977
  isIpad,
1887
2978
  isMobile,
1888
2979
  isPreview,
2980
+ logger,
1889
2981
  normalizeBasePath,
1890
2982
  reportTeaEvent,
1891
2983
  resolveAppUrl,