Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
guybedford committed Jul 22, 2021
0 parents commit 6017d6b
Show file tree
Hide file tree
Showing 12 changed files with 913 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: CI

on:
push:
branches: main
pull_request:
branches: main

jobs:
test-node:
name: Node.js Tests
runs-on: ubuntu-latest
strategy:
matrix:
node: [14.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node }}
uses: actions/setup-node@v2
with:
node: ${{ matrix.node }}
- run: npm install
- run: npm run build
- run: npm run test

5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
package-lock.json
lib
dist

10 changes: 10 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
MIT License
-----------

Copyright (C) 2020-2021 Guy Bedford

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
133 changes: 133 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Import Map Utility

Generic ImportMap class utility for the manipulation and resolution of import maps, used by JSPM.

## Getting Started

### Installation

Node.js:
```
npm install @jspm/import-map
```

Browser:

```js
const { ImportMap } = await import('https://jspm.dev/@jspm/import-map');
```

`@jspm/import-map` only ships as an ES module, so to use it in Node.js add `"type": "module"` to your package.json file or write an `.mjs` to load it.

### Usage

example.mjs
```js
import { ImportMap } from '@jspm/import-map';

// Must pass a full URL as a base URL for the map
const mapBase = new URL('.', import.meta.url);

const map = new ImportMap(mapBase, {
imports: {
react: 'https://cdn.com/react.js'
},
scopes: {
'https://site.com/': {
react: 'https://cdn.com/react2.js'
}
}
});

// Use the map resolver
map.resolve('react', mapBase) === 'https://cdn.com/react.js';
map.resolve('react', 'https://site.com/') === 'https://cdn.com/react2.js';

// Supports normal URL resolution behaving a browser-compatible ES module resolver
map.resolve('./hello.js', 'https://site.com/') === 'https://site.com/hello.js';

// Mutate the map
map.set('react', './custom-react.js');
map.resolve('react') === new URL('./custom-react.js', mapBase).href;

// Mutate the map inside a custom scope
map.set('react', './custom-react2.js', 'https://another.com/');
map.resolve('react', 'https://another.com/') === new URL('./custom-react2.js', mapBase).href;

// Get the map JSON
console.log(JSON.stringify(map.toJSON(), null, 2));
// {
// "imports": {
// "react": "./custom-react.js"
// },
// "scopes": {
// "https://site.com/": {
// "react": "https://cdn.com/react2.js"
// },
// "https://another.com/": {
// "react": "./custom-react2.js"
// }
// }
// }

// Rebase the map
map.rebase('./map/');
console.log(JSON.stringify(map.toJSON(), null, 2));
// {
// "imports": {
// "react": "../custom-react.js"
// },
// "scopes": {
// "https://site.com/": {
// "react": "https://cdn.com/react2.js"
// },
// "https://another.com/": {
// "react": "../custom-react2.js"
// }
// }
// }

// Flatten the import map (removes unnecessary scope redundancy)
map.set('react', '../custom-react.js', 'https://site.com/');
map.flatten();
console.log(JSON.stringify(map.toJSON(), null, 2));
// {
// "imports": {
// "react": "../custom-react.js"
// },
// "scopes": {
// "https://another.com/": {
// "react": "../custom-react2.js"
// }
// }
// }

// Replace URLs in the map
map.replace('https://cdn.com/', 'https://cdn-mirror.com/');
map.replace('https://another.com/', 'https://another-site.com/');
console.log(JSON.stringify(map.toJSON(), null, 2));
// {
// "imports": {
// "react": "../custom-react.js"
// },
// "scopes": {
// "https://another-site.com/": {
// "react": "../custom-react2.js"
// }
// }
// }
```
## API
See [map.d.ts](blob/main/map.d.ts).
Support is also provided for conditional maps supporting a way to manage generic maps for multiple environment targets, before serializing or resolving for exact environment targets.
## Contributing
**All pull requests welcome!**
### License
MIT
39 changes: 39 additions & 0 deletions map.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
export interface ConditionalTarget {
[env: string]: ConditionalTarget | string | null;
}
export interface IImportMap {
imports?: Record<string, string | null>;
scopes?: {
[scope: string]: Record<string, string | null>;
};
}
export interface IConditionalImportMap {
imports?: Record<string, string | ConditionalTarget | null>;
scopes?: {
[scope: string]: Record<string, string | ConditionalTarget | null>;
};
}
export declare class ImportMap {
#private;
constructor(mapBaseUrl: string | URL, initialMap?: IConditionalImportMap);
clone(): ImportMap;
extend(map: IImportMap | IConditionalImportMap, overrideScopes?: boolean): this;
sort(): void;
set(name: string, target: string | null | ConditionalTarget, parent?: string): void;
replace(url: string, newUrl: string): this;
combineSubpaths(): void;
flatten(): this;
rebase(newBaseUrl?: string, abs?: boolean): this;
/**
* Narrow all mappings to the given conditional environment constraints
*/
setEnv(env: string[] | EnvConstraints): this;
resolve(specifier: string, parentUrl?: URL | string, env?: string[] | EnvConstraints): string | ConditionalTarget | null;
toJSON(): any;
}
export declare type EnvConstraints = {
include?: string[];
exclude?: string[];
covers?: string[][];
};
export declare function resolveConditional(target: string | ConditionalTarget | null, env?: string[] | EnvConstraints): string | ConditionalTarget;
40 changes: 40 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "@jspm/import-map",
"description": "Package Import Map Utility",
"license": "MIT",
"version": "0.1.0",
"types": "map.d.ts",
"scripts": {
"tsc": "tsc -p .",
"tsc:watch": "tsc -p . --watch",
"rollup": "rollup -c",
"build": "npm run tsc && npm run rollup && cp lib/map.d.ts .",
"test": "node --conditions test --enable-source-maps test/test.js",
"test:build": "node --enable-source-maps test/test.js"
},
"type": "module",
"exports": {
"test": "./lib/map.js",
"default": "./dist/map.js"
},
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/jspm/map.git"
},
"keywords": [
"jspm",
"import maps",
"es modules"
],
"author": "Guy Bedford",
"bugs": {
"url": "https://github.com/jspm/map/issues"
},
"homepage": "https://github.com/jspm/map#readme",
"devDependencies": {
"typescript": "^4.3.5"
}
}
25 changes: 25 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { pathToFileURL, fileURLToPath } from 'url';

export default {
input: {
'map': 'lib/map.js',
},
output: {
dir: 'dist',
format: 'esm'
},
plugins: [{
resolveId (specifier, parent) {
if (parent && !specifier.startsWith('./') && !specifier.startsWith('../') && !specifier.startsWith('/'))
return { id: specifier, external: true };
return fileURLToPath(new URL(specifier, parent ? pathToFileURL(parent) : import.meta.url));
}
}],
// disable external module warnings
// (JSPM / the import map handles these for us instead)
onwarn (warning, warn) {
if (warning.code === 'UNRESOLVED_IMPORT')
return;
warn(warning);
}
};
6 changes: 6 additions & 0 deletions src/common/alphabetize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function alphabetize<T> (obj: Record<string, T>): Record<string, T> {
const out: Record<string, T> = {};
for (const key of Object.keys(obj).sort())
out[key] = obj[key];
return out;
}
79 changes: 79 additions & 0 deletions src/common/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
declare global {
// @ts-ignore
var document: any;
// @ts-ignore
var location: any;
// @ts-ignore
var process: any;
}

export let baseUrl: URL;
// @ts-ignore
if (typeof Deno !== 'undefined') {
// @ts-ignore
baseUrl = new URL('file://' + Deno.cwd() + '/');
}
else if (typeof process !== 'undefined' && process.versions.node) {
baseUrl = new URL('file://' + process.cwd() + '/');
}
else if (typeof document as any !== 'undefined') {
const baseEl: any | null = document.querySelector('base[href]');
if (baseEl)
baseUrl = new URL(baseEl.href + (baseEl.href.endsWith('/') ? '' : '/'));
else if (typeof location !== 'undefined')
baseUrl = new URL('../', new URL(location.href));
}

export function importedFrom (parentUrl?: string | URL) {
if (!parentUrl) return '';
return ` imported from ${parentUrl}`;
}

function matchesRoot (url: URL, baseUrl: URL) {
return url.protocol === baseUrl.protocol && url.host === baseUrl.host && url.port === baseUrl.port && url.username === baseUrl.username && url.password === baseUrl.password;
}

export function relativeUrl (url: URL, baseUrl: URL, absolute = false) {
const href = url.href;
const baseUrlHref = baseUrl.href;
if (href.startsWith(baseUrlHref))
return (absolute ? '/' : './') + href.slice(baseUrlHref.length);
if (!matchesRoot(url, baseUrl))
return url.href;
if (absolute)
return url.href;
const baseUrlPath = baseUrl.pathname;
const urlPath = url.pathname;
const minLen = Math.min(baseUrlPath.length, urlPath.length);
let sharedBaseIndex = -1;
for (let i = 0; i < minLen; i++) {
if (baseUrlPath[i] !== urlPath[i]) break;
if (urlPath[i] === '/') sharedBaseIndex = i;
}
return '../'.repeat(baseUrlPath.slice(sharedBaseIndex + 1).split('/').length - 1) + urlPath.slice(sharedBaseIndex + 1) + url.search + url.hash;
}

export function isURL (specifier: string) {
try {
if (specifier[0] === '#')
return false;
new URL(specifier);
}
catch {
return false;
}
return true;
}

export function isPlain (specifier: string) {
return !isRelative(specifier) && !isURL(specifier);
}

export function isRelative (specifier: string) {
return specifier.startsWith('./') || specifier.startsWith('../') || specifier.startsWith('/');
}

export function urlToNiceStr (url: string) {
if (url.startsWith(baseUrl.href))
return './' + url.slice(baseUrl.href.length);
}
Loading

0 comments on commit 6017d6b

Please sign in to comment.