diff --git a/.eslintrc.js b/.eslintrc.js index 43a3ad8c..81e9841c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1 +1,13 @@ -module.exports = require('@betahuhn/config').eslint \ No newline at end of file +const eslintConfig = require('@betahuhn/config').eslint; + +eslintConfig.parserOptions = { + ...eslintConfig.parserOptions, + ecmaVersion: "latest", +} +eslintConfig.rules = { + ...eslintConfig.rules, + 'comma-dangle': 0, + 'brace-style': 0, +} + +module.exports = eslintConfig \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 5cad031a..689cc6df 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2313,7 +2313,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var endpoint = __nccwpck_require__(9440); var universalUserAgent = __nccwpck_require__(5030); var isPlainObject = __nccwpck_require__(3287); -var nodeFetch = _interopDefault(__nccwpck_require__(3801)); +var nodeFetch = _interopDefault(__nccwpck_require__(467)); var requestError = __nccwpck_require__(9910); const VERSION = "5.6.3"; @@ -2393,1799 +2393,94 @@ function fetchWrapper(requestOptions) { response: { url, status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - - return getResponseData(response); - }).then(data => { - return { - status, - url, - headers, - data - }; - }).catch(error => { - if (error instanceof requestError.RequestError) throw error; - throw new requestError.RequestError(error.message, 500, { - request: requestOptions - }); - }); -} - -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - - if (/application\/json/.test(contentType)) { - return response.json(); - } - - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } - - return getBufferResponse(response); -} - -function toErrorMessage(data) { - if (typeof data === "string") return data; // istanbul ignore else - just in case - - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; - } - - return data.message; - } // istanbul ignore next - just in case - - - return `Unknown error: ${JSON.stringify(data)}`; -} - -function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); - - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); - } - - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); - }; - - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); - return endpointOptions.request.hook(request, endpointOptions); - }; - - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); -} - -const request = withDefaults(endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } -}); - -exports.request = request; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 3801: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__nccwpck_require__(2781)); -var http = _interopDefault(__nccwpck_require__(3685)); -var Url = _interopDefault(__nccwpck_require__(7310)); -var whatwgUrl = _interopDefault(__nccwpck_require__(8665)); -var https = _interopDefault(__nccwpck_require__(5687)); -var zlib = _interopDefault(__nccwpck_require__(9796)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); - - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} - -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); - -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ - -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); - - this.message = message; - this.type = type; - - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = (__nccwpck_require__(2877).convert); -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; - -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - -/** - * 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); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(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, 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 errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - - 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); - }); - - body.on('end', function () { - if (abort) { - return; - } - - clearTimeout(resTimeout); - - try { - resolve(Buffer.concat(accum, accumBytes)); - } 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)); - } - }); - }); -} - -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} - -const INTERNAL = Symbol('internal'); - -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} - -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } - - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; -} - -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; - -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); - -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); - -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; - -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; - -/** - * Wrapper around `new URL` to handle arbitrary URLs - * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 - */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } - - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} - -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } - - get redirect() { - return this[INTERNALS$2].redirect; - } - - get signal() { - return this[INTERNALS$2].signal; - } - - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} - -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} - -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ - -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); - - this.type = 'aborted'; - this.message = message; - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; - -const URL$1 = Url.URL || whatwgUrl.URL; - -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; - -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; - - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; - -/** - * 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, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); - - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - - let response = null; - - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - - // send request - const req = send(options); - let reqTimeout; - - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } - - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - 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 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, 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) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - 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; - } + headers, + data + }, + request: requestOptions + }); + throw error; + } - // 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, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; + return getResponseData(response); + }).then(data => { + return { + status, + url, + headers, + data + }; + }).catch(error => { + if (error instanceof requestError.RequestError) throw error; + throw new requestError.RequestError(error.message, 500, { + request: requestOptions + }); + }); +} - if (!isDomainOrSubdomain(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); - // 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; - } + if (/application\/json/.test(contentType)) { + return response.json(); + } - // 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'); - } + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } + return getBufferResponse(response); +} - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); +function toErrorMessage(data) { + if (typeof data === "string") return data; // istanbul ignore else - just in case - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; + } - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); + return data.message; + } // istanbul ignore next - just in case - // 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) { - response = new Response(body, response_options); - resolve(response); - return; - } + return `Unknown error: ${JSON.stringify(data)}`; +} - // 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 - }; +function withDefaults(oldEndpoint, newDefaults) { + const endpoint = oldEndpoint.defaults(newDefaults); - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + const newApi = function (route, parameters) { + const endpointOptions = endpoint.merge(route, parameters); - // 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$1()); - 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()); - } - response = new Response(body, response_options); - resolve(response); - }); - return; - } + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint.parse(endpointOptions)); + } - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } + const request = (route, parameters) => { + return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + }; - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); + Object.assign(request, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); + return endpointOptions.request.hook(request, endpointOptions); + }; - writeToStream(req, request); - }); + return Object.assign(newApi, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); } -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; -// expose Promise -fetch.Promise = global.Promise; +const request = withDefaults(endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } +}); -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; +exports.request = request; +//# sourceMappingURL=index.js.map /***/ }), @@ -17224,6 +15519,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var Stream = _interopDefault(__nccwpck_require__(2781)); var http = _interopDefault(__nccwpck_require__(3685)); var Url = _interopDefault(__nccwpck_require__(7310)); +var whatwgUrl = _interopDefault(__nccwpck_require__(8665)); var https = _interopDefault(__nccwpck_require__(5687)); var zlib = _interopDefault(__nccwpck_require__(9796)); @@ -18358,11 +16654,32 @@ Object.defineProperty(Response.prototype, Symbol.toStringTag, { }); const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; // fix an issue where "format", "parse" aren't a named export for node <10 const parse_url = Url.parse; const format_url = Url.format; +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; /** @@ -18399,14 +16716,14 @@ class Request { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) - parsedURL = parse_url(input.href); + parsedURL = parseURL(input.href); } else { // coerce input to a string before attempting to parse - parsedURL = parse_url(`${input}`); + parsedURL = parseURL(`${input}`); } input = {}; } else { - parsedURL = parse_url(input.url); + parsedURL = parseURL(input.url); } let method = init.method || input.method || 'GET'; @@ -18560,10 +16877,6 @@ function getNodeRequestOptions(request) { agent = agent(parsedURL); } - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js @@ -18600,9 +16913,31 @@ AbortError.prototype = Object.create(Error.prototype); AbortError.prototype.constructor = AbortError; AbortError.prototype.name = 'AbortError'; +const URL$1 = Url.URL || whatwgUrl.URL; + // fix an issue where "PassThrough", "resolve" aren't a named export for node <10 const PassThrough$1 = Stream.PassThrough; -const resolve_url = Url.resolve; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; /** * Fetch function @@ -18635,7 +16970,7 @@ function fetch(url, opts) { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); + destroyStream(request.body, error); } if (!response || !response.body) return; response.body.emit('error', error); @@ -18676,9 +17011,43 @@ function fetch(url, opts) { req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + finalize(); }); + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + req.on('response', function (res) { clearTimeout(reqTimeout); @@ -18690,7 +17059,19 @@ function fetch(url, opts) { const location = headers.get('Location'); // HTTP fetch step 5.3 - const locationURL = location === null ? null : resolve_url(request.url, location); + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } // HTTP fetch step 5.5 switch (request.redirect) { @@ -18738,6 +17119,12 @@ function fetch(url, opts) { size: request.size }; + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + // 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')); @@ -18825,6 +17212,13 @@ function fetch(url, opts) { response = new Response(body, response_options); resolve(response); }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); return; } @@ -18844,6 +17238,44 @@ function fetch(url, opts) { writeToStream(req, request); }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + /** * Redirect code matching * @@ -18864,6 +17296,7 @@ exports.Headers = Headers; exports.Request = Request; exports.Response = Response; exports.FetchError = FetchError; +exports.AbortError = AbortError; /***/ }), @@ -19057,42 +17490,28 @@ module.exports = readfiles; var lib = __nccwpck_require__(4127); - var _require = __nccwpck_require__(4428), - Environment = _require.Environment, - Template = _require.Template; - + Environment = _require.Environment, + Template = _require.Template; var Loader = __nccwpck_require__(6981); - var loaders = __nccwpck_require__(4395); - var precompile = __nccwpck_require__(7513); - var compiler = __nccwpck_require__(4548); - var parser = __nccwpck_require__(6614); - var lexer = __nccwpck_require__(3158); - var runtime = __nccwpck_require__(1998); - var nodes = __nccwpck_require__(429); +var installJinjaCompat = __nccwpck_require__(6976); -var installJinjaCompat = __nccwpck_require__(6976); // A single instance of an environment, since this is so commonly used - - +// A single instance of an environment, since this is so commonly used var e; - function configure(templatesPath, opts) { opts = opts || {}; - if (lib.isObject(templatesPath)) { opts = templatesPath; templatesPath = null; } - var TemplateLoader; - if (loaders.FileSystemLoader) { TemplateLoader = new loaders.FileSystemLoader(templatesPath, { watch: opts.watch, @@ -19104,16 +17523,12 @@ function configure(templatesPath, opts) { async: opts.web && opts.web.async }); } - e = new Environment(TemplateLoader, opts); - if (opts && opts.express) { e.express(opts.express); } - return e; } - module.exports = { Environment: Environment, Template: Template, @@ -19137,21 +17552,18 @@ module.exports = { if (!e) { configure(); } - return new Template(src, env, path, eagerCompile); }, render: function render(name, ctx, cb) { if (!e) { configure(); } - return e.render(name, ctx, cb); }, renderString: function renderString(src, ctx, cb) { if (!e) { configure(); } - return e.renderString(src, ctx, cb); }, precompile: precompile ? precompile.precompile : undefined, @@ -19167,26 +17579,19 @@ module.exports = { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var parser = __nccwpck_require__(6614); - var transformer = __nccwpck_require__(3773); - var nodes = __nccwpck_require__(429); - var _require = __nccwpck_require__(4127), - TemplateError = _require.TemplateError; - + TemplateError = _require.TemplateError; var _require2 = __nccwpck_require__(1998), - Frame = _require2.Frame; - + Frame = _require2.Frame; var _require3 = __nccwpck_require__(7007), - Obj = _require3.Obj; // These are all the same for now, but shouldn't be passed straight -// through - + Obj = _require3.Obj; +// These are all the same for now, but shouldn't be passed straight +// through var compareOps = { '==': '==', '===': '===', @@ -19197,16 +17602,12 @@ var compareOps = { '<=': '<=', '>=': '>=' }; - var Compiler = /*#__PURE__*/function (_Obj) { _inheritsLoose(Compiler, _Obj); - function Compiler() { return _Obj.apply(this, arguments) || this; } - var _proto = Compiler.prototype; - _proto.init = function init(templateName, throwOnUndefined) { this.templateName = templateName; this.codebuf = []; @@ -19217,258 +17618,186 @@ var Compiler = /*#__PURE__*/function (_Obj) { this.inBlock = false; this.throwOnUndefined = throwOnUndefined; }; - _proto.fail = function fail(msg, lineno, colno) { if (lineno !== undefined) { lineno += 1; } - if (colno !== undefined) { colno += 1; } - throw new TemplateError(msg, lineno, colno); }; - _proto._pushBuffer = function _pushBuffer() { var id = this._tmpid(); - this.bufferStack.push(this.buffer); this.buffer = id; - this._emit("var " + this.buffer + " = \"\";"); - return id; }; - _proto._popBuffer = function _popBuffer() { this.buffer = this.bufferStack.pop(); }; - _proto._emit = function _emit(code) { this.codebuf.push(code); }; - _proto._emitLine = function _emitLine(code) { this._emit(code + '\n'); }; - _proto._emitLines = function _emitLines() { var _this = this; - for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) { lines[_key] = arguments[_key]; } - lines.forEach(function (line) { return _this._emitLine(line); }); }; - _proto._emitFuncBegin = function _emitFuncBegin(node, name) { this.buffer = 'output'; this._scopeClosers = ''; - this._emitLine("function " + name + "(env, context, frame, runtime, cb) {"); - this._emitLine("var lineno = " + node.lineno + ";"); - this._emitLine("var colno = " + node.colno + ";"); - this._emitLine("var " + this.buffer + " = \"\";"); - this._emitLine('try {'); }; - _proto._emitFuncEnd = function _emitFuncEnd(noReturn) { if (!noReturn) { this._emitLine('cb(null, ' + this.buffer + ');'); } - this._closeScopeLevels(); - this._emitLine('} catch (e) {'); - this._emitLine(' cb(runtime.handleError(e, lineno, colno));'); - this._emitLine('}'); - this._emitLine('}'); - this.buffer = null; }; - _proto._addScopeLevel = function _addScopeLevel() { this._scopeClosers += '})'; }; - _proto._closeScopeLevels = function _closeScopeLevels() { this._emitLine(this._scopeClosers + ';'); - this._scopeClosers = ''; }; - _proto._withScopedSyntax = function _withScopedSyntax(func) { var _scopeClosers = this._scopeClosers; this._scopeClosers = ''; func.call(this); - this._closeScopeLevels(); - this._scopeClosers = _scopeClosers; }; - _proto._makeCallback = function _makeCallback(res) { var err = this._tmpid(); - return 'function(' + err + (res ? ',' + res : '') + ') {\n' + 'if(' + err + ') { cb(' + err + '); return; }'; }; - _proto._tmpid = function _tmpid() { this.lastId++; return 't_' + this.lastId; }; - _proto._templateName = function _templateName() { return this.templateName == null ? 'undefined' : JSON.stringify(this.templateName); }; - _proto._compileChildren = function _compileChildren(node, frame) { var _this2 = this; - node.children.forEach(function (child) { _this2.compile(child, frame); }); }; - _proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) { var _this3 = this; - if (startChar) { this._emit(startChar); } - node.children.forEach(function (child, i) { if (i > 0) { _this3._emit(','); } - _this3.compile(child, frame); }); - if (endChar) { this._emit(endChar); } }; - _proto._compileExpression = function _compileExpression(node, frame) { // TODO: I'm not really sure if this type check is worth it or // not. this.assertType(node, nodes.Literal, nodes.Symbol, nodes.Group, nodes.Array, nodes.Dict, nodes.FunCall, nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, nodes.In, nodes.Is, nodes.And, nodes.Or, nodes.Not, nodes.Add, nodes.Concat, nodes.Sub, nodes.Mul, nodes.Div, nodes.FloorDiv, nodes.Mod, nodes.Pow, nodes.Neg, nodes.Pos, nodes.Compare, nodes.NodeList); this.compile(node, frame); }; - _proto.assertType = function assertType(node) { for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { types[_key2 - 1] = arguments[_key2]; } - if (!types.some(function (t) { return node instanceof t; })) { this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno); } }; - _proto.compileCallExtension = function compileCallExtension(node, frame, async) { var _this4 = this; - var args = node.args; var contentArgs = node.contentArgs; var autoescape = typeof node.autoescape === 'boolean' ? node.autoescape : true; - if (!async) { this._emit(this.buffer + " += runtime.suppressValue("); } - this._emit("env.getExtension(\"" + node.extName + "\")[\"" + node.prop + "\"]("); - this._emit('context'); - if (args || contentArgs) { this._emit(','); } - if (args) { if (!(args instanceof nodes.NodeList)) { this.fail('compileCallExtension: arguments must be a NodeList, ' + 'use `parser.parseSignature`'); } - args.children.forEach(function (arg, i) { // Tag arguments are passed normally to the call. Note // that keyword arguments are turned into a single js // object as the last argument, if they exist. _this4._compileExpression(arg, frame); - if (i !== args.children.length - 1 || contentArgs.length) { _this4._emit(','); } }); } - if (contentArgs.length) { contentArgs.forEach(function (arg, i) { if (i > 0) { _this4._emit(','); } - if (arg) { _this4._emitLine('function(cb) {'); - _this4._emitLine('if(!cb) { cb = function(err) { if(err) { throw err; }}}'); - var id = _this4._pushBuffer(); - _this4._withScopedSyntax(function () { _this4.compile(arg, frame); - _this4._emitLine("cb(null, " + id + ");"); }); - _this4._popBuffer(); - _this4._emitLine("return " + id + ";"); - _this4._emitLine('}'); } else { _this4._emit('null'); } }); } - if (async) { var res = this._tmpid(); - this._emitLine(', ' + this._makeCallback(res)); - this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);"); - this._addScopeLevel(); } else { this._emit(')'); - this._emit(", " + autoescape + " && env.opts.autoescape);\n"); } }; - _proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) { this.compileCallExtension(node, frame, true); }; - _proto.compileNodeList = function compileNodeList(node, frame) { this._compileChildren(node, frame); }; - _proto.compileLiteral = function compileLiteral(node) { if (typeof node.value === 'string') { var val = node.value.replace(/\\/g, '\\\\'); @@ -19477,7 +17806,6 @@ var Compiler = /*#__PURE__*/function (_Obj) { val = val.replace(/\r/g, '\\r'); val = val.replace(/\t/g, '\\t'); val = val.replace(/\u2028/g, "\\u2028"); - this._emit("\"" + val + "\""); } else if (node.value === null) { this._emit('null'); @@ -19485,418 +17813,295 @@ var Compiler = /*#__PURE__*/function (_Obj) { this._emit(node.value.toString()); } }; - _proto.compileSymbol = function compileSymbol(node, frame) { var name = node.value; var v = frame.lookup(name); - if (v) { this._emit(v); } else { this._emit('runtime.contextOrFrameLookup(' + 'context, frame, "' + name + '")'); } }; - _proto.compileGroup = function compileGroup(node, frame) { this._compileAggregate(node, frame, '(', ')'); }; - _proto.compileArray = function compileArray(node, frame) { this._compileAggregate(node, frame, '[', ']'); }; - _proto.compileDict = function compileDict(node, frame) { this._compileAggregate(node, frame, '{', '}'); }; - _proto.compilePair = function compilePair(node, frame) { var key = node.key; var val = node.value; - if (key instanceof nodes.Symbol) { key = new nodes.Literal(key.lineno, key.colno, key.value); } else if (!(key instanceof nodes.Literal && typeof key.value === 'string')) { this.fail('compilePair: Dict keys must be strings or names', key.lineno, key.colno); } - this.compile(key, frame); - this._emit(': '); - this._compileExpression(val, frame); }; - _proto.compileInlineIf = function compileInlineIf(node, frame) { this._emit('('); - this.compile(node.cond, frame); - this._emit('?'); - this.compile(node.body, frame); - this._emit(':'); - if (node.else_ !== null) { this.compile(node.else_, frame); } else { this._emit('""'); } - this._emit(')'); }; - _proto.compileIn = function compileIn(node, frame) { this._emit('runtime.inOperator('); - this.compile(node.left, frame); - this._emit(','); - this.compile(node.right, frame); - this._emit(')'); }; - _proto.compileIs = function compileIs(node, frame) { // first, we need to try to get the name of the test function, if it's a // callable (i.e., has args) and not a symbol. - var right = node.right.name ? node.right.name.value // otherwise go with the symbol value + var right = node.right.name ? node.right.name.value + // otherwise go with the symbol value : node.right.value; - this._emit('env.getTest("' + right + '").call(context, '); - - this.compile(node.left, frame); // compile the arguments for the callable if they exist - + this.compile(node.left, frame); + // compile the arguments for the callable if they exist if (node.right.args) { this._emit(','); - this.compile(node.right.args, frame); } - this._emit(') === true'); }; - _proto._binOpEmitter = function _binOpEmitter(node, frame, str) { this.compile(node.left, frame); - this._emit(str); - this.compile(node.right, frame); - } // ensure concatenation instead of addition + } + + // ensure concatenation instead of addition // by adding empty string in between ; - _proto.compileOr = function compileOr(node, frame) { return this._binOpEmitter(node, frame, ' || '); }; - _proto.compileAnd = function compileAnd(node, frame) { return this._binOpEmitter(node, frame, ' && '); }; - _proto.compileAdd = function compileAdd(node, frame) { return this._binOpEmitter(node, frame, ' + '); }; - _proto.compileConcat = function compileConcat(node, frame) { return this._binOpEmitter(node, frame, ' + "" + '); }; - _proto.compileSub = function compileSub(node, frame) { return this._binOpEmitter(node, frame, ' - '); }; - _proto.compileMul = function compileMul(node, frame) { return this._binOpEmitter(node, frame, ' * '); }; - _proto.compileDiv = function compileDiv(node, frame) { return this._binOpEmitter(node, frame, ' / '); }; - _proto.compileMod = function compileMod(node, frame) { return this._binOpEmitter(node, frame, ' % '); }; - _proto.compileNot = function compileNot(node, frame) { this._emit('!'); - this.compile(node.target, frame); }; - _proto.compileFloorDiv = function compileFloorDiv(node, frame) { this._emit('Math.floor('); - this.compile(node.left, frame); - this._emit(' / '); - this.compile(node.right, frame); - this._emit(')'); }; - _proto.compilePow = function compilePow(node, frame) { this._emit('Math.pow('); - this.compile(node.left, frame); - this._emit(', '); - this.compile(node.right, frame); - this._emit(')'); }; - _proto.compileNeg = function compileNeg(node, frame) { this._emit('-'); - this.compile(node.target, frame); }; - _proto.compilePos = function compilePos(node, frame) { this._emit('+'); - this.compile(node.target, frame); }; - _proto.compileCompare = function compileCompare(node, frame) { var _this5 = this; - this.compile(node.expr, frame); node.ops.forEach(function (op) { _this5._emit(" " + compareOps[op.type] + " "); - _this5.compile(op.expr, frame); }); }; - _proto.compileLookupVal = function compileLookupVal(node, frame) { this._emit('runtime.memberLookup(('); - this._compileExpression(node.target, frame); - this._emit('),'); - this._compileExpression(node.val, frame); - this._emit(')'); }; - _proto._getNodeName = function _getNodeName(node) { switch (node.typename) { case 'Symbol': return node.value; - case 'FunCall': return 'the return value of (' + this._getNodeName(node.name) + ')'; - case 'LookupVal': return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]'; - case 'Literal': return node.value.toString(); - default: return '--expression--'; } }; - _proto.compileFunCall = function compileFunCall(node, frame) { // Keep track of line/col info at runtime by settings // variables within an expression. An expression in javascript // like (x, y, z) returns the last value, and x and y can be // anything this._emit('(lineno = ' + node.lineno + ', colno = ' + node.colno + ', '); + this._emit('runtime.callWrap('); + // Compile it as normal. + this._compileExpression(node.name, frame); - this._emit('runtime.callWrap('); // Compile it as normal. - - - this._compileExpression(node.name, frame); // Output the name of what we're calling so we can get friendly errors + // Output the name of what we're calling so we can get friendly errors // if the lookup fails. - - this._emit(', "' + this._getNodeName(node.name).replace(/"/g, '\\"') + '", context, '); - this._compileAggregate(node.args, frame, '[', '])'); - this._emit(')'); }; - _proto.compileFilter = function compileFilter(node, frame) { var name = node.name; this.assertType(name, nodes.Symbol); - this._emit('env.getFilter("' + name.value + '").call(context, '); - this._compileAggregate(node.args, frame); - this._emit(')'); }; - _proto.compileFilterAsync = function compileFilterAsync(node, frame) { var name = node.name; var symbol = node.symbol.value; this.assertType(name, nodes.Symbol); frame.set(symbol, symbol); - this._emit('env.getFilter("' + name.value + '").call(context, '); - this._compileAggregate(node.args, frame); - this._emitLine(', ' + this._makeCallback(symbol)); - this._addScopeLevel(); }; - _proto.compileKeywordArgs = function compileKeywordArgs(node, frame) { this._emit('runtime.makeKeywordArgs('); - this.compileDict(node, frame); - this._emit(')'); }; - _proto.compileSet = function compileSet(node, frame) { var _this6 = this; + var ids = []; - var ids = []; // Lookup the variable names for each identifier and create + // Lookup the variable names for each identifier and create // new ones if necessary - node.targets.forEach(function (target) { var name = target.value; var id = frame.lookup(name); - if (id === null || id === undefined) { - id = _this6._tmpid(); // Note: This relies on js allowing scope across - // blocks, in case this is created inside an `if` + id = _this6._tmpid(); + // Note: This relies on js allowing scope across + // blocks, in case this is created inside an `if` _this6._emitLine('var ' + id + ';'); } - ids.push(id); }); - if (node.value) { this._emit(ids.join(' = ') + ' = '); - this._compileExpression(node.value, frame); - this._emitLine(';'); } else { this._emit(ids.join(' = ') + ' = '); - this.compile(node.body, frame); - this._emitLine(';'); } - node.targets.forEach(function (target, i) { var id = ids[i]; - var name = target.value; // We are running this for every var, but it's very - // uncommon to assign to multiple vars anyway + var name = target.value; + // We are running this for every var, but it's very + // uncommon to assign to multiple vars anyway _this6._emitLine("frame.set(\"" + name + "\", " + id + ", true);"); - _this6._emitLine('if(frame.topLevel) {'); - _this6._emitLine("context.setVariable(\"" + name + "\", " + id + ");"); - _this6._emitLine('}'); - if (name.charAt(0) !== '_') { _this6._emitLine('if(frame.topLevel) {'); - _this6._emitLine("context.addExport(\"" + name + "\", " + id + ");"); - _this6._emitLine('}'); } }); }; - _proto.compileSwitch = function compileSwitch(node, frame) { var _this7 = this; - this._emit('switch ('); - this.compile(node.expr, frame); - this._emit(') {'); - node.cases.forEach(function (c, i) { _this7._emit('case '); - _this7.compile(c.cond, frame); - _this7._emit(': '); - - _this7.compile(c.body, frame); // preserve fall-throughs - - + _this7.compile(c.body, frame); + // preserve fall-throughs if (c.body.children.length) { _this7._emitLine('break;'); } }); - if (node.default) { this._emit('default:'); - this.compile(node.default, frame); } - this._emit('}'); }; - _proto.compileIf = function compileIf(node, frame, async) { var _this8 = this; - this._emit('if('); - this._compileExpression(node.cond, frame); - this._emitLine(') {'); - this._withScopedSyntax(function () { _this8.compile(node.body, frame); - if (async) { _this8._emit('cb()'); } }); - if (node.else_) { this._emitLine('}\nelse {'); - this._withScopedSyntax(function () { _this8.compile(node.else_, frame); - if (async) { _this8._emit('cb()'); } }); } else if (async) { this._emitLine('}\nelse {'); - this._emit('cb()'); } - this._emitLine('}'); }; - _proto.compileIfAsync = function compileIfAsync(node, frame) { this._emit('(function(cb) {'); - this.compileIf(node, frame, true); - this._emit('})(' + this._makeCallback()); - this._addScopeLevel(); }; - _proto._emitLoopBindings = function _emitLoopBindings(node, arr, i, len) { var _this9 = this; - var bindings = [{ name: 'index', val: i + " + 1" @@ -19923,404 +18128,279 @@ var Compiler = /*#__PURE__*/function (_Obj) { _this9._emitLine("frame.set(\"loop." + b.name + "\", " + b.val + ");"); }); }; - _proto.compileFor = function compileFor(node, frame) { var _this10 = this; - // Some of this code is ugly, but it keeps the generated code // as fast as possible. ForAsync also shares some of this, but // not much. - var i = this._tmpid(); + var i = this._tmpid(); var len = this._tmpid(); - var arr = this._tmpid(); - frame = frame.push(); - this._emitLine('frame = frame.push();'); - this._emit("var " + arr + " = "); - this._compileExpression(node.arr, frame); - this._emitLine(';'); - this._emit("if(" + arr + ") {"); + this._emitLine(arr + ' = runtime.fromIterator(' + arr + ');'); - this._emitLine(arr + ' = runtime.fromIterator(' + arr + ');'); // If multiple names are passed, we need to bind them + // If multiple names are passed, we need to bind them // appropriately - - if (node.name instanceof nodes.Array) { - this._emitLine("var " + i + ";"); // The object could be an arroy or object. Note that the + this._emitLine("var " + i + ";"); + + // The object could be an arroy or object. Note that the // body of the loop is duplicated for each condition, but // we are optimizing for speed over size. - - this._emitLine("if(runtime.isArray(" + arr + ")) {"); - this._emitLine("var " + len + " = " + arr + ".length;"); + this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); - this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); // Bind each declared var - - + // Bind each declared var node.name.children.forEach(function (child, u) { var tid = _this10._tmpid(); - _this10._emitLine("var " + tid + " = " + arr + "[" + i + "][" + u + "];"); - _this10._emitLine("frame.set(\"" + child + "\", " + arr + "[" + i + "][" + u + "]);"); - frame.set(node.name.children[u].value, tid); }); - this._emitLoopBindings(node, arr, i, len); - this._withScopedSyntax(function () { _this10.compile(node.body, frame); }); - this._emitLine('}'); - - this._emitLine('} else {'); // Iterate over the key/values of an object - - + this._emitLine('} else {'); + // Iterate over the key/values of an object var _node$name$children = node.name.children, - key = _node$name$children[0], - val = _node$name$children[1]; - + key = _node$name$children[0], + val = _node$name$children[1]; var k = this._tmpid(); - var v = this._tmpid(); - frame.set(key.value, k); frame.set(val.value, v); - this._emitLine(i + " = -1;"); - this._emitLine("var " + len + " = runtime.keys(" + arr + ").length;"); - this._emitLine("for(var " + k + " in " + arr + ") {"); - this._emitLine(i + "++;"); - this._emitLine("var " + v + " = " + arr + "[" + k + "];"); - this._emitLine("frame.set(\"" + key.value + "\", " + k + ");"); - this._emitLine("frame.set(\"" + val.value + "\", " + v + ");"); - this._emitLoopBindings(node, arr, i, len); - this._withScopedSyntax(function () { _this10.compile(node.body, frame); }); - this._emitLine('}'); - this._emitLine('}'); } else { // Generate a typical array iteration var _v = this._tmpid(); - frame.set(node.name.value, _v); - this._emitLine("var " + len + " = " + arr + ".length;"); - this._emitLine("for(var " + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); - this._emitLine("var " + _v + " = " + arr + "[" + i + "];"); - this._emitLine("frame.set(\"" + node.name.value + "\", " + _v + ");"); - this._emitLoopBindings(node, arr, i, len); - this._withScopedSyntax(function () { _this10.compile(node.body, frame); }); - this._emitLine('}'); } - this._emitLine('}'); - if (node.else_) { this._emitLine('if (!' + len + ') {'); - this.compile(node.else_, frame); - this._emitLine('}'); } - this._emitLine('frame = frame.pop();'); }; - _proto._compileAsyncLoop = function _compileAsyncLoop(node, frame, parallel) { var _this11 = this; - // This shares some code with the For tag, but not enough to // worry about. This iterates across an object asynchronously, // but not in parallel. - var i = this._tmpid(); + var i = this._tmpid(); var len = this._tmpid(); - var arr = this._tmpid(); - var asyncMethod = parallel ? 'asyncAll' : 'asyncEach'; frame = frame.push(); - this._emitLine('frame = frame.push();'); - this._emit('var ' + arr + ' = runtime.fromIterator('); - this._compileExpression(node.arr, frame); - this._emitLine(');'); - if (node.name instanceof nodes.Array) { var arrayLen = node.name.children.length; - this._emit("runtime." + asyncMethod + "(" + arr + ", " + arrayLen + ", function("); - node.name.children.forEach(function (name) { _this11._emit(name.value + ","); }); - this._emit(i + ',' + len + ',next) {'); - node.name.children.forEach(function (name) { var id = name.value; frame.set(id, id); - _this11._emitLine("frame.set(\"" + id + "\", " + id + ");"); }); } else { var id = node.name.value; - this._emitLine("runtime." + asyncMethod + "(" + arr + ", 1, function(" + id + ", " + i + ", " + len + ",next) {"); - this._emitLine('frame.set("' + id + '", ' + id + ');'); - frame.set(id, id); } - this._emitLoopBindings(node, arr, i, len); - this._withScopedSyntax(function () { var buf; - if (parallel) { buf = _this11._pushBuffer(); } - _this11.compile(node.body, frame); - _this11._emitLine('next(' + i + (buf ? ',' + buf : '') + ');'); - if (parallel) { _this11._popBuffer(); } }); - var output = this._tmpid(); - this._emitLine('}, ' + this._makeCallback(output)); - this._addScopeLevel(); - if (parallel) { this._emitLine(this.buffer + ' += ' + output + ';'); } - if (node.else_) { this._emitLine('if (!' + arr + '.length) {'); - this.compile(node.else_, frame); - this._emitLine('}'); } - this._emitLine('frame = frame.pop();'); }; - _proto.compileAsyncEach = function compileAsyncEach(node, frame) { this._compileAsyncLoop(node, frame); }; - _proto.compileAsyncAll = function compileAsyncAll(node, frame) { this._compileAsyncLoop(node, frame, true); }; - _proto._compileMacro = function _compileMacro(node, frame) { var _this12 = this; - var args = []; var kwargs = null; - var funcId = 'macro_' + this._tmpid(); + var keepFrame = frame !== undefined; - var keepFrame = frame !== undefined; // Type check the definition of the args - + // Type check the definition of the args node.args.children.forEach(function (arg, i) { if (i === node.args.children.length - 1 && arg instanceof nodes.Dict) { kwargs = arg; } else { _this12.assertType(arg, nodes.Symbol); - args.push(arg); } }); var realNames = [].concat(args.map(function (n) { return "l_" + n.value; - }), ['kwargs']); // Quoted argument names + }), ['kwargs']); + // Quoted argument names var argNames = args.map(function (n) { return "\"" + n.value + "\""; }); var kwargNames = (kwargs && kwargs.children || []).map(function (n) { return "\"" + n.key.value + "\""; - }); // We pass a function to makeMacro which destructures the + }); + + // We pass a function to makeMacro which destructures the // arguments so support setting positional args with keywords // args and passing keyword args as positional args // (essentially default values). See runtime.js. - var currFrame; - if (keepFrame) { currFrame = frame.push(true); } else { currFrame = new Frame(); } + this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(', ') + "], ", "[" + kwargNames.join(', ') + "], ", "function (" + realNames.join(', ') + ") {", 'var callerFrame = frame;', 'frame = ' + (keepFrame ? 'frame.push(true);' : 'new runtime.Frame();'), 'kwargs = kwargs || {};', 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }'); - this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(', ') + "], ", "[" + kwargNames.join(', ') + "], ", "function (" + realNames.join(', ') + ") {", 'var callerFrame = frame;', 'frame = ' + (keepFrame ? 'frame.push(true);' : 'new runtime.Frame();'), 'kwargs = kwargs || {};', 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }'); // Expose the arguments to the template. Don't need to use + // Expose the arguments to the template. Don't need to use // random names because the function // will create a new run-time scope for us - - args.forEach(function (arg) { _this12._emitLine("frame.set(\"" + arg.value + "\", l_" + arg.value + ");"); - currFrame.set(arg.value, "l_" + arg.value); - }); // Expose the keyword arguments + }); + // Expose the keyword arguments if (kwargs) { kwargs.children.forEach(function (pair) { var name = pair.key.value; - _this12._emit("frame.set(\"" + name + "\", "); - _this12._emit("Object.prototype.hasOwnProperty.call(kwargs, \"" + name + "\")"); - _this12._emit(" ? kwargs[\"" + name + "\"] : "); - _this12._compileExpression(pair.value, currFrame); - _this12._emit(');'); }); } - var bufferId = this._pushBuffer(); - this._withScopedSyntax(function () { _this12.compile(node.body, currFrame); }); - this._emitLine('frame = ' + (keepFrame ? 'frame.pop();' : 'callerFrame;')); - this._emitLine("return new runtime.SafeString(" + bufferId + ");"); - this._emitLine('});'); - this._popBuffer(); - return funcId; }; - _proto.compileMacro = function compileMacro(node, frame) { - var funcId = this._compileMacro(node); // Expose the macro to the templates - + var funcId = this._compileMacro(node); + // Expose the macro to the templates var name = node.name.value; frame.set(name, funcId); - if (frame.parent) { this._emitLine("frame.set(\"" + name + "\", " + funcId + ");"); } else { if (node.name.value.charAt(0) !== '_') { this._emitLine("context.addExport(\"" + name + "\");"); } - this._emitLine("context.setVariable(\"" + name + "\", " + funcId + ");"); } }; - _proto.compileCaller = function compileCaller(node, frame) { // basically an anonymous "macro expression" this._emit('(function (){'); - var funcId = this._compileMacro(node, frame); - this._emit("return " + funcId + ";})()"); }; - _proto._compileGetTemplate = function _compileGetTemplate(node, frame, eagerCompile, ignoreMissing) { var parentTemplateId = this._tmpid(); - var parentName = this._templateName(); - var cb = this._makeCallback(parentTemplateId); - var eagerCompileArg = eagerCompile ? 'true' : 'false'; var ignoreMissingArg = ignoreMissing ? 'true' : 'false'; - this._emit('env.getTemplate('); - this._compileExpression(node.template, frame); - this._emitLine(", " + eagerCompileArg + ", " + parentName + ", " + ignoreMissingArg + ", " + cb); - return parentTemplateId; }; - _proto.compileImport = function compileImport(node, frame) { var target = node.target.value; - var id = this._compileGetTemplate(node, frame, false, false); - this._addScopeLevel(); - this._emitLine(id + '.getExported(' + (node.withContext ? 'context.getVariables(), frame, ' : '') + this._makeCallback(id)); - this._addScopeLevel(); - frame.set(target, id); - if (frame.parent) { this._emitLine("frame.set(\"" + target + "\", " + id + ");"); } else { this._emitLine("context.setVariable(\"" + target + "\", " + id + ");"); } }; - _proto.compileFromImport = function compileFromImport(node, frame) { var _this13 = this; - var importedId = this._compileGetTemplate(node, frame, false, false); - this._addScopeLevel(); - this._emitLine(importedId + '.getExported(' + (node.withContext ? 'context.getVariables(), frame, ' : '') + this._makeCallback(importedId)); - this._addScopeLevel(); - node.names.children.forEach(function (nameNode) { var name; var alias; - var id = _this13._tmpid(); - if (nameNode instanceof nodes.Pair) { name = nameNode.key.value; alias = nameNode.value.value; @@ -20328,19 +18408,12 @@ var Compiler = /*#__PURE__*/function (_Obj) { name = nameNode.value; alias = name; } - _this13._emitLine("if(Object.prototype.hasOwnProperty.call(" + importedId + ", \"" + name + "\")) {"); - _this13._emitLine("var " + id + " = " + importedId + "." + name + ";"); - _this13._emitLine('} else {'); - _this13._emitLine("cb(new Error(\"cannot import '" + name + "'\")); return;"); - _this13._emitLine('}'); - frame.set(alias, id); - if (frame.parent) { _this13._emitLine("frame.set(\"" + alias + "\", " + id + ");"); } else { @@ -20348,9 +18421,10 @@ var Compiler = /*#__PURE__*/function (_Obj) { } }); }; - _proto.compileBlock = function compileBlock(node) { - var id = this._tmpid(); // If we are executing outside a block (creating a top-level + var id = this._tmpid(); + + // If we are executing outside a block (creating a top-level // block), we really don't want to execute its code because it // will execute twice: once when the child template runs and // again when the parent template runs. Note that blocks @@ -20360,130 +18434,81 @@ var Compiler = /*#__PURE__*/function (_Obj) { // because blocks can have side effects, but it seems like a // waste of performance to always execute huge top-level // blocks twice - - if (!this.inBlock) { this._emit('(parentTemplate ? function(e, c, f, r, cb) { cb(""); } : '); } - this._emit("context.getBlock(\"" + node.name.value + "\")"); - if (!this.inBlock) { this._emit(')'); } - this._emitLine('(env, context, frame, runtime, ' + this._makeCallback(id)); - this._emitLine(this.buffer + " += " + id + ";"); - this._addScopeLevel(); }; - _proto.compileSuper = function compileSuper(node, frame) { var name = node.blockName.value; var id = node.symbol.value; - var cb = this._makeCallback(id); - this._emitLine("context.getSuper(env, \"" + name + "\", b_" + name + ", frame, runtime, " + cb); - this._emitLine(id + " = runtime.markSafe(" + id + ");"); - this._addScopeLevel(); - frame.set(id, id); }; - _proto.compileExtends = function compileExtends(node, frame) { var k = this._tmpid(); + var parentTemplateId = this._compileGetTemplate(node, frame, true, false); - var parentTemplateId = this._compileGetTemplate(node, frame, true, false); // extends is a dynamic tag and can occur within a block like + // extends is a dynamic tag and can occur within a block like // `if`, so if this happens we need to capture the parent // template in the top-level scope - - this._emitLine("parentTemplate = " + parentTemplateId); - this._emitLine("for(var " + k + " in parentTemplate.blocks) {"); - this._emitLine("context.addBlock(" + k + ", parentTemplate.blocks[" + k + "]);"); - this._emitLine('}'); - this._addScopeLevel(); }; - _proto.compileInclude = function compileInclude(node, frame) { this._emitLine('var tasks = [];'); - this._emitLine('tasks.push('); - this._emitLine('function(callback) {'); - var id = this._compileGetTemplate(node, frame, false, node.ignoreMissing); - this._emitLine("callback(null," + id + ");});"); - this._emitLine('});'); - var id2 = this._tmpid(); - this._emitLine('tasks.push('); - this._emitLine('function(template, callback){'); - this._emitLine('template.render(context.getVariables(), frame, ' + this._makeCallback(id2)); - this._emitLine('callback(null,' + id2 + ');});'); - this._emitLine('});'); - this._emitLine('tasks.push('); - this._emitLine('function(result, callback){'); - this._emitLine(this.buffer + " += result;"); - this._emitLine('callback(null);'); - this._emitLine('});'); - this._emitLine('env.waterfall(tasks, function(){'); - this._addScopeLevel(); }; - _proto.compileTemplateData = function compileTemplateData(node, frame) { this.compileLiteral(node, frame); }; - _proto.compileCapture = function compileCapture(node, frame) { var _this14 = this; - // we need to temporarily override the current buffer id as 'output' // so the set block writes to the capture output instead of the buffer var buffer = this.buffer; this.buffer = 'output'; - this._emitLine('(function() {'); - this._emitLine('var output = "";'); - this._withScopedSyntax(function () { _this14.compile(node.body, frame); }); - this._emitLine('return output;'); - - this._emitLine('})()'); // and of course, revert back to the old buffer id - - + this._emitLine('})()'); + // and of course, revert back to the old buffer id this.buffer = buffer; }; - _proto.compileOutput = function compileOutput(node, frame) { var _this15 = this; - var children = node.children; children.forEach(function (child) { // TemplateData is a special case because it is never @@ -20491,115 +18516,80 @@ var Compiler = /*#__PURE__*/function (_Obj) { if (child instanceof nodes.TemplateData) { if (child.value) { _this15._emit(_this15.buffer + " += "); - _this15.compileLiteral(child, frame); - _this15._emitLine(';'); } } else { _this15._emit(_this15.buffer + " += runtime.suppressValue("); - if (_this15.throwOnUndefined) { _this15._emit('runtime.ensureDefined('); } - _this15.compile(child, frame); - if (_this15.throwOnUndefined) { _this15._emit("," + node.lineno + "," + node.colno + ")"); } - _this15._emit(', env.opts.autoescape);\n'); } }); }; - _proto.compileRoot = function compileRoot(node, frame) { var _this16 = this; - if (frame) { this.fail('compileRoot: root node can\'t have frame'); } - frame = new Frame(); - this._emitFuncBegin(node, 'root'); - this._emitLine('var parentTemplate = null;'); - this._compileChildren(node, frame); - this._emitLine('if(parentTemplate) {'); - this._emitLine('parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);'); - this._emitLine('} else {'); - this._emitLine("cb(null, " + this.buffer + ");"); - this._emitLine('}'); - this._emitFuncEnd(true); - this.inBlock = true; var blockNames = []; var blocks = node.findAll(nodes.Block); blocks.forEach(function (block, i) { var name = block.name.value; - if (blockNames.indexOf(name) !== -1) { throw new Error("Block \"" + name + "\" defined more than once."); } - blockNames.push(name); - _this16._emitFuncBegin(block, "b_" + name); - var tmpFrame = new Frame(); - _this16._emitLine('var frame = frame.push(true);'); - _this16.compile(block.body, tmpFrame); - _this16._emitFuncEnd(); }); - this._emitLine('return {'); - blocks.forEach(function (block, i) { var blockName = "b_" + block.name.value; - _this16._emitLine(blockName + ": " + blockName + ","); }); - this._emitLine('root: root\n};'); }; - _proto.compile = function compile(node, frame) { var _compile = this['compile' + node.typename]; - if (_compile) { _compile.call(this, node, frame); } else { this.fail("compile: Cannot compile node: " + node.typename, node.lineno, node.colno); } }; - _proto.getCode = function getCode() { return this.codebuf.join(''); }; - return Compiler; }(Obj); - module.exports = { compile: function compile(src, asyncFilters, extensions, name, opts) { if (opts === void 0) { opts = {}; } + var c = new Compiler(name, opts.throwOnUndefined); - var c = new Compiler(name, opts.throwOnUndefined); // Run the extension preprocessors against the source. - + // Run the extension preprocessors against the source. var preprocessors = (extensions || []).map(function (ext) { return ext.preprocess; }).filter(function (f) { @@ -20623,51 +18613,37 @@ module.exports = { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var asap = __nccwpck_require__(7943); - var _waterfall = __nccwpck_require__(3980); - var lib = __nccwpck_require__(4127); - var compiler = __nccwpck_require__(4548); - var filters = __nccwpck_require__(9223); - var _require = __nccwpck_require__(4395), - FileSystemLoader = _require.FileSystemLoader, - WebLoader = _require.WebLoader, - PrecompiledLoader = _require.PrecompiledLoader; - + FileSystemLoader = _require.FileSystemLoader, + WebLoader = _require.WebLoader, + PrecompiledLoader = _require.PrecompiledLoader; var tests = __nccwpck_require__(841); - var globals = __nccwpck_require__(8956); - var _require2 = __nccwpck_require__(7007), - Obj = _require2.Obj, - EmitterObj = _require2.EmitterObj; - + Obj = _require2.Obj, + EmitterObj = _require2.EmitterObj; var globalRuntime = __nccwpck_require__(1998); - var handleError = globalRuntime.handleError, - Frame = globalRuntime.Frame; + Frame = globalRuntime.Frame; +var expressApp = __nccwpck_require__(6548); -var expressApp = __nccwpck_require__(6548); // If the user is using the async API, *always* call it +// If the user is using the async API, *always* call it // asynchronously even if the template was synchronous. - - function callbackAsap(cb, err, res) { asap(function () { cb(err, res); }); } + /** * A no-op template, for use with {% include ignore missing %} */ - - var noopTmplSrc = { type: 'code', obj: { @@ -20680,19 +18656,14 @@ var noopTmplSrc = { } } }; - var Environment = /*#__PURE__*/function (_EmitterObj) { _inheritsLoose(Environment, _EmitterObj); - function Environment() { return _EmitterObj.apply(this, arguments) || this; } - var _proto = Environment.prototype; - _proto.init = function init(loaders, opts) { var _this = this; - // The dev flag determines the trace that'll be shown on errors. // If set to true, returns the full trace from the error point, // otherwise will return trace starting from Template.render @@ -20700,19 +18671,20 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { // the library) // defaults to false opts = this.opts = opts || {}; - this.opts.dev = !!opts.dev; // The autoescape flag sets global autoescaping. If true, + this.opts.dev = !!opts.dev; + + // The autoescape flag sets global autoescaping. If true, // every string variable will be escaped by default. // If false, strings can be manually escaped using the `escape` filter. // defaults to true + this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true; - this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true; // If true, this will make the system throw errors if trying + // If true, this will make the system throw errors if trying // to output a null or undefined value - this.opts.throwOnUndefined = !!opts.throwOnUndefined; this.opts.trimBlocks = !!opts.trimBlocks; this.opts.lstripBlocks = !!opts.lstripBlocks; this.loaders = []; - if (!loaders) { // The filesystem loader is only available server-side if (FileSystemLoader) { @@ -20722,48 +18694,40 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { } } else { this.loaders = lib.isArray(loaders) ? loaders : [loaders]; - } // It's easy to use precompiled templates: just include them + } + + // It's easy to use precompiled templates: just include them // before you configure nunjucks and this will automatically // pick it up and use it - - if (typeof window !== 'undefined' && window.nunjucksPrecompiled) { this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled)); } - this._initLoaders(); - this.globals = globals(); this.filters = {}; this.tests = {}; this.asyncFilters = []; this.extensions = {}; this.extensionsList = []; - lib._entries(filters).forEach(function (_ref) { var name = _ref[0], - filter = _ref[1]; + filter = _ref[1]; return _this.addFilter(name, filter); }); - lib._entries(tests).forEach(function (_ref2) { var name = _ref2[0], - test = _ref2[1]; + test = _ref2[1]; return _this.addTest(name, test); }); }; - _proto._initLoaders = function _initLoaders() { var _this2 = this; - this.loaders.forEach(function (loader) { // Caching and cache busting loader.cache = {}; - if (typeof loader.on === 'function') { loader.on('update', function (name, fullname) { loader.cache[name] = null; - _this2.emit('update', name, fullname, loader); }); loader.on('load', function (name, source) { @@ -20772,111 +18736,86 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { } }); }; - _proto.invalidateCache = function invalidateCache() { this.loaders.forEach(function (loader) { loader.cache = {}; }); }; - _proto.addExtension = function addExtension(name, extension) { extension.__name = name; this.extensions[name] = extension; this.extensionsList.push(extension); return this; }; - _proto.removeExtension = function removeExtension(name) { var extension = this.getExtension(name); - if (!extension) { return; } - this.extensionsList = lib.without(this.extensionsList, extension); delete this.extensions[name]; }; - _proto.getExtension = function getExtension(name) { return this.extensions[name]; }; - _proto.hasExtension = function hasExtension(name) { return !!this.extensions[name]; }; - _proto.addGlobal = function addGlobal(name, value) { this.globals[name] = value; return this; }; - _proto.getGlobal = function getGlobal(name) { if (typeof this.globals[name] === 'undefined') { throw new Error('global not found: ' + name); } - return this.globals[name]; }; - _proto.addFilter = function addFilter(name, func, async) { var wrapped = func; - if (async) { this.asyncFilters.push(name); } - this.filters[name] = wrapped; return this; }; - _proto.getFilter = function getFilter(name) { if (!this.filters[name]) { throw new Error('filter not found: ' + name); } - return this.filters[name]; }; - _proto.addTest = function addTest(name, func) { this.tests[name] = func; return this; }; - _proto.getTest = function getTest(name) { if (!this.tests[name]) { throw new Error('test not found: ' + name); } - return this.tests[name]; }; - _proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) { var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false; return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename; }; - _proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) { var _this3 = this; - var that = this; var tmpl = null; - if (name && name.raw) { // this fixes autoescape for templates referenced in symbols name = name.raw; } - if (lib.isFunction(parentName)) { cb = parentName; parentName = null; eagerCompile = eagerCompile || false; } - if (lib.isFunction(eagerCompile)) { cb = eagerCompile; eagerCompile = false; } - if (name instanceof Template) { tmpl = name; } else if (typeof name !== 'string') { @@ -20885,18 +18824,15 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { for (var i = 0; i < this.loaders.length; i++) { var loader = this.loaders[i]; tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)]; - if (tmpl) { break; } } } - if (tmpl) { if (eagerCompile) { tmpl.compile(); } - if (cb) { cb(null, tmpl); return undefined; @@ -20904,14 +18840,11 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { return tmpl; } } - var syncResult; - var createTemplate = function createTemplate(err, info) { if (!info && !err && !ignoreMissing) { err = new Error('template not found: ' + name); } - if (err) { if (cb) { cb(err); @@ -20920,26 +18853,21 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { throw err; } } - var newTmpl; - if (!info) { newTmpl = new Template(noopTmplSrc, _this3, '', eagerCompile); } else { newTmpl = new Template(info.src, _this3, info.path, eagerCompile); - if (!info.noCache) { info.loader.cache[name] = newTmpl; } } - if (cb) { cb(null, newTmpl); } else { syncResult = newTmpl; } }; - lib.asyncIter(this.loaders, function (loader, i, next, done) { function handle(err, src) { if (err) { @@ -20950,11 +18878,10 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { } else { next(); } - } // Resolve name relative to parentName - + } + // Resolve name relative to parentName name = that.resolveTemplate(loader, parentName, name); - if (loader.async) { loader.getSource(name, handle); } else { @@ -20963,21 +18890,19 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { }, createTemplate); return syncResult; }; - _proto.express = function express(app) { return expressApp(this, app); }; - _proto.render = function render(name, ctx, cb) { if (lib.isFunction(ctx)) { cb = ctx; ctx = null; - } // We support a synchronous API to make it easier to migrate + } + + // We support a synchronous API to make it easier to migrate // existing code to async. This works because if you don't do // anything async work, the whole thing is actually run // synchronously. - - var syncResult = null; this.getTemplate(name, function (err, tmpl) { if (err && cb) { @@ -20990,40 +18915,32 @@ var Environment = /*#__PURE__*/function (_EmitterObj) { }); return syncResult; }; - _proto.renderString = function renderString(src, ctx, opts, cb) { if (lib.isFunction(opts)) { cb = opts; opts = {}; } - opts = opts || {}; var tmpl = new Template(src, this, opts.path); return tmpl.render(ctx, cb); }; - _proto.waterfall = function waterfall(tasks, callback, forceAsync) { return _waterfall(tasks, callback, forceAsync); }; - return Environment; }(EmitterObj); - var Context = /*#__PURE__*/function (_Obj) { _inheritsLoose(Context, _Obj); - function Context() { return _Obj.apply(this, arguments) || this; } - var _proto2 = Context.prototype; - _proto2.init = function init(ctx, blocks, env) { var _this4 = this; - // Has to be tied to an environment so we can tap into its globals. - this.env = env || new Environment(); // Make a duplicate of ctx + this.env = env || new Environment(); + // Make a duplicate of ctx this.ctx = lib.extend({}, ctx); this.blocks = {}; this.exported = []; @@ -21031,7 +18948,6 @@ var Context = /*#__PURE__*/function (_Obj) { _this4.addBlock(name, blocks[name]); }); }; - _proto2.lookup = function lookup(name) { // This is one of the most called functions, so optimize for // the typical case where the name isn't in the globals @@ -21041,80 +18957,61 @@ var Context = /*#__PURE__*/function (_Obj) { return this.ctx[name]; } }; - _proto2.setVariable = function setVariable(name, val) { this.ctx[name] = val; }; - _proto2.getVariables = function getVariables() { return this.ctx; }; - _proto2.addBlock = function addBlock(name, block) { this.blocks[name] = this.blocks[name] || []; this.blocks[name].push(block); return this; }; - _proto2.getBlock = function getBlock(name) { if (!this.blocks[name]) { throw new Error('unknown block "' + name + '"'); } - return this.blocks[name][0]; }; - _proto2.getSuper = function getSuper(env, name, block, frame, runtime, cb) { var idx = lib.indexOf(this.blocks[name] || [], block); var blk = this.blocks[name][idx + 1]; var context = this; - if (idx === -1 || !blk) { throw new Error('no super block available for "' + name + '"'); } - blk(env, context, frame, runtime, cb); }; - _proto2.addExport = function addExport(name) { this.exported.push(name); }; - _proto2.getExported = function getExported() { var _this5 = this; - var exported = {}; this.exported.forEach(function (name) { exported[name] = _this5.ctx[name]; }); return exported; }; - return Context; }(Obj); - var Template = /*#__PURE__*/function (_Obj2) { _inheritsLoose(Template, _Obj2); - function Template() { return _Obj2.apply(this, arguments) || this; } - var _proto3 = Template.prototype; - _proto3.init = function init(src, env, path, eagerCompile) { this.env = env || new Environment(); - if (lib.isObject(src)) { switch (src.type) { case 'code': this.tmplProps = src.obj; break; - case 'string': this.tmplStr = src.obj; break; - default: throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'"); } @@ -21123,9 +19020,7 @@ var Template = /*#__PURE__*/function (_Obj2) { } else { throw new Error('src must be a string or an object describing the source'); } - this.path = path; - if (eagerCompile) { try { this._compile(); @@ -21136,36 +19031,33 @@ var Template = /*#__PURE__*/function (_Obj2) { this.compiled = false; } }; - _proto3.render = function render(ctx, parentFrame, cb) { var _this6 = this; - if (typeof ctx === 'function') { cb = ctx; ctx = {}; } else if (typeof parentFrame === 'function') { cb = parentFrame; parentFrame = null; - } // If there is a parent frame, we are being called from internal + } + + // If there is a parent frame, we are being called from internal // code of another template, and the internal system // depends on the sync/async nature of the parent template // to be inherited, so force an async callback + var forceAsync = !parentFrame; - - var forceAsync = !parentFrame; // Catch compile errors for async rendering - + // Catch compile errors for async rendering try { this.compile(); } catch (e) { var err = lib._prettifyError(this.path, this.env.opts.dev, e); - if (cb) { return callbackAsap(cb, err); } else { throw err; } } - var context = new Context(ctx || {}, this.blocks, this.env); var frame = parentFrame ? parentFrame.push(true) : new Frame(); frame.topLevel = true; @@ -21180,12 +19072,10 @@ var Template = /*#__PURE__*/function (_Obj2) { // prevent multiple calls to cb return; } - if (err) { err = lib._prettifyError(_this6.path, _this6.env.opts.dev, err); didError = true; } - if (cb) { if (forceAsync) { callbackAsap(cb, err, res); @@ -21196,26 +19086,23 @@ var Template = /*#__PURE__*/function (_Obj2) { if (err) { throw err; } - syncResult = res; } }); return syncResult; }; - _proto3.getExported = function getExported(ctx, parentFrame, cb) { // eslint-disable-line consistent-return if (typeof ctx === 'function') { cb = ctx; ctx = {}; } - if (typeof parentFrame === 'function') { cb = parentFrame; parentFrame = null; - } // Catch compile errors for async rendering - + } + // Catch compile errors for async rendering try { this.compile(); } catch (e) { @@ -21225,10 +19112,10 @@ var Template = /*#__PURE__*/function (_Obj2) { throw e; } } - var frame = parentFrame ? parentFrame.push() : new Frame(); - frame.topLevel = true; // Run the rootRenderFunc to populate the context with exported vars + frame.topLevel = true; + // Run the rootRenderFunc to populate the context with exported vars var context = new Context(ctx || {}, this.blocks, this.env); this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err) { if (err) { @@ -21238,30 +19125,24 @@ var Template = /*#__PURE__*/function (_Obj2) { } }); }; - _proto3.compile = function compile() { if (!this.compiled) { this._compile(); } }; - _proto3._compile = function _compile() { var props; - if (this.tmplProps) { props = this.tmplProps; } else { var source = compiler.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts); var func = new Function(source); // eslint-disable-line no-new-func - props = func(); } - this.blocks = this._getBlocks(props); this.rootRenderFunc = props.root; this.compiled = true; }; - _proto3._getBlocks = function _getBlocks(props) { var blocks = {}; lib.keys(props).forEach(function (k) { @@ -21271,10 +19152,8 @@ var Template = /*#__PURE__*/function (_Obj2) { }); return blocks; }; - return Template; }(Obj); - module.exports = { Environment: Environment, Template: Template @@ -21289,27 +19168,22 @@ module.exports = { var path = __nccwpck_require__(1017); - module.exports = function express(env, app) { function NunjucksView(name, opts) { this.name = name; this.path = name; this.defaultEngine = opts.defaultEngine; this.ext = path.extname(name); - if (!this.ext && !this.defaultEngine) { throw new Error('No default engine was specified and no extension was provided.'); } - if (!this.ext) { this.name += this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine; } } - NunjucksView.prototype.render = function render(opts, cb) { env.render(this.name, opts, cb); }; - app.set('view', NunjucksView); app.set('nunjucksEnv', env); return env; @@ -21324,21 +19198,15 @@ module.exports = function express(env, app) { var lib = __nccwpck_require__(4127); - var r = __nccwpck_require__(1998); - var _exports = module.exports = {}; - function normalize(value, defaultValue) { if (value === null || value === undefined || value === false) { return defaultValue; } - return value; } - _exports.abs = Math.abs; - function isNaN(num) { return num !== num; // eslint-disable-line no-self-compare } @@ -21347,80 +19215,64 @@ function batch(arr, linecount, fillWith) { var i; var res = []; var tmp = []; - for (i = 0; i < arr.length; i++) { if (i % linecount === 0 && tmp.length) { res.push(tmp); tmp = []; } - tmp.push(arr[i]); } - if (tmp.length) { if (fillWith) { for (i = tmp.length; i < linecount; i++) { tmp.push(fillWith); } } - res.push(tmp); } - return res; } - _exports.batch = batch; - function capitalize(str) { str = normalize(str, ''); var ret = str.toLowerCase(); return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1)); } - _exports.capitalize = capitalize; - function center(str, width) { str = normalize(str, ''); width = width || 80; - if (str.length >= width) { return str; } - var spaces = width - str.length; var pre = lib.repeat(' ', spaces / 2 - spaces % 2); var post = lib.repeat(' ', spaces / 2); return r.copySafeness(str, pre + str + post); } - _exports.center = center; - function default_(val, def, bool) { if (bool) { return val || def; } else { return val !== undefined ? val : def; } -} // TODO: it is confusing to export something called 'default' - +} +// TODO: it is confusing to export something called 'default' _exports['default'] = default_; // eslint-disable-line dot-notation function dictsort(val, caseSensitive, by) { if (!lib.isObject(val)) { throw new lib.TemplateError('dictsort filter: val must be an object'); } - - var array = []; // deliberately include properties from the object's prototype - + var array = []; + // deliberately include properties from the object's prototype for (var k in val) { // eslint-disable-line guard-for-in, no-restricted-syntax array.push([k, val[k]]); } - var si; - if (by === undefined || by === 'key') { si = 0; } else if (by === 'value') { @@ -21428,84 +19280,63 @@ function dictsort(val, caseSensitive, by) { } else { throw new lib.TemplateError('dictsort filter: You can only sort by either key or value'); } - array.sort(function (t1, t2) { var a = t1[si]; var b = t2[si]; - if (!caseSensitive) { if (lib.isString(a)) { a = a.toUpperCase(); } - if (lib.isString(b)) { b = b.toUpperCase(); } } - return a > b ? 1 : a === b ? 0 : -1; // eslint-disable-line no-nested-ternary }); + return array; } - _exports.dictsort = dictsort; - function dump(obj, spaces) { return JSON.stringify(obj, null, spaces); } - _exports.dump = dump; - function escape(str) { if (str instanceof r.SafeString) { return str; } - str = str === null || str === undefined ? '' : str; return r.markSafe(lib.escape(str.toString())); } - _exports.escape = escape; - function safe(str) { if (str instanceof r.SafeString) { return str; } - str = str === null || str === undefined ? '' : str; return r.markSafe(str.toString()); } - _exports.safe = safe; - function first(arr) { return arr[0]; } - _exports.first = first; - function forceescape(str) { str = str === null || str === undefined ? '' : str; return r.markSafe(lib.escape(str.toString())); } - _exports.forceescape = forceescape; - function groupby(arr, attr) { return lib.groupBy(arr, attr, this.env.opts.throwOnUndefined); } - _exports.groupby = groupby; - function indent(str, width, indentfirst) { str = normalize(str, ''); - if (str === '') { return ''; } - - width = width || 4; // let res = ''; - + width = width || 4; + // let res = ''; var lines = str.split('\n'); var sp = lib.repeat(' ', width); var res = lines.map(function (l, i) { @@ -21513,58 +19344,44 @@ function indent(str, width, indentfirst) { }).join('\n'); return r.copySafeness(str, res); } - _exports.indent = indent; - function join(arr, del, attr) { del = del || ''; - if (attr) { arr = lib.map(arr, function (v) { return v[attr]; }); } - return arr.join(del); } - _exports.join = join; - function last(arr) { return arr[arr.length - 1]; } - _exports.last = last; - function lengthFilter(val) { var value = normalize(val, ''); - if (value !== undefined) { if (typeof Map === 'function' && value instanceof Map || typeof Set === 'function' && value instanceof Set) { // ECMAScript 2015 Maps and Sets return value.size; } - if (lib.isObject(value) && !(value instanceof r.SafeString)) { // Objects (besides SafeStrings), non-primative Arrays return lib.keys(value).length; } - return value.length; } - return 0; } - _exports.length = lengthFilter; - function list(val) { if (lib.isString(val)) { return val.split(''); } else if (lib.isObject(val)) { return lib._entries(val || {}).map(function (_ref) { var key = _ref[0], - value = _ref[1]; + value = _ref[1]; return { key: key, value: value @@ -21576,148 +19393,123 @@ function list(val) { throw new lib.TemplateError('list filter: type not iterable'); } } - _exports.list = list; - function lower(str) { str = normalize(str, ''); return str.toLowerCase(); } - _exports.lower = lower; - function nl2br(str) { if (str === null || str === undefined) { return ''; } - return r.copySafeness(str, str.replace(/\r\n|\n/g, '
\n')); } - _exports.nl2br = nl2br; - function random(arr) { return arr[Math.floor(Math.random() * arr.length)]; } - _exports.random = random; + /** * Construct select or reject filter * * @param {boolean} expectedTestResult * @returns {function(array, string, *): array} */ - function getSelectOrReject(expectedTestResult) { function filter(arr, testName, secondArg) { if (testName === void 0) { testName = 'truthy'; } - var context = this; var test = context.env.getTest(testName); return lib.toArray(arr).filter(function examineTestResult(item) { return test.call(context, item, secondArg) === expectedTestResult; }); } - return filter; } - _exports.reject = getSelectOrReject(false); - function rejectattr(arr, attr) { return arr.filter(function (item) { return !item[attr]; }); } - _exports.rejectattr = rejectattr; _exports.select = getSelectOrReject(true); - function selectattr(arr, attr) { return arr.filter(function (item) { return !!item[attr]; }); } - _exports.selectattr = selectattr; - function replace(str, old, new_, maxCount) { var originalStr = str; - if (old instanceof RegExp) { return str.replace(old, new_); } - if (typeof maxCount === 'undefined') { maxCount = -1; } - var res = ''; // Output - // Cast Numbers in the search term to string + // Cast Numbers in the search term to string if (typeof old === 'number') { old = '' + old; } else if (typeof old !== 'string') { // If it is something other than number or string, // return the original string return str; - } // Cast numbers in the replacement to string - + } + // Cast numbers in the replacement to string if (typeof str === 'number') { str = '' + str; - } // If by now, we don't have a string, throw it back - + } + // If by now, we don't have a string, throw it back if (typeof str !== 'string' && !(str instanceof r.SafeString)) { return str; - } // ShortCircuits - + } + // ShortCircuits if (old === '') { // Mimic the python behaviour: empty string is replaced // by replacement e.g. "abc"|replace("", ".") -> .a.b.c. res = new_ + str.split('').join(new_) + new_; return r.copySafeness(str, res); } - - var nextIndex = str.indexOf(old); // if # of replacements to perform is 0, or the string to does + var nextIndex = str.indexOf(old); + // if # of replacements to perform is 0, or the string to does // not contain the old value, return the string - if (maxCount === 0 || nextIndex === -1) { return str; } - var pos = 0; var count = 0; // # of replacements made while (nextIndex > -1 && (maxCount === -1 || count < maxCount)) { // Grab the next chunk of src string and add it with the // replacement, to the result - res += str.substring(pos, nextIndex) + new_; // Increment our pointer in the src string - + res += str.substring(pos, nextIndex) + new_; + // Increment our pointer in the src string pos = nextIndex + old.length; - count++; // See if there are any more replacements to be made - + count++; + // See if there are any more replacements to be made nextIndex = str.indexOf(old, pos); - } // We've either reached the end, or done the max # of - // replacements, tack on any remaining string - + } + // We've either reached the end, or done the max # of + // replacements, tack on any remaining string if (pos < str.length) { res += str.substring(pos); } - return r.copySafeness(originalStr, res); } - _exports.replace = replace; - function reverse(val) { var arr; - if (lib.isString(val)) { arr = list(val); } else { @@ -21726,23 +19518,17 @@ function reverse(val) { return v; }); } - arr.reverse(); - if (lib.isString(val)) { return r.copySafeness(val, arr.join('')); } - return arr; } - _exports.reverse = reverse; - function round(val, precision, method) { precision = precision || 0; var factor = Math.pow(10, precision); var rounder; - if (method === 'ceil') { rounder = Math.ceil; } else if (method === 'floor') { @@ -21750,60 +19536,45 @@ function round(val, precision, method) { } else { rounder = Math.round; } - return rounder(val * factor) / factor; } - _exports.round = round; - function slice(arr, slices, fillWith) { var sliceLength = Math.floor(arr.length / slices); var extra = arr.length % slices; var res = []; var offset = 0; - for (var i = 0; i < slices; i++) { var start = offset + i * sliceLength; - if (i < extra) { offset++; } - var end = offset + (i + 1) * sliceLength; var currSlice = arr.slice(start, end); - if (fillWith && i >= extra) { currSlice.push(fillWith); } - res.push(currSlice); } - return res; } - _exports.slice = slice; - function sum(arr, attr, start) { if (start === void 0) { start = 0; } - if (attr) { arr = lib.map(arr, function (v) { return v[attr]; }); } - return start + arr.reduce(function (a, b) { return a + b; }, 0); } - _exports.sum = sum; _exports.sort = r.makeMacro(['value', 'reverse', 'case_sensitive', 'attribute'], [], function sortFilter(arr, reversed, caseSens, attr) { var _this = this; - // Copy it var array = lib.map(arr, function (v) { return v; @@ -21812,16 +19583,13 @@ _exports.sort = r.makeMacro(['value', 'reverse', 'case_sensitive', 'attribute'], array.sort(function (a, b) { var x = attr ? getAttribute(a) : a; var y = attr ? getAttribute(b) : b; - if (_this.env.opts.throwOnUndefined && attr && (x === undefined || y === undefined)) { throw new TypeError("sort: attribute \"" + attr + "\" resolved to undefined"); } - if (!caseSens && lib.isString(x) && lib.isString(y)) { x = x.toLowerCase(); y = y.toLowerCase(); } - if (x < y) { return reversed ? 1 : -1; } else if (x > y) { @@ -21832,19 +19600,15 @@ _exports.sort = r.makeMacro(['value', 'reverse', 'case_sensitive', 'attribute'], }); return array; }); - function string(obj) { return r.copySafeness(obj, obj); } - _exports.string = string; - function striptags(input, preserveLinebreaks) { input = normalize(input, ''); var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|/gi; var trimmedInput = trim(input.replace(tags, '')); var res = ''; - if (preserveLinebreaks) { res = trimmedInput.replace(/^ +| +$/gm, '') // remove leading and trailing spaces .replace(/ +/g, ' ') // squash adjacent spaces @@ -21853,12 +19617,9 @@ function striptags(input, preserveLinebreaks) { } else { res = trimmedInput.replace(/\s+/gi, ' '); } - return r.copySafeness(input, res); } - _exports.striptags = striptags; - function title(str) { str = normalize(str, ''); var words = str.split(' ').map(function (word) { @@ -21866,79 +19627,63 @@ function title(str) { }); return r.copySafeness(str, words.join(' ')); } - _exports.title = title; - function trim(str) { return r.copySafeness(str, str.replace(/^\s*|\s*$/g, '')); } - _exports.trim = trim; - function truncate(input, length, killwords, end) { var orig = input; input = normalize(input, ''); length = length || 255; - if (input.length <= length) { return input; } - if (killwords) { input = input.substring(0, length); } else { var idx = input.lastIndexOf(' ', length); - if (idx === -1) { idx = length; } - input = input.substring(0, idx); } - input += end !== undefined && end !== null ? end : '...'; return r.copySafeness(orig, input); } - _exports.truncate = truncate; - function upper(str) { str = normalize(str, ''); return str.toUpperCase(); } - _exports.upper = upper; - function urlencode(obj) { var enc = encodeURIComponent; - if (lib.isString(obj)) { return enc(obj); } else { var keyvals = lib.isArray(obj) ? obj : lib._entries(obj); return keyvals.map(function (_ref2) { var k = _ref2[0], - v = _ref2[1]; + v = _ref2[1]; return enc(k) + "=" + enc(v); }).join('&'); } } +_exports.urlencode = urlencode; -_exports.urlencode = urlencode; // For the jinja regexp, see +// For the jinja regexp, see // https://github.com/mitsuhiko/jinja2/blob/f15b814dcba6aa12bc74d1f7d0c881d55f7126be/jinja2/utils.py#L20-L23 - -var puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; // from http://blog.gerv.net/2011/05/html5_email_address_regexp/ - +var puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; +// from http://blog.gerv.net/2011/05/html5_email_address_regexp/ var emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; var httpHttpsRe = /^https?:\/\/.*$/; var wwwRe = /^www\./; var tldRe = /\.(?:org|net|com)(?:\:|\/|$)/; - function urlize(str, length, nofollow) { if (isNaN(length)) { length = Infinity; } - var noFollowAttr = nofollow === true ? ' rel="nofollow"' : ''; var words = str.split(/(\s+)/).filter(function (word) { // If the word has no length, bail. This can happen for str with @@ -21947,58 +19692,53 @@ function urlize(str, length, nofollow) { }).map(function (word) { var matches = word.match(puncRe); var possibleUrl = matches ? matches[1] : word; - var shortUrl = possibleUrl.substr(0, length); // url that starts with http or https + var shortUrl = possibleUrl.substr(0, length); + // url that starts with http or https if (httpHttpsRe.test(possibleUrl)) { return "" + shortUrl + ""; - } // url that starts with www. - + } + // url that starts with www. if (wwwRe.test(possibleUrl)) { return "" + shortUrl + ""; - } // an email address of the form username@domain.tld - + } + // an email address of the form username@domain.tld if (emailRe.test(possibleUrl)) { return "" + possibleUrl + ""; - } // url that ends in .com, .org or .net that is not an email address - + } + // url that ends in .com, .org or .net that is not an email address if (tldRe.test(possibleUrl)) { return "" + shortUrl + ""; } - return word; }); return words.join(''); } - _exports.urlize = urlize; - function wordcount(str) { str = normalize(str, ''); var words = str ? str.match(/\w+/g) : null; return words ? words.length : null; } - _exports.wordcount = wordcount; - function float(val, def) { var res = parseFloat(val); return isNaN(res) ? def : res; } - _exports.float = float; var intFilter = r.makeMacro(['value', 'default', 'base'], [], function doInt(value, defaultValue, base) { if (base === void 0) { base = 10; } - var res = parseInt(value, base); return isNaN(res) ? defaultValue : res; }); -_exports.int = intFilter; // Aliases +_exports.int = intFilter; +// Aliases _exports.d = _exports.default; _exports.e = _exports.escape; @@ -22020,17 +19760,14 @@ function _cycler(items) { }, next: function next() { index++; - if (index >= items.length) { index = 0; } - this.current = items[index]; return this.current; } }; } - function _joiner(sep) { sep = sep || ','; var first = true; @@ -22039,11 +19776,11 @@ function _joiner(sep) { first = false; return val; }; -} // Making this a function instead so it returns a new object +} + +// Making this a function instead so it returns a new object // each time it's called. That way, if something like an environment // uses it, they will each have their own copy. - - function globals() { return { range: function range(start, stop, step) { @@ -22054,9 +19791,7 @@ function globals() { } else if (!step) { step = 1; } - var arr = []; - if (step > 0) { for (var i = start; i < stop; i += step) { arr.push(i); @@ -22067,7 +19802,6 @@ function globals() { arr.push(_i); } } - return arr; }, cycler: function cycler() { @@ -22078,7 +19812,6 @@ function globals() { } }; } - module.exports = globals; /***/ }), @@ -22091,13 +19824,14 @@ module.exports = globals; function installCompat() { 'use strict'; + /* eslint-disable camelcase */ + // This must be called like `nunjucks.installCompat` so that `this` // references the nunjucks instance - var runtime = this.runtime; - var lib = this.lib; // Handle slim case where these 'modules' are excluded from the built source - + var lib = this.lib; + // Handle slim case where these 'modules' are excluded from the built source var Compiler = this.compiler.Compiler; var Parser = this.parser.Parser; var nodes = this.nodes; @@ -22106,50 +19840,38 @@ function installCompat() { var orig_memberLookup = runtime.memberLookup; var orig_Compiler_assertType; var orig_Parser_parseAggregate; - if (Compiler) { orig_Compiler_assertType = Compiler.prototype.assertType; } - if (Parser) { orig_Parser_parseAggregate = Parser.prototype.parseAggregate; } - function uninstall() { runtime.contextOrFrameLookup = orig_contextOrFrameLookup; runtime.memberLookup = orig_memberLookup; - if (Compiler) { Compiler.prototype.assertType = orig_Compiler_assertType; } - if (Parser) { Parser.prototype.parseAggregate = orig_Parser_parseAggregate; } } - runtime.contextOrFrameLookup = function contextOrFrameLookup(context, frame, key) { var val = orig_contextOrFrameLookup.apply(this, arguments); - if (val !== undefined) { return val; } - switch (key) { case 'True': return true; - case 'False': return false; - case 'None': return null; - default: return undefined; } }; - function getTokensState(tokens) { return { index: tokens.index, @@ -22157,7 +19879,6 @@ function installCompat() { colno: tokens.colno }; } - if (process.env.BUILD_TYPE !== 'SLIM' && nodes && Compiler && Parser) { // i.e., not slim mode var Slice = nodes.Node.extend('Slice', { @@ -22169,72 +19890,54 @@ function installCompat() { this.parent(lineno, colno, start, stop, step); } }); - Compiler.prototype.assertType = function assertType(node) { if (node instanceof Slice) { return; } - orig_Compiler_assertType.apply(this, arguments); }; - Compiler.prototype.compileSlice = function compileSlice(node, frame) { this._emit('('); - this._compileExpression(node.start, frame); - this._emit('),('); - this._compileExpression(node.stop, frame); - this._emit('),('); - this._compileExpression(node.step, frame); - this._emit(')'); }; - Parser.prototype.parseAggregate = function parseAggregate() { var _this = this; - - var origState = getTokensState(this.tokens); // Set back one accounting for opening bracket/parens - + var origState = getTokensState(this.tokens); + // Set back one accounting for opening bracket/parens origState.colno--; origState.index--; - try { return orig_Parser_parseAggregate.apply(this); } catch (e) { var errState = getTokensState(this.tokens); - var rethrow = function rethrow() { lib._assign(_this.tokens, errState); - return e; - }; // Reset to state before original parseAggregate called - + }; + // Reset to state before original parseAggregate called lib._assign(this.tokens, origState); - this.peeked = false; var tok = this.peekToken(); - if (tok.type !== lexer.TOKEN_LEFT_BRACKET) { throw rethrow(); } else { this.nextToken(); } + var node = new Slice(tok.lineno, tok.colno); - var node = new Slice(tok.lineno, tok.colno); // If we don't encounter a colon while parsing, this is not a slice, + // If we don't encounter a colon while parsing, this is not a slice, // so re-raise the original exception. - var isSlice = false; - for (var i = 0; i <= node.fields.length; i++) { if (this.skip(lexer.TOKEN_RIGHT_BRACKET)) { break; } - if (i === node.fields.length) { if (isSlice) { this.fail('parseSlice: too many slice components', tok.lineno, tok.colno); @@ -22242,7 +19945,6 @@ function installCompat() { break; } } - if (this.skip(lexer.TOKEN_COLON)) { isSlice = true; } else { @@ -22251,68 +19953,52 @@ function installCompat() { isSlice = this.skip(lexer.TOKEN_COLON) || isSlice; } } - if (!isSlice) { throw rethrow(); } - return new nodes.Array(tok.lineno, tok.colno, [node]); } }; } - function sliceLookup(obj, start, stop, step) { obj = obj || []; - if (start === null) { start = step < 0 ? obj.length - 1 : 0; } - if (stop === null) { stop = step < 0 ? -1 : obj.length; } else if (stop < 0) { stop += obj.length; } - if (start < 0) { start += obj.length; } - var results = []; - for (var i = start;; i += step) { if (i < 0 || i > obj.length) { break; } - if (step > 0 && i >= stop) { break; } - if (step < 0 && i <= stop) { break; } - results.push(runtime.memberLookup(obj, i)); } - return results; } - function hasOwnProp(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } - var ARRAY_MEMBERS = { pop: function pop(index) { if (index === undefined) { return this.pop(); } - if (index >= this.length || index < 0) { throw new Error('KeyError'); } - return this.splice(index, 1); }, append: function append(element) { @@ -22324,27 +20010,22 @@ function installCompat() { return this.splice(i, 1); } } - throw new Error('ValueError'); }, count: function count(element) { var count = 0; - for (var i = 0; i < this.length; i++) { if (this[i] === element) { count++; } } - return count; }, index: function index(element) { var i; - if ((i = this.indexOf(element)) === -1) { throw new Error('ValueError'); } - return i; }, find: function find(element) { @@ -22366,11 +20047,9 @@ function installCompat() { }, get: function get(key, def) { var output = this[key]; - if (output === undefined) { output = def; } - return output; }, has_key: function has_key(key) { @@ -22378,7 +20057,6 @@ function installCompat() { }, pop: function pop(key, def) { var output = this[key]; - if (output === undefined && def !== undefined) { output = def; } else if (output === undefined) { @@ -22386,16 +20064,13 @@ function installCompat() { } else { delete this[key]; } - return output; }, popitem: function popitem() { var keys = lib.keys(this); - if (!keys.length) { throw new Error('KeyError'); } - var k = keys[0]; var val = this[k]; delete this[k]; @@ -22405,45 +20080,38 @@ function installCompat() { if (def === void 0) { def = null; } - if (!(key in this)) { this[key] = def; } - return this[key]; }, update: function update(kwargs) { lib._assign(this, kwargs); - return null; // Always returns None } }; + OBJECT_MEMBERS.iteritems = OBJECT_MEMBERS.items; OBJECT_MEMBERS.itervalues = OBJECT_MEMBERS.values; OBJECT_MEMBERS.iterkeys = OBJECT_MEMBERS.keys; - runtime.memberLookup = function memberLookup(obj, val, autoescape) { if (arguments.length === 4) { return sliceLookup.apply(this, arguments); } + obj = obj || {}; - obj = obj || {}; // If the object is an object, return any of the methods that Python would + // If the object is an object, return any of the methods that Python would // otherwise provide. - if (lib.isArray(obj) && hasOwnProp(ARRAY_MEMBERS, val)) { return ARRAY_MEMBERS[val].bind(obj); } - if (lib.isObject(obj) && hasOwnProp(OBJECT_MEMBERS, val)) { return OBJECT_MEMBERS[val].bind(obj); } - return orig_memberLookup.apply(this, arguments); }; - return uninstall; } - module.exports = installCompat; /***/ }), @@ -22455,7 +20123,6 @@ module.exports = installCompat; var lib = __nccwpck_require__(4127); - var whitespaceChars = " \n\t\r\xA0"; var delimChars = '()[]{}%*-+~/#,:|.<>=!'; var intChars = '0123456789'; @@ -22491,7 +20158,6 @@ var TOKEN_NONE = 'none'; var TOKEN_SYMBOL = 'symbol'; var TOKEN_SPECIAL = 'special'; var TOKEN_REGEX = 'regex'; - function token(type, value, lineno, colno) { return { type: type, @@ -22500,7 +20166,6 @@ function token(type, value, lineno, colno) { colno: colno }; } - var Tokenizer = /*#__PURE__*/function () { function Tokenizer(str, opts) { this.str = str; @@ -22522,18 +20187,14 @@ var Tokenizer = /*#__PURE__*/function () { this.trimBlocks = !!opts.trimBlocks; this.lstripBlocks = !!opts.lstripBlocks; } - var _proto = Tokenizer.prototype; - _proto.nextToken = function nextToken() { var lineno = this.lineno; var colno = this.colno; var tok; - if (this.in_code) { // Otherwise, if we are in a block parse it as code var cur = this.current(); - if (this.isFinished()) { // We have nothing else to parse return null; @@ -22551,10 +20212,8 @@ var Tokenizer = /*#__PURE__*/function () { // breaks on delimiters so we can assume the token parsing // doesn't consume these elsewhere this.in_code = false; - if (this.trimBlocks) { cur = this.current(); - if (cur === '\n') { // Skip newline this.forward(); @@ -22562,7 +20221,6 @@ var Tokenizer = /*#__PURE__*/function () { // Skip CRLF newline this.forward(); cur = this.current(); - if (cur === '\n') { this.forward(); } else { @@ -22571,7 +20229,6 @@ var Tokenizer = /*#__PURE__*/function () { } } } - return token(TOKEN_BLOCK_END, tok, lineno, colno); } else if ((tok = this._extractString(this.tags.VARIABLE_END)) || (tok = this._extractString('-' + this.tags.VARIABLE_END))) { // Special check for variable end tag (see above) @@ -22579,10 +20236,10 @@ var Tokenizer = /*#__PURE__*/function () { return token(TOKEN_VARIABLE_END, tok, lineno, colno); } else if (cur === 'r' && this.str.charAt(this.index + 1) === '/') { // Skip past 'r/'. - this.forwardN(2); // Extract until the end of the regex -- / ends it, \/ does not. + this.forwardN(2); + // Extract until the end of the regex -- / ends it, \/ does not. var regexBody = ''; - while (!this.isFinished()) { if (this.current() === '/' && this.previous() !== '\\') { this.forward(); @@ -22591,16 +20248,14 @@ var Tokenizer = /*#__PURE__*/function () { regexBody += this.current(); this.forward(); } - } // Check for flags. - // The possible flags are according to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) - + } + // Check for flags. + // The possible flags are according to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) var POSSIBLE_FLAGS = ['g', 'i', 'm', 'y']; var regexFlags = ''; - while (!this.isFinished()) { var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1; - if (isCurrentAFlag) { regexFlags += this.current(); this.forward(); @@ -22608,7 +20263,6 @@ var Tokenizer = /*#__PURE__*/function () { break; } } - return token(TOKEN_REGEX, { body: regexBody, flags: regexFlags @@ -22619,74 +20273,59 @@ var Tokenizer = /*#__PURE__*/function () { var complexOps = ['==', '===', '!=', '!==', '<=', '>=', '//', '**']; var curComplex = cur + this.current(); var type; - if (lib.indexOf(complexOps, curComplex) !== -1) { this.forward(); - cur = curComplex; // See if this is a strict equality/inequality comparator + cur = curComplex; + // See if this is a strict equality/inequality comparator if (lib.indexOf(complexOps, curComplex + this.current()) !== -1) { cur = curComplex + this.current(); this.forward(); } } - switch (cur) { case '(': type = TOKEN_LEFT_PAREN; break; - case ')': type = TOKEN_RIGHT_PAREN; break; - case '[': type = TOKEN_LEFT_BRACKET; break; - case ']': type = TOKEN_RIGHT_BRACKET; break; - case '{': type = TOKEN_LEFT_CURLY; break; - case '}': type = TOKEN_RIGHT_CURLY; break; - case ',': type = TOKEN_COMMA; break; - case ':': type = TOKEN_COLON; break; - case '~': type = TOKEN_TILDE; break; - case '|': type = TOKEN_PIPE; break; - default: type = TOKEN_OPERATOR; } - return token(type, cur, lineno, colno); } else { // We are not at whitespace or a delimiter, so extract the // text and parse it tok = this._extractUntil(whitespaceChars + delimChars); - if (tok.match(/^[-+]?[0-9]+$/)) { if (this.current() === '.') { this.forward(); - var dec = this._extract(intChars); - return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); } else { return token(TOKEN_INT, tok, lineno, colno); @@ -22715,7 +20354,6 @@ var Tokenizer = /*#__PURE__*/function () { // delimiters because we need to look for block/variable start // tags (don't use the full delimChars for optimization) var beginChars = this.tags.BLOCK_START.charAt(0) + this.tags.VARIABLE_START.charAt(0) + this.tags.COMMENT_START.charAt(0) + this.tags.COMMENT_END.charAt(0); - if (this.isFinished()) { return null; } else if ((tok = this._extractString(this.tags.BLOCK_START + '-')) || (tok = this._extractString(this.tags.BLOCK_START))) { @@ -22728,44 +20366,38 @@ var Tokenizer = /*#__PURE__*/function () { tok = ''; var data; var inComment = false; - if (this._matches(this.tags.COMMENT_START)) { inComment = true; tok = this._extractString(this.tags.COMMENT_START); - } // Continually consume text, breaking on the tag delimiter + } + + // Continually consume text, breaking on the tag delimiter // characters and checking to see if it's a start tag. // // We could hit the end of the template in the middle of // our looping, so check for the null return value from // _extractUntil - - while ((data = this._extractUntil(beginChars)) !== null) { tok += data; - if ((this._matches(this.tags.BLOCK_START) || this._matches(this.tags.VARIABLE_START) || this._matches(this.tags.COMMENT_START)) && !inComment) { if (this.lstripBlocks && this._matches(this.tags.BLOCK_START) && this.colno > 0 && this.colno <= tok.length) { var lastLine = tok.slice(-this.colno); - if (/^\s+$/.test(lastLine)) { // Remove block leading whitespace from beginning of the string tok = tok.slice(0, -this.colno); - if (!tok.length) { // All data removed, collapse to avoid unnecessary nodes // by returning next token (block start) return this.nextToken(); } } - } // If it is a start tag, stop looping - - + } + // If it is a start tag, stop looping break; } else if (this._matches(this.tags.COMMENT_END)) { if (!inComment) { throw new Error('unexpected end of comment'); } - tok += this._extractString(this.tags.COMMENT_END); break; } else { @@ -22775,138 +20407,113 @@ var Tokenizer = /*#__PURE__*/function () { this.forward(); } } - if (data === null && inComment) { throw new Error('expected end of comment, got end of file'); } - return token(inComment ? TOKEN_COMMENT : TOKEN_DATA, tok, lineno, colno); } } }; - _proto._parseString = function _parseString(delimiter) { this.forward(); var str = ''; - while (!this.isFinished() && this.current() !== delimiter) { var cur = this.current(); - if (cur === '\\') { this.forward(); - switch (this.current()) { case 'n': str += '\n'; break; - case 't': str += '\t'; break; - case 'r': str += '\r'; break; - default: str += this.current(); } - this.forward(); } else { str += cur; this.forward(); } } - this.forward(); return str; }; - _proto._matches = function _matches(str) { if (this.index + str.length > this.len) { return null; } - var m = this.str.slice(this.index, this.index + str.length); return m === str; }; - _proto._extractString = function _extractString(str) { if (this._matches(str)) { this.forwardN(str.length); return str; } - return null; }; - _proto._extractUntil = function _extractUntil(charString) { // Extract all non-matching chars, with the default matching set // to everything return this._extractMatching(true, charString || ''); }; - _proto._extract = function _extract(charString) { // Extract all matching chars (no default, so charString must be // explicit) return this._extractMatching(false, charString); }; - _proto._extractMatching = function _extractMatching(breakOnMatch, charString) { // Pull out characters until a breaking char is hit. // If breakOnMatch is false, a non-matching char stops it. // If breakOnMatch is true, a matching char stops it. + if (this.isFinished()) { return null; } + var first = charString.indexOf(this.current()); - var first = charString.indexOf(this.current()); // Only proceed if the first character doesn't meet our condition - + // Only proceed if the first character doesn't meet our condition if (breakOnMatch && first === -1 || !breakOnMatch && first !== -1) { var t = this.current(); - this.forward(); // And pull out all the chars one at a time until we hit a - // breaking char + this.forward(); + // And pull out all the chars one at a time until we hit a + // breaking char var idx = charString.indexOf(this.current()); - while ((breakOnMatch && idx === -1 || !breakOnMatch && idx !== -1) && !this.isFinished()) { t += this.current(); this.forward(); idx = charString.indexOf(this.current()); } - return t; } - return ''; }; - _proto._extractRegex = function _extractRegex(regex) { var matches = this.currentStr().match(regex); - if (!matches) { return null; - } // Move forward whatever was matched - + } + // Move forward whatever was matched this.forwardN(matches[0].length); return matches; }; - _proto.isFinished = function isFinished() { return this.index >= this.len; }; - _proto.forwardN = function forwardN(n) { for (var i = 0; i < n; i++) { this.forward(); } }; - _proto.forward = function forward() { this.index++; - if (this.previous() === '\n') { this.lineno++; this.colno = 0; @@ -22914,20 +20521,16 @@ var Tokenizer = /*#__PURE__*/function () { this.colno++; } }; - _proto.backN = function backN(n) { for (var i = 0; i < n; i++) { this.back(); } }; - _proto.back = function back() { this.index--; - if (this.current() === '\n') { this.lineno--; var idx = this.src.lastIndexOf('\n', this.index - 1); - if (idx === -1) { this.colno = this.index; } else { @@ -22936,33 +20539,30 @@ var Tokenizer = /*#__PURE__*/function () { } else { this.colno--; } - } // current returns current character - ; + } + // current returns current character + ; _proto.current = function current() { if (!this.isFinished()) { return this.str.charAt(this.index); } - return ''; - } // currentStr returns what's left of the unparsed string - ; + } + // currentStr returns what's left of the unparsed string + ; _proto.currentStr = function currentStr() { if (!this.isFinished()) { return this.str.substr(this.index); } - return ''; }; - _proto.previous = function previous() { return this.str.charAt(this.index - 1); }; - return Tokenizer; }(); - module.exports = { lex: function lex(src, opts) { return new Tokenizer(src, opts); @@ -23010,50 +20610,41 @@ var escapeMap = { '"': '"', '\'': ''', '<': '<', - '>': '>' + '>': '>', + '\\': '\' }; -var escapeRegex = /[&"'<>]/g; - +var escapeRegex = /[&"'<>\\]/g; var _exports = module.exports = {}; - function hasOwnProp(obj, k) { return ObjProto.hasOwnProperty.call(obj, k); } - _exports.hasOwnProp = hasOwnProp; - function lookupEscape(ch) { return escapeMap[ch]; } - function _prettifyError(path, withInternals, err) { if (!err.Update) { // not one of ours, cast it err = new _exports.TemplateError(err); } + err.Update(path); - err.Update(path); // Unless they marked the dev flag, show them a trace from here - + // Unless they marked the dev flag, show them a trace from here if (!withInternals) { var old = err; err = new Error(old.message); err.name = old.name; } - return err; } - _exports._prettifyError = _prettifyError; - function TemplateError(message, lineno, colno) { var err; var cause; - if (message instanceof Error) { cause = message; message = cause.name + ": " + cause.message; } - if (Object.setPrototypeOf) { err = new Error(message); Object.setPrototypeOf(err, TemplateError.prototype); @@ -23065,24 +20656,18 @@ function TemplateError(message, lineno, colno) { value: message }); } - Object.defineProperty(err, 'name', { value: 'Template render error' }); - if (Error.captureStackTrace) { Error.captureStackTrace(err, this.constructor); } - var getStack; - if (cause) { var stackDescriptor = Object.getOwnPropertyDescriptor(cause, 'stack'); - getStack = stackDescriptor && (stackDescriptor.get || function () { return stackDescriptor.value; }); - if (!getStack) { getStack = function getStack() { return cause.stack; @@ -23090,12 +20675,10 @@ function TemplateError(message, lineno, colno) { } } else { var stack = new Error(message).stack; - getStack = function getStack() { return stack; }; } - Object.defineProperty(err, 'stack', { get: function get() { return getStack.call(err); @@ -23107,11 +20690,11 @@ function TemplateError(message, lineno, colno) { err.lineno = lineno; err.colno = colno; err.firstUpdate = true; - err.Update = function Update(path) { - var msg = '(' + (path || 'unknown path') + ')'; // only show lineno + colno next to path of template - // where error occurred + var msg = '(' + (path || 'unknown path') + ')'; + // only show lineno + colno next to path of template + // where error occurred if (this.firstUpdate) { if (this.lineno && this.colno) { msg += " [Line " + this.lineno + ", Column " + this.colno + "]"; @@ -23119,21 +20702,16 @@ function TemplateError(message, lineno, colno) { msg += " [Line " + this.lineno + "]"; } } - msg += '\n '; - if (this.firstUpdate) { msg += ' '; } - this.message = msg + (this.message || ''); this.firstUpdate = false; return this; }; - return err; } - if (Object.setPrototypeOf) { Object.setPrototypeOf(TemplateError.prototype, Error.prototype); } else { @@ -23143,149 +20721,112 @@ if (Object.setPrototypeOf) { } }); } - _exports.TemplateError = TemplateError; - function escape(val) { return val.replace(escapeRegex, lookupEscape); } - _exports.escape = escape; - function isFunction(obj) { return ObjProto.toString.call(obj) === '[object Function]'; } - _exports.isFunction = isFunction; - function isArray(obj) { return ObjProto.toString.call(obj) === '[object Array]'; } - _exports.isArray = isArray; - function isString(obj) { return ObjProto.toString.call(obj) === '[object String]'; } - _exports.isString = isString; - function isObject(obj) { return ObjProto.toString.call(obj) === '[object Object]'; } - _exports.isObject = isObject; + /** * @param {string|number} attr * @returns {(string|number)[]} * @private */ - function _prepareAttributeParts(attr) { if (!attr) { return []; } - if (typeof attr === 'string') { return attr.split('.'); } - return [attr]; } + /** * @param {string} attribute Attribute value. Dots allowed. * @returns {function(Object): *} */ - - function getAttrGetter(attribute) { var parts = _prepareAttributeParts(attribute); - return function attrGetter(item) { var _item = item; - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; // If item is not an object, and we still got parts to handle, it means - // that something goes wrong. Just roll out to undefined in that case. + var part = parts[i]; + // If item is not an object, and we still got parts to handle, it means + // that something goes wrong. Just roll out to undefined in that case. if (hasOwnProp(_item, part)) { _item = _item[part]; } else { return undefined; } } - return _item; }; } - _exports.getAttrGetter = getAttrGetter; - function groupBy(obj, val, throwOnUndefined) { var result = {}; var iterator = isFunction(val) ? val : getAttrGetter(val); - for (var i = 0; i < obj.length; i++) { var value = obj[i]; var key = iterator(value, i); - if (key === undefined && throwOnUndefined === true) { throw new TypeError("groupby: attribute \"" + val + "\" resolved to undefined"); } - (result[key] || (result[key] = [])).push(value); } - return result; } - _exports.groupBy = groupBy; - function toArray(obj) { return Array.prototype.slice.call(obj); } - _exports.toArray = toArray; - function without(array) { var result = []; - if (!array) { return result; } - var length = array.length; var contains = toArray(arguments).slice(1); var index = -1; - while (++index < length) { if (indexOf(contains, array[index]) === -1) { result.push(array[index]); } } - return result; } - _exports.without = without; - function repeat(char_, n) { var str = ''; - for (var i = 0; i < n; i++) { str += char_; } - return str; } - _exports.repeat = repeat; - function each(obj, func, context) { if (obj == null) { return; } - if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) { obj.forEach(func, context); } else if (obj.length === +obj.length) { @@ -23294,109 +20835,80 @@ function each(obj, func, context) { } } } - _exports.each = each; - function map(obj, func) { var results = []; - if (obj == null) { return results; } - if (ArrayProto.map && obj.map === ArrayProto.map) { return obj.map(func); } - for (var i = 0; i < obj.length; i++) { results[results.length] = func(obj[i], i); } - if (obj.length === +obj.length) { results.length = obj.length; } - return results; } - _exports.map = map; - function asyncIter(arr, iter, cb) { var i = -1; - function next() { i++; - if (i < arr.length) { iter(arr[i], i, next, cb); } else { cb(); } } - next(); } - _exports.asyncIter = asyncIter; - function asyncFor(obj, iter, cb) { var keys = keys_(obj || {}); var len = keys.length; var i = -1; - function next() { i++; var k = keys[i]; - if (i < len) { iter(k, obj[k], i, len, next); } else { cb(); } } - next(); } - _exports.asyncFor = asyncFor; - function indexOf(arr, searchElement, fromIndex) { return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex); } - _exports.indexOf = indexOf; - function keys_(obj) { /* eslint-disable no-restricted-syntax */ var arr = []; - for (var k in obj) { if (hasOwnProp(obj, k)) { arr.push(k); } } - return arr; } - _exports.keys = keys_; - function _entries(obj) { return keys_(obj).map(function (k) { return [k, obj[k]]; }); } - _exports._entries = _entries; - function _values(obj) { return keys_(obj).map(function (k) { return obj[k]; }); } - _exports._values = _values; - function extend(obj1, obj2) { obj1 = obj1 || {}; keys_(obj2).forEach(function (k) { @@ -23404,19 +20916,15 @@ function extend(obj1, obj2) { }); return obj1; } - _exports._assign = _exports.extend = extend; - function inOperator(key, val) { if (isArray(val) || isString(val)) { return val.indexOf(key) !== -1; } else if (isObject(val)) { return key in val; } - throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.'); } - _exports.inOperator = inOperator; /***/ }), @@ -23428,31 +20936,22 @@ _exports.inOperator = inOperator; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var path = __nccwpck_require__(1017); - var _require = __nccwpck_require__(7007), - EmitterObj = _require.EmitterObj; - + EmitterObj = _require.EmitterObj; module.exports = /*#__PURE__*/function (_EmitterObj) { _inheritsLoose(Loader, _EmitterObj); - function Loader() { return _EmitterObj.apply(this, arguments) || this; } - var _proto = Loader.prototype; - _proto.resolve = function resolve(from, to) { return path.resolve(path.dirname(from), to); }; - _proto.isRelative = function isRelative(filename) { return filename.indexOf('./') === 0 || filename.indexOf('../') === 0; }; - return Loader; }(EmitterObj); @@ -23477,45 +20976,33 @@ module.exports = __nccwpck_require__(9082); /* eslint-disable no-console */ -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var fs = __nccwpck_require__(7147); - var path = __nccwpck_require__(1017); - var Loader = __nccwpck_require__(6981); - var _require = __nccwpck_require__(8957), - PrecompiledLoader = _require.PrecompiledLoader; - + PrecompiledLoader = _require.PrecompiledLoader; var chokidar; - var FileSystemLoader = /*#__PURE__*/function (_Loader) { _inheritsLoose(FileSystemLoader, _Loader); - function FileSystemLoader(searchPaths, opts) { var _this; - _this = _Loader.call(this) || this; - if (typeof opts === 'boolean') { console.log('[nunjucks] Warning: you passed a boolean as the second ' + 'argument to FileSystemLoader, but it now takes an options ' + 'object. See http://mozilla.github.io/nunjucks/api.html#filesystemloader'); } - opts = opts || {}; _this.pathsToNames = {}; _this.noCache = !!opts.noCache; - if (searchPaths) { - searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths]; // For windows, convert to forward slashes - + searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths]; + // For windows, convert to forward slashes _this.searchPaths = searchPaths.map(path.normalize); } else { _this.searchPaths = ['.']; } - if (opts.watch) { // Watch all the templates in the paths and fire an event when // they change @@ -23524,13 +21011,10 @@ var FileSystemLoader = /*#__PURE__*/function (_Loader) { } catch (e) { throw new Error('watch requires chokidar to be installed'); } - var paths = _this.searchPaths.filter(fs.existsSync); - var watcher = chokidar.watch(paths); watcher.on('all', function (event, fullname) { fullname = path.resolve(fullname); - if (event === 'change' && fullname in _this.pathsToNames) { _this.emit('update', _this.pathsToNames[fullname], fullname); } @@ -23539,31 +21023,26 @@ var FileSystemLoader = /*#__PURE__*/function (_Loader) { console.log('Watcher error: ' + error); }); } - return _this; } - var _proto = FileSystemLoader.prototype; - _proto.getSource = function getSource(name) { var fullpath = null; var paths = this.searchPaths; - for (var i = 0; i < paths.length; i++) { var basePath = path.resolve(paths[i]); - var p = path.resolve(paths[i], name); // Only allow the current directory and anything - // underneath it to be searched + var p = path.resolve(paths[i], name); + // Only allow the current directory and anything + // underneath it to be searched if (p.indexOf(basePath) === 0 && fs.existsSync(p)) { fullpath = p; break; } } - if (!fullpath) { return null; } - this.pathsToNames[fullpath] = name; var source = { src: fs.readFileSync(fullpath, 'utf-8'), @@ -23573,66 +21052,50 @@ var FileSystemLoader = /*#__PURE__*/function (_Loader) { this.emit('load', name, source); return source; }; - return FileSystemLoader; }(Loader); - var NodeResolveLoader = /*#__PURE__*/function (_Loader2) { _inheritsLoose(NodeResolveLoader, _Loader2); - function NodeResolveLoader(opts) { var _this2; - _this2 = _Loader2.call(this) || this; opts = opts || {}; _this2.pathsToNames = {}; _this2.noCache = !!opts.noCache; - if (opts.watch) { try { chokidar = __nccwpck_require__(561); // eslint-disable-line global-require } catch (e) { throw new Error('watch requires chokidar to be installed'); } - _this2.watcher = chokidar.watch(); - _this2.watcher.on('change', function (fullname) { _this2.emit('update', _this2.pathsToNames[fullname], fullname); }); - _this2.watcher.on('error', function (error) { console.log('Watcher error: ' + error); }); - _this2.on('load', function (name, source) { _this2.watcher.add(source.path); }); } - return _this2; } - var _proto2 = NodeResolveLoader.prototype; - _proto2.getSource = function getSource(name) { // Don't allow file-system traversal if (/^\.?\.?(\/|\\)/.test(name)) { return null; } - if (/^[A-Z]:/.test(name)) { return null; } - var fullpath; - try { fullpath = require.resolve(name); } catch (e) { return null; } - this.pathsToNames[fullpath] = name; var source = { src: fs.readFileSync(fullpath, 'utf-8'), @@ -23642,10 +21105,8 @@ var NodeResolveLoader = /*#__PURE__*/function (_Loader2) { this.emit('load', name, source); return source; }; - return NodeResolveLoader; }(Loader); - module.exports = { FileSystemLoader: FileSystemLoader, PrecompiledLoader: PrecompiledLoader, @@ -23660,64 +21121,51 @@ module.exports = { "use strict"; -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _require = __nccwpck_require__(7007), - Obj = _require.Obj; - + Obj = _require.Obj; function traverseAndCheck(obj, type, results) { if (obj instanceof type) { results.push(obj); } - if (obj instanceof Node) { obj.findAll(type, results); } } - var Node = /*#__PURE__*/function (_Obj) { _inheritsLoose(Node, _Obj); - function Node() { return _Obj.apply(this, arguments) || this; } - var _proto = Node.prototype; - _proto.init = function init(lineno, colno) { var _arguments = arguments, - _this = this; - + _this = this; for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } - this.lineno = lineno; this.colno = colno; this.fields.forEach(function (field, i) { // The first two args are line/col numbers, so offset by 2 - var val = _arguments[i + 2]; // Fields should never be undefined, but null. It makes - // testing easier to normalize values. + var val = _arguments[i + 2]; + // Fields should never be undefined, but null. It makes + // testing easier to normalize values. if (val === undefined) { val = null; } - _this[field] = val; }); }; - _proto.findAll = function findAll(type, results) { var _this2 = this; - results = results || []; - if (this instanceof NodeList) { this.children.forEach(function (child) { return traverseAndCheck(child, type, results); @@ -23727,29 +21175,21 @@ var Node = /*#__PURE__*/function (_Obj) { return traverseAndCheck(_this2[field], type, results); }); } - return results; }; - _proto.iterFields = function iterFields(func) { var _this3 = this; - this.fields.forEach(function (field) { func(_this3[field], field); }); }; - return Node; }(Obj); // Abstract nodes - - var Value = /*#__PURE__*/function (_Node) { _inheritsLoose(Value, _Node); - function Value() { return _Node.apply(this, arguments) || this; } - _createClass(Value, [{ key: "typename", get: function get() { @@ -23761,28 +21201,20 @@ var Value = /*#__PURE__*/function (_Node) { return ['value']; } }]); - return Value; }(Node); // Concrete nodes - - var NodeList = /*#__PURE__*/function (_Node2) { _inheritsLoose(NodeList, _Node2); - function NodeList() { return _Node2.apply(this, arguments) || this; } - var _proto2 = NodeList.prototype; - _proto2.init = function init(lineno, colno, nodes) { _Node2.prototype.init.call(this, lineno, colno, nodes || []); }; - _proto2.addChild = function addChild(node) { this.children.push(node); }; - _createClass(NodeList, [{ key: "typename", get: function get() { @@ -23794,13 +21226,11 @@ var NodeList = /*#__PURE__*/function (_Node2) { return ['children']; } }]); - return NodeList; }(Node); - var Root = NodeList.extend('Root'); var Literal = Value.extend('Literal'); -var Symbol = Value.extend('Symbol'); +var _Symbol = Value.extend('Symbol'); var Group = NodeList.extend('Group'); var ArrayNode = NodeList.extend('Array'); var Pair = Node.extend('Pair', { @@ -23829,20 +21259,15 @@ var Caller = Macro.extend('Caller'); var Import = Node.extend('Import', { fields: ['template', 'target', 'withContext'] }); - var FromImport = /*#__PURE__*/function (_Node3) { _inheritsLoose(FromImport, _Node3); - function FromImport() { return _Node3.apply(this, arguments) || this; } - var _proto3 = FromImport.prototype; - _proto3.init = function init(lineno, colno, template, names, withContext) { _Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList(), withContext); }; - _createClass(FromImport, [{ key: "typename", get: function get() { @@ -23854,10 +21279,8 @@ var FromImport = /*#__PURE__*/function (_Node3) { return ['template', 'names', 'withContext']; } }]); - return FromImport; }(Node); - var FunCall = Node.extend('FunCall', { fields: ['name', 'args'] }); @@ -23931,25 +21354,24 @@ var CallExtension = Node.extend('CallExtension', { }, fields: ['extName', 'prop', 'args', 'contentArgs'] }); -var CallExtensionAsync = CallExtension.extend('CallExtensionAsync'); // This is hacky, but this is just a debugging function anyway +var CallExtensionAsync = CallExtension.extend('CallExtensionAsync'); +// This is hacky, but this is just a debugging function anyway function print(str, indent, inline) { var lines = str.split('\n'); lines.forEach(function (line, i) { if (line && (inline && i > 0 || !inline)) { process.stdout.write(' '.repeat(indent)); } - var nl = i === lines.length - 1 ? '' : '\n'; process.stdout.write("" + line + nl); }); -} // Print the AST in a nicely formatted tree format for debuggin - +} +// Print the AST in a nicely formatted tree format for debuggin function printNodes(node, indent) { indent = indent || 0; print(node.typename + ': ', indent); - if (node instanceof NodeList) { print('\n'); node.children.forEach(function (n) { @@ -23957,11 +21379,9 @@ function printNodes(node, indent) { }); } else if (node instanceof CallExtension) { print(node.extName + "." + node.prop + "\n"); - if (node.args) { printNodes(node.args, indent + 2); } - if (node.contentArgs) { node.contentArgs.forEach(function (n) { printNodes(n, indent + 2); @@ -23978,29 +21398,26 @@ function printNodes(node, indent) { props[fieldName] = val; } }); - if (props) { print(JSON.stringify(props, null, 2) + '\n', null, true); } else { print('\n'); } - nodes.forEach(function (_ref) { var fieldName = _ref[0], - n = _ref[1]; + n = _ref[1]; print("[" + fieldName + "] =>", indent + 2); printNodes(n, indent + 4); }); } } - module.exports = { Node: Node, Root: Root, NodeList: NodeList, Value: Value, Literal: Literal, - Symbol: Symbol, + Symbol: _Symbol, Group: Group, Array: ArrayNode, Pair: Pair, @@ -24059,131 +21476,102 @@ module.exports = { /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - // A simple class system, more documentation to come - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } +// A simple class system, more documentation to come +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var EventEmitter = __nccwpck_require__(2361); - var lib = __nccwpck_require__(4127); - function parentWrap(parent, prop) { if (typeof parent !== 'function' || typeof prop !== 'function') { return prop; } - return function wrap() { // Save the current parent method - var tmp = this.parent; // Set parent to the previous method, call, and restore + var tmp = this.parent; + // Set parent to the previous method, call, and restore this.parent = parent; var res = prop.apply(this, arguments); this.parent = tmp; return res; }; } - function extendClass(cls, name, props) { props = props || {}; lib.keys(props).forEach(function (k) { props[k] = parentWrap(cls.prototype[k], props[k]); }); - var subclass = /*#__PURE__*/function (_cls) { _inheritsLoose(subclass, _cls); - function subclass() { return _cls.apply(this, arguments) || this; } - _createClass(subclass, [{ key: "typename", get: function get() { return name; } }]); - return subclass; }(cls); - lib._assign(subclass.prototype, props); - return subclass; } - var Obj = /*#__PURE__*/function () { function Obj() { // Unfortunately necessary for backwards compatibility this.init.apply(this, arguments); } - var _proto = Obj.prototype; - _proto.init = function init() {}; - Obj.extend = function extend(name, props) { if (typeof name === 'object') { props = name; name = 'anonymous'; } - return extendClass(this, name, props); }; - _createClass(Obj, [{ key: "typename", get: function get() { return this.constructor.name; } }]); - return Obj; }(); - var EmitterObj = /*#__PURE__*/function (_EventEmitter) { _inheritsLoose(EmitterObj, _EventEmitter); - function EmitterObj() { var _this2; - var _this; - - _this = _EventEmitter.call(this) || this; // Unfortunately necessary for backwards compatibility - + _this = _EventEmitter.call(this) || this; + // Unfortunately necessary for backwards compatibility (_this2 = _this).init.apply(_this2, arguments); - return _this; } - var _proto2 = EmitterObj.prototype; - _proto2.init = function init() {}; - EmitterObj.extend = function extend(name, props) { if (typeof name === 'object') { props = name; name = 'anonymous'; } - return extendClass(this, name, props); }; - _createClass(EmitterObj, [{ key: "typename", get: function get() { return this.constructor.name; } }]); - return EmitterObj; }(EventEmitter); - module.exports = { Obj: Obj, EmitterObj: EmitterObj @@ -24198,26 +21586,17 @@ module.exports = { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var lexer = __nccwpck_require__(3158); - var nodes = __nccwpck_require__(429); - var Obj = (__nccwpck_require__(7007).Obj); - var lib = __nccwpck_require__(4127); - var Parser = /*#__PURE__*/function (_Obj) { _inheritsLoose(Parser, _Obj); - function Parser() { return _Obj.apply(this, arguments) || this; } - var _proto = Parser.prototype; - _proto.init = function init(tokens) { this.tokens = tokens; this.peeked = null; @@ -24225,10 +21604,8 @@ var Parser = /*#__PURE__*/function (_Obj) { this.dropLeadingWhitespace = false; this.extensions = []; }; - _proto.nextToken = function nextToken(withWhitespace) { var tok; - if (this.peeked) { if (!withWhitespace && this.peeked.type === lexer.TOKEN_WHITESPACE) { this.peeked = null; @@ -24238,108 +21615,80 @@ var Parser = /*#__PURE__*/function (_Obj) { return tok; } } - tok = this.tokens.nextToken(); - if (!withWhitespace) { while (tok && tok.type === lexer.TOKEN_WHITESPACE) { tok = this.tokens.nextToken(); } } - return tok; }; - _proto.peekToken = function peekToken() { this.peeked = this.peeked || this.nextToken(); return this.peeked; }; - _proto.pushToken = function pushToken(tok) { if (this.peeked) { throw new Error('pushToken: can only push one token on between reads'); } - this.peeked = tok; }; - _proto.error = function error(msg, lineno, colno) { if (lineno === undefined || colno === undefined) { var tok = this.peekToken() || {}; lineno = tok.lineno; colno = tok.colno; } - if (lineno !== undefined) { lineno += 1; } - if (colno !== undefined) { colno += 1; } - return new lib.TemplateError(msg, lineno, colno); }; - _proto.fail = function fail(msg, lineno, colno) { throw this.error(msg, lineno, colno); }; - _proto.skip = function skip(type) { var tok = this.nextToken(); - if (!tok || tok.type !== type) { this.pushToken(tok); return false; } - return true; }; - _proto.expect = function expect(type) { var tok = this.nextToken(); - if (tok.type !== type) { this.fail('expected ' + type + ', got ' + tok.type, tok.lineno, tok.colno); } - return tok; }; - _proto.skipValue = function skipValue(type, val) { var tok = this.nextToken(); - if (!tok || tok.type !== type || tok.value !== val) { this.pushToken(tok); return false; } - return true; }; - _proto.skipSymbol = function skipSymbol(val) { return this.skipValue(lexer.TOKEN_SYMBOL, val); }; - _proto.advanceAfterBlockEnd = function advanceAfterBlockEnd(name) { var tok; - if (!name) { tok = this.peekToken(); - if (!tok) { this.fail('unexpected end of file'); } - if (tok.type !== lexer.TOKEN_SYMBOL) { this.fail('advanceAfterBlockEnd: expected symbol token or ' + 'explicit name to be passed'); } - name = this.nextToken().value; } - tok = this.nextToken(); - if (tok && tok.type === lexer.TOKEN_BLOCK_END) { if (tok.value.charAt(0) === '-') { this.dropLeadingWhitespace = true; @@ -24347,13 +21696,10 @@ var Parser = /*#__PURE__*/function (_Obj) { } else { this.fail('expected block end in ' + name + ' statement'); } - return tok; }; - _proto.advanceAfterVariableEnd = function advanceAfterVariableEnd() { var tok = this.nextToken(); - if (tok && tok.type === lexer.TOKEN_VARIABLE_END) { this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.VARIABLE_END.length - 1) === '-'; } else { @@ -24361,12 +21707,10 @@ var Parser = /*#__PURE__*/function (_Obj) { this.fail('expected variable end'); } }; - _proto.parseFor = function parseFor() { var forTok = this.peekToken(); var node; var endBlock; - if (this.skipSymbol('for')) { node = new nodes.For(forTok.lineno, forTok.colno); endBlock = 'endfor'; @@ -24379,51 +21723,39 @@ var Parser = /*#__PURE__*/function (_Obj) { } else { this.fail('parseFor: expected for{Async}', forTok.lineno, forTok.colno); } - node.name = this.parsePrimary(); - if (!(node.name instanceof nodes.Symbol)) { this.fail('parseFor: variable name expected for loop'); } - var type = this.peekToken().type; - if (type === lexer.TOKEN_COMMA) { // key/value iteration var key = node.name; node.name = new nodes.Array(key.lineno, key.colno); node.name.addChild(key); - while (this.skip(lexer.TOKEN_COMMA)) { var prim = this.parsePrimary(); node.name.addChild(prim); } } - if (!this.skipSymbol('in')) { this.fail('parseFor: expected "in" keyword for loop', forTok.lineno, forTok.colno); } - node.arr = this.parseExpression(); this.advanceAfterBlockEnd(forTok.value); node.body = this.parseUntilBlocks(endBlock, 'else'); - if (this.skipSymbol('else')) { this.advanceAfterBlockEnd('else'); node.else_ = this.parseUntilBlocks(endBlock); } - this.advanceAfterBlockEnd(); return node; }; - _proto.parseMacro = function parseMacro() { var macroTok = this.peekToken(); - if (!this.skipSymbol('macro')) { this.fail('expected macro'); } - var name = this.parsePrimary(true); var args = this.parseSignature(); var node = new nodes.Macro(macroTok.lineno, macroTok.colno, name, args); @@ -24432,198 +21764,154 @@ var Parser = /*#__PURE__*/function (_Obj) { this.advanceAfterBlockEnd(); return node; }; - _proto.parseCall = function parseCall() { // a call block is parsed as a normal FunCall, but with an added // 'caller' kwarg which is a Caller node. var callTok = this.peekToken(); - if (!this.skipSymbol('call')) { this.fail('expected call'); } - var callerArgs = this.parseSignature(true) || new nodes.NodeList(); var macroCall = this.parsePrimary(); this.advanceAfterBlockEnd(callTok.value); var body = this.parseUntilBlocks('endcall'); this.advanceAfterBlockEnd(); var callerName = new nodes.Symbol(callTok.lineno, callTok.colno, 'caller'); - var callerNode = new nodes.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body); // add the additional caller kwarg, adding kwargs if necessary + var callerNode = new nodes.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body); + // add the additional caller kwarg, adding kwargs if necessary var args = macroCall.args.children; - if (!(args[args.length - 1] instanceof nodes.KeywordArgs)) { args.push(new nodes.KeywordArgs()); } - var kwargs = args[args.length - 1]; kwargs.addChild(new nodes.Pair(callTok.lineno, callTok.colno, callerName, callerNode)); return new nodes.Output(callTok.lineno, callTok.colno, [macroCall]); }; - _proto.parseWithContext = function parseWithContext() { var tok = this.peekToken(); var withContext = null; - if (this.skipSymbol('with')) { withContext = true; } else if (this.skipSymbol('without')) { withContext = false; } - if (withContext !== null) { if (!this.skipSymbol('context')) { this.fail('parseFrom: expected context after with/without', tok.lineno, tok.colno); } } - return withContext; }; - _proto.parseImport = function parseImport() { var importTok = this.peekToken(); - if (!this.skipSymbol('import')) { this.fail('parseImport: expected import', importTok.lineno, importTok.colno); } - var template = this.parseExpression(); - if (!this.skipSymbol('as')) { this.fail('parseImport: expected "as" keyword', importTok.lineno, importTok.colno); } - var target = this.parseExpression(); var withContext = this.parseWithContext(); var node = new nodes.Import(importTok.lineno, importTok.colno, template, target, withContext); this.advanceAfterBlockEnd(importTok.value); return node; }; - _proto.parseFrom = function parseFrom() { var fromTok = this.peekToken(); - if (!this.skipSymbol('from')) { this.fail('parseFrom: expected from'); } - var template = this.parseExpression(); - if (!this.skipSymbol('import')) { this.fail('parseFrom: expected import', fromTok.lineno, fromTok.colno); } - var names = new nodes.NodeList(); var withContext; - while (1) { // eslint-disable-line no-constant-condition var nextTok = this.peekToken(); - if (nextTok.type === lexer.TOKEN_BLOCK_END) { if (!names.children.length) { this.fail('parseFrom: Expected at least one import name', fromTok.lineno, fromTok.colno); - } // Since we are manually advancing past the block end, + } + + // Since we are manually advancing past the block end, // need to keep track of whitespace control (normally // this is done in `advanceAfterBlockEnd` - - if (nextTok.value.charAt(0) === '-') { this.dropLeadingWhitespace = true; } - this.nextToken(); break; } - if (names.children.length > 0 && !this.skip(lexer.TOKEN_COMMA)) { this.fail('parseFrom: expected comma', fromTok.lineno, fromTok.colno); } - var name = this.parsePrimary(); - if (name.value.charAt(0) === '_') { this.fail('parseFrom: names starting with an underscore cannot be imported', name.lineno, name.colno); } - if (this.skipSymbol('as')) { var alias = this.parsePrimary(); names.addChild(new nodes.Pair(name.lineno, name.colno, name, alias)); } else { names.addChild(name); } - withContext = this.parseWithContext(); } - return new nodes.FromImport(fromTok.lineno, fromTok.colno, template, names, withContext); }; - _proto.parseBlock = function parseBlock() { var tag = this.peekToken(); - if (!this.skipSymbol('block')) { this.fail('parseBlock: expected block', tag.lineno, tag.colno); } - var node = new nodes.Block(tag.lineno, tag.colno); node.name = this.parsePrimary(); - if (!(node.name instanceof nodes.Symbol)) { this.fail('parseBlock: variable name expected', tag.lineno, tag.colno); } - this.advanceAfterBlockEnd(tag.value); node.body = this.parseUntilBlocks('endblock'); this.skipSymbol('endblock'); this.skipSymbol(node.name.value); var tok = this.peekToken(); - if (!tok) { this.fail('parseBlock: expected endblock, got end of file'); } - this.advanceAfterBlockEnd(tok.value); return node; }; - _proto.parseExtends = function parseExtends() { var tagName = 'extends'; var tag = this.peekToken(); - if (!this.skipSymbol(tagName)) { this.fail('parseTemplateRef: expected ' + tagName); } - var node = new nodes.Extends(tag.lineno, tag.colno); node.template = this.parseExpression(); this.advanceAfterBlockEnd(tag.value); return node; }; - _proto.parseInclude = function parseInclude() { var tagName = 'include'; var tag = this.peekToken(); - if (!this.skipSymbol(tagName)) { this.fail('parseInclude: expected ' + tagName); } - var node = new nodes.Include(tag.lineno, tag.colno); node.template = this.parseExpression(); - if (this.skipSymbol('ignore') && this.skipSymbol('missing')) { node.ignoreMissing = true; } - this.advanceAfterBlockEnd(tag.value); return node; }; - _proto.parseIf = function parseIf() { var tag = this.peekToken(); var node; - if (this.skipSymbol('if') || this.skipSymbol('elif') || this.skipSymbol('elseif')) { node = new nodes.If(tag.lineno, tag.colno); } else if (this.skipSymbol('ifAsync')) { @@ -24631,54 +21919,42 @@ var Parser = /*#__PURE__*/function (_Obj) { } else { this.fail('parseIf: expected if, elif, or elseif', tag.lineno, tag.colno); } - node.cond = this.parseExpression(); this.advanceAfterBlockEnd(tag.value); node.body = this.parseUntilBlocks('elif', 'elseif', 'else', 'endif'); var tok = this.peekToken(); - switch (tok && tok.value) { case 'elseif': case 'elif': node.else_ = this.parseIf(); break; - case 'else': this.advanceAfterBlockEnd(); node.else_ = this.parseUntilBlocks('endif'); this.advanceAfterBlockEnd(); break; - case 'endif': node.else_ = null; this.advanceAfterBlockEnd(); break; - default: this.fail('parseIf: expected elif, else, or endif, got end of file'); } - return node; }; - _proto.parseSet = function parseSet() { var tag = this.peekToken(); - if (!this.skipSymbol('set')) { this.fail('parseSet: expected set', tag.lineno, tag.colno); } - var node = new nodes.Set(tag.lineno, tag.colno, []); var target; - while (target = this.parsePrimary()) { node.targets.push(target); - if (!this.skip(lexer.TOKEN_COMMA)) { break; } } - if (!this.skipValue(lexer.TOKEN_OPERATOR, '=')) { if (!this.skip(lexer.TOKEN_BLOCK_END)) { this.fail('parseSet: expected = or block end in set tag', tag.lineno, tag.colno); @@ -24691,10 +21967,8 @@ var Parser = /*#__PURE__*/function (_Obj) { node.value = this.parseExpression(); this.advanceAfterBlockEnd(tag.value); } - return node; }; - _proto.parseSwitch = function parseSwitch() { /* * Store the tag names in variables in case someone ever wants to @@ -24703,175 +21977,157 @@ var Parser = /*#__PURE__*/function (_Obj) { var switchStart = 'switch'; var switchEnd = 'endswitch'; var caseStart = 'case'; - var caseDefault = 'default'; // Get the switch tag. + var caseDefault = 'default'; - var tag = this.peekToken(); // fail early if we get some unexpected tag. + // Get the switch tag. + var tag = this.peekToken(); + // fail early if we get some unexpected tag. if (!this.skipSymbol(switchStart) && !this.skipSymbol(caseStart) && !this.skipSymbol(caseDefault)) { this.fail('parseSwitch: expected "switch," "case" or "default"', tag.lineno, tag.colno); - } // parse the switch expression - + } - var expr = this.parseExpression(); // advance until a start of a case, a default case or an endswitch. + // parse the switch expression + var expr = this.parseExpression(); + // advance until a start of a case, a default case or an endswitch. this.advanceAfterBlockEnd(switchStart); - this.parseUntilBlocks(caseStart, caseDefault, switchEnd); // this is the first case. it could also be an endswitch, we'll check. + this.parseUntilBlocks(caseStart, caseDefault, switchEnd); - var tok = this.peekToken(); // create new variables for our cases and default case. + // this is the first case. it could also be an endswitch, we'll check. + var tok = this.peekToken(); + // create new variables for our cases and default case. var cases = []; - var defaultCase; // while we're dealing with new cases nodes... + var defaultCase; + // while we're dealing with new cases nodes... do { // skip the start symbol and get the case expression this.skipSymbol(caseStart); var cond = this.parseExpression(); - this.advanceAfterBlockEnd(switchStart); // get the body of the case node and add it to the array of cases. - + this.advanceAfterBlockEnd(switchStart); + // get the body of the case node and add it to the array of cases. var body = this.parseUntilBlocks(caseStart, caseDefault, switchEnd); - cases.push(new nodes.Case(tok.line, tok.col, cond, body)); // get our next case - + cases.push(new nodes.Case(tok.line, tok.col, cond, body)); + // get our next case tok = this.peekToken(); - } while (tok && tok.value === caseStart); // we either have a default case or a switch end. - + } while (tok && tok.value === caseStart); + // we either have a default case or a switch end. switch (tok.value) { case caseDefault: this.advanceAfterBlockEnd(); defaultCase = this.parseUntilBlocks(switchEnd); this.advanceAfterBlockEnd(); break; - case switchEnd: this.advanceAfterBlockEnd(); break; - default: // otherwise bail because EOF this.fail('parseSwitch: expected "case," "default" or "endswitch," got EOF.'); - } // and return the switch node. - + } + // and return the switch node. return new nodes.Switch(tag.lineno, tag.colno, expr, cases, defaultCase); }; - _proto.parseStatement = function parseStatement() { var tok = this.peekToken(); var node; - if (tok.type !== lexer.TOKEN_SYMBOL) { this.fail('tag name expected', tok.lineno, tok.colno); } - if (this.breakOnBlocks && lib.indexOf(this.breakOnBlocks, tok.value) !== -1) { return null; } - switch (tok.value) { case 'raw': return this.parseRaw(); - case 'verbatim': return this.parseRaw('verbatim'); - case 'if': case 'ifAsync': return this.parseIf(); - case 'for': case 'asyncEach': case 'asyncAll': return this.parseFor(); - case 'block': return this.parseBlock(); - case 'extends': return this.parseExtends(); - case 'include': return this.parseInclude(); - case 'set': return this.parseSet(); - case 'macro': return this.parseMacro(); - case 'call': return this.parseCall(); - case 'import': return this.parseImport(); - case 'from': return this.parseFrom(); - case 'filter': return this.parseFilterStatement(); - case 'switch': return this.parseSwitch(); - default: if (this.extensions.length) { for (var i = 0; i < this.extensions.length; i++) { var ext = this.extensions[i]; - if (lib.indexOf(ext.tags || [], tok.value) !== -1) { return ext.parse(this, nodes, lexer); } } } - this.fail('unknown block tag: ' + tok.value, tok.lineno, tok.colno); } - return node; }; - _proto.parseRaw = function parseRaw(tagName) { tagName = tagName || 'raw'; - var endTagName = 'end' + tagName; // Look for upcoming raw blocks (ignore all other kinds of blocks) - + var endTagName = 'end' + tagName; + // Look for upcoming raw blocks (ignore all other kinds of blocks) var rawBlockRegex = new RegExp('([\\s\\S]*?){%\\s*(' + tagName + '|' + endTagName + ')\\s*(?=%})%}'); var rawLevel = 1; var str = ''; - var matches = null; // Skip opening raw token + var matches = null; + + // Skip opening raw token // Keep this token to track line and column numbers + var begun = this.advanceAfterBlockEnd(); - var begun = this.advanceAfterBlockEnd(); // Exit when there's nothing to match + // Exit when there's nothing to match // or when we've found the matching "endraw" block - while ((matches = this.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) { var all = matches[0]; var pre = matches[1]; - var blockName = matches[2]; // Adjust rawlevel + var blockName = matches[2]; + // Adjust rawlevel if (blockName === tagName) { rawLevel += 1; } else if (blockName === endTagName) { rawLevel -= 1; - } // Add to str - + } + // Add to str if (rawLevel === 0) { // We want to exclude the last "endraw" - str += pre; // Move tokenizer to beginning of endraw block - + str += pre; + // Move tokenizer to beginning of endraw block this.tokens.backN(all.length - pre.length); } else { str += all; } } - return new nodes.Output(begun.lineno, begun.colno, [new nodes.TemplateData(begun.lineno, begun.colno, str)]); }; - _proto.parsePostfix = function parsePostfix(node) { var lookup; var tok = this.peekToken(); - while (tok) { if (tok.type === lexer.TOKEN_LEFT_PAREN) { // Function call @@ -24879,114 +22135,89 @@ var Parser = /*#__PURE__*/function (_Obj) { } else if (tok.type === lexer.TOKEN_LEFT_BRACKET) { // Reference lookup = this.parseAggregate(); - if (lookup.children.length > 1) { this.fail('invalid index'); } - node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup.children[0]); } else if (tok.type === lexer.TOKEN_OPERATOR && tok.value === '.') { // Reference this.nextToken(); var val = this.nextToken(); - if (val.type !== lexer.TOKEN_SYMBOL) { this.fail('expected name as lookup value, got ' + val.value, val.lineno, val.colno); - } // Make a literal string because it's not a variable - // reference - + } + // Make a literal string because it's not a variable + // reference lookup = new nodes.Literal(val.lineno, val.colno, val.value); node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup); } else { break; } - tok = this.peekToken(); } - return node; }; - _proto.parseExpression = function parseExpression() { var node = this.parseInlineIf(); return node; }; - _proto.parseInlineIf = function parseInlineIf() { var node = this.parseOr(); - if (this.skipSymbol('if')) { var condNode = this.parseOr(); var bodyNode = node; node = new nodes.InlineIf(node.lineno, node.colno); node.body = bodyNode; node.cond = condNode; - if (this.skipSymbol('else')) { node.else_ = this.parseOr(); } else { node.else_ = null; } } - return node; }; - _proto.parseOr = function parseOr() { var node = this.parseAnd(); - while (this.skipSymbol('or')) { var node2 = this.parseAnd(); node = new nodes.Or(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseAnd = function parseAnd() { var node = this.parseNot(); - while (this.skipSymbol('and')) { var node2 = this.parseNot(); node = new nodes.And(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseNot = function parseNot() { var tok = this.peekToken(); - if (this.skipSymbol('not')) { return new nodes.Not(tok.lineno, tok.colno, this.parseNot()); } - return this.parseIn(); }; - _proto.parseIn = function parseIn() { var node = this.parseIs(); - while (1) { // eslint-disable-line no-constant-condition // check if the next token is 'not' var tok = this.nextToken(); - if (!tok) { break; } - - var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === 'not'; // if it wasn't 'not', put it back - + var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === 'not'; + // if it wasn't 'not', put it back if (!invert) { this.pushToken(tok); } - if (this.skipSymbol('in')) { var node2 = this.parseIs(); node = new nodes.In(node.lineno, node.colno, node, node2); - if (invert) { node = new nodes.Not(node.lineno, node.colno, node); } @@ -24995,45 +22226,40 @@ var Parser = /*#__PURE__*/function (_Obj) { if (invert) { this.pushToken(tok); } - break; } } - return node; - } // I put this right after "in" in the operator precedence stack. That can + } + + // I put this right after "in" in the operator precedence stack. That can // obviously be changed to be closer to Jinja. ; - _proto.parseIs = function parseIs() { - var node = this.parseCompare(); // look for an is - + var node = this.parseCompare(); + // look for an is if (this.skipSymbol('is')) { // look for a not - var not = this.skipSymbol('not'); // get the next node - - var node2 = this.parseCompare(); // create an Is node using the next node and the info from our Is node. - - node = new nodes.Is(node.lineno, node.colno, node, node2); // if we have a Not, create a Not node from our Is node. - + var not = this.skipSymbol('not'); + // get the next node + var node2 = this.parseCompare(); + // create an Is node using the next node and the info from our Is node. + node = new nodes.Is(node.lineno, node.colno, node, node2); + // if we have a Not, create a Not node from our Is node. if (not) { node = new nodes.Not(node.lineno, node.colno, node); } - } // return the node. - - + } + // return the node. return node; }; - _proto.parseCompare = function parseCompare() { var compareOps = ['==', '===', '!=', '!==', '<', '>', '<=', '>=']; var expr = this.parseConcat(); var ops = []; - while (1) { // eslint-disable-line no-constant-condition var tok = this.nextToken(); - if (!tok) { break; } else if (compareOps.indexOf(tok.value) !== -1) { @@ -25043,107 +22269,82 @@ var Parser = /*#__PURE__*/function (_Obj) { break; } } - if (ops.length) { return new nodes.Compare(ops[0].lineno, ops[0].colno, expr, ops); } else { return expr; } - } // finds the '~' for string concatenation - ; + } + // finds the '~' for string concatenation + ; _proto.parseConcat = function parseConcat() { var node = this.parseAdd(); - while (this.skipValue(lexer.TOKEN_TILDE, '~')) { var node2 = this.parseAdd(); node = new nodes.Concat(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseAdd = function parseAdd() { var node = this.parseSub(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '+')) { var node2 = this.parseSub(); node = new nodes.Add(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseSub = function parseSub() { var node = this.parseMul(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '-')) { var node2 = this.parseMul(); node = new nodes.Sub(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseMul = function parseMul() { var node = this.parseDiv(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '*')) { var node2 = this.parseDiv(); node = new nodes.Mul(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseDiv = function parseDiv() { var node = this.parseFloorDiv(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '/')) { var node2 = this.parseFloorDiv(); node = new nodes.Div(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseFloorDiv = function parseFloorDiv() { var node = this.parseMod(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '//')) { var node2 = this.parseMod(); node = new nodes.FloorDiv(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseMod = function parseMod() { var node = this.parsePow(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '%')) { var node2 = this.parsePow(); node = new nodes.Mod(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parsePow = function parsePow() { var node = this.parseUnary(); - while (this.skipValue(lexer.TOKEN_OPERATOR, '**')) { var node2 = this.parseUnary(); node = new nodes.Pow(node.lineno, node.colno, node, node2); } - return node; }; - _proto.parseUnary = function parseUnary(noFilters) { var tok = this.peekToken(); var node; - if (this.skipValue(lexer.TOKEN_OPERATOR, '-')) { node = new nodes.Neg(tok.lineno, tok.colno, this.parseUnary(true)); } else if (this.skipValue(lexer.TOKEN_OPERATOR, '+')) { @@ -25151,19 +22352,15 @@ var Parser = /*#__PURE__*/function (_Obj) { } else { node = this.parsePrimary(); } - if (!noFilters) { node = this.parseFilter(node); } - return node; }; - _proto.parsePrimary = function parsePrimary(noPostfix) { var tok = this.nextToken(); var val; var node = null; - if (!tok) { this.fail('expected expression, got end of file'); } else if (tok.type === lexer.TOKEN_STRING) { @@ -25185,7 +22382,6 @@ var Parser = /*#__PURE__*/function (_Obj) { } else if (tok.type === lexer.TOKEN_REGEX) { val = new RegExp(tok.value.body, tok.value.flags); } - if (val !== undefined) { node = new nodes.Literal(tok.lineno, tok.colno, val); } else if (tok.type === lexer.TOKEN_SYMBOL) { @@ -25196,29 +22392,23 @@ var Parser = /*#__PURE__*/function (_Obj) { this.pushToken(tok); node = this.parseAggregate(); } - if (!noPostfix) { node = this.parsePostfix(node); } - if (node) { return node; } else { throw this.error("unexpected token: " + tok.value, tok.lineno, tok.colno); } }; - _proto.parseFilterName = function parseFilterName() { var tok = this.expect(lexer.TOKEN_SYMBOL); var name = tok.value; - while (this.skipValue(lexer.TOKEN_OPERATOR, '.')) { name += '.' + this.expect(lexer.TOKEN_SYMBOL).value; } - return new nodes.Symbol(tok.lineno, tok.colno, name); }; - _proto.parseFilterArgs = function parseFilterArgs(node) { if (this.peekToken().type === lexer.TOKEN_LEFT_PAREN) { // Get a FunCall node and add the parameters to the @@ -25226,26 +22416,20 @@ var Parser = /*#__PURE__*/function (_Obj) { var call = this.parsePostfix(node); return call.args.children; } - return []; }; - _proto.parseFilter = function parseFilter(node) { while (this.skip(lexer.TOKEN_PIPE)) { var name = this.parseFilterName(); node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [node].concat(this.parseFilterArgs(node)))); } - return node; }; - _proto.parseFilterStatement = function parseFilterStatement() { var filterTok = this.peekToken(); - if (!this.skipSymbol('filter')) { this.fail('parseFilterStatement: expected filter'); } - var name = this.parseFilterName(); var args = this.parseFilterArgs(name); this.advanceAfterBlockEnd(filterTok.value); @@ -25254,53 +22438,45 @@ var Parser = /*#__PURE__*/function (_Obj) { var node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [body].concat(args))); return new nodes.Output(name.lineno, name.colno, [node]); }; - _proto.parseAggregate = function parseAggregate() { var tok = this.nextToken(); var node; - switch (tok.type) { case lexer.TOKEN_LEFT_PAREN: node = new nodes.Group(tok.lineno, tok.colno); break; - case lexer.TOKEN_LEFT_BRACKET: node = new nodes.Array(tok.lineno, tok.colno); break; - case lexer.TOKEN_LEFT_CURLY: node = new nodes.Dict(tok.lineno, tok.colno); break; - default: return null; } - while (1) { // eslint-disable-line no-constant-condition var type = this.peekToken().type; - if (type === lexer.TOKEN_RIGHT_PAREN || type === lexer.TOKEN_RIGHT_BRACKET || type === lexer.TOKEN_RIGHT_CURLY) { this.nextToken(); break; } - if (node.children.length > 0) { if (!this.skip(lexer.TOKEN_COMMA)) { this.fail('parseAggregate: expected comma after expression', tok.lineno, tok.colno); } } - if (node instanceof nodes.Dict) { // TODO: check for errors - var key = this.parsePrimary(); // We expect a key/value pair for dicts, separated by a - // colon + var key = this.parsePrimary(); + // We expect a key/value pair for dicts, separated by a + // colon if (!this.skip(lexer.TOKEN_COLON)) { this.fail('parseAggregate: expected colon after dict key', tok.lineno, tok.colno); - } // TODO: check for errors - + } + // TODO: check for errors var value = this.parseExpression(); node.addChild(new nodes.Pair(key.lineno, key.colno, key, value)); } else { @@ -25309,13 +22485,10 @@ var Parser = /*#__PURE__*/function (_Obj) { node.addChild(expr); } } - return node; }; - _proto.parseSignature = function parseSignature(tolerant, noParens) { var tok = this.peekToken(); - if (!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) { if (tolerant) { return null; @@ -25323,94 +22496,78 @@ var Parser = /*#__PURE__*/function (_Obj) { this.fail('expected arguments', tok.lineno, tok.colno); } } - if (tok.type === lexer.TOKEN_LEFT_PAREN) { tok = this.nextToken(); } - var args = new nodes.NodeList(tok.lineno, tok.colno); var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); var checkComma = false; - while (1) { // eslint-disable-line no-constant-condition tok = this.peekToken(); - if (!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) { this.nextToken(); break; } else if (noParens && tok.type === lexer.TOKEN_BLOCK_END) { break; } - if (checkComma && !this.skip(lexer.TOKEN_COMMA)) { this.fail('parseSignature: expected comma after expression', tok.lineno, tok.colno); } else { var arg = this.parseExpression(); - if (this.skipValue(lexer.TOKEN_OPERATOR, '=')) { kwargs.addChild(new nodes.Pair(arg.lineno, arg.colno, arg, this.parseExpression())); } else { args.addChild(arg); } } - checkComma = true; } - if (kwargs.children.length) { args.addChild(kwargs); } - return args; }; - _proto.parseUntilBlocks = function parseUntilBlocks() { var prev = this.breakOnBlocks; - for (var _len = arguments.length, blockNames = new Array(_len), _key = 0; _key < _len; _key++) { blockNames[_key] = arguments[_key]; } - this.breakOnBlocks = blockNames; var ret = this.parse(); this.breakOnBlocks = prev; return ret; }; - _proto.parseNodes = function parseNodes() { var tok; var buf = []; - while (tok = this.nextToken()) { if (tok.type === lexer.TOKEN_DATA) { var data = tok.value; var nextToken = this.peekToken(); - var nextVal = nextToken && nextToken.value; // If the last token has "-" we need to trim the + var nextVal = nextToken && nextToken.value; + + // If the last token has "-" we need to trim the // leading whitespace of the data. This is marked with // the `dropLeadingWhitespace` variable. - if (this.dropLeadingWhitespace) { // TODO: this could be optimized (don't use regex) data = data.replace(/^\s*/, ''); this.dropLeadingWhitespace = false; - } // Same for the succeeding block start token - + } + // Same for the succeeding block start token if (nextToken && (nextToken.type === lexer.TOKEN_BLOCK_START && nextVal.charAt(nextVal.length - 1) === '-' || nextToken.type === lexer.TOKEN_VARIABLE_START && nextVal.charAt(this.tokens.tags.VARIABLE_START.length) === '-' || nextToken.type === lexer.TOKEN_COMMENT && nextVal.charAt(this.tokens.tags.COMMENT_START.length) === '-')) { // TODO: this could be optimized (don't use regex) data = data.replace(/\s*$/, ''); } - buf.push(new nodes.Output(tok.lineno, tok.colno, [new nodes.TemplateData(tok.lineno, tok.colno, data)])); } else if (tok.type === lexer.TOKEN_BLOCK_START) { this.dropLeadingWhitespace = false; var n = this.parseStatement(); - if (!n) { break; } - buf.push(n); } else if (tok.type === lexer.TOKEN_VARIABLE_START) { var e = this.parseExpression(); @@ -25424,18 +22581,14 @@ var Parser = /*#__PURE__*/function (_Obj) { this.fail('Unexpected token at top-level: ' + tok.type, tok.lineno, tok.colno); } } - return buf; }; - _proto.parse = function parse() { return new nodes.NodeList(0, 0, this.parseNodes()); }; - _proto.parseAsRoot = function parseAsRoot() { return new nodes.Root(0, 0, this.parseNodes()); }; - return Parser; }(Obj); // var util = require('util'); // var l = lexer.lex('{%- if x -%}\n hello {% endif %}'); @@ -25448,16 +22601,12 @@ var Parser = /*#__PURE__*/function (_Obj) { // '{% endfilter %}')); // var n = p.parseAsRoot(); // nodes.printNodes(n); - - module.exports = { parse: function parse(src, extensions, opts) { var p = new Parser(lexer.lex(src, opts)); - if (extensions !== undefined) { p.extensions = extensions; } - return p.parseAsRoot(); }, Parser: Parser @@ -25474,22 +22623,17 @@ module.exports = { function precompileGlobal(templates, opts) { var out = ''; opts = opts || {}; - for (var i = 0; i < templates.length; i++) { var name = JSON.stringify(templates[i].name); var template = templates[i].template; out += '(function() {' + '(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' + '[' + name + '] = (function() {\n' + template + '\n})();\n'; - if (opts.asFunction) { out += 'return function(ctx, cb) { return nunjucks.render(' + name + ', ctx, cb); }\n'; } - out += '})();\n'; } - return out; } - module.exports = precompileGlobal; /***/ }), @@ -25501,42 +22645,31 @@ module.exports = precompileGlobal; var fs = __nccwpck_require__(7147); - var path = __nccwpck_require__(1017); - var _require = __nccwpck_require__(4127), - _prettifyError = _require._prettifyError; - + _prettifyError = _require._prettifyError; var compiler = __nccwpck_require__(4548); - var _require2 = __nccwpck_require__(4428), - Environment = _require2.Environment; - + Environment = _require2.Environment; var precompileGlobal = __nccwpck_require__(1524); - function match(filename, patterns) { if (!Array.isArray(patterns)) { return false; } - return patterns.some(function (pattern) { return filename.match(pattern); }); } - function precompileString(str, opts) { opts = opts || {}; opts.isString = true; var env = opts.env || new Environment([]); var wrapper = opts.wrapper || precompileGlobal; - if (!opts.name) { throw new Error('the "name" option is required when compiling a string'); } - return wrapper([_precompile(str, opts.name, env)], opts); } - function precompile(input, opts) { // The following options are available: // @@ -25551,27 +22684,23 @@ function precompile(input, opts) { // Customize the output format to store the compiled template. // By default, templates are stored in a global variable used by the runtime. // A custom loader will be necessary to load your custom wrapper. + opts = opts || {}; var env = opts.env || new Environment([]); var wrapper = opts.wrapper || precompileGlobal; - if (opts.isString) { return precompileString(input, opts); } - var pathStats = fs.existsSync(input) && fs.statSync(input); var precompiled = []; var templates = []; - function addTemplates(dir) { fs.readdirSync(dir).forEach(function (file) { var filepath = path.join(dir, file); var subpath = filepath.substr(path.join(input, '/').length); var stat = fs.statSync(filepath); - if (stat && stat.isDirectory()) { subpath += '/'; - if (!match(subpath, opts.exclude)) { addTemplates(filepath); } @@ -25580,15 +22709,12 @@ function precompile(input, opts) { } }); } - if (pathStats.isFile()) { precompiled.push(_precompile(fs.readFileSync(input, 'utf-8'), opts.name || input, env)); } else if (pathStats.isDirectory()) { addTemplates(input); - for (var i = 0; i < templates.length; i++) { var name = templates[i].replace(path.join(input, '/'), ''); - try { precompiled.push(_precompile(fs.readFileSync(templates[i], 'utf-8'), name, env)); } catch (e) { @@ -25602,29 +22728,24 @@ function precompile(input, opts) { } } } - return wrapper(precompiled, opts); } - function _precompile(str, name, env) { env = env || new Environment([]); var asyncFilters = env.asyncFilters; var extensions = env.extensionsList; var template; name = name.replace(/\\/g, '/'); - try { template = compiler.compile(str, asyncFilters, extensions, name, env.opts); } catch (err) { throw _prettifyError(name, false, err); } - return { name: name, template: template }; } - module.exports = { precompile: precompile, precompileString: precompileString @@ -25639,24 +22760,17 @@ module.exports = { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Loader = __nccwpck_require__(6981); - var PrecompiledLoader = /*#__PURE__*/function (_Loader) { _inheritsLoose(PrecompiledLoader, _Loader); - function PrecompiledLoader(compiledTemplates) { var _this; - _this = _Loader.call(this) || this; _this.precompiled = compiledTemplates || {}; return _this; } - var _proto = PrecompiledLoader.prototype; - _proto.getSource = function getSource(name) { if (this.precompiled[name]) { return { @@ -25667,13 +22781,10 @@ var PrecompiledLoader = /*#__PURE__*/function (_Loader) { path: name }; } - return null; }; - return PrecompiledLoader; }(Loader); - module.exports = { PrecompiledLoader: PrecompiledLoader }; @@ -25687,108 +22798,87 @@ module.exports = { var lib = __nccwpck_require__(4127); - var arrayFrom = Array.from; -var supportsIterators = typeof Symbol === 'function' && Symbol.iterator && typeof arrayFrom === 'function'; // Frames keep track of scoping both at compile-time and run-time so +var supportsIterators = typeof Symbol === 'function' && Symbol.iterator && typeof arrayFrom === 'function'; + +// Frames keep track of scoping both at compile-time and run-time so // we know how to access variables. Block tags can introduce special // variables, for example. - var Frame = /*#__PURE__*/function () { function Frame(parent, isolateWrites) { this.variables = Object.create(null); this.parent = parent; - this.topLevel = false; // if this is true, writes (set) should never propagate upwards past + this.topLevel = false; + // if this is true, writes (set) should never propagate upwards past // this frame to its parent (though reads may). - this.isolateWrites = isolateWrites; } - var _proto = Frame.prototype; - _proto.set = function set(name, val, resolveUp) { // Allow variables with dots by automatically creating the // nested structure var parts = name.split('.'); var obj = this.variables; var frame = this; - if (resolveUp) { if (frame = this.resolve(parts[0], true)) { frame.set(name, val); return; } } - for (var i = 0; i < parts.length - 1; i++) { var id = parts[i]; - if (!obj[id]) { obj[id] = {}; } - obj = obj[id]; } - obj[parts[parts.length - 1]] = val; }; - _proto.get = function get(name) { var val = this.variables[name]; - if (val !== undefined) { return val; } - return null; }; - _proto.lookup = function lookup(name) { var p = this.parent; var val = this.variables[name]; - if (val !== undefined) { return val; } - return p && p.lookup(name); }; - _proto.resolve = function resolve(name, forWrite) { var p = forWrite && this.isolateWrites ? undefined : this.parent; var val = this.variables[name]; - if (val !== undefined) { return this; } - return p && p.resolve(name); }; - _proto.push = function push(isolateWrites) { return new Frame(this, isolateWrites); }; - _proto.pop = function pop() { return this.parent; }; - return Frame; }(); - function makeMacro(argNames, kwargNames, func) { return function macro() { for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) { macroArgs[_key] = arguments[_key]; } - var argCount = numArgs(macroArgs); var args; var kwargs = getKeywordArgs(macroArgs); - if (argCount > argNames.length) { - args = macroArgs.slice(0, argNames.length); // Positional arguments that should be passed in as - // keyword arguments (essentially default values) + args = macroArgs.slice(0, argNames.length); + // Positional arguments that should be passed in as + // keyword arguments (essentially default values) macroArgs.slice(args.length, argCount).forEach(function (val, i) { if (i < kwargNames.length) { kwargs[kwargNames[i]] = val; @@ -25797,76 +22887,62 @@ function makeMacro(argNames, kwargNames, func) { args.push(kwargs); } else if (argCount < argNames.length) { args = macroArgs.slice(0, argCount); - for (var i = argCount; i < argNames.length; i++) { - var arg = argNames[i]; // Keyword arguments that should be passed as + var arg = argNames[i]; + + // Keyword arguments that should be passed as // positional arguments, i.e. the caller explicitly // used the name of a positional arg - args.push(kwargs[arg]); delete kwargs[arg]; } - args.push(kwargs); } else { args = macroArgs; } - return func.apply(this, args); }; } - function makeKeywordArgs(obj) { obj.__keywords = true; return obj; } - function isKeywordArgs(obj) { return obj && Object.prototype.hasOwnProperty.call(obj, '__keywords'); } - function getKeywordArgs(args) { var len = args.length; - if (len) { var lastArg = args[len - 1]; - if (isKeywordArgs(lastArg)) { return lastArg; } } - return {}; } - function numArgs(args) { var len = args.length; - if (len === 0) { return 0; } - var lastArg = args[len - 1]; - if (isKeywordArgs(lastArg)) { return len - 1; } else { return len; } -} // A SafeString object indicates that the string should not be +} + +// A SafeString object indicates that the string should not be // autoescaped. This happens magically because autoescaping only // occurs on primitive string objects. - - function SafeString(val) { if (typeof val !== 'string') { return val; } - this.val = val; this.length = val.length; } - SafeString.prototype = Object.create(String.prototype, { length: { writable: true, @@ -25874,26 +22950,20 @@ SafeString.prototype = Object.create(String.prototype, { value: 0 } }); - SafeString.prototype.valueOf = function valueOf() { return this.val; }; - SafeString.prototype.toString = function toString() { return this.val; }; - function copySafeness(dest, target) { if (dest instanceof SafeString) { return new SafeString(target); } - return target.toString(); } - function markSafe(val) { var type = typeof val; - if (type === 'string') { return new SafeString(val); } else if (type !== 'function') { @@ -25901,67 +22971,52 @@ function markSafe(val) { } else { return function wrapSafe(args) { var ret = val.apply(this, arguments); - if (typeof ret === 'string') { return new SafeString(ret); } - return ret; }; } } - function suppressValue(val, autoescape) { val = val !== undefined && val !== null ? val : ''; - if (autoescape && !(val instanceof SafeString)) { val = lib.escape(val.toString()); } - return val; } - function ensureDefined(val, lineno, colno) { if (val === null || val === undefined) { throw new lib.TemplateError('attempted to output null or undefined value', lineno + 1, colno + 1); } - return val; } - function memberLookup(obj, val) { if (obj === undefined || obj === null) { return undefined; } - if (typeof obj[val] === 'function') { return function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } - return obj[val].apply(obj, args); }; } - return obj[val]; } - function callWrap(obj, name, context, args) { if (!obj) { throw new Error('Unable to call `' + name + '`, which is undefined or falsey'); } else if (typeof obj !== 'function') { throw new Error('Unable to call `' + name + '`, which is not a function'); } - return obj.apply(context, args); } - function contextOrFrameLookup(context, frame, name) { var val = frame.lookup(name); return val !== undefined ? val : context.lookup(name); } - function handleError(error, lineno, colno) { if (error.lineno) { return error; @@ -25969,7 +23024,6 @@ function handleError(error, lineno, colno) { return new lib.TemplateError(error, lineno, colno); } } - function asyncEach(arr, dimen, iter, cb) { if (lib.isArray(arr)) { var len = arr.length; @@ -25978,15 +23032,12 @@ function asyncEach(arr, dimen, iter, cb) { case 1: iter(item, i, len, next); break; - case 2: iter(item[0], item[1], i, len, next); break; - case 3: iter(item[0], item[1], item[2], i, len, next); break; - default: item.push(i, len, next); iter.apply(this, item); @@ -25998,44 +23049,35 @@ function asyncEach(arr, dimen, iter, cb) { }, cb); } } - function asyncAll(arr, dimen, func, cb) { var finished = 0; var len; var outputArr; - function done(i, output) { finished++; outputArr[i] = output; - if (finished === len) { cb(null, outputArr.join('')); } } - if (lib.isArray(arr)) { len = arr.length; outputArr = new Array(len); - if (len === 0) { cb(null, ''); } else { for (var i = 0; i < arr.length; i++) { var item = arr[i]; - switch (dimen) { case 1: func(item, i, len, done); break; - case 2: func(item[0], item[1], i, len, done); break; - case 3: func(item[0], item[1], item[2], i, len, done); break; - default: item.push(i, len, done); func.apply(this, item); @@ -26046,7 +23088,6 @@ function asyncAll(arr, dimen, func, cb) { var keys = lib.keys(arr || {}); len = keys.length; outputArr = new Array(len); - if (len === 0) { cb(null, ''); } else { @@ -26057,7 +23098,6 @@ function asyncAll(arr, dimen, func, cb) { } } } - function fromIterator(arr) { if (typeof arr !== 'object' || arr === null || lib.isArray(arr)) { return arr; @@ -26067,7 +23107,6 @@ function fromIterator(arr) { return arr; } } - module.exports = { Frame: Frame, makeMacro: makeMacro, @@ -26099,29 +23138,27 @@ module.exports = { var SafeString = (__nccwpck_require__(1998).SafeString); + /** * Returns `true` if the object is a function, otherwise `false`. * @param { any } value * @returns { boolean } */ - - function callable(value) { return typeof value === 'function'; } - exports.callable = callable; + /** * Returns `true` if the object is strictly not `undefined`. * @param { any } value * @returns { boolean } */ - function defined(value) { return value !== undefined; } - exports.defined = defined; + /** * Returns `true` if the operand (one) is divisble by the test's argument * (two). @@ -26129,48 +23166,45 @@ exports.defined = defined; * @param { number } two * @returns { boolean } */ - function divisibleby(one, two) { return one % two === 0; } - exports.divisibleby = divisibleby; + /** * Returns true if the string has been escaped (i.e., is a SafeString). * @param { any } value * @returns { boolean } */ - function escaped(value) { return value instanceof SafeString; } - exports.escaped = escaped; + /** * Returns `true` if the arguments are strictly equal. * @param { any } one * @param { any } two */ - function equalto(one, two) { return one === two; } +exports.equalto = equalto; -exports.equalto = equalto; // Aliases - +// Aliases exports.eq = exports.equalto; exports.sameas = exports.equalto; + /** * Returns `true` if the value is evenly divisible by 2. * @param { number } value * @returns { boolean } */ - function even(value) { return value % 2 === 0; } - exports.even = even; + /** * Returns `true` if the value is falsy - if I recall correctly, '', 0, false, * undefined, NaN or null. I don't know if we should stick to the default JS @@ -26179,12 +23213,11 @@ exports.even = even; * @param { any } value * @returns { boolean } */ - function falsy(value) { return !value; } - exports.falsy = falsy; + /** * Returns `true` if the operand (one) is greater or equal to the test's * argument (two). @@ -26192,12 +23225,11 @@ exports.falsy = falsy; * @param { number } two * @returns { boolean } */ - function ge(one, two) { return one >= two; } - exports.ge = ge; + /** * Returns `true` if the operand (one) is greater than the test's argument * (two). @@ -26205,14 +23237,14 @@ exports.ge = ge; * @param { number } two * @returns { boolean } */ - function greaterthan(one, two) { return one > two; } +exports.greaterthan = greaterthan; -exports.greaterthan = greaterthan; // alias - +// alias exports.gt = exports.greaterthan; + /** * Returns `true` if the operand (one) is less than or equal to the test's * argument (two). @@ -26220,12 +23252,11 @@ exports.gt = exports.greaterthan; * @param { number } two * @returns { boolean } */ - function le(one, two) { return one <= two; } - exports.le = le; + /** * Returns `true` if the operand (one) is less than the test's passed argument * (two). @@ -26233,25 +23264,24 @@ exports.le = le; * @param { number } two * @returns { boolean } */ - function lessthan(one, two) { return one < two; } +exports.lessthan = lessthan; -exports.lessthan = lessthan; // alias - +// alias exports.lt = exports.lessthan; + /** * Returns `true` if the string is lowercased. * @param { string } value * @returns { boolean } */ - function lower(value) { return value.toLowerCase() === value; } - exports.lower = lower; + /** * Returns `true` if the operand (one) is less than or equal to the test's * argument (two). @@ -26259,90 +23289,82 @@ exports.lower = lower; * @param { number } two * @returns { boolean } */ - function ne(one, two) { return one !== two; } - exports.ne = ne; + /** * Returns true if the value is strictly equal to `null`. * @param { any } * @returns { boolean } */ - function nullTest(value) { return value === null; } - exports["null"] = nullTest; + /** * Returns true if value is a number. * @param { any } * @returns { boolean } */ - function number(value) { return typeof value === 'number'; } - exports.number = number; + /** * Returns `true` if the value is *not* evenly divisible by 2. * @param { number } value * @returns { boolean } */ - function odd(value) { return value % 2 === 1; } - exports.odd = odd; + /** * Returns `true` if the value is a string, `false` if not. * @param { any } value * @returns { boolean } */ - function string(value) { return typeof value === 'string'; } - exports.string = string; + /** * Returns `true` if the value is not in the list of things considered falsy: * '', null, undefined, 0, NaN and false. * @param { any } value * @returns { boolean } */ - function truthy(value) { return !!value; } - exports.truthy = truthy; + /** * Returns `true` if the value is undefined. * @param { any } value * @returns { boolean } */ - function undefinedTest(value) { return value === undefined; } - exports.undefined = undefinedTest; + /** * Returns `true` if the string is uppercased. * @param { string } value * @returns { boolean } */ - function upper(value) { return value.toUpperCase() === value; } - exports.upper = upper; + /** * If ES6 features are available, returns `true` if the value implements the * `Symbol.iterator` method. If not, it's a string or Array. @@ -26353,7 +23375,6 @@ exports.upper = upper; * @param { any } value * @returns { boolean } */ - function iterable(value) { if (typeof Symbol !== 'undefined') { return !!value[Symbol.iterator]; @@ -26361,26 +23382,23 @@ function iterable(value) { return Array.isArray(value) || typeof value === 'string'; } } - exports.iterable = iterable; + /** * If ES6 features are available, returns `true` if the value is an object hash * or an ES6 Map. Otherwise just return if it's an object hash. * @param { any } value * @returns { boolean } */ - function mapping(value) { // only maps and object hashes var bool = value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value); - if (Set) { return bool && !(value instanceof Set); } else { return bool; } } - exports.mapping = mapping; /***/ }), @@ -26392,52 +23410,40 @@ exports.mapping = mapping; var nodes = __nccwpck_require__(429); - var lib = __nccwpck_require__(4127); - var sym = 0; - function gensym() { return 'hole_' + sym++; -} // copy-on-write version of map - +} +// copy-on-write version of map function mapCOW(arr, func) { var res = null; - for (var i = 0; i < arr.length; i++) { var item = func(arr[i]); - if (item !== arr[i]) { if (!res) { res = arr.slice(); } - res[i] = item; } } - return res || arr; } - function walk(ast, func, depthFirst) { if (!(ast instanceof nodes.Node)) { return ast; } - if (!depthFirst) { var astT = func(ast); - if (astT && astT !== ast) { return astT; } } - if (ast instanceof nodes.NodeList) { var children = mapCOW(ast.children, function (node) { return walk(node, func, depthFirst); }); - if (children !== ast.children) { ast = new nodes[ast.typename](ast.lineno, ast.colno, children); } @@ -26446,7 +23452,6 @@ function walk(ast, func, depthFirst) { var contentArgs = mapCOW(ast.contentArgs, function (node) { return walk(node, func, depthFirst); }); - if (args !== ast.args || contentArgs !== ast.contentArgs) { ast = new nodes[ast.typename](ast.extName, ast.prop, args, contentArgs); } @@ -26457,7 +23462,6 @@ function walk(ast, func, depthFirst) { var propsT = mapCOW(props, function (prop) { return walk(prop, func, depthFirst); }); - if (propsT !== props) { ast = new nodes[ast.typename](ast.lineno, ast.colno); propsT.forEach(function (prop, i) { @@ -26465,35 +23469,28 @@ function walk(ast, func, depthFirst) { }); } } - return depthFirst ? func(ast) || ast : ast; } - function depthWalk(ast, func) { return walk(ast, func, true); } - function _liftFilters(node, asyncFilters, prop) { var children = []; var walked = depthWalk(prop ? node[prop] : node, function (descNode) { var symbol; - if (descNode instanceof nodes.Block) { return descNode; } else if (descNode instanceof nodes.Filter && lib.indexOf(asyncFilters, descNode.name.value) !== -1 || descNode instanceof nodes.CallExtensionAsync) { symbol = new nodes.Symbol(descNode.lineno, descNode.colno, gensym()); children.push(new nodes.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol)); } - return symbol; }); - if (prop) { node[prop] = walked; } else { node = walked; } - if (children.length) { children.push(node); return new nodes.NodeList(node.lineno, node.colno, children); @@ -26501,7 +23498,6 @@ function _liftFilters(node, asyncFilters, prop) { return node; } } - function liftFilters(ast, asyncFilters) { return depthWalk(ast, function (node) { if (node instanceof nodes.Output) { @@ -26519,13 +23515,11 @@ function liftFilters(ast, asyncFilters) { } }); } - function liftSuper(ast) { return walk(ast, function (blockNode) { if (!(blockNode instanceof nodes.Block)) { return; } - var hasSuper = false; var symbol = gensym(); blockNode.body = walk(blockNode.body, function (node) { @@ -26535,30 +23529,25 @@ function liftSuper(ast) { return new nodes.Symbol(node.lineno, node.colno, symbol); } }); - if (hasSuper) { blockNode.body.children.unshift(new nodes.Super(0, 0, blockNode.name, new nodes.Symbol(0, 0, symbol))); } }); } - function convertStatements(ast) { return depthWalk(ast, function (node) { if (!(node instanceof nodes.If) && !(node instanceof nodes.For)) { return undefined; } - var async = false; walk(node, function (child) { if (child instanceof nodes.FilterAsync || child instanceof nodes.IfAsync || child instanceof nodes.AsyncEach || child instanceof nodes.AsyncAll || child instanceof nodes.CallExtensionAsync) { - async = true; // Stop iterating by returning the node - + async = true; + // Stop iterating by returning the node return child; } - return undefined; }); - if (async) { if (node instanceof nodes.If) { return new nodes.IfAsync(node.lineno, node.colno, node.cond, node.body, node.else_); @@ -26566,23 +23555,21 @@ function convertStatements(ast) { return new nodes.AsyncEach(node.lineno, node.colno, node.arr, node.name, node.body, node.else_); } } - return undefined; }); } - function cps(ast, asyncFilters) { return convertStatements(liftSuper(liftFilters(ast, asyncFilters))); } - function transform(ast, asyncFilters) { return cps(ast, asyncFilters || []); -} // var parser = require('./parser'); +} + +// var parser = require('./parser'); // var src = 'hello {% foo %}{% endfoo %} end'; // var ast = transform(parser.parse(src, [new FooExtension()]), ['bar']); // nodes.printNodes(ast); - module.exports = { transform: transform }; @@ -30201,9 +27188,9 @@ class Git { async createPrBranch(existingPr) { core.debug(`Creating PR Branch ${ this.prBranch }`) - let checkout_existing_branch = existingPr !== undefined + const checkoutExistingBranch = existingPr !== undefined - if (checkout_existing_branch) { + if (checkoutExistingBranch) { await execCmd( `git remote set-branches origin "${ this.prBranch }"`, this.workingDir @@ -30214,7 +27201,7 @@ class Git { ) } - await this.checkout(this.prBranch, this.workingDir, !checkout_existing_branch) + await this.checkout(this.prBranch, this.workingDir, !checkoutExistingBranch) } async add(file) { @@ -30411,7 +27398,7 @@ class Git { } async deepenCheckout(depth, workingDir) { - let output = await execCmd( + const output = await execCmd( `git fetch --deepen=${ depth }`, workingDir, ) @@ -30481,7 +27468,7 @@ class Git { console.debug('BEFORE') console.debug(JSON.stringify(commitMessages, 2)) // Change a commit message FROM `foobar (#123)` TO `foobar (https://gh.com///pull/123)` - commitMessages = commitMessages.map(commitMessage => { + commitMessages = commitMessages.map((commitMessage) => { return commitMessage // Change a commit message FROM `foobar (#123)` TO `foobar (https://gh.com///pull/123)` .replace(new RegExp('\(#([0-9]+)\)', 'g'), `${ github.context.payload.repository.html_url }/pull/$2`) @@ -30494,7 +27481,7 @@ class Git { // Build the PR title from commit message(s) and list the commit messages in the PR description. const title = commitMessages.map((message) => message.split('\n')[0]).join('; ') - let originalCommitMessages = commitMessages.map((message) => { + const originalCommitMessages = commitMessages.map((message) => { const multiline = message.split('\n') if (multiline.length > 1) { // We build the return value this way to ensure that none of the lines are indented. @@ -31132,7 +28119,7 @@ async function run() { // If the push was forced, or there were multiple commits, deepen the checkouts if (github.context.payload?.forced || github.context.payload?.commits?.length > 1) { // let fetchDepth = Math.max(existingPrCommitsLength, github.context.payload.commits.length) - let fetchDepth = existingPrCommitsLength + github.context.payload.commits.length + const fetchDepth = existingPrCommitsLength + github.context.payload.commits.length await git.deepenCheckout(fetchDepth, SRC_REPO) await git.deepenCheckout(fetchDepth, DST_REPO) } @@ -31153,12 +28140,12 @@ async function run() { // (b) get the commits between `(a)..HEAD` for SRC_REPO & build the array of commits const commitHashes = await execCmd(`git log --reverse --format='%H' ${ srcRepoBaseCommitSha }..HEAD`, SRC_REPO) core.debug(`commit hashes: ${ commitHashes }`) - let individualCommits = commitHashes?.split('\n') + const individualCommits = commitHashes?.split('\n') core.debug(`individual commit hashes: ${ individualCommits }`) iterator = (await Promise.all(individualCommits?.map(async (hash, idx) => { core.debug(`processing hash #${ idx }: ${ hash }`) return await git.getCommitShaAndMessage(hash, SRC_REPO) - }))).filter(commit => commit.sha !== '' && commit.message !== '') + }))).filter((commit) => commit.sha !== '' && commit.message !== '') // (c) reset DST_REPO to the base sha await execCmd( @@ -31166,7 +28153,7 @@ async function run() { DST_REPO ) } - // If the payload was not force-pushed, but contains commits, we simply build the + // If the payload was not force-pushed, but contains commits, we simply build the // iterator from the payload's commits. else if (github.context.payload.commits) { iterator = github.context.payload.commits.map((commit) => ({ @@ -31174,7 +28161,7 @@ async function run() { message: commit.message, })) } - // Otherwise, we are likely run from `workflow_dispatch` event, so we just grab the + // Otherwise, we are likely run from `workflow_dispatch` event, so we just grab the // current head commit to use. else { iterator = [ await git.getCommitShaAndMessage('HEAD', SRC_REPO) ] @@ -31202,7 +28189,7 @@ async function run() { // Otherwise, there are still local changes left, so commit them before pushing core.debug(`Creating commit`) // Change a commit message FROM `foobar (#123)` TO `foobar (https://gh.com///pull/123)` - let commitMessage = commit.message.replace(new RegExp('\(#([0-9]+)\)', 'g'), `${ github.context.payload.repository.html_url }/pull/$2`) + const commitMessage = commit.message.replace(new RegExp('\(#([0-9]+)\)', 'g'), `${ github.context.payload.repository.html_url }/pull/$2`) await git.commit(commitMessage) modified.push({ dest: DST_REPO, @@ -31243,7 +28230,7 @@ async function run() { try { await git.addPrLabels(PR_LABELS) } catch (err) { - core.warning(`Failed to add label(s) "${PR_LABELS.join(', ')}" to PR`) + core.warning(`Failed to add label(s) "${ PR_LABELS.join(', ') }" to PR`) core.warning(err.message) } } @@ -31253,7 +28240,7 @@ async function run() { try { await git.addPrAssignees(ASSIGNEES) } catch (err) { - core.warning(`Failed to add assignee(s) "${ASSIGNEES.join(', ')}" to PR`) + core.warning(`Failed to add assignee(s) "${ ASSIGNEES.join(', ') }" to PR`) core.warning(err.message) } } @@ -31263,7 +28250,7 @@ async function run() { try { await git.addPrReviewers(REVIEWERS) } catch (err) { - core.warning(`Failed to add reviewer(s) "${REVIEWERS.join(', ')}" to PR`) + core.warning(`Failed to add reviewer(s) "${ REVIEWERS.join(', ') }" to PR`) core.warning(err.message) } } @@ -31273,7 +28260,7 @@ async function run() { try { await git.addPrTeamReviewers(TEAM_REVIEWERS) } catch (err) { - core.warning(`Failed to add team reviewer(s) "${TEAM_REVIEWERS.join(', ')}" to PR`) + core.warning(`Failed to add team reviewer(s) "${ TEAM_REVIEWERS.join(', ') }" to PR`) core.warning(err.message) } } diff --git a/src/git.js b/src/git.js index 7ad46340..564aa581 100644 --- a/src/git.js +++ b/src/git.js @@ -156,9 +156,9 @@ class Git { async createPrBranch(existingPr) { core.debug(`Creating PR Branch ${ this.prBranch }`) - let checkout_existing_branch = existingPr !== undefined + const checkoutExistingBranch = existingPr !== undefined - if (checkout_existing_branch) { + if (checkoutExistingBranch) { await execCmd( `git remote set-branches origin "${ this.prBranch }"`, this.workingDir @@ -169,7 +169,7 @@ class Git { ) } - await this.checkout(this.prBranch, this.workingDir, !checkout_existing_branch) + await this.checkout(this.prBranch, this.workingDir, !checkoutExistingBranch) } async add(file) { @@ -366,7 +366,7 @@ class Git { } async deepenCheckout(depth, workingDir) { - let output = await execCmd( + const output = await execCmd( `git fetch --deepen=${ depth }`, workingDir, ) @@ -436,7 +436,7 @@ class Git { console.debug('BEFORE') console.debug(JSON.stringify(commitMessages, 2)) // Change a commit message FROM `foobar (#123)` TO `foobar (https://gh.com///pull/123)` - commitMessages = commitMessages.map(commitMessage => { + commitMessages = commitMessages.map((commitMessage) => { return commitMessage // Change a commit message FROM `foobar (#123)` TO `foobar (https://gh.com///pull/123)` .replace(new RegExp('\(#([0-9]+)\)', 'g'), `${ github.context.payload.repository.html_url }/pull/$2`) @@ -449,7 +449,7 @@ class Git { // Build the PR title from commit message(s) and list the commit messages in the PR description. const title = commitMessages.map((message) => message.split('\n')[0]).join('; ') - let originalCommitMessages = commitMessages.map((message) => { + const originalCommitMessages = commitMessages.map((message) => { const multiline = message.split('\n') if (multiline.length > 1) { // We build the return value this way to ensure that none of the lines are indented. diff --git a/src/index.js b/src/index.js index e2d48e8e..2ddda6cc 100644 --- a/src/index.js +++ b/src/index.js @@ -82,7 +82,7 @@ async function run() { // If the push was forced, or there were multiple commits, deepen the checkouts if (github.context.payload?.forced || github.context.payload?.commits?.length > 1) { // let fetchDepth = Math.max(existingPrCommitsLength, github.context.payload.commits.length) - let fetchDepth = existingPrCommitsLength + github.context.payload.commits.length + const fetchDepth = existingPrCommitsLength + github.context.payload.commits.length await git.deepenCheckout(fetchDepth, SRC_REPO) await git.deepenCheckout(fetchDepth, DST_REPO) } @@ -103,12 +103,12 @@ async function run() { // (b) get the commits between `(a)..HEAD` for SRC_REPO & build the array of commits const commitHashes = await execCmd(`git log --reverse --format='%H' ${ srcRepoBaseCommitSha }..HEAD`, SRC_REPO) core.debug(`commit hashes: ${ commitHashes }`) - let individualCommits = commitHashes?.split('\n') + const individualCommits = commitHashes?.split('\n') core.debug(`individual commit hashes: ${ individualCommits }`) iterator = (await Promise.all(individualCommits?.map(async (hash, idx) => { core.debug(`processing hash #${ idx }: ${ hash }`) return await git.getCommitShaAndMessage(hash, SRC_REPO) - }))).filter(commit => commit.sha !== '' && commit.message !== '') + }))).filter((commit) => commit.sha !== '' && commit.message !== '') // (c) reset DST_REPO to the base sha await execCmd( @@ -116,7 +116,7 @@ async function run() { DST_REPO ) } - // If the payload was not force-pushed, but contains commits, we simply build the + // If the payload was not force-pushed, but contains commits, we simply build the // iterator from the payload's commits. else if (github.context.payload.commits) { iterator = github.context.payload.commits.map((commit) => ({ @@ -124,7 +124,7 @@ async function run() { message: commit.message, })) } - // Otherwise, we are likely run from `workflow_dispatch` event, so we just grab the + // Otherwise, we are likely run from `workflow_dispatch` event, so we just grab the // current head commit to use. else { iterator = [ await git.getCommitShaAndMessage('HEAD', SRC_REPO) ] @@ -152,7 +152,7 @@ async function run() { // Otherwise, there are still local changes left, so commit them before pushing core.debug(`Creating commit`) // Change a commit message FROM `foobar (#123)` TO `foobar (https://gh.com///pull/123)` - let commitMessage = commit.message.replace(new RegExp('\(#([0-9]+)\)', 'g'), `${ github.context.payload.repository.html_url }/pull/$2`) + const commitMessage = commit.message.replace(new RegExp('\(#([0-9]+)\)', 'g'), `${ github.context.payload.repository.html_url }/pull/$2`) await git.commit(commitMessage) modified.push({ dest: DST_REPO, @@ -193,7 +193,7 @@ async function run() { try { await git.addPrLabels(PR_LABELS) } catch (err) { - core.warning(`Failed to add label(s) "${PR_LABELS.join(', ')}" to PR`) + core.warning(`Failed to add label(s) "${ PR_LABELS.join(', ') }" to PR`) core.warning(err.message) } } @@ -203,7 +203,7 @@ async function run() { try { await git.addPrAssignees(ASSIGNEES) } catch (err) { - core.warning(`Failed to add assignee(s) "${ASSIGNEES.join(', ')}" to PR`) + core.warning(`Failed to add assignee(s) "${ ASSIGNEES.join(', ') }" to PR`) core.warning(err.message) } } @@ -213,7 +213,7 @@ async function run() { try { await git.addPrReviewers(REVIEWERS) } catch (err) { - core.warning(`Failed to add reviewer(s) "${REVIEWERS.join(', ')}" to PR`) + core.warning(`Failed to add reviewer(s) "${ REVIEWERS.join(', ') }" to PR`) core.warning(err.message) } } @@ -223,7 +223,7 @@ async function run() { try { await git.addPrTeamReviewers(TEAM_REVIEWERS) } catch (err) { - core.warning(`Failed to add team reviewer(s) "${TEAM_REVIEWERS.join(', ')}" to PR`) + core.warning(`Failed to add team reviewer(s) "${ TEAM_REVIEWERS.join(', ') }" to PR`) core.warning(err.message) } }