#!/bin/sh
# Fix the import attributes of the compiled ECMAScript modules.
#
# The rollup of the archive (3.x) does not know the "importAttributesKey"
# output option Babel passes, so it emits the deprecated "assert" keyword,
# which Node.js 24 removed.
#
# And when the build is bootstrapped with Babel 7, debian/bootstrap-babel7.sh
# has to strip the attributes from the sources altogether: put them back.
set -e

FILES=$(find packages/*/lib codemods/*/lib \
	\( -name '*.js' -o -name '*.mjs' \) 2>/dev/null || true)
[ -n "$FILES" ] || exit 0

echo "$FILES" | xargs -r perl -i -pe '
	s{\bassert(\s*\{\s*type:\s*(["\x27])json\2\s*\})}{with$1}g;
'

[ -s debian/json-imports.list ] || exit 0

echo "$FILES" | xargs -r perl -i -pe '
	BEGIN {
		open my $fh, "<", "debian/json-imports.list" or die $!;
		chomp(my @s = <$fh>);
		$re = join "|", map { quotemeta } grep { length } @s;
	}
	s{(\bfrom\s*(["\x27])(?:$re)\2)(?!\s*with)(\s*;)}
	 {$1 with { type: "json" }$3}g if $re;
'
