Swagger2.prototype.fixSpec = function () { var swagger = this.spec; //Typical mistake is to make version number insted of string var version = _.get(swagger, 'info.version'); if (_.isNumber(version)) swagger.info.version = version % 1 ? version.toString() : version.toFixed(1); if (this.sourceType == 'url') { var url = URI(this.source); swagger.host = swagger.host || url.host(); swagger.schemes = swagger.schemes || [url.scheme()]; //TODO: deside what to do with base path } Util.removeNonValues(swagger); var basePath = swagger.basePath if (_.isString(basePath)) swagger.basePath = URI().path(basePath).normalize().path(); _.each(swagger.definitions, function (schema) { if (!_.isUndefined(schema.id)) delete schema.id; }); };
/** * Return the corresponding object for a URI, if resolved. If the URI * has not been resolved, it will be returned unmodified. * * @param {string|URI} uri * @returns {Array} */ lookupURI(uri) { if(typeof(uri) === 'string') uri = URI(uri); if(! (uri instanceof URI)) return uri assert(uri instanceof URI) uri = uri.toString(); assert(typeof uri === 'string') assert(uri !== '[object Object]') var object = this._URIs[uri]; if(object === undefined) { this._unresolvedURIs[uri] = true return URI(uri) } else { delete this._unresolvedURIs[uri] return object } }
helper.analyzeLinks = function(options){ var baseURI; try{ // parse base url as URIjs object. baseURI = URI(options.url).normalize(); // the `base` tag in `head` takes top priority as base href. var baseEle = options.ele('head>base'), baseHref; if(baseEle && baseEle.length > 0 && (baseHref = baseEle.eq(0).attr('href'))){ var baseHrefURI = URI(baseHref); if(baseHrefURI.is('absolute')){ baseURI = baseHrefURI; }else{ baseURI = baseHrefURI.absoluteTo(baseURI); } } }catch(err){ return err.message; } var links = []; // map all anchors as simple {title: '', href:''} object. options.ele('a').each(function(idx,lnk){ var ele = helper.analyzeHref({ ele: options.ele(this), domain: options.domain, baseURI: baseURI }); ele && links.push(ele); }); return links; }
links: function(url, options) { options = options || {}; var page = parseInt(options.page, 10); var count = options.count; var perPage = options.perPage; var prev = page - 1; var next = page + 1; var last = Math.floor(count / perPage); if (count % perPage > 0) { ++last; } var links = {}; if (prev > 0) { links.prev = uri(url).query({ page: prev }).toString(); } // if not the last page, show the next and last links if (next <= last) { links.next = uri(url).query({ page: next }).toString(); links.last = uri(url).query({ page: last }).toString(); } return links; }
const ExperimentPageRouter = ({atlasUrl, resourcesUrl, experimentAccession, species, accessKey, tabs}) => { const tabCommonProps = { atlasUrl, resourcesUrl, experimentAccession, species, accessKey } return ( <BrowserRouter basename={URI(`experiments/${experimentAccession}`, URI(atlasUrl).path()).toString()}> <div> <Route path={`/`} render={ (routeProps) => <TopRibbon tabNames={tabs.map((tab) => tab.name)} routeProps={routeProps}/> } /> <Switch> { tabs.map((tab) => <Route key={tab.name} path={`/${tab.name}`} render={ (routeProps) => <TabContent type={tab.type} tabProps={tab.props} commonProps={tabCommonProps} routeProps={routeProps}/> } /> ) } <RedirectWithLocation pathname={`/${tabs[0].name}`} /> </Switch> </div> </BrowserRouter> ) }
$(urlSelector).each(function() { const $element = $(this); $element.nodeName = $element[0].name; const attribute = URI.getDomAttribute($element); if (!attribute) { // element does not have a URL attribute return; } const url = $element.attr(attribute); if (url.slice(0, options.resolve.length) !== options.resolve) { // URL is not using the absolute prefix return; } let resolved = URI(url).relativeTo(absolute).toString(); if (!resolved) { // the file is linking to itself resolved = URI(fileName).filename(); } if (resolved[resolved.length - 1] === '/') { // the file is linking to a directory, append index.html resolved += 'index.html'; } $element.attr(attribute, resolved); });
constructor(sbolDocument, uri) { super(sbolDocument, uri); this._refinement = URI(); this._remote = URI(); this._local = URI(); }
it("also checks the coupon query param", () => { window.location = "http://fake/?coupon=aBc-123." helper.store.dispatch(setDialogVisibility(true)) renderDialog() const link = getEl(document.body, ".signup-dialog a") const expectedNext = URI("/dashboard/").setQuery("coupon", "aBc-123.") const expectedUrl = URI("/login/edxorg").setQuery("next", expectedNext) assert.equal(link.getAttribute("href"), expectedUrl.toString()) })
export function getExploreUrlAndPayload({ formData, endpointType = 'base', force = false, curUrl = null, requestParams = {}, }) { if (!formData.datasource) { return null; } // The search params from the window.location are carried through, // but can be specified with curUrl (used for unit tests to spoof // the window.location). let uri = new URI([location.protocol, '//', location.host].join('')); if (curUrl) { uri = URI(URI(curUrl).search()); } const directory = getURIDirectory(formData, endpointType); // Building the querystring (search) part of the URI const search = uri.search(true); if (formData.slice_id) { search.form_data = JSON.stringify({ slice_id: formData.slice_id }); } if (force) { search.force = 'true'; } if (endpointType === 'csv') { search.csv = 'true'; } if (endpointType === 'standalone') { search.standalone = 'true'; } if (endpointType === 'query') { search.query = 'true'; } const paramNames = Object.keys(requestParams); if (paramNames.length) { paramNames.forEach((name) => { if (requestParams.hasOwnProperty(name)) { search[name] = requestParams[name]; } }); } uri = uri.search(search).directory(directory); const payload = { ...formData }; return { url: uri.toString(), payload, }; }
return opts => { let uri; if (link.templated) { let template = URITemplate(link.href); uri = URI(template.expand(opts || {})); } else { uri = URI(link.href); } return this._sendNormalRequest(uri).then(r => this._parseResponse(r)); };
/** * Server handles the network connection to a [Horizon](https://www.stellar.org/developers/horizon/learn/index.html) * instance and exposes an interface for requests to that instance. * @constructor * @param {string} serverURL Horizon Server URL (ex. `https://horizon-testnet.stellar.org`). The old method (config object parameter) is **deprecated**. */ constructor(serverURL={}) { if (isString(serverURL)) { this.serverURL = URI(serverURL); } else { // We leave the old method for compatibility reasons. // This will be removed in the next major release. this.protocol = serverURL.secure ? "https" : "http"; this.hostname = serverURL.hostname || "localhost"; this.port = serverURL.port || 3000; this.serverURL = URI({ protocol: this.protocol, hostname: this.hostname, port: this.port }); } }
constructor(sbolDocument, uri) { this._sbolDocument = sbolDocument; this._displayId = ''; this._uri = URI(); this._persistentIdentity = URI(); this._version = ''; this._wasDerivedFrom = URI(); this._name = ''; this._description = ''; this._annotations = []; if(uri !== undefined) this.uri = uri; }
export default (options = {}) => { const url = uri(options.url) const cwd = process.cwd() const root = options.root || 'public' const output = options.output || 'capture' const timestamp = options.timestamp || new Date().getTime() const site = url.port() !== 80 ? [url.hostname(), url.port()].join(':') : url.hostname() const destPath = path.join(cwd, root, output, site, url.pathname().split('/').join(path.sep)) const size = options.size || '1024x1000' console.log('Start capture: ', colors.cyan(url.pathname())) return new Pageres({ delay: 1, filename: timestamp ? [timestamp, size].join('__') : '<%= date %>__<%= time %>__<%= size %>' }) .src(url.toString(), [size]) .dest(destPath) .run() .then((file) => { var filename = file[0].filename var filepath = path.relative(cwd, path.join(destPath, file[0].filename)) console.log('Finish captured: ', colors.green(filepath)) return Promise.resolve(filepath) }) }
getResults(e) { this.setState({'loading': true}); if(e) { e.preventDefault(); } let queryPath = URI(window.API_LOCATION) .path([window.API_VERSION, 'legal', 'search'].join('/')) .addQuery('api_key', window.API_KEY) .addQuery('type', 'advisory_opinions'); let queryState = this.getUserSearchCriteria(this.state); Object.keys(queryState).forEach((queryParam) => { queryPath = queryPath.addQuery(queryParam, queryState[queryParam]); }); const lastResultCount = this.state.resultCount; $.getJSON(queryPath.toString(), (results) => { this.setState({ advisory_opinions: results.advisory_opinions, resultCount: results.total_advisory_opinions, lastResultCount, loading: false, lastQuery: this.getUserSearchCriteria(this.state)}, () => { queryPath = queryPath.removeSearch('api_key'); window.history.pushState(URI.parseQuery(queryPath.query()), null, queryPath.search().toString()); }); }); }
return Q.Promise(function(resolve, reject) { var hostname = URI(url).hostname(); tls.connect(443, hostname, { servername: hostname, rejectUnauthorized: false }, function() { if (!this.authorized || this.authorizationError || this.getPeerCertificate().fingerprint !== fingerprint) { // "These are not the certificates you're looking for..." // Seems like they even got a certificate signed for us :O reject('Cannot validate the certificate'); } // looks the SSL is ok :) this.end(); resolve(true); }).on('error', function() { this.end(); reject('No SSL support'); }).on('timeout', function() { this.end(); reject('Connection timed out'); }).setTimeout(10000); // Set 10 second timeout });
HS.login = function(opts, cb) { var url = URI(BASE_URL + '/Login').href(); if (_.isFunction(opts)) { cb = opts; return cb(new Error('You must provide a callback')); } if (!opts.username || !opts.password) { return cb(new Error('You must provide a username and password')); } request.post(url) .send({ key: options.key, username: opts.username, password: opts.password, }) .set('Content-Type', 'application/x-www-form-urlencoded') .end(function(err, res) { if (res.error) { return cb(new Error(res.body.msg)); } cb(null, res.body); }); };
HS.scores = function(opts, cb) { var url = URI(BASE_URL + '/Scores'); if (_.isFunction(opts)) { cb = opts; opts = {}; } if (!cb) { throw new Error('You must provide a callback'); } if (opts.date && !/\d{2}\/\d{2}\/\d{4}/.test(opts.date)) { return cb(new Error('Dates must be formatted as MM/DD/YYYY')); } // add API key opts.key = options.scores_key; url = url.query(opts).href(); request.get(url) .end(function(err, res) { if (res.error) { return cb(new Error(res.body.msg)); } cb(null, res.body); }); };
exports.resizeImage = function(imageUrl, width) { var uri = URI(imageUrl), ext = uri.suffix() file = uri.filename().split('.' + ext)[0]; return uri.filename(file + '-' + width + '.' + ext).toString(); }
function formatResponse(searchAPIResponse) { let response = { statuses: searchAPIResponse.statuses, search_metadata: Object.assign({}, searchAPIResponse.search_metadata) }; console.log(searchAPIResponse.search_metadata); delete response.search_metadata.refresh_url; delete response.search_metadata.next_results; const nextMaxId = uri.parseQuery(searchAPIResponse.search_metadata.next_results).max_id; console.log(nextMaxId); if (nextMaxId) { response.search_metadata.next_results = uri('') .query({ query, count, maxId: nextMaxId }) .toString(); } return response; }
/** * 判断链接是否合法 * @param parsedURL {String} 链接 * @returns {boolean} */ urlIsAllowed(parsedURL) { if (typeof parsedURL === "object") { parsedURL = { protocol: parsedURL.protocol(), hostname: parsedURL.host(), port: parsedURL.port().toString(), path: parsedURL.path(), query: parsedURL.query() }; } let formattedURL = uri(parsedURL).normalize().href(), allowed = false; // The punycode module sometimes chokes on really weird domain // names. Catching those errors to prevent crawler from crashing try { allowed = this._robotsTxts.reduce((result, robots) => { let allowed = robots.isAllowed(formattedURL, this.userAgent); return result !== undefined ? result : allowed; }, undefined); } catch (error) { // URL will be avoided } allowed !== undefined && console.log(`${formattedURL} is ${allowed === undefined ? "allow" : "disallow"}`); return allowed === undefined ? true : allowed; }
* registerCaptcha(apiKey, captchaInBase64) { const url = 'http://rucaptcha.com/in.php'; const targetURL = uri(url); const data = { method: 'base64', key: apiKey, body: captchaInBase64, json: true, }; const result = yield request({ url: targetURL.toString(), form: data, method: 'POST', }); const body = result.body; if (result.statusCode >= 400) { debug(`Captcha service not available. Code ${result.statusCode}`); throw new Error('Captcha service not available'); } const response = JSON.parse(body); if (response.status === 1) { const captchaId = response.request; return yield* this.getResult(apiKey, captchaId); } else { throw new Error(`Error from service: ${JSON.stringify(response)}`); } }
var ImportHelper = function ( rule ) { var exports = {}; if ( ! ( this instanceof ImportHelper ) ) { return new ImportHelper( rule ); } this._originalURI = this._extractURI( rule ); if ( !this._originalURI ) { return false; } this._originalRule = rule; this._mediaQuery = this.getOriginalMediaQuery(); this.URI = URI( this._originalURI ); exports.URI = this.URI; exports.getOriginalURI = this.getOriginalURI.bind( this ); exports.getModifiedRule = this.getModifiedRule.bind( this ); exports.getOriginalRule = this.getOriginalRule.bind( this ); exports.setMediaQuery = this.setMediaQuery.bind( this ); exports.getMediaQuery = this.getMediaQuery.bind( this ); exports.getOriginalMediaQuery = this.getOriginalMediaQuery.bind( this ); return exports; };
exports.TestTransaction = function (req, res) { //main net var tx = ""; axios .post( URI(urlAPI) .segment("transactions") .toString(), `tx=${tx}`, { timeout: config.SUBMIT_TRANSACTION_TIMEOUT } ) .then(function (response) { console.log("response: ", response.data); res.json({ status: 200, msg: "success", data: response.data }); }) .catch(function (response) { console.log(response.data); if (response.type == Error.type) { res.json({ status: 400, msg: "Transaction submission failed.", data: response }); } else { res.json({ status: 400, msg: "Transaction submission failed.", data: response.data }); } }); };
Crawler.prototype.processURL = function(URL,context) { var newURL, crawler = this; // If the URL didn't contain anything, don't fetch it. if (!URL.replace(/\s+/ig,"").length) return false; try { newURL = URI(URL) .absoluteTo(context.url) .normalize(); if (crawler.urlEncoding === "iso8859") { newURL = newURL.iso8859(); } } catch(e) { // Couldn't process the URL, since URIjs choked on it. return false; } // simplecrawler uses slightly different terminology to URIjs. Sorry! return { "protocol": newURL.protocol() || "http", "host": newURL.hostname(), "port": newURL.port() || 80, "path": newURL.resource(), "uriPath": newURL.path() }; };
const contactsURL = function (groupUUID) { let url = URI(config.url).segment('api/v1/contacts.json') if (groupUUID) { url = url.addQuery('group_uuids', groupUUID) } return url.toString() }
clients.findById(code.clientId, function(err, client) { if (err) { return done(err); } var key_hint = client.jwks_uri || client.jwks; jwtBearerClientAuth.verify(cSecret, key_hint, cId, cId, URI(config.get('auth:server:publicUri') + config.get('auth:endpoints:token')) .normalize() .toString(), {}, function(err, valid) { if (err) { if(err.name === 'JsonWebTokenError') { return done(null, err); } else { return done(err); } } if (!valid) { return done(null, valid); } clients.findById(code.clientId, function(err, client) { if (err) { return done(err); } done(null, client); }); }); });
.reduce(function(list,URL) { // Ensure URL is whole and complete try { URL = URI(URL) .absoluteTo(queueItem.url) .normalize() .toString(); } catch(e) { // But if URI.js couldn't parse it - nobody can! return list; } // If we hit an empty item, don't add return it if (!URL.length) return list; // If we don't support the protocol in question if (!crawler.protocolSupported(URL)) return list; // Does the item already exist in the list? if (resources.reduce(function(prev,current) { return prev || current === URL; },false)) return list; return list.concat(URL); },[]);
const onNavigationRequested = (redirectedToUrl, type, willNavigate, mainFrame) => { if (urijs(scope.url).equals(redirectedToUrl)) { // this is the initial open of the task URL, ignore return; } logger.debug(` Page for ${scope.url} asks for redirect. Will navigatate? ${willNavigate ? 'Yes' : 'No'} `); if (followRedirects) { if (mainFrame && type === 'Other') { try { const state = applyUrlFilterFn( redirectFilter, redirectedToUrl, scope.url, addUrl ); if (state === false) { done(`URL ${redirectedToUrl} was not followed`, scope); } else { done(new errors.RedirectError('Redirected', redirectedToUrl), scope); } } catch (e) { logger.debug(`Error on redirect filter (${redirectedToUrl}, ${scope.url})`); done(e); } } } };
function run_remote_command() { var payload = {"command": JSON.parse($('#command').val())}; $.ajax( { contentType: "application/json", type: "POST", url: URI(api_root + "remotes/"+$('#hostname').val()+"/post-remote-command"), success: function(result) { document.getElementById('response').value = JSON.stringify(result) }, error: function(request, status, reason_phrase) { console.log( "status:" + request.status); if(request.status === 400){ document.getElementById('response').value = "status: " + request.status + "\n\nmessage: " + request.getResponseHeader('X-Slycat-Message'); }else { document.getElementById('response').value = "error response from server:\n" + "error request:" + JSON.stringify(request, undefined, 4) + "\n\n status: " + request.status + "\n\n reason: " + reason_phrase; } }, data: JSON.stringify(payload) }); }
const onResourceReceived = (res) => { if (urijs(scope.url).equals(res.url) && parseInt(res.status, 10) >= 400) { // main page returned with a 4XX or higher done(new errors.StatusError(res.statusText, res.status)); return; } };