jy.js_parse#
Utils to parse JS
Functions
|
Append code to the body of a function definition |
Python value -> JS literal text, via |
|
|
Extract one or several function |
|
Extract the body of a function definition from its code |
|
|
|
Get |
|
|
|
Parse JavaScript source (or a path to a |
|
Parse JavaScript source (or a path to a |
|
Replaces IDs in a mixed HTML, CSS, and JS string with unique versions. |
|
Yield |
Exceptions
|
To be raised when an AST node type wasn't handled by a function |
- exception jy.js_parse.UnknownNodeType(node_type, context='')[source]#
Bases:
ValueErrorTo be raised when an AST node type wasn’t handled by a function
- jy.js_parse.append_to_func_body(func_def_code, code_to_append)[source]#
Append code to the body of a function definition
- Return type:
- jy.js_parse.dflt_py_to_js_value_trans(x)[source]#
Python value -> JS literal text, via
json.dumps(quotes and nesting are escaped).>>> dflt_py_to_js_value_trans(True), dflt_py_to_js_value_trans(None) ('true', 'null') >>> dflt_py_to_js_value_trans('say "hi"\n') '"say \\"hi\\"\\n"' >>> dflt_py_to_js_value_trans([{"a": 1}, {"b": [2, "x"]}]) '[{"a": 1}, {"b": [2, "x"]}]'
Values
jsoncannot encode are passed through unchanged (so a caller can supply a raw JS expression object whosestris the code).
- jy.js_parse.extract_func_name_and_params(ast_node)[source]#
Extract one or several function
(name, params)pair(s) from an AST node
- jy.js_parse.extract_function_def_parts(func_def_code)[source]#
Extract the body of a function definition from its code
- Return type:
- jy.js_parse.func_name_and_params_pairs(js_code, *, encoding=None)[source]#
Get
(name, params)pairs of function definitions extracted fromjs_code.>>> js_code = ''' ... function foo(a, b="hello", c= 3) { ... return a + b.length * c ... } ... const bar = (y, z = 1) => y * z ... func.assigned.to.nested.prop = function (x) { ... return x + 3 ... }''' >>> assert list(func_name_and_params_pairs(js_code)) == [ ... ('foo', [ ... {'name': 'a'}, ... {'name': 'b', 'default': 'hello'}, ... {'name': 'c', 'default': 3} ... ]), ... ('bar', [ ... {'name': 'y'}, ... {'name': 'z', 'default': 1} ... ]), ... ('func.assigned.to.nested.prop', [ ... {'name': 'x'} ... ]) ... ]
- jy.js_parse.parse_js(js_code, encoding=None, *, ingress=<function <lambda>>, egress=<function <lambda>>)[source]#
Parse JavaScript source (or a path to a
.jsfile) into an esprima AST.js_codemay be a string of JS or a filesystem path, in which case the file is read (honoringencoding).ingresspreprocesses the source before parsing;egresspost-processes the resulting AST.>>> tree = parse_js("const x = 42;") >>> tree.body[0].type 'VariableDeclaration' >>> tree.body[0].declarations[0].id.name 'x'
- Return type:
Script
- jy.js_parse.parse_js_code(js_code, encoding=None, *, ingress=<function <lambda>>, egress=<function <lambda>>)#
Parse JavaScript source (or a path to a
.jsfile) into an esprima AST.js_codemay be a string of JS or a filesystem path, in which case the file is read (honoringencoding).ingresspreprocesses the source before parsing;egresspost-processes the resulting AST.>>> tree = parse_js("const x = 42;") >>> tree.body[0].type 'VariableDeclaration' >>> tree.body[0].declarations[0].id.name 'x'
- Return type:
Script
- jy.js_parse.replace_ids_in_code(code, patterns=('id="([^"]+)"', '#([a-zA-Z][\\w\\-]*)', 'document\\.getElementById\\("([^"]+)"\\)'))[source]#
Replaces IDs in a mixed HTML, CSS, and JS string with unique versions.
Args
code (str): The input code containing HTML, CSS, and/or JS.
patterns (tuple): A tuple of regex patterns to match IDs.
Returns
tuple: A tuple containing the modified code and a dictionary of old-to-new ID mappings.
This function is useful to make id-unique copies of HTML/JS components that have IDs. This need was noticed and discussed in: i2mint/jy#3
- jy.js_parse.variable_declarations_pairs(src, *, encoding=None)[source]#
Yield
(name, value)pairs for the top-level variable declarations in JS.Literal, object, array and unary-minus initializers are evaluated to their Python equivalents; other initializer kinds yield
None. A leadingexporton a declaration is stripped first, so ES-module sources parse.>>> list(variable_declarations_pairs("const a = 3; let b = 'hi';")) [('a', 3), ('b', 'hi')] >>> list(variable_declarations_pairs("export const config = {x: 1, y: [2, 3]};")) [('config', {'x': 1, 'y': [2, 3]})] >>> list(variable_declarations_pairs("var n = -5; const flag = true;")) [('n', -5), ('flag', True)]