mappel 0.0.0-name-check.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ibrahima Toure
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1 +1,26 @@
1
- placeholder
1
+ # mappel
2
+
3
+ This package builds an import map from what a workspace actually imports. It reads package manifests and import statements, and writes JSON. It does not bundle or build anything.
4
+
5
+ The browser resolves a bare specifier only through an import map and never reads package.json. Every transitive subpath has to be listed — including the ones a package reaches through its own dependencies. Written by hand, that list is wrong within a release.
6
+
7
+ It resolves each specifier through the package's own exports map — nested conditions, wildcards, and the form with no "." key — then walks the files it finds for more specifiers. It reports what it could not resolve rather than emitting a map that fails in the browser.
8
+
9
+ A repo declares named layers in importmap.config.mjs, and a layer can exclude what another already resolves, so a page loads two maps and neither repeats the other. Layers can also drop a whole scope by prefix. A css specifier maps to a `.js` sibling that adds the file as a link, because a browser cannot import a stylesheet as a module. Pass `--css link` to get the specifier mapped away and the link tags printed instead.
10
+
11
+ ```sh
12
+ mappel --layer min # to stdout, urls pinned to installed versions
13
+ mappel --layer components --split dist/ # one file per package in the layer
14
+ mappel --layer foundation --target local # workspace paths, for a dev server
15
+ mappel --layer min --html # ready to paste into a page
16
+ ```
17
+
18
+ ```js
19
+ // importmap.config.mjs
20
+ export default {
21
+ layers: {
22
+ base: { packages: ['@scope/core', '@scope/dom'] },
23
+ extra: { packages: ['@scope/extra'], excludes: ['base'] },
24
+ },
25
+ };
26
+ ```
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env node
2
+ // Emit the import map a page needs, from the layers a repo defines.
3
+ //
4
+ // import-map --layer min
5
+ // import-map --layer components --split dist/components
6
+ // import-map --layer foundation --target local --html
7
+ //
8
+ // Layers come from importmap.config.mjs in the repo this runs in, so the tool
9
+ // stays generic and the policy stays where it belongs.
10
+
11
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
12
+ import { join, resolve as resolvePath } from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+ import { buildLayer, subpathsOf } from '../src/index.mjs';
15
+
16
+ const argv = process.argv.slice(2);
17
+ const flag = (name, fallback) => {
18
+ const i = argv.indexOf(`--${name}`);
19
+ return i === -1 ? fallback : argv[i + 1];
20
+ };
21
+ const has = (name) => argv.includes(`--${name}`);
22
+
23
+ // The repo being scanned, not where this tool is installed — it lives in
24
+ // node_modules, and every path it resolves hangs off this.
25
+ const root = resolvePath(flag('root', process.cwd()));
26
+ const configPath = resolvePath(flag('config', join(root, 'importmap.config.mjs')));
27
+
28
+ let config;
29
+ try {
30
+ config = (await import(pathToFileURL(configPath).href)).default;
31
+ } catch (error) {
32
+ process.stderr.write(`[import-map] cannot read ${configPath}\n ${error.message}\n`);
33
+ process.exit(2);
34
+ }
35
+
36
+ const options = {
37
+ root,
38
+ target: flag('target', 'cdn'),
39
+ cdn: flag('cdn', 'https://unpkg.com'),
40
+ css: flag('css', 'loader'),
41
+ workspaces: config.workspaces ?? ['packages'],
42
+ };
43
+
44
+ const layerName = flag('layer', Object.keys(config.layers)[0]);
45
+ const splitInto = flag('split', null);
46
+
47
+ if (splitInto) {
48
+ const layer = config.layers[layerName];
49
+ const names =
50
+ typeof layer.packages === 'function'
51
+ ? layer.packages({ subpathsOf: (n) => subpathsOf(root, n, options.workspaces), root })
52
+ : layer.packages;
53
+ mkdirSync(splitInto, { recursive: true });
54
+ let written = 0;
55
+ for (const name of names) {
56
+ const one = buildLayer(
57
+ layerName,
58
+ { ...config, layers: { ...config.layers, [layerName]: { ...layer, packages: [name] } } },
59
+ options,
60
+ );
61
+ if (Object.keys(one.imports).length === 0) continue;
62
+ writeFileSync(
63
+ join(splitInto, name.split('/').pop() + '.json'),
64
+ JSON.stringify({ imports: one.imports }, null, 2) + '\n',
65
+ );
66
+ written += 1;
67
+ }
68
+ process.stderr.write(`wrote ${written} maps to ${splitInto}\n`);
69
+ process.exit(0);
70
+ }
71
+
72
+ const { imports, stylesheets, unresolved } = buildLayer(layerName, config, options);
73
+ const json = JSON.stringify({ imports }, null, 2);
74
+
75
+ const out = flag('out', null);
76
+ if (out) {
77
+ writeFileSync(out, json + '\n');
78
+ process.stderr.write(`wrote ${out} — ${Object.keys(imports).length} entries\n`);
79
+ } else if (has('html')) {
80
+ const links =
81
+ options.css === 'link'
82
+ ? stylesheets.map((href) => `<link rel="stylesheet" href="${href}" />`).join('\n')
83
+ : '';
84
+ process.stdout.write(`<script type="importmap">\n${json}\n</script>\n${links ? links + '\n' : ''}`);
85
+ } else {
86
+ process.stdout.write(json + '\n');
87
+ }
88
+
89
+ if (unresolved.length) {
90
+ process.stderr.write('\nnot in the map (check they are installed):\n');
91
+ for (const u of unresolved.sort()) process.stderr.write(` ${u}\n`);
92
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "mappel",
3
- "version": "0.0.0-name-check.0",
4
- "description": "placeholder",
5
- "license": "MIT"
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "generate the import map a page needs from a workspace: resolves every transitive subpath through each package exports map, in layers that compose",
6
+ "type": "module",
7
+ "bin": {
8
+ "mappel": "./bin/import-map.mjs",
9
+ "import-map": "./bin/import-map.mjs"
10
+ },
11
+ "exports": {
12
+ ".": "./src/index.mjs",
13
+ "./resolve": "./src/resolve.mjs"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test \"test/*.test.mjs\"",
23
+ "version": "changeset version",
24
+ "release": "npm test && changeset publish"
25
+ },
26
+ "publishConfig": {
27
+ "registry": "https://registry.npmjs.org/",
28
+ "access": "public"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/bambiste/mappel.git"
33
+ },
34
+ "devDependencies": {
35
+ "@changesets/cli": "^3.0.1"
36
+ }
6
37
  }
package/src/index.mjs ADDED
@@ -0,0 +1,120 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import { dirname, join, normalize, relative } from 'node:path';
3
+ import { manifest, packageDir, resolveExport, splitSpecifier, subpathsOf } from './resolve.mjs';
4
+
5
+ const IMPORT_RE = /(?:from|import)\s*["']([^"']+)["']/g;
6
+
7
+ function scanImports(file) {
8
+ let src;
9
+ try {
10
+ src = readFileSync(file, 'utf8');
11
+ } catch {
12
+ return [];
13
+ }
14
+ const found = [];
15
+ for (const [, spec] of src.matchAll(IMPORT_RE)) {
16
+ // Doc comments quote specifiers too; a real one has no whitespace or `${}`.
17
+ if (/\s|\$\{/.test(spec)) continue;
18
+ found.push(spec);
19
+ }
20
+ return found;
21
+ }
22
+
23
+ /**
24
+ * Walk from a set of specifiers to every bare specifier reachable from them,
25
+ * mapped to a url a browser can fetch.
26
+ */
27
+ export function collect(specifiers, options) {
28
+ const { root, target = 'cdn', cdn = 'https://unpkg.com', css = 'loader', workspaces } = options;
29
+ const imports = {};
30
+ const stylesheets = new Set();
31
+ const unresolved = new Set();
32
+ const visited = new Set();
33
+
34
+ const urlFor = (name, dir, file) => {
35
+ const clean = file.replace(/^\.\//, '');
36
+ return target === 'local'
37
+ ? '/' + relative(root, join(dir, clean)).split('\\').join('/')
38
+ : `${cdn}/${name}@${manifest(dir).version}/${clean}`;
39
+ };
40
+
41
+ const add = (spec) => {
42
+ if (visited.has(spec)) return;
43
+ visited.add(spec);
44
+
45
+ const { pkg, sub } = splitSpecifier(spec);
46
+ const dir = packageDir(root, pkg, workspaces);
47
+ if (!dir) return void unresolved.add(spec);
48
+
49
+ const file = resolveExport(dir, sub);
50
+ if (!file) return void unresolved.add(spec);
51
+
52
+ if (spec.endsWith('.css')) {
53
+ stylesheets.add(urlFor(pkg, dir, file));
54
+ // A browser cannot import a stylesheet as a module. The loader sibling adds
55
+ // it as a <link>, so importing a component still brings its styles.
56
+ imports[spec] = css === 'loader' ? urlFor(pkg, dir, file + '.js') : 'data:text/javascript,';
57
+ return;
58
+ }
59
+
60
+ imports[spec] = urlFor(pkg, dir, file);
61
+
62
+ const entry = join(dir, file.replace(/^\.\//, ''));
63
+ const seen = new Set();
64
+ const stack = [entry];
65
+ while (stack.length) {
66
+ const current = stack.pop();
67
+ if (seen.has(current) || !existsSync(current)) continue;
68
+ seen.add(current);
69
+ for (const nested of scanImports(current)) {
70
+ if (nested.startsWith('.')) {
71
+ const next = normalize(join(dirname(current), nested));
72
+ stack.push(existsSync(next) ? next : next + '.js');
73
+ } else if (!nested.startsWith('node:')) {
74
+ add(nested);
75
+ }
76
+ }
77
+ }
78
+ };
79
+
80
+ for (const spec of specifiers) add(spec);
81
+ return { imports, stylesheets: [...stylesheets], unresolved: [...unresolved] };
82
+ }
83
+
84
+ const sorted = (obj) =>
85
+ Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
86
+
87
+ /**
88
+ * Build one named layer. `excludes` names other layers whose entries this one
89
+ * leaves out, so a page loading both is not handed the same entry twice.
90
+ */
91
+ export function buildLayer(name, config, options) {
92
+ const layer = config.layers[name];
93
+ if (!layer) throw new Error(`[import-map] no layer named "${name}"`);
94
+
95
+ const resolveList = (list) => (typeof list === 'function' ? list(helpers(options)) : list);
96
+ const mine = collect(resolveList(layer.packages), { ...options, ...config.options });
97
+
98
+ const skip = new Set();
99
+ for (const other of layer.excludes ?? []) {
100
+ const theirs = collect(resolveList(config.layers[other].packages), { ...options, ...config.options });
101
+ for (const key of Object.keys(theirs.imports)) skip.add(key);
102
+ }
103
+
104
+ const imports = {};
105
+ for (const [key, value] of Object.entries(mine.imports)) {
106
+ if (skip.has(key)) continue;
107
+ if ((layer.excludePrefixes ?? []).some((p) => key.startsWith(p))) continue;
108
+ imports[key] = value;
109
+ }
110
+ return { imports: sorted(imports), stylesheets: mine.stylesheets, unresolved: mine.unresolved };
111
+ }
112
+
113
+ function helpers(options) {
114
+ return {
115
+ subpathsOf: (name) => subpathsOf(options.root, name, options.workspaces),
116
+ root: options.root,
117
+ };
118
+ }
119
+
120
+ export { subpathsOf, packageDir, resolveExport };
@@ -0,0 +1,101 @@
1
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ const manifests = new Map();
5
+
6
+ export function manifest(dir) {
7
+ if (!manifests.has(dir)) {
8
+ manifests.set(dir, JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')));
9
+ }
10
+ return manifests.get(dir);
11
+ }
12
+
13
+ export function splitSpecifier(spec) {
14
+ const parts = spec.split('/');
15
+ const pkg = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
16
+ const sub = spec.length > pkg.length ? '.' + spec.slice(pkg.length) : '.';
17
+ return { pkg, sub };
18
+ }
19
+
20
+ /**
21
+ * Where a package lives. A workspace folder wins over an installed copy, and
22
+ * pnpm's store is searched last: it keeps the real files under
23
+ * .pnpm/<name>@<version>/node_modules/<name>, and a package only appears at the
24
+ * top level when something depends on it directly.
25
+ */
26
+ export function packageDir(root, name, workspaces = ['packages']) {
27
+ for (const dir of workspaces) {
28
+ const local = join(root, dir, name.split('/').pop());
29
+ if (existsSync(join(local, 'package.json'))) {
30
+ try {
31
+ if (manifest(local).name === name) return local;
32
+ } catch {
33
+ /* not a manifest we can read */
34
+ }
35
+ }
36
+ }
37
+ const installed = join(root, 'node_modules', name);
38
+ if (existsSync(join(installed, 'package.json'))) return installed;
39
+
40
+ const store = join(root, 'node_modules', '.pnpm');
41
+ if (existsSync(store)) {
42
+ const prefix = name.replace('/', '+') + '@';
43
+ for (const dir of readdirSync(store).filter((d) => d.startsWith(prefix)).sort().reverse()) {
44
+ const real = join(store, dir, 'node_modules', name);
45
+ if (existsSync(join(real, 'package.json'))) return real;
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /** Conditions nest, and `{ import: { types, default } }` is as common as a string. */
52
+ export function pickTarget(entry) {
53
+ if (typeof entry === 'string') return entry;
54
+ if (Array.isArray(entry)) {
55
+ for (const alt of entry) {
56
+ const found = pickTarget(alt);
57
+ if (found) return found;
58
+ }
59
+ return null;
60
+ }
61
+ if (entry && typeof entry === 'object') {
62
+ for (const key of ['browser', 'import', 'default', 'require']) {
63
+ if (entry[key] === undefined) continue;
64
+ const found = pickTarget(entry[key]);
65
+ if (found) return found;
66
+ }
67
+ }
68
+ return null;
69
+ }
70
+
71
+ export function resolveExport(dir, sub) {
72
+ const m = manifest(dir);
73
+ const exp = m.exports;
74
+ if (!exp) return sub === '.' ? m.module || m.main || null : null;
75
+ // No key starting with '.' means `exports` is a bare set of conditions that IS
76
+ // the root entry — `{ import, require, types }` — rather than a subpath map.
77
+ if (!Object.keys(exp).some((k) => k.startsWith('.'))) {
78
+ return sub === '.' ? pickTarget(exp) : null;
79
+ }
80
+ if (exp[sub] !== undefined) return pickTarget(exp[sub]);
81
+ for (const [pattern, entry] of Object.entries(exp)) {
82
+ if (!pattern.includes('*')) continue;
83
+ const [before, after] = pattern.split('*');
84
+ if (sub.startsWith(before) && sub.endsWith(after)) {
85
+ const filled = sub.slice(before.length, sub.length - (after.length || 0));
86
+ const target = pickTarget(entry);
87
+ if (target) return target.replace('*', filled);
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+
93
+ /** A package with no root export still has subpaths worth mapping. */
94
+ export function subpathsOf(root, name, workspaces) {
95
+ const dir = packageDir(root, name, workspaces);
96
+ if (!dir) return [];
97
+ const exp = manifest(dir).exports || {};
98
+ return Object.keys(exp)
99
+ .filter((k) => k.startsWith('./') && k !== './package.json')
100
+ .map((k) => name + k.slice(1));
101
+ }