-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgetfrontend.py
More file actions
1581 lines (1173 loc) · 61.3 KB
/
getfrontend.py
File metadata and controls
1581 lines (1173 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import base64
import hashlib
import html
import sys
import re
import time
import zipfile
import requests
import os
import json
import threading
import urllib3
from urllib.parse import urljoin, urlparse
from queue import Queue
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class Logger:
LOG = 1
DEBUG = 2
VERBOSE_DEBUG = 3
def __init__(self):
self.level = self.LOG
def write(self, level, *args, **kwargs):
if level <= self.level:
print(*args, **kwargs, file=sys.stderr)
def log(self, *args, **kwargs):
self.write(self.LOG, *args, **kwargs)
def debug(self, *args, **kwargs):
self.write(self.DEBUG, *args, **kwargs)
def vdebug(self, *args, **kwargs):
self.write(self.VERBOSE_DEBUG, *args, **kwargs)
log = Logger()
class SourceMapError(Exception):
pass
def normpath(path):
# os.path.normpath allows //, we can't since these are protocol-relative urls
path = os.path.normpath(path)
if path.startswith('//'):
path = path[1:]
return path
class FArchive:
def __init__(self):
self.files = {}
self.names = set()
self.effective_names = {}
def normalize_name(self, name):
name = normpath('/' + name)[1:]
return name
def get_unique_name(self, name):
base_name, ext = os.path.splitext(name)
counter = 2
while name in self.names:
name = f"{base_name}_{counter}{ext}"
counter += 1
self.names.add(name)
return name
def add_file(self, name, content):
name = self.normalize_name(name)
content_hash = hashlib.md5(content).hexdigest()
name_key = name + '//' + content_hash
if self.effective_names.get(name + '//' + content_hash):
# same name + existing content has means we can skip it
return
name = self.get_unique_name(name)
self.effective_names[name_key] = name
assert name not in self.files
self.files[name] = content
def write_to_file(self, wf):
with zipfile.ZipFile(wf, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
for name, content in self.files.items():
zf.writestr(name, content)
def save_to_directory(self, path):
os.makedirs(path, exist_ok=True)
for name, content in self.files.items():
file_path = os.path.join(path, name)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'wb') as f:
f.write(content)
def dump_to_stdout(self):
for name, content in self.files.items():
print(f"// {name}\n// [{len(content)}] bytes\n")
print(content.decode())
class Client:
def __init__(self, timeout: None | float | tuple[float, float] = (8, 16), cookies: dict | None = None, headers: dict | None = None):
self.timeout = timeout
self.sleep = 5
self.rs = requests.Session()
self.rs.verify = False
if cookies:
self.rs.cookies.update(cookies)
if headers:
self.rs.headers.update(headers)
def request(self, method, url, *args, **kwargs):
try:
while True:
try:
res = self.rs.request(method, url, *args, timeout=self.timeout, **kwargs)
if res.status_code in (408, 429, 500, 502, 503, 504):
log.log('retrying', url)
time.sleep(self.sleep)
continue
return res
except requests.exceptions.RequestException as e:
log.log('non-status request error, retrying', url, e)
time.sleep(self.sleep)
continue
except Exception as e:
log.log('non-status request exception', url, e)
return None
def get(self, *args, **kwargs):
return self.request('GET', *args, **kwargs)
class Fetcher:
def __init__(self, client: Client, n_workers):
self.input_queue = Queue()
self.output_queue = Queue()
self.client = client
self.queued_urls = set()
self.lock = threading.Lock()
self.pending_urls = 0
self.n_workers = n_workers
for _ in range(n_workers):
threading.Thread(target=self.worker).start()
def queue(self, url, *args):
# called from the main thread only
if url not in self.queued_urls:
self.pending_urls += 1
self.queued_urls.add(url)
self.input_queue.put([url, *args])
def get_response(self):
# called from the main thread only
if not self.pending_urls:
self.shutdown_workers()
return None
ret = self.output_queue.get()
self.pending_urls -= 1
return ret
def worker(self):
while True:
arg = self.input_queue.get()
if arg is None:
break
[url, *args] = arg
response = self.client.get(url) # doesn't throw
self.output_queue.put([url, response, *args])
def shutdown_workers(self):
for _ in range(self.n_workers):
self.input_queue.put(None)
def prepare_link(link):
if '?' in link:
link = link.split('?', 1)[0]
if '#' in link:
link = link.split('#', 1)[0]
return link
class Crawler:
def __init__(self, gf, root, save_prefix=''):
self.gf: GetFrontend = gf
self.save_prefix = save_prefix # this also affects url assets
self.root = root
self.webpack_chunk_formats = []
self.possible_webpack_chunk_ids = set()
def check_prefix(self, link):
if not self.gf.prefix_whitelist:
return True
for prefix in self.gf.prefix_whitelist:
if link.startswith(prefix):
return True
return False
def save_fetched_asset(self, path, content):
# path is an url
# this is meant for original assets
path = re.sub(r'^(https?:)//', r'\1', path)
return self.gf.save_asset(self.save_prefix + path, content)
def save_mapped_asset(self, path, content, origin_path):
return self.save_generated_asset(path, content, origin_path, 'mapped')
def save_unpacked_asset(self, path, content, origin_path):
return self.save_generated_asset(path, content, origin_path, 'unpacked')
def save_generated_asset(self, path, content, origin_path, label):
origin = re.search(r'https?://([^/]+)', origin_path).group(1)
self.gf.save_asset(f'{self.save_prefix}{label}@{origin}/{path}', content)
def queue(self, link, tag, *args):
self.gf.fetcher.queue(link, self, tag, *args)
def queue_link(self, link, tag=None, fallback=None):
if not self.check_prefix(link) and not fallback:
return
link = prepare_link(link)
if tag is None:
if link.endswith('.css') and not self.gf.skip_css:
tag = 'css'
elif re.search(r'\.m?[jt]sx?$', link):
tag = 'js'
elif self.gf.other_asset_extensions and link.endswith('.webmanifest'):
tag = 'webmanifest'
elif self.gf.other_asset_extensions and re.search(rf'{self.gf.asset_ext_pat}$', link, flags=re.IGNORECASE):
tag = 'asset'
if not tag and fallback:
tag = fallback
if tag:
self.queue(link, tag)
def handle_result(self, url, response, mode, *args):
response = self.gf.check_response(url, response)
if response:
if mode == 'dynamic':
content_type = response.headers.get('content-type', '')
if ';' in content_type:
content_type = content_type.split(';', 1)[0]
match content_type:
case "text/javascript" | "application/javascript" | "application/x-javascript":
mode = 'js'
case "text/css":
mode = 'css'
case "text/html" | "application/xhtml+xml" | "application/xml":
mode = 'page'
case _:
mode = 'asset'
log.debug('dynamic mode detected as', mode, 'for url', url)
match mode:
case "page":
self.handle_html_response(url, response)
case "nextjs":
self.handle_nextjs_manifest(url, response)
case "js":
self.handle_js(url, response)
case "css":
self.handle_css(url, response)
case "remote_entry_js":
self.handle_remote_module(url, response, *args)
case "webmanifest":
self.handle_webmanifest(url, response)
case "asset":
self.handle_asset(url, response)
def handle_js_data(self, content, path, skip_sourcemaps=False):
self.find_webpack_chunk_info(content, path)
self.find_federated_modules(content, path)
self.find_webpack_chunk_refs(content, path)
self.find_vite_chunks(content, path)
self.unpack_webpack_eval_sources(content, path)
if not skip_sourcemaps:
self.handle_content_sourcemaps(content, path)
# module scan, here we might encounter absolute links
for module_link in find_import_references(content, path):
self.queue_link(module_link)
self.find_imported_scripts(content, path)
self.find_workers(content, path)
self.find_manifests(content, path)
if self.gf.aggressive_mode:
self.run_aggressive_scan(content, path)
def handle_js(self, url, res):
res_headers = res.headers
res = self.gf.decode_response(res)
skip_sourcemaps = False
if self.gf.ignore_vendor:
last_part = url.rsplit('/', 1)[-1]
if re.match(r'(chunk[-.])?vendors?[-.]', last_part):
skip_sourcemaps = True
log.debug('skipping maps for', url, 'due to vendor detection')
self.handle_js_data(res, url, skip_sourcemaps=skip_sourcemaps)
should_save = True
if not skip_sourcemaps:
if self.handle_header_sourcemaps(res_headers, url):
should_save = False
# it's often the case that there wasn't a comment but a sourcemap exists
# we don't queue because we need the result here
if self.fetch_and_handle_srcmap(url + '.map'):
should_save = False
if should_save or self.gf.save_original_assets:
self.save_fetched_asset(url, res.encode())
def handle_css_data(self, content, path):
self.handle_content_sourcemaps(content, path)
url_pat = r'''(?<![a-zA-Z0-9$_])url\(\s*['"]?(?!data:)([^'")]+)'''
import_pat = rf'''@import(?:\s*['"]([^'"]+)['"]|\s+{url_pat})'''
for m in re.finditer(import_pat, content):
link = urljoin(path, m.group(1) or m.group(2))
log.log('adding css import', link)
self.queue_link(link, 'css')
if self.gf.other_asset_extensions:
for m in re.finditer(url_pat, content):
link = urljoin(path, m.group(1))
log.log('adding css url asset', link)
self.queue_link(link)
def handle_css(self, url, res):
res_headers = res.headers
res = self.gf.decode_response(res)
self.handle_css_data(res, url)
should_save = True
if self.handle_header_sourcemaps(res_headers, url):
should_save = False
if self.fetch_and_handle_srcmap(url + '.map'):
should_save = False
if should_save or self.gf.save_original_assets:
self.save_fetched_asset(url, res.encode())
def handle_header_sourcemaps(self, headers, path):
header_map = headers.get('SourceMap') or headers.get('X-SourceMap')
if header_map and not self.gf.no_header_sourcemaps:
log.debug('found SourceMap header for', path)
if self.fetch_and_handle_srcmap(urljoin(path, header_map)):
return True
def handle_content_sourcemaps(self, content, path, inline_only=False):
had_sourcemap = False
# url sourcemaps.. we normally append .map
# and normally there should be only one
# otherwise that's probably spam (like nonexisting files inside eval)
sourcemap_urls = re.findall(r'sourceMappingURL=(?!data:application/json)([^\s?#*]+)', content)
if not inline_only and (len(sourcemap_urls) < 2 or self.gf.all_srcmap_urls):
for src_map in sourcemap_urls:
link = urljoin(path, src_map)
if self.fetch_and_handle_srcmap(link):
had_sourcemap = True
json_map_contents = []
# iterate inline sourcemaps
for m in re.finditer(r'sourceMappingURL=data:application/json;(?:charset=([^;]+);)?base64,([A-Za-z0-9/+]+)', content):
charset = m.group(1) or 'utf-8'
map_content = base64.b64decode(m.group(2) + '==').decode(charset)
json_map_contents.append(map_content)
# iterate JSON-embedded sourcemaps (example observed in css-loader)
if '{"version":3,"sources":[' in content and '"sourcesContent":[' in content:
str_pat_part = r'"(?:(?:\\.|[^"\\]+)*)"'
str_arr_pat_part = rf'\[(?:{str_pat_part},?)*\]'
for m in re.finditer(rf'\{"{"}"version":3,"sources":{str_arr_pat_part}(?:,{str_pat_part}:(?:{str_pat_part}|{str_arr_pat_part}))+\{"}"}', content):
log.debug(f'found embedded source map at {path}')
map_content = m.group(0)
json_map_contents.append(map_content)
for map_content in json_map_contents:
try:
data = json.loads(map_content)
self.handle_srcmap_data(data, path)
had_sourcemap = True
except (json.decoder.JSONDecodeError, SourceMapError) as e:
log.debug(f'warn: inline sourcemap at {path} was not correct', e)
return had_sourcemap
def handle_nextjs_manifest(self, url, res):
res = self.gf.decode_response(res)
base = url[:url.index('/_next/') + len('/_next/')]
if self.gf.save_original_assets:
self.save_fetched_asset(url, res.encode())
res = res.replace('\\u002F', '/')
for m in re.finditer(r'''"(static/(?:chunks|css)/[^"]+\.(m?jsx?|css))([#?][^"]*)?"''', res):
link = urljoin(base, m.group(1))
log.log('adding nextjs chunk from manifest', link)
self.queue_link(link)
if self.gf.aggressive_mode:
self.run_aggressive_scan(res, url)
def handle_webmanifest(self, url, res):
res = self.gf.decode_response(res)
if not res:
return
self.save_fetched_asset(url, res.encode())
self.run_aggressive_scan(res, url)
def handle_asset(self, url, res):
self.save_fetched_asset(url, res.content)
def fetch_and_handle_srcmap(self, path):
if path in self.gf.fetched_sourcemaps:
return self.gf.fetched_sourcemaps[path]
ok = True
url = urljoin(self.root, path)
response = self.gf.get_url(url)
if not response:
log.log(f'no source map at {path}')
self.gf.fetched_sourcemaps[path] = False
return
try:
try:
data = response.json()
except Exception:
raise SourceMapError('not json')
self.handle_srcmap_data(data, path)
except SourceMapError as e:
log.log(f'source map at {path} error:', e)
ok = False
self.gf.fetched_sourcemaps[path] = ok
return ok
def _prepare_mapped_asset(self, name, content, real_dir=None):
if name.startswith('webpack://'):
name = name[len('webpack://'):]
# not sure if we could normalize the name..
name = re.sub(r'(\/|^)\.(?=\/|$)', r'', name)
name = re.sub(r'(\/|^)\.\.(?=\/|$)', '\1_', name)
if name.startswith('/'):
name = name[1:]
if '/' not in name and real_dir:
log.debug('using real_dir prefix', real_dir)
name = real_dir + '/' + name
name = re.sub(r'//+', r'/', name)
if '?' in name:
left, right = name.split('?', 1)
if '/' in right or '?' in right:
log.debug('unusual name', name)
right = '_' + re.sub(r'[^a-zA-Z0-9_.-]', '_', right)
base_name, ext = os.path.splitext(left)
name = base_name + right + ext
else:
base_name, ext = os.path.splitext(name)
# content processing, for example unpack angular .html
content = self.process_src_asset(name, ext, content)
return name, content
def handle_srcmap_data(self, data, origin):
real_dir = None
try:
try:
if len(data['sources']) != len(data['sourcesContent']):
log.debug('warn: invalid source map sources length in', origin)
except KeyError:
raise SourceMapError('no sources content')
if 'file' in data and '!.' in data['file']:
last_part = data['file'].rsplit('!.', 1)[-1]
file_part = last_part.split('?', 1)[0]
real_dir = os.path.dirname(file_part)
if real_dir.startswith('/'):
real_dir = real_dir[1:]
# for webpack, this might be a chain, but it could give us the idea
# of the original file location, as sometimes the location in
# ['sources'] might not be complete
for x in range(min(len(data['sources']), len(data['sourcesContent']))):
if not data['sourcesContent'][x]:
# yeah, it can happen
continue
name = data['sources'][x]
content = data['sourcesContent'][x]
# ignore names here
if name.endswith('/'):
log.debug('skipping source map entry: name', name, 'ends with a slash, content is', content)
continue
name, content = self._prepare_mapped_asset(name, content, real_dir=real_dir)
# nested source maps? not practically useful
if self.gf.extract_nested_sourcemaps:
self.handle_content_sourcemaps(content, origin, True)
self.save_mapped_asset(name, content.encode(), origin)
except (TypeError, ValueError) as e:
raise SourceMapError(f'invalid data {e}')
def process_src_asset(self, name, ext, content):
# currently we only unpack html templates here
if ext == '.html':
if m := re.match(r'^(?:module\.exports\s*=\s*|export default\s+)(".+");?\s*(\n\s*//[^\n]*)*$', content):
try:
json_content = json.loads(m.group(1))
log.debug('replacing html', name)
return json_content
except json.decoder.JSONDecodeError:
pass
return content
def find_workers(self, content, current_path):
worker_pat = r'''(?:[^a-zA-Z0-9$_]new\s+(?:Shared)?Worker|navigator\.serviceWorker\.register)\s*\(\s*(?!data:)['"]([^'"]+)['"]\s*[,)]'''
for m in re.finditer(worker_pat, content):
link = urljoin(self.root, m.group(1))
log.log('adding worker', link)
self.queue_link(link, tag='js')
def find_imported_scripts(self, content, current_path):
pat = r'''(?:^|[^a-zA-Z0-9_$])importScripts\s*\(\s*((?:['"][^'"]+['"],?\s*)+)\)'''
for m in re.finditer(pat, content):
for mv in re.finditer(r'''['"]([^'"]+)['"]''', m.group(1)):
link = urljoin(current_path, mv.group(1))
log.log('adding imported script', link)
self.queue_link(link, tag='js')
def find_manifests(self, content, current_path):
# search for remix manifest
if '/manifest-' in current_path:
if content.startswith('window.__remixManifest={'):
for m in re.finditer(r'"(/[^"]+\.js)(?:[?#][^"]*)?', content):
link = urljoin(self.root, m.group(1))
log.log('adding remix link', link)
self.queue_link(link)
def find_vite_chunks(self, content, current_path):
# limited vite support, we rely on duplication to find the base path..
# .js files are picked up by imports, but .css files seem to only be here
vite_file_pat = r'''['"]([^'"]+)['"]'''
vite_pat = rf'(?:__vite__fileDeps|__vite__mapDeps\.viteFileDeps)\s*=\s*\[\s*((?:{vite_file_pat},?\s*)+)\]'
had_vite_deps = False
vite_deps = []
for m in re.finditer(vite_pat, content):
for mf in re.finditer(vite_file_pat, m.group(1)):
had_vite_deps = True
dep = mf.group(1)
if dep.startswith('.'):
chunk_path = urljoin(current_path, dep)
log.log('adding vite2 rel', chunk_path)
self.queue_link(chunk_path)
else:
vite_deps.append(dep)
vite_base = None
if vite_deps:
# process deps that have base
vite_base = None
# we need at least one import to find the base path
if m := re.search(rf'''\(\s*\(\)\s*=>\s*import\({vite_file_pat}\),\s*__vite__mapDeps\(\[(\d+)''', content):
proper_path = urljoin(current_path, m.group(1))
dep_path = vite_deps[int(m.group(2))]
assert proper_path.endswith(dep_path)
vite_base = proper_path[:-len(dep_path)]
log.debug('vite base', vite_base)
else:
log.debug('failed to find vite base path')
vite_base = self.root
if vite_base:
for dep in vite_deps:
chunk_path = urljoin(vite_base, dep)
log.log('adding vite', chunk_path)
self.queue_link(chunk_path)
elif not had_vite_deps:
# the older variant with no __vite__mapDeps
# here we use the first import to derive the base path
for m in re.finditer(rf'''\(\s*\(\)\s*=>\s*import\({vite_file_pat}\),\s*\[\s*(({vite_file_pat},?\s*)+)''', content):
deps = []
for dm in re.finditer(vite_file_pat, m.group(2)):
chk = dm.group(1)
if chk.startswith('.'):
chunk_path = urljoin(current_path, chk)
log.log('adding vite1 rel', chunk_path)
self.queue_link(chunk_path)
else:
deps.append(chk)
if not deps:
continue
# now we have those that require a base
if not vite_base:
proper_path = urljoin(current_path, m.group(1))
dep_path = deps[0]
if not proper_path.endswith(dep_path):
# that's not vite...
continue
vite_base = proper_path[:-len(dep_path)]
log.debug('vite base2', vite_base)
for dep in deps:
chunk_path = urljoin(vite_base, dep)
log.log('adding vite2', chunk_path)
self.queue_link(chunk_path)
def unpack_webpack_eval_sources(self, content, current_path):
for m in re.finditer(r'''[\n{]eval\s*\(\s*(?:"((?:\\.|[^"\\])+)"|'((?:\\.|[^'\\])+)')\s*\)''', content):
src = ''
if src := m.group(2): # transform single quotes so we can decode as json
src = src.replace("\\'", "'").replace('"', '\\"')
else:
src = m.group(1)
if '//# sourceURL=' not in src:
continue
src = json.loads('"' + src + '"')
if m := re.search(r'\n//# sourceURL=([^\n?]+)[?]?', src):
name = m.group(1)
content = src[:m.start()]
name, content = self._prepare_mapped_asset(name, content)
log.debug('unpacking eval asset', name, 'from', current_path)
self.save_unpacked_asset(name, content.encode(), current_path)
def add_webpack_chunk_format(self, fmt):
self.webpack_chunk_formats.append([fmt, set()])
def add_possible_webpack_chunk_id(self, chunk_id):
self.possible_webpack_chunk_ids.add(chunk_id)
def queue_possible_webpack_chunks(self):
for resolve, queued in self.webpack_chunk_formats:
for chunk_id in self.possible_webpack_chunk_ids - queued:
self.queue_link(resolve(chunk_id))
queued.update(self.possible_webpack_chunk_ids)
def find_webpack_chunk_info(self, res, current_path):
# todo: this vs remote? what if we encounter remoteEntry.js
# this works since 2015
is_webpack_chunk_runtime = 'ChunkLoadError' in res or "'Loading chunk '" in res or '"Loading chunk "' in res or 'Automatic publicPath is not supported in this browser' in res
if not is_webpack_chunk_runtime:
return
res = res.replace('\\u002F', '/')
if current_path in self.gf.public_path_map:
public_path = self.gf.public_path_map[current_path]
else:
public_path = ''
# note for paths like someVariable + sth, we assume someVariable is empty
for m in re.finditer(r'''(?:\w|__webpack_require__)\.p\s*=(\s*[\w.]+\s*\+)?\s*(?P<quot>['"])(?P<path>[^'"]*)(?P=quot)\s*[,;})]''', res):
# we pick the last one
public_path = m.group('path')
if 'Automatic publicPath is not supported in this browser' in res:
# in one case it was relative to the script.. is it always true for automatic publicpath?
# EDIT: well, no... need more data
public_path = urljoin(current_path, 'abc')[:-3]
# public_path is sometimes empty.. in that case it won't work with urljoin, we assume the root folder is used
if public_path == '':
public_path = urljoin(self.root, 'abc')[:-3]
# relative to root, not the script
public_path = urljoin(self.root, public_path)
log.debug('webpack public path for', current_path, 'is', public_path)
# first we need some cleanup, clean /******/ then clean // comments
wr = re.sub(r'/\*{3,}/', ' ', res)
# be careful not to trip strings like https://
wr = re.sub(r'\n\s*//.*', ' ', wr)
# resolve full hashes
def make_hash_repl(target):
def hash_repl(m):
ret = target
if maxlen := m.group('maxlen'):
log.debug('maxlen', maxlen)
ret = target[:int(maxlen)]
return '"' + ret + '"'
return hash_repl
hash_maxlen_pat = r'(?:\.(?:slice|substr(?:ing)?)\(\s*0,\s*(?P<maxlen>\d+)\))?'
if 'hotCurrentHash' in wr and (full_hash := re.search(r'[^a-zA-Z0-9$_]hotCurrentHash\s*=\s*"(?P<hash>[a-fA-F0-9]+)"', wr)):
full_hash = full_hash.group('hash')
log.debug('hotcurrenthash', full_hash)
wr = re.sub(rf'hotCurrentHash{hash_maxlen_pat}', make_hash_repl(full_hash), wr)
last_match = None
for m in re.finditer(r'''(__webpack_require__|\w)\.h\s*=\s*(?:function\s*\(\s*\)\s*\{\s*return(?![a-zA-Z0-9$_])|\(\s*\)\s*=>(?:\s*\{\s*return(?![a-zA-Z0-9$_]))?)\s*(?:\(\s*)?['"](?P<hash>[^'"]+)['"]''', wr):
last_match = m
if m := last_match:
full_hash = m.group('hash')
log.debug('replacing full hash', full_hash)
wr = re.sub(rf'(?<![a-zA-Z0-9_$])(__webpack_require__|\w)\.h\(\){hash_maxlen_pat}', make_hash_repl(full_hash), wr)
wr = re.sub(r'"\s*\+\s*"', '', wr) # clean concatenated strings, must be done also after replacing hashes
# also need scoring for this "big" part
r1v_func = r'(?:function(?:\s+\w+|\s*)\(\s*\w+\s*\)\s*\{\s*|\(?\s*?\w+\s*\)?\s*=>\s*(?:\{\s*|\(\s*)?)'
r1v_func_start = r'(?:function(?:\s+\w+|\s*)\(\s*\w+\s*\)\s*\{\s*|=>\s*(?:\{\s*|\(\s*)?)' # optimized
static_path_param = r'''['"]\s*\+\s*\w+\s*\+\s*['"]'''
static_path_inner_pat = rf'''[^'"]+(?:{static_path_param}[^'"]+)?'''
static_multi_ids_pat = r'''\{(?:(?:\d+(?:e\d+)?|['"][^'"]+['"]):1,?)+\}\s*\[\w+\]'''
static_chunk_pat1 = rf'''if\s*\((?:\w+\s*===\s*(?P<static1_id>\d+(?:e\d+)?|['"][^'"]+['"])|(?P<static1_ids>{static_multi_ids_pat}))\)\s*return\s*['"](?P<static1_path>{static_path_inner_pat})['"]\s*;\s*'''
static_chunk_pat2 = rf'''(?:(?P<static2_id>\d+(?:e\d+)?|['"][^'"]+['"])===\w+|(?P<static2_ids>{static_multi_ids_pat}))\?['"](?P<static2_path>{static_path_inner_pat})['"]:'''
start_v1 = rf'(?:{r1v_func_start}(return(?![a-zA-Z0-9$_])\s*\(?\s*)?|\.src\s*=\s*(?:\([^;]{"{,5}"})?)(?:\w|__webpack_require__)\.p\s*\+'
# return is possible in two locations depending on static_chunks variant
start_v2 = rf'\.u\s*=\s*{r1v_func}(return(?![a-zA-Z0-9$_])\s*\(?\s*)?(?P<static_chunks>(?:{static_chunk_pat1}|{static_chunk_pat2})+)?(return(?![a-zA-Z0-9$_])\s*\(?\s*)?'
prefix_pat = r'''['"](?P<prefix>[^"' ]*)['"]'''
# premap can be identity or in a compact form
# but... there might be no premap.. we saw this with federated modules
premap_pat = r'''(?:\(\(?\s*\{(?P<premap>[^{}]*)\}\)?\s*\[(?:\s*\w+\s*=)?\s*\w+\s*\]\s*\|\|\s*\w+\s*\)|\{(?P<premap_e>[^{}]*)\}\s*\[(?:\s*\w+\s*=)?\s*\w+\s*\]|\((?:(?P<cpm_id>\d+)\s*===\s*\w+|\w+\s*===\s*(?P<cpm_id_2>\d+))\s*\?\s*"(?P<cpm_value>[^"]+)"\s*:\s*\w+\)|(?P<identity>\w+))'''
# exhaustive maps
map_pat = r'''(?:['"](?P<sep>[^"' ]*)['"]\s*\+\s*)?\(?\{(?P<map>[^{}]*)\}\)?\s*\[(?:\w+\s*=\s*)?\w+\]'''
qmap_pat_common = r'''\?\w+=)['"]\s*\+\s*\{(?P<qmap>[^{}]*)\}\s*\[(?:\w+\s*=\s*)?\w+\]\s*[,;]'''
qmap_pat = r'''['"](?P<qmap_sep>[^"' ]*\.m?jsx?''' + qmap_pat_common
qmap_css_pat = r'''['"](?P<qmap_sep>[^"' ]*\.css''' + qmap_pat_common
suffix_pat = r'''(?:['"](?P<suffix>[^"']*\.m?jsx?)(?:\?t=\d+)?['"]\s*[^+]|(?P<void_suffix>(?<=:)void\(?\s*0\s*\)?|undefined))'''
def parse_chunk_match(m, search_static=False):
prefix = m.group('prefix') or ''
suffix = m.group('suffix') or ''
known_ids = set()
exhaustive = False
# premap should be constructed for the chunk format...
# either from parse chunkmap if a dict, or from cm map
# or identity
# empty premap is not truthy but it's not "None", can't use "or"
if m.group('premap_e') is not None:
pm = m.group('premap_e')
exhaustive = True
else:
pm = m.group('premap')
if pm is not None:
premap = parse_chunkmap(pm)
known_ids.update(premap.keys())
elif cid := m.group('cpm_id') or m.group('cpm_id_2'):
premap = {cid: m.group('cpm_value')}
known_ids.add(cid)
elif m.group('identity'):
premap = {}
else:
premap = None
cmap = m.group('map') or m.group('qmap')
if cmap:
cmap = parse_chunkmap(cmap)
known_ids.update(cmap.keys())
exhaustive = True
if m.group('qmap'):
sep = m.group('qmap_sep')
else:
sep = m.group('sep') or ''
static_map = {}
if search_static:
if sp := m.group('static_chunks'):
for sm in re.finditer(rf'{static_chunk_pat1}|{static_chunk_pat2}', sp):
chunk_ids = []
if single_id := sm.group('static1_id') or sm.group('static2_id'):
chunk_ids.append(parse_chunk_id(single_id))
else:
ids = sm.group('static1_ids') or sm.group('static2_ids')
for scm in re.finditer(r'''(\d+(?:e\d+)?|['"][^'"]+['"]):1''', ids):
chunk_ids.append(parse_chunk_id(scm.group(1)))
path_src = sm.group('static1_path') or sm.group('static2_path')
for chunk_id in chunk_ids:
chunk_path = re.sub(static_path_param, chunk_id, path_src)
log.debug('static path', chunk_path)
static_map[chunk_id] = chunk_path
known_ids.add(chunk_id)
log.debug('static path map', static_map)
def resolve(chunk_id):
if chunk_id in static_map:
chunk_path = static_map[chunk_id]
else:
chunk_path = premap.get(chunk_id, chunk_id) if premap is not None else ''
chunk_path += sep + (cmap[chunk_id] if cmap else '')
chunk_path = prefix + chunk_path + suffix
return urljoin(public_path, chunk_path)
depends_on_id = static_map or premap is not None or cmap
return depends_on_id, known_ids, exhaustive, resolve
has_exhaustive_chunks = False
pattern = rf'(?:{start_v1}|{start_v2})\s*(?:{prefix_pat}\s*\+\s*)?(?:{premap_pat}\s*\+\s*)?(?:{qmap_pat}|(?:{map_pat}\s*\+\s*)?{suffix_pat})'
last_match = None
for m in re.finditer(pattern, wr):
last_match = m
if m := last_match:
depends_on_id, known_ids, exhaustive, resolve = parse_chunk_match(m, True)
log.debug('webpack match result', current_path, known_ids)
# the js version should depend on the id somehow..
if not depends_on_id:
log.log('webpack: no premap and no map', current_path)
if exhaustive:
has_exhaustive_chunks = True
# here we don't add the chunk format deliberately
for chunk_id in known_ids:
self.queue_link(resolve(chunk_id))
else:
self.add_webpack_chunk_format(resolve)
for chunk_id in known_ids:
self.add_possible_webpack_chunk_id(chunk_id)
self.queue_possible_webpack_chunks()
if not self.gf.skip_css:
suffix_css_pat = r'''['"](?P<suffix>[^"']*\.css)(?:\?t=\d+)?['"]\s*[^+]'''
css_pattern = rf'(?P<prelude>\.miniCssF\s*=\s*{r1v_func}(return(?![a-zA-Z0-9$_])\s*)?|(?:for\s*\(|\{"{"})\s*var \w+\s*=)\s*(?:{prefix_pat}\s*\+\s*)?(?:{premap_pat}\s*\+\s*)?(?:{qmap_css_pat}|(?:{map_pat}\s*\+\s*)?{suffix_css_pat})'
last_match = None
for m in re.finditer(css_pattern, wr):
last_match = m
# css chunks.. they're always exhaustive (a subset of js chunks?)
if m := last_match:
has_css_map = None
# try to find the 01 map, a subset of emap
if 'var ' in m.group('prelude'):
# in this case we match the map.. backwards
if m2 := re.search(r'''(?:[;,]|\]\s*\w+\s*\[)\}\s*((?:,?1\s*:\s*(?:\d+(?:e\d+)?|["'][^'"]*['"])\s*)+)\{''', wr[:m.start()][::-1]):
has_css_map = m2.group(1)[::-1]
else:
# the map is inside the minicss
if m2 := re.search(r'''\.miniCss\s*=\s*(?:function|\().*?\{(\s*((?:\d+(?:e\d+)?|["'][^'"]*['"])\s*:\s*1,?\s*)+)\}''', wr, flags=re.DOTALL):
has_css_map = m2.group(1)
if has_css_map is not None:
cstr = has_css_map
has_css_map = set()
for cid in re.findall(r'''([a-zA-Z0-9_$]+|['"][^'"]+['"])\s*:\s*1,?''', cstr):
has_css_map.add(parse_chunk_id(cid))
depends_on_id, known_ids, exhaustive, resolve = parse_chunk_match(m)
log.debug('css chunks', has_css_map, known_ids)
if not depends_on_id and not has_css_map:
# corner case: only one chunk... :D
has_css_map = set([''])
if has_css_map is None:
# basically this.. "should not happen"
# might happen if css chunks not used
log.log('webpack: no css bitmap', current_path)
has_css_map = set()
for chunk_id in known_ids:
has_css_map.add(chunk_id)
for chunk_id in has_css_map:
self.queue_link(resolve(chunk_id))
if not has_exhaustive_chunks:
# these are all inside the webpack runtime, not other chunks
# preload/prefetch maps
chunk_id_pat = r'\d+(?:e\d+)?|"[^"]+"' # map keys might be strings