UNPKG

1.9 kBPlain TextView Raw
1/**
2 * @license
3 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
4 * This code may only be used under the BSD style license found at
5 * http://polymer.github.io/LICENSE.txt
6 * The complete set of authors may be found at
7 * http://polymer.github.io/AUTHORS.txt
8 * The complete set of contributors may be found at
9 * http://polymer.github.io/CONTRIBUTORS.txt
10 * Code distributed by Google as part of the polymer project is also
11 * subject to an additional IP rights grant found at
12 * http://polymer.github.io/PATENTS.txt
13 */
14
15import {ResolvedUrl, UrlLoader} from 'polymer-analyzer';
16
17import {getFileContents} from './streams';
18
19import File = require('vinyl');
20
21/**
22 * This is a `UrlLoader` for use with a `polymer-analyzer` that reads files
23 * that have been gathered by a `BuildBundler` transform stream.
24 */
25export class FileMapUrlLoader implements UrlLoader {
26 files: Map<ResolvedUrl, File>;
27 fallbackLoader?: UrlLoader;
28
29 constructor(files: Map<ResolvedUrl, File>, fallbackLoader?: UrlLoader) {
30 this.files = files;
31 this.fallbackLoader = fallbackLoader;
32 }
33
34 // Return true if we can return load the given url.
35 canLoad(url: ResolvedUrl): boolean {
36 return !!(
37 this.files.has(url) ||
38 this.fallbackLoader && this.fallbackLoader.canLoad(url));
39 }
40
41 // Try to load the file from the map. If not in the map, try to load
42 // from the fallback loader.
43 async load(url: ResolvedUrl): Promise<string> {
44 const file = this.files.get(url);
45
46 if (file == null) {
47 if (this.fallbackLoader) {
48 if (this.fallbackLoader.canLoad(url)) {
49 return this.fallbackLoader.load(url);
50 }
51 throw new Error(
52 `${url} not present in file map and fallback loader can not load.`);
53 }
54 throw new Error(`${url} not present in file map and no fallback loader.`);
55 }
56
57 return getFileContents(file);
58 }
59}