#!/usr/bin/python3
# Extract sourcesContent from a javascript source map produced by webpack.
#
# Usage: $0 <output.js.map> <extraction directory> > <filelist>
#

import json
import os
import re
import sys

PREFIX = "webpack:///"
FOOTER = re.compile(r"^(.*)\n\n/*\n/[\*/][\s\*]* WEBPACK FOOTER.*$", re.DOTALL)

remove_footer = True


def main(fn, outdir, *args):
    with open(fn) as fp:
        j = json.load(fp)
        pairs = zip(j["sources"], j["sourcesContent"])
        for f, c in pairs:
            if f.startswith(PREFIX):
                p = f[len(PREFIX):].replace("/~/", "/node_modules/")
                assert not os.path.isabs(p)
                print(p)
                p = os.path.join(outdir, p)
                dirname, basename = os.path.split(p)
                if dirname:
                    os.makedirs(dirname, exist_ok=True)
                if remove_footer:
                    c = re.sub(FOOTER, "\\1", c)
                with open(p, 'w') as wfp:
                    wfp.write(c)
            else:
                print("unrecognised; ignoring: %s" % f, file=sys.stderr)


if __name__ == "__main__":
    sys.exit(main(*sys.argv[1:]))
