22 return 0 if x
in (None, JS_Undefined
) else x
25 return op(zeroise(a
), zeroise(b
)) & 0xffffffff
33 if JS_Undefined
in (a
, b
):
35 return op(a
or 0, b
or 0)
41 if JS_Undefined
in (a
, b
) or not (a
and b
):
43 return (a
or 0) / b
if b
else float('inf')
47 if JS_Undefined
in (a
, b
) or not b
:
54 return 1 # even 0 ** 0 !!
55 elif JS_Undefined
in (a
, b
):
63 if {a, b}
<= {None, JS_Undefined}
:
73 if JS_Undefined
in (a
, b
):
75 return op(a
or 0, b
or 0)
80 def _js_ternary(cndn
, if_true
=True, if_false
=False):
81 """Simulate JS's ternary operator (cndn?if_true:if_false)"""
82 if cndn
in (False, None, 0, '', JS_Undefined
):
84 with contextlib
.suppress(TypeError):
85 if math
.isnan(cndn
): # NB: NaN cannot be checked by membership
90 # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
91 _OPERATORS
= { # None => Defined in JSInterpreter._operator
97 '|': _js_bit_op(operator
.or_
),
98 '^': _js_bit_op(operator
.xor
),
99 '&': _js_bit_op(operator
.and_
),
102 '!==': operator
.is_not
,
103 '==': _js_eq_op(operator
.eq
),
104 '!=': _js_eq_op(operator
.ne
),
106 '<=': _js_comp_op(operator
.le
),
107 '>=': _js_comp_op(operator
.ge
),
108 '<': _js_comp_op(operator
.lt
),
109 '>': _js_comp_op(operator
.gt
),
111 '>>': _js_bit_op(operator
.rshift
),
112 '<<': _js_bit_op(operator
.lshift
),
114 '+': _js_arith_op(operator
.add
),
115 '-': _js_arith_op(operator
.sub
),
117 '*': _js_arith_op(operator
.mul
),
123 _COMP_OPERATORS
= {'===', '!==', '==', '!=', '<=', '>=', '<', '>'}
125 _NAME_RE
= r
'[a-zA-Z_$][\w$]*'
126 _MATCHING_PARENS
= dict(zip(*zip('()', '{}', '[]')))
134 class JS_Break(ExtractorError
):
136 ExtractorError
.__init
__(self
, 'Invalid break')
139 class JS_Continue(ExtractorError
):
141 ExtractorError
.__init
__(self
, 'Invalid continue')
144 class JS_Throw(ExtractorError
):
145 def __init__(self
, e
):
147 ExtractorError
.__init
__(self
, f
'Uncaught exception {e}')
150 class LocalNameSpace(collections
.ChainMap
):
151 def __setitem__(self
, key
, value
):
152 for scope
in self
.maps
:
156 self
.maps
[0][key
] = value
158 def __delitem__(self
, key
):
159 raise NotImplementedError('Deleting is not supported')
164 ENABLED
= False and 'pytest' in sys
.modules
167 def write(*args
, level
=100):
168 write_string(f
'[debug] JS: {" " * (100 - level)}'
169 f
'{" ".join(truncate_string(str(x), 50, 50) for x in args)}\n')
172 def wrap_interpreter(cls
, f
):
173 def interpret_statement(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
):
174 if cls
.ENABLED
and stmt
.strip():
175 cls
.write(stmt
, level
=allow_recursion
)
177 ret
, should_ret
= f(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
)
178 except Exception as e
:
180 if isinstance(e
, ExtractorError
):
182 cls
.write('=> Raises:', e
, '<-|', stmt
, level
=allow_recursion
)
184 if cls
.ENABLED
and stmt
.strip():
185 cls
.write(['->', '=>'][should_ret
], repr(ret
), '<-|', stmt
, level
=allow_recursion
)
186 return ret
, should_ret
187 return interpret_statement
191 __named_object_counter
= 0
194 # special knowledge: Python's re flags are bitmask values, current max 128
195 # invent new bitmask values well above that for literal parsing
196 # TODO: new pattern class to execute matches with these flags
197 'd': 1024, # Generate indices for substring matches
198 'g': 2048, # Global search
199 'i': re
.I
, # Case-insensitive search
200 'm': re
.M
, # Multi-line search
201 's': re
.S
, # Allows . to match newline characters
202 'u': re
.U
, # Treat a pattern as a sequence of unicode code points
203 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
206 _EXC_NAME
= '__yt_dlp_exception__'
208 def __init__(self
, code
, objects
=None):
209 self
.code
, self
._functions
= code
, {}
210 self
._objects
= {} if objects
is None else objects
212 class Exception(ExtractorError
):
213 def __init__(self
, msg
, expr
=None, *args
, **kwargs
):
215 msg
= f
'{msg.rstrip()} in: {truncate_string(expr, 50, 50)}'
216 super().__init
__(msg
, *args
, **kwargs
)
218 def _named_object(self
, namespace
, obj
):
219 self
.__named
_object
_counter
+= 1
220 name
= f
'__yt_dlp_jsinterp_obj{self.__named_object_counter}'
221 namespace
[name
] = obj
225 def _regex_flags(cls
, expr
):
229 for idx
, ch
in enumerate(expr
):
230 if ch
not in cls
._RE
_FLAGS
:
232 flags |
= cls
._RE
_FLAGS
[ch
]
233 return flags
, expr
[idx
+ 1:]
236 def _separate(expr
, delim
=',', max_split
=None):
237 OP_CHARS
= '+-*/%&|^=<>!,;{}:'
240 counters
= {k: 0 for k in _MATCHING_PARENS.values()}
241 start
, splits
, pos
, delim_len
= 0, 0, 0, len(delim
) - 1
242 in_quote
, escaping
, after_op
, in_regex_char_group
= None, False, True, False
243 for idx
, char
in enumerate(expr
):
244 if not in_quote
and char
in _MATCHING_PARENS
:
245 counters
[_MATCHING_PARENS
[char
]] += 1
246 elif not in_quote
and char
in counters
:
248 elif not escaping
and char
in _QUOTES
and in_quote
in (char
, None):
249 if in_quote
or after_op
or char
!= '/':
250 in_quote
= None if in_quote
and not in_regex_char_group
else char
251 elif in_quote
== '/' and char
in '[]':
252 in_regex_char_group
= char
== '['
253 escaping
= not escaping
and in_quote
and char
== '\\'
254 after_op
= not in_quote
and char
in OP_CHARS
or (char
.isspace() and after_op
)
256 if char
!= delim
[pos
] or any(counters
.values()) or in_quote
:
259 elif pos
!= delim_len
:
262 yield expr
[start
: idx
- delim_len
]
263 start
, pos
= idx
+ 1, 0
265 if max_split
and splits
>= max_split
:
270 def _separate_at_paren(cls
, expr
, delim
):
271 separated
= list(cls
._separate
(expr
, delim
, 1))
272 if len(separated
) < 2:
273 raise cls
.Exception(f
'No terminating paren {delim}', expr
)
274 return separated
[0][1:].strip(), separated
[1].strip()
276 def _operator(self
, op
, left_val
, right_expr
, expr
, local_vars
, allow_recursion
):
277 if op
in ('||', '&&'):
278 if (op
== '&&') ^
_js_ternary(left_val
):
279 return left_val
# short circuiting
281 if left_val
not in (None, JS_Undefined
):
284 right_expr
= _js_ternary(left_val
, *self
._separate
(right_expr
, ':', 1))
286 right_val
= self
.interpret_expression(right_expr
, local_vars
, allow_recursion
)
287 if not _OPERATORS
.get(op
):
291 return _OPERATORS
[op
](left_val
, right_val
)
292 except Exception as e
:
293 raise self
.Exception(f
'Failed to evaluate {left_val!r} {op} {right_val!r}', expr
, cause
=e
)
295 def _index(self
, obj
, idx
, allow_undefined
=False):
299 return obj
[int(idx
)] if isinstance(obj
, list) else obj
[idx
]
300 except Exception as e
:
303 raise self
.Exception(f
'Cannot get index {idx}', repr(obj
), cause
=e
)
305 def _dump(self
, obj
, namespace
):
307 return json
.dumps(obj
)
309 return self
._named
_object
(namespace
, obj
)
311 @Debugger.wrap_interpreter
312 def interpret_statement(self
, stmt
, local_vars
, allow_recursion
=100):
313 if allow_recursion
< 0:
314 raise self
.Exception('Recursion limit reached')
317 should_return
= False
318 sub_statements
= list(self
._separate
(stmt
, ';')) or ['']
319 expr
= stmt
= sub_statements
.pop().strip()
321 for sub_stmt
in sub_statements
:
322 ret
, should_return
= self
.interpret_statement(sub_stmt
, local_vars
, allow_recursion
)
324 return ret
, should_return
326 m
= re
.match(r
'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$
)|
(?P
<throw
>throw\s
+)', stmt)
328 expr = stmt[len(m.group(0)):].strip()
330 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
331 should_return = not m.group('var
')
333 return None, should_return
335 if expr[0] in _QUOTES:
336 inner, outer = self._separate(expr, expr[0], 1)
338 flags, outer = self._regex_flags(outer)
339 inner = re.compile(inner[1:], flags=flags)
341 inner = json.loads(js_to_json(f'{inner}{expr[0]}
', strict=True))
343 return inner, should_return
344 expr = self._named_object(local_vars, inner) + outer
346 if expr.startswith('new
'):
348 if obj.startswith('Date('):
349 left, right = self._separate_at_paren(obj[4:], ')')
350 expr = unified_timestamp(
351 self.interpret_expression(left, local_vars, allow_recursion), False)
353 raise self.Exception(f'Failed to parse date {left!r}
', expr)
354 expr = self._dump(int(expr * 1000), local_vars) + right
356 raise self.Exception(f'Unsupported
object {obj}
', expr)
358 if expr.startswith('void
'):
359 left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
360 return None, should_return
362 if expr.startswith('{'):
363 inner, outer = self._separate_at_paren(expr, '}')
365 sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
366 if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
367 def dict_item(key, val):
368 val = self.interpret_expression(val, local_vars, allow_recursion)
369 if re.match(_NAME_RE, key):
371 return self.interpret_expression(key, local_vars, allow_recursion), val
373 return dict(dict_item(k, v) for k, v in sub_expressions), should_return
375 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
376 if not outer or should_abort:
377 return inner, should_abort or should_return
379 expr = self._dump(inner, local_vars) + outer
381 if expr.startswith('('):
382 inner, outer = self._separate_at_paren(expr, ')')
383 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
384 if not outer or should_abort:
385 return inner, should_abort or should_return
387 expr = self._dump(inner, local_vars) + outer
389 if expr.startswith('['):
390 inner, outer = self._separate_at_paren(expr, ']')
391 name = self._named_object(local_vars, [
392 self.interpret_expression(item, local_vars, allow_recursion)
393 for item in self._separate(inner)])
396 m = re.match(rf'''(?x)
397 (?P<try>try|finally)\s*|
398 (?P<catch>catch\s*(?P<err>\(\s*{_NAME_RE}\s*\)))|
399 (?P<switch>switch)\s*\(|
400 (?P<for>for)\s*\(|''', expr)
401 if m and m.group('try'):
402 if expr[m.end()] == '{':
403 try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
405 try_expr, expr = expr[m.end() - 1:], ''
407 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
410 except JS_Throw as e:
411 local_vars[self._EXC_NAME] = e.error
412 except Exception as e:
413 # XXX: This works for now, but makes debugging future issues very hard
414 local_vars[self._EXC_NAME] = e
415 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
416 return ret, should_abort or should_return
418 elif m and m.group('catch
'):
419 catch_expr, expr = self._separate_at_paren(expr[m.end():], '}')
420 if self._EXC_NAME in local_vars:
421 catch_vars = local_vars.new_child({m.group('err'): local_vars.pop(self._EXC_NAME)})
422 ret, should_abort = self.interpret_statement(catch_expr, catch_vars, allow_recursion)
426 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
427 return ret, should_abort or should_return
429 elif m and m.group('for'):
430 constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
431 if remaining.startswith('{'):
432 body, expr = self._separate_at_paren(remaining, '}')
434 switch_m = re.match(r'switch\s
*\
(', remaining) # FIXME
436 switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
437 body, expr = self._separate_at_paren(remaining, '}')
438 body = 'switch(%s){%s}
' % (switch_val, body)
440 body, expr = remaining, ''
441 start, cndn, increment = self._separate(constructor, ';')
442 self.interpret_expression(start, local_vars, allow_recursion)
444 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
447 ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
454 self.interpret_expression(increment, local_vars, allow_recursion)
455 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
456 return ret, should_abort or should_return
458 elif m and m.group('switch
'):
459 switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
460 switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
461 body, expr = self._separate_at_paren(remaining, '}')
462 items = body.replace('default
:', 'case default
:').split('case
')[1:]
463 for default in (False, True):
466 case, stmt = (i.strip() for i in self._separate(item, ':', 1))
468 matched = matched or case == 'default
'
470 matched = (case != 'default
'
471 and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
475 ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
482 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
483 return ret, should_abort or should_return
485 # Comma separated statements
486 sub_expressions = list(self._separate(expr))
487 if len(sub_expressions) > 1:
488 for sub_expr in sub_expressions:
489 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
494 for m in re.finditer(rf'''(?x)
495 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
496 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr):
497 var = m.group('var1
') or m.group('var2
')
498 start, end = m.span()
499 sign = m.group('pre_sign
') or m.group('post_sign
')
500 ret = local_vars[var]
501 local_vars[var] += 1 if sign[0] == '+' else -1
502 if m.group('pre_sign
'):
503 ret = local_vars[var]
504 expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
507 return None, should_return
509 m = re.match(fr'''(?x)
511 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
512 (?P<op>{"|".join(map(re.escape, set(_OPERATORS) - _COMP_OPERATORS))})?
515 (?!if|return|true|false|null|undefined|NaN)(?P<name>{_NAME_RE})$
517 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
519 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
521 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
523 if m and m.group('assign
'):
524 left_val = local_vars.get(m.group('out
'))
526 if not m.group('index
'):
527 local_vars[m.group('out
')] = self._operator(
528 m.group('op
'), left_val, m.group('expr
'), expr, local_vars, allow_recursion)
529 return local_vars[m.group('out
')], should_return
530 elif left_val in (None, JS_Undefined):
531 raise self.Exception(f'Cannot index undefined variable {m.group("out")}
', expr)
533 idx = self.interpret_expression(m.group('index
'), local_vars, allow_recursion)
534 if not isinstance(idx, (int, float)):
535 raise self.Exception(f'List index {idx} must be integer
', expr)
537 left_val[idx] = self._operator(
538 m.group('op
'), self._index(left_val, idx), m.group('expr
'), expr, local_vars, allow_recursion)
539 return left_val[idx], should_return
542 return int(expr), should_return
544 elif expr == 'break':
546 elif expr == 'continue':
548 elif expr == 'undefined
':
549 return JS_Undefined, should_return
551 return float('NaN
'), should_return
553 elif m and m.group('return'):
554 return local_vars.get(m.group('name
'), JS_Undefined), should_return
556 with contextlib.suppress(ValueError):
557 return json.loads(js_to_json(expr, strict=True)), should_return
559 if m and m.group('indexing
'):
560 val = local_vars[m.group('in')]
561 idx = self.interpret_expression(m.group('idx
'), local_vars, allow_recursion)
562 return self._index(val, idx), should_return
564 for op in _OPERATORS:
565 separated = list(self._separate(expr, op))
566 right_expr = separated.pop()
568 if op in '?
<>*-' and len(separated) > 1 and not separated[-1].strip():
570 elif not (separated and op == '?
' and right_expr.startswith('.')):
572 right_expr = f'{op}{right_expr}
'
574 right_expr = f'{separated.pop()}{op}{right_expr}
'
577 left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
578 return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
580 if m and m.group('attribute
'):
581 variable, member, nullish = m.group('var
', 'member
', 'nullish
')
583 member = self.interpret_expression(m.group('member2
'), local_vars, allow_recursion)
584 arg_str = expr[m.end():]
585 if arg_str.startswith('('):
586 arg_str, remaining = self._separate_at_paren(arg_str, ')')
588 arg_str, remaining = None, arg_str
590 def assertion(cndn, msg):
591 """ assert, but without risk of getting optimized out """
593 raise self.Exception(f'{member} {msg}
', expr)
596 if (variable, member) == ('console
', 'debug
'):
598 Debugger.write(self.interpret_expression(f'[{arg_str}
]', local_vars, allow_recursion))
605 obj = local_vars.get(variable, types.get(variable, NO_DEFAULT))
606 if obj is NO_DEFAULT:
607 if variable not in self._objects:
609 self._objects[variable] = self.extract_object(variable)
610 except self.Exception:
613 obj = self._objects.get(variable, JS_Undefined)
615 if nullish and obj is JS_Undefined:
620 return self._index(obj, member, nullish)
624 self.interpret_expression(v, local_vars, allow_recursion)
625 for v in self._separate(arg_str)]
628 if member == 'fromCharCode
':
629 assertion(argvals, 'takes one
or more arguments
')
630 return ''.join(map(chr, argvals))
631 raise self.Exception(f'Unsupported String method {member}
', expr)
634 assertion(len(argvals) == 2, 'takes two arguments
')
635 return argvals[0] ** argvals[1]
636 raise self.Exception(f'Unsupported Math method {member}
', expr)
638 if member == 'split
':
639 assertion(argvals, 'takes one
or more arguments
')
640 assertion(len(argvals) == 1, 'with limit argument
is not implemented
')
641 return obj.split(argvals[0]) if argvals[0] else list(obj)
642 elif member == 'join
':
643 assertion(isinstance(obj, list), 'must be applied on a
list')
644 assertion(len(argvals) == 1, 'takes exactly one argument
')
645 return argvals[0].join(obj)
646 elif member == 'reverse
':
647 assertion(not argvals, 'does
not take any arguments
')
650 elif member == 'slice':
651 assertion(isinstance(obj, list), 'must be applied on a
list')
652 assertion(len(argvals) == 1, 'takes exactly one argument
')
653 return obj[argvals[0]:]
654 elif member == 'splice
':
655 assertion(isinstance(obj, list), 'must be applied on a
list')
656 assertion(argvals, 'takes one
or more arguments
')
657 index, howMany = map(int, (argvals + [len(obj)])[:2])
660 add_items = argvals[2:]
662 for i in range(index, min(index + howMany, len(obj))):
663 res.append(obj.pop(index))
664 for i, item in enumerate(add_items):
665 obj.insert(index + i, item)
667 elif member == 'unshift
':
668 assertion(isinstance(obj, list), 'must be applied on a
list')
669 assertion(argvals, 'takes one
or more arguments
')
670 for item in reversed(argvals):
673 elif member == 'pop
':
674 assertion(isinstance(obj, list), 'must be applied on a
list')
675 assertion(not argvals, 'does
not take any arguments
')
679 elif member == 'push
':
680 assertion(argvals, 'takes one
or more arguments
')
683 elif member == 'forEach
':
684 assertion(argvals, 'takes one
or more arguments
')
685 assertion(len(argvals) <= 2, 'takes at
-most
2 arguments
')
686 f, this = (argvals + [''])[:2]
687 return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
688 elif member == 'indexOf
':
689 assertion(argvals, 'takes one
or more arguments
')
690 assertion(len(argvals) <= 2, 'takes at
-most
2 arguments
')
691 idx, start = (argvals + [0])[:2]
693 return obj.index(idx, start)
696 elif member == 'charCodeAt
':
697 assertion(isinstance(obj, str), 'must be applied on a string
')
698 assertion(len(argvals) == 1, 'takes exactly one argument
')
699 idx = argvals[0] if isinstance(argvals[0], int) else 0
704 idx = int(member) if isinstance(obj, list) else member
705 return obj[idx](argvals, allow_recursion=allow_recursion)
708 ret, should_abort = self.interpret_statement(
709 self._named_object(local_vars, eval_method()) + remaining,
710 local_vars, allow_recursion)
711 return ret, should_return or should_abort
713 return eval_method(), should_return
715 elif m and m.group('function
'):
716 fname = m.group('fname
')
717 argvals = [self.interpret_expression(v, local_vars, allow_recursion)
718 for v in self._separate(m.group('args
'))]
719 if fname in local_vars:
720 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
721 elif fname not in self._functions:
722 self._functions[fname] = self.extract_function(fname)
723 return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
725 raise self.Exception(
726 f'Unsupported JS expression {truncate_string(expr, 20, 20) if expr != stmt else ""}
', stmt)
728 def interpret_expression(self, expr, local_vars, allow_recursion):
729 ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
731 raise self.Exception('Cannot
return from an expression
', expr)
734 def extract_object(self, objname):
735 _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a
-zA
-Z$
0-9]+')'''
739 (?<!this\.)%s\s*=\s*{\s*
740 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
742 ''' % (re.escape(objname), _FUNC_NAME_RE),
745 raise self.Exception(f'Could
not find
object {objname}
')
746 fields = obj_m.group('fields
')
747 # Currently, it only supports function definitions
748 fields_m = re.finditer(
750 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
751 ''' % (_FUNC_NAME_RE, _NAME_RE),
754 argnames = f.group('args
').split(',')
755 obj[remove_quotes(f.group('key
'))] = self.build_function(argnames, f.group('code
'))
759 def extract_function_code(self, funcname):
760 """ @returns argnames, code """
765 [{;,]\s*%(name)s\s*=\s*function|
766 (?:var|const|let)\s+%(name)s\s*=\s*function
768 \((?P<args>[^)]*)\)\s*
769 (?P<code>{.+})''' % {'name': re.escape(funcname)},
771 code, _ = self._separate_at_paren(func_m.group('code
'), '}')
773 raise self.Exception(f'Could
not find JS function
"{funcname}"')
774 return [x.strip() for x in func_m.group('args
').split(',')], code
776 def extract_function(self, funcname):
777 return self.extract_function_from_code(*self.extract_function_code(funcname))
779 def extract_function_from_code(self, argnames, code, *global_stack):
782 mobj = re.search(r'function\
((?P
<args
>[^
)]*)\
)\s
*{', code)
785 start, body_start = mobj.span()
786 body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
787 name = self._named_object(local_vars, self.extract_function_from_code(
788 [x.strip() for x in mobj.group('args
').split(',')],
789 body, local_vars, *global_stack))
790 code = code[:start] + name + remaining
791 return self.build_function(argnames, code, local_vars, *global_stack)
793 def call_function(self, funcname, *args):
794 return self.extract_function(funcname)(args)
796 def build_function(self, argnames, code, *global_stack):
797 global_stack = list(global_stack) or [{}]
798 argnames = tuple(argnames)
800 def resf(args, kwargs={}, allow_recursion=100):
801 global_stack[0].update(itertools.zip_longest(argnames, args, fillvalue=None))
802 global_stack[0].update(kwargs)
803 var_stack = LocalNameSpace(*global_stack)
804 ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)