File: AutoTransform.pm

package info (click to toggle)
pkg-js-tools 0.16.0
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,992 kB
  • sloc: perl: 4,975; sh: 840; makefile: 36; javascript: 22
file content (65 lines) | stat: -rw-r--r-- 1,895 bytes parent folder | download | duplicates (3)
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
package Debian::PkgJs::AutoTransform;

use strict;
use Debian::PkgJs::Utils;
use Dpkg::IPC;
use Exporter 'import';
use File::Copy;
use JSON;

use constant BUNDLE => './dhnodejsBundle.cjs';

our @EXPORT = ('run');

sub run {
    copy('package.json', '.mjs2cjs-package.json');
    my $pkg = pjson(main_package) or die 'Unable to open package.json';
    die "Package isn't 'type:module', aborting"
      unless $pkg->{type} eq 'module';
    my $entryPoint = $ENV{ENTRY_POINT} || $pkg->{module} || $pkg->{exports};
    $entryPoint = './index.js' if !$entryPoint && -e 'index.js';
    die 'Unable to find entry point. Set it in env vars (ENTRY_POINT)'
      if ref $entryPoint;
    my @links;
    foreach my $type ( grep { $pkg->{$_} } (qw(dependencies peerDependencies devDependencies)) )
    {
        foreach
          my $dep ( grep { !-e "node_modules/$_" } keys %{ $pkg->{$type} } )
        {
            eval { ln($dep); };
            push @links, $dep unless $@;
        }
    }
    spawn(
        exec       => [ qw(mjs2cjs -b -o ), BUNDLE, $entryPoint ],
        wait_child => 1,
    );
    spawn(
        exec => [qw(perl -i -pe ), q{s/(["'])node:/$1/g}, BUNDLE],
        wait_child => 1,
    );
    foreach (@links) {
        unlink "node_modules/$_";
        rmdir "node_modules/$_" if s#/.*?$##;
    }

    # Transform package.json
    if ( $pkg->{files} ) {
        push @{ $pkg->{files} }, BUNDLE;
    }
    $pkg->{module} ||= $entryPoint;
    my $mainCjs = BUNDLE;
    if ( -e 'debian/index.cjs' ) {
        copy('debian/index.cjs','index.cjs');
        push @{ $pkg->{files} }, 'index.cjs';
        $mainCjs = './index.cjs';
    }
    $pkg->{exports} = { "import" => $pkg->{exports} } unless ref $pkg->{exports};
    $pkg->{exports}->{require} = $mainCjs;

    open PKG, '>', 'package.json' or die $?;
    print PKG JSON->new->pretty->canonical->encode($pkg);
    close PKG;
}

1;