UNPKG

@gemini-dock/server

Version:

An extensible Gemini server written in TypeScript

4 lines 208 kB
{ "version": 3, "sources": ["../../../../node_modules/.pnpm/colorette@2.0.20/node_modules/colorette/index.cjs", "../../../../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js", "../../../../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js", "../../../../node_modules/.pnpm/end-of-stream@1.4.4/node_modules/end-of-stream/index.js", "../../../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js", "../../../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js", "../../../../node_modules/.pnpm/pino-abstract-transport@2.0.0/node_modules/pino-abstract-transport/index.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/constants.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/get-level-label-data.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/colors.js", "../../../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/noop.js", "../../../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/build-safe-sonic-boom.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/is-valid-date.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/create-date.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/split-property-key.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/get-property-value.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/delete-log-property.js", "../../../../node_modules/.pnpm/fast-copy@3.0.2/src/utils.ts", "../../../../node_modules/.pnpm/fast-copy@3.0.2/src/copier.ts", "../../../../node_modules/.pnpm/fast-copy@3.0.2/src/index.ts", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/filter-log.js", "../../../../node_modules/.pnpm/dateformat@4.6.3/node_modules/dateformat/lib/dateformat.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/format-time.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/handle-custom-levels-names-opts.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/handle-custom-levels-opts.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/interpret-conditionals.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/is-object.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/join-lines-with-indentation.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/parse-factory-options.js", "../../../../node_modules/.pnpm/fast-safe-stringify@2.1.1/node_modules/fast-safe-stringify/index.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-error.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-object.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-error-log.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-level.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-message.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-metadata.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/prettify-time.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/utils/index.js", "../../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/lib/pretty.js", "../../../../node_modules/.pnpm/pino-pretty@13.0.0/node_modules/pino-pretty/index.js"], "sourcesContent": ["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar tty = require('tty');\n\nfunction _interopNamespace(e) {\n if (e && e.__esModule) return e;\n var n = Object.create(null);\n if (e) {\n Object.keys(e).forEach(function (k) {\n if (k !== 'default') {\n var d = Object.getOwnPropertyDescriptor(e, k);\n Object.defineProperty(n, k, d.get ? d : {\n enumerable: true,\n get: function () { return e[k]; }\n });\n }\n });\n }\n n[\"default\"] = e;\n return Object.freeze(n);\n}\n\nvar tty__namespace = /*#__PURE__*/_interopNamespace(tty);\n\nconst {\n env = {},\n argv = [],\n platform = \"\",\n} = typeof process === \"undefined\" ? {} : process;\n\nconst isDisabled = \"NO_COLOR\" in env || argv.includes(\"--no-color\");\nconst isForced = \"FORCE_COLOR\" in env || argv.includes(\"--color\");\nconst isWindows = platform === \"win32\";\nconst isDumbTerminal = env.TERM === \"dumb\";\n\nconst isCompatibleTerminal =\n tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;\n\nconst isCI =\n \"CI\" in env &&\n (\"GITHUB_ACTIONS\" in env || \"GITLAB_CI\" in env || \"CIRCLECI\" in env);\n\nconst isColorSupported =\n !isDisabled &&\n (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);\n\nconst replaceClose = (\n index,\n string,\n close,\n replace,\n head = string.substring(0, index) + replace,\n tail = string.substring(index + close.length),\n next = tail.indexOf(close)\n) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));\n\nconst clearBleed = (index, string, open, close, replace) =>\n index < 0\n ? open + string + close\n : open + replaceClose(index, string, close, replace) + close;\n\nconst filterEmpty =\n (open, close, replace = open, at = open.length + 1) =>\n (string) =>\n string || !(string === \"\" || string === undefined)\n ? clearBleed(\n (\"\" + string).indexOf(close, at),\n string,\n open,\n close,\n replace\n )\n : \"\";\n\nconst init = (open, close, replace) =>\n filterEmpty(`\\x1b[${open}m`, `\\x1b[${close}m`, replace);\n\nconst colors = {\n reset: init(0, 0),\n bold: init(1, 22, \"\\x1b[22m\\x1b[1m\"),\n dim: init(2, 22, \"\\x1b[22m\\x1b[2m\"),\n italic: init(3, 23),\n underline: init(4, 24),\n inverse: init(7, 27),\n hidden: init(8, 28),\n strikethrough: init(9, 29),\n black: init(30, 39),\n red: init(31, 39),\n green: init(32, 39),\n yellow: init(33, 39),\n blue: init(34, 39),\n magenta: init(35, 39),\n cyan: init(36, 39),\n white: init(37, 39),\n gray: init(90, 39),\n bgBlack: init(40, 49),\n bgRed: init(41, 49),\n bgGreen: init(42, 49),\n bgYellow: init(43, 49),\n bgBlue: init(44, 49),\n bgMagenta: init(45, 49),\n bgCyan: init(46, 49),\n bgWhite: init(47, 49),\n blackBright: init(90, 39),\n redBright: init(91, 39),\n greenBright: init(92, 39),\n yellowBright: init(93, 39),\n blueBright: init(94, 39),\n magentaBright: init(95, 39),\n cyanBright: init(96, 39),\n whiteBright: init(97, 39),\n bgBlackBright: init(100, 49),\n bgRedBright: init(101, 49),\n bgGreenBright: init(102, 49),\n bgYellowBright: init(103, 49),\n bgBlueBright: init(104, 49),\n bgMagentaBright: init(105, 49),\n bgCyanBright: init(106, 49),\n bgWhiteBright: init(107, 49),\n};\n\nconst createColors = ({ useColor = isColorSupported } = {}) =>\n useColor\n ? colors\n : Object.keys(colors).reduce(\n (colors, key) => ({ ...colors, [key]: String }),\n {}\n );\n\nconst {\n reset,\n bold,\n dim,\n italic,\n underline,\n inverse,\n hidden,\n strikethrough,\n black,\n red,\n green,\n yellow,\n blue,\n magenta,\n cyan,\n white,\n gray,\n bgBlack,\n bgRed,\n bgGreen,\n bgYellow,\n bgBlue,\n bgMagenta,\n bgCyan,\n bgWhite,\n blackBright,\n redBright,\n greenBright,\n yellowBright,\n blueBright,\n magentaBright,\n cyanBright,\n whiteBright,\n bgBlackBright,\n bgRedBright,\n bgGreenBright,\n bgYellowBright,\n bgBlueBright,\n bgMagentaBright,\n bgCyanBright,\n bgWhiteBright,\n} = createColors();\n\nexports.bgBlack = bgBlack;\nexports.bgBlackBright = bgBlackBright;\nexports.bgBlue = bgBlue;\nexports.bgBlueBright = bgBlueBright;\nexports.bgCyan = bgCyan;\nexports.bgCyanBright = bgCyanBright;\nexports.bgGreen = bgGreen;\nexports.bgGreenBright = bgGreenBright;\nexports.bgMagenta = bgMagenta;\nexports.bgMagentaBright = bgMagentaBright;\nexports.bgRed = bgRed;\nexports.bgRedBright = bgRedBright;\nexports.bgWhite = bgWhite;\nexports.bgWhiteBright = bgWhiteBright;\nexports.bgYellow = bgYellow;\nexports.bgYellowBright = bgYellowBright;\nexports.black = black;\nexports.blackBright = blackBright;\nexports.blue = blue;\nexports.blueBright = blueBright;\nexports.bold = bold;\nexports.createColors = createColors;\nexports.cyan = cyan;\nexports.cyanBright = cyanBright;\nexports.dim = dim;\nexports.gray = gray;\nexports.green = green;\nexports.greenBright = greenBright;\nexports.hidden = hidden;\nexports.inverse = inverse;\nexports.isColorSupported = isColorSupported;\nexports.italic = italic;\nexports.magenta = magenta;\nexports.magentaBright = magentaBright;\nexports.red = red;\nexports.redBright = redBright;\nexports.reset = reset;\nexports.strikethrough = strikethrough;\nexports.underline = underline;\nexports.white = white;\nexports.whiteBright = whiteBright;\nexports.yellow = yellow;\nexports.yellowBright = yellowBright;\n", "// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n", "var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n", "var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n", "var once = require('once')\nvar eos = require('end-of-stream')\nvar fs\n\ntry {\n fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n} catch (e) {}\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n", "/*\nCopyright (c) 2014-2021, Matteo Collina <hello@matteocollina.com>\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\nIN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n\n'use strict'\n\nconst { Transform } = require('stream')\nconst { StringDecoder } = require('string_decoder')\nconst kLast = Symbol('last')\nconst kDecoder = Symbol('decoder')\n\nfunction transform (chunk, enc, cb) {\n let list\n if (this.overflow) { // Line buffer is full. Skip to start of next line.\n const buf = this[kDecoder].write(chunk)\n list = buf.split(this.matcher)\n\n if (list.length === 1) return cb() // Line ending not found. Discard entire chunk.\n\n // Line ending found. Discard trailing fragment of previous line and reset overflow state.\n list.shift()\n this.overflow = false\n } else {\n this[kLast] += this[kDecoder].write(chunk)\n list = this[kLast].split(this.matcher)\n }\n\n this[kLast] = list.pop()\n\n for (let i = 0; i < list.length; i++) {\n try {\n push(this, this.mapper(list[i]))\n } catch (error) {\n return cb(error)\n }\n }\n\n this.overflow = this[kLast].length > this.maxLength\n if (this.overflow && !this.skipOverflow) {\n cb(new Error('maximum buffer reached'))\n return\n }\n\n cb()\n}\n\nfunction flush (cb) {\n // forward any gibberish left in there\n this[kLast] += this[kDecoder].end()\n\n if (this[kLast]) {\n try {\n push(this, this.mapper(this[kLast]))\n } catch (error) {\n return cb(error)\n }\n }\n\n cb()\n}\n\nfunction push (self, val) {\n if (val !== undefined) {\n self.push(val)\n }\n}\n\nfunction noop (incoming) {\n return incoming\n}\n\nfunction split (matcher, mapper, options) {\n // Set defaults for any arguments not supplied.\n matcher = matcher || /\\r?\\n/\n mapper = mapper || noop\n options = options || {}\n\n // Test arguments explicitly.\n switch (arguments.length) {\n case 1:\n // If mapper is only argument.\n if (typeof matcher === 'function') {\n mapper = matcher\n matcher = /\\r?\\n/\n // If options is only argument.\n } else if (typeof matcher === 'object' && !(matcher instanceof RegExp) && !matcher[Symbol.split]) {\n options = matcher\n matcher = /\\r?\\n/\n }\n break\n\n case 2:\n // If mapper and options are arguments.\n if (typeof matcher === 'function') {\n options = mapper\n mapper = matcher\n matcher = /\\r?\\n/\n // If matcher and options are arguments.\n } else if (typeof mapper === 'object') {\n options = mapper\n mapper = noop\n }\n }\n\n options = Object.assign({}, options)\n options.autoDestroy = true\n options.transform = transform\n options.flush = flush\n options.readableObjectMode = true\n\n const stream = new Transform(options)\n\n stream[kLast] = ''\n stream[kDecoder] = new StringDecoder('utf8')\n stream.matcher = matcher\n stream.mapper = mapper\n stream.maxLength = options.maxLength\n stream.skipOverflow = options.skipOverflow || false\n stream.overflow = false\n stream._destroy = function (err, cb) {\n // Weird Node v12 bug that we need to work around\n this._writableState.errorEmitted = false\n cb(err)\n }\n\n return stream\n}\n\nmodule.exports = split\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst split = require('split2')\nconst { Duplex } = require('stream')\nconst { parentPort, workerData } = require('worker_threads')\n\nfunction createDeferred () {\n let resolve\n let reject\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve\n reject = _reject\n })\n promise.resolve = resolve\n promise.reject = reject\n return promise\n}\n\nmodule.exports = function build (fn, opts = {}) {\n const waitForConfig = opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig === true\n const parseLines = opts.parse === 'lines'\n const parseLine = typeof opts.parseLine === 'function' ? opts.parseLine : JSON.parse\n const close = opts.close || defaultClose\n const stream = split(function (line) {\n let value\n\n try {\n value = parseLine(line)\n } catch (error) {\n this.emit('unknown', line, error)\n return\n }\n\n if (value === null) {\n this.emit('unknown', line, 'Null value ignored')\n return\n }\n\n if (typeof value !== 'object') {\n value = {\n data: value,\n time: Date.now()\n }\n }\n\n if (stream[metadata]) {\n stream.lastTime = value.time\n stream.lastLevel = value.level\n stream.lastObj = value\n }\n\n if (parseLines) {\n return line\n }\n\n return value\n }, { autoDestroy: true })\n\n stream._destroy = function (err, cb) {\n const promise = close(err, cb)\n if (promise && typeof promise.then === 'function') {\n promise.then(cb, cb)\n }\n }\n\n if (opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig !== true) {\n setImmediate(() => {\n stream.emit('error', new Error('This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.'))\n })\n }\n\n if (opts.metadata !== false) {\n stream[metadata] = true\n stream.lastTime = 0\n stream.lastLevel = 0\n stream.lastObj = null\n }\n\n if (waitForConfig) {\n let pinoConfig = {}\n const configReceived = createDeferred()\n parentPort.on('message', function handleMessage (message) {\n if (message.code === 'PINO_CONFIG') {\n pinoConfig = message.config\n configReceived.resolve()\n parentPort.off('message', handleMessage)\n }\n })\n\n Object.defineProperties(stream, {\n levels: {\n get () { return pinoConfig.levels }\n },\n messageKey: {\n get () { return pinoConfig.messageKey }\n },\n errorKey: {\n get () { return pinoConfig.errorKey }\n }\n })\n\n return configReceived.then(finish)\n }\n\n return finish()\n\n function finish () {\n let res = fn(stream)\n\n if (res && typeof res.catch === 'function') {\n res.catch((err) => {\n stream.destroy(err)\n })\n\n // set it to null to not retain a reference to the promise\n res = null\n } else if (opts.enablePipelining && res) {\n return Duplex.from({ writable: stream, readable: res })\n }\n\n return stream\n }\n}\n\nfunction defaultClose (err, cb) {\n process.nextTick(cb, err)\n}\n", "'use strict'\n\n/**\n * A set of property names that indicate the value represents an error object.\n *\n * @typedef {string[]} K_ERROR_LIKE_KEYS\n */\n\nmodule.exports = {\n DATE_FORMAT: 'yyyy-mm-dd HH:MM:ss.l o',\n DATE_FORMAT_SIMPLE: 'HH:MM:ss.l',\n\n /**\n * @type {K_ERROR_LIKE_KEYS}\n */\n ERROR_LIKE_KEYS: ['err', 'error'],\n\n MESSAGE_KEY: 'msg',\n\n LEVEL_KEY: 'level',\n\n LEVEL_LABEL: 'levelLabel',\n\n TIMESTAMP_KEY: 'time',\n\n LEVELS: {\n default: 'USERLVL',\n 60: 'FATAL',\n 50: 'ERROR',\n 40: 'WARN',\n 30: 'INFO',\n 20: 'DEBUG',\n 10: 'TRACE'\n },\n\n LEVEL_NAMES: {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n debug: 20,\n trace: 10\n },\n\n // Object keys that probably came from a logger like Pino or Bunyan.\n LOGGER_KEYS: [\n 'pid',\n 'hostname',\n 'name',\n 'level',\n 'time',\n 'timestamp',\n 'caller'\n ]\n}\n", "'use strict'\n\nmodule.exports = getLevelLabelData\nconst { LEVELS, LEVEL_NAMES } = require('../constants')\n\n/**\n * Given initial settings for custom levels/names and use of only custom props\n * get the level label that corresponds with a given level number\n *\n * @param {boolean} useOnlyCustomProps\n * @param {object} customLevels\n * @param {object} customLevelNames\n *\n * @returns {function} A function that takes a number level and returns the level's label string\n */\nfunction getLevelLabelData (useOnlyCustomProps, customLevels, customLevelNames) {\n const levels = useOnlyCustomProps ? customLevels || LEVELS : Object.assign({}, LEVELS, customLevels)\n const levelNames = useOnlyCustomProps ? customLevelNames || LEVEL_NAMES : Object.assign({}, LEVEL_NAMES, customLevelNames)\n return function (level) {\n let levelNum = 'default'\n if (Number.isInteger(+level)) {\n levelNum = Object.prototype.hasOwnProperty.call(levels, level) ? level : levelNum\n } else {\n levelNum = Object.prototype.hasOwnProperty.call(levelNames, level.toLowerCase()) ? levelNames[level.toLowerCase()] : levelNum\n }\n\n return [levels[levelNum], levelNum]\n }\n}\n", "'use strict'\n\nconst nocolor = input => input\nconst plain = {\n default: nocolor,\n 60: nocolor,\n 50: nocolor,\n 40: nocolor,\n 30: nocolor,\n 20: nocolor,\n 10: nocolor,\n message: nocolor,\n greyMessage: nocolor\n}\n\nconst { createColors } = require('colorette')\nconst getLevelLabelData = require('./utils/get-level-label-data')\nconst availableColors = createColors({ useColor: true })\nconst { white, bgRed, red, yellow, green, blue, gray, cyan } = availableColors\n\nconst colored = {\n default: white,\n 60: bgRed,\n 50: red,\n 40: yellow,\n 30: green,\n 20: blue,\n 10: gray,\n message: cyan,\n greyMessage: gray\n}\n\nfunction resolveCustomColoredColorizer (customColors) {\n return customColors.reduce(\n function (agg, [level, color]) {\n agg[level] = typeof availableColors[color] === 'function' ? availableColors[color] : white\n\n return agg\n },\n { default: white, message: cyan, greyMessage: gray }\n )\n}\n\nfunction colorizeLevel (useOnlyCustomProps) {\n return function (level, colorizer, { customLevels, customLevelNames } = {}) {\n const [levelStr, levelNum] = getLevelLabelData(useOnlyCustomProps, customLevels, customLevelNames)(level)\n\n return Object.prototype.hasOwnProperty.call(colorizer, levelNum) ? colorizer[levelNum](levelStr) : colorizer.default(levelStr)\n }\n}\n\nfunction plainColorizer (useOnlyCustomProps) {\n const newPlainColorizer = colorizeLevel(useOnlyCustomProps)\n const customColoredColorizer = function (level, opts) {\n return newPlainColorizer(level, plain, opts)\n }\n customColoredColorizer.message = plain.message\n customColoredColorizer.greyMessage = plain.greyMessage\n customColoredColorizer.colors = createColors({ useColor: false })\n return customColoredColorizer\n}\n\nfunction coloredColorizer (useOnlyCustomProps) {\n const newColoredColorizer = colorizeLevel(useOnlyCustomProps)\n const customColoredColorizer = function (level, opts) {\n return newColoredColorizer(level, colored, opts)\n }\n customColoredColorizer.message = colored.message\n customColoredColorizer.greyMessage = colored.greyMessage\n customColoredColorizer.colors = availableColors\n return customColoredColorizer\n}\n\nfunction customColoredColorizerFactory (customColors, useOnlyCustomProps) {\n const onlyCustomColored = resolveCustomColoredColorizer(customColors)\n const customColored = useOnlyCustomProps ? onlyCustomColored : Object.assign({}, colored, onlyCustomColored)\n const colorizeLevelCustom = colorizeLevel(useOnlyCustomProps)\n\n const customColoredColorizer = function (level, opts) {\n return colorizeLevelCustom(level, customColored, opts)\n }\n customColoredColorizer.colors = availableColors\n customColoredColorizer.message = customColoredColorizer.message || customColored.message\n customColoredColorizer.greyMessage = customColoredColorizer.greyMessage || customColored.greyMessage\n\n return customColoredColorizer\n}\n\n/**\n * Applies colorization, if possible, to a string representing the passed in\n * `level`. For example, the default colorizer will return a \"green\" colored\n * string for the \"info\" level.\n *\n * @typedef {function} ColorizerFunc\n * @param {string|number} level In either case, the input will map to a color\n * for the specified level or to the color for `USERLVL` if the level is not\n * recognized.\n * @property {function} message Accepts one string parameter that will be\n * colorized to a predefined color.\n * @property {Colorette.Colorette} colors Available color functions based on `useColor` (or `colorize`) context\n */\n\n/**\n * Factory function get a function to colorized levels. The returned function\n * also includes a `.message(str)` method to colorize strings.\n *\n * @param {boolean} [useColors=false] When `true` a function that applies standard\n * terminal colors is returned.\n * @param {array[]} [customColors] Tuple where first item of each array is the\n * level index and the second item is the color\n * @param {boolean} [useOnlyCustomProps] When `true`, only use the provided\n * custom colors provided and not fallback to default\n *\n * @returns {ColorizerFunc} `function (level) {}` has a `.message(str)` method to\n * apply colorization to a string. The core function accepts either an integer\n * `level` or a `string` level. The integer level will map to a known level\n * string or to `USERLVL` if not known. The string `level` will map to the same\n * colors as the integer `level` and will also default to `USERLVL` if the given\n * string is not a recognized level name.\n */\nmodule.exports = function getColorizer (useColors = false, customColors, useOnlyCustomProps) {\n if (useColors && customColors !== undefined) {\n return customColoredColorizerFactory(customColors, useOnlyCustomProps)\n } else if (useColors) {\n return coloredColorizer(useOnlyCustomProps)\n }\n\n return plainColorizer(useOnlyCustomProps)\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n *