UNPKG

1.88 kBJavaScriptView Raw
1#!/usr/bin/env node
2import * as fs from 'fs'
3import * as object from '../object.js'
4import * as env from '../environment.js'
5
6const script = env.getParam('--script', './test.js')
7
8/**
9 * @type {Object<string,string>}
10 */
11const exports = {}
12/**
13 * @type {Object<string,Object<string,string>>}
14 */
15const scopes = {}
16
17/**
18 * @param {any} v
19 * @param {string} k
20 * @param {string} pkgName
21 * @param {string} pathPrefix
22 * @param {Object<string,string>} importMap
23 */
24const extractModMap = (v, k, pkgName, pathPrefix, importMap) => {
25 if (k[0] !== '.') return
26 if (typeof v === 'object') {
27 extractModMap(v.browser || v.module || v.default || v.import, k, pkgName, pathPrefix, importMap)
28 } else if (v && v[0] === '.') {
29 importMap[pkgName + k.slice(1)] = pathPrefix + v.slice(1)
30 }
31}
32
33/**
34 * @param {any} pkgJson
35 * @param {string} pathPrefix
36 * @param {Object<string,string>} importMap
37 */
38const readPkg = (pkgJson, pathPrefix, importMap) => {
39 object.forEach(pkgJson.exports, (v, k) => extractModMap(v, k, pkgJson.name, pathPrefix, importMap))
40 object.forEach(pkgJson.dependencies, (_v, depName) => {
41 const nextImportMap = pathPrefix === '.' ? exports : (scopes[pathPrefix + '/'] = {})
42 const prefix = `./node_modules/${depName}`
43 const depPkgJson = JSON.parse(fs.readFileSync(prefix + '/package.json', { encoding: 'utf8' }))
44 readPkg(depPkgJson, prefix, nextImportMap)
45 })
46}
47
48const rootPkgJson = JSON.parse(fs.readFileSync('./package.json', { encoding: 'utf8' }))
49readPkg(rootPkgJson, '.', exports)
50
51const testHtml = `
52<!DOCTYPE html>
53<html>
54<head>
55 <title>Testing ${rootPkgJson.name}</title>
56 <script type="importmap">
57 {
58 "imports": ${JSON.stringify(exports, null, 2)},
59 "scopes": ${JSON.stringify(scopes, null, 2)}
60 }
61 </script>
62</head>
63<body>
64 <script type="module" src="${script}"></script>
65</body>
66</html>
67`
68
69console.log(testHtml)