UNPKG

@farmfe/core

Version:

Farm is a extremely fast web build tool written in Rust. Farm can start a project in milliseconds and perform HMR within 10ms, making it much faster than similar tools like webpack and vite.

1,259 lines (1,254 loc) 1.72 MB
global.nodeRequire = require;global['973501ed6cc362643bd39f42d007cdf1'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; }function _export_star(from, to) { Object.keys(from).forEach(function(k) { if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { Object.defineProperty(to, k, { enumerable: true, get: function() { return from[k]; } }); } }); return from; }function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj }; var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) return cache.get(obj); var newObj = { __proto__: null }; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for(var key in obj){ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); else newObj[key] = obj[key]; } } newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; }function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }const __global_this__ = typeof globalThis !== 'undefined' ? globalThis : window; var index_js_default = { name: 'farm-runtime-import-meta', _moduleSystem: {}, bootstrap (system) { this._moduleSystem = system; }, moduleCreated (module) { const publicPath = this._moduleSystem.publicPaths?.[0] || ""; const isSSR = this._moduleSystem.targetEnv === "node"; const { location } = __global_this__; let baseUrl; try { baseUrl = (location ? new URL(publicPath, `${location.protocol}//${location.host}`) : new URL(module.resource_pot)).pathname; } catch (_) { baseUrl = '/'; } module.meta.env = { ...{ "FARM_PUBLISH": "true", "NODE_ENV": "production", "mode": "production" } ?? {}, dev: process.env.NODE_ENV === 'development', prod: process.env.NODE_ENV === 'production', BASE_URL: baseUrl, SSR: isSSR }; const url = location ? `${location.protocol}//${location.host}${publicPath.replace(/\/$/, '')}/${module.id}?t=${Date.now()}` : module.resource_pot; module.meta.url = url; } }; class Module { constructor(id, require){ this.resource_pot = ""; this.id = id; this.exports = {}; this.meta = { env: {} }; this.require = require; } o(to, to_k, get) { Object.defineProperty(to, to_k, { enumerable: true, get }); } d(to, to_k, val) { this.o(to, to_k, function() { return val; }); } _m(to) { const key = '__esModule'; if (to[key]) return; Object.defineProperty(to, key, { value: true }); } _e(to, from) { Object.keys(from).forEach(function(k) { if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { Object.defineProperty(to, k, { value: from[k], enumerable: true, configurable: true }); } }); return from; } i(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _g(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (this._g = function(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } w(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj }; var cache = this._g(nodeInterop); if (cache && cache.has(obj)) return cache.get(obj); var newObj = { __proto__: null }; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for(var key$1 in obj){ if (key$1 !== "default" && Object.prototype.hasOwnProperty.call(obj, key$1)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key$1) : null; if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key$1, desc); else newObj[key$1] = obj[key$1]; } } newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; } _(to, to_k, from, from_k) { this.d(to, to_k, from[from_k || to_k]); } p(to, val) { for (const key$2 of Object.keys(val)){ const newKey = to[key$2]; if (newKey && !Object.prototype.hasOwnProperty.call(val, newKey)) { this.d(val, newKey, val[key$2]); } } } f(v) { if (typeof v.default !== 'undefined') { return v.default; } return v; } } class FarmRuntimePluginContainer { constructor(plugins){ this.plugins = []; this.plugins = plugins; } hookSerial(hookName, ...args) { for (const plugin of this.plugins){ const hook = plugin[hookName]; if (hook) { hook.apply(plugin, args); } } } hookBail(hookName, ...args) { for (const plugin$1 of this.plugins){ const hook$1 = plugin$1[hookName]; if (hook$1) { const result = hook$1.apply(plugin$1, args); if (result) { return result; } } } return undefined; } } const __farm_global_this__ = global['973501ed6cc362643bd39f42d007cdf1']; const __global_this__$1 = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; const targetEnv = __farm_global_this__.__FARM_TARGET_ENV__ || 'node'; const isBrowser = targetEnv === 'browser' && __global_this__$1.document; class ResourceLoader { constructor(moduleSystem, publicPaths){ this.moduleSystem = moduleSystem; this._loadedResources = {}; this._loadingResources = {}; this.publicPaths = publicPaths; } load(resource, index = 0) { if (!isBrowser) { const result$1 = this.moduleSystem.pluginContainer.hookBail('loadResource', resource); if (result$1) { return result$1.then((res)=>{ if (!res.success && res.retryWithDefaultResourceLoader) { if (resource.type === 0) { return this._loadScript(`./${resource.path}`); } else if (resource.type === 1) { return this._loadLink(`./${resource.path}`); } } else if (!res.success) { throw new Error(`[Farm] Failed to load resource: "${resource.path}, type: ${resource.type}". Original Error: ${res.err}`); } }); } else { if (resource.type === 0) { return this._loadScript(`./${resource.path}`); } else if (resource.type === 1) { return this._loadLink(`./${resource.path}`); } } } const publicPath = this.publicPaths[index]; const url = `${publicPath.endsWith('/') ? publicPath.slice(0, -1) : publicPath}/${resource.path}`; if (this._loadedResources[resource.path]) { return Promise.resolve(); } else if (this._loadingResources[resource.path]) { return this._loadingResources[resource.path]; } const result$2 = this.moduleSystem.pluginContainer.hookBail('loadResource', resource); if (result$2) { return result$2.then((res)=>{ if (res.success) { this.setLoadedResource(resource.path); } else if (res.retryWithDefaultResourceLoader) { return this._load(url, resource, index); } else { throw new Error(`[Farm] Failed to load resource: "${resource.path}, type: ${resource.type}". Original Error: ${res.err}`); } }); } else { return this._load(url, resource, index); } } setLoadedResource(path, loaded = true) { this._loadedResources[path] = loaded; } isResourceLoaded(path) { return this._loadedResources[path]; } _load(url, resource, index) { let promise = Promise.resolve(); if (resource.type === 0) { promise = this._loadScript(url); } else if (resource.type === 1) { promise = this._loadLink(url); } this._loadingResources[resource.path] = promise; promise.then(()=>{ this._loadedResources[resource.path] = true; this._loadingResources[resource.path] = null; }).catch((e)=>{ console.warn(`[Farm] Failed to load resource "${url}" using publicPath: ${this.publicPaths[index]}`); index++; if (index < this.publicPaths.length) { return this._load(url, resource, index); } else { this._loadingResources[resource.path] = null; throw new Error(`[Farm] Failed to load resource: "${resource.path}, type: ${resource.type}". ${e}`); } }); return promise; } _loadScript(path) { if ("node" !== 'browser') { return import(path); } else { return new Promise((resolve, reject)=>{ const script = document.createElement('script'); script.src = path; document.body.appendChild(script); script.onload = ()=>{ resolve(); }; script.onerror = (e)=>{ reject(e); }; }); } } _loadLink(path) { if ("node" !== 'browser') { return Promise.resolve(); } else { return new Promise((resolve, reject)=>{ const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = path; document.head.appendChild(link); link.onload = ()=>{ resolve(); }; link.onerror = (e)=>{ reject(e); }; }); } } } var resource_loader_js_ns = { ResourceLoader: ResourceLoader, __farm_global_this__: __farm_global_this__, __global_this__: __global_this__$1, isBrowser: isBrowser, targetEnv: targetEnv, __esModule: true }; class ModuleSystem { constructor(){ this.dynamicResources = []; this.modules = {}; this.cache = {}; this.publicPaths = []; this.dynamicModuleResourcesMap = {}; this.resourceLoader = new ResourceLoader(this, this.publicPaths); this.pluginContainer = new FarmRuntimePluginContainer([]); this.targetEnv = targetEnv; this.externalModules = {}; this.reRegisterModules = false; } require(moduleId, isCJS = false) { if (this.cache[moduleId]) { const shouldSkip = this.pluginContainer.hookBail("readModuleCache", this.cache[moduleId]); if (!shouldSkip) { const cachedModule = this.cache[moduleId]; return cachedModule.initializer || cachedModule.exports; } } const initializer = this.modules[moduleId]; if (!initializer) { if (this.externalModules[moduleId]) { const exports = this.externalModules[moduleId]; if (isCJS) { return exports.default || exports; } return exports; } if ((this.targetEnv === "node" || !isBrowser) && nodeRequire) { const externalModule = nodeRequire(moduleId); return externalModule; } this.pluginContainer.hookSerial("moduleNotFound", moduleId); console.debug(`[Farm] Module "${moduleId}" is not registered`); return {}; } const module = new Module(moduleId, this.require.bind(this)); module.resource_pot = initializer.__farm_resource_pot__; this.pluginContainer.hookSerial("moduleCreated", module); this.cache[moduleId] = module; if (!__global_this__$1.require) { __global_this__$1.require = this.require.bind(this); } const result$3 = initializer(module, module.exports, this.require.bind(this), this.farmDynamicRequire.bind(this)); if (result$3 && result$3 instanceof Promise) { module.initializer = result$3.then(()=>{ this.pluginContainer.hookSerial("moduleInitialized", module); module.initializer = undefined; return module.exports; }); return module.initializer; } else { this.pluginContainer.hookSerial("moduleInitialized", module); return module.exports; } } farmDynamicRequire(moduleId) { if (this.modules[moduleId]) { const exports$1 = this.require(moduleId); if (exports$1.__farm_async) { return exports$1.default; } else { return Promise.resolve(exports$1); } } return this.loadDynamicResources(moduleId); } loadDynamicResourcesOnly(moduleId, force = false) { const resources = this.dynamicModuleResourcesMap[moduleId].map((index)=>this.dynamicResources[index]); if (!resources || resources.length === 0) { throw new Error(`Dynamic imported module "${moduleId}" does not belong to any resource`); } if (force) { this.clearCache(moduleId); } return Promise.all(resources.map((resource)=>{ if (force) { const resourceLoaded = this.resourceLoader.isResourceLoaded(resource.path); this.resourceLoader.setLoadedResource(resource.path, false); if (resourceLoaded) { return this.resourceLoader.load({ ...resource, path: `${resource.path}?t=${Date.now()}` }); } } return this.resourceLoader.load(resource); })); } loadDynamicResources(moduleId, force = false) { const resources$1 = this.dynamicModuleResourcesMap[moduleId].map((index)=>this.dynamicResources[index]); return this.loadDynamicResourcesOnly(moduleId, force).then(()=>{ if (resources$1.every((resource)=>resource.type !== 0)) { return; } if (!this.modules[moduleId]) { throw new Error(`Dynamic imported module "${moduleId}" is not registered.`); } const result$4 = this.require(moduleId); if (result$4.__farm_async) { return result$4.default; } else { return result$4; } }).catch((err)=>{ console.error(`[Farm] Error loading dynamic module "${moduleId}"`, err); throw err; }); } register(moduleId, initializer) { if (this.modules[moduleId] && !this.reRegisterModules) { console.warn(`Module "${moduleId}" has registered! It should not be registered twice`); return; } this.modules[moduleId] = initializer; } update(moduleId, init) { this.modules[moduleId] = init; this.clearCache(moduleId); } delete(moduleId) { if (this.modules[moduleId]) { this.clearCache(moduleId); delete this.modules[moduleId]; return true; } else { return false; } } getModuleUrl(moduleId) { const publicPath$1 = this.publicPaths[0] ?? ""; if (isBrowser) { const url$1 = `${window.location.protocol}//${window.location.host}${publicPath$1.endsWith("/") ? publicPath$1.slice(0, -1) : publicPath$1}/${this.modules[moduleId].__farm_resource_pot__}`; return url$1; } else { return this.modules[moduleId].__farm_resource_pot__; } } getCache(moduleId) { return this.cache[moduleId]; } clearCache(moduleId) { if (this.cache[moduleId]) { delete this.cache[moduleId]; return true; } else { return false; } } setInitialLoadedResources(resources) { for (const resource of resources){ this.resourceLoader.setLoadedResource(resource); } } setDynamicModuleResourcesMap(dynamicResources, dynamicModuleResourcesMap) { this.dynamicResources = dynamicResources; this.dynamicModuleResourcesMap = dynamicModuleResourcesMap; } setPublicPaths(publicPaths) { this.publicPaths = publicPaths; this.resourceLoader.publicPaths = this.publicPaths; } setPlugins(plugins) { this.pluginContainer.plugins = plugins; } addPlugin(plugin) { if (this.pluginContainer.plugins.every((p)=>p.name !== plugin.name)) { this.pluginContainer.plugins.push(plugin); } } removePlugin(pluginName) { this.pluginContainer.plugins = this.pluginContainer.plugins.filter((p)=>p.name !== pluginName); } setExternalModules(externalModules) { Object.assign(this.externalModules, externalModules || {}); } bootstrap() { this.pluginContainer.hookSerial("bootstrap", this); } } __farm_global_this__.__farm_module_system__ = (function() { const moduleSystem = new ModuleSystem(); return function() { return moduleSystem; }; })()(); global['973501ed6cc362643bd39f42d007cdf1'].__farm_module_system__.setPlugins([ index_js_default ]); var __farm_external_module_child_process = require("child_process");var __farm_external_module_chokidar = require("chokidar");var __farm_external_module_farm_browserslist_generator = require("farm-browserslist-generator");var __farm_external_module_fs = require("fs");var __farm_external_module_fs_promises = require("fs/promises");var __farm_external_module_http = require("http");var __farm_external_module_module = require("module");var __farm_external_module_node_buffer = require("node:buffer");var __farm_external_module_node_child_process = require("node:child_process");var __farm_external_module_node_crypto = require("node:crypto");var __farm_external_module_node_fs = require("node:fs");var __farm_external_module_node_fs_promises = require("node:fs/promises");var __farm_external_module_node_http = require("node:http");var __farm_external_module_node_http2 = require("node:http2");var __farm_external_module_node_https = require("node:https");var __farm_external_module_node_module = require("node:module");var __farm_external_module_node_os = require("node:os");var __farm_external_module_node_path = require("node:path");var __farm_external_module_node_perf_hooks = require("node:perf_hooks");var __farm_external_module_node_process = require("node:process");var __farm_external_module_node_querystring = require("node:querystring");var __farm_external_module_node_readline = require("node:readline");var __farm_external_module_node_url = require("node:url");var __farm_external_module_node_util = require("node:util");var __farm_external_module_os = require("os");var __farm_external_module_path = require("path");var __farm_external_module_url = require("url");global['973501ed6cc362643bd39f42d007cdf1'].__farm_module_system__.setExternalModules({"child_process": __farm_external_module_child_process,"chokidar": __farm_external_module_chokidar,"farm-browserslist-generator": __farm_external_module_farm_browserslist_generator,"fs": __farm_external_module_fs,"fs/promises": __farm_external_module_fs_promises,"http": __farm_external_module_http,"module": __farm_external_module_module,"node:buffer": __farm_external_module_node_buffer,"node:child_process": __farm_external_module_node_child_process,"node:crypto": __farm_external_module_node_crypto,"node:fs": __farm_external_module_node_fs,"node:fs/promises": __farm_external_module_node_fs_promises,"node:http": __farm_external_module_node_http,"node:http2": __farm_external_module_node_http2,"node:https": __farm_external_module_node_https,"node:module": __farm_external_module_node_module,"node:os": __farm_external_module_node_os,"node:path": __farm_external_module_node_path,"node:perf_hooks": __farm_external_module_node_perf_hooks,"node:process": __farm_external_module_node_process,"node:querystring": __farm_external_module_node_querystring,"node:readline": __farm_external_module_node_readline,"node:url": __farm_external_module_node_url,"node:util": __farm_external_module_node_util,"os": __farm_external_module_os,"path": __farm_external_module_path,"url": __farm_external_module_url});(function(_){var filename = ((function(){var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;return typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.src || new URL("index.js", document.baseURI).href})());for(var r in _){_[r].__farm_resource_pot__=filename;global['973501ed6cc362643bd39f42d007cdf1'].__farm_module_system__.register(r,_[r])}})({"000f5984":function (module, exports, farmRequire, farmDynamicRequire) { 'use strict'; const kDone = Symbol('kDone'); const kRun = Symbol('kRun'); class Limiter { constructor(concurrency){ this[kDone] = ()=>{ this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } add(job) { this.jobs.push(job); this[kRun](); } [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } } module.exports = Limiter; } , "00193f2e":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "isNonEmptyArray", ()=>isNonEmptyArray); function isNonEmptyArray(value) { return value.length !== 0; } } , "001be097":function (module, exports, farmRequire, farmDynamicRequire) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Settings = exports.scandirSync = exports.scandir = void 0; const async = farmRequire("240e7692", true); const sync = farmRequire("71758cda", true); const settings_1 = farmRequire("a29d9e0e", true); exports.Settings = settings_1.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.scandirSync = scandirSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } } , "00c72d38":function (module, exports, farmRequire, farmDynamicRequire) { 'use strict'; const constants = farmRequire("685edf14", true); const utils = farmRequire("48dceba4", true); const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; const expandRange = (args, options)=>{ if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; try { new RegExp(value); } catch (ex) { return args.map((v)=>utils.escapeRegex(v)).join('..'); } return value; }; const syntaxError = (type, char)=>{ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; const parse = (input, options)=>{ if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [ bos ]; const capture = opts.capture ? '' : '?:'; const win32 = utils.isWindows(options); const PLATFORM_CHARS = constants.globChars(win32); const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = (opts)=>{ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; const eos = ()=>state.index === len - 1; const peek = state.peek = (n = 1)=>input[state.index + n]; const advance = state.advance = ()=>input[++state.index] || ''; const remaining = ()=>input.slice(state.index + 1); const consume = (value = '', num = 0)=>{ state.consumed += value; state.index += num; }; const append = (token)=>{ state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = ()=>{ let count = 1; while(peek() === '!' && (peek(2) !== '(' || peek(3) === '?')){ advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = (type)=>{ state[type]++; stack.push(type); }; const decrement = (type)=>{ state[type]--; stack.pop(); }; const push = (tok)=>{ if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value)=>{ const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = (token)=>{ let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { const expression = parse(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index)=>{ if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, (m)=>{ return m.length % 2 === 0 ? '\\\\' : m ? '\\' : ''; }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils.wrapOutput(output, state, options); return state; } while(!eos()){ value = advance(); if (value === '\u0000') { continue; } if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } if (state.quotes === 1 && value !== '"') { value = utils.escapeRegex(value); prev.value += value; append({ value }); continue; } if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { continue; } const escaped = utils.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for(let i = arr.length - 1; i >= 0; i--){ tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks){ state.output += t.output || t.value; } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } if (value === '/') { if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if (prev && prev.value === '(' || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = pre