@lynx-js/web-core-server-canary 0.18.4-canary-20251120-e2c78043 → 0.18.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,194 +4,427 @@ import node_path from "node:path";
4
4
  import node_vm from "node:vm";
5
5
  import node_fs from "node:fs";
6
6
  var __webpack_modules__ = {
7
- "../web-style-transformer/dist/standard.js": function(__webpack_module__, __webpack_exports__, __webpack_require__) {
8
- __webpack_require__.a(__webpack_module__, async function(__webpack_handle_async_dependencies__, __webpack_async_result__) {
9
- try {
10
- __webpack_require__.d(__webpack_exports__, {
11
- H4: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.H4,
12
- RS: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.RS,
13
- aC: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.aC,
14
- bL: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.bL,
15
- f: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.f,
16
- iG: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.iG,
17
- lI: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.lI,
18
- pY: ()=>_standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.pY
19
- });
20
- var _standard_bg_wasm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("../web-style-transformer/dist/standard_bg.wasm");
21
- var _standard_bg_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("../web-style-transformer/dist/standard_bg.js");
22
- var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([
23
- _standard_bg_wasm__WEBPACK_IMPORTED_MODULE_1__
24
- ]);
25
- _standard_bg_wasm__WEBPACK_IMPORTED_MODULE_1__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
26
- (0, _standard_bg_js__WEBPACK_IMPORTED_MODULE_0__.lI)(_standard_bg_wasm__WEBPACK_IMPORTED_MODULE_1__);
27
- _standard_bg_wasm__WEBPACK_IMPORTED_MODULE_1__.__wbindgen_start();
28
- __webpack_async_result__();
29
- } catch (e) {
30
- __webpack_async_result__(e);
31
- }
32
- });
33
- },
34
- "../web-style-transformer/dist/standard_bg.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
7
+ "../web-constants/dist/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
35
8
  __webpack_require__.d(__webpack_exports__, {
36
- H4: ()=>__wbg___wbindgen_throw_b855445ff6a94295,
37
- RS: ()=>__wbg_push_df81a39d04db858c,
38
- aC: ()=>transform_raw_u16_inline_style_ptr,
39
- bL: ()=>__wbindgen_init_externref_table,
40
- f: ()=>__wbg_new_e17d9f43105b08be,
41
- iG: ()=>transform_raw_u16_inline_style_ptr_parsed,
42
- lI: ()=>__wbg_set_wasm,
43
- pY: ()=>__wbindgen_cast_2241b6af4c4b2941
9
+ tf: ()=>LynxCrossThreadContext,
10
+ iH: ()=>callLepusMethodEndpoint,
11
+ Yx: ()=>generateTemplate,
12
+ Fw: ()=>getCustomSectionsEndpoint,
13
+ JA: ()=>lynxDisposedAttribute,
14
+ oZ: ()=>"l-part",
15
+ Ke: ()=>publicComponentEventEndpoint,
16
+ Ve: ()=>updateDataEndpoint,
17
+ $4: ()=>W3cEventNameToLynx,
18
+ mB: ()=>dispatchI18nResourceEndpoint,
19
+ SP: ()=>"l-uid",
20
+ er: ()=>parentComponentUniqueIdAttribute,
21
+ Gq: ()=>lynxTagAttribute,
22
+ im: ()=>LynxEventNameToW3cCommon,
23
+ js: ()=>cssIdAttribute,
24
+ Is: ()=>dispatchJSContextOnMainThreadEndpoint,
25
+ HO: ()=>getCacheI18nResourcesKey,
26
+ jK: ()=>dispatchCoreContextOnBackgroundEndpoint,
27
+ I7: ()=>__lynx_timing_flag,
28
+ vQ: ()=>LynxEventNameToW3cByTagName,
29
+ tl: ()=>lynxComponentConfigAttribute,
30
+ WS: ()=>updateBTSTemplateCacheEndpoint,
31
+ Pb: ()=>lynxEntryNameAttribute,
32
+ c1: ()=>systemInfo,
33
+ y: ()=>lynxElementTemplateMarkerAttribute,
34
+ a$: ()=>BackgroundThreadStartEndpoint,
35
+ F6: ()=>postTimingFlagsEndpoint,
36
+ gI: ()=>I18nResources,
37
+ C6: ()=>"l-dset",
38
+ pP: ()=>componentIdAttribute,
39
+ Gm: ()=>lynxDefaultDisplayLinearAttribute,
40
+ pd: ()=>postExposureEndpoint,
41
+ nk: ()=>queryComponentEndpoint,
42
+ eZ: ()=>switchExposureServiceEndpoint,
43
+ OE: ()=>inShadowRootStyles,
44
+ JW: ()=>publishEventEndpoint
44
45
  });
45
- let wasm;
46
- function __wbg_set_wasm(val) {
47
- wasm = val;
48
- }
49
- let cachedUint8ArrayMemory0 = null;
50
- function getUint8ArrayMemory0() {
51
- if (null === cachedUint8ArrayMemory0 || 0 === cachedUint8ArrayMemory0.byteLength) cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
52
- return cachedUint8ArrayMemory0;
46
+ const cssIdAttribute = 'l-css-id';
47
+ const componentIdAttribute = 'l-comp-id';
48
+ const parentComponentUniqueIdAttribute = 'l-p-comp-uid';
49
+ const lynxEntryNameAttribute = 'l-e-name';
50
+ const lynxTagAttribute = 'lynx-tag';
51
+ const lynxComponentConfigAttribute = 'l-comp-cfg';
52
+ const lynxDisposedAttribute = 'l-disposed';
53
+ const lynxElementTemplateMarkerAttribute = 'l-template';
54
+ const lynxDefaultDisplayLinearAttribute = 'lynx-default-display-linear';
55
+ const __lynx_timing_flag = '__lynx_timing_flag';
56
+ const systemInfo = {
57
+ platform: 'web',
58
+ lynxSdkVersion: '3.0'
59
+ };
60
+ const inShadowRootStyles = [
61
+ ` [lynx-default-display-linear="false"] * {
62
+ --lynx-display: flex;
63
+ --lynx-display-toggle: var(--lynx-display-flex);
64
+ }`,
65
+ `[lynx-default-overflow-visible="true"] x-view{
66
+ overflow: visible;
67
+ }`
68
+ ];
69
+ const W3cEventNameToLynx = {
70
+ click: 'tap',
71
+ lynxscroll: 'scroll',
72
+ lynxscrollend: 'scrollend',
73
+ overlaytouch: 'touch',
74
+ lynxfocus: 'focus',
75
+ lynxblur: 'blur',
76
+ lynxinput: 'input'
77
+ };
78
+ const LynxEventNameToW3cByTagName = {
79
+ 'X-INPUT': {
80
+ blur: 'lynxblur',
81
+ focus: 'lynxfocus',
82
+ input: 'lynxinput'
83
+ },
84
+ 'X-TEXTAREA': {
85
+ blur: 'lynxblur',
86
+ focus: 'lynxfocus',
87
+ input: 'lynxinput'
88
+ }
89
+ };
90
+ const LynxEventNameToW3cCommon = {
91
+ tap: 'click',
92
+ scroll: 'lynxscroll',
93
+ scrollend: 'lynxscrollend',
94
+ touch: 'overlaytouch'
95
+ };
96
+ var dist = __webpack_require__("../web-worker-rpc/dist/index.js");
97
+ const postExposureEndpoint = (0, dist.H)('__postExposure', false, false);
98
+ const publicComponentEventEndpoint = (0, dist.H)('publicComponentEvent', false, false);
99
+ const publishEventEndpoint = (0, dist.H)('publishEvent', false, false);
100
+ (0, dist.H)('postOffscreenEventEndpoint', false, false);
101
+ const switchExposureServiceEndpoint = (0, dist.H)('switchExposureServiceEndpoint', false, false);
102
+ (0, dist.H)('mainThreadStart', false, false);
103
+ const updateDataEndpoint = (0, dist.H)('updateData', false, true);
104
+ (0, dist.H)('sendGlobalEventEndpoint', false, false);
105
+ (0, dist.H)('dispose', false, true);
106
+ const BackgroundThreadStartEndpoint = (0, dist.H)('start', false, true);
107
+ (0, dist.H)('reportError', false, false);
108
+ (0, dist.H)('flushElementTree', false, true);
109
+ const callLepusMethodEndpoint = (0, dist.H)('callLepusMethod', false, true);
110
+ (0, dist.H)('multiThreadExposureChangedEndpoint', false, false);
111
+ (0, dist.H)('__invokeUIMethod', false, true);
112
+ (0, dist.H)('__setNativeProps', false, true);
113
+ (0, dist.H)('__getPathInfo', false, true);
114
+ (0, dist.H)('nativeModulesCall', false, true);
115
+ (0, dist.H)('napiModulesCall', false, true, true);
116
+ const getCustomSectionsEndpoint = (0, dist.H)('getCustomSections', false, true);
117
+ (0, dist.H)('markTiming', false, false);
118
+ const postTimingFlagsEndpoint = (0, dist.H)('postTimingFlags', false, false);
119
+ (0, dist.H)('__triggerComponentEvent', false, false);
120
+ (0, dist.H)('__selectComponent', false, true);
121
+ (0, dist.H)('dispatchLynxViewEvent', false, false);
122
+ (0, dist.H)('dispatchNapiModule', false, false);
123
+ const dispatchCoreContextOnBackgroundEndpoint = (0, dist.H)('dispatchCoreContextOnBackground', false, false);
124
+ const dispatchJSContextOnMainThreadEndpoint = (0, dist.H)('dispatchJSContextOnMainThread', false, false);
125
+ (0, dist.H)('__triggerElementMethod', false, false);
126
+ (0, dist.H)('updateGlobalProps', false, false);
127
+ (0, dist.H)('updateI18nResources', false, false);
128
+ (0, dist.H)('updateI18nResource', false, false);
129
+ const dispatchI18nResourceEndpoint = (0, dist.H)('dispatchI18nResource', false, false);
130
+ const queryComponentEndpoint = (0, dist.H)('queryComponent', false, true);
131
+ const updateBTSTemplateCacheEndpoint = (0, dist.H)('updateBTSTemplateCacheEndpoint', false, true);
132
+ (0, dist.H)('loadTemplateMultiThread', false, true);
133
+ var NativeApp_IdentifierType;
134
+ (function(IdentifierType) {
135
+ IdentifierType[IdentifierType["ID_SELECTOR"] = 0] = "ID_SELECTOR";
136
+ IdentifierType[IdentifierType["REF_ID"] = 1] = "REF_ID";
137
+ IdentifierType[IdentifierType["UNIQUE_ID"] = 2] = "UNIQUE_ID";
138
+ })(NativeApp_IdentifierType || (NativeApp_IdentifierType = {}));
139
+ var NativeApp_ErrorCode;
140
+ (function(ErrorCode) {
141
+ ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS";
142
+ ErrorCode[ErrorCode["UNKNOWN"] = 1] = "UNKNOWN";
143
+ ErrorCode[ErrorCode["NODE_NOT_FOUND"] = 2] = "NODE_NOT_FOUND";
144
+ ErrorCode[ErrorCode["METHOD_NOT_FOUND"] = 3] = "METHOD_NOT_FOUND";
145
+ ErrorCode[ErrorCode["PARAM_INVALID"] = 4] = "PARAM_INVALID";
146
+ ErrorCode[ErrorCode["SELECTOR_NOT_SUPPORTED"] = 5] = "SELECTOR_NOT_SUPPORTED";
147
+ ErrorCode[ErrorCode["NO_UI_FOR_NODE"] = 6] = "NO_UI_FOR_NODE";
148
+ })(NativeApp_ErrorCode || (NativeApp_ErrorCode = {}));
149
+ var UpdateDataOptions_NativeUpdateDataType;
150
+ (function(NativeUpdateDataType) {
151
+ NativeUpdateDataType[NativeUpdateDataType["UPDATE"] = 0] = "UPDATE";
152
+ NativeUpdateDataType[NativeUpdateDataType["RESET"] = 1] = "RESET";
153
+ })(UpdateDataOptions_NativeUpdateDataType || (UpdateDataOptions_NativeUpdateDataType = {}));
154
+ const DispatchEventResult = {
155
+ NotCanceled: 0,
156
+ CanceledByEventHandler: 1,
157
+ CanceledByDefaultEventHandler: 2,
158
+ CanceledBeforeDispatch: 3
159
+ };
160
+ var Element_AnimationOperation;
161
+ (function(AnimationOperation) {
162
+ AnimationOperation[AnimationOperation["START"] = 0] = "START";
163
+ AnimationOperation[AnimationOperation["PLAY"] = 1] = "PLAY";
164
+ AnimationOperation[AnimationOperation["PAUSE"] = 2] = "PAUSE";
165
+ AnimationOperation[AnimationOperation["CANCEL"] = 3] = "CANCEL";
166
+ AnimationOperation[AnimationOperation["FINISH"] = 4] = "FINISH";
167
+ })(Element_AnimationOperation || (Element_AnimationOperation = {}));
168
+ const getCacheI18nResourcesKey = (options)=>`${options.locale}_${options.channel}_${options.fallback_url}`;
169
+ class I18nResources {
170
+ data;
171
+ constructor(data){
172
+ this.data = data;
173
+ }
174
+ setData(data) {
175
+ this.data = data;
176
+ }
53
177
  }
54
- let cachedTextDecoder = new TextDecoder('utf-8', {
55
- ignoreBOM: true,
56
- fatal: true
57
- });
58
- cachedTextDecoder.decode();
59
- const MAX_SAFARI_DECODE_BYTES = 2146435072;
60
- let numBytesDecoded = 0;
61
- function decodeText(ptr, len) {
62
- numBytesDecoded += len;
63
- if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
64
- cachedTextDecoder = new TextDecoder('utf-8', {
65
- ignoreBOM: true,
66
- fatal: true
178
+ class LynxCrossThreadContext extends EventTarget {
179
+ _config;
180
+ constructor(_config){
181
+ super();
182
+ this._config = _config;
183
+ }
184
+ postMessage(...args) {
185
+ console.error('[lynx-web] postMessage not implemented, args:', ...args);
186
+ }
187
+ dispatchEvent(event) {
188
+ const { rpc, sendEventEndpoint } = this._config;
189
+ rpc.invoke(sendEventEndpoint, [
190
+ event
191
+ ]);
192
+ return DispatchEventResult.CanceledBeforeDispatch;
193
+ }
194
+ __start() {
195
+ const { rpc, receiveEventEndpoint } = this._config;
196
+ rpc.registerHandler(receiveEventEndpoint, ({ type, data })=>{
197
+ super.dispatchEvent(new MessageEvent(type, {
198
+ data: data ?? {}
199
+ }));
67
200
  });
68
- cachedTextDecoder.decode();
69
- numBytesDecoded = len;
70
201
  }
71
- return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
72
202
  }
73
- function getStringFromWasm0(ptr, len) {
74
- ptr >>>= 0;
75
- return decodeText(ptr, len);
203
+ const currentSupportedTemplateVersion = 2;
204
+ const globalDisallowedVars = [
205
+ 'navigator',
206
+ 'postMessage',
207
+ 'window'
208
+ ];
209
+ const templateUpgraders = [
210
+ (template)=>{
211
+ template.appType = template.appType ?? (template.lepusCode.root.startsWith('(function (globDynamicComponentEntry') ? 'lazy' : 'card');
212
+ template.version = 2;
213
+ template.lepusCode = Object.fromEntries(Object.entries(template.lepusCode).filter(([_, content])=>'string' == typeof content));
214
+ return template;
215
+ }
216
+ ];
217
+ const generateModuleContent = (fileName, content, eager, appType)=>[
218
+ eager ? '//# allFunctionsCalledOnLoad' : '',
219
+ '\n(function() { "use strict"; const ',
220
+ globalDisallowedVars.join('=void 0,'),
221
+ '=void 0;\n',
222
+ 'card' !== appType ? 'module.exports=\n' : '',
223
+ content,
224
+ '\n})()',
225
+ '\n//# sourceURL=',
226
+ fileName
227
+ ].join('');
228
+ async function generateJavascriptUrl(obj, createJsModuleUrl, eager, appType, templateName) {
229
+ return Promise.all(Object.entries(obj).filter(([_, content])=>'string' == typeof content).map(async ([name, content])=>[
230
+ name,
231
+ await createJsModuleUrl(generateModuleContent(`${templateName}/${name.replaceAll('/', '_')}.js`, content, eager, appType), `${templateName}-${name.replaceAll('/', '_')}.js`)
232
+ ])).then(Object.fromEntries);
76
233
  }
77
- let WASM_VECTOR_LEN = 0;
78
- const cachedTextEncoder = new TextEncoder();
79
- if (!('encodeInto' in cachedTextEncoder)) cachedTextEncoder.encodeInto = function(arg, view) {
80
- const buf = cachedTextEncoder.encode(arg);
81
- view.set(buf);
234
+ async function generateTemplate(template, createJsModuleUrl, templateName) {
235
+ template.version = template.version ?? 1;
236
+ if (template.version > currentSupportedTemplateVersion) throw new Error("Unsupported template, please upgrade your web-platform dependencies");
237
+ let upgrader;
238
+ while(template.version < currentSupportedTemplateVersion && (upgrader = templateUpgraders[template.version - 1]))template = upgrader(template);
82
239
  return {
83
- read: arg.length,
84
- written: buf.length
240
+ ...template,
241
+ lepusCode: await generateJavascriptUrl(template.lepusCode, createJsModuleUrl, true, template.appType, templateName)
85
242
  };
86
- };
87
- function passStringToWasm0(arg, malloc, realloc) {
88
- if (void 0 === realloc) {
89
- const buf = cachedTextEncoder.encode(arg);
90
- const ptr = malloc(buf.length, 1) >>> 0;
91
- getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
92
- WASM_VECTOR_LEN = buf.length;
93
- return ptr;
243
+ }
244
+ },
245
+ "../web-worker-rpc/dist/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
246
+ __webpack_require__.d(__webpack_exports__, {
247
+ C: ()=>Rpc,
248
+ H: ()=>createRpcEndpoint
249
+ });
250
+ class Rpc {
251
+ port;
252
+ name;
253
+ incId = 0;
254
+ #messageCache = {};
255
+ #textEncoder = new TextEncoder();
256
+ #textDecoder = new TextDecoder();
257
+ #handlerMap = new Map();
258
+ constructor(port, name){
259
+ this.port = port;
260
+ this.name = name;
261
+ port.onmessage = (ev)=>this.#onMessage(ev.data);
94
262
  }
95
- let len = arg.length;
96
- let ptr = malloc(len, 1) >>> 0;
97
- const mem = getUint8ArrayMemory0();
98
- let offset = 0;
99
- for(; offset < len; offset++){
100
- const code = arg.charCodeAt(offset);
101
- if (code > 0x7F) break;
102
- mem[ptr + offset] = code;
263
+ get nextRetId() {
264
+ return `ret_${this.name}_${this.incId++}`;
103
265
  }
104
- if (offset !== len) {
105
- if (0 !== offset) arg = arg.slice(offset);
106
- ptr = realloc(ptr, len, len = offset + 3 * arg.length, 1) >>> 0;
107
- const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
108
- const ret = cachedTextEncoder.encodeInto(arg, view);
109
- offset += ret.written;
110
- ptr = realloc(ptr, len, offset, 1) >>> 0;
266
+ static createRetEndpoint(retId) {
267
+ return {
268
+ name: retId,
269
+ hasReturn: false,
270
+ isSync: false
271
+ };
111
272
  }
112
- WASM_VECTOR_LEN = offset;
113
- return ptr;
114
- }
115
- function transform_raw_u16_inline_style_ptr(str) {
116
- const ptr0 = passStringToWasm0(str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
117
- const len0 = WASM_VECTOR_LEN;
118
- const ret = wasm.transform_raw_u16_inline_style_ptr(ptr0, len0);
119
- let v2;
120
- if (0 !== ret[0]) {
121
- v2 = getStringFromWasm0(ret[0], ret[1]).slice();
122
- wasm.__wbindgen_free(ret[0], +ret[1], 1);
273
+ #onMessage = async (message)=>{
274
+ const handler = this.#handlerMap.get(message.name);
275
+ if (handler) {
276
+ const lockViewer = message.sync ? new Int32Array(message.lock) : void 0;
277
+ const replyTempEndpoint = !message.sync && message.retId ? Rpc.createRetEndpoint(message.retId) : void 0;
278
+ try {
279
+ const result = await handler(...message.data);
280
+ let retData, transfer = [];
281
+ if (message.sync) retData = result;
282
+ else if (message.hasTransfer) ({ data: retData, transfer } = result || {});
283
+ else retData = result;
284
+ if (message.sync) {
285
+ if (message.buf) {
286
+ const retStr = JSON.stringify(retData);
287
+ const lengthViewer = new Uint32Array(message.buf, 0, 1);
288
+ const bufViewer = new Uint8Array(message.buf, 4);
289
+ const retCache = new Uint8Array(message.buf.byteLength - 4);
290
+ const { written: byteLength } = this.#textEncoder.encodeInto(retStr, retCache);
291
+ lengthViewer[0] = byteLength;
292
+ bufViewer.set(retCache, 0);
293
+ }
294
+ Atomics.store(lockViewer, 0, 1);
295
+ Atomics.notify(lockViewer, 0);
296
+ } else if (message.retId) this.invoke(replyTempEndpoint, [
297
+ retData,
298
+ false
299
+ ], transfer || []);
300
+ } catch (e) {
301
+ console.error(e);
302
+ if (message.sync) {
303
+ Atomics.store(lockViewer, 0, 2);
304
+ Atomics.notify(lockViewer, 0);
305
+ lockViewer[1] = 2;
306
+ } else this.invoke(replyTempEndpoint, [
307
+ void 0,
308
+ true
309
+ ]);
310
+ }
311
+ } else {
312
+ const cache = this.#messageCache[message.name];
313
+ if (cache) cache.push(message);
314
+ else this.#messageCache[message.name] = [
315
+ message
316
+ ];
317
+ }
318
+ };
319
+ createCall(endpoint) {
320
+ return (...args)=>this.invoke(endpoint, args);
123
321
  }
124
- return v2;
125
- }
126
- function transform_raw_u16_inline_style_ptr_parsed(name, value) {
127
- const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
128
- const len0 = WASM_VECTOR_LEN;
129
- const ptr1 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
130
- const len1 = WASM_VECTOR_LEN;
131
- const ret = wasm.transform_raw_u16_inline_style_ptr_parsed(ptr0, len0, ptr1, len1);
132
- return ret;
133
- }
134
- function __wbg___wbindgen_throw_b855445ff6a94295(arg0, arg1) {
135
- throw new Error(getStringFromWasm0(arg0, arg1));
136
- }
137
- function __wbg_new_e17d9f43105b08be() {
138
- const ret = new Array();
139
- return ret;
140
- }
141
- function __wbg_push_df81a39d04db858c(arg0, arg1) {
142
- const ret = arg0.push(arg1);
143
- return ret;
144
- }
145
- function __wbindgen_cast_2241b6af4c4b2941(arg0, arg1) {
146
- const ret = getStringFromWasm0(arg0, arg1);
147
- return ret;
148
- }
149
- function __wbindgen_init_externref_table() {
150
- const table = wasm.__wbindgen_externrefs;
151
- const offset = table.grow(4);
152
- table.set(0, void 0);
153
- table.set(offset + 0, void 0);
154
- table.set(offset + 1, null);
155
- table.set(offset + 2, true);
156
- table.set(offset + 3, false);
157
- }
158
- },
159
- "../web-style-transformer/standard.js": function(__webpack_module__, __webpack_exports__, __webpack_require__) {
160
- __webpack_require__.a(__webpack_module__, async function(__webpack_handle_async_dependencies__, __webpack_async_result__) {
161
- try {
162
- __webpack_require__.r(__webpack_exports__);
163
- __webpack_require__.d(__webpack_exports__, {
164
- __wbg___wbindgen_throw_b855445ff6a94295: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.H4,
165
- __wbg_new_e17d9f43105b08be: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.f,
166
- __wbg_push_df81a39d04db858c: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.RS,
167
- __wbg_set_wasm: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.lI,
168
- __wbindgen_cast_2241b6af4c4b2941: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.pY,
169
- __wbindgen_init_externref_table: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.bL,
170
- transform_raw_u16_inline_style_ptr: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.aC,
171
- transform_raw_u16_inline_style_ptr_parsed: ()=>_dist_standard_js__WEBPACK_IMPORTED_MODULE_0__.iG
172
- });
173
- var _dist_standard_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("../web-style-transformer/dist/standard.js");
174
- var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([
175
- _dist_standard_js__WEBPACK_IMPORTED_MODULE_0__
176
- ]);
177
- _dist_standard_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
178
- __webpack_async_result__();
179
- } catch (e) {
180
- __webpack_async_result__(e);
322
+ registerHandler(endpoint, handler) {
323
+ this.#handlerMap.set(endpoint.name, handler);
324
+ const currentCache = this.#messageCache[endpoint.name];
325
+ if (currentCache?.length) {
326
+ this.#messageCache[endpoint.name] = void 0;
327
+ for (const message of currentCache)this.#onMessage(message);
328
+ }
181
329
  }
182
- });
183
- },
184
- "../web-style-transformer/dist/standard_bg.wasm": function(module, exports, __webpack_require__) {
185
- var WEBPACK_IMPORTED_MODULE_0 = __webpack_require__("../web-style-transformer/dist/standard_bg.js");
186
- module.exports = __webpack_require__.v(exports, module.id, "75dda3584a4e8253", {
187
- "./standard_bg.js": {
188
- __wbg_new_e17d9f43105b08be: WEBPACK_IMPORTED_MODULE_0.f,
189
- __wbg_push_df81a39d04db858c: WEBPACK_IMPORTED_MODULE_0.RS,
190
- __wbg___wbindgen_throw_b855445ff6a94295: WEBPACK_IMPORTED_MODULE_0.H4,
191
- __wbindgen_init_externref_table: WEBPACK_IMPORTED_MODULE_0.bL,
192
- __wbindgen_cast_2241b6af4c4b2941: WEBPACK_IMPORTED_MODULE_0.pY
330
+ registerHandlerRef(endpoint, target, propertyName) {
331
+ this.registerHandler(endpoint, (...args)=>target[propertyName]?.call(target, ...args));
193
332
  }
194
- });
333
+ registerHandlerLazy(endpoint, target, propertyName) {
334
+ if (target[propertyName]) this.registerHandlerRef(endpoint, target, propertyName);
335
+ else {
336
+ let property;
337
+ const rpc = this;
338
+ Object.defineProperty(target, propertyName, {
339
+ get () {
340
+ return property;
341
+ },
342
+ set (v) {
343
+ property = v;
344
+ if (v) rpc.registerHandlerRef(endpoint, target, propertyName);
345
+ }
346
+ });
347
+ }
348
+ }
349
+ removeHandler(rpc) {
350
+ this.#handlerMap.delete(rpc.name);
351
+ }
352
+ invoke(endpoint, parameters, transfer = []) {
353
+ if (endpoint.isSync) {
354
+ const sharedBuffer = endpoint.bufferSize ? new SharedArrayBuffer(endpoint.bufferSize + 4) : void 0;
355
+ const lock = new SharedArrayBuffer(4);
356
+ const lockViewer = new Int32Array(lock);
357
+ lockViewer[0] = 0;
358
+ const message = {
359
+ name: endpoint.name,
360
+ data: parameters,
361
+ sync: true,
362
+ lock: lock,
363
+ buf: sharedBuffer
364
+ };
365
+ this.port.postMessage(message, {
366
+ transfer
367
+ });
368
+ Atomics.wait(lockViewer, 0, 0);
369
+ if (2 === lockViewer[0]) throw null;
370
+ if (!sharedBuffer) return;
371
+ {
372
+ const byteLength = new Uint32Array(sharedBuffer, 0, 4)[0];
373
+ const sharedBufferView = new Uint8Array(sharedBuffer, 4, byteLength);
374
+ const localBuf = new Uint8Array(byteLength);
375
+ localBuf.set(sharedBufferView, 0);
376
+ const ret = localBuf ? JSON.parse(this.#textDecoder.decode(localBuf)) : void 0;
377
+ return ret;
378
+ }
379
+ }
380
+ if (endpoint.hasReturn) {
381
+ const { promise, resolve, reject } = Promise.withResolvers();
382
+ const retHandler = Rpc.createRetEndpoint(this.nextRetId);
383
+ this.registerHandler(retHandler, (returnValue, error)=>{
384
+ if (error) reject();
385
+ resolve(returnValue);
386
+ });
387
+ const message = {
388
+ name: endpoint.name,
389
+ data: parameters,
390
+ sync: false,
391
+ retId: retHandler?.name,
392
+ hasTransfer: endpoint.hasReturnTransfer
393
+ };
394
+ this.port.postMessage(message, {
395
+ transfer
396
+ });
397
+ return promise;
398
+ }
399
+ {
400
+ const message = {
401
+ name: endpoint.name,
402
+ data: parameters,
403
+ sync: false
404
+ };
405
+ this.port.postMessage(message, {
406
+ transfer
407
+ });
408
+ }
409
+ }
410
+ createCallbackify(endpoint, callbackAt) {
411
+ const call = this.createCall(endpoint);
412
+ return (...params)=>{
413
+ const callback = params.at(callbackAt);
414
+ params.splice(callbackAt, 1);
415
+ call(...params).then(callback);
416
+ };
417
+ }
418
+ }
419
+ function createRpcEndpoint(name, isSync, hasReturn = true, hasReturnTransfer = false, bufferSize) {
420
+ return {
421
+ name,
422
+ isSync,
423
+ hasReturn,
424
+ hasReturnTransfer,
425
+ bufferSize
426
+ };
427
+ }
195
428
  }
196
429
  };
197
430
  var __webpack_module_cache__ = {};
@@ -312,7 +545,10 @@ __webpack_require__.m = __webpack_modules__;
312
545
  }, []));
313
546
  })();
314
547
  (()=>{
315
- __webpack_require__.u = (chunkId)=>"legacy-wasm-chunk.js";
548
+ __webpack_require__.k = (chunkId)=>"" + chunkId + ".css";
549
+ })();
550
+ (()=>{
551
+ __webpack_require__.u = (chunkId)=>"" + ("8" === chunkId ? "legacy-wasm-chunk" : chunkId) + ".js";
316
552
  })();
317
553
  (()=>{
318
554
  __webpack_require__.g = (()=>{
@@ -404,1756 +640,12 @@ __webpack_require__.m = __webpack_modules__;
404
640
  }
405
641
  };
406
642
  })();
407
- const cssIdAttribute = 'l-css-id';
408
- const componentIdAttribute = 'l-comp-id';
409
- const parentComponentUniqueIdAttribute = 'l-p-comp-uid';
410
- const lynxEntryNameAttribute = 'l-e-name';
411
- const lynxTagAttribute = 'lynx-tag';
412
- const lynxComponentConfigAttribute = 'l-comp-cfg';
413
- const lynxDisposedAttribute = 'l-disposed';
414
- const lynxElementTemplateMarkerAttribute = 'l-template';
415
- const lynxDefaultDisplayLinearAttribute = 'lynx-default-display-linear';
416
- const __lynx_timing_flag = '__lynx_timing_flag';
417
- const systemInfo = {
418
- platform: 'web',
419
- lynxSdkVersion: '3.0'
420
- };
421
- const inShadowRootStyles = [
422
- ` [lynx-default-display-linear="false"] * {
423
- --lynx-display: flex;
424
- --lynx-display-toggle: var(--lynx-display-flex);
425
- }`,
426
- `[lynx-default-overflow-visible="true"] x-view{
427
- overflow: visible;
428
- }`
429
- ];
430
- const W3cEventNameToLynx = {
431
- click: 'tap',
432
- lynxscroll: 'scroll',
433
- lynxscrollend: 'scrollend',
434
- overlaytouch: 'touch',
435
- lynxfocus: 'focus',
436
- lynxblur: 'blur',
437
- lynxinput: 'input'
438
- };
439
- const LynxEventNameToW3cByTagName = {
440
- 'X-INPUT': {
441
- blur: 'lynxblur',
442
- focus: 'lynxfocus',
443
- input: 'lynxinput'
444
- },
445
- 'X-TEXTAREA': {
446
- blur: 'lynxblur',
447
- focus: 'lynxfocus',
448
- input: 'lynxinput'
449
- }
450
- };
451
- const LynxEventNameToW3cCommon = {
452
- tap: 'click',
453
- scroll: 'lynxscroll',
454
- scrollend: 'lynxscrollend',
455
- touch: 'overlaytouch'
456
- };
457
- class Rpc {
458
- port;
459
- name;
460
- incId = 0;
461
- #messageCache = {};
462
- #textEncoder = new TextEncoder();
463
- #textDecoder = new TextDecoder();
464
- #handlerMap = new Map();
465
- constructor(port, name){
466
- this.port = port;
467
- this.name = name;
468
- port.onmessage = (ev)=>this.#onMessage(ev.data);
469
- }
470
- get nextRetId() {
471
- return `ret_${this.name}_${this.incId++}`;
472
- }
473
- static createRetEndpoint(retId) {
474
- return {
475
- name: retId,
476
- hasReturn: false,
477
- isSync: false
478
- };
479
- }
480
- #onMessage = async (message)=>{
481
- const handler = this.#handlerMap.get(message.name);
482
- if (handler) {
483
- const lockViewer = message.sync ? new Int32Array(message.lock) : void 0;
484
- const replyTempEndpoint = !message.sync && message.retId ? Rpc.createRetEndpoint(message.retId) : void 0;
485
- try {
486
- const result = await handler(...message.data);
487
- let retData, transfer = [];
488
- if (message.sync) retData = result;
489
- else if (message.hasTransfer) ({ data: retData, transfer } = result || {});
490
- else retData = result;
491
- if (message.sync) {
492
- if (message.buf) {
493
- const retStr = JSON.stringify(retData);
494
- const lengthViewer = new Uint32Array(message.buf, 0, 1);
495
- const bufViewer = new Uint8Array(message.buf, 4);
496
- const retCache = new Uint8Array(message.buf.byteLength - 4);
497
- const { written: byteLength } = this.#textEncoder.encodeInto(retStr, retCache);
498
- lengthViewer[0] = byteLength;
499
- bufViewer.set(retCache, 0);
500
- }
501
- Atomics.store(lockViewer, 0, 1);
502
- Atomics.notify(lockViewer, 0);
503
- } else if (message.retId) this.invoke(replyTempEndpoint, [
504
- retData,
505
- false
506
- ], transfer || []);
507
- } catch (e) {
508
- console.error(e);
509
- if (message.sync) {
510
- Atomics.store(lockViewer, 0, 2);
511
- Atomics.notify(lockViewer, 0);
512
- lockViewer[1] = 2;
513
- } else this.invoke(replyTempEndpoint, [
514
- void 0,
515
- true
516
- ]);
517
- }
518
- } else {
519
- const cache = this.#messageCache[message.name];
520
- if (cache) cache.push(message);
521
- else this.#messageCache[message.name] = [
522
- message
523
- ];
524
- }
525
- };
526
- createCall(endpoint) {
527
- return (...args)=>this.invoke(endpoint, args);
528
- }
529
- registerHandler(endpoint, handler) {
530
- this.#handlerMap.set(endpoint.name, handler);
531
- const currentCache = this.#messageCache[endpoint.name];
532
- if (currentCache?.length) {
533
- this.#messageCache[endpoint.name] = void 0;
534
- for (const message of currentCache)this.#onMessage(message);
535
- }
536
- }
537
- registerHandlerRef(endpoint, target, propertyName) {
538
- this.registerHandler(endpoint, (...args)=>target[propertyName]?.call(target, ...args));
539
- }
540
- registerHandlerLazy(endpoint, target, propertyName) {
541
- if (target[propertyName]) this.registerHandlerRef(endpoint, target, propertyName);
542
- else {
543
- let property;
544
- const rpc = this;
545
- Object.defineProperty(target, propertyName, {
546
- get () {
547
- return property;
548
- },
549
- set (v) {
550
- property = v;
551
- if (v) rpc.registerHandlerRef(endpoint, target, propertyName);
552
- }
553
- });
554
- }
555
- }
556
- removeHandler(rpc) {
557
- this.#handlerMap.delete(rpc.name);
558
- }
559
- invoke(endpoint, parameters, transfer = []) {
560
- if (endpoint.isSync) {
561
- const sharedBuffer = endpoint.bufferSize ? new SharedArrayBuffer(endpoint.bufferSize + 4) : void 0;
562
- const lock = new SharedArrayBuffer(4);
563
- const lockViewer = new Int32Array(lock);
564
- lockViewer[0] = 0;
565
- const message = {
566
- name: endpoint.name,
567
- data: parameters,
568
- sync: true,
569
- lock: lock,
570
- buf: sharedBuffer
571
- };
572
- this.port.postMessage(message, {
573
- transfer
574
- });
575
- Atomics.wait(lockViewer, 0, 0);
576
- if (2 === lockViewer[0]) throw null;
577
- if (!sharedBuffer) return;
578
- {
579
- const byteLength = new Uint32Array(sharedBuffer, 0, 4)[0];
580
- const sharedBufferView = new Uint8Array(sharedBuffer, 4, byteLength);
581
- const localBuf = new Uint8Array(byteLength);
582
- localBuf.set(sharedBufferView, 0);
583
- const ret = localBuf ? JSON.parse(this.#textDecoder.decode(localBuf)) : void 0;
584
- return ret;
585
- }
586
- }
587
- if (endpoint.hasReturn) {
588
- const { promise, resolve, reject } = Promise.withResolvers();
589
- const retHandler = Rpc.createRetEndpoint(this.nextRetId);
590
- this.registerHandler(retHandler, (returnValue, error)=>{
591
- if (error) reject();
592
- resolve(returnValue);
593
- });
594
- const message = {
595
- name: endpoint.name,
596
- data: parameters,
597
- sync: false,
598
- retId: retHandler?.name,
599
- hasTransfer: endpoint.hasReturnTransfer
600
- };
601
- this.port.postMessage(message, {
602
- transfer
603
- });
604
- return promise;
605
- }
606
- {
607
- const message = {
608
- name: endpoint.name,
609
- data: parameters,
610
- sync: false
611
- };
612
- this.port.postMessage(message, {
613
- transfer
614
- });
615
- }
616
- }
617
- createCallbackify(endpoint, callbackAt) {
618
- const call = this.createCall(endpoint);
619
- return (...params)=>{
620
- const callback = params.at(callbackAt);
621
- params.splice(callbackAt, 1);
622
- call(...params).then(callback);
623
- };
624
- }
625
- }
626
- function createRpcEndpoint(name, isSync, hasReturn = true, hasReturnTransfer = false, bufferSize) {
627
- return {
628
- name,
629
- isSync,
630
- hasReturn,
631
- hasReturnTransfer,
632
- bufferSize
633
- };
634
- }
635
- const postExposureEndpoint = createRpcEndpoint('__postExposure', false, false);
636
- const publicComponentEventEndpoint = createRpcEndpoint('publicComponentEvent', false, false);
637
- const publishEventEndpoint = createRpcEndpoint('publishEvent', false, false);
638
- createRpcEndpoint('postOffscreenEventEndpoint', false, false);
639
- const switchExposureServiceEndpoint = createRpcEndpoint('switchExposureServiceEndpoint', false, false);
640
- createRpcEndpoint('mainThreadStart', false, false);
641
- const updateDataEndpoint = createRpcEndpoint('updateData', false, true);
642
- createRpcEndpoint('sendGlobalEventEndpoint', false, false);
643
- createRpcEndpoint('dispose', false, true);
644
- const BackgroundThreadStartEndpoint = createRpcEndpoint('start', false, true);
645
- createRpcEndpoint('reportError', false, false);
646
- createRpcEndpoint('flushElementTree', false, true);
647
- const callLepusMethodEndpoint = createRpcEndpoint('callLepusMethod', false, true);
648
- createRpcEndpoint('multiThreadExposureChangedEndpoint', false, false);
649
- createRpcEndpoint('__invokeUIMethod', false, true);
650
- createRpcEndpoint('__setNativeProps', false, true);
651
- createRpcEndpoint('__getPathInfo', false, true);
652
- createRpcEndpoint('nativeModulesCall', false, true);
653
- createRpcEndpoint('napiModulesCall', false, true, true);
654
- const getCustomSectionsEndpoint = createRpcEndpoint('getCustomSections', false, true);
655
- createRpcEndpoint('markTiming', false, false);
656
- const postTimingFlagsEndpoint = createRpcEndpoint('postTimingFlags', false, false);
657
- createRpcEndpoint('__triggerComponentEvent', false, false);
658
- createRpcEndpoint('__selectComponent', false, true);
659
- createRpcEndpoint('dispatchLynxViewEvent', false, false);
660
- createRpcEndpoint('dispatchNapiModule', false, false);
661
- const dispatchCoreContextOnBackgroundEndpoint = createRpcEndpoint('dispatchCoreContextOnBackground', false, false);
662
- const dispatchJSContextOnMainThreadEndpoint = createRpcEndpoint('dispatchJSContextOnMainThread', false, false);
663
- createRpcEndpoint('__triggerElementMethod', false, false);
664
- createRpcEndpoint('updateGlobalProps', false, false);
665
- createRpcEndpoint('updateI18nResources', false, false);
666
- createRpcEndpoint('updateI18nResource', false, false);
667
- const dispatchI18nResourceEndpoint = createRpcEndpoint('dispatchI18nResource', false, false);
668
- const queryComponentEndpoint = createRpcEndpoint('queryComponent', false, true);
669
- const updateBTSTemplateCacheEndpoint = createRpcEndpoint('updateBTSTemplateCacheEndpoint', false, true);
670
- createRpcEndpoint('loadTemplateMultiThread', false, true);
671
- var NativeApp_IdentifierType;
672
- (function(IdentifierType) {
673
- IdentifierType[IdentifierType["ID_SELECTOR"] = 0] = "ID_SELECTOR";
674
- IdentifierType[IdentifierType["REF_ID"] = 1] = "REF_ID";
675
- IdentifierType[IdentifierType["UNIQUE_ID"] = 2] = "UNIQUE_ID";
676
- })(NativeApp_IdentifierType || (NativeApp_IdentifierType = {}));
677
- var NativeApp_ErrorCode;
678
- (function(ErrorCode) {
679
- ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS";
680
- ErrorCode[ErrorCode["UNKNOWN"] = 1] = "UNKNOWN";
681
- ErrorCode[ErrorCode["NODE_NOT_FOUND"] = 2] = "NODE_NOT_FOUND";
682
- ErrorCode[ErrorCode["METHOD_NOT_FOUND"] = 3] = "METHOD_NOT_FOUND";
683
- ErrorCode[ErrorCode["PARAM_INVALID"] = 4] = "PARAM_INVALID";
684
- ErrorCode[ErrorCode["SELECTOR_NOT_SUPPORTED"] = 5] = "SELECTOR_NOT_SUPPORTED";
685
- ErrorCode[ErrorCode["NO_UI_FOR_NODE"] = 6] = "NO_UI_FOR_NODE";
686
- })(NativeApp_ErrorCode || (NativeApp_ErrorCode = {}));
687
- var UpdateDataOptions_NativeUpdateDataType;
688
- (function(NativeUpdateDataType) {
689
- NativeUpdateDataType[NativeUpdateDataType["UPDATE"] = 0] = "UPDATE";
690
- NativeUpdateDataType[NativeUpdateDataType["RESET"] = 1] = "RESET";
691
- })(UpdateDataOptions_NativeUpdateDataType || (UpdateDataOptions_NativeUpdateDataType = {}));
692
- const DispatchEventResult = {
693
- NotCanceled: 0,
694
- CanceledByEventHandler: 1,
695
- CanceledByDefaultEventHandler: 2,
696
- CanceledBeforeDispatch: 3
697
- };
698
- var Element_AnimationOperation;
699
- (function(AnimationOperation) {
700
- AnimationOperation[AnimationOperation["START"] = 0] = "START";
701
- AnimationOperation[AnimationOperation["PLAY"] = 1] = "PLAY";
702
- AnimationOperation[AnimationOperation["PAUSE"] = 2] = "PAUSE";
703
- AnimationOperation[AnimationOperation["CANCEL"] = 3] = "CANCEL";
704
- AnimationOperation[AnimationOperation["FINISH"] = 4] = "FINISH";
705
- })(Element_AnimationOperation || (Element_AnimationOperation = {}));
706
- const getCacheI18nResourcesKey = (options)=>`${options.locale}_${options.channel}_${options.fallback_url}`;
707
- class I18nResources {
708
- data;
709
- constructor(data){
710
- this.data = data;
711
- }
712
- setData(data) {
713
- this.data = data;
714
- }
715
- }
716
- class LynxCrossThreadContext extends EventTarget {
717
- _config;
718
- constructor(_config){
719
- super();
720
- this._config = _config;
721
- }
722
- postMessage(...args) {
723
- console.error('[lynx-web] postMessage not implemented, args:', ...args);
724
- }
725
- dispatchEvent(event) {
726
- const { rpc, sendEventEndpoint } = this._config;
727
- rpc.invoke(sendEventEndpoint, [
728
- event
729
- ]);
730
- return DispatchEventResult.CanceledBeforeDispatch;
731
- }
732
- __start() {
733
- const { rpc, receiveEventEndpoint } = this._config;
734
- rpc.registerHandler(receiveEventEndpoint, ({ type, data })=>{
735
- super.dispatchEvent(new MessageEvent(type, {
736
- data: data ?? {}
737
- }));
738
- });
739
- }
740
- }
741
- const currentSupportedTemplateVersion = 2;
742
- const globalDisallowedVars = [
743
- 'navigator',
744
- 'postMessage',
745
- 'window'
746
- ];
747
- const templateUpgraders = [
748
- (template)=>{
749
- template.appType = template.appType ?? (template.lepusCode.root.startsWith('(function (globDynamicComponentEntry') ? 'lazy' : 'card');
750
- template.version = 2;
751
- template.lepusCode = Object.fromEntries(Object.entries(template.lepusCode).filter(([_, content])=>'string' == typeof content));
752
- return template;
753
- }
754
- ];
755
- const generateModuleContent = (fileName, content, eager, appType)=>[
756
- eager ? '//# allFunctionsCalledOnLoad' : '',
757
- '\n(function() { "use strict"; const ',
758
- globalDisallowedVars.join('=void 0,'),
759
- '=void 0;\n',
760
- 'card' !== appType ? 'module.exports=\n' : '',
761
- content,
762
- '\n})()',
763
- '\n//# sourceURL=',
764
- fileName
765
- ].join('');
766
- async function generateJavascriptUrl(obj, createJsModuleUrl, eager, appType, templateName) {
767
- return Promise.all(Object.entries(obj).filter(([_, content])=>'string' == typeof content).map(async ([name, content])=>[
768
- name,
769
- await createJsModuleUrl(generateModuleContent(`${templateName}/${name.replaceAll('/', '_')}.js`, content, eager, appType), `${templateName}-${name.replaceAll('/', '_')}.js`)
770
- ])).then(Object.fromEntries);
771
- }
772
- async function generateTemplate(template, createJsModuleUrl, templateName) {
773
- template.version = template.version ?? 1;
774
- if (template.version > currentSupportedTemplateVersion) throw new Error("Unsupported template, please upgrade your web-platform dependencies");
775
- let upgrader;
776
- while(template.version < currentSupportedTemplateVersion && (upgrader = templateUpgraders[template.version - 1]))template = upgrader(template);
777
- return {
778
- ...template,
779
- lepusCode: await generateJavascriptUrl(template.lepusCode, createJsModuleUrl, true, template.appType, templateName)
780
- };
781
- }
782
- function registerCallLepusMethodHandler(rpc, runtime) {
783
- rpc.registerHandler(callLepusMethodEndpoint, (methodName, data)=>{
784
- runtime[methodName](data);
785
- });
786
- }
787
- function registerGetCustomSectionHandler(rpc, customSections) {
788
- rpc.registerHandler(getCustomSectionsEndpoint, (key)=>customSections[key]?.content);
789
- }
790
- function createMainThreadLynx(config, SystemInfo) {
791
- const requestAnimationFrameBrowserImpl = requestAnimationFrame;
792
- const cancelAnimationFrameBrowserImpl = cancelAnimationFrame;
793
- const setTimeoutBrowserImpl = setTimeout;
794
- const clearTimeoutBrowserImpl = clearTimeout;
795
- const setIntervalBrowserImpl = setInterval;
796
- const clearIntervalBrowserImpl = clearInterval;
797
- return {
798
- getJSContext () {
799
- return config.jsContext;
800
- },
801
- requestAnimationFrame (cb) {
802
- return requestAnimationFrameBrowserImpl(cb);
803
- },
804
- cancelAnimationFrame (handler) {
805
- return cancelAnimationFrameBrowserImpl(handler);
806
- },
807
- __globalProps: config.globalProps,
808
- getCustomSectionSync (key) {
809
- return config.lynxTemplate.customSections[key]?.content;
810
- },
811
- markPipelineTiming: config.callbacks.markTiming,
812
- SystemInfo,
813
- setTimeout: setTimeoutBrowserImpl,
814
- clearTimeout: clearTimeoutBrowserImpl,
815
- setInterval: setIntervalBrowserImpl,
816
- clearInterval: clearIntervalBrowserImpl
817
- };
818
- }
819
- const cacheForCamelize = {};
820
- function camelize(str) {
821
- if (cacheForCamelize[str]) return cacheForCamelize[str];
822
- const result = (str + '').replace(/-\D/g, function(match) {
823
- return match.charAt(1).toUpperCase();
824
- });
825
- cacheForCamelize[str] = result;
826
- return result;
827
- }
828
- let cssPropertyMap_index = 1;
829
- const cssPropertyMap = {};
830
- const cssPropertyReverseMap = {};
831
- const V = (name)=>{
832
- const k = cssPropertyMap_index++;
833
- const isX = name.startsWith('-x-');
834
- cssPropertyMap[k] = {
835
- name: camelize(name),
836
- dashName: name,
837
- isX
838
- };
839
- cssPropertyReverseMap[name] = k;
840
- };
841
- V('top');
842
- V('left');
843
- V('right');
844
- V('bottom');
845
- V('position');
846
- V('box-sizing');
847
- V('background-color');
848
- V('border-left-color');
849
- V('border-right-color');
850
- V('border-top-color');
851
- V('border-bottom-color');
852
- V('border-radius');
853
- V('border-top-left-radius');
854
- V('border-bottom-left-radius');
855
- V('border-top-right-radius');
856
- V('border-bottom-right-radius');
857
- V('border-width');
858
- V('border-left-width');
859
- V('border-right-width');
860
- V('border-top-width');
861
- V('border-bottom-width');
862
- V('color');
863
- V('opacity');
864
- V('display');
865
- V('overflow');
866
- V('height');
867
- V('width');
868
- V('max-width');
869
- V('min-width');
870
- V('max-height');
871
- V('min-height');
872
- V('padding');
873
- V('padding-left');
874
- V('padding-right');
875
- V('padding-top');
876
- V('padding-bottom');
877
- V('margin');
878
- V('margin-left');
879
- V('margin-right');
880
- V('margin-top');
881
- V('margin-bottom');
882
- V('white-space');
883
- V('letter-spacing');
884
- V('text-align');
885
- V('line-height');
886
- V('text-overflow');
887
- V('font-size');
888
- V('font-weight');
889
- V('flex');
890
- V('flex-grow');
891
- V('flex-shrink');
892
- V('flex-basis');
893
- V('flex-direction');
894
- V('flex-wrap');
895
- V('align-items');
896
- V('align-self');
897
- V('align-content');
898
- V('justify-content');
899
- V('background');
900
- V('border-color');
901
- V('font-family');
902
- V('font-style');
903
- V('transform');
904
- V('animation');
905
- V('animation-name');
906
- V('animation-duration');
907
- V('animation-timing-function');
908
- V('animation-delay');
909
- V('animation-iteration-count');
910
- V('animation-direction');
911
- V('animation-fill-mode');
912
- V('animation-play-state');
913
- V('line-spacing');
914
- V('border-style');
915
- V('order');
916
- V('box-shadow');
917
- V('transform-origin');
918
- V('linear-orientation');
919
- V('linear-weight-sum');
920
- V('linear-weight');
921
- V('linear-gravity');
922
- V('linear-layout-gravity');
923
- V('layout-animation-create-duration');
924
- V('layout-animation-create-timing-function');
925
- V('layout-animation-create-delay');
926
- V('layout-animation-create-property');
927
- V('layout-animation-delete-duration');
928
- V('layout-animation-delete-timing-function');
929
- V('layout-animation-delete-delay');
930
- V('layout-animation-delete-property');
931
- V('layout-animation-update-duration');
932
- V('layout-animation-update-timing-function');
933
- V('layout-animation-update-delay');
934
- V('adapt-font-size');
935
- V('aspect-ratio');
936
- V('text-decoration');
937
- V('text-shadow');
938
- V('background-image');
939
- V('background-position');
940
- V('background-origin');
941
- V('background-repeat');
942
- V('background-size');
943
- V('border');
944
- V('visibility');
945
- V('border-right');
946
- V('border-left');
947
- V('border-top');
948
- V('border-bottom');
949
- V('transition');
950
- V('transition-property');
951
- V('transition-duration');
952
- V('transition-delay');
953
- V('transition-timing-function');
954
- V('content');
955
- V('border-left-style');
956
- V('border-right-style');
957
- V('border-top-style');
958
- V('border-bottom-style');
959
- V('implicit-animation');
960
- V('overflow-x');
961
- V('overflow-y');
962
- V('word-break');
963
- V('background-clip');
964
- V('outline');
965
- V('outline-color');
966
- V('outline-style');
967
- V('outline-width');
968
- V('vertical-align');
969
- V('caret-color');
970
- V('direction');
971
- V('relative-id');
972
- V('relative-align-top');
973
- V('relative-align-right');
974
- V('relative-align-bottom');
975
- V('relative-align-left');
976
- V('relative-top-of');
977
- V('relative-right-of');
978
- V('relative-bottom-of');
979
- V('relative-left-of');
980
- V('relative-layout-once');
981
- V('relative-center');
982
- V('enter-transition-name');
983
- V('exit-transition-name');
984
- V('pause-transition-name');
985
- V('resume-transition-name');
986
- V('flex-flow');
987
- V('z-index');
988
- V('text-decoration-color');
989
- V('linear-cross-gravity');
990
- V('margin-inline-start');
991
- V('margin-inline-end');
992
- V('padding-inline-start');
993
- V('padding-inline-end');
994
- V('border-inline-start-color');
995
- V('border-inline-end-color');
996
- V('border-inline-start-width');
997
- V('border-inline-end-width');
998
- V('border-inline-start-style');
999
- V('border-inline-end-style');
1000
- V('border-start-start-radius');
1001
- V('border-end-start-radius');
1002
- V('border-start-end-radius');
1003
- V('border-end-end-radius');
1004
- V('relative-align-inline-start');
1005
- V('relative-align-inline-end');
1006
- V('relative-inline-start-of');
1007
- V('relative-inline-end-of');
1008
- V('inset-inline-start');
1009
- V('inset-inline-end');
1010
- V('mask-image');
1011
- V('grid-template-columns');
1012
- V('grid-template-rows');
1013
- V('grid-auto-columns');
1014
- V('grid-auto-rows');
1015
- V('grid-column-span');
1016
- V('grid-row-span');
1017
- V('grid-column-start');
1018
- V('grid-column-end');
1019
- V('grid-row-start');
1020
- V('grid-row-end');
1021
- V('grid-column-gap');
1022
- V('grid-row-gap');
1023
- V('justify-items');
1024
- V('justify-self');
1025
- V('grid-auto-flow');
1026
- V('filter');
1027
- V('list-main-axis-gap');
1028
- V('list-cross-axis-gap');
1029
- V('linear-direction');
1030
- V('perspective');
1031
- V('cursor');
1032
- V('text-indent');
1033
- V('clip-path');
1034
- V('text-stroke');
1035
- V('text-stroke-width');
1036
- V('text-stroke-color');
1037
- V('-x-auto-font-size');
1038
- V('-x-auto-font-size-preset-sizes');
1039
- V('mask');
1040
- V('mask-repeat');
1041
- V('mask-position');
1042
- V('mask-clip');
1043
- V('mask-origin');
1044
- V('mask-size');
1045
- V('gap');
1046
- V('column-gap');
1047
- V('row-gap');
1048
- V('image-rendering');
1049
- V('hyphens');
1050
- V('-x-app-region');
1051
- V('-x-animation-color-interpolation');
1052
- V('-x-handle-color');
1053
- V('-x-handle-size');
1054
- V('offset-path');
1055
- V('offset-distance');
1056
- function queryCSSProperty(index) {
1057
- return cssPropertyMap[index];
1058
- }
1059
- const referenceTypes = async ()=>WebAssembly.validate(new Uint8Array([
1060
- 0,
1061
- 97,
1062
- 115,
1063
- 109,
1064
- 1,
1065
- 0,
1066
- 0,
1067
- 0,
1068
- 1,
1069
- 4,
1070
- 1,
1071
- 96,
1072
- 0,
1073
- 0,
1074
- 3,
1075
- 2,
1076
- 1,
1077
- 0,
1078
- 10,
1079
- 7,
1080
- 1,
1081
- 5,
1082
- 0,
1083
- 208,
1084
- 112,
1085
- 26,
1086
- 11
1087
- ]));
1088
- let wasm;
1089
- async function initWasm() {
1090
- const supportsReferenceTypes = await referenceTypes();
1091
- wasm = supportsReferenceTypes ? await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../web-style-transformer/standard.js")) : await __webpack_require__.e("8").then(__webpack_require__.bind(__webpack_require__, "../web-style-transformer/legacy.js"));
1092
- }
1093
- function transformInlineStyleString(str) {
1094
- return wasm.transform_raw_u16_inline_style_ptr(str) ?? str;
1095
- }
1096
- function transformParsedStyles(styles) {
1097
- let childStyle = [];
1098
- let transformedStyle = [];
1099
- for (const [property, value] of styles){
1100
- const transformedResult = wasm.transform_raw_u16_inline_style_ptr_parsed(property, value);
1101
- if (transformedResult) {
1102
- const [transformedStyleForCurrent, childStyleForCurrent] = transformedResult;
1103
- transformedStyle = transformedStyle.concat(transformedStyleForCurrent);
1104
- if (childStyleForCurrent) childStyle = childStyle.concat(childStyleForCurrent);
1105
- } else transformedStyle.push([
1106
- property,
1107
- value
1108
- ]);
1109
- }
1110
- return {
1111
- childStyle,
1112
- transformedStyle
1113
- };
1114
- }
1115
- var uppercasePattern = /[A-Z]/g;
1116
- var msPattern = /^ms-/;
1117
- var hyphenate_style_name_cache = {};
1118
- function toHyphenLower(match) {
1119
- return '-' + match.toLowerCase();
1120
- }
1121
- function hyphenateStyleName(name) {
1122
- if (hyphenate_style_name_cache.hasOwnProperty(name)) return hyphenate_style_name_cache[name];
1123
- var hName = name.replace(uppercasePattern, toHyphenLower);
1124
- return hyphenate_style_name_cache[name] = msPattern.test(hName) ? '-' + hName : hName;
1125
- }
1126
- const hyphenate_style_name = hyphenateStyleName;
1127
- const __AppendElement = /*#__PURE__*/ (parent, child)=>parent.appendChild(child);
1128
- const __ElementIsEqual = /*#__PURE__*/ (left, right)=>left === right;
1129
- const __FirstElement = /*#__PURE__*/ (element)=>element.firstElementChild;
1130
- const __GetChildren = /*#__PURE__*/ (element)=>element.children ? [
1131
- ...element.children
1132
- ] : null;
1133
- const __GetParent = /*#__PURE__*/ (element)=>element.parentElement;
1134
- const __InsertElementBefore = /*#__PURE__*/ (parent, child, ref)=>parent.insertBefore(child, ref);
1135
- const __LastElement = /*#__PURE__*/ (element)=>element.lastElementChild;
1136
- const __NextElement = /*#__PURE__*/ (element)=>element.nextElementSibling;
1137
- const __RemoveElement = /*#__PURE__*/ (parent, child)=>parent.removeChild(child);
1138
- const __ReplaceElement = /*#__PURE__*/ (newElement, oldElement)=>oldElement.replaceWith(newElement);
1139
- const __ReplaceElements = /*#__PURE__*/ (parent, newChildren, oldChildren)=>{
1140
- newChildren = Array.isArray(newChildren) ? newChildren : [
1141
- newChildren
1142
- ];
1143
- if (!oldChildren || Array.isArray(oldChildren) && oldChildren?.length === 0) parent.append(...newChildren);
1144
- else {
1145
- oldChildren = Array.isArray(oldChildren) ? oldChildren : [
1146
- oldChildren
1147
- ];
1148
- for(let ii = 1; ii < oldChildren.length; ii++)__RemoveElement(parent, oldChildren[ii]);
1149
- const firstOldChildren = oldChildren[0];
1150
- firstOldChildren.replaceWith(...newChildren);
1151
- }
1152
- };
1153
- const __AddConfig = /*#__PURE__*/ (element, type, value)=>{
1154
- const currentComponentConfigString = element.getAttribute(lynxComponentConfigAttribute);
1155
- let currentComponentConfig = currentComponentConfigString ? JSON.parse(decodeURIComponent(currentComponentConfigString)) : {};
1156
- currentComponentConfig[type] = value;
1157
- element.setAttribute(lynxComponentConfigAttribute, encodeURIComponent(JSON.stringify(currentComponentConfig)));
1158
- };
1159
- const __AddDataset = /*#__PURE__*/ (element, key, value)=>{
1160
- const currentDataset = __GetDataset(element);
1161
- currentDataset[key] = value;
1162
- element.setAttribute("l-dset", encodeURIComponent(JSON.stringify(currentDataset)));
1163
- value ? element.setAttribute('data-' + key, value.toString()) : element.removeAttribute('data-' + key);
1164
- };
1165
- const __GetDataset = /*#__PURE__*/ (element)=>{
1166
- const datasetString = element.getAttribute("l-dset");
1167
- const currentDataset = datasetString ? JSON.parse(decodeURIComponent(datasetString)) : {};
1168
- return currentDataset;
1169
- };
1170
- const __GetDataByKey = /*#__PURE__*/ (element, key)=>{
1171
- const dataset = __GetDataset(element);
1172
- return dataset[key];
1173
- };
1174
- const __GetAttributes = /*#__PURE__*/ (element)=>Object.fromEntries(element.getAttributeNames().map((attributeName)=>[
1175
- attributeName,
1176
- element.getAttribute(attributeName)
1177
- ]).filter(([, value])=>value));
1178
- const __GetComponentID = /*#__PURE__*/ (element)=>element.getAttribute(componentIdAttribute);
1179
- const __GetElementConfig = /*#__PURE__*/ (element)=>{
1180
- const currentComponentConfigString = element.getAttribute(lynxComponentConfigAttribute);
1181
- return currentComponentConfigString ? JSON.parse(decodeURIComponent(currentComponentConfigString)) : {};
1182
- };
1183
- const __GetAttributeByName = /*#__PURE__*/ (element, name)=>element.getAttribute(name);
1184
- const __GetElementUniqueID = /*#__PURE__*/ (element)=>element && element.getAttribute ? Number(element.getAttribute("l-uid")) : -1;
1185
- const __GetID = /*#__PURE__*/ (element)=>element.getAttribute('id');
1186
- const __SetID = /*#__PURE__*/ (element, id)=>id ? element.setAttribute('id', id) : element.removeAttribute('id');
1187
- const __GetTag = /*#__PURE__*/ (element)=>element.getAttribute(lynxTagAttribute);
1188
- const __SetConfig = /*#__PURE__*/ (element, config)=>{
1189
- element.setAttribute(lynxComponentConfigAttribute, encodeURIComponent(JSON.stringify(config)));
1190
- };
1191
- const __SetDataset = /*#__PURE__*/ (element, dataset)=>{
1192
- element.setAttribute("l-dset", encodeURIComponent(JSON.stringify(dataset)));
1193
- for (const [key, value] of Object.entries(dataset))element.setAttribute('data-' + key, value.toString());
1194
- };
1195
- const __UpdateComponentID = /*#__PURE__*/ (element, componentID)=>element.setAttribute(componentIdAttribute, componentID);
1196
- const __GetClasses = /*#__PURE__*/ (element)=>(element.getAttribute('class') ?? '').split(' ').filter((e)=>e);
1197
- const __UpdateComponentInfo = /*#__PURE__*/ (element, params)=>{
1198
- void 0 !== params.componentID && __UpdateComponentID(element, params.componentID);
1199
- void 0 !== params.cssID && element.setAttribute(cssIdAttribute, params.cssID + '');
1200
- void 0 !== params.name && element.setAttribute('name', params.name);
1201
- };
1202
- const __SetCSSId = /*#__PURE__*/ (elements, cssId, entryName)=>{
1203
- for (const element of elements){
1204
- element.setAttribute(cssIdAttribute, cssId + '');
1205
- entryName && element.setAttribute(lynxEntryNameAttribute, entryName);
1206
- }
1207
- };
1208
- const __SetClasses = /*#__PURE__*/ (element, classname)=>{
1209
- classname ? element.setAttribute('class', classname) : element.removeAttribute('class');
1210
- };
1211
- const __AddInlineStyle = /*#__PURE__*/ (element, key, value)=>{
1212
- let dashName;
1213
- if ('number' == typeof key) {
1214
- const queryResult = queryCSSProperty(key);
1215
- dashName = queryResult.dashName;
1216
- if (queryResult.isX) console.error(`[lynx-web] css property: ${dashName} is not supported.`);
1217
- } else dashName = key;
1218
- const valueStr = 'number' == typeof value ? value.toString() : value;
1219
- if (valueStr) {
1220
- const { transformedStyle } = transformParsedStyles([
1221
- [
1222
- dashName,
1223
- valueStr
1224
- ]
1225
- ]);
1226
- for (const [property, value] of transformedStyle)element.style.setProperty(property, value);
1227
- } else element.style.removeProperty(dashName);
1228
- };
1229
- const __AddClass = /*#__PURE__*/ (element, className)=>{
1230
- const newClassName = ((element.getAttribute('class') ?? '') + ' ' + className).trim();
1231
- element.setAttribute('class', newClassName);
1232
- };
1233
- const __SetInlineStyles = /*#__PURE__*/ (element, value)=>{
1234
- if (!value) return;
1235
- if ('string' == typeof value) element.setAttribute('style', transformInlineStyleString(value));
1236
- else {
1237
- const { transformedStyle } = transformParsedStyles(Object.entries(value).map(([k, value])=>[
1238
- hyphenate_style_name(k),
1239
- value?.toString?.() ?? ''
1240
- ]));
1241
- const transformedStyleStr = transformedStyle.map(([property, value])=>`${property}:${value};`).join('');
1242
- element.setAttribute('style', transformedStyleStr);
1243
- }
1244
- };
1245
- const __GetTemplateParts = (templateElement)=>{
1246
- const isTemplate = null !== templateElement.getAttribute(lynxElementTemplateMarkerAttribute);
1247
- if (!isTemplate) return {};
1248
- const templateUniqueId = __GetElementUniqueID(templateElement);
1249
- const parts = {};
1250
- const partElements = templateElement.querySelectorAll(`[l-uid="${templateUniqueId}"] [l-part]:not([l-uid="${templateUniqueId}"] [${lynxElementTemplateMarkerAttribute}] [l-part])`);
1251
- for (const partElement of partElements){
1252
- const partId = partElement.getAttribute("l-part");
1253
- if (partId) parts[partId] = partElement;
1254
- }
1255
- return parts;
1256
- };
1257
- const __MarkTemplateElement = (element)=>{
1258
- element.setAttribute(lynxElementTemplateMarkerAttribute, '');
1259
- };
1260
- const __MarkPartElement = (element, partId)=>{
1261
- element.setAttribute("l-part", partId);
1262
- };
1263
- function toCloneableObject(obj) {
1264
- const cloneableObj = {};
1265
- for(const key in obj){
1266
- const value = obj[key];
1267
- if ('boolean' == typeof value || 'number' == typeof value || 'string' == typeof value || null === value) cloneableObj[key] = value;
1268
- }
1269
- return cloneableObj;
1270
- }
1271
- function createCrossThreadEvent(domEvent, eventName) {
1272
- const targetElement = domEvent.target;
1273
- const currentTargetElement = domEvent.currentTarget.getAttribute ? domEvent.currentTarget : void 0;
1274
- const type = domEvent.type;
1275
- const params = {};
1276
- const isTrusted = domEvent.isTrusted;
1277
- const otherProperties = {};
1278
- let detail = domEvent.detail ?? {};
1279
- if (type.match(/^transition/)) Object.assign(params, {
1280
- animation_type: 'keyframe-animation',
1281
- animation_name: domEvent.propertyName,
1282
- new_animator: true
1283
- });
1284
- else if (type.match(/animation/)) Object.assign(params, {
1285
- animation_type: 'keyframe-animation',
1286
- animation_name: domEvent.animationName,
1287
- new_animator: true
1288
- });
1289
- else if (type.startsWith('touch')) {
1290
- const touchEvent = domEvent;
1291
- const touch = [
1292
- ...touchEvent.touches
1293
- ];
1294
- const targetTouches = [
1295
- ...touchEvent.targetTouches
1296
- ];
1297
- const changedTouches = [
1298
- ...touchEvent.changedTouches
1299
- ];
1300
- Object.assign(otherProperties, {
1301
- touches: isTrusted ? touch.map(toCloneableObject) : touch,
1302
- targetTouches: isTrusted ? targetTouches.map(toCloneableObject) : targetTouches,
1303
- changedTouches: isTrusted ? changedTouches.map(toCloneableObject) : changedTouches
1304
- });
1305
- } else if (type.startsWith('mouse')) {
1306
- const mouseEvent = domEvent;
1307
- Object.assign(otherProperties, {
1308
- button: mouseEvent.button,
1309
- buttons: mouseEvent.buttons,
1310
- x: mouseEvent.x,
1311
- y: mouseEvent.y,
1312
- pageX: mouseEvent.pageX,
1313
- pageY: mouseEvent.pageY,
1314
- clientX: mouseEvent.clientX,
1315
- clientY: mouseEvent.clientY
1316
- });
1317
- } else if ('click' === type) detail = {
1318
- x: domEvent.x,
1319
- y: domEvent.y
1320
- };
1321
- const currentTargetDatasetString = currentTargetElement?.getAttribute("l-dset");
1322
- const currentTargetDataset = currentTargetDatasetString ? JSON.parse(decodeURIComponent(currentTargetDatasetString)) : {};
1323
- const targetDatasetString = targetElement.getAttribute("l-dset");
1324
- const targetDataset = targetDatasetString ? JSON.parse(decodeURIComponent(targetDatasetString)) : {};
1325
- return {
1326
- type: eventName,
1327
- timestamp: domEvent.timeStamp,
1328
- target: {
1329
- id: targetElement.getAttribute('id'),
1330
- dataset: targetDataset,
1331
- uniqueId: Number(targetElement.getAttribute("l-uid"))
1332
- },
1333
- currentTarget: currentTargetElement ? {
1334
- id: currentTargetElement.getAttribute('id'),
1335
- dataset: currentTargetDataset,
1336
- uniqueId: Number(currentTargetElement.getAttribute("l-uid"))
1337
- } : null,
1338
- detail,
1339
- params,
1340
- ...otherProperties
1341
- };
1342
- }
1343
- const exposureRelatedAttributes = new Set([
1344
- 'exposure-id',
1345
- 'exposure-area',
1346
- 'exposure-screen-margin-top',
1347
- 'exposure-screen-margin-right',
1348
- 'exposure-screen-margin-bottom',
1349
- 'exposure-screen-margin-left',
1350
- 'exposure-ui-margin-top',
1351
- 'exposure-ui-margin-right',
1352
- 'exposure-ui-margin-bottom',
1353
- 'exposure-ui-margin-left'
1354
- ]);
1355
- function createMainThreadGlobalThis(config) {
1356
- let timingFlags = [];
1357
- const { callbacks, tagMap, pageConfig, lynxTemplate, rootDom, globalProps, ssrHydrateInfo, ssrHooks, mtsRealm, document } = config;
1358
- const { elementTemplate, lepusCode } = lynxTemplate;
1359
- const lynxUniqueIdToElement = ssrHydrateInfo?.lynxUniqueIdToElement ?? [];
1360
- const elementToRuntimeInfoMap = new WeakMap();
1361
- let pageElement = lynxUniqueIdToElement[1]?.deref();
1362
- let uniqueIdInc = lynxUniqueIdToElement.length || 1;
1363
- const exposureChangedElements = new Set();
1364
- const commonHandler = (event)=>{
1365
- if (!event.currentTarget) return;
1366
- const currentTarget = event.currentTarget;
1367
- const isCapture = event.eventPhase === Event.CAPTURING_PHASE;
1368
- const lynxEventName = W3cEventNameToLynx[event.type] ?? event.type;
1369
- const runtimeInfo = elementToRuntimeInfoMap.get(currentTarget);
1370
- if (runtimeInfo) {
1371
- const hname = isCapture ? runtimeInfo.eventHandlerMap[lynxEventName]?.capture?.handler : runtimeInfo.eventHandlerMap[lynxEventName]?.bind?.handler;
1372
- const crossThreadEvent = createCrossThreadEvent(event, lynxEventName);
1373
- if ('string' == typeof hname) {
1374
- const parentComponentUniqueId = Number(currentTarget.getAttribute(parentComponentUniqueIdAttribute));
1375
- const parentComponent = lynxUniqueIdToElement[parentComponentUniqueId].deref();
1376
- const componentId = parentComponent?.getAttribute(lynxTagAttribute) !== 'page' ? parentComponent?.getAttribute(componentIdAttribute) ?? void 0 : void 0;
1377
- if (componentId) callbacks.publicComponentEvent(componentId, hname, crossThreadEvent);
1378
- else callbacks.publishEvent(hname, crossThreadEvent);
1379
- return true;
1380
- }
1381
- if (hname) {
1382
- crossThreadEvent.target.elementRefptr = event.target;
1383
- if (crossThreadEvent.currentTarget) crossThreadEvent.currentTarget.elementRefptr = event.currentTarget;
1384
- mtsRealm.globalWindow.runWorklet?.(hname.value, [
1385
- crossThreadEvent
1386
- ]);
1387
- }
1388
- }
1389
- return false;
1390
- };
1391
- const commonCatchHandler = (event)=>{
1392
- const handlerTriggered = commonHandler(event);
1393
- if (handlerTriggered) event.stopPropagation();
1394
- };
1395
- const __AddEvent = (element, eventType, eventName, newEventHandler)=>{
1396
- eventName = eventName.toLowerCase();
1397
- const isCatch = 'catchEvent' === eventType || 'capture-catch' === eventType;
1398
- const isCapture = eventType.startsWith('capture');
1399
- const runtimeInfo = elementToRuntimeInfoMap.get(element) ?? {
1400
- eventHandlerMap: {},
1401
- componentAtIndex: void 0,
1402
- enqueueComponent: void 0
1403
- };
1404
- const currentHandler = isCapture ? runtimeInfo.eventHandlerMap[eventName]?.capture : runtimeInfo.eventHandlerMap[eventName]?.bind;
1405
- const currentRegisteredHandler = isCatch ? commonCatchHandler : commonHandler;
1406
- if (currentHandler) {
1407
- if (!newEventHandler) {
1408
- element.removeEventListener(eventName, currentRegisteredHandler, {
1409
- capture: isCapture
1410
- });
1411
- const isExposure = 'uiappear' === eventName || 'uidisappear' === eventName;
1412
- if (isExposure && '-1' === element.getAttribute('exposure-id')) mtsGlobalThis.__SetAttribute(element, 'exposure-id', null);
1413
- }
1414
- } else if (newEventHandler) {
1415
- const htmlEventName = LynxEventNameToW3cByTagName[element.tagName]?.[eventName] ?? LynxEventNameToW3cCommon[eventName] ?? eventName;
1416
- element.addEventListener(htmlEventName, currentRegisteredHandler, {
1417
- capture: isCapture
1418
- });
1419
- const isExposure = 'uiappear' === eventName || 'uidisappear' === eventName;
1420
- if (isExposure && null === element.getAttribute('exposure-id')) mtsGlobalThis.__SetAttribute(element, 'exposure-id', '-1');
1421
- }
1422
- if (newEventHandler) {
1423
- const info = {
1424
- type: eventType,
1425
- handler: newEventHandler
1426
- };
1427
- if (!runtimeInfo.eventHandlerMap[eventName]) runtimeInfo.eventHandlerMap[eventName] = {
1428
- capture: void 0,
1429
- bind: void 0
1430
- };
1431
- if (isCapture) runtimeInfo.eventHandlerMap[eventName].capture = info;
1432
- else runtimeInfo.eventHandlerMap[eventName].bind = info;
1433
- }
1434
- elementToRuntimeInfoMap.set(element, runtimeInfo);
1435
- };
1436
- const __GetEvent = (element, eventName, eventType)=>{
1437
- const runtimeInfo = elementToRuntimeInfoMap.get(element);
1438
- if (!runtimeInfo) return;
1439
- {
1440
- eventName = eventName.toLowerCase();
1441
- const isCapture = eventType.startsWith('capture');
1442
- const handler = isCapture ? runtimeInfo.eventHandlerMap[eventName]?.capture : runtimeInfo.eventHandlerMap[eventName]?.bind;
1443
- return handler?.handler;
1444
- }
1445
- };
1446
- const __GetEvents = (element)=>{
1447
- const eventHandlerMap = elementToRuntimeInfoMap.get(element)?.eventHandlerMap ?? {};
1448
- const eventInfos = [];
1449
- for (const [lynxEventName, info] of Object.entries(eventHandlerMap))for (const atomInfo of [
1450
- info.bind,
1451
- info.capture
1452
- ])if (atomInfo) {
1453
- const { type, handler } = atomInfo;
1454
- if (handler) eventInfos.push({
1455
- type: type,
1456
- name: lynxEventName,
1457
- function: handler
1458
- });
1459
- }
1460
- return eventInfos;
1461
- };
1462
- const __SetEvents = (element, listeners)=>{
1463
- for (const { type: eventType, name: lynxEventName, function: eventHandler } of listeners)__AddEvent(element, eventType, lynxEventName, eventHandler);
1464
- };
1465
- const __CreateElement = (tag, parentComponentUniqueId)=>{
1466
- const uniqueId = uniqueIdInc++;
1467
- const htmlTag = tagMap[tag] ?? tag;
1468
- const element = document.createElement(htmlTag);
1469
- lynxUniqueIdToElement[uniqueId] = new WeakRef(element);
1470
- const parentComponentCssID = lynxUniqueIdToElement[parentComponentUniqueId]?.deref()?.getAttribute(cssIdAttribute);
1471
- parentComponentCssID && '0' !== parentComponentCssID && element.setAttribute(cssIdAttribute, parentComponentCssID);
1472
- element.setAttribute(lynxTagAttribute, tag);
1473
- element.setAttribute("l-uid", uniqueId + '');
1474
- element.setAttribute(parentComponentUniqueIdAttribute, parentComponentUniqueId + '');
1475
- return element;
1476
- };
1477
- const __CreateView = (parentComponentUniqueId)=>__CreateElement('view', parentComponentUniqueId);
1478
- const __CreateText = (parentComponentUniqueId)=>__CreateElement('text', parentComponentUniqueId);
1479
- const __CreateRawText = (text1)=>{
1480
- const element = __CreateElement('raw-text', -1);
1481
- element.setAttribute('text', text1);
1482
- return element;
1483
- };
1484
- const __CreateImage = (parentComponentUniqueId)=>__CreateElement('image', parentComponentUniqueId);
1485
- const __CreateScrollView = (parentComponentUniqueId)=>__CreateElement('scroll-view', parentComponentUniqueId);
1486
- const __CreateWrapperElement = (parentComponentUniqueId)=>__CreateElement('lynx-wrapper', parentComponentUniqueId);
1487
- const __CreatePage = (componentID, cssID)=>{
1488
- const page = __CreateElement('page', 0);
1489
- page.setAttribute('part', 'page');
1490
- page.setAttribute(cssIdAttribute, cssID + '');
1491
- page.setAttribute(parentComponentUniqueIdAttribute, '0');
1492
- page.setAttribute(componentIdAttribute, componentID);
1493
- __MarkTemplateElement(page);
1494
- if (false === pageConfig.defaultDisplayLinear) page.setAttribute(lynxDefaultDisplayLinearAttribute, 'false');
1495
- if (true === pageConfig.defaultOverflowVisible) page.setAttribute('lynx-default-overflow-visible', 'true');
1496
- pageElement = page;
1497
- return page;
1498
- };
1499
- const __CreateList = (parentComponentUniqueId, componentAtIndex, enqueueComponent)=>{
1500
- const list = __CreateElement('list', parentComponentUniqueId);
1501
- const runtimeInfo = {
1502
- eventHandlerMap: {},
1503
- componentAtIndex: componentAtIndex,
1504
- enqueueComponent: enqueueComponent
1505
- };
1506
- elementToRuntimeInfoMap.set(list, runtimeInfo);
1507
- return list;
1508
- };
1509
- const __CreateComponent = (componentParentUniqueID, componentID, cssID, _, name)=>{
1510
- const component = __CreateElement('view', componentParentUniqueID);
1511
- component.setAttribute(cssIdAttribute, cssID + '');
1512
- component.setAttribute(componentIdAttribute, componentID);
1513
- component.setAttribute('name', name);
1514
- return component;
1515
- };
1516
- const __SetAttribute = (element, key, value)=>{
1517
- const tag = element.getAttribute(lynxTagAttribute);
1518
- if ('list' === tag && 'update-list-info' === key) {
1519
- const listInfo = value;
1520
- const { insertAction, removeAction } = listInfo;
1521
- queueMicrotask(()=>{
1522
- const runtimeInfo = elementToRuntimeInfoMap.get(element);
1523
- if (runtimeInfo) {
1524
- const componentAtIndex = runtimeInfo.componentAtIndex;
1525
- const enqueueComponent = runtimeInfo.enqueueComponent;
1526
- const uniqueId = __GetElementUniqueID(element);
1527
- for (const action of insertAction)componentAtIndex?.(element, uniqueId, action.position, 0, false);
1528
- for (const action of removeAction)enqueueComponent?.(element, uniqueId, action.position);
1529
- }
1530
- });
1531
- } else {
1532
- null == value ? element.removeAttribute(key) : element.setAttribute(key, value + '');
1533
- if (key === __lynx_timing_flag && value) timingFlags.push(value);
1534
- if (exposureRelatedAttributes.has(key)) exposureChangedElements.add(element);
1535
- }
1536
- };
1537
- const __UpdateListCallbacks = (element, componentAtIndex, enqueueComponent)=>{
1538
- const runtimeInfo = elementToRuntimeInfoMap.get(element) ?? {
1539
- eventHandlerMap: {},
1540
- componentAtIndex: componentAtIndex,
1541
- enqueueComponent: enqueueComponent,
1542
- uniqueId: __GetElementUniqueID(element)
1543
- };
1544
- runtimeInfo.componentAtIndex = componentAtIndex;
1545
- runtimeInfo.enqueueComponent = enqueueComponent;
1546
- elementToRuntimeInfoMap.set(element, runtimeInfo);
1547
- };
1548
- const __SwapElement = (childA, childB)=>{
1549
- const temp = document.createElement('div');
1550
- childA.replaceWith(temp);
1551
- childB.replaceWith(childA);
1552
- temp.replaceWith(childB);
1553
- };
1554
- const __SetCSSIdForCSSOG = (elements, cssId, entryName)=>{
1555
- for (const element of elements){
1556
- element.setAttribute(cssIdAttribute, cssId + '');
1557
- entryName && element.setAttribute(lynxEntryNameAttribute, entryName);
1558
- const cls = element.getAttribute('class');
1559
- cls && __SetClassesForCSSOG(element, cls);
1560
- }
1561
- };
1562
- const __AddClassForCSSOG = (element, className)=>{
1563
- const newClassName = ((element.getAttribute('class') ?? '') + ' ' + className).trim();
1564
- element.setAttribute('class', newClassName);
1565
- const cssId = element.getAttribute(cssIdAttribute);
1566
- const uniqueId = Number(element.getAttribute("l-uid"));
1567
- const entryName = element.getAttribute(lynxEntryNameAttribute);
1568
- callbacks.updateCssOGStyle(uniqueId, newClassName, cssId, entryName);
1569
- };
1570
- const __SetClassesForCSSOG = (element, classNames)=>{
1571
- __SetClasses(element, classNames);
1572
- const cssId = element.getAttribute(cssIdAttribute);
1573
- const uniqueId = Number(element.getAttribute("l-uid"));
1574
- const entryName = element.getAttribute(lynxEntryNameAttribute);
1575
- callbacks.updateCssOGStyle(uniqueId, classNames ?? '', cssId, entryName);
1576
- };
1577
- const __LoadLepusChunk = (path)=>{
1578
- try {
1579
- path = lepusCode?.[path] ?? path;
1580
- mtsRealm.loadScriptSync(path);
1581
- return true;
1582
- } catch (e) {
1583
- console.error(`failed to load lepus chunk ${path}`, e);
1584
- return false;
1585
- }
1586
- };
1587
- const __FlushElementTree = (_subTree, options)=>{
1588
- const timingFlagsCopied = timingFlags;
1589
- timingFlags = [];
1590
- if (pageElement && !pageElement.parentNode && '' !== pageElement.getAttribute(lynxDisposedAttribute)) rootDom.append(pageElement);
1591
- const exposureChangedElementsArray = Array.from(exposureChangedElements);
1592
- exposureChangedElements.clear();
1593
- callbacks.flushElementTree(options, timingFlagsCopied, exposureChangedElementsArray);
1594
- };
1595
- const __GetPageElement = ()=>pageElement;
1596
- const templateIdToTemplate = {};
1597
- const createElementForElementTemplateData = (data, parentComponentUniId)=>{
1598
- const element = __CreateElement(data.type, parentComponentUniId);
1599
- __SetID(element, data.id);
1600
- data.class && __SetClasses(element, data.class.join(' '));
1601
- for (const [key, value] of Object.entries(data.attributes || {}))__SetAttribute(element, key, value);
1602
- for (const [key, value] of Object.entries(data.builtinAttributes || {})){
1603
- if ('dirtyID' === key && value === data.id) __MarkPartElement(element, value);
1604
- __SetAttribute(element, key, value);
1605
- }
1606
- for (const childData of data.children || [])__AppendElement(element, createElementForElementTemplateData(childData, parentComponentUniId));
1607
- void 0 !== data.dataset && __SetDataset(element, data.dataset);
1608
- return element;
1609
- };
1610
- const applyEventsForElementTemplate = (data, element)=>{
1611
- const uniqueId = uniqueIdInc++;
1612
- element.setAttribute("l-uid", uniqueId + '');
1613
- for (const event of data.events || []){
1614
- const { type, name, value } = event;
1615
- __AddEvent(element, type, name, value);
1616
- }
1617
- for(let ii = 0; ii < (data.children || []).length; ii++){
1618
- const childData = (data.children || [])[ii];
1619
- const childElement = element.children[ii];
1620
- if (childData && childElement) applyEventsForElementTemplate(childData, childElement);
1621
- }
1622
- };
1623
- const __ElementFromBinary = (templateId, parentComponentUniId)=>{
1624
- const elementTemplateData = elementTemplate[templateId];
1625
- if (elementTemplateData) {
1626
- let clonedElements;
1627
- if (templateIdToTemplate[templateId]) clonedElements = Array.from(templateIdToTemplate[templateId].content.cloneNode(true).children);
1628
- else {
1629
- clonedElements = elementTemplateData.map((data)=>createElementForElementTemplateData(data, parentComponentUniId));
1630
- if (rootDom.cloneNode) {
1631
- const template = document.createElement('template');
1632
- template.content.append(...clonedElements);
1633
- templateIdToTemplate[templateId] = template;
1634
- rootDom.append(template);
1635
- return __ElementFromBinary(templateId, parentComponentUniId);
1636
- }
1637
- }
1638
- for(let ii = 0; ii < clonedElements.length; ii++){
1639
- const data = elementTemplateData[ii];
1640
- const element = clonedElements[ii];
1641
- if (data && element) applyEventsForElementTemplate(data, element);
1642
- }
1643
- clonedElements.forEach(__MarkTemplateElement);
1644
- return clonedElements;
1645
- }
1646
- return [];
1647
- };
1648
- let release = '';
1649
- const isCSSOG = !pageConfig.enableCSSSelector;
1650
- const SystemInfo = {
1651
- ...systemInfo,
1652
- ...config.browserConfig
1653
- };
1654
- const mtsGlobalThis = {
1655
- __ElementFromBinary,
1656
- __GetTemplateParts: rootDom.querySelectorAll ? __GetTemplateParts : void 0,
1657
- __MarkTemplateElement: __MarkTemplateElement,
1658
- __MarkPartElement: __MarkPartElement,
1659
- __AddEvent: ssrHooks?.__AddEvent ?? __AddEvent,
1660
- __GetEvent,
1661
- __GetEvents,
1662
- __SetEvents,
1663
- __AppendElement: __AppendElement,
1664
- __ElementIsEqual: __ElementIsEqual,
1665
- __FirstElement: __FirstElement,
1666
- __GetChildren: __GetChildren,
1667
- __GetParent: __GetParent,
1668
- __InsertElementBefore: __InsertElementBefore,
1669
- __LastElement: __LastElement,
1670
- __NextElement: __NextElement,
1671
- __RemoveElement: __RemoveElement,
1672
- __ReplaceElement: __ReplaceElement,
1673
- __ReplaceElements: __ReplaceElements,
1674
- __AddConfig: __AddConfig,
1675
- __AddDataset: __AddDataset,
1676
- __GetAttributes: __GetAttributes,
1677
- __GetComponentID: __GetComponentID,
1678
- __GetDataByKey: __GetDataByKey,
1679
- __GetDataset: __GetDataset,
1680
- __GetElementConfig: __GetElementConfig,
1681
- __GetElementUniqueID: __GetElementUniqueID,
1682
- __GetID: __GetID,
1683
- __GetTag: __GetTag,
1684
- __SetConfig: __SetConfig,
1685
- __SetDataset: __SetDataset,
1686
- __SetID: __SetID,
1687
- __UpdateComponentID: __UpdateComponentID,
1688
- __UpdateComponentInfo: __UpdateComponentInfo,
1689
- __CreateElement,
1690
- __CreateView,
1691
- __CreateText,
1692
- __CreateComponent,
1693
- __CreatePage,
1694
- __CreateRawText,
1695
- __CreateImage,
1696
- __CreateScrollView,
1697
- __CreateWrapperElement,
1698
- __CreateList,
1699
- __SetAttribute,
1700
- __SwapElement,
1701
- __UpdateListCallbacks,
1702
- __GetConfig: __GetElementConfig,
1703
- __GetAttributeByName: __GetAttributeByName,
1704
- __GetClasses: __GetClasses,
1705
- __AddClass: isCSSOG ? __AddClassForCSSOG : __AddClass,
1706
- __SetClasses: isCSSOG ? __SetClassesForCSSOG : __SetClasses,
1707
- __AddInlineStyle: __AddInlineStyle,
1708
- __SetCSSId: isCSSOG ? __SetCSSIdForCSSOG : __SetCSSId,
1709
- __SetInlineStyles: __SetInlineStyles,
1710
- __LoadLepusChunk,
1711
- __GetPageElement,
1712
- __globalProps: globalProps,
1713
- __QueryComponent: callbacks.__QueryComponent,
1714
- SystemInfo,
1715
- lynx: createMainThreadLynx(config, SystemInfo),
1716
- _ReportError: (err, _)=>callbacks._ReportError(err, _, release),
1717
- _SetSourceMapRelease: (errInfo)=>release = errInfo?.release,
1718
- __OnLifecycleEvent: callbacks.__OnLifecycleEvent,
1719
- __FlushElementTree,
1720
- _I18nResourceTranslation: callbacks._I18nResourceTranslation,
1721
- _AddEventListener: ()=>{},
1722
- renderPage: void 0
1723
- };
1724
- Object.assign(mtsRealm.globalWindow, mtsGlobalThis);
1725
- Object.defineProperty(mtsRealm.globalWindow, 'renderPage', {
1726
- get () {
1727
- return mtsGlobalThis.renderPage;
1728
- },
1729
- set (v) {
1730
- mtsGlobalThis.renderPage = v;
1731
- queueMicrotask(callbacks.mainChunkReady);
1732
- },
1733
- configurable: true,
1734
- enumerable: true
1735
- });
1736
- return mtsRealm.globalWindow;
1737
- }
1738
- function createExposureService(rootDom, postExposure) {
1739
- let working = true;
1740
- let exposureCache = [];
1741
- let disexposureCache = [];
1742
- let delayCallback = null;
1743
- const onScreen = new Map();
1744
- function exposureEventHandler(ev) {
1745
- const exposureEvent = createCrossThreadEvent(ev, ev.type);
1746
- exposureEvent.detail['unique-id'] = parseFloat(ev.target.getAttribute("l-uid"));
1747
- const exposureID = exposureEvent.detail.exposureID;
1748
- if ('exposure' === ev.type) {
1749
- exposureCache.push(exposureEvent);
1750
- onScreen.set(exposureID, exposureEvent);
1751
- } else {
1752
- disexposureCache.push(exposureEvent);
1753
- onScreen.delete(exposureID);
1754
- }
1755
- if (!delayCallback) delayCallback = setTimeout(()=>{
1756
- if (exposureCache.length > 0 || disexposureCache.length > 0) {
1757
- const currentExposure = exposureCache;
1758
- const currentDisexposure = disexposureCache;
1759
- exposureCache = [];
1760
- disexposureCache = [];
1761
- postExposure({
1762
- exposures: currentExposure,
1763
- disExposures: currentDisexposure
1764
- });
1765
- }
1766
- delayCallback = null;
1767
- }, 50);
1768
- }
1769
- rootDom.addEventListener('exposure', exposureEventHandler, {
1770
- passive: true
1771
- });
1772
- rootDom.addEventListener('disexposure', exposureEventHandler, {
1773
- passive: true
1774
- });
1775
- function switchExposureService(enable, sendEvent) {
1776
- if (enable && !working) postExposure({
1777
- exposures: [
1778
- ...onScreen.values()
1779
- ],
1780
- disExposures: []
1781
- });
1782
- else if (!enable && working) {
1783
- if (sendEvent) postExposure({
1784
- exposures: [],
1785
- disExposures: [
1786
- ...onScreen.values()
1787
- ]
1788
- });
1789
- }
1790
- working = enable;
1791
- }
1792
- return {
1793
- switchExposureService
1794
- };
1795
- }
1796
- function decodeCssOG(classes, styleInfo, cssId) {
1797
- const classList = classes.split(' ').filter((e)=>e);
1798
- let declarations = [];
1799
- const currentStyleInfo = styleInfo[cssId ?? '0'];
1800
- if (currentStyleInfo) for (const oneClassName of classList){
1801
- const oneRule = currentStyleInfo[oneClassName];
1802
- if (oneRule) declarations.push(...oneRule);
1803
- }
1804
- else console.warn(`[lynx-web] cannot find styleinfo for cssid ${cssId}`);
1805
- return declarations.map(([property, value])=>`${property}:${value};`).join('');
1806
- }
1807
- function topologicalSort(styleInfo) {
1808
- const queue = [];
1809
- const inDegreeMap = new Map();
1810
- for (const [cssId, oneStyleInfo] of Object.entries(styleInfo)){
1811
- inDegreeMap.has(cssId) || inDegreeMap.set(cssId, 0);
1812
- for (const importCssId of oneStyleInfo.imports ?? []){
1813
- const currentInDegree = inDegreeMap.get(importCssId) ?? 0;
1814
- inDegreeMap.set(importCssId, currentInDegree + 1);
1815
- }
1816
- }
1817
- for (const [cssId, inDegree] of inDegreeMap.entries())if (0 === inDegree) queue.push(cssId);
1818
- const sortedCssIds = [];
1819
- while(queue.length > 0){
1820
- const currentCssId = queue.shift();
1821
- sortedCssIds.push(currentCssId);
1822
- const currentAdjunction = styleInfo[currentCssId]?.imports;
1823
- if (currentAdjunction) for (const importCssId of currentAdjunction){
1824
- const importInDegree = inDegreeMap.get(importCssId) - 1;
1825
- inDegreeMap.set(importCssId, importInDegree);
1826
- if (0 === importInDegree) queue.push(importCssId);
1827
- }
1828
- }
1829
- return sortedCssIds;
1830
- }
1831
- function generateImportByMap(styleInfo, sortedCssIds) {
1832
- const cssIdToImportBy = new Map();
1833
- for (const cssId of sortedCssIds){
1834
- const currentAdjunction = styleInfo[cssId]?.imports;
1835
- if (currentAdjunction) {
1836
- const currentImportBy = cssIdToImportBy.get(cssId) ?? new Set([
1837
- cssId
1838
- ]);
1839
- for (const importCssId of currentAdjunction){
1840
- const importDeps = cssIdToImportBy.get(importCssId) ?? new Set([
1841
- importCssId
1842
- ]);
1843
- importDeps.add(cssId);
1844
- cssIdToImportBy.set(importCssId, currentImportBy.union(importDeps));
1845
- }
1846
- cssIdToImportBy.set(cssId, currentImportBy);
1847
- }
1848
- }
1849
- return cssIdToImportBy;
1850
- }
1851
- function flattenStyleInfo(styleInfo) {
1852
- const sortedCssIds = topologicalSort(styleInfo);
1853
- const cssIdToImportBy = generateImportByMap(styleInfo, sortedCssIds);
1854
- sortedCssIds.reverse();
1855
- return sortedCssIds.map((cssId)=>{
1856
- const oneInfo = styleInfo[cssId];
1857
- const flattenedInfo = oneInfo ? {
1858
- content: oneInfo.content,
1859
- rules: oneInfo.rules,
1860
- importBy: Array.from(cssIdToImportBy.get(cssId) ?? [
1861
- cssId
1862
- ])
1863
- } : {
1864
- content: [],
1865
- rules: [],
1866
- importBy: [
1867
- cssId
1868
- ]
1869
- };
1870
- return flattenedInfo;
1871
- });
1872
- }
1873
- function transformToWebCss(styleInfo) {
1874
- for (const cssInfos of styleInfo)for (const rule of cssInfos.rules){
1875
- const { sel: selectors, decl: declarations } = rule;
1876
- const { transformedStyle, childStyle } = transformParsedStyles(declarations);
1877
- rule.decl = transformedStyle;
1878
- if (childStyle.length > 0) cssInfos.rules.push({
1879
- sel: selectors.map((selector)=>selector.toSpliced(-2, 1, [
1880
- '>'
1881
- ], [
1882
- '*'
1883
- ], [], [], [])),
1884
- decl: childStyle
1885
- });
1886
- }
1887
- }
1888
- function genCssContent(styleInfo, pageConfig, entryName) {
1889
- function getExtraSelectors(cssId) {
1890
- let suffix;
1891
- suffix = pageConfig.enableRemoveCSSScope ? `[${lynxTagAttribute}]` : `[${cssIdAttribute}="${cssId}"]`;
1892
- suffix = entryName ? `${suffix}[${lynxEntryNameAttribute}=${JSON.stringify(entryName)}]` : `${suffix}:not([${lynxEntryNameAttribute}])`;
1893
- return suffix;
1894
- }
1895
- const finalCssContent = [];
1896
- for (const cssInfos of styleInfo){
1897
- const declarationContent = cssInfos.rules.map((rule)=>{
1898
- const { sel: selectorList, decl: declarations } = rule;
1899
- const selectorString = cssInfos.importBy.map((cssId)=>{
1900
- const suffix = getExtraSelectors(cssId);
1901
- return selectorList.map((selectors)=>selectors.toSpliced(-4, 0, [
1902
- suffix
1903
- ]).flat().join('')).join(',');
1904
- }).join(',');
1905
- const declarationString = declarations.map(([k, v])=>`${k}:${v};`).join('');
1906
- return `${selectorString}{${declarationString}}`;
1907
- }).join('');
1908
- finalCssContent.push(...cssInfos.content, declarationContent);
1909
- }
1910
- return finalCssContent.join('\n');
1911
- }
1912
- function genCssOGInfo(styleInfo) {
1913
- const cssOGInfo = {};
1914
- for (const oneInfo of styleInfo)oneInfo.rules = oneInfo.rules.filter((oneRule)=>{
1915
- oneRule.sel = oneRule.sel.filter((selectorList)=>{
1916
- const [classSelectors, pseudoClassSelectors, pseudoElementSelectors, combinator] = selectorList;
1917
- if (1 === classSelectors.length && '.' === classSelectors[0][0] && 0 === pseudoClassSelectors.length && 0 === pseudoElementSelectors.length && 0 === combinator.length) {
1918
- const selectorName = classSelectors[0].substring(1);
1919
- for (const cssId of oneInfo.importBy){
1920
- if (!cssOGInfo[cssId]) cssOGInfo[cssId] = {};
1921
- const currentDeclarations = cssOGInfo[cssId][selectorName];
1922
- if (currentDeclarations) currentDeclarations.push(...oneRule.decl);
1923
- else cssOGInfo[cssId][selectorName] = oneRule.decl;
1924
- }
1925
- return false;
1926
- }
1927
- return true;
1928
- });
1929
- return oneRule.sel.length > 0;
1930
- });
1931
- return cssOGInfo;
1932
- }
1933
- function appendStyleElement(styleInfo, pageConfig, rootDom, document, ssrHydrateInfo) {
1934
- const lynxUniqueIdToStyleRulesIndex = ssrHydrateInfo?.lynxUniqueIdToStyleRulesIndex ?? [];
1935
- const flattenedStyleInfo = flattenStyleInfo(styleInfo);
1936
- transformToWebCss(flattenedStyleInfo);
1937
- const cssOGInfo = pageConfig.enableCSSSelector ? {} : genCssOGInfo(flattenedStyleInfo);
1938
- const lazyCSSOGInfo = {};
1939
- let cardStyleElement;
1940
- if (ssrHydrateInfo?.cardStyleElement) cardStyleElement = ssrHydrateInfo.cardStyleElement;
1941
- else {
1942
- cardStyleElement = document.createElement('style');
1943
- cardStyleElement.textContent = genCssContent(flattenedStyleInfo, pageConfig, void 0);
1944
- rootDom.appendChild(cardStyleElement);
1945
- }
1946
- const updateCssOGStyle = (uniqueId, newClassName, cssID, entryName)=>{
1947
- const cardStyleElementSheet = cardStyleElement.sheet;
1948
- const styleMap = entryName && lazyCSSOGInfo[entryName] ? lazyCSSOGInfo[entryName] : cssOGInfo;
1949
- const newStyles = decodeCssOG(newClassName, styleMap, cssID);
1950
- if (void 0 !== lynxUniqueIdToStyleRulesIndex[uniqueId]) {
1951
- const rule = cardStyleElementSheet.cssRules[lynxUniqueIdToStyleRulesIndex[uniqueId]];
1952
- rule.style.cssText = newStyles;
1953
- } else {
1954
- const index = cardStyleElementSheet.insertRule(`[l-uid="${uniqueId}"]{${newStyles}}`, cardStyleElementSheet.cssRules.length);
1955
- lynxUniqueIdToStyleRulesIndex[uniqueId] = index;
1956
- }
1957
- };
1958
- const updateLazyComponentStyle = (styleInfo, entryName)=>{
1959
- const flattenedStyleInfo = flattenStyleInfo(styleInfo);
1960
- transformToWebCss(flattenedStyleInfo);
1961
- if (!pageConfig.enableCSSSelector) lazyCSSOGInfo[entryName] = genCssOGInfo(flattenedStyleInfo);
1962
- const newStyleSheet = genCssContent(flattenedStyleInfo, pageConfig, entryName);
1963
- cardStyleElement.textContent += newStyleSheet;
1964
- };
1965
- return {
1966
- updateCssOGStyle,
1967
- updateLazyComponentStyle
1968
- };
1969
- }
1970
- function createQueryComponent(loadTemplate, updateLazyComponentStyle, backgroundThreadRpc, mtsGlobalThisRef, jsContext, mtsRealm) {
1971
- const updateBTSTemplateCache = backgroundThreadRpc.createCall(updateBTSTemplateCacheEndpoint);
1972
- const lazyCache = new Map();
1973
- const __QueryComponentImpl = (url, callback)=>{
1974
- const cacheLazy = lazyCache.get(url);
1975
- const loadPromise = cacheLazy ?? loadTemplate(url).then(async (template)=>{
1976
- const updateBTSCachePromise = updateBTSTemplateCache(url, template);
1977
- let lepusRootChunkExport = await mtsRealm.loadScript(template.lepusCode.root);
1978
- if (mtsGlobalThisRef.mtsGlobalThis.processEvalResult) lepusRootChunkExport = mtsGlobalThisRef.mtsGlobalThis.processEvalResult(lepusRootChunkExport, url);
1979
- updateLazyComponentStyle(template.styleInfo, url);
1980
- await updateBTSCachePromise;
1981
- jsContext.dispatchEvent({
1982
- type: '__OnDynamicJSSourcePrepared',
1983
- data: url
1984
- });
1985
- return lepusRootChunkExport;
1986
- });
1987
- cacheLazy || lazyCache.set(url, loadPromise);
1988
- loadPromise.then((lepusRootChunkExport)=>{
1989
- callback?.({
1990
- code: 0,
1991
- data: {
1992
- url,
1993
- evalResult: lepusRootChunkExport
1994
- }
1995
- });
1996
- }).catch((error)=>{
1997
- console.error("lynx web: lazy bundle load failed:", error);
1998
- lazyCache.delete(url);
1999
- callback?.({
2000
- code: -1,
2001
- data: void 0
2002
- });
2003
- });
2004
- return null;
2005
- };
2006
- backgroundThreadRpc.registerHandler(queryComponentEndpoint, (url)=>{
2007
- const ret = new Promise((resolve)=>{
2008
- __QueryComponentImpl(url, (result)=>{
2009
- resolve({
2010
- code: result.code,
2011
- detail: {
2012
- schema: url
2013
- }
2014
- });
2015
- });
2016
- });
2017
- return ret;
2018
- });
2019
- return __QueryComponentImpl;
2020
- }
2021
- const initWasmPromise = initWasm();
2022
- function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, document, mtsRealmPromise, commitDocument, markTimingInternal, flushMarkTimingInternal, reportError, triggerI18nResourceFallback, initialI18nResources, loadTemplate, ssrHooks) {
2023
- const postTimingFlags = backgroundThreadRpc.createCall(postTimingFlagsEndpoint);
2024
- const backgroundStart = backgroundThreadRpc.createCall(BackgroundThreadStartEndpoint);
2025
- const publishEvent = backgroundThreadRpc.createCall(publishEventEndpoint);
2026
- const publicComponentEvent = backgroundThreadRpc.createCall(publicComponentEventEndpoint);
2027
- const postExposure = backgroundThreadRpc.createCall(postExposureEndpoint);
2028
- const dispatchI18nResource = backgroundThreadRpc.createCall(dispatchI18nResourceEndpoint);
2029
- const updateDataBackground = backgroundThreadRpc.createCall(updateDataEndpoint);
2030
- markTimingInternal('lepus_execute_start');
2031
- async function startMainThread(config, ssrHydrateInfo) {
2032
- let isFp = true;
2033
- const { globalProps, template, browserConfig, nativeModulesMap, napiModulesMap, tagMap, initI18nResources } = config;
2034
- const { styleInfo, pageConfig, customSections, cardType } = template;
2035
- const mtsRealm = await mtsRealmPromise;
2036
- markTimingInternal('decode_start');
2037
- await initWasmPromise;
2038
- const jsContext = new LynxCrossThreadContext({
2039
- rpc: backgroundThreadRpc,
2040
- receiveEventEndpoint: dispatchJSContextOnMainThreadEndpoint,
2041
- sendEventEndpoint: dispatchCoreContextOnBackgroundEndpoint
2042
- });
2043
- const i18nResources = initialI18nResources(initI18nResources);
2044
- const { updateCssOGStyle, updateLazyComponentStyle } = appendStyleElement(styleInfo, pageConfig, rootDom, document, ssrHydrateInfo);
2045
- const mtsGlobalThisRef = {
2046
- mtsGlobalThis: void 0
2047
- };
2048
- const __QueryComponent = createQueryComponent(loadTemplate, updateLazyComponentStyle, backgroundThreadRpc, mtsGlobalThisRef, jsContext, mtsRealm);
2049
- const mtsGlobalThis = createMainThreadGlobalThis({
2050
- lynxTemplate: template,
2051
- mtsRealm,
2052
- jsContext,
2053
- tagMap,
2054
- browserConfig,
2055
- globalProps,
2056
- pageConfig,
2057
- rootDom,
2058
- ssrHydrateInfo,
2059
- ssrHooks,
2060
- document,
2061
- callbacks: {
2062
- updateCssOGStyle,
2063
- mainChunkReady: ()=>{
2064
- markTimingInternal('data_processor_start');
2065
- let initData = config.initData;
2066
- if (true !== pageConfig.enableJSDataProcessor && mtsGlobalThis.processData) initData = mtsGlobalThis.processData(config.initData);
2067
- markTimingInternal('data_processor_end');
2068
- registerCallLepusMethodHandler(backgroundThreadRpc, mtsGlobalThis);
2069
- registerGetCustomSectionHandler(backgroundThreadRpc, customSections);
2070
- const { switchExposureService } = createExposureService(rootDom, postExposure);
2071
- backgroundThreadRpc.registerHandler(switchExposureServiceEndpoint, switchExposureService);
2072
- backgroundStart({
2073
- initData,
2074
- globalProps,
2075
- template,
2076
- cardType: cardType ?? 'react',
2077
- customSections: Object.fromEntries(Object.entries(customSections).filter(([, value])=>'lazy' !== value.type).map(([k, v])=>[
2078
- k,
2079
- v.content
2080
- ])),
2081
- nativeModulesMap,
2082
- napiModulesMap
2083
- });
2084
- if (ssrHydrateInfo) {
2085
- for (const event of ssrHydrateInfo.events){
2086
- const uniqueId = event[0];
2087
- const element = ssrHydrateInfo.lynxUniqueIdToElement[uniqueId]?.deref();
2088
- if (element) mtsGlobalThis.__AddEvent(element, event[1], event[2], event[3]);
2089
- }
2090
- mtsGlobalThis.ssrHydrate?.(ssrHydrateInfo.ssrEncodeData);
2091
- } else {
2092
- mtsGlobalThis.renderPage(initData);
2093
- mtsGlobalThis.__FlushElementTree(void 0, {});
2094
- }
2095
- },
2096
- flushElementTree: async (options, timingFlags, exposureChangedElements)=>{
2097
- const pipelineId = options?.pipelineOptions?.pipelineID;
2098
- markTimingInternal('dispatch_start', pipelineId);
2099
- if (isFp) {
2100
- isFp = false;
2101
- jsContext.dispatchEvent({
2102
- type: '__OnNativeAppReady',
2103
- data: void 0
2104
- });
2105
- }
2106
- markTimingInternal('layout_start', pipelineId);
2107
- markTimingInternal('ui_operation_flush_start', pipelineId);
2108
- await commitDocument(exposureChangedElements);
2109
- markTimingInternal('ui_operation_flush_end', pipelineId);
2110
- markTimingInternal('layout_end', pipelineId);
2111
- markTimingInternal('dispatch_end', pipelineId);
2112
- flushMarkTimingInternal();
2113
- requestAnimationFrame(()=>{
2114
- postTimingFlags(timingFlags, pipelineId);
2115
- });
2116
- },
2117
- _ReportError: reportError,
2118
- __OnLifecycleEvent: (data)=>{
2119
- jsContext.dispatchEvent({
2120
- type: '__OnLifecycleEvent',
2121
- data
2122
- });
2123
- },
2124
- markTiming: (a, b)=>markTimingInternal(b, a),
2125
- publishEvent,
2126
- publicComponentEvent,
2127
- _I18nResourceTranslation: (options)=>{
2128
- const matchedInitI18nResources = i18nResources.data?.find((i)=>getCacheI18nResourcesKey(i.options) === getCacheI18nResourcesKey(options));
2129
- dispatchI18nResource(matchedInitI18nResources?.resource);
2130
- if (matchedInitI18nResources) return matchedInitI18nResources.resource;
2131
- return triggerI18nResourceFallback(options);
2132
- },
2133
- __QueryComponent
2134
- }
2135
- });
2136
- mtsGlobalThisRef.mtsGlobalThis = mtsGlobalThis;
2137
- markTimingInternal('decode_end');
2138
- await mtsRealm.loadScript(template.lepusCode.root);
2139
- jsContext.__start();
2140
- }
2141
- async function handleUpdatedData(newData, options) {
2142
- const mtsRealm = await mtsRealmPromise;
2143
- const runtime = mtsRealm.globalWindow;
2144
- const processedData = runtime.processData ? runtime.processData(newData, options?.processorName) : newData;
2145
- runtime.updatePage?.(processedData, options);
2146
- return updateDataBackground(processedData, options);
2147
- }
2148
- return {
2149
- startMainThread,
2150
- handleUpdatedData
2151
- };
2152
- }
643
+ var dist = __webpack_require__("../web-constants/dist/index.js");
644
+ var web_worker_rpc_dist = __webpack_require__("../web-worker-rpc/dist/index.js");
2153
645
  const templateCache = new Map();
2154
646
  let tmpDir;
2155
647
  const tmpDirPromise = promises.mkdtemp(node_path.join(node_os.tmpdir(), 'lynx'));
2156
- async function loadTemplate_createJsModuleUrl(content, filename) {
648
+ async function createJsModuleUrl(content, filename) {
2157
649
  if (!tmpDir) tmpDir = await tmpDirPromise;
2158
650
  const fileUrl = node_path.join(tmpDir, filename);
2159
651
  await promises.writeFile(fileUrl, content, {
@@ -2161,10 +653,10 @@ async function loadTemplate_createJsModuleUrl(content, filename) {
2161
653
  });
2162
654
  return fileUrl;
2163
655
  }
2164
- async function loadTemplate_loadTemplate(rawTemplate, templateName = Math.random().toString(36).substring(2, 7)) {
656
+ async function loadTemplate(rawTemplate, templateName = Math.random().toString(36).substring(2, 7)) {
2165
657
  if (templateCache.has(rawTemplate)) return templateCache.get(rawTemplate);
2166
658
  templateName += Math.random().toString(36).substring(2, 7);
2167
- const decodedTemplate = templateCache.get(rawTemplate) ?? await generateTemplate(rawTemplate, loadTemplate_createJsModuleUrl, templateName + '-lepusCode');
659
+ const decodedTemplate = templateCache.get(rawTemplate) ?? await (0, dist.Yx)(rawTemplate, createJsModuleUrl, templateName + '-lepusCode');
2168
660
  templateCache.set(rawTemplate, decodedTemplate);
2169
661
  return decodedTemplate;
2170
662
  }
@@ -2823,8 +1315,8 @@ function getTextContentImpl(buffer, element, shadowrootTemplates) {
2823
1315
  buffer.push('"');
2824
1316
  }
2825
1317
  }
2826
- const partId = element[_attributes].get("l-part") ?? element[_attributes].get("l-uid");
2827
- buffer.push(' ', "l-part", '="', partId, '"');
1318
+ const partId = element[_attributes].get(dist.oZ) ?? element[_attributes].get(dist.SP);
1319
+ buffer.push(' ', dist.oZ, '="', partId, '"');
2828
1320
  buffer.push('>');
2829
1321
  const templateImpl = shadowrootTemplates[localName];
2830
1322
  if (templateImpl) {
@@ -2868,19 +1360,19 @@ const builtinTagTransformMap = {
2868
1360
  };
2869
1361
  OffscreenElement.prototype.toJSON = function() {
2870
1362
  return {
2871
- ssrID: this[_attributes].get("l-part") ?? this[_attributes].get("l-uid")
1363
+ ssrID: this[_attributes].get(dist.oZ) ?? this[_attributes].get(dist.SP)
2872
1364
  };
2873
1365
  };
2874
1366
  async function createLynxView(config) {
2875
1367
  const { template: rawTemplate, browserConfig, tagMap, initData, globalProps, overrideElementTemplates = {}, hydrateUrl, autoSize, injectStyles, lynxViewStyle, threadStrategy = 'all-on-ui', initI18nResources } = config;
2876
- const template = await loadTemplate_loadTemplate(rawTemplate, config.templateName);
1368
+ const template = await loadTemplate(rawTemplate, config.templateName);
2877
1369
  const { promise: firstPaintReadyPromise, resolve: firstPaintReady } = Promise.withResolvers();
2878
1370
  const mainWithBackgroundChannel = new MessageChannel();
2879
- const backgroundThreadRpc = new Rpc(mainWithBackgroundChannel.port1, 'background-thread');
1371
+ const backgroundThreadRpc = new web_worker_rpc_dist.C(mainWithBackgroundChannel.port1, 'background-thread');
2880
1372
  const offscreenDocument = new OffscreenDocument({
2881
1373
  onCommit: ()=>{}
2882
1374
  });
2883
- const i18nResources = new I18nResources();
1375
+ const i18nResources = new dist.gI();
2884
1376
  const events = [];
2885
1377
  const mtsVMContext = node_vm.createContext(node_vm.constants.DONT_CONTEXTIFY);
2886
1378
  Object.assign(mtsVMContext, {
@@ -2925,6 +1417,7 @@ async function createLynxView(config) {
2925
1417
  }
2926
1418
  });
2927
1419
  });
1420
+ const { prepareMainThreadAPIs } = await __webpack_require__.e("27").then(__webpack_require__.bind(__webpack_require__, "../web-mainthread-apis/dist/index.js"));
2928
1421
  const { startMainThread } = prepareMainThreadAPIs(backgroundThreadRpc, offscreenDocument, offscreenDocument, {
2929
1422
  globalWindow: mtsVMContext,
2930
1423
  loadScript,
@@ -2937,7 +1430,7 @@ async function createLynxView(config) {
2937
1430
  }, ()=>{}, {
2938
1431
  __AddEvent (element, eventName, eventData, eventOptions) {
2939
1432
  events.push([
2940
- Number(element.getAttribute("l-uid")),
1433
+ Number(element.getAttribute(dist.SP)),
2941
1434
  eventName,
2942
1435
  eventData,
2943
1436
  eventOptions
@@ -2972,7 +1465,7 @@ async function createLynxView(config) {
2972
1465
  buffer.push('<lynx-view url="', hydrateUrl, '" ssr ="', encodeURI(JSON.stringify(ssrDumpInfo)), '" ', 'thread-strategy="', threadStrategy, '"');
2973
1466
  if (autoSize) buffer.push(' height="auto" width="auto"');
2974
1467
  if (lynxViewStyle) buffer.push(' style="', lynxViewStyle, '"');
2975
- buffer.push('><template shadowrootmode="open">', '<style>', injectStyles, '\n', inShadowRootStyles.join('\n'), '</style>');
1468
+ buffer.push('><template shadowrootmode="open">', '<style>', injectStyles, '\n', dist.OE.join('\n'), '</style>');
2976
1469
  dumpHTMLString(buffer, offscreenDocument, elementTemplates);
2977
1470
  buffer.push('</template>');
2978
1471
  buffer.push('</lynx-view>');