forked from whitlockjc/path-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
203 lines (185 loc) · 6.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jeremy Whitlock
*
* 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.
*/
'use strict';
var supportedLoaders = {
file: require('./lib/loaders/file'),
http: require('./lib/loaders/http'),
https: require('./lib/loaders/http')
};
var defaultLoader = typeof window === 'object' || typeof importScripts === 'function' ?
supportedLoaders.http :
supportedLoaders.file;
// Load promises polyfill if necessary
/* istanbul ignore if */
if (typeof Promise === 'undefined') {
require('native-promise-only');
}
function getScheme (location) {
if (typeof location !== 'undefined') {
location = location.indexOf('://') === -1 ? '' : location.split('://')[0];
}
return location;
}
/**
* Utility that provides a single API for loading the content of a path/URL.
*
* @module path-loader
*/
function getLoader (location) {
var scheme = getScheme(location);
var loader = supportedLoaders[scheme];
if (typeof loader === 'undefined') {
if (scheme === '') {
loader = defaultLoader;
} else {
throw new Error('Unsupported scheme: ' + scheme);
}
}
return loader;
}
/**
* Loads a document at the provided location and returns a JavaScript object representation.
*
* @param {string} location - The location to the document
* @param {module:path-loader.LoadOptions} [options] - The loader options
*
* @returns {Promise<*>} Always returns a promise even if there is a callback provided
*
* @example
* // Example using Promises
*
* PathLoader
* .load('./package.json')
* .then(JSON.parse)
* .then(function (document) {
* console.log(document.name + ' (' + document.version + '): ' + document.description);
* }, function (err) {
* console.error(err.stack);
* });
*
* @example
* // Example using options.prepareRequest to provide authentication details for a remotely secure URL
*
* PathLoader
* .load('https://api.github.com/repos/whitlockjc/path-loader', {
* prepareRequest: function (req, callback) {
* req.auth('my-username', 'my-password');
* callback(undefined, req);
* }
* })
* .then(JSON.parse)
* .then(function (document) {
* console.log(document.full_name + ': ' + document.description);
* }, function (err) {
* console.error(err.stack);
* });
*
* @example
* // Example loading a YAML file
*
* PathLoader
* .load('/Users/not-you/projects/path-loader/.travis.yml')
* .then(YAML.safeLoad)
* .then(function (document) {
* console.log('path-loader uses the', document.language, 'language.');
* }, function (err) {
* console.error(err.stack);
* });
*
* @example
* // Example loading a YAML file with options.processContent (Useful if you need information in the raw response)
*
* PathLoader
* .load('/Users/not-you/projects/path-loader/.travis.yml', {
* processContent: function (res, callback) {
* callback(YAML.safeLoad(res.text));
* }
* })
* .then(function (document) {
* console.log('path-loader uses the', document.language, 'language.');
* }, function (err) {
* console.error(err.stack);
* });
*/
module.exports.load = function (location, options) {
var allTasks = Promise.resolve();
// Default options to empty object
if (typeof options === 'undefined') {
options = {};
}
// Validate arguments
allTasks = allTasks.then(function () {
if (typeof location === 'undefined') {
throw new TypeError('location is required');
} else if (typeof location !== 'string') {
throw new TypeError('location must be a string');
}
if (typeof options !== 'undefined') {
if (typeof options !== 'object') {
throw new TypeError('options must be an object');
} else if (typeof options.processContent !== 'undefined' && typeof options.processContent !== 'function') {
throw new TypeError('options.processContent must be a function');
}
}
});
// Load the document from the provided location and process it
allTasks = allTasks
.then(function () {
return new Promise(function (resolve, reject) {
var loader = getLoader(location);
loader.load(location, options || {}, function (err, document) {
if (err) {
reject(err);
} else {
resolve(document);
}
});
});
})
.then(function (res) {
if (options.processContent) {
return new Promise(function (resolve, reject) {
// For consistency between file and http, always send an object with a 'text' property containing the raw
// string value being processed.
if (typeof res !== 'object') {
res = {text: res};
}
// Pass the path being loaded
res.location = location;
options.processContent(res, function (err, processed) {
if (err) {
reject(err);
} else {
resolve(processed);
}
});
});
} else {
// If there was no content processor, we will assume that for all objects that it is a Superagent response
// and will return its `text` property value. Otherwise, we will return the raw response.
return typeof res === 'object' ? res.text : res;
}
});
return allTasks;
};