@dimina-kit/devkit 0.1.1 → 0.1.2-dev.20260522085907

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/README.md CHANGED
@@ -44,7 +44,9 @@ await session.close()
44
44
  | `port` | `number` | `0` | 预览服务器端口,`0` 表示自动分配 |
45
45
  | `sourcemap` | `boolean` | `false` | 是否生成 sourcemap |
46
46
  | `simulatorDir` | `string` | -- | 模拟器外壳静态资源目录;不传则不启用 `/simulator` 路由 |
47
+ | `containerDir` | `string` | -- | H5 容器静态资源目录;不传则使用内置 `dimina-fe-container` |
47
48
  | `outputDir` | `string` | -- | 编译产物输出目录,默认 `<os.tmpdir()>/dimina-kit/<projectPath 哈希前 12 位>`(每个项目独立) |
49
+ | `watch` | `boolean` | `true` | 为 `false` 时跳过 chokidar 文件监听 / 自动重编译循环 |
48
50
  | `onRebuild` | `() => void` | -- | 文件变更触发重新编译后的回调 |
49
51
  | `onBuildError` | `(err: unknown) => void` | -- | 编译出错时的回调 |
50
52
 
package/dist/index.d.ts CHANGED
@@ -8,14 +8,25 @@ export interface ProjectSession {
8
8
  port: number;
9
9
  close: () => Promise<void>;
10
10
  }
11
- export declare function openProject(opts: {
11
+ export interface OpenProjectOptions {
12
12
  projectPath: string;
13
13
  port?: number;
14
14
  sourcemap?: boolean;
15
15
  simulatorDir?: string;
16
16
  containerDir?: string;
17
17
  outputDir?: string;
18
+ /** When false, skip the chokidar file-watcher / auto-rebuild loop. Default true. */
19
+ watch?: boolean;
18
20
  onRebuild?: () => void;
19
21
  onBuildError?: (err: unknown) => void;
20
- }): Promise<ProjectSession>;
22
+ }
23
+ export declare function openProject(opts: OpenProjectOptions): Promise<ProjectSession>;
24
+ /**
25
+ * Watch a project directory and invoke `onChange` whenever a source file is
26
+ * created, modified, or deleted. Returns a handle whose `close()` stops the
27
+ * watcher.
28
+ */
29
+ export declare function createProjectWatcher(projectPath: string, onChange: () => void | Promise<void>): {
30
+ close: () => Promise<void>;
31
+ };
21
32
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAiDA,MAAM,WAAW,OAAO;IACvB,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACZ;AAED,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1B;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE;IACvC,WAAW,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAA;CACrC,GAAG,OAAO,CAAC,cAAc,CAAC,CAmF1B"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAiDA,MAAM,WAAW,OAAO;IACvB,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACZ;AAED,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1B;AAED,MAAM,WAAW,kBAAkB;IAClC,WAAW,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,oFAAoF;IACpF,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAA;CACrC;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,cAAc,CAAC,CA4GnF;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CACnC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAClC;IAAE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAgBhC"}
package/dist/index.js CHANGED
@@ -35,7 +35,7 @@ function getRandomPort() {
35
35
  });
36
36
  }
37
37
  export async function openProject(opts) {
38
- const { projectPath: rawProjectPath, port = 0, sourcemap = false, simulatorDir, containerDir: overrideContainerDir, outputDir, onRebuild, onBuildError, } = opts;
38
+ const { projectPath: rawProjectPath, port = 0, sourcemap = false, simulatorDir, containerDir: overrideContainerDir, outputDir, watch = true, onRebuild, onBuildError, } = opts;
39
39
  const projectPath = path.resolve(rawProjectPath);
40
40
  const buildOptions = { sourcemap };
41
41
  const resolvedPort = port === 0 ? await getRandomPort() : port;
@@ -52,6 +52,34 @@ export async function openProject(opts) {
52
52
  finally {
53
53
  process.chdir(prevCwd);
54
54
  }
55
+ // When the compiler is racing (e.g. opening a project that was just
56
+ // closed elsewhere in the same Electron process) `build()` can return
57
+ // null even though the manifest on disk is perfectly readable. The
58
+ // pre-existing fallback to `{ appId: 'unknown' }` was load-bearing for
59
+ // any consumer that calls `wx.setStorageSync` — the dimina runtime
60
+ // stores values under `${appId}_${key}` and the devtools storage panel
61
+ // also derives its IPC prefix from `appInfo.appId`. A stale `unknown`
62
+ // appId makes the panel and the runtime disagree (panel writes
63
+ // `unknown_foo`, runtime reads `${realAppId}_foo`), so this falls back
64
+ // to the canonical id from `project.config.json` instead. The literal
65
+ // `'unknown'` is only used as a last resort when the manifest itself
66
+ // is missing/unreadable, preserving the original error path.
67
+ if (!initialAppInfo) {
68
+ try {
69
+ const configRaw = fs.readFileSync(path.join(projectPath, 'project.config.json'), 'utf8');
70
+ const config = JSON.parse(configRaw);
71
+ if (config.appid && typeof config.appid === 'string' && config.appid.length > 0) {
72
+ initialAppInfo = {
73
+ appId: config.appid,
74
+ name: config.projectname ?? path.basename(projectPath),
75
+ path: projectPath,
76
+ };
77
+ }
78
+ }
79
+ catch {
80
+ // best-effort — fall through to the 'unknown' fallback below
81
+ }
82
+ }
55
83
  const sessionApps = initialAppInfo ? [initialAppInfo] : [];
56
84
  process.env.DIMINA_NO_OPEN_BROWSER = '1';
57
85
  const fe = await import('../fe/index.js');
@@ -64,13 +92,8 @@ export async function openProject(opts) {
64
92
  liveReload: true,
65
93
  sessionApps,
66
94
  });
67
- const watcher = chokidar.watch(projectPath, {
68
- ignored: /(^|[/\\])\../,
69
- persistent: true,
70
- ignoreInitial: true,
71
- });
72
95
  let isBuilding = false;
73
- watcher.on('change', async () => {
96
+ async function rebuild() {
74
97
  if (isBuilding)
75
98
  return;
76
99
  isBuilding = true;
@@ -94,14 +117,37 @@ export async function openProject(opts) {
94
117
  process.chdir(prevCwd);
95
118
  isBuilding = false;
96
119
  }
97
- });
120
+ }
121
+ const watcher = watch ? createProjectWatcher(projectPath, rebuild) : null;
98
122
  return {
99
123
  appInfo: initialAppInfo ?? { appId: 'unknown', name: path.basename(projectPath), path: projectPath },
100
124
  port: resolvedPort,
101
125
  close: async () => {
102
- await watcher.close();
126
+ await watcher?.close();
103
127
  server.closeAllConnections?.();
104
128
  await new Promise(resolve => server.close(() => resolve()));
105
129
  },
106
130
  };
107
131
  }
132
+ /**
133
+ * Watch a project directory and invoke `onChange` whenever a source file is
134
+ * created, modified, or deleted. Returns a handle whose `close()` stops the
135
+ * watcher.
136
+ */
137
+ export function createProjectWatcher(projectPath, onChange) {
138
+ const watcher = chokidar.watch(projectPath, {
139
+ ignored: /(^|[/\\])\../,
140
+ persistent: true,
141
+ ignoreInitial: true,
142
+ });
143
+ // Listen to add + change + unlink so creating, editing, and deleting a
144
+ // source file all surface as onChange. Listening only to 'change' silently
145
+ // dropped the "developer added a new page" case (a chokidar 'add' event)
146
+ // and made auto-compile feel broken on a common save pattern.
147
+ watcher.on('add', () => { void onChange(); });
148
+ watcher.on('change', () => { void onChange(); });
149
+ watcher.on('unlink', () => { void onChange(); });
150
+ return {
151
+ close: () => watcher.close(),
152
+ };
153
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=project-watcher.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-watcher.test.d.ts","sourceRoot":"","sources":["../src/project-watcher.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,152 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+ import { createProjectWatcher } from './index.js';
6
+ /**
7
+ * Behavior tests for createProjectWatcher.
8
+ *
9
+ * These tests pin down the user-visible contract: when a developer edits
10
+ * something inside their mini-app project, the watcher must fire onChange so
11
+ * auto-compile can run. We deliberately use the real filesystem and real
12
+ * chokidar — the suspected bug is in how chokidar is configured against
13
+ * macOS reality, so any mocking would mask it.
14
+ */
15
+ // macOS's os.tmpdir() lives under /var which is a symlink to /private/var.
16
+ // Some watcher configurations resolve symlinks and some don't; if we pass the
17
+ // /var path in but chokidar reports events under /private/var, every test
18
+ // would fail for the wrong reason. Normalize via realpath so the watcher
19
+ // path and the path we mutate match byte-for-byte.
20
+ function makeTempProject() {
21
+ const raw = fs.mkdtempSync(path.join(os.tmpdir(), 'devkit-watcher-'));
22
+ return fs.realpathSync(raw);
23
+ }
24
+ // Give chokidar time to finish its initial scan before we start mutating.
25
+ // createProjectWatcher doesn't expose chokidar's 'ready' event, so a short
26
+ // settle delay is the practical option. 300ms is conservative on macOS.
27
+ const READY_DELAY_MS = 300;
28
+ async function settle(ms = READY_DELAY_MS) {
29
+ await new Promise(resolve => setTimeout(resolve, ms));
30
+ }
31
+ describe('createProjectWatcher', () => {
32
+ let tempDir;
33
+ let handle;
34
+ beforeEach(() => {
35
+ tempDir = makeTempProject();
36
+ handle = undefined;
37
+ });
38
+ afterEach(async () => {
39
+ if (handle) {
40
+ try {
41
+ await handle.close();
42
+ }
43
+ catch {
44
+ // ignore close errors during cleanup
45
+ }
46
+ }
47
+ fs.rmSync(tempDir, { recursive: true, force: true });
48
+ });
49
+ it('fires onChange when an existing file is overwritten', async () => {
50
+ // Why this matters: the bread-and-butter case — developer hits save in
51
+ // their editor on an existing file (e.g. app.json) and expects a rebuild.
52
+ const target = path.join(tempDir, 'app.json');
53
+ fs.writeFileSync(target, '{}');
54
+ const onChange = vi.fn();
55
+ handle = createProjectWatcher(tempDir, onChange);
56
+ await settle();
57
+ fs.writeFileSync(target, '{"a":1}');
58
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 2000 });
59
+ });
60
+ it('fires onChange when a brand-new file is created', async () => {
61
+ // Why this matters: "I added a new page and nothing rebuilt" is one of
62
+ // the most common auto-compile complaints.
63
+ fs.mkdirSync(path.join(tempDir, 'pages'), { recursive: true });
64
+ const onChange = vi.fn();
65
+ handle = createProjectWatcher(tempDir, onChange);
66
+ await settle();
67
+ fs.writeFileSync(path.join(tempDir, 'pages', 'new-page.js'), '// new');
68
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 2000 });
69
+ });
70
+ it('fires onChange when a file is deleted', async () => {
71
+ // Why this matters: removing a page should also trigger a rebuild so
72
+ // route tables and asset manifests stay in sync.
73
+ fs.mkdirSync(path.join(tempDir, 'pages'), { recursive: true });
74
+ const target = path.join(tempDir, 'pages', 'index.js');
75
+ fs.writeFileSync(target, '// initial');
76
+ const onChange = vi.fn();
77
+ handle = createProjectWatcher(tempDir, onChange);
78
+ await settle();
79
+ fs.unlinkSync(target);
80
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 2000 });
81
+ });
82
+ it('fires onChange on atomic-save rename (editor writes temp file, renames over target)', async () => {
83
+ // Why this matters: VS Code on macOS uses atomic-save by default — it
84
+ // writes to app.json.tmp-xyz and renames it over app.json. If the
85
+ // watcher only listens for direct writes, every save in VS Code looks
86
+ // like nothing happened. We accept any number of onChange invocations
87
+ // >= 1, since this single user action can naturally surface as either
88
+ // an "add" or a "change" event in chokidar.
89
+ const target = path.join(tempDir, 'app.json');
90
+ fs.writeFileSync(target, '{}');
91
+ const onChange = vi.fn();
92
+ handle = createProjectWatcher(tempDir, onChange);
93
+ await settle();
94
+ const tmp = path.join(tempDir, 'app.json.tmp-xyz');
95
+ fs.writeFileSync(tmp, '{"a":1}');
96
+ fs.renameSync(tmp, target);
97
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 2000 });
98
+ });
99
+ it('fires onChange for edits deep inside subdirectories', async () => {
100
+ // Why this matters: mini-app source trees are always nested
101
+ // (pages/index/index.wxml, components/foo/foo.js). If the watcher is
102
+ // non-recursive or has a shallow depth setting, the most common files
103
+ // in the project will silently fail to rebuild.
104
+ const nestedDir = path.join(tempDir, 'pages', 'index');
105
+ fs.mkdirSync(nestedDir, { recursive: true });
106
+ const target = path.join(nestedDir, 'index.wxml');
107
+ fs.writeFileSync(target, '<view></view>');
108
+ const onChange = vi.fn();
109
+ handle = createProjectWatcher(tempDir, onChange);
110
+ await settle();
111
+ fs.writeFileSync(target, '<view>updated</view>');
112
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 2000 });
113
+ });
114
+ it('stays quiet when only .git internals change', async () => {
115
+ // Why this matters: if the watcher picks up .git/HEAD shuffling or
116
+ // other VCS bookkeeping, every `git checkout` or `git commit` triggers
117
+ // a spurious rebuild — and worse, an auto-compile that itself touches
118
+ // files can loop. The watcher must ignore .git entirely.
119
+ const gitDir = path.join(tempDir, '.git');
120
+ fs.mkdirSync(gitDir, { recursive: true });
121
+ const head = path.join(gitDir, 'HEAD');
122
+ fs.writeFileSync(head, 'ref: refs/heads/main\n');
123
+ const onChange = vi.fn();
124
+ handle = createProjectWatcher(tempDir, onChange);
125
+ await settle();
126
+ fs.writeFileSync(head, 'ref: refs/heads/other\n');
127
+ // Negative assertion: wait a bit, then confirm no call happened.
128
+ // We don't use vi.waitFor here because we're proving absence, not
129
+ // presence — vi.waitFor would just burn the full timeout regardless.
130
+ await settle(500);
131
+ expect(onChange).not.toHaveBeenCalled();
132
+ });
133
+ it('stops firing onChange after close() is called', async () => {
134
+ // Why this matters: when a project session ends (user closes the
135
+ // devtools window, switches projects), lingering watchers would keep
136
+ // triggering rebuilds against stale state. close() must actually stop
137
+ // the watcher.
138
+ const target = path.join(tempDir, 'app.json');
139
+ fs.writeFileSync(target, '{}');
140
+ const onChange = vi.fn();
141
+ handle = createProjectWatcher(tempDir, onChange);
142
+ await settle();
143
+ await handle.close();
144
+ handle = undefined; // prevent afterEach double-close
145
+ // Clear any events that arrived during the ready window so we're only
146
+ // measuring what happens after close().
147
+ onChange.mockClear();
148
+ fs.writeFileSync(target, '{"after":"close"}');
149
+ await settle(500);
150
+ expect(onChange).not.toHaveBeenCalled();
151
+ });
152
+ });
@@ -1 +1 @@
1
- var e=(e=0)=>t=>`[${t+e}m`,t=(e=0)=>t=>`[${38+e};5;${t}m`,i=(e=0)=>(t,i,s)=>`[${38+e};2;${t};${i};${s}m`,s={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(s.modifier),Object.keys(s.color),Object.keys(s.bgColor);var a=function(){const a=/* @__PURE__ */new Map;for(const[e,t]of Object.entries(s)){for(const[e,i]of Object.entries(t))s[e]={open:`[${i[0]}m`,close:`[${i[1]}m`},t[e]=s[e],a.set(i[0],i[1]);Object.defineProperty(s,e,{value:t,enumerable:!1})}return Object.defineProperty(s,"codes",{value:a,enumerable:!1}),s.color.close="",s.bgColor.close="",s.color.ansi=e(),s.color.ansi256=t(),s.color.ansi16m=i(),s.bgColor.ansi=e(10),s.bgColor.ansi256=t(10),s.bgColor.ansi16m=i(10),Object.defineProperties(s,{rgbToAnsi256:{value:(e,t,i)=>e===t&&t===i?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(i/255*5),enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[i]=t;3===i.length&&(i=[...i].map(e=>e+e).join(""));const s=Number.parseInt(i,16);return[s>>16&255,s>>8&255,255&s]},enumerable:!1},hexToAnsi256:{value:e=>s.rgbToAnsi256(...s.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return e-8+90;let t,i,s;if(e>=232)t=(10*(e-232)+8)/255,i=t,s=t;else{const a=(e-=16)%36;t=Math.floor(e/36)/5,i=Math.floor(a/6)/5,s=a%6/5}const a=2*Math.max(t,i,s);if(0===a)return 30;let n=30+(Math.round(s)<<2|Math.round(i)<<1|Math.round(t));return 2===a&&(n+=60),n},enumerable:!1},rgbToAnsi:{value:(e,t,i)=>s.ansi256ToAnsi(s.rgbToAnsi256(e,t,i)),enumerable:!1},hexToAnsi:{value:e=>s.ansi256ToAnsi(s.hexToAnsi256(e)),enumerable:!1}}),s}(),n=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const e=navigator.userAgentData.brands.find(({brand:e})=>"Chromium"===e);if(e&&e.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),o=0!==n&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3},r={stdout:o,stderr:o};function l(e,t,i){let s=e.indexOf(t);if(-1===s)return e;const a=t.length;let n=0,o="";do{o+=e.slice(n,s)+t+i,n=s+a,s=e.indexOf(t,n)}while(-1!==s);return o+=e.slice(n),o}var{stdout:c,stderr:d}=r,h=Symbol("GENERATOR"),p=Symbol("STYLER"),g=Symbol("IS_EMPTY"),m=["ansi","ansi","ansi256","ansi16m"],u=Object.create(null),v=e=>{const t=(...e)=>e.join(" ");return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const i=c?c.level:0;e.level=void 0===t.level?i:t.level})(t,e),Object.setPrototypeOf(t,w.prototype),t};function w(e){return v(e)}Object.setPrototypeOf(w.prototype,Function.prototype);for(const[j,O]of Object.entries(a))u[j]={get(){const e=C(this,y(O.open,O.close,this[p]),this[g]);return Object.defineProperty(this,j,{value:e}),e}};u.visible={get(){const e=C(this,this[p],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var b=(e,t,i,...s)=>"rgb"===e?"ansi16m"===t?a[i].ansi16m(...s):"ansi256"===t?a[i].ansi256(a.rgbToAnsi256(...s)):a[i].ansi(a.rgbToAnsi(...s)):"hex"===e?b("rgb",t,i,...a.hexToRgb(...s)):a[i][e](...s);for(const j of["rgb","hex","ansi256"]){u[j]={get(){const{level:e}=this;return function(...t){const i=y(b(j,m[e],"color",...t),a.color.close,this[p]);return C(this,i,this[g])}}};u["bg"+j[0].toUpperCase()+j.slice(1)]={get(){const{level:e}=this;return function(...t){const i=y(b(j,m[e],"bgColor",...t),a.bgColor.close,this[p]);return C(this,i,this[g])}}}}var f=Object.defineProperties(()=>{},{...u,level:{enumerable:!0,get(){return this[h].level},set(e){this[h].level=e}}}),y=(e,t,i)=>{let s,a;return void 0===i?(s=e,a=t):(s=i.openAll+e,a=t+i.closeAll),{open:e,close:t,openAll:s,closeAll:a,parent:i}},C=(e,t,i)=>{const s=(...e)=>_(s,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(s,f),s[h]=e,s[p]=t,s[g]=i,s},_=(e,t)=>{if(e.level<=0||!t)return e[g]?"":t;let i=e[p];if(void 0===i)return t;const{openAll:s,closeAll:a}=i;if(t.includes(""))for(;void 0!==i;)t=l(t,i.close,i.open),i=i.parent;const n=t.indexOf("\n");return-1!==n&&(t=function(e,t,i,s){let a=0,n="";do{const o="\r"===e[s-1];n+=e.slice(a,o?s-1:s)+t+(o?"\r\n":"\n")+i,a=s+1,s=e.indexOf("\n",a)}while(-1!==s);return n+=e.slice(a),n}(t,a,s,n)),s+t+a};Object.defineProperties(w.prototype,u);w(),w({level:d?d.level:0});function k(e){return{all:e=e||/* @__PURE__ */new Map,on:function(t,i){var s=e.get(t);s?s.push(i):e.set(t,[i])},off:function(t,i){var s=e.get(t);s&&(i?s.splice(s.indexOf(i)>>>0,1):e.set(t,[]))},emit:function(t,i){var s=e.get(t);s&&s.slice().map(function(e){e(i)}),(s=e.get("*"))&&s.slice().map(function(e){e(t,i)})}}}function S(){return Math.random().toString(36).slice(2,7)}function L(e){const t=e.split("?"),i=t[0],s=t[1],a={query:{},pagePath:i};return s?(s.split("&").forEach(e=>{const t=e.split("=")[0],i=e.split("=")[1];a.query[t]=i}),a):a}function I(e,t){const i={},s=e.window||{},a=t||{};return i.navigationBarTitleText=a.navigationBarTitleText||s.navigationBarTitleText||"",i.navigationBarBackgroundColor=a.navigationBarBackgroundColor||s.navigationBarBackgroundColor||"#000",i.navigationBarTextStyle=a.navigationBarTextStyle||s.navigationBarTextStyle||"white",i.backgroundColor=a.backgroundColor||s.backgroundColor||"#fff",i.navigationStyle=a.navigationStyle||s.navigationStyle||"default",i.usingComponents=a.usingComponents||{},i}var M=class{constructor(e){this.opts=e,this.id=`webview_${S()}`,this.el=document.createElement("div"),this.el.classList.add("dimina-native-view"),this.el.innerHTML='<div class="dimina-native-webview">\n\t\x3c!-- 导航区域 --\x3e\n\t<div class="dimina-native-webview__navigation">\n\t\t<div class="dimina-native-webview__navigation-content">\n\t\t\t<div class="dimina-native-webview__navigation-left-btn"></div>\n\t\t\t<h2 class="dimina-native-webview__navigation-title"></h2>\n\t\t</div>\n\t</div>\n\n\t\x3c!-- iframe --\x3e\n\t<div class="dimina-native-webview__body">\n\t\t<div class="dimina-native-webview__root">\n\t\t\t<iframe class="dimina-native-webview__window" title="pageFrame"></iframe>\n\t\t</div>\n\t</div>\n</div>',this.setInitialStyle(),this.iframe=this.el.querySelector(".dimina-native-webview__window"),this.iframe.src="/pageFrame.html",this.iframe.name=this.id,this.event=k(),this.bindBackEvent()}async init(e){await this.frameLoaded();const t=window.frames[this.iframe.name];t.DiminaRenderBridge.invoke=e=>{this.event.emit("invoke",e)},t.DiminaRenderBridge.publish=e=>{this.event.emit("publish",e)},e?.()}invoke(e){this.event.on("invoke",e)}publish(e){this.event.on("publish",e)}postMessage(e){window.frames[this.iframe.name].DiminaRenderBridge.onMessage(e)}bindBackEvent(){this.el.querySelector(".dimina-native-webview__navigation-left-btn").onclick=()=>{this.parent.parent.navigateBack()}}frameLoaded(){return new Promise(e=>{this.iframe.onload=()=>{e()}})}setInitialStyle(){const e=this.opts.configInfo,t=this.el.querySelector(".dimina-native-webview"),i=this.el.querySelector(".dimina-native-webview__navigation-title"),s=this.el.querySelector(".dimina-native-webview__navigation"),a=this.el.querySelector(".dimina-native-webview__navigation-left-btn"),n=this.el.querySelector(".dimina-native-webview__root");this.opts.isRoot?a.style.display="none":a.style.display="block","white"===e.navigationBarTextStyle?s.classList.add("dimina-native-webview__navigation--white"):s.classList.add("dimina-native-webview__navigation--black"),"custom"===e.navigationStyle&&t.classList.add("dimina-native-webview--custom-nav"),n.style.backgroundColor=e.backgroundColor,s.style.backgroundColor=e.navigationBarBackgroundColor,i.textContent=e.navigationBarTitleText}},P=class{constructor(e){this.id=`bridge_${S()}`,this.opts=e,this.webview=null,this.jscore=e.jscore,this.parent=null,this.resetStatus()}async init(){this.jscore.invoke(e=>this.messageInvoke("service",e)),this.jscore.publish(e=>this.messagePublish(e)),this.webview=await this.createWebview(),this.webview.invoke(e=>this.messageInvoke("render",e)),this.webview.publish(e=>this.messagePublish(e))}messagePublish(e){"string"==typeof e&&(e=JSON.parse(e));const{body:t,target:i}=e;t.bridgeId&&t.bridgeId!==this.id||("service"===i?this.jscore.postMessage(e):"render"===i&&this.webview.postMessage(e))}messageInvoke(e,t){"string"==typeof t&&(t=JSON.parse(t));const{type:i,body:s,target:a}=t;if(s.bridgeId&&s.bridgeId!==this.id)return;const n={type:i,body:{bridgeId:this.id,pagePath:this.opts.pagePath,scene:this.opts.scene,query:this.opts.query,...s}};if("service"===a){if("serviceResourceLoaded"===i){if(this.serviceResource=!0,!this.isResourceLoaded())return;n.type="resourceLoaded"}else if("renderResourceLoaded"===i){if(this.renderResource=!0,!this.isResourceLoaded())return;n.type="resourceLoaded"}this.jscore.postMessage(n)}else if("container"===a&&"invokeAPI"===i){const{name:e,params:t}=s;this.parent.invokeApi(e,t)}}start(){this.webview.postMessage({type:"loadResource",body:{bridgeId:this.id,appId:this.opts.appId,pagePath:this.opts.pagePath,root:this.opts.root,baseUrl:"/"}}),this.jscore.postMessage({type:"loadResource",body:{bridgeId:this.id,appId:this.opts.appId,pagePath:this.opts.pagePath,root:this.opts.root,baseUrl:"/",hostEnv:this.parent.getHostEnvSnapshot()}})}resetStatus(){this.serviceResource=!1,this.renderResource=!1}createWebview(){return new Promise(e=>{const t=new M({configInfo:this.opts.configInfo,isRoot:this.opts.isRoot});t.parent=this,t.init(()=>{e(t)}),this.opts.isRoot||t.el.classList.add("dimina-native-view--before-enter"),this.parent.webviewsContainer.appendChild(t.el)})}isResourceLoaded(){return this.serviceResource&&this.renderResource}appShow(){this.isResourceLoaded()&&this.jscore.postMessage({type:"appShow",body:{}})}appHide(){this.isResourceLoaded()&&this.jscore.postMessage({type:"appHide",body:{}})}pageShow(){this.isResourceLoaded()&&this.jscore.postMessage({type:"pageShow",body:{bridgeId:this.id}})}pageHide(){this.isResourceLoaded()&&this.jscore.postMessage({type:"pageHide",body:{bridgeId:this.id}})}destroy(){this.isResourceLoaded()&&this.jscore.postMessage({type:"pageUnload",body:{bridgeId:this.id}})}},x=class{constructor(e){this.parent=e,this.worker=null,this.event=k()}async init(){const e=this.parent.getApiNamespaces?.()||[],t=JSON.stringify({apiNamespaces:e});this.worker=new Worker("/assets/service.js",{type:"classic",name:t}),this.worker.onmessage=e=>{const t=e.data;this.event.emit(t.method,t)}}invoke(e){this.event.on("invoke",e)}publish(e){this.event.on("publish",e)}postMessage(e){this.worker.postMessage(e)}destroy(){this.worker.terminate()}},A=class{static _encodePage(e,t){return t&&Object.keys(t).length>0?`${e}?${Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&")}`:e}static _decodePage(e){const t=e.indexOf("?");if(-1===t)return{pagePath:e,query:{}};const i=e.slice(0,t),s={};return e.slice(t+1).split("&").forEach(e=>{const[t,i]=e.split("=");t&&(s[decodeURIComponent(t)]=decodeURIComponent(i??""))}),{pagePath:i,query:s}}static syncStack(e,t){const i=t.map(e=>this._encodePage(e.pagePath,e.query)).join("|");history.replaceState(null,"",`#${e}|${i}`)}static clear(){history.replaceState(null,"",window.location.pathname+window.location.search)}static parse(e){if(!e||e.length<=1)return null;const t=e.slice(1).split("|");if(t.length<2)return null;const i=t[0],s=t.slice(1).map(e=>this._decodePage(e));return i&&0!==s.length?{appId:i,stack:s}:null}},B=(e,t,i=560)=>new Promise(s=>{const a=setTimeout(s,i),n=i=>{t&&i.propertyName!==t||(clearTimeout(a),e.removeEventListener("transitionend",n),s())};e.addEventListener("transitionend",n)}),q=class{constructor(e){this.id=`mini_app_${S()}`,this.parent=null,this.appId=e.appId,this.name=e.name,this.logo=e.logo,this.scene=e.scene,this.pagePath=e.pagePath,this.query=e.query,this.appConfig=null,this.bridgeList=[],this.jscore=new x(this),this.webviewsContainer=null,this.webviewAnimaEnd=!0,this.el=document.createElement("div"),this.el.classList.add("dimina-native-view"),this.toastInfo={dom:null,timer:null},this.color=null,this.restoreStack=e.restoreStack,this.apiRegistry={...e.apiRegistry},this._extSubscriptions=/* @__PURE__ */new Map}getCurrentPagePath(){return this.bridgeList[this.bridgeList.length-1]?.opts?.pagePath||this.appInfo.pagePath||this.appConfig?.app?.entryPagePath||""}getCurrentPageQuery(){return this.bridgeList[this.bridgeList.length-1]?.opts?.query||this.appInfo.query||{}}getEntryPagePath(){return this.appInfo.pagePath||this.appConfig?.app?.entryPagePath||""}async copyText(e,t){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(e);else{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}this.showToast({title:t,icon:"success"})}catch{this.showToast({title:"复制失败",icon:"none"})}}closeMiniProgram(){A.clear(),this.closeMiniAppMenu(),T.closeApp(this)}renderMiniAppMenu(){const e=this.el.querySelector(".dimina-mini-app-menu__app-name"),t=this.el.querySelector(".dimina-mini-app-menu__app-id"),i=this.el.querySelector(".dimina-mini-app-menu__app-desc"),s=this.el.querySelector(".dimina-mini-app-menu__app-logo-img"),a=this.el.querySelector(".dimina-mini-app-menu__quick-actions"),n=this.getCurrentPagePath(),o=this.getEntryPagePath(),r=this.getCurrentPageQuery(),l=n||o||"",c=`${l}${Object.keys(r).length?`?${new URLSearchParams(r).toString()}`:""}`,d=`${window.location.origin}${window.location.pathname}#${this.appId}|${c}`;e.textContent=this.appInfo.name||"未命名小程序",t.textContent=`AppID:${this.appId||"--"}`,i.textContent=`当前页面:${l||"--"}`,s.src=this.appInfo.logo||"";const h=[{label:"复制链接",icon:"↗",handler:()=>this.copyText(d,"链接已复制")},{label:"重新进入",icon:"↻",handler:()=>{this.closeMiniAppMenu(),this.reLaunch({url:o||n})}},{label:"关闭小程序",icon:"×",danger:!0,handler:()=>this.closeMiniProgram()}];a.innerHTML=h.map((e,t)=>`\n\t\t\t\t<button type="button" class="dimina-mini-app-menu__quick-action${e.danger?" is-danger":""}" data-quick-index="${t}">\n\t\t\t\t\t<span class="dimina-mini-app-menu__quick-action-icon">${e.icon}</span>\n\t\t\t\t\t<span class="dimina-mini-app-menu__quick-action-label">${e.label}</span>\n\t\t\t\t</button>\n\t\t\t`).join(""),a.querySelectorAll("[data-quick-index]").forEach((e,t)=>{e.onclick=()=>h[t].handler()})}openMiniAppMenu(){const e=this.el.querySelector(".dimina-mini-app-menu__mask"),t=this.el.querySelector(".dimina-mini-app-menu");this.renderMiniAppMenu(),e.style.display="block",requestAnimationFrame(()=>{e.classList.add("show"),t.classList.add("show")})}closeMiniAppMenu(){const e=this.el.querySelector(".dimina-mini-app-menu__mask"),t=this.el.querySelector(".dimina-mini-app-menu");e.classList.remove("show"),t.classList.remove("show")}registerApi(e,t){this.apiRegistry[e]=t}invokeApi(e,t){const i=this.apiRegistry[e];i?i.call(this,t):"function"==typeof this[e]?this[e](t):this._handleExtCall(e,t)}viewDidLoad(){this.initPageFrame(),this.webviewsContainer=this.el.querySelector(".dimina-mini-app__webviews"),this.showLaunchScreen(),this.bindMoreEvent(),this.bindCloseEvent(),this.initApp()}async initApp(){await this.jscore.init();const e="main",t=`${this.appId}/${e}/app-config.json`,[i]=await Promise.all([(a=`/${t}`,new Promise(e=>{fetch(`${a}`).then(e=>e.text()).then(t=>{e(t)}).catch(()=>{e(null)})})),(s=560,new Promise(e=>{setTimeout(()=>{e()},s)}))]);var s,a;if(!i)return;this.appConfig=JSON.parse(i);const n=this.pagePath||this.appConfig.app.entryPagePath,o=this.appConfig.modules[n],r=I(this.appConfig.app,o);this.updateTargetPageColorStyle(r);const l=await this.createBridge({pagePath:n,query:this.query,scene:this.scene,jscore:this.jscore,isRoot:!0,root:e,appId:this.appId,pages:this.appConfig.app.pages,configInfo:r});this.bridgeList.push(l),l.start(),this.restoreStack&&this.restoreStack.length>1&&await this.restorePageStack(this.restoreStack.slice(1)),this._syncHash(),this.hideLaunchScreen()}async restorePageStack(e){for(let t=0;t<e.length;t++){const{pagePath:i,query:s}=e[t],a=t===e.length-1,n=i.startsWith("/")?i.slice(1):i,o=this.appConfig.modules[n],r=I(this.appConfig.app,o),l=await this.createBridge({pagePath:n,query:s,scene:this.scene,jscore:this.jscore,isRoot:!1,root:o?.root||"main",appId:this.appId,pages:this.appConfig.app.pages,configInfo:r}),c=this.bridgeList[this.bridgeList.length-1];c.webview.el.classList.remove("dimina-native-view--instage"),c.webview.el.classList.add("dimina-native-view--slide-out"),this.bridgeList.push(l),l.webview.el.style.zIndex=this.bridgeList.length+1,l.webview.el.classList.remove("dimina-native-view--before-enter"),a||l.webview.el.classList.add("dimina-native-view--slide-out"),l.start()}if(e.length>0){const e=this.bridgeList[this.bridgeList.length-1],t=this.appConfig.modules[e.opts.pagePath],i=I(this.appConfig.app,t);this.updateTargetPageColorStyle(i)}}_syncHash(){const e=this.bridgeList.map(e=>({pagePath:e.opts.pagePath.startsWith("/")?e.opts.pagePath.slice(1):e.opts.pagePath,query:e.opts.query||{}}));A.syncStack(this.appId,e)}async createBridge(e){const{jscore:t,configInfo:i,isRoot:s,appId:a,pagePath:n,query:o,scene:r,pages:l,root:c}=e,d=new P({jscore:t,configInfo:i,isRoot:s,appId:a,pagePath:n,query:o,scene:r,pages:l,root:c});return d.parent=this,await d.init(),d}onPresentIn(){const e=this.bridgeList[this.bridgeList.length-1];e?.appShow(),e?.pageShow()}onPresentOut(){const e=this.bridgeList[this.bridgeList.length-1];e?.appHide(),e?.pageHide()}initPageFrame(){this.el.innerHTML='<div class="dimina-mini-app">\n\t\x3c!-- 右上方药丸按钮 --\x3e\n\t<ul class="dimina-mini-app-navigation__actions">\n\t\t<li class="dimina-mini-app-navigation__actions-variable"></li>\n\t\t<li class="dimina-mini-app-navigation__actions-close"></li>\n\t</ul>\n\n\t\x3c!-- webview挂载节点 --\x3e\n\t<div class="dimina-mini-app__webviews"></div>\n\n\t\x3c!-- 启动loading页面 --\x3e\n\t<div class="dimina-mini-app__launch-screen">\n\t\t<div class="dimina-mini-app__launch-screen-content">\n\t\t\t<div class="dimina-mini-app__logo">\n\t\t\t\t<div class="dimina-mini-app__logo-img">\n\t\t\t\t\t<img class="dimina-mini-app__logo-img-url" alt="logo" />\n\t\t\t\t</div>\n\t\t\t\t<div class="dimina-mini-app__logo-circle"></div>\n\t\t\t\t<span class="dimina-mini-app__green-point"></span>\n\t\t\t</div>\n\t\t\t<h1 class="dimina-mini-app__name"></h1>\n\t\t</div>\n\t</div>\n\n\t<div class="dimina-mini-app-menu__mask"></div>\n\t<div class="dimina-mini-app-menu">\n\t\t<div class="dimina-mini-app-menu__handle"></div>\n\t\t<div class="dimina-mini-app-menu__app">\n\t\t\t<div class="dimina-mini-app-menu__app-logo">\n\t\t\t\t<img class="dimina-mini-app-menu__app-logo-img" alt="logo" />\n\t\t\t</div>\n\t\t\t<div class="dimina-mini-app-menu__app-meta">\n\t\t\t\t<h2 class="dimina-mini-app-menu__app-name"></h2>\n\t\t\t\t<p class="dimina-mini-app-menu__app-id"></p>\n\t\t\t\t<p class="dimina-mini-app-menu__app-desc"></p>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class="dimina-mini-app-menu__quick-actions"></div>\n\t\t<div class="dimina-mini-app-menu__footer">\n\t\t\t<button type="button" class="dimina-mini-app-menu__footer-btn dimina-mini-app-menu__footer-btn--cancel">取消</button>\n\t\t</div>\n\t</div>\n</div>\n'}updateTargetPageColorStyle(e){const{navigationBarTextStyle:t}=e;this.updateActionColorStyle(t)}showLaunchScreen(){const e=this.el.querySelector(".dimina-mini-app__launch-screen"),t=this.el.querySelector(".dimina-mini-app__name"),i=this.el.querySelector(".dimina-mini-app__logo-img-url");this.updateActionColorStyle("black"),t.innerHTML=this.name||this.appId||"",this.logo?(i.src=this.logo,i.style.display=""):(i.removeAttribute("src"),i.style.display="none"),e.style.display="block"}hideLaunchScreen(){this.el.querySelector(".dimina-mini-app__launch-screen").style.display="none"}updateActionColorStyle(e){this.color=e;const t=this.el.querySelector(".dimina-mini-app-navigation__actions");"white"===e?(t.classList.remove("dimina-mini-app-navigation__actions--black"),t.classList.add("dimina-mini-app-navigation__actions--white")):"black"===e&&(t.classList.remove("dimina-mini-app-navigation__actions--white"),t.classList.add("dimina-mini-app-navigation__actions--black")),this.parent.updateStatusBarColor(e)}restoreColorStyle(){this.updateActionColorStyle(this.color)}createCallbackFunction(e){if(e)return t=>{this.jscore.postMessage({type:"triggerCallback",body:{id:e,args:t}})}}async navigateTo(e){if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const{url:t,success:i}=e,{query:s,pagePath:a}=L(t),n=this.createCallbackFunction(i),o=this.appConfig.modules[a],r=I(this.appConfig.app,o);this.updateTargetPageColorStyle(r);const l=await this.createBridge({pagePath:a,query:s,scene:this.scene,jscore:this.jscore,isRoot:!1,root:o?.root||"main",appId:this.appId,pages:this.appConfig.app.pages,configInfo:r}),c=this.bridgeList[this.bridgeList.length-1],d=c.webview;this.bridgeList.push(l),l.start(),this._syncHash(),d.el.classList.remove("dimina-native-view--instage"),d.el.classList.add("dimina-native-view--slide-out"),d.el.classList.add("dimina-native-view--linear-anima"),c?.pageHide(),l.webview.el.style.zIndex=this.bridgeList.length+1,l.webview.el.classList.add("dimina-native-view--enter-anima"),l.webview.el.classList.add("dimina-native-view--instage"),await B(l.webview.el,"transform"),this.webviewAnimaEnd=!0,d.el.classList.remove("dimina-native-view--linear-anima"),l.webview.el.classList.remove("dimina-native-view--before-enter"),l.webview.el.classList.remove("dimina-native-view--enter-anima"),l.webview.el.classList.remove("dimina-native-view--instage"),n?.()}reLaunch(e){if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const{url:t,success:i,fail:s,complete:a}=e,{query:n,pagePath:o}=L(t),r=this.createCallbackFunction(i),l=this.createCallbackFunction(s),c=this.createCallbackFunction(a);try{const e=this.appConfig.modules[o],t=I(this.appConfig.app,e);for(this.updateTargetPageColorStyle(t);this.bridgeList.length>0;){const e=this.bridgeList.pop();e.destroy(),e.webview&&e.webview.el&&e.webview.el.remove()}this.webviewsContainer&&(this.webviewsContainer.innerHTML=""),this.createBridge({pagePath:o,query:n,scene:this.scene,jscore:this.jscore,isRoot:!0,root:e?.root||"main",appId:this.appId,pages:this.appConfig.app.pages,configInfo:t}).then(e=>{this.bridgeList.push(e),e.start(),this._syncHash(),e.webview.el.style.zIndex=1,this.webviewAnimaEnd=!0,r?.({errMsg:"reLaunch:ok"}),c?.()}).catch(e=>{l?.({errMsg:`reLaunch:fail ${e.message}`}),c?.(),this.webviewAnimaEnd=!0})}catch(d){l?.({errMsg:`reLaunch:fail ${d.message}`}),c?.(),this.webviewAnimaEnd=!0}}redirectTo(e){if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const{url:t,success:i}=e,{query:s,pagePath:a}=L(t),n=this.createCallbackFunction(i),o=this.bridgeList[this.bridgeList.length-1],r=this.appConfig.modules[a],l=I(this.appConfig.app,r);this.updateTargetPageColorStyle(l),o.destroy(),o.opts={...o.opts,pagePath:a,query:s,configInfo:l},o.resetStatus(),o.start(),this._syncHash(),this.webviewAnimaEnd=!0,n?.()}async navigateBack(){if(this.bridgeList.length<2)return;if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const e=this.bridgeList.pop(),t=this.bridgeList[this.bridgeList.length-1],i=this.appConfig.modules[t.opts.pagePath],s=I(this.appConfig.app,i);this.updateTargetPageColorStyle(s),e.webview.el.classList.add("dimina-native-view--before-enter"),e.webview.el.classList.add("dimina-native-view--enter-anima"),e?.destroy(),t.webview.el.classList.remove("dimina-native-view--slide-out"),t.webview.el.classList.add("dimina-native-view--instage"),t.webview.el.classList.add("dimina-native-view--enter-anima"),t?.pageShow(),this._syncHash(),await B(t.webview.el,"transform"),this.webviewAnimaEnd=!0,t.webview.el.classList.remove("dimina-native-view--enter-anima"),t.webview.el.classList.remove("dimina-native-view--instage"),e.webview.el.parentNode.removeChild(e.webview.el)}navigateToMiniProgram(e){const{appId:t,path:i}=e;T.openApp({appId:t,path:i,scene:1037},this.parent)}bindMoreEvent(){const e=this.el.querySelector(".dimina-mini-app-navigation__actions-variable"),t=this.el.querySelector(".dimina-mini-app-menu__mask"),i=this.el.querySelector(".dimina-mini-app-menu"),s=this.el.querySelector(".dimina-mini-app-menu__footer-btn--cancel");t.addEventListener("transitionend",()=>{t.classList.contains("show")||(t.style.display="none")}),e.onclick=()=>this.openMiniAppMenu(),t.onclick=()=>this.closeMiniAppMenu(),s.onclick=()=>this.closeMiniAppMenu(),i.onclick=e=>e.stopPropagation()}bindCloseEvent(){this.el.querySelector(".dimina-mini-app-navigation__actions-close").onclick=()=>{this.closeMiniProgram()}}destroy(){for(const e of this._extSubscriptions.values())e?.();this._extSubscriptions.clear(),T.popView(),this.jscore.destroy()}getNetworkType(e){const{success:t}=e;this.createCallbackFunction(t)?.({networkType:"wifi"})}getSystemInfoAsync(e){const t=this.parent.getStatusBarRect(),i=this.parent.el.querySelector(".dimina-native-webview__root").getBoundingClientRect(),{success:s,complete:a}=e,n=this.createCallbackFunction(s),o=this.createCallbackFunction(a);n?.({statusBarHeight:t.height,brand:"devtools",mode:"default",model:"web",platform:"devtools",system:"web",deviceOrientation:"portrait",SDKVersion:"3.0.0",language:"zh_CN",wifiEnabled:!0,safeArea:{width:i.width,height:i.height,top:i.top,bottom:i.bottom,left:i.left,right:i.right}}),o?.()}getMenuButtonBoundingClientRect(){const e=this.el.querySelector(".dimina-mini-app-navigation__actions").getBoundingClientRect(),t=(this.parent.parent.root.querySelector(".iphone__status-bar")?.getBoundingClientRect().height||20)+4,i=t+e.height;return{top:t,right:e.right,bottom:i,left:e.left,width:e.width,height:e.height,x:e.x,y:t}}getHostEnvSnapshot(){return{menuRect:this.getMenuButtonBoundingClientRect(),systemInfo:this.getSystemInfoSync()}}getSystemInfoSync(){const e=this.parent.parent.root.querySelector(".iphone__status-bar"),t=this.parent.el.querySelector(".dimina-native-webview__root")?.getBoundingClientRect(),i=t?.width||this.el.clientWidth||375,s=t?.height||this.el.clientHeight||667,a=e?.getBoundingClientRect().height||20;return{brand:"devtools",model:"web",platform:"devtools",system:"web",SDKVersion:"3.0.0",pixelRatio:globalThis.devicePixelRatio||1,screenWidth:i,screenHeight:s,windowWidth:i,windowHeight:s,statusBarHeight:a,safeArea:{left:0,right:i,top:a,bottom:s,width:i,height:Math.max(s-a,0)}}}showToast(e){const{title:t="",duration:i=1500,icon:s="success",success:a,complete:n}=e;if(!t)return;this.hideToast({});const o=this.createCallbackFunction(a),r=this.createCallbackFunction(n);this.toastInfo.dom=document.createElement("div"),this.toastInfo.dom.classList.add("dimina-toast",`dimina-toast--${s}`),this.toastInfo.dom.innerHTML=`<p>${t}</p>`,this.webviewsContainer.appendChild(this.toastInfo.dom),this.toastInfo.timer=setTimeout(()=>{this.webviewsContainer.removeChild(this.toastInfo.dom),this.toastInfo.dom=null},i),o?.(),r?.()}hideToast(e){const{success:t,complete:i}=e,s=this.createCallbackFunction(t),a=this.createCallbackFunction(i);this.toastInfo.dom&&(this.webviewsContainer.removeChild(this.toastInfo.dom),this.toastInfo.dom=null),this.toastInfo.timer&&(clearTimeout(this.toastInfo.timer),this.toastInfo.timer=null),s?.(),a?.()}showLoading(e){this.showToast({...e,icon:"loading"})}hideLoading(e){this.hideLoading(e)}showModal(e){const{content:t="",cancelText:i="取消",confirmText:s="确定",success:a,complete:n}=e,o=this.createCallbackFunction(a),r=this.createCallbackFunction(n),l=document.createElement("div");l.className="dimina-dialog-mask";const c=document.createElement("div");c.className="dimina-dialog",c.innerHTML=`<p>${t}</p>\n\t\t<div>\n\t\t\t<a id="cancelBtn" class="dimina-dialog__button" href="javascript:">${i}</a>\n\t\t\t<a id="confirmBtn" class="dimina-dialog__button" style="color: #576b95;" href="javascript:">${s}</a>\n \t</div>`;const d=()=>{l.remove(),c.remove()};c.querySelector("#cancelBtn").addEventListener("click",()=>{d(),o?.({cancel:!0}),r?.()}),c.querySelector("#confirmBtn").addEventListener("click",()=>{d(),o?.({confirm:!0}),r?.()}),l.onclick=d,this.webviewsContainer.appendChild(l),this.webviewsContainer.appendChild(c),requestAnimationFrame(()=>requestAnimationFrame(()=>{l.classList.add("show"),c.classList.add("show")}))}showActionSheet(e){const{itemList:t=[],itemColor:i="#000",success:s,fail:a,complete:n}=e||{};if(!Array.isArray(t)||0===t.length)return a&&this.createCallbackFunction(a)({errMsg:"showActionSheet:fail"}),void(n&&this.createCallbackFunction(n)());const o=document.createElement("div");o.className="dimina-action-sheet-mask";const r=document.createElement("div");r.className="dimina-action-sheet";const l=()=>{o.remove(),r.remove()};t.forEach((e,t)=>{const a=document.createElement("div");a.className="dimina-action-sheet-item",a.style.color=i,a.textContent=e,a.onclick=()=>{l(),s&&this.createCallbackFunction(s)({tapIndex:t}),n&&this.createCallbackFunction(n)()},r.appendChild(a)});const c=document.createElement("div");c.className="dimina-action-sheet-cancel",c.textContent="取消",c.onclick=()=>{l(),a&&this.createCallbackFunction(a)({errMsg:"showActionSheet:fail cancel"}),n&&this.createCallbackFunction(n)()},r.appendChild(c),o.onclick=l,this.webviewsContainer.appendChild(o),this.webviewsContainer.appendChild(r),requestAnimationFrame(()=>requestAnimationFrame(()=>{r.classList.add("show"),o.classList.add("show")}))}setNavigationBarTitle(e){const{title:t,success:i,fail:s,complete:a}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(s),r=this.createCallbackFunction(a);try{const e=this.bridgeList[this.bridgeList.length-1].webview.el.querySelector(".dimina-native-webview__navigation-title");e?(e.textContent=t||"",n?.({errMsg:"setNavigationBarTitle:ok"})):o?.({errMsg:"setNavigationBarTitle:fail Navigation title element not found"})}catch(l){o?.({errMsg:`setNavigationBarTitle:fail ${l.message}`})}finally{r?.()}}setNavigationBarColor(e){const{frontColor:t,backgroundColor:i,success:s,fail:a,complete:n}=e,o=this.createCallbackFunction(s),r=this.createCallbackFunction(a),l=this.createCallbackFunction(n);try{const e=this.bridgeList[this.bridgeList.length-1].webview.el.querySelector(".dimina-native-webview__navigation");e?(t&&(e.querySelector(".dimina-native-webview__navigation-title").style.color=t),i&&(e.style.backgroundColor=i),o?.({errMsg:"setNavigationBarColor:ok"})):r?.({errMsg:"setNavigationBarColor:fail Navigation element not found"})}catch(c){r?.({errMsg:`setNavigationBarColor:fail ${c.message}`})}finally{l?.()}}pageScrollTo(e){const{scrollTop:t,duration:i=300,success:s,fail:a,complete:n}=e,o=this.createCallbackFunction(s),r=this.createCallbackFunction(a),l=this.createCallbackFunction(n);try{const e=this.bridgeList[this.bridgeList.length-1].webview.iframe.contentWindow.document.documentElement;e?(e.scrollTo({top:t,behavior:i>0?"smooth":"auto"}),setTimeout(()=>{o?.({errMsg:"pageScrollTo:ok"}),l?.()},i)):(r?.({errMsg:"pageScrollTo:fail Webview root element not found"}),l?.())}catch(c){r?.({errMsg:`pageScrollTo:fail ${c.message}`}),l?.()}}setClipboardData(e){const{data:t,success:i,fail:s,complete:a}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(s),r=this.createCallbackFunction(a);try{navigator.clipboard.writeText(t).then(()=>{n?.({errMsg:"setClipboardData:ok"}),r?.()}).catch(e=>{o?.({errMsg:`setClipboardData:fail ${e.message}`}),r?.()})}catch(l){o?.({errMsg:`setClipboardData:fail ${l.message}`}),r?.()}}getClipboardData(e){const{success:t,fail:i,complete:s}=e,a=this.createCallbackFunction(t),n=this.createCallbackFunction(i),o=this.createCallbackFunction(s);try{navigator.clipboard.readText().then(e=>{a?.({data:e,errMsg:"getClipboardData:ok"}),o?.()}).catch(e=>{n?.({errMsg:`getClipboardData:fail ${e.message}`}),o?.()})}catch(r){n?.({errMsg:`getClipboardData:fail ${r.message}`}),o?.()}}setStorage(e){const{key:t,data:i,success:s,fail:a,complete:n}=e,o=this.createCallbackFunction(s),r=this.createCallbackFunction(a),l=this.createCallbackFunction(n);try{const e=`${this.appId}_${t}`,s="object"==typeof i?JSON.stringify(i):String(i);localStorage.setItem(e,s),o?.({errMsg:"setStorage:ok"})}catch(c){r?.({errMsg:`setStorage:fail ${c.message}`})}finally{l?.()}}getStorage(e){const{key:t,success:i,fail:s,complete:a}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(s),r=this.createCallbackFunction(a);try{const e=`${this.appId}_${t}`,i=localStorage.getItem(e);if(null!==i){let e=i;try{e=JSON.parse(i)}catch{}n?.({data:e,errMsg:"getStorage:ok"})}else o?.({errMsg:"getStorage:fail data not found"})}catch(l){o?.({errMsg:`getStorage:fail ${l.message}`})}finally{r?.()}}removeStorage(e){const{key:t,success:i,fail:s,complete:a}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(s),r=this.createCallbackFunction(a);try{const e=`${this.appId}_${t}`;null!==localStorage.getItem(e)?(localStorage.removeItem(e),n?.({errMsg:"removeStorage:ok"})):n?.({errMsg:"removeStorage:ok"})}catch(l){o?.({errMsg:`removeStorage:fail ${l.message}`})}finally{r?.()}}clearStorage(e){const{success:t,fail:i,complete:s}=e||{},a=this.createCallbackFunction(t),n=this.createCallbackFunction(i),o=this.createCallbackFunction(s);try{const e=`${this.appId}_`,t=[];for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);s.startsWith(e)&&t.push(s)}t.forEach(e=>localStorage.removeItem(e)),a?.({errMsg:"clearStorage:ok"})}catch(r){n?.({errMsg:`clearStorage:fail ${r.message}`})}finally{o?.()}}getStorageInfo(e){const{success:t,fail:i,complete:s}=e||{},a=this.createCallbackFunction(t),n=this.createCallbackFunction(i),o=this.createCallbackFunction(s);try{const e=[];let t=0;const i=10485760,s=`${this.appId}_`;for(let a=0;a<localStorage.length;a++){const i=localStorage.key(a);if(i.startsWith(s)){const a=i.substring(s.length);e.push(a);const n=localStorage.getItem(i);t+=n?2*n.length:0}}a?.({keys:e,currentSize:t,limitSize:i,errMsg:"getStorageInfo:ok"})}catch(r){n?.({errMsg:`getStorageInfo:fail ${r.message}`})}finally{o?.()}}_parseExtEventKey(e){const t=T.getExtModules();for(const i of Object.keys(t)){const t=`${i}_`;if(e.startsWith(t))return{module:i,event:e.slice(t.length)}}return{module:null,event:null}}_handleExtCall(e,t={}){void 0!==t.module?this._extBridgeCall(e,t):t.success?this._extOnBridgeCall(e,t):this._extOffBridgeCall(e)}_extBridgeCall(e,t){const{module:i,data:s={},success:a,fail:n,complete:o}=t,r=this.createCallbackFunction(a),l=this.createCallbackFunction(n),c=this.createCallbackFunction(o),d=T.getExtModule(i);if(!d){const e=`extBridge:fail module "${i}" not registered`;return l?.({errMsg:e}),void c?.()}try{d({event:e,data:s,success:e=>{r?.(e),c?.()},fail:e=>{l?.(e),c?.()}})}catch(h){l?.({errMsg:`extBridge:fail ${h.message}`}),c?.()}}_extOnBridgeCall(e,t){const{success:i}=t,s=this.createCallbackFunction(i),{module:a,event:n}=this._parseExtEventKey(e);if(!a)return;const o=T.getExtModule(a);this._extSubscriptions.get(e)?.();try{const t=o({event:n,data:{isSustain:!0},success:e=>s?.(e),fail:()=>{}});this._extSubscriptions.set(e,t??null)}catch(r){}}_extOffBridgeCall(e){const t=this._extSubscriptions.get(e);t&&(t(),this._extSubscriptions.delete(e))}},T=class{static appStack=[];static apiRegistry={};static _extModules={};static registerApi(e,t){this.apiRegistry[e]=t}static registerExtModule(e,t){this._extModules[e]=t}static getExtModule(e){return this._extModules[e]}static getExtModules(){return this._extModules}static async openApp(e,t){const{appId:i,path:s,scene:a,destroy:n,name:o,logo:r,restoreStack:l}=e,{pagePath:c,query:d}=L(s);if(n)for(const p of this.appStack)p.appId!==i&&(p.bridgeList.pop()?.destroy(),t.destroyRootView(p));const h=this.getAppById(i);if(h)t.presentView(h,!0);else{const e=new q({appId:i,scene:a,name:o,logo:r,pagePath:c,query:d,apiRegistry:this.apiRegistry,restoreStack:l});this.appStack.push(e),t.presentView(e,!1)}}static getAppById(e){for(const t of this.appStack)if(t.appId===e)return t;return null}static popView(){this.appStack.pop()}static closeApp(e){e.parent.dismissView({destroy:!1})}},E=()=>new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e))),R=(e,t,i=560)=>new Promise(s=>{const a=setTimeout(s,i),n=i=>{t&&i.propertyName!==t||(clearTimeout(a),e.removeEventListener("transitionend",n),s())};e.addEventListener("transitionend",n)}),F=class{constructor(){this.el=null,this.window=null,this.root=null,this.views=[],this.rootView=null,this.parent=null,this.done=!0,this.isSleeping=!1,this._queue=Promise.resolve(),this.init()}_enqueue(e){return this._queue=this._queue.then(()=>e()),this._queue}init(){this.el=document.createElement("div"),this.el.classList.add("dimina-application"),this.window=document.createElement("div"),this.window.classList.add("dimina-native-window"),this.el.appendChild(this.window)}initRootView(e){this.rootView=e,e.parent=this,e.el.classList.add("dimina-native-view--instage"),e.el.style.zIndex=1,this.root=e,this.window.appendChild(e.el),e.viewDidLoad()}async pushView(e){if(!this.done)return;this.done=!1;const t=this.views[this.views.length-1];e.parent=this,this.views.push(e),e.el.style.zIndex=this.views.length,e.el.classList.add("dimina-native-view--before-enter"),this.window.appendChild(e.el),e?.viewDidLoad(),await E(),t.el.classList.remove("dimina-native-view--instage"),t.el.classList.add("dimina-native-view--slide-out"),t.el.classList.add("dimina-native-view--linear-anima"),e.el.classList.add("dimina-native-view--enter-anima"),e.el.classList.add("dimina-native-view--instage"),await R(e.el,"transform"),t.el.classList.remove("dimina-native-view--linear-anima"),e.el.classList.remove("dimina-native-view--before-enter"),e.el.classList.remove("dimina-native-view--enter-anima"),e.el.classList.remove("dimina-native-view--instage"),this.done=!0}async popView(){if(this.views.length<2)return;if(!this.done)return;this.done=!1;const e=this.views[this.views.length-2],t=this.views[this.views.length-1];e.el.classList.remove("dimina-native-view--slide-out"),e.el.classList.add("dimina-native-view--instage"),e.el.classList.add("dimina-native-view--enter-anima"),t.el.classList.remove("dimina-native-view--instage"),t.el.classList.add("dimina-native-view--before-enter"),t.el.classList.add("dimina-native-view--enter-anima"),await R(t.el,"transform"),this.views.pop(),this.window.removeChild(t.el),e.el.classList.remove("dimina-native-view--enter-anima"),this.done=!0}presentView(e,t){return this._enqueue(()=>this._presentView(e,t))}async _presentView(e,t){if(!this.done)return;this.done=!1;const i=this.views[this.views.length-1];e.parent=this,e.el.style.zIndex=this.views.length+1,e.el.classList.add("dimina-native-view--before-present"),e.el.classList.add("dimina-native-view--enter-anima"),i?.el.classList.add("dimina-native-view--before-presenting"),i?.el.classList.remove("dimina-native-view--instage"),i?.el.classList.add("dimina-native-view--enter-anima"),i?.onPresentOut(),e.onPresentIn(),!t&&this.el.appendChild(e.el),this.views.push(e),!t&&e.viewDidLoad&&e.viewDidLoad(),t&&e.restoreColorStyle(),await E(),i?.el.classList.add("dimina-native-view--presenting"),e.el.classList.add("dimina-native-view--instage"),await R(e.el,"transform"),e.el.classList.remove("dimina-native-view--before-present"),e.el.classList.remove("dimina-native-view--enter-anima"),i?.el.classList.remove("dimina-native-view--enter-anima"),i?.el.classList.remove("dimina-native-view--before-presenting"),this.done=!0}dismissView(e={}){return this._enqueue(()=>this._dismissView(e))}async _dismissView(e={}){if(!this.done)return;this.done=!1;const t=this.views[this.views.length-2],i=this.views[this.views.length-1],{destroy:s=!0}=e;i.el.classList.add("dimina-native-view--enter-anima"),t?.el.classList.add("dimina-native-view--enter-anima"),t?.el.classList.add("dimina-native-view--before-presenting"),await E(),i.el.classList.add("dimina-native-view--before-present"),i.el.classList.remove("dimina-native-view--instage"),t?.el.classList.remove("dimina-native-view--presenting"),t?.onPresentIn(),i?.onPresentOut(),await R(i.el,"transform"),s&&(i.destroy(),this.el.removeChild(i.el)),this.views.pop(),t?.el.classList.remove("dimina-native-view--enter-anima"),t?.el.classList.remove("dimina-native-view--before-presenting"),this.done=!0}async destroyRootView(e){e.destroy(),this.el.removeChild(e.el)}getStatusBarRect(){const e=this.parent?.root?.querySelector(".iphone__status-bar");return e?e.getBoundingClientRect():{height:0}}getActiveView(){return this.views[this.views.length-1]||this.rootView}sleepActiveView(){this.isSleeping||(this.isSleeping=!0,this.getActiveView()?.onPresentOut?.())}wakeActiveView(){if(!this.isSleeping)return;this.isSleeping=!1;const e=this.getActiveView();e?.restoreColorStyle?.(),e?.onPresentIn?.()}updateStatusBarColor(e){this.parent?.updateDeviceBarColor(e)}};function $(e){const t=new F;e.appendChild(t.el);const i=A.parse(window.location.hash);return i&&T.openApp({appId:i.appId,path:i.path,scene:1001,destroy:!0},t),t}export{T as AppManager,F as Application,A as HashRouter,$ as openWithHash};
1
+ var e=()=>new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e))),t=(e,t,i=560)=>new Promise(a=>{const s=setTimeout(a,i),n=i=>{t&&i.propertyName!==t||(clearTimeout(s),e.removeEventListener("transitionend",n),a())};e.addEventListener("transitionend",n)}),i=class{constructor(){this.el=null,this.window=null,this.root=null,this.views=[],this.rootView=null,this.parent=null,this.done=!0,this.isSleeping=!1,this._queue=Promise.resolve(),this.init()}_enqueue(e){return this._queue=this._queue.then(()=>e()),this._queue}init(){this.el=document.createElement("div"),this.el.classList.add("dimina-application"),this.window=document.createElement("div"),this.window.classList.add("dimina-native-window"),this.el.appendChild(this.window)}initRootView(e){this.rootView=e,e.parent=this,e.el.classList.add("dimina-native-view--instage"),e.el.style.zIndex=1,this.root=e,this.window.appendChild(e.el),e.viewDidLoad()}async pushView(i){if(!this.done)return;this.done=!1;const a=this.views[this.views.length-1];i.parent=this,this.views.push(i),i.el.style.zIndex=this.views.length,i.el.classList.add("dimina-native-view--before-enter"),this.window.appendChild(i.el),i?.viewDidLoad(),await e(),a.el.classList.remove("dimina-native-view--instage"),a.el.classList.add("dimina-native-view--slide-out"),a.el.classList.add("dimina-native-view--linear-anima"),i.el.classList.add("dimina-native-view--enter-anima"),i.el.classList.add("dimina-native-view--instage"),await t(i.el,"transform"),a.el.classList.remove("dimina-native-view--linear-anima"),i.el.classList.remove("dimina-native-view--before-enter"),i.el.classList.remove("dimina-native-view--enter-anima"),i.el.classList.remove("dimina-native-view--instage"),this.done=!0}async popView(){if(this.views.length<2)return;if(!this.done)return;this.done=!1;const e=this.views[this.views.length-2],i=this.views[this.views.length-1];e.el.classList.remove("dimina-native-view--slide-out"),e.el.classList.add("dimina-native-view--instage"),e.el.classList.add("dimina-native-view--enter-anima"),i.el.classList.remove("dimina-native-view--instage"),i.el.classList.add("dimina-native-view--before-enter"),i.el.classList.add("dimina-native-view--enter-anima"),await t(i.el,"transform"),this.views.pop(),this.window.removeChild(i.el),e.el.classList.remove("dimina-native-view--enter-anima"),this.done=!0}presentView(e,t){return this._enqueue(()=>this._presentView(e,t))}async _presentView(i,a){if(!this.done)return;this.done=!1;const s=this.views[this.views.length-1];i.parent=this,i.el.style.zIndex=this.views.length+1,i.el.classList.add("dimina-native-view--before-present"),i.el.classList.add("dimina-native-view--enter-anima"),s?.el.classList.add("dimina-native-view--before-presenting"),s?.el.classList.remove("dimina-native-view--instage"),s?.el.classList.add("dimina-native-view--enter-anima"),s?.onPresentOut(),i.onPresentIn(),!a&&this.el.appendChild(i.el),this.views.push(i),!a&&i.viewDidLoad&&i.viewDidLoad(),a&&i.restoreColorStyle(),await e(),s?.el.classList.add("dimina-native-view--presenting"),i.el.classList.add("dimina-native-view--instage"),await t(i.el,"transform"),i.el.classList.remove("dimina-native-view--before-present"),i.el.classList.remove("dimina-native-view--enter-anima"),s?.el.classList.remove("dimina-native-view--enter-anima"),s?.el.classList.remove("dimina-native-view--before-presenting"),this.done=!0}dismissView(e={}){return this._enqueue(()=>this._dismissView(e))}async _dismissView(i={}){if(!this.done)return;this.done=!1;const a=this.views[this.views.length-2],s=this.views[this.views.length-1],{destroy:n=!0}=i;s.el.classList.add("dimina-native-view--enter-anima"),a?.el.classList.add("dimina-native-view--enter-anima"),a?.el.classList.add("dimina-native-view--before-presenting"),await e(),s.el.classList.add("dimina-native-view--before-present"),s.el.classList.remove("dimina-native-view--instage"),a?.el.classList.remove("dimina-native-view--presenting"),a?.onPresentIn(),s?.onPresentOut(),await t(s.el,"transform"),n&&(s.destroy(),this.el.removeChild(s.el)),this.views.pop(),a?.el.classList.remove("dimina-native-view--enter-anima"),a?.el.classList.remove("dimina-native-view--before-presenting"),this.done=!0}async destroyRootView(e){e.destroy(),this.el.removeChild(e.el)}getActiveView(){return this.views[this.views.length-1]||this.rootView}sleepActiveView(){this.isSleeping||(this.isSleeping=!0,this.getActiveView()?.onPresentOut?.())}wakeActiveView(){if(!this.isSleeping)return;this.isSleeping=!1;const e=this.getActiveView();e?.restoreColorStyle?.(),e?.onPresentIn?.()}updateStatusBarColor(e){this.parent?.updateDeviceBarColor(e)}};var a=function(e){const t=/* @__PURE__ */new Map;return function(...i){const a=1===i.length?i[0]:JSON.stringify(i);if(t.has(a))return t.get(a);const s=e.apply(this,i);return t.set(a,s),s}}(async()=>{const e=await fetch("/appList.json").then(e=>e.json());return e.forEach(e=>{const t=JSON.stringify(e),i=sessionStorage.getItem(t);if(i)e.logo=i;else{const i=function(e){const t=[60,60],i=window.devicePixelRatio||1,a=document.createElement("canvas");a.style.width=t[0]+"px",a.style.height=t[1]+"px",a.width=t[0]*i,a.height=t[1]*i;const s=a.getContext("2d");s.scale(i,i),s.imageSmoothingEnabled=!0,s.imageSmoothingQuality="high",s.textRenderingOptimization="optimizeQuality",s.fillStyle=function(e){if(!e||0===e.length)return"#2196F3";let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;const i=function(e,t,i){let a,s,n;const o=Math.floor(e/60),r=e/60-o,l=i*(1-t),c=i*(1-r*t),h=i*(1-(1-r)*t);switch(o%6){case 0:a=i,s=h,n=l;break;case 1:a=c,s=i,n=l;break;case 2:a=l,s=i,n=h;break;case 3:a=l,s=c,n=i;break;case 4:a=h,s=l,n=i;break;case 5:a=i,s=l,n=c}return[Math.round(255*a),Math.round(255*s),Math.round(255*n)]}(Math.abs(t%360),.7+Math.abs(t%3e3)/1e4,.8+Math.abs(t%2e3)/1e4);return a=i[0],s=i[1],n=i[2],`#${((1<<24)+(a<<16)+(s<<8)+n).toString(16).slice(1)}`;var a,s,n}(e.name),s.fillRect(0,0,t[0],t[1]),s.fillStyle="rgb(255,255,255)",s.font=.6*t[0]+"px Arial";const n=e.name.charAt(0),o=s.measureText(n),r=t[0]/2,l=t[1]/2+(o.actualBoundingBoxAscent-o.actualBoundingBoxDescent)/2;return s.textAlign="center",s.fillText(n,r,l),a.toDataURL("image/png",1)}(e);sessionStorage.setItem(t,i),e.logo=i}}),e});function s(){return Math.random().toString(36).slice(2,7)}function n(e){const t=e.split("?"),i=t[0],a=t[1],s={query:{},pagePath:i};return a?(a.split("&").forEach(e=>{const t=e.split("=")[0],i=e.split("=")[1];s.query[t]=i}),s):s}function o(e,t){const i={},a=e.window||{},s=t||{};return i.navigationBarTitleText=s.navigationBarTitleText||a.navigationBarTitleText||"",i.navigationBarBackgroundColor=s.navigationBarBackgroundColor||a.navigationBarBackgroundColor||"#000",i.navigationBarTextStyle=s.navigationBarTextStyle||a.navigationBarTextStyle||"white",i.backgroundColor=s.backgroundColor||a.backgroundColor||"#fff",i.navigationStyle=s.navigationStyle||a.navigationStyle||"default",i.usingComponents=s.usingComponents||{},i}var r=class{static appStack=[];static _extModules={};static registerExtModule(e,t){this._extModules[e]=t}static getExtModule(e){return this._extModules[e]}static getExtModules(){return this._extModules}static async openApp(e,t){const{appId:i,path:s,scene:o,destroy:r,restoreStack:l}=e,{pagePath:c,query:h}=n(s),{name:d,logo:p}=await async function(e){const t=await a();for(const i of t)if(i.appId===e)return i}(i);if(r)for(const a of this.appStack)a.appId!==i&&(a.bridgeList.pop()?.destroy(),t.destroyRootView(a));const g=this.getAppById(i);if(g)t.presentView(g,!0);else{const e=new $({appId:i,scene:o,name:d,logo:p,pagePath:c,query:h,restoreStack:l});this.appStack.push(e),t.presentView(e,!1)}}static getAppById(e){for(const t of this.appStack)if(t.appId===e)return t;return null}static popView(){this.appStack.pop()}static closeApp(e){e.parent.dismissView({destroy:!1})}},l=(e=0)=>t=>`[${t+e}m`,c=(e=0)=>t=>`[${38+e};5;${t}m`,h=(e=0)=>(t,i,a)=>`[${38+e};2;${t};${i};${a}m`,d={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(d.modifier),Object.keys(d.color),Object.keys(d.bgColor);var p=function(){const e=/* @__PURE__ */new Map;for(const[t,i]of Object.entries(d)){for(const[t,a]of Object.entries(i))d[t]={open:`[${a[0]}m`,close:`[${a[1]}m`},i[t]=d[t],e.set(a[0],a[1]);Object.defineProperty(d,t,{value:i,enumerable:!1})}return Object.defineProperty(d,"codes",{value:e,enumerable:!1}),d.color.close="",d.bgColor.close="",d.color.ansi=l(),d.color.ansi256=c(),d.color.ansi16m=h(),d.bgColor.ansi=l(10),d.bgColor.ansi256=c(10),d.bgColor.ansi16m=h(10),Object.defineProperties(d,{rgbToAnsi256:{value:(e,t,i)=>e===t&&t===i?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(i/255*5),enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[i]=t;3===i.length&&(i=[...i].map(e=>e+e).join(""));const a=Number.parseInt(i,16);return[a>>16&255,a>>8&255,255&a]},enumerable:!1},hexToAnsi256:{value:e=>d.rgbToAnsi256(...d.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return e-8+90;let t,i,a;if(e>=232)t=(10*(e-232)+8)/255,i=t,a=t;else{const s=(e-=16)%36;t=Math.floor(e/36)/5,i=Math.floor(s/6)/5,a=s%6/5}const s=2*Math.max(t,i,a);if(0===s)return 30;let n=30+(Math.round(a)<<2|Math.round(i)<<1|Math.round(t));return 2===s&&(n+=60),n},enumerable:!1},rgbToAnsi:{value:(e,t,i)=>d.ansi256ToAnsi(d.rgbToAnsi256(e,t,i)),enumerable:!1},hexToAnsi:{value:e=>d.ansi256ToAnsi(d.hexToAnsi256(e)),enumerable:!1}}),d}(),g=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const e=navigator.userAgentData.brands.find(({brand:e})=>"Chromium"===e);if(e&&e.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),m=0!==g&&{level:g,hasBasic:!0,has256:g>=2,has16m:g>=3},u={stdout:m,stderr:m};function b(e,t,i){let a=e.indexOf(t);if(-1===a)return e;const s=t.length;let n=0,o="";do{o+=e.slice(n,a)+t+i,n=a+s,a=e.indexOf(t,n)}while(-1!==a);return o+=e.slice(n),o}var{stdout:v,stderr:w}=u,f=Symbol("GENERATOR"),y=Symbol("STYLER"),_=Symbol("IS_EMPTY"),C=["ansi","ansi","ansi256","ansi16m"],S=Object.create(null),k=e=>{const t=(...e)=>e.join(" ");return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const i=v?v.level:0;e.level=void 0===t.level?i:t.level})(t,e),Object.setPrototypeOf(t,B.prototype),t};function B(e){return k(e)}Object.setPrototypeOf(B.prototype,Function.prototype);for(const[j,O]of Object.entries(p))S[j]={get(){const e=I(this,P(O.open,O.close,this[y]),this[_]);return Object.defineProperty(this,j,{value:e}),e}};S.visible={get(){const e=I(this,this[y],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var L=(e,t,i,...a)=>"rgb"===e?"ansi16m"===t?p[i].ansi16m(...a):"ansi256"===t?p[i].ansi256(p.rgbToAnsi256(...a)):p[i].ansi(p.rgbToAnsi(...a)):"hex"===e?L("rgb",t,i,...p.hexToRgb(...a)):p[i][e](...a);for(const j of["rgb","hex","ansi256"]){S[j]={get(){const{level:e}=this;return function(...t){const i=P(L(j,C[e],"color",...t),p.color.close,this[y]);return I(this,i,this[_])}}};S["bg"+j[0].toUpperCase()+j.slice(1)]={get(){const{level:e}=this;return function(...t){const i=P(L(j,C[e],"bgColor",...t),p.bgColor.close,this[y]);return I(this,i,this[_])}}}}var T=Object.defineProperties(()=>{},{...S,level:{enumerable:!0,get(){return this[f].level},set(e){this[f].level=e}}}),P=(e,t,i)=>{let a,s;return void 0===i?(a=e,s=t):(a=i.openAll+e,s=t+i.closeAll),{open:e,close:t,openAll:a,closeAll:s,parent:i}},I=(e,t,i)=>{const a=(...e)=>M(a,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(a,T),a[f]=e,a[y]=t,a[_]=i,a},M=(e,t)=>{if(e.level<=0||!t)return e[_]?"":t;let i=e[y];if(void 0===i)return t;const{openAll:a,closeAll:s}=i;if(t.includes(""))for(;void 0!==i;)t=b(t,i.close,i.open),i=i.parent;const n=t.indexOf("\n");return-1!==n&&(t=function(e,t,i,a){let s=0,n="";do{const o="\r"===e[a-1];n+=e.slice(s,o?a-1:a)+t+(o?"\r\n":"\n")+i,s=a+1,a=e.indexOf("\n",s)}while(-1!==a);return n+=e.slice(s),n}(t,s,a,n)),a+t+s};Object.defineProperties(B.prototype,S);B(),B({level:w?w.level:0});function E(e){return{all:e=e||/* @__PURE__ */new Map,on:function(t,i){var a=e.get(t);a?a.push(i):e.set(t,[i])},off:function(t,i){var a=e.get(t);a&&(i?a.splice(a.indexOf(i)>>>0,1):e.set(t,[]))},emit:function(t,i){var a=e.get(t);a&&a.slice().map(function(e){e(i)}),(a=e.get("*"))&&a.slice().map(function(e){e(t,i)})}}}var x=class{constructor(e){this.opts=e,this.id=`webview_${s()}`,this.el=document.createElement("div"),this.el.classList.add("dimina-native-view"),this.el.innerHTML='<div class="dimina-native-webview">\n\t\x3c!-- 导航区域 --\x3e\n\t<div class="dimina-native-webview__navigation">\n\t\t<div class="dimina-native-webview__navigation-content">\n\t\t\t<div class="dimina-native-webview__navigation-left-btn"></div>\n\t\t\t<h2 class="dimina-native-webview__navigation-title"></h2>\n\t\t</div>\n\t</div>\n\n\t\x3c!-- iframe --\x3e\n\t<div class="dimina-native-webview__body">\n\t\t<div class="dimina-native-webview__root">\n\t\t\t<iframe class="dimina-native-webview__window" title="pageFrame"></iframe>\n\t\t</div>\n\t</div>\n</div>',this.setInitialStyle(),this.iframe=this.el.querySelector(".dimina-native-webview__window"),this.iframe.src="/pageFrame.html?vconsole=1",this.iframe.name=this.id,this.event=E(),this.bindBackEvent()}async init(e){await this.frameLoaded();const t=window.frames[this.iframe.name];t.DiminaRenderBridge.invoke=e=>{this.event.emit("invoke",e)},t.DiminaRenderBridge.publish=e=>{this.event.emit("publish",e)},e?.()}invoke(e){this.event.on("invoke",e)}publish(e){this.event.on("publish",e)}postMessage(e){window.frames[this.iframe.name].DiminaRenderBridge.onMessage(e)}bindBackEvent(){this.el.querySelector(".dimina-native-webview__navigation-left-btn").onclick=()=>{this.parent.parent.navigateBack()}}frameLoaded(){return new Promise(e=>{this.iframe.onload=()=>{e()}})}setInitialStyle(){const e=this.opts.configInfo,t=this.el.querySelector(".dimina-native-webview"),i=this.el.querySelector(".dimina-native-webview__navigation-title"),a=this.el.querySelector(".dimina-native-webview__navigation"),s=this.el.querySelector(".dimina-native-webview__navigation-left-btn"),n=this.el.querySelector(".dimina-native-webview__root");this.opts.isRoot?s.style.display="none":s.style.display="block","white"===e.navigationBarTextStyle?a.classList.add("dimina-native-webview__navigation--white"):a.classList.add("dimina-native-webview__navigation--black"),"custom"===e.navigationStyle&&t.classList.add("dimina-native-webview--custom-nav"),n.style.backgroundColor=e.backgroundColor,a.style.backgroundColor=e.navigationBarBackgroundColor,i.textContent=e.navigationBarTitleText}},A=class{constructor(e){this.id=`bridge_${s()}`,this.opts=e,this.webview=null,this.jscore=e.jscore,this.parent=null,this.resetStatus()}async init(){this.jscore.invoke(e=>this.messageInvoke("service",e)),this.jscore.publish(e=>this.messagePublish(e)),this.webview=await this.createWebview(),this.webview.invoke(e=>this.messageInvoke("render",e)),this.webview.publish(e=>this.messagePublish(e))}messagePublish(e){"string"==typeof e&&(e=JSON.parse(e));const{body:t,target:i}=e;t.bridgeId&&t.bridgeId!==this.id||("service"===i?this.jscore.postMessage(e):"render"===i&&this.webview.postMessage(e))}messageInvoke(e,t){"string"==typeof t&&(t=JSON.parse(t));const{type:i,body:a,target:s}=t;if(a.bridgeId&&a.bridgeId!==this.id)return;const n={type:i,body:{bridgeId:this.id,pagePath:this.opts.pagePath,scene:this.opts.scene,query:this.opts.query,...a}};if("service"===s){if("serviceResourceLoaded"===i){if(this.serviceResource=!0,!this.isResourceLoaded())return;n.type="resourceLoaded"}else if("renderResourceLoaded"===i){if(this.renderResource=!0,!this.isResourceLoaded())return;n.type="resourceLoaded"}this.jscore.postMessage(n)}else if("container"===s&&"invokeAPI"===i){const{name:e,params:t}=a;this.parent.invokeApi(e,t)}}start(){this.webview.postMessage({type:"loadResource",body:{bridgeId:this.id,appId:this.opts.appId,pagePath:this.opts.pagePath,root:this.opts.root,baseUrl:"/"}}),this.jscore.postMessage({type:"loadResource",body:{bridgeId:this.id,appId:this.opts.appId,pagePath:this.opts.pagePath,root:this.opts.root,baseUrl:"/",hostEnv:this.parent.getHostEnvSnapshot()}}),this.opts.isRoot&&this.jscore.postMessage({type:"onUpdateStatusChange",body:{bridgeId:this.id,event:"noupdate"}})}resetStatus(){this.serviceResource=!1,this.renderResource=!1}createWebview(){return new Promise(e=>{const t=new x({configInfo:this.opts.configInfo,isRoot:this.opts.isRoot});t.parent=this,t.init(()=>{e(t)}),this.opts.isRoot||t.el.classList.add("dimina-native-view--before-enter"),this.parent.webviewsContainer.appendChild(t.el)})}isResourceLoaded(){return this.serviceResource&&this.renderResource}appShow(){this.isResourceLoaded()&&this.jscore.postMessage({type:"appShow",body:{}})}appHide(){this.isResourceLoaded()&&this.jscore.postMessage({type:"appHide",body:{}})}pageShow(){this.isResourceLoaded()&&this.jscore.postMessage({type:"pageShow",body:{bridgeId:this.id}})}pageHide(){this.isResourceLoaded()&&this.jscore.postMessage({type:"pageHide",body:{bridgeId:this.id}})}destroy(){this.isResourceLoaded()&&this.jscore.postMessage({type:"pageUnload",body:{bridgeId:this.id}})}},q=class{constructor(e){this.parent=e,this.worker=null,this.event=E()}async init(){const e=this.parent.getApiNamespaces?.()||[],t=JSON.stringify({apiNamespaces:e});this.worker=new Worker("/assets/service.js",{type:"classic",name:t}),this.worker.onmessage=e=>{const t=e.data;this.event.emit(t.method,t)}}invoke(e){this.event.on("invoke",e)}publish(e){this.event.on("publish",e)}postMessage(e){this.worker.postMessage(e)}destroy(){this.worker.terminate()}},F=class{static ROUTE_QUERY_KEYS=["appId","entry","page"];static _encodePage(e,t){return t&&Object.keys(t).length>0?`${e}?${Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&")}`:e}static _decodePage(e){const t=e.indexOf("?");if(-1===t)return{pagePath:e,query:{}};const i=e.slice(0,t),a={};return new URLSearchParams(e.slice(t+1)).forEach((e,t)=>{a[t]=e}),{pagePath:i,query:a}}static _encodeSearchValue(e){return encodeURIComponent(e).replace(/%2F/g,"/")}static _normalizeSearch(e){return e?e.startsWith("?")?e.slice(1):e:""}static _stringifySearchParams(e){return Array.from(e.entries()).map(([e,t])=>`${encodeURIComponent(e)}=${this._encodeSearchValue(t)}`).join("&")}static buildRouteSearch(e,t,i=("undefined"!=typeof window?window.location.search:"")){const a=new URLSearchParams(this._normalizeSearch(i));if(this.ROUTE_QUERY_KEYS.forEach(e=>a.delete(e)),!e||!t?.length)return this._stringifySearchParams(a);const s=t[0],n=t[t.length-1];return a.set("appId",e),a.set("entry",this._encodePage(s.pagePath,s.query||{})),a.set("page",this._encodePage(n.pagePath,n.query||{})),this._stringifySearchParams(a)}static buildRouteURL(e,t,i=("undefined"!=typeof window?`${window.location.origin}${window.location.pathname}`:"")){const a=this.buildRouteSearch(e,t);return`${i}${a?`?${a}`:""}`}static syncStack(e,t){const i=this.buildRouteSearch(e,t);history.replaceState(null,"",`${window.location.pathname}${i?`?${i}`:""}`)}static clear(){const e=new URLSearchParams(this._normalizeSearch(window.location.search));this.ROUTE_QUERY_KEYS.forEach(t=>e.delete(t));const t=this._stringifySearchParams(e);history.replaceState(null,"",`${window.location.pathname}${t?`?${t}`:""}`)}static parseSearch(e){const t=new URLSearchParams(this._normalizeSearch(e)),i=t.get("appId"),a=t.get("entry"),s=t.get("page")||a;if(!i||!a)return null;const n=this._decodePage(a);if(!n.pagePath)return null;const o=[n];if(s&&s!==a){const e=this._decodePage(s);e.pagePath&&o.push(e)}return{appId:i,stack:o}}static parseHash(e){if(!e||e.length<=1)return null;const t=e.slice(1).split("|");if(t.length<2)return null;const i=t[0],a=t.slice(1).map(e=>this._decodePage(e));return i&&0!==a.length?{appId:i,stack:a}:null}static parse(e,t=("undefined"!=typeof window?window.location.search:"")){return this.parseSearch(t)||this.parseHash(e)}},R=(e,t,i=560)=>new Promise(a=>{const s=setTimeout(a,i),n=i=>{t&&i.propertyName!==t||(clearTimeout(s),e.removeEventListener("transitionend",n),a())};e.addEventListener("transitionend",n)}),$=class{constructor(e){this.appInfo=e,this.id=`mini_app_${s()}`,this.parent=null,this.appId=e.appId,this.appConfig=null,this.bridgeList=[],this.jscore=new q(this),this.webviewsContainer=null,this.webviewAnimaEnd=!0,this.el=document.createElement("div"),this.el.classList.add("dimina-native-view"),this.toastInfo={dom:null,timer:null},this.color=null,this.apiRegistry={},this._extSubscriptions=/* @__PURE__ */new Map,this.tabBarConfig=null,this.tabBarPaths=[],this.tabBarBridges=/* @__PURE__ */new Map,this.currentTabPath=null,this.tabBarEl=null,this.tabBarHeight=0,this._modalStack=[],this._modalPendingTimers=/* @__PURE__ */new Set,this._destroyed=!1}_normalizePagePath(e){return e?e.startsWith("/")?e.slice(1):e:""}_isTabBarPage(e){return this.tabBarPaths.includes(this._normalizePagePath(e))}getCurrentPagePath(){return this.bridgeList[this.bridgeList.length-1]?.opts?.pagePath||this.appInfo.pagePath||this.appConfig?.app?.entryPagePath||""}getCurrentPageQuery(){return this.bridgeList[this.bridgeList.length-1]?.opts?.query||this.appInfo.query||{}}getEntryPagePath(){return this.appInfo.pagePath||this.appConfig?.app?.entryPagePath||""}async copyText(e,t){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(e);else{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}this.showToast({title:t,icon:"success"})}catch{this.showToast({title:"复制失败",icon:"none"})}}closeMiniProgram(){F.clear(),this.closeMiniAppMenu(),r.closeApp(this)}renderMiniAppMenu(){const e=this.el.querySelector(".dimina-mini-app-menu__app-name"),t=this.el.querySelector(".dimina-mini-app-menu__app-id"),i=this.el.querySelector(".dimina-mini-app-menu__app-desc"),a=this.el.querySelector(".dimina-mini-app-menu__app-logo-img"),s=this.el.querySelector(".dimina-mini-app-menu__quick-actions"),n=this.getCurrentPagePath(),o=this.getEntryPagePath(),r=this.getCurrentPageQuery(),l=n||o||"",c=F.buildRouteURL(this.appId,[{pagePath:o,query:this.appInfo.query||{}},{pagePath:l,query:r}]);e.textContent=this.appInfo.name||"未命名小程序",t.textContent=`AppID:${this.appId||"--"}`,i.textContent=`当前页面:${l||"--"}`,a.src=this.appInfo.logo||"";const h=[{label:"复制链接",icon:"↗",handler:()=>this.copyText(c,"链接已复制")},{label:"重新进入",icon:"↻",handler:()=>{this.closeMiniAppMenu(),this.reLaunch({url:o||n})}},{label:"关闭小程序",icon:"×",danger:!0,handler:()=>this.closeMiniProgram()}];s.innerHTML=h.map((e,t)=>`\n\t\t\t\t<button type="button" class="dimina-mini-app-menu__quick-action${e.danger?" is-danger":""}" data-quick-index="${t}">\n\t\t\t\t\t<span class="dimina-mini-app-menu__quick-action-icon">${e.icon}</span>\n\t\t\t\t\t<span class="dimina-mini-app-menu__quick-action-label">${e.label}</span>\n\t\t\t\t</button>\n\t\t\t`).join(""),s.querySelectorAll("[data-quick-index]").forEach((e,t)=>{e.onclick=()=>h[t].handler()})}openMiniAppMenu(){const e=this.el.querySelector(".dimina-mini-app-menu__mask"),t=this.el.querySelector(".dimina-mini-app-menu");this.renderMiniAppMenu(),e.style.display="block",requestAnimationFrame(()=>{e.classList.add("show"),t.classList.add("show")})}closeMiniAppMenu(){const e=this.el.querySelector(".dimina-mini-app-menu__mask"),t=this.el.querySelector(".dimina-mini-app-menu");e.classList.remove("show"),t.classList.remove("show")}registerApi(e,t){this.apiRegistry[e]=t}invokeApi(e,t){const i=this.apiRegistry[e];i?i.call(this,t):"function"==typeof this[e]?this[e](t):this._handleExtCall(e,t)}viewDidLoad(){this.initPageFrame(),this.webviewsContainer=this.el.querySelector(".dimina-mini-app__webviews"),this.showLaunchScreen(),this.bindMoreEvent(),this.bindCloseEvent(),this.initApp()}async initApp(){await this.jscore.init();const e="main",t=`${this.appInfo.appId}/${e}/app-config.json`,[i]=await Promise.all([(s=`/${t}`,new Promise(e=>{fetch(`${s}`).then(e=>e.text()).then(t=>{e(t)}).catch(()=>{e(null)})})),(a=560,new Promise(e=>{setTimeout(()=>{e()},a)}))]);var a,s;if(!i)return;this.appConfig=JSON.parse(i),this._initTabBar();const n=this.appInfo.pagePath||this.appConfig.app.entryPagePath,r=this.appConfig.modules[n],l=o(this.appConfig.app,r);this.updateTargetPageColorStyle(l);const c=await this.createBridge({pagePath:n,query:this.appInfo.query,scene:this.appInfo.scene,jscore:this.jscore,isRoot:!0,root:e,appId:this.appInfo.appId,pages:this.appConfig.app.pages,configInfo:l});if(this.bridgeList.push(c),this._isTabBarPage(n)){const e=this._normalizePagePath(n);this.tabBarBridges.set(e,c),this.currentTabPath=e,this._setTabBarVisible(!0),this._updateTabBarSelection(e)}c.start(),this.appInfo.restoreStack&&this.appInfo.restoreStack.length>1&&await this.restorePageStack(this.appInfo.restoreStack.slice(1)),this._syncHash(),this.hideLaunchScreen()}async restorePageStack(e){for(let t=0;t<e.length;t++){const{pagePath:i,query:a}=e[t],s=t===e.length-1,n=i.startsWith("/")?i.slice(1):i,r=this.appConfig.modules[n],l=o(this.appConfig.app,r),c=await this.createBridge({pagePath:n,query:a,scene:this.appInfo.scene,jscore:this.jscore,isRoot:!1,root:r?.root||"main",appId:this.appInfo.appId,pages:this.appConfig.app.pages,configInfo:l}),h=this.bridgeList[this.bridgeList.length-1];h.webview.el.classList.remove("dimina-native-view--instage"),h.webview.el.classList.add("dimina-native-view--slide-out"),this.bridgeList.push(c),c.webview.el.style.zIndex=this.bridgeList.length+1,c.webview.el.classList.remove("dimina-native-view--before-enter"),s||c.webview.el.classList.add("dimina-native-view--slide-out"),c.start()}if(e.length>0){const e=this.bridgeList[this.bridgeList.length-1],t=this.appConfig.modules[e.opts.pagePath],i=o(this.appConfig.app,t);this.updateTargetPageColorStyle(i),this._isTabBarPage(e.opts.pagePath)||this._setTabBarVisible(!1)}}_syncHash(){const e=this.bridgeList.map(e=>({pagePath:e.opts.pagePath.startsWith("/")?e.opts.pagePath.slice(1):e.opts.pagePath,query:e.opts.query||{}}));F.syncStack(this.appId,e)}async createBridge(e){const{jscore:t,configInfo:i,isRoot:a,appId:s,pagePath:n,query:o,scene:r,pages:l,root:c}=e,h=new A({jscore:t,configInfo:i,isRoot:a,appId:s,pagePath:n,query:o,scene:r,pages:l,root:c});return h.parent=this,await h.init(),h}onPresentIn(){const e=this.bridgeList[this.bridgeList.length-1];e?.appShow(),e?.pageShow()}onPresentOut(){const e=this.bridgeList[this.bridgeList.length-1];e?.appHide(),e?.pageHide()}initPageFrame(){this.el.innerHTML='<div class="dimina-mini-app">\n\t\x3c!-- 右上方药丸按钮 --\x3e\n\t<ul class="dimina-mini-app-navigation__actions">\n\t\t<li class="dimina-mini-app-navigation__actions-variable"></li>\n\t\t<li class="dimina-mini-app-navigation__actions-close"></li>\n\t</ul>\n\n\t\x3c!-- webview挂载节点 --\x3e\n\t<div class="dimina-mini-app__webviews"></div>\n\n\t\x3c!-- TabBar 底部导航栏 --\x3e\n\t<div class="dimina-mini-app__tabbar" style="display: none;"></div>\n\n\t\x3c!-- 启动loading页面 --\x3e\n\t<div class="dimina-mini-app__launch-screen">\n\t\t<div class="dimina-mini-app__launch-screen-content">\n\t\t\t<div class="dimina-mini-app__logo">\n\t\t\t\t<div class="dimina-mini-app__logo-img">\n\t\t\t\t\t<img class="dimina-mini-app__logo-img-url" alt="logo" />\n\t\t\t\t</div>\n\t\t\t\t<div class="dimina-mini-app__logo-circle"></div>\n\t\t\t\t<span class="dimina-mini-app__green-point"></span>\n\t\t\t</div>\n\t\t\t<h1 class="dimina-mini-app__name"></h1>\n\t\t</div>\n\t</div>\n\n\t<div class="dimina-mini-app-menu__mask"></div>\n\t<div class="dimina-mini-app-menu">\n\t\t<div class="dimina-mini-app-menu__handle"></div>\n\t\t<div class="dimina-mini-app-menu__app">\n\t\t\t<div class="dimina-mini-app-menu__app-logo">\n\t\t\t\t<img class="dimina-mini-app-menu__app-logo-img" alt="logo" />\n\t\t\t</div>\n\t\t\t<div class="dimina-mini-app-menu__app-meta">\n\t\t\t\t<h2 class="dimina-mini-app-menu__app-name"></h2>\n\t\t\t\t<p class="dimina-mini-app-menu__app-id"></p>\n\t\t\t\t<p class="dimina-mini-app-menu__app-desc"></p>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class="dimina-mini-app-menu__quick-actions"></div>\n\t\t<div class="dimina-mini-app-menu__footer">\n\t\t\t<button type="button" class="dimina-mini-app-menu__footer-btn dimina-mini-app-menu__footer-btn--cancel">取消</button>\n\t\t</div>\n\t</div>\n</div>\n'}updateTargetPageColorStyle(e){const{navigationBarTextStyle:t}=e;this.updateActionColorStyle(t)}showLaunchScreen(){const e=this.el.querySelector(".dimina-mini-app__launch-screen"),t=this.el.querySelector(".dimina-mini-app__name"),i=this.el.querySelector(".dimina-mini-app__logo-img-url");this.updateActionColorStyle("black"),t.innerHTML=this.appInfo.name,i.src=this.appInfo.logo,e.style.display="block"}hideLaunchScreen(){this.el.querySelector(".dimina-mini-app__launch-screen").style.display="none"}updateActionColorStyle(e){this.color=e;const t=this.el.querySelector(".dimina-mini-app-navigation__actions");"white"===e?(t.classList.remove("dimina-mini-app-navigation__actions--black"),t.classList.add("dimina-mini-app-navigation__actions--white")):"black"===e&&(t.classList.remove("dimina-mini-app-navigation__actions--white"),t.classList.add("dimina-mini-app-navigation__actions--black")),this.parent.updateStatusBarColor(e)}restoreColorStyle(){this.updateActionColorStyle(this.color)}createCallbackFunction(e){if(e)return t=>{this.jscore.postMessage({type:"triggerCallback",body:{id:e,args:t}})}}async navigateTo(e){const{url:t,success:i,fail:a,complete:s}=e,{query:r,pagePath:l}=n(t),c=this.createCallbackFunction(i),h=this.createCallbackFunction(a),d=this.createCallbackFunction(s);if(this._isTabBarPage(l))return h?.({errMsg:"navigateTo:fail can not navigateTo a tabbar page"}),void d?.();if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const p=this.appConfig.modules[l],g=o(this.appConfig.app,p);this.updateTargetPageColorStyle(g);const m=await this.createBridge({pagePath:l,query:r,scene:this.appInfo.scene,jscore:this.jscore,isRoot:!1,root:p?.root||"main",appId:this.appInfo.appId,pages:this.appConfig.app.pages,configInfo:g}),u=this.bridgeList[this.bridgeList.length-1],b=u.webview;this.bridgeList.push(m),m.start(),this._syncHash(),b.el.classList.remove("dimina-native-view--instage"),b.el.classList.add("dimina-native-view--slide-out"),b.el.classList.add("dimina-native-view--linear-anima"),u?.pageHide(),this._setTabBarVisible(!1),m.webview.el.style.zIndex=this.bridgeList.length+1,m.webview.el.classList.add("dimina-native-view--enter-anima"),m.webview.el.classList.add("dimina-native-view--instage"),await R(m.webview.el,"transform"),this.webviewAnimaEnd=!0,b.el.classList.remove("dimina-native-view--linear-anima"),m.webview.el.classList.remove("dimina-native-view--before-enter"),m.webview.el.classList.remove("dimina-native-view--enter-anima"),m.webview.el.classList.remove("dimina-native-view--instage"),c?.({errMsg:"navigateTo:ok"}),d?.()}reLaunch(e){if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const{url:t,success:i,fail:a,complete:s}=e,{query:r,pagePath:l}=n(t),c=this.createCallbackFunction(i),h=this.createCallbackFunction(a),d=this.createCallbackFunction(s);try{const e=this.appConfig.modules[l],t=o(this.appConfig.app,e);this.updateTargetPageColorStyle(t);const i=new Set([...this.bridgeList,...this.tabBarBridges.values()]);for(const a of i)a.destroy(),a.webview?.el?.remove();this.bridgeList.length=0,this.tabBarBridges.clear(),this.currentTabPath=null,this.webviewsContainer&&(this.webviewsContainer.innerHTML=""),this.createBridge({pagePath:l,query:r,scene:this.appInfo.scene,jscore:this.jscore,isRoot:!0,root:e?.root||"main",appId:this.appInfo.appId,pages:this.appConfig.app.pages,configInfo:t}).then(e=>{if(this.bridgeList.push(e),this._isTabBarPage(l)){const t=this._normalizePagePath(l);this.tabBarBridges.set(t,e),this.currentTabPath=t,this._setTabBarVisible(!0),this._updateTabBarSelection(t)}else this._setTabBarVisible(!1);e.start(),this._syncHash(),e.webview.el.style.zIndex=1,this.webviewAnimaEnd=!0,c?.({errMsg:"reLaunch:ok"}),d?.()}).catch(e=>{h?.({errMsg:`reLaunch:fail ${e.message}`}),d?.(),this.webviewAnimaEnd=!0})}catch(p){h?.({errMsg:`reLaunch:fail ${p.message}`}),d?.(),this.webviewAnimaEnd=!0}}applyUpdate(){this.reLaunch({url:this.getEntryPagePath()})}redirectTo(e){const{url:t,success:i,fail:a,complete:s}=e,{query:r,pagePath:l}=n(t),c=this.createCallbackFunction(i),h=this.createCallbackFunction(a),d=this.createCallbackFunction(s);if(this._isTabBarPage(l))return h?.({errMsg:"redirectTo:fail can not redirectTo a tabbar page"}),void d?.();if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const p=this.bridgeList[this.bridgeList.length-1],g=this._normalizePagePath(p.opts.pagePath),m=this.appConfig.modules[l],u=o(this.appConfig.app,m);this.updateTargetPageColorStyle(u),p.destroy(),p.opts={...p.opts,pagePath:l,query:r,configInfo:u},p.resetStatus(),p.start(),this._syncHash(),this.tabBarBridges.get(g)===p&&(this.tabBarBridges.delete(g),this.currentTabPath===g&&(this.currentTabPath=null)),this._setBridgeTabBarInset(p,!1),this._setTabBarVisible(!1),this.webviewAnimaEnd=!0,c?.({errMsg:"redirectTo:ok"}),d?.()}async navigateBack(){if(this.bridgeList.length<2)return;if(!this.webviewAnimaEnd)return;this.webviewAnimaEnd=!1;const e=this.bridgeList.pop(),t=this.bridgeList[this.bridgeList.length-1],i=this.appConfig.modules[t.opts.pagePath],a=o(this.appConfig.app,i);if(this.updateTargetPageColorStyle(a),e.webview.el.classList.add("dimina-native-view--before-enter"),e.webview.el.classList.add("dimina-native-view--enter-anima"),e?.destroy(),t.webview.el.classList.remove("dimina-native-view--slide-out"),t.webview.el.classList.add("dimina-native-view--instage"),t.webview.el.classList.add("dimina-native-view--enter-anima"),t?.pageShow(),this._syncHash(),this._isTabBarPage(t.opts.pagePath)){const e=this._normalizePagePath(t.opts.pagePath);this.currentTabPath=e,this._setTabBarVisible(!0),this._updateTabBarSelection(e)}await R(t.webview.el,"transform"),this.webviewAnimaEnd=!0,t.webview.el.classList.remove("dimina-native-view--enter-anima"),t.webview.el.classList.remove("dimina-native-view--instage"),e.webview.el.parentNode.removeChild(e.webview.el)}async switchTab(e){const{url:t,success:i,fail:a,complete:s}=e,{query:r,pagePath:l}=n(t),c=this._normalizePagePath(l),h=this.createCallbackFunction(i),d=this.createCallbackFunction(a),p=this.createCallbackFunction(s);if(!this._isTabBarPage(c))return d?.({errMsg:`switchTab:fail not a tabBar page: ${c}`}),void p?.();if(!this.webviewAnimaEnd)return d?.({errMsg:"switchTab:fail busy"}),void p?.();if(this.currentTabPath===c&&1===this.bridgeList.length)return this._setTabBarVisible(!0),this._updateTabBarSelection(c),h?.({errMsg:"switchTab:ok"}),void p?.();this.webviewAnimaEnd=!1;try{const e=this.currentTabPath,t=e?this.tabBarBridges.get(e):null,i=!!t&&1===this.bridgeList.length&&this.bridgeList[0]===t;for(;this.bridgeList.length>0;){const e=this.bridgeList[this.bridgeList.length-1];if(this._isTabBarPage(e.opts.pagePath))break;e.pageHide(),e.destroy(),e.webview?.el?.remove(),this.bridgeList.pop()}if(t&&t!==this.tabBarBridges.get(c)){i&&t.pageHide(),t.webview?.el&&(t.webview.el.style.display="none");const e=this.bridgeList.indexOf(t);e>=0&&this.bridgeList.splice(e,1)}let a=this.tabBarBridges.get(c);const s=this.appConfig.modules[c],n=o(this.appConfig.app,s);this.updateTargetPageColorStyle(n),a||(a=await this.createBridge({pagePath:c,query:r,scene:this.appInfo.scene,jscore:this.jscore,isRoot:!0,root:s?.root||"main",appId:this.appInfo.appId,pages:this.appConfig.app.pages,configInfo:n}),this.tabBarBridges.set(c,a),a.start());const l=a.webview.el;this._setBridgeTabBarInset(a,!0),l.classList.remove("dimina-native-view--before-enter","dimina-native-view--slide-out","dimina-native-view--enter-anima","dimina-native-view--linear-anima","dimina-native-view--instage"),l.style.display="",l.style.zIndex=1,this.bridgeList.includes(a)||this.bridgeList.push(a),this.currentTabPath=c,a.pageShow(),this._setTabBarVisible(!0),this._updateTabBarSelection(c),this._syncHash(),h?.({errMsg:"switchTab:ok"})}catch(g){d?.({errMsg:`switchTab:fail ${g.message}`})}finally{this.webviewAnimaEnd=!0,p?.()}}_initTabBar(){const e=this.appConfig?.app?.tabBar;e&&Array.isArray(e.list)&&0!==e.list.length&&(this.tabBarConfig=e,this.tabBarPaths=e.list.map(e=>this._normalizePagePath(e.pagePath)),this._renderTabBar())}_renderTabBar(){if(this.tabBarEl=this.el.querySelector(".dimina-mini-app__tabbar"),!this.tabBarEl)return;const{color:e,backgroundColor:t,borderStyle:i,list:a}=this.tabBarConfig,s=this._sanitizeCssColor(e)||"#999999",n=this._sanitizeCssColor(t)||"#ffffff",o="white"===i?"#FFFFFF":"#E0E0E0";this.tabBarEl.textContent="";const r=document.createElement("div");r.className="dimina-tabbar",r.style.backgroundColor=n,r.style.borderTop=`0.5px solid ${o}`,a.forEach((e,t)=>{const i=this._normalizePagePath(e.pagePath),a=document.createElement("div");a.className="dimina-tabbar-item",a.dataset.path=i,a.dataset.index=String(t);const n=this._resolveTabBarIcon(e.iconPath);n&&a.appendChild(this._createTabBarIcon(n,"dimina-tabbar-icon-default"));const o=this._resolveTabBarIcon(e.selectedIconPath);o&&a.appendChild(this._createTabBarIcon(o,"dimina-tabbar-icon-selected"));const l=document.createElement("span");l.className="dimina-tabbar-text",l.style.color=s,l.textContent=e.text||"",a.appendChild(l),r.appendChild(a)}),this.tabBarEl.appendChild(r),this.tabBarEl.addEventListener("click",e=>{const t=e.target.closest(".dimina-tabbar-item");if(!t)return;const i=t.dataset.path;i&&i!==this.currentTabPath&&this.switchTab({url:`/${i}`})}),"undefined"!=typeof ResizeObserver&&(this._tabBarResizeObserver?.disconnect(),this._tabBarResizeObserver=new ResizeObserver(()=>this._syncTabBarHeightVar()),this._tabBarResizeObserver.observe(this.tabBarEl))}_createTabBarIcon(e,t){const i=document.createElement("img");return i.className=`dimina-tabbar-icon ${t}`,i.src=e,i.alt="",i.addEventListener("error",()=>{i.style.display="none"}),i}_sanitizeCssColor(e){if(!e||"string"!=typeof e)return"";const t=e.trim();return 0===t.length||t.length>64?"":/[<>"';{}()\\]/.test(t)?/^(?:rgb|rgba|hsl|hsla)\(\s*[\d.,%\s/-]+\)$/i.test(t)?t:"":t}_getTabBarHeight(){if(!this.tabBarEl)return this.tabBarHeight;let e=this.tabBarEl.getBoundingClientRect().height;if(!e&&"none"===this.tabBarEl.style.display){const t=this.tabBarEl.style.display,i=this.tabBarEl.style.visibility;this.tabBarEl.style.visibility="hidden",this.tabBarEl.style.display="block",e=this.tabBarEl.getBoundingClientRect().height,this.tabBarEl.style.display=t,this.tabBarEl.style.visibility=i}return e>0&&(this.tabBarHeight=e),this.tabBarHeight}_syncTabBarHeightVar(){const e=this._getTabBarHeight();this.el.style.setProperty("--dimina-tabbar-height",`${e}px`),this._syncTabBarBridgeInsets()}_setBridgeTabBarInset(e,t){const i=e?.webview?.el;i&&(t?i.style.bottom=`${this._getTabBarHeight()}px`:i.style.removeProperty("bottom"))}_syncTabBarBridgeInsets(){for(const e of this.tabBarBridges.values())this._setBridgeTabBarInset(e,!0)}_joinBaseUrl(...e){return`${"/".endsWith("/")?"/":"//"}${e.map(e=>String(e).trim().replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/")}`}_resolveTabBarIcon(e){if(!e||"string"!=typeof e)return null;const t=e.trim();if(!t)return null;if(/^(?:data:|blob:|https?:|\/\/)/i.test(t))return t;const i=t.replace(/^\/+/,"").replace(/^\.\//,""),a=`${this.appId}/`;return i.startsWith(a)?this._joinBaseUrl(i):this._joinBaseUrl(this.appId,"main",i)}_setTabBarVisible(e){this.tabBarEl&&(this.tabBarEl.style.display=e?"block":"none",this._syncTabBarHeightVar())}_updateTabBarSelection(e){if(!this.tabBarEl||!this.tabBarConfig)return;const t=this.tabBarConfig.color||"#999999",i=this.tabBarConfig.selectedColor||"#1890ff";this.tabBarEl.querySelectorAll(".dimina-tabbar-item").forEach(a=>{const s=a.getAttribute("data-path")===e,n=a.querySelector(".dimina-tabbar-text"),o=a.querySelector(".dimina-tabbar-icon-default"),r=a.querySelector(".dimina-tabbar-icon-selected");n&&(n.style.color=s?i:t),o&&(o.style.display=s?"none":"block"),r&&(r.style.display=s?"block":"none"),a.classList.toggle("dimina-tabbar-item--selected",s)})}setTabBarStyle(e={}){const{color:t,selectedColor:i,backgroundColor:a,borderStyle:s,success:n,fail:o,complete:r}=e,l=this.createCallbackFunction(n),c=this.createCallbackFunction(o),h=this.createCallbackFunction(r);if(!this.tabBarConfig||!this.tabBarEl)return c?.({errMsg:"setTabBarStyle:fail tabBar not configured"}),void h?.();const d="black"===s||"white"===s?s:null,p=void 0!==t?this._sanitizeCssColor(t):null,g=void 0!==i?this._sanitizeCssColor(i):null,m=void 0!==a?this._sanitizeCssColor(a):null;p&&(this.tabBarConfig.color=p),g&&(this.tabBarConfig.selectedColor=g),m&&(this.tabBarConfig.backgroundColor=m),d&&(this.tabBarConfig.borderStyle=d);const u=this.tabBarEl.querySelector(".dimina-tabbar");if(u&&(m&&(u.style.backgroundColor=m),d)){const e="white"===d?"#FFFFFF":"#E0E0E0";u.style.borderTop=`0.5px solid ${e}`}this._updateTabBarSelection(this.currentTabPath),l?.({errMsg:"setTabBarStyle:ok"}),h?.()}navigateToMiniProgram(e){const{appId:t,path:i}=e;r.openApp({appId:t,path:i,scene:1037},this.parent)}bindMoreEvent(){const e=this.el.querySelector(".dimina-mini-app-navigation__actions-variable"),t=this.el.querySelector(".dimina-mini-app-menu__mask"),i=this.el.querySelector(".dimina-mini-app-menu"),a=this.el.querySelector(".dimina-mini-app-menu__footer-btn--cancel");t.addEventListener("transitionend",()=>{t.classList.contains("show")||(t.style.display="none")}),e.onclick=()=>this.openMiniAppMenu(),t.onclick=()=>this.closeMiniAppMenu(),a.onclick=()=>this.closeMiniAppMenu(),i.onclick=e=>e.stopPropagation()}bindCloseEvent(){this.el.querySelector(".dimina-mini-app-navigation__actions-close").onclick=()=>{this.closeMiniProgram()}}destroy(){this._destroyed=!0;for(const e of this._extSubscriptions.values())e?.();this._extSubscriptions.clear(),this._tabBarResizeObserver?.disconnect(),this._tabBarResizeObserver=null;for(const e of this._modalPendingTimers)clearTimeout(e);this._modalPendingTimers.clear();for(const e of this._modalStack)e.mask?.remove(),e.dialog?.remove();this._modalStack.length=0,this.hideToast({}),r.popView(),this.jscore.destroy()}getNetworkType(e){const{success:t}=e;this.createCallbackFunction(t)?.({networkType:"wifi"})}request({url:e,data:t,header:i={},timeout:a=0,method:s="GET",dataType:n="json",responseType:o="text",success:r,fail:l,complete:c}){const h={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e,data:t,header:i,timeout:a,method:s,dataType:n,responseType:o})},d=this.createCallbackFunction(r),p=this.createCallbackFunction(l),g=this.createCallbackFunction(c);fetch("http://localhost:7788/proxy",h).then(e=>{if(!e.ok){const t=new Error(e.statusText);throw t.code=e.status,t}const t={};switch(e.headers.forEach((e,i)=>{t[i]=e}),n){case"json":return e.json().then(i=>({data:JSON.parse(i),header:t,statusCode:e.status}));case"arraybuffer":return e.arrayBuffer().then(i=>({data:i,header:t,statusCode:e.status}));default:return e.text().then(i=>({data:i,header:t,statusCode:e.status}))}}).then(e=>{d?.(e)}).catch(e=>{p?.({errMsg:e.message,errno:e.code})}).finally(()=>{g?.()})}getSystemInfoAsync(e){const t=this.parent.parent.root.querySelector(".iphone__status-bar").getBoundingClientRect(),i=this.parent.el.querySelector(".dimina-native-webview__root").getBoundingClientRect(),{success:a,complete:s}=e,n=this.createCallbackFunction(a),o=this.createCallbackFunction(s);n?.({statusBarHeight:t.height,brand:"devtools",mode:"default",model:"web",platform:"devtools",system:"web",deviceOrientation:"portrait",SDKVersion:"3.0.0",language:"zh_CN",wifiEnabled:!0,safeArea:{width:i.width,height:i.height,top:i.top,bottom:i.bottom,left:i.left,right:i.right}}),o?.()}getMenuButtonBoundingClientRect(){const e=this.el.querySelector(".dimina-mini-app-navigation__actions").getBoundingClientRect(),t=(this.parent.parent.root.querySelector(".iphone__status-bar")?.getBoundingClientRect().height||20)+4,i=t+e.height;return{top:t,right:e.right,bottom:i,left:e.left,width:e.width,height:e.height,x:e.x,y:t}}getHostEnvSnapshot(){return{menuRect:this.getMenuButtonBoundingClientRect(),systemInfo:this.getSystemInfoSync()}}getSystemInfoSync(){const e=this.parent.parent.root.querySelector(".iphone__status-bar"),t=this.parent.el.querySelector(".dimina-native-webview__root")?.getBoundingClientRect(),i=t?.width||this.el.clientWidth||375,a=t?.height||this.el.clientHeight||667,s=e?.getBoundingClientRect().height||20;return{brand:"devtools",model:"web",platform:"devtools",system:"web",SDKVersion:"3.0.0",pixelRatio:globalThis.devicePixelRatio||1,screenWidth:i,screenHeight:a,windowWidth:i,windowHeight:a,statusBarHeight:s,safeArea:{left:0,right:i,top:s,bottom:a,width:i,height:Math.max(a-s,0)}}}showToast(e={}){const{title:t="",duration:i=1500,icon:a="success",mask:s=!1,success:n,complete:o}=e;if(!t)return;this.hideToast({});const r=this.createCallbackFunction(n),l=this.createCallbackFunction(o);let c=null;s&&(c=document.createElement("div"),c.className="dimina-toast-mask",this.el.appendChild(c));const h=document.createElement("div");h.className=`dimina-toast dimina-toast--${a}`,"none"===a&&h.classList.add("dimina-toast--text-only");const d=document.createElement("p");d.textContent=String(t),h.appendChild(d),this.el.appendChild(h),this.toastInfo.dom=h,this.toastInfo.maskEl=c,this.toastInfo.timer=setTimeout(()=>{h.remove(),c?.remove(),this.toastInfo.dom===h&&(this.toastInfo.dom=null,this.toastInfo.maskEl=null,this.toastInfo.timer=null)},i),r?.(),l?.()}hideToast(e={}){const{success:t,complete:i}=e,a=this.createCallbackFunction(t),s=this.createCallbackFunction(i);this.toastInfo.dom&&(this.toastInfo.dom.remove(),this.toastInfo.dom=null),this.toastInfo.maskEl&&(this.toastInfo.maskEl.remove(),this.toastInfo.maskEl=null),this.toastInfo.timer&&(clearTimeout(this.toastInfo.timer),this.toastInfo.timer=null),a?.(),s?.()}showLoading(e={}){this.showToast({...e,icon:"loading"})}hideLoading(e={}){this.hideToast(e)}showModal(e){if(this._destroyed)return;const t=this._mountModal(e||{});this._modalStack.push(t),this._updateModalView(),t.mask.classList.add("show");const i=setTimeout(()=>{this._modalPendingTimers.delete(i),this._destroyed||this._modalStack.includes(t)&&t.dialog.classList.add("show")},100);this._modalPendingTimers.add(i)}_updateModalView(){const e=this._modalStack.length-1;for(let t=0;t<this._modalStack.length;t++){const i=this._modalStack[t];t===e?(i.mask.classList.remove("dimina-modal--occluded"),i.dialog.classList.remove("dimina-modal--occluded")):(i.mask.classList.add("dimina-modal--occluded"),i.dialog.classList.add("dimina-modal--occluded"))}}_mountModal(e){const{title:t="",content:i="",showCancel:a=!0,cancelText:s="取消",cancelColor:n="#000",confirmText:o="确定",confirmColor:r="#576b95",success:l,complete:c}=e,h=this.createCallbackFunction(l),d=this.createCallbackFunction(c),p=document.createElement("div");p.className="dimina-dialog-mask";const g=document.createElement("div");g.className="dimina-dialog";const m=this._modalStack.length;if(p.style.zIndex=String(1100+20*m),g.style.zIndex=String(1110+20*m),t){const e=document.createElement("h2");e.className="dimina-dialog__title",e.textContent=String(t),g.appendChild(e)}if(i){const e=document.createElement("p");e.className="dimina-dialog__content",e.textContent=String(i),g.appendChild(e)}const u=document.createElement("div");u.className="dimina-dialog__buttons";let b=!1;const v={mask:p,dialog:g,close:null},w=e=>{if(b)return;b=!0;const t=this._modalStack.indexOf(v);t>=0&&this._modalStack.splice(t,1),0===this._modalStack.length?(p.classList.remove("show"),g.classList.remove("show"),setTimeout(()=>{p.remove(),g.remove()},200)):(p.remove(),g.remove()),this._updateModalView(),h?.(e),d?.()};if(v.close=w,a){const e=document.createElement("button");e.type="button",e.className="dimina-dialog__button",e.style.color=n,e.textContent=String(s),e.addEventListener("click",()=>{w({cancel:!0,confirm:!1,errMsg:"showModal:ok"})}),u.appendChild(e)}const f=document.createElement("button");return f.type="button",f.className="dimina-dialog__button",f.style.color=r,f.textContent=String(o),f.addEventListener("click",()=>{w({cancel:!1,confirm:!0,errMsg:"showModal:ok"})}),u.appendChild(f),g.appendChild(u),this.el.appendChild(p),this.el.appendChild(g),v}showActionSheet(e){const{itemList:t=[],itemColor:i="#000",success:a,fail:s,complete:n}=e||{};if(!Array.isArray(t)||0===t.length)return s&&this.createCallbackFunction(s)({errMsg:"showActionSheet:fail"}),void(n&&this.createCallbackFunction(n)());const o=document.createElement("div");o.className="dimina-action-sheet-mask";const r=document.createElement("div");r.className="dimina-action-sheet";const l=()=>{o.remove(),r.remove()};t.forEach((e,t)=>{const s=document.createElement("div");s.className="dimina-action-sheet-item",s.style.color=i,s.textContent=e,s.onclick=()=>{l(),a&&this.createCallbackFunction(a)({tapIndex:t}),n&&this.createCallbackFunction(n)()},r.appendChild(s)});const c=document.createElement("div");c.className="dimina-action-sheet-cancel",c.textContent="取消",c.onclick=()=>{l(),s&&this.createCallbackFunction(s)({errMsg:"showActionSheet:fail cancel"}),n&&this.createCallbackFunction(n)()},r.appendChild(c),o.onclick=l,this.el.appendChild(o),this.el.appendChild(r),requestAnimationFrame(()=>requestAnimationFrame(()=>{r.classList.add("show"),o.classList.add("show")}))}setNavigationBarTitle(e){const{title:t,success:i,fail:a,complete:s}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(a),r=this.createCallbackFunction(s);try{const e=this.bridgeList[this.bridgeList.length-1].webview.el.querySelector(".dimina-native-webview__navigation-title");e?(e.textContent=t||"",n?.({errMsg:"setNavigationBarTitle:ok"})):o?.({errMsg:"setNavigationBarTitle:fail Navigation title element not found"})}catch(l){o?.({errMsg:`setNavigationBarTitle:fail ${l.message}`})}finally{r?.()}}setNavigationBarColor(e){const{frontColor:t,backgroundColor:i,success:a,fail:s,complete:n}=e,o=this.createCallbackFunction(a),r=this.createCallbackFunction(s),l=this.createCallbackFunction(n);try{const e=this.bridgeList[this.bridgeList.length-1].webview.el.querySelector(".dimina-native-webview__navigation");e?(t&&(e.querySelector(".dimina-native-webview__navigation-title").style.color=t),i&&(e.style.backgroundColor=i),o?.({errMsg:"setNavigationBarColor:ok"})):r?.({errMsg:"setNavigationBarColor:fail Navigation element not found"})}catch(c){r?.({errMsg:`setNavigationBarColor:fail ${c.message}`})}finally{l?.()}}pageScrollTo(e){const{scrollTop:t,duration:i=300,success:a,fail:s,complete:n}=e,o=this.createCallbackFunction(a),r=this.createCallbackFunction(s),l=this.createCallbackFunction(n);try{const e=this.bridgeList[this.bridgeList.length-1].webview.iframe.contentWindow.document.documentElement;e?(e.scrollTo({top:t,behavior:i>0?"smooth":"auto"}),setTimeout(()=>{o?.({errMsg:"pageScrollTo:ok"}),l?.()},i)):(r?.({errMsg:"pageScrollTo:fail Webview root element not found"}),l?.())}catch(c){r?.({errMsg:`pageScrollTo:fail ${c.message}`}),l?.()}}setClipboardData(e){const{data:t,success:i,fail:a,complete:s}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(a),r=this.createCallbackFunction(s);try{navigator.clipboard.writeText(t).then(()=>{n?.({errMsg:"setClipboardData:ok"}),r?.()}).catch(e=>{o?.({errMsg:`setClipboardData:fail ${e.message}`}),r?.()})}catch(l){o?.({errMsg:`setClipboardData:fail ${l.message}`}),r?.()}}getClipboardData(e){const{success:t,fail:i,complete:a}=e,s=this.createCallbackFunction(t),n=this.createCallbackFunction(i),o=this.createCallbackFunction(a);try{navigator.clipboard.readText().then(e=>{s?.({data:e,errMsg:"getClipboardData:ok"}),o?.()}).catch(e=>{n?.({errMsg:`getClipboardData:fail ${e.message}`}),o?.()})}catch(r){n?.({errMsg:`getClipboardData:fail ${r.message}`}),o?.()}}setStorage(e){const{key:t,data:i,success:a,fail:s,complete:n}=e,o=this.createCallbackFunction(a),r=this.createCallbackFunction(s),l=this.createCallbackFunction(n);try{const e=`${this.appId}_${t}`,a="object"==typeof i?JSON.stringify(i):String(i);localStorage.setItem(e,a),o?.({errMsg:"setStorage:ok"})}catch(c){r?.({errMsg:`setStorage:fail ${c.message}`})}finally{l?.()}}getStorage(e){const{key:t,success:i,fail:a,complete:s}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(a),r=this.createCallbackFunction(s);try{const e=`${this.appId}_${t}`,i=localStorage.getItem(e);if(null!==i){let e=i;try{e=JSON.parse(i)}catch{}n?.({data:e,errMsg:"getStorage:ok"})}else o?.({errMsg:"getStorage:fail data not found"})}catch(l){o?.({errMsg:`getStorage:fail ${l.message}`})}finally{r?.()}}removeStorage(e){const{key:t,success:i,fail:a,complete:s}=e,n=this.createCallbackFunction(i),o=this.createCallbackFunction(a),r=this.createCallbackFunction(s);try{const e=`${this.appId}_${t}`;null!==localStorage.getItem(e)?(localStorage.removeItem(e),n?.({errMsg:"removeStorage:ok"})):n?.({errMsg:"removeStorage:ok"})}catch(l){o?.({errMsg:`removeStorage:fail ${l.message}`})}finally{r?.()}}clearStorage(e){const{success:t,fail:i,complete:a}=e||{},s=this.createCallbackFunction(t),n=this.createCallbackFunction(i),o=this.createCallbackFunction(a);try{const e=`${this.appId}_`,t=[];for(let i=0;i<localStorage.length;i++){const a=localStorage.key(i);a.startsWith(e)&&t.push(a)}t.forEach(e=>localStorage.removeItem(e)),s?.({errMsg:"clearStorage:ok"})}catch(r){n?.({errMsg:`clearStorage:fail ${r.message}`})}finally{o?.()}}getStorageInfo(e){const{success:t,fail:i,complete:a}=e||{},s=this.createCallbackFunction(t),n=this.createCallbackFunction(i),o=this.createCallbackFunction(a);try{const e=[];let t=0;const i=10485760,a=`${this.appId}_`;for(let s=0;s<localStorage.length;s++){const i=localStorage.key(s);if(i.startsWith(a)){const s=i.substring(a.length);e.push(s);const n=localStorage.getItem(i);t+=n?2*n.length:0}}s?.({keys:e,currentSize:t,limitSize:i,errMsg:"getStorageInfo:ok"})}catch(r){n?.({errMsg:`getStorageInfo:fail ${r.message}`})}finally{o?.()}}_parseExtEventKey(e){const t=r.getExtModules();for(const i of Object.keys(t)){const t=`${i}_`;if(e.startsWith(t))return{module:i,event:e.slice(t.length)}}return{module:null,event:null}}_handleExtCall(e,t={}){void 0!==t.module?this._extBridgeCall(e,t):t.success?this._extOnBridgeCall(e,t):this._extOffBridgeCall(e)}_extBridgeCall(e,t){const{module:i,data:a={},success:s,fail:n,complete:o}=t,l=this.createCallbackFunction(s),c=this.createCallbackFunction(n),h=this.createCallbackFunction(o),d=r.getExtModule(i);if(!d){const e=`extBridge:fail module "${i}" not registered`;return c?.({errMsg:e}),void h?.()}try{d({event:e,data:a,success:e=>{l?.(e),h?.()},fail:e=>{c?.(e),h?.()}})}catch(p){c?.({errMsg:`extBridge:fail ${p.message}`}),h?.()}}_extOnBridgeCall(e,t){const{success:i}=t,a=this.createCallbackFunction(i),{module:s,event:n}=this._parseExtEventKey(e);if(!s)return;const o=r.getExtModule(s);this._extSubscriptions.get(e)?.();try{const t=o({event:n,data:{isSustain:!0},success:e=>a?.(e),fail:()=>{}});this._extSubscriptions.set(e,t??null)}catch(l){}}_extOffBridgeCall(e){const t=this._extSubscriptions.get(e);t&&(t(),this._extSubscriptions.delete(e))}};export{i as Application,$ as MiniApp};