url#resolve JavaScript Examples
The following examples show how to use
url#resolve.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: nav.js From nextjs-ipfs-example with MIT License | 6 votes |
BaseLink = ({href, as, ...rest}) => {
const newAs = useMemo(() => {
let baseURI_as = as || href
// make absolute url relative
// when displayed in url bar
if (baseURI_as.startsWith('/')) {
// for static html compilation
baseURI_as = '.' + href
// <IPFSLink href="/about"> => <a class="jsx-2055897931" href="./about">About</a>
// on the client
if (typeof document !== 'undefined') {
baseURI_as = resolve(document.baseURI, baseURI_as)
// => <a href="https://gateway.ipfs.io/ipfs/Qm<hash>/about">About</a>
}
}
return baseURI_as
}, [as, href])
return <Link {...rest} href={href} as={newAs} />
}
Example #2
Source File: index.es.js From ipfs-action with MIT License | 5 votes |
isReady = electron && electron.app && !electron.app.isReady() ? new Promise(resolve => electron.app.once('ready', resolve)) : Promise.resolve()
Example #3
Source File: rehype-docs.js From Nextjs-ja-translation-docs with MIT License | 4 votes |
export default function rehypeDocs({ filePath, tag }) {
const slugger = new GithubSlugger();
const anchorSlugger = new GithubSlugger();
// Don't use the custom tag here, relative URLs to repo files should always go to canary
const blobUrl = `${GITHUB_URL}/${ORGANIZATION_NAME}/${REPOSITORY_NAME}/${DEFAULT_BRANCH}/blob/canary`;
function visitAnchor(node) {
const props = node.properties;
const href = props?.href;
if (!href) return;
props.href = href.replace(SITE_URL, '');
const isDocs = href.startsWith('/docs');
if (props.href === href) {
const isAbsoluteUrl = ABSOLUTE_URL.test(href);
const isHash = href[0] === '#';
const isRepoUrl = !isHash && !isDocs;
if (isAbsoluteUrl || isRepoUrl) {
props.className = 'absolute';
props.target = '_blank';
props.rel = 'noopener noreferrer';
if (!isAbsoluteUrl) {
// Turn any relative URL that's not handled by the Next.js site into an absolute URL
props.href = blobUrl + resolve(filePath, href);
}
return;
}
}
const [relativePath, hash] = props.href.split('#');
// Reset the slugger because single pages can have multiple urls to the same hash
anchorSlugger.reset();
// The URL is relative at this point
props.className = 'relative';
// Update the hash used by anchors to match the one set for headers
props.href = hash ? `${relativePath}#${anchorSlugger.slug(hash)}` : relativePath;
// Relative URL for another documentation route
if (isDocs) {
props.href = removeExt(tag ? props.href.replace('/docs', `/docs/tag/${tag}`) : props.href);
}
}
function visitHeading(node) {
const text = toString(node);
if (!text) return;
const id = slugger.slug(text);
node.properties.className = 'heading';
node.children = [
{
type: 'element',
tagName: 'span',
properties: { id }
},
{
type: 'element',
tagName: 'a',
properties: {
href: `#${id}`
},
children: node.children
},
{
type: 'element',
tagName: 'span',
properties: { className: 'permalink' },
children: [permalinkIcon]
}
];
}
return function transformer(tree) {
visit(tree, node => node.tagName === 'a', visitAnchor);
visit(tree, node => HEADINGS.includes(node.tagName), visitHeading);
visit(tree, node => node.tagName === 'div', visitCard);
};
}
Example #4
Source File: index.es.js From ipfs-action with MIT License | 4 votes |
/**
* Decode buffers into utf-8 string
*
* @return {Promise}
*/
function consumeBody() {
if (this[DISTURBED]) {
return Promise.reject(new Error(`body used already for: ${this.url}`));
}
this[DISTURBED] = true; // body is null
if (this.body === null) {
return Promise.resolve(Buffer.alloc(0));
} // body is string
if (typeof this.body === 'string') {
return Promise.resolve(Buffer.from(this.body));
} // body is blob
if (this.body instanceof Blob) {
return Promise.resolve(this.body[BUFFER]);
} // body is buffer
if (Buffer.isBuffer(this.body)) {
return Promise.resolve(this.body);
} // istanbul ignore if: should never happen
if (!(this.body instanceof Stream)) {
return Promise.resolve(Buffer.alloc(0));
} // body is stream
// get ready to actually consume the body
const accum = [];
let accumBytes = 0;
let abort = false;
return new Promise((resolve, reject) => {
let resTimeout; // allow timeout on slow response body
if (this.timeout) {
resTimeout = setTimeout(() => {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${this.url} (over ${this.timeout}ms)`, 'body-timeout'));
this.body.emit('cancel-request');
}, this.timeout);
} // handle stream error, such as incorrect content-encoding
this.body.on('error', err => {
reject(new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, 'system', err));
});
this.body.on('data', chunk => {
if (abort || chunk === null) {
return;
}
if (this.size && accumBytes + chunk.length > this.size) {
abort = true;
reject(new FetchError(`content size at ${this.url} over limit: ${this.size}`, 'max-size'));
this.body.emit('cancel-request');
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
this.body.on('end', () => {
if (abort) {
return;
}
clearTimeout(resTimeout);
resolve(Buffer.concat(accum));
});
});
}
Example #5
Source File: index.es.js From ipfs-action with MIT License | 4 votes |
/**
* Fetch function
*
* @param {string|Request} url Absolute url or Request instance
* @param {Object} [opts] Fetch options
* @return {Promise}
*/
function fetch(url, opts = {}) {
// wrap http.request into fetch
return isReady.then(() => new Promise((resolve$1, reject) => {
// build request object
const request = new Request(url, opts);
const options = getNodeRequestOptions(request);
const send = request.useElectronNet ? electron.net.request : (options.protocol === 'https:' ? https : http).request; // http.request only support string as host header, this hack make custom host header possible
if (options.headers.host) {
options.headers.host = options.headers.host[0];
}
if (request.signal && request.signal.aborted) {
reject(new FetchError('request aborted', 'abort'));
return;
} // send request
let headers;
if (request.useElectronNet) {
headers = options.headers;
delete options.headers;
options.session = opts.session || electron.session.defaultSession;
options.useSessionCookies = request.useSessionCookies;
} else {
if (opts.agent) options.agent = opts.agent;
}
const req = send(options);
if (request.useElectronNet) {
for (const headerName in headers) {
if (typeof headers[headerName] === 'string') req.setHeader(headerName, headers[headerName]);else {
for (var _iterator = _createForOfIteratorHelperLoose(headers[headerName]), _step; !(_step = _iterator()).done;) {
const headerValue = _step.value;
req.setHeader(headerName, headerValue);
}
}
}
}
let reqTimeout;
const cancelRequest = () => {
if (request.useElectronNet) {
req.abort(); // in electron, `req.destroy()` does not send abort to server
} else {
req.destroy(); // in node.js, `req.abort()` is deprecated
}
};
const abortRequest = () => {
const err = new FetchError('request aborted', 'abort');
reject(err);
cancelRequest();
req.emit('error', err);
};
if (request.signal) {
request.signal.addEventListener('abort', abortRequest);
}
if (request.timeout) {
reqTimeout = setTimeout(() => {
const err = new FetchError(`network timeout at: ${request.url}`, 'request-timeout');
reject(err);
cancelRequest();
}, request.timeout);
}
if (request.useElectronNet) {
// handle authenticating proxies
req.on('login', (authInfo, callback) => {
if (opts.user && opts.password) {
callback(opts.user, opts.password);
} else {
cancelRequest();
reject(new FetchError(`login event received from ${authInfo.host} but no credentials provided`, 'proxy', {
code: 'PROXY_AUTH_FAILED'
}));
}
});
}
req.on('error', err => {
clearTimeout(reqTimeout);
if (request.signal) {
request.signal.removeEventListener('abort', abortRequest);
}
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
});
req.on('abort', () => {
clearTimeout(reqTimeout);
if (request.signal) {
request.signal.removeEventListener('abort', abortRequest);
}
});
req.on('response', res => {
clearTimeout(reqTimeout);
if (request.signal) {
request.signal.removeEventListener('abort', abortRequest);
} // handle redirect
if (fetch.isRedirect(res.statusCode) && request.redirect !== 'manual') {
if (request.redirect === 'error') {
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
return;
}
if (request.counter >= request.follow) {
reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
return;
}
if (!res.headers.location) {
reject(new FetchError(`redirect location header missing at: ${request.url}`, 'invalid-redirect'));
return;
} // per fetch spec, for POST request with 301/302 response, or any request with 303 response, use GET when following redirect
if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
request.method = 'GET';
request.body = null;
request.headers.delete('content-length');
}
request.counter++;
resolve$1(fetch(resolve(request.url, res.headers.location), request));
return;
} // normalize location header for manual redirect mode
const headers = new Headers();
for (var _i = 0, _Object$keys = Object.keys(res.headers); _i < _Object$keys.length; _i++) {
const name = _Object$keys[_i];
if (Array.isArray(res.headers[name])) {
for (var _iterator2 = _createForOfIteratorHelperLoose(res.headers[name]), _step2; !(_step2 = _iterator2()).done;) {
const val = _step2.value;
headers.append(name, val);
}
} else {
headers.append(name, res.headers[name]);
}
}
if (request.redirect === 'manual' && headers.has('location')) {
headers.set('location', resolve(request.url, headers.get('location')));
} // prepare response
let body = new PassThrough();
res.on('error', err => body.emit('error', err));
res.pipe(body);
body.on('error', cancelRequest);
body.on('cancel-request', cancelRequest);
const abortBody = () => {
res.destroy();
res.emit('error', new FetchError('request aborted', 'abort')); // separated from the `.destroy()` because somehow Node's IncomingMessage streams do not emit errors on destroy
};
if (request.signal) {
request.signal.addEventListener('abort', abortBody);
res.on('end', () => {
request.signal.removeEventListener('abort', abortBody);
});
res.on('error', () => {
request.signal.removeEventListener('abort', abortBody);
});
}
const responseOptions = {
url: request.url,
status: res.statusCode,
statusText: res.statusMessage,
headers: headers,
size: request.size,
timeout: request.timeout,
useElectronNet: request.useElectronNet,
useSessionCookies: request.useSessionCookies
}; // HTTP-network fetch step 16.1.2
const codings = headers.get('Content-Encoding'); // HTTP-network fetch step 16.1.3: handle content codings
// in following scenarios we ignore compression support
// 1. running on Electron/net module (it manages it for us)
// 2. HEAD request
// 3. no Content-Encoding header
// 4. no content response (204)
// 5. content not modified response (304)
if (!request.useElectronNet && request.method !== 'HEAD' && codings !== null && res.statusCode !== 204 && res.statusCode !== 304) {
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
// /!\ This is disabled for now, because it seems broken in recent node
// const zlibOptions = {
// flush: zlib.Z_SYNC_FLUSH,
// finishFlush: zlib.Z_SYNC_FLUSH
// }
if (codings === 'gzip' || codings === 'x-gzip') {
// for gzip
body = body.pipe(zlib.createGunzip());
} else if (codings === 'deflate' || codings === 'x-deflate') {
// for deflate
// handle the infamous raw deflate response from old servers
// a hack for old IIS and Apache servers
const raw = res.pipe(new PassThrough());
return raw.once('data', chunk => {
// see http://stackoverflow.com/questions/37519828
if ((chunk[0] & 0x0F) === 0x08) {
body = body.pipe(zlib.createInflate());
} else {
body = body.pipe(zlib.createInflateRaw());
}
const response = new Response(body, responseOptions);
resolve$1(response);
});
}
}
const response = new Response(body, responseOptions);
resolve$1(response);
});
writeToStream(req, request);
}));
}
Example #6
Source File: index.es.js From Lynx with MIT License | 4 votes |
/**
* Consume and convert an entire Body to a Buffer.
*
* Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
*
* @return Promise
*/
function consumeBody() {
var _this4 = this;
if (this[INTERNALS].disturbed) {
return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
}
this[INTERNALS].disturbed = true;
if (this[INTERNALS].error) {
return Body.Promise.reject(this[INTERNALS].error);
}
// body is null
if (this.body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is string
if (typeof this.body === 'string') {
return Body.Promise.resolve(Buffer.from(this.body));
}
// body is blob
if (this.body instanceof Blob) {
return Body.Promise.resolve(this.body[BUFFER]);
}
// body is buffer
if (Buffer.isBuffer(this.body)) {
return Body.Promise.resolve(this.body);
}
// body is ArrayBuffer
if (Object.prototype.toString.call(this.body) === '[object ArrayBuffer]') {
return Body.Promise.resolve(Buffer.from(this.body));
}
// body is ArrayBufferView
if (ArrayBuffer.isView(this.body)) {
return Body.Promise.resolve(Buffer.from(this.body.buffer, this.body.byteOffset, this.body.byteLength));
}
// istanbul ignore if: should never happen
if (!(this.body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise(function (resolve$$1, reject) {
let resTimeout;
// allow timeout on slow response body
if (_this4.timeout) {
resTimeout = setTimeout(function () {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
}, _this4.timeout);
}
// handle stream error, such as incorrect content-encoding
_this4.body.on('error', function (err) {
reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
});
_this4.body.on('data', function (chunk) {
if (abort || chunk === null) {
return;
}
if (_this4.size && accumBytes + chunk.length > _this4.size) {
abort = true;
reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
_this4.body.on('end', function () {
if (abort) {
return;
}
clearTimeout(resTimeout);
try {
resolve$$1(Buffer.concat(accum));
} catch (err) {
// handle streams that have accumulated too much data (issue #414)
reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
}
});
});
}
Example #7
Source File: index.es.js From Lynx with MIT License | 4 votes |
/**
* Fetch function
*
* @param Mixed url Absolute url or Request instance
* @param Object opts Fetch options
* @return Promise
*/
function fetch(url, opts) {
// allow custom promise
if (!fetch.Promise) {
throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
}
Body.Promise = fetch.Promise;
// wrap http.request into fetch
return new fetch.Promise(function (resolve$$1, reject) {
// build request object
const request = new Request(url, opts);
const options = getNodeRequestOptions(request);
const send = (options.protocol === 'https:' ? https : http).request;
// send request
const req = send(options);
let reqTimeout;
function finalize() {
req.abort();
clearTimeout(reqTimeout);
}
if (request.timeout) {
req.once('socket', function (socket) {
reqTimeout = setTimeout(function () {
reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
finalize();
}, request.timeout);
});
}
req.on('error', function (err) {
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
finalize();
});
req.on('response', function (res) {
clearTimeout(reqTimeout);
const headers = createHeadersLenient(res.headers);
// HTTP fetch step 5
if (fetch.isRedirect(res.statusCode)) {
// HTTP fetch step 5.2
const location = headers.get('Location');
// HTTP fetch step 5.3
const locationURL = location === null ? null : resolve(request.url, location);
// HTTP fetch step 5.5
switch (request.redirect) {
case 'error':
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
finalize();
return;
case 'manual':
// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
if (locationURL !== null) {
headers.set('Location', locationURL);
}
break;
case 'follow':
// HTTP-redirect fetch step 2
if (locationURL === null) {
break;
}
// HTTP-redirect fetch step 5
if (request.counter >= request.follow) {
reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
finalize();
return;
}
// HTTP-redirect fetch step 6 (counter increment)
// Create a new Request object.
const requestOpts = {
headers: new Headers(request.headers),
follow: request.follow,
counter: request.counter + 1,
agent: request.agent,
compress: request.compress,
method: request.method,
body: request.body
};
// HTTP-redirect fetch step 9
if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
finalize();
return;
}
// HTTP-redirect fetch step 11
if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
requestOpts.method = 'GET';
requestOpts.body = undefined;
requestOpts.headers.delete('content-length');
}
// HTTP-redirect fetch step 15
resolve$$1(fetch(new Request(locationURL, requestOpts)));
finalize();
return;
}
}
// prepare response
let body = res.pipe(new PassThrough());
const response_options = {
url: request.url,
status: res.statusCode,
statusText: res.statusMessage,
headers: headers,
size: request.size,
timeout: request.timeout
};
// HTTP-network fetch step 12.1.1.3
const codings = headers.get('Content-Encoding');
// HTTP-network fetch step 12.1.1.4: handle content codings
// in following scenarios we ignore compression support
// 1. compression support is disabled
// 2. HEAD request
// 3. no Content-Encoding header
// 4. no content response (204)
// 5. content not modified response (304)
if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
resolve$$1(new Response(body, response_options));
return;
}
// For Node v6+
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
const zlibOptions = {
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
};
// for gzip
if (codings == 'gzip' || codings == 'x-gzip') {
body = body.pipe(zlib.createGunzip(zlibOptions));
resolve$$1(new Response(body, response_options));
return;
}
// for deflate
if (codings == 'deflate' || codings == 'x-deflate') {
// handle the infamous raw deflate response from old servers
// a hack for old IIS and Apache servers
const raw = res.pipe(new PassThrough());
raw.once('data', function (chunk) {
// see http://stackoverflow.com/questions/37519828
if ((chunk[0] & 0x0F) === 0x08) {
body = body.pipe(zlib.createInflate());
} else {
body = body.pipe(zlib.createInflateRaw());
}
resolve$$1(new Response(body, response_options));
});
return;
}
// otherwise, use response as-is
resolve$$1(new Response(body, response_options));
});
writeToStream(req, request);
});
}