1111it appropriately
1212- a specific JS file (provided in `statics` folder) for JS modules is included in the
1313ZIM at `_zim_static/__wb_module_decl.js`
14+
15+ This code is based on https://github.com/webrecorder/wabac.js/blob/main/src/rewrite/jsrewriter.ts
16+ Last backport of upstream changes is from Sept 13, 2025
17+ Commit 6dd2d9ae664cfcd2ea8637d7d6c7ed7a0ca332a0
1418"""
1519
1620import re
2933from zimscraperlib .rewriting .url_rewriting import ArticleUrlRewriter , ZimPath
3034
3135# The regex used to rewrite `import ...` in module code.
32- IMPORT_MATCH_RX = re .compile (
33- r"""^ \s*?import (?:['"\s]*(?:[\w*${}\s,]+from\s*)?['"\s]?['"\s])(?:.*?)['"\s]""" ,
36+ IMPORT_EXPORT_MATCH_RX = re .compile (
37+ r"""(^|;) \s*?(?:im|ex)port (?:['"\s]*(?:[\w*${}\s,]+from\s*)?['"\s]?['"\s])(?:.*?)['"\s]""" ,
3438)
3539
3640# A sub regex used inside `import ...` rewrite to rewrite http url imported
37- IMPORT_HTTP_RX = re .compile (
38- r"""(import (?:['"\s]*(?:[\w*${}\s,]+from\s*)?['"\s]?['"\s]))((?:https?|[./]).*?)(['"\s])""" ,
41+ IMPORT_EXPORT_HTTP_RX = re .compile (
42+ r"""((?:im|ex)port (?:['"\s]*(?:[\w*${}\s,]+from\s*)?['"\s]?['"\s]))((?:https?|[./]).*?)(['"\s])""" ,
3943)
4044
4145# This list of global variables we want to wrap.
@@ -153,7 +157,10 @@ def create_js_rules() -> list[TransformationRule]:
153157
154158 return [
155159 # rewriting `eval(...)` - invocation
156- (re .compile (r"(?:^|\s)\beval\s*\(" ), replace_prefix_from (eval_str , "eval" )),
160+ (
161+ re .compile (r"(?<!static)(?<!function)(?<!})(?:^|\s)\beval\s*\(" ),
162+ replace_prefix_from (eval_str , "eval" ),
163+ ),
157164 (re .compile (r"\([\w]+,\s*eval\)\(" ), m2str (lambda _ : f" { eval_str } " )),
158165 # rewriting `x = eval` - no invocation
159166 (re .compile (r"[=]\s*\beval\b(?![(:.$])" ), replace ("eval" , "self.eval" )),
@@ -162,7 +169,7 @@ def create_js_rules() -> list[TransformationRule]:
162169 (re .compile (r"\.postMessage\b\(" ), add_prefix (".__WB_pmw(self)" )),
163170 # rewriting `location = ` to custom expression `(...).href =` assignement
164171 (
165- re .compile (r"(?:^|[^$.+*/%^-])\s?\blocation\b\s*[=]\s*(?![\s\d=])" ),
172+ re .compile (r"(?:^|[^$.+*/%^-])\s?\blocation\b\s*[=]\s*(?![\s\d=> ])" ),
166173 add_suffix_non_prop (check_loc ),
167174 ),
168175 # rewriting `return this`
@@ -312,8 +319,8 @@ def sub_funct(match: re.Match[str]) -> str:
312319 f"{ match .group (3 )} "
313320 )
314321
315- return IMPORT_HTTP_RX .sub (sub_funct , m_object [0 ])
322+ return IMPORT_EXPORT_HTTP_RX .sub (sub_funct , m_object [0 ])
316323
317324 return func
318325
319- return (IMPORT_MATCH_RX , rewrite_import ())
326+ return (IMPORT_EXPORT_MATCH_RX , rewrite_import ())
0 commit comments