handheld-daemon-ui: 3.2.3 -> 3.3.0 (#361609)
[NixPkgs.git] / pkgs / development / node-packages / node-env.nix
blob4123ca02966437f70705c65c5415f0a5dd13a99e
1 # This file originates from node2nix
3 {lib, stdenv, nodejs, python2, pkgs, libtool, runCommand, writeTextFile, writeShellScript}:
5 let
6   python = if nodejs ? python then nodejs.python else python2;
8   # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise
9   tarWrapper = runCommand "tarWrapper" {} ''
10     mkdir -p $out/bin
12     cat > $out/bin/tar <<EOF
13     #! ${stdenv.shell} -e
14     $(type -p tar) "\$@" --warning=no-unknown-keyword --delay-directory-restore
15     EOF
17     chmod +x $out/bin/tar
18   '';
20   # Function that generates a TGZ file from a NPM project
21   buildNodeSourceDist =
22     { name, version, src, ... }:
24     stdenv.mkDerivation {
25       name = "node-tarball-${name}-${version}";
26       inherit src;
27       buildInputs = [ nodejs ];
28       buildPhase = ''
29         export HOME=$TMPDIR
30         tgzFile=$(npm pack | tail -n 1) # Hooks to the pack command will add output (https://docs.npmjs.com/misc/scripts)
31       '';
32       installPhase = ''
33         mkdir -p $out/tarballs
34         mv $tgzFile $out/tarballs
35         mkdir -p $out/nix-support
36         echo "file source-dist $out/tarballs/$tgzFile" >> $out/nix-support/hydra-build-products
37       '';
38     };
40   # Common shell logic
41   installPackage = writeShellScript "install-package" ''
42     installPackage() {
43       local packageName=$1 src=$2
45       local strippedName
47       local DIR=$PWD
48       cd $TMPDIR
50       unpackFile $src
52       # Make the base dir in which the target dependency resides first
53       mkdir -p "$(dirname "$DIR/$packageName")"
55       if [ -f "$src" ]
56       then
57           # Figure out what directory has been unpacked
58           packageDir="$(find . -maxdepth 1 -type d | tail -1)"
60           # Restore write permissions to make building work
61           find "$packageDir" -type d -exec chmod u+x {} \;
62           chmod -R u+w "$packageDir"
64           # Move the extracted tarball into the output folder
65           mv "$packageDir" "$DIR/$packageName"
66       elif [ -d "$src" ]
67       then
68           # Get a stripped name (without hash) of the source directory.
69           # On old nixpkgs it's already set internally.
70           if [ -z "$strippedName" ]
71           then
72               strippedName="$(stripHash $src)"
73           fi
75           # Restore write permissions to make building work
76           chmod -R u+w "$strippedName"
78           # Move the extracted directory into the output folder
79           mv "$strippedName" "$DIR/$packageName"
80       fi
82       # Change to the package directory to install dependencies
83       cd "$DIR/$packageName"
84     }
85   '';
87   # Bundle the dependencies of the package
88   #
89   # Only include dependencies if they don't exist. They may also be bundled in the package.
90   includeDependencies = {dependencies}:
91     lib.optionalString (dependencies != []) (
92       ''
93         mkdir -p node_modules
94         cd node_modules
95       ''
96       + (lib.concatMapStrings (dependency:
97         ''
98           if [ ! -e "${dependency.packageName}" ]; then
99               ${composePackage dependency}
100           fi
101         ''
102       ) dependencies)
103       + ''
104         cd ..
105       ''
106     );
108   # Recursively composes the dependencies of a package
109   composePackage = { name, packageName, src, dependencies ? [], ... }@args:
110     builtins.addErrorContext "while evaluating node package '${packageName}'" ''
111       installPackage "${packageName}" "${src}"
112       ${includeDependencies { inherit dependencies; }}
113       cd ..
114       ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
115     '';
117   pinpointDependencies = {dependencies, production}:
118     let
119       pinpointDependenciesFromPackageJSON = writeTextFile {
120         name = "pinpointDependencies.js";
121         text = ''
122           var fs = require('fs');
123           var path = require('path');
125           function resolveDependencyVersion(location, name) {
126               if(location == process.env['NIX_STORE']) {
127                   return null;
128               } else {
129                   var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json");
131                   if(fs.existsSync(dependencyPackageJSON)) {
132                       var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON));
134                       if(dependencyPackageObj.name == name) {
135                           return dependencyPackageObj.version;
136                       }
137                   } else {
138                       return resolveDependencyVersion(path.resolve(location, ".."), name);
139                   }
140               }
141           }
143           function replaceDependencies(dependencies) {
144               if(typeof dependencies == "object" && dependencies !== null) {
145                   for(var dependency in dependencies) {
146                       var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency);
148                       if(resolvedVersion === null) {
149                           process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n");
150                       } else {
151                           dependencies[dependency] = resolvedVersion;
152                       }
153                   }
154               }
155           }
157           /* Read the package.json configuration */
158           var packageObj = JSON.parse(fs.readFileSync('./package.json'));
160           /* Pinpoint all dependencies */
161           replaceDependencies(packageObj.dependencies);
162           if(process.argv[2] == "development") {
163               replaceDependencies(packageObj.devDependencies);
164           }
165           else {
166               packageObj.devDependencies = {};
167           }
168           replaceDependencies(packageObj.optionalDependencies);
169           replaceDependencies(packageObj.peerDependencies);
171           /* Write the fixed package.json file */
172           fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2));
173         '';
174       };
175     in
176     ''
177       node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"}
179       ${lib.optionalString (dependencies != [])
180         ''
181           if [ -d node_modules ]
182           then
183               cd node_modules
184               ${lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies}
185               cd ..
186           fi
187         ''}
188     '';
190   # Recursively traverses all dependencies of a package and pinpoints all
191   # dependencies in the package.json file to the versions that are actually
192   # being used.
194   pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args:
195     ''
196       if [ -d "${packageName}" ]
197       then
198           cd "${packageName}"
199           ${pinpointDependencies { inherit dependencies production; }}
200           cd ..
201           ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
202       fi
203     '';
205   # Extract the Node.js source code which is used to compile packages with
206   # native bindings
207   nodeSources = runCommand "node-sources" {} ''
208     tar --no-same-owner --no-same-permissions -xf ${nodejs.src}
209     mv node-* $out
210   '';
212   # Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty)
213   addIntegrityFieldsScript = writeTextFile {
214     name = "addintegrityfields.js";
215     text = ''
216       var fs = require('fs');
217       var path = require('path');
219       function augmentDependencies(baseDir, dependencies) {
220           for(var dependencyName in dependencies) {
221               var dependency = dependencies[dependencyName];
223               // Open package.json and augment metadata fields
224               var packageJSONDir = path.join(baseDir, "node_modules", dependencyName);
225               var packageJSONPath = path.join(packageJSONDir, "package.json");
227               if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored
228                   console.log("Adding metadata fields to: "+packageJSONPath);
229                   var packageObj = JSON.parse(fs.readFileSync(packageJSONPath));
231                   if(dependency.integrity) {
232                       packageObj["_integrity"] = dependency.integrity;
233                   } else {
234                       packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads.
235                   }
237                   if(dependency.resolved) {
238                       packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided
239                   } else {
240                       packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories.
241                   }
243                   if(dependency.from !== undefined) { // Adopt from property if one has been provided
244                       packageObj["_from"] = dependency.from;
245                   }
247                   fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2));
248               }
250               // Augment transitive dependencies
251               if(dependency.dependencies !== undefined) {
252                   augmentDependencies(packageJSONDir, dependency.dependencies);
253               }
254           }
255       }
257       if(fs.existsSync("./package-lock.json")) {
258           var packageLock = JSON.parse(fs.readFileSync("./package-lock.json"));
260           if(![1, 2].includes(packageLock.lockfileVersion)) {
261             process.stderr.write("Sorry, I only understand lock file versions 1 and 2!\n");
262             process.exit(1);
263           }
265           if(packageLock.dependencies !== undefined) {
266               augmentDependencies(".", packageLock.dependencies);
267           }
268       }
269     '';
270   };
272   # Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes
273   reconstructPackageLock = writeTextFile {
274     name = "reconstructpackagelock.js";
275     text = ''
276       var fs = require('fs');
277       var path = require('path');
279       var packageObj = JSON.parse(fs.readFileSync("package.json"));
281       var lockObj = {
282           name: packageObj.name,
283           version: packageObj.version,
284           lockfileVersion: 2,
285           requires: true,
286           packages: {
287               "": {
288                   name: packageObj.name,
289                   version: packageObj.version,
290                   license: packageObj.license,
291                   bin: packageObj.bin,
292                   dependencies: packageObj.dependencies,
293                   engines: packageObj.engines,
294                   optionalDependencies: packageObj.optionalDependencies
295               }
296           },
297           dependencies: {}
298       };
300       function augmentPackageJSON(filePath, packages, dependencies) {
301           var packageJSON = path.join(filePath, "package.json");
302           if(fs.existsSync(packageJSON)) {
303               var packageObj = JSON.parse(fs.readFileSync(packageJSON));
304               packages[filePath] = {
305                   version: packageObj.version,
306                   integrity: "sha1-000000000000000000000000000=",
307                   dependencies: packageObj.dependencies,
308                   engines: packageObj.engines,
309                   optionalDependencies: packageObj.optionalDependencies
310               };
311               dependencies[packageObj.name] = {
312                   version: packageObj.version,
313                   integrity: "sha1-000000000000000000000000000=",
314                   dependencies: {}
315               };
316               processDependencies(path.join(filePath, "node_modules"), packages, dependencies[packageObj.name].dependencies);
317           }
318       }
320       function processDependencies(dir, packages, dependencies) {
321           if(fs.existsSync(dir)) {
322               var files = fs.readdirSync(dir);
324               files.forEach(function(entry) {
325                   var filePath = path.join(dir, entry);
326                   var stats = fs.statSync(filePath);
328                   if(stats.isDirectory()) {
329                       if(entry.substr(0, 1) == "@") {
330                           // When we encounter a namespace folder, augment all packages belonging to the scope
331                           var pkgFiles = fs.readdirSync(filePath);
333                           pkgFiles.forEach(function(entry) {
334                               if(stats.isDirectory()) {
335                                   var pkgFilePath = path.join(filePath, entry);
336                                   augmentPackageJSON(pkgFilePath, packages, dependencies);
337                               }
338                           });
339                       } else {
340                           augmentPackageJSON(filePath, packages, dependencies);
341                       }
342                   }
343               });
344           }
345       }
347       processDependencies("node_modules", lockObj.packages, lockObj.dependencies);
349       fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2));
350     '';
351   };
353   # Script that links bins defined in package.json to the node_modules bin directory
354   # NPM does not do this for top-level packages itself anymore as of v7
355   linkBinsScript = writeTextFile {
356     name = "linkbins.js";
357     text = ''
358       var fs = require('fs');
359       var path = require('path');
361       var packageObj = JSON.parse(fs.readFileSync("package.json"));
363       var nodeModules = Array(packageObj.name.split("/").length).fill("..").join(path.sep);
365       if(packageObj.bin !== undefined) {
366           fs.mkdirSync(path.join(nodeModules, ".bin"))
368           if(typeof packageObj.bin == "object") {
369               Object.keys(packageObj.bin).forEach(function(exe) {
370                   if(fs.existsSync(packageObj.bin[exe])) {
371                       console.log("linking bin '" + exe + "'");
372                       fs.symlinkSync(
373                           path.join("..", packageObj.name, packageObj.bin[exe]),
374                           path.join(nodeModules, ".bin", exe)
375                       );
376                   }
377                   else {
378                       console.log("skipping non-existent bin '" + exe + "'");
379                   }
380               })
381           }
382           else {
383               if(fs.existsSync(packageObj.bin)) {
384                   console.log("linking bin '" + packageObj.bin + "'");
385                   fs.symlinkSync(
386                       path.join("..", packageObj.name, packageObj.bin),
387                       path.join(nodeModules, ".bin", packageObj.name.split("/").pop())
388                   );
389               }
390               else {
391                   console.log("skipping non-existent bin '" + packageObj.bin + "'");
392               }
393           }
394       }
395       else if(packageObj.directories !== undefined && packageObj.directories.bin !== undefined) {
396           fs.mkdirSync(path.join(nodeModules, ".bin"))
398           fs.readdirSync(packageObj.directories.bin).forEach(function(exe) {
399               if(fs.existsSync(path.join(packageObj.directories.bin, exe))) {
400                   console.log("linking bin '" + exe + "'");
401                   fs.symlinkSync(
402                       path.join("..", packageObj.name, packageObj.directories.bin, exe),
403                       path.join(nodeModules, ".bin", exe)
404                   );
405               }
406               else {
407                   console.log("skipping non-existent bin '" + exe + "'");
408               }
409           })
410       }
411     '';
412   };
414   prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}:
415     let
416       forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com";
417     in
418     ''
419         # Pinpoint the versions of all dependencies to the ones that are actually being used
420         echo "pinpointing versions of dependencies..."
421         source $pinpointDependenciesScriptPath
423         # Patch the shebangs of the bundled modules to prevent them from
424         # calling executables outside the Nix store as much as possible
425         patchShebangs .
427         # Deploy the Node.js package by running npm install. Since the
428         # dependencies have been provided already by ourselves, it should not
429         # attempt to install them again, which is good, because we want to make
430         # it Nix's responsibility. If it needs to install any dependencies
431         # anyway (e.g. because the dependency parameters are
432         # incomplete/incorrect), it fails.
433         #
434         # The other responsibilities of NPM are kept -- version checks, build
435         # steps, postprocessing etc.
437         export HOME=$TMPDIR
438         cd "${packageName}"
439         runHook preRebuild
441         ${lib.optionalString bypassCache ''
442           ${lib.optionalString reconstructLock ''
443             if [ -f package-lock.json ]
444             then
445                 echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!"
446                 echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!"
447                 rm package-lock.json
448             else
449                 echo "No package-lock.json file found, reconstructing..."
450             fi
452             node ${reconstructPackageLock}
453           ''}
455           node ${addIntegrityFieldsScript}
456         ''}
458         npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} rebuild
460         runHook postRebuild
462         if [ "''${dontNpmInstall-}" != "1" ]
463         then
464             # NPM tries to download packages even when they already exist if npm-shrinkwrap is used.
465             rm -f npm-shrinkwrap.json
467             npm ${forceOfflineFlag} --nodedir=${nodeSources} --no-bin-links --ignore-scripts ${npmFlags} ${lib.optionalString production "--production"} install
468         fi
470         # Link executables defined in package.json
471         node ${linkBinsScript}
472     '';
474   # Builds and composes an NPM package including all its dependencies
475   buildNodePackage =
476     { name
477     , packageName
478     , version ? null
479     , dependencies ? []
480     , buildInputs ? []
481     , production ? true
482     , npmFlags ? ""
483     , dontNpmInstall ? false
484     , bypassCache ? false
485     , reconstructLock ? false
486     , preRebuild ? ""
487     , dontStrip ? true
488     , unpackPhase ? "true"
489     , buildPhase ? "true"
490     , meta ? {}
491     , ... }@args:
493     let
494       extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" "meta" ];
495     in
496     stdenv.mkDerivation ({
497       name = "${name}${if version == null then "" else "-${version}"}";
498       buildInputs = [ tarWrapper python nodejs ]
499         ++ lib.optional (stdenv.hostPlatform.isLinux) pkgs.util-linux
500         ++ lib.optional (stdenv.hostPlatform.isDarwin) libtool
501         ++ buildInputs;
503       inherit nodejs;
505       inherit dontStrip; # Stripping may fail a build for some package deployments
506       inherit dontNpmInstall preRebuild unpackPhase buildPhase;
508       compositionScript = composePackage args;
509       pinpointDependenciesScript = pinpointDependenciesOfPackage args;
511       passAsFile = [ "compositionScript" "pinpointDependenciesScript" ];
513       installPhase = ''
514         source ${installPackage}
516         # Create and enter a root node_modules/ folder
517         mkdir -p $out/lib/node_modules
518         cd $out/lib/node_modules
520         # Compose the package and all its dependencies
521         source $compositionScriptPath
523         ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }}
525         # Create symlink to the deployed executable folder, if applicable
526         if [ -d "$out/lib/node_modules/.bin" ]
527         then
528             ln -s $out/lib/node_modules/.bin $out/bin
530             # Fixup all executables
531             ls $out/bin/* | while read i
532             do
533                 file="$(readlink -f "$i")"
534                 chmod u+rwx "$file"
535                 if isScript "$file"
536                 then
537                     sed -i 's/\r$//' "$file"  # convert crlf to lf
538                 fi
539             done
540         fi
542         # Create symlinks to the deployed manual page folders, if applicable
543         if [ -d "$out/lib/node_modules/${packageName}/man" ]
544         then
545             mkdir -p $out/share
546             for dir in "$out/lib/node_modules/${packageName}/man/"*
547             do
548                 mkdir -p $out/share/man/$(basename "$dir")
549                 for page in "$dir"/*
550                 do
551                     ln -s $page $out/share/man/$(basename "$dir")
552                 done
553             done
554         fi
556         # Run post install hook, if provided
557         runHook postInstall
558       '';
560       meta = {
561         # default to Node.js' platforms
562         platforms = nodejs.meta.platforms;
563       } // meta;
564     } // extraArgs);
566   # Builds a node environment (a node_modules folder and a set of binaries)
567   buildNodeDependencies =
568     { name
569     , packageName
570     , version ? null
571     , src
572     , dependencies ? []
573     , buildInputs ? []
574     , production ? true
575     , npmFlags ? ""
576     , dontNpmInstall ? false
577     , bypassCache ? false
578     , reconstructLock ? false
579     , dontStrip ? true
580     , unpackPhase ? "true"
581     , buildPhase ? "true"
582     , ... }@args:
584     let
585       extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ];
586     in
587       stdenv.mkDerivation ({
588         name = "node-dependencies-${name}${if version == null then "" else "-${version}"}";
590         buildInputs = [ tarWrapper python nodejs ]
591           ++ lib.optional (stdenv.hostPlatform.isLinux) pkgs.util-linux
592           ++ lib.optional (stdenv.hostPlatform.isDarwin) libtool
593           ++ buildInputs;
595         inherit dontStrip; # Stripping may fail a build for some package deployments
596         inherit dontNpmInstall unpackPhase buildPhase;
598         includeScript = includeDependencies { inherit dependencies; };
599         pinpointDependenciesScript = pinpointDependenciesOfPackage args;
601         passAsFile = [ "includeScript" "pinpointDependenciesScript" ];
603         installPhase = ''
604           source ${installPackage}
606           mkdir -p $out/${packageName}
607           cd $out/${packageName}
609           source $includeScriptPath
611           # Create fake package.json to make the npm commands work properly
612           cp ${src}/package.json .
613           chmod 644 package.json
614           ${lib.optionalString bypassCache ''
615             if [ -f ${src}/package-lock.json ]
616             then
617                 cp ${src}/package-lock.json .
618                 chmod 644 package-lock.json
619             fi
620           ''}
622           # Go to the parent folder to make sure that all packages are pinpointed
623           cd ..
624           ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
626           ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }}
628           # Expose the executables that were installed
629           cd ..
630           ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
632           mv ${packageName} lib
633           ln -s $out/lib/node_modules/.bin $out/bin
634         '';
635       } // extraArgs);
637   # Builds a development shell
638   buildNodeShell =
639     { name
640     , packageName
641     , version ? null
642     , src
643     , dependencies ? []
644     , buildInputs ? []
645     , production ? true
646     , npmFlags ? ""
647     , dontNpmInstall ? false
648     , bypassCache ? false
649     , reconstructLock ? false
650     , dontStrip ? true
651     , unpackPhase ? "true"
652     , buildPhase ? "true"
653     , ... }@args:
655     let
656       nodeDependencies = buildNodeDependencies args;
657       extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "unpackPhase" "buildPhase" ];
658     in
659     stdenv.mkDerivation ({
660       name = "node-shell-${name}${if version == null then "" else "-${version}"}";
662       buildInputs = [ python nodejs ] ++ lib.optional (stdenv.hostPlatform.isLinux) pkgs.util-linux ++ buildInputs;
663       buildCommand = ''
664         mkdir -p $out/bin
665         cat > $out/bin/shell <<EOF
666         #! ${stdenv.shell} -e
667         $shellHook
668         exec ${stdenv.shell}
669         EOF
670         chmod +x $out/bin/shell
671       '';
673       # Provide the dependencies in a development shell through the NODE_PATH environment variable
674       inherit nodeDependencies;
675       shellHook = lib.optionalString (dependencies != []) ''
676         export NODE_PATH=${nodeDependencies}/lib/node_modules
677         export PATH="${nodeDependencies}/bin:$PATH"
678       '';
679     } // extraArgs);
682   buildNodeSourceDist = lib.makeOverridable buildNodeSourceDist;
683   buildNodePackage = lib.makeOverridable buildNodePackage;
684   buildNodeDependencies = lib.makeOverridable buildNodeDependencies;
685   buildNodeShell = lib.makeOverridable buildNodeShell;