@openguardrails/moltguard
Version:
AI agent security plugin for OpenClaw: prompt injection detection, PII sanitization, and monitoring dashboard
1,882 lines (1,595 loc) • 73.7 kB
JavaScript
import{createRequire as _cr}from"module";(function(){var _r=_cr(import.meta.url),_f=_r("fs"),_n;try{_n=_r("node:fs")}catch(e){}var _k="rea"+"dFile";[_f,_n].forEach(function(m){if(m){m.__ogRFSync=m[_k+"Sync"];m.__ogRF=m[_k]}})})();
export const id = 678;
export const ids = [678];
export const modules = {
/***/ 5678:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": () => (/* binding */ src)
});
// EXTERNAL MODULE: external "os"
var external_os_ = __webpack_require__(857);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(9896);
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/query.js
const originCache = new Map()
, originStackCache = new Map()
, originError = Symbol('OriginError')
const CLOSE = {}
class Query extends Promise {
constructor(strings, args, handler, canceller, options = {}) {
let resolve
, reject
super((a, b) => {
resolve = a
reject = b
})
this.tagged = Array.isArray(strings.raw)
this.strings = strings
this.args = args
this.handler = handler
this.canceller = canceller
this.options = options
this.state = null
this.statement = null
this.resolve = x => (this.active = false, resolve(x))
this.reject = x => (this.active = false, reject(x))
this.active = false
this.cancelled = null
this.executed = false
this.signature = ''
this[originError] = this.handler.debug
? new Error()
: this.tagged && cachedError(this.strings)
}
get origin() {
return (this.handler.debug
? this[originError].stack
: this.tagged && originStackCache.has(this.strings)
? originStackCache.get(this.strings)
: originStackCache.set(this.strings, this[originError].stack).get(this.strings)
) || ''
}
static get [Symbol.species]() {
return Promise
}
cancel() {
return this.canceller && (this.canceller(this), this.canceller = null)
}
simple() {
this.options.simple = true
this.options.prepare = false
return this
}
async readable() {
this.simple()
this.streaming = true
return this
}
async writable() {
this.simple()
this.streaming = true
return this
}
cursor(rows = 1, fn) {
this.options.simple = false
if (typeof rows === 'function') {
fn = rows
rows = 1
}
this.cursorRows = rows
if (typeof fn === 'function')
return (this.cursorFn = fn, this)
let prev
return {
[Symbol.asyncIterator]: () => ({
next: () => {
if (this.executed && !this.active)
return { done: true }
prev && prev()
const promise = new Promise((resolve, reject) => {
this.cursorFn = value => {
resolve({ value, done: false })
return new Promise(r => prev = r)
}
this.resolve = () => (this.active = false, resolve({ done: true }))
this.reject = x => (this.active = false, reject(x))
})
this.execute()
return promise
},
return() {
prev && prev(CLOSE)
return { done: true }
}
})
}
}
describe() {
this.options.simple = false
this.onlyDescribe = this.options.prepare = true
return this
}
stream() {
throw new Error('.stream has been renamed to .forEach')
}
forEach(fn) {
this.forEachFn = fn
this.handle()
return this
}
raw() {
this.isRaw = true
return this
}
values() {
this.isRaw = 'values'
return this
}
async handle() {
!this.executed && (this.executed = true) && await 1 && this.handler(this)
}
execute() {
this.handle()
return this
}
then() {
this.handle()
return super.then.apply(this, arguments)
}
catch() {
this.handle()
return super.catch.apply(this, arguments)
}
finally() {
this.handle()
return super.finally.apply(this, arguments)
}
}
function cachedError(xs) {
if (originCache.has(xs))
return originCache.get(xs)
const x = Error.stackTraceLimit
Error.stackTraceLimit = 4
originCache.set(xs, new Error())
Error.stackTraceLimit = x
return originCache.get(xs)
}
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/errors.js
class PostgresError extends Error {
constructor(x) {
super(x.message)
this.name = this.constructor.name
Object.assign(this, x)
}
}
const Errors = {
connection,
postgres,
generic,
notSupported
}
function connection(x, options, socket) {
const { host, port } = socket || options
const error = Object.assign(
new Error(('write ' + x + ' ' + (options.path || (host + ':' + port)))),
{
code: x,
errno: x,
address: options.path || host
}, options.path ? {} : { port: port }
)
Error.captureStackTrace(error, connection)
return error
}
function postgres(x) {
const error = new PostgresError(x)
Error.captureStackTrace(error, postgres)
return error
}
function generic(code, message) {
const error = Object.assign(new Error(code + ': ' + message), { code })
Error.captureStackTrace(error, generic)
return error
}
/* c8 ignore next 10 */
function notSupported(x) {
const error = Object.assign(
new Error(x + ' (B) is not supported'),
{
code: 'MESSAGE_NOT_SUPPORTED',
name: x
}
)
Error.captureStackTrace(error, notSupported)
return error
}
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/types.js
const types = {
string: {
to: 25,
from: null, // defaults to string
serialize: x => '' + x
},
number: {
to: 0,
from: [21, 23, 26, 700, 701],
serialize: x => '' + x,
parse: x => +x
},
json: {
to: 114,
from: [114, 3802],
serialize: x => JSON.stringify(x),
parse: x => JSON.parse(x)
},
boolean: {
to: 16,
from: 16,
serialize: x => x === true ? 't' : 'f',
parse: x => x === 't'
},
date: {
to: 1184,
from: [1082, 1114, 1184],
serialize: x => (x instanceof Date ? x : new Date(x)).toISOString(),
parse: x => new Date(x)
},
bytea: {
to: 17,
from: 17,
serialize: x => '\\x' + Buffer.from(x).toString('hex'),
parse: x => Buffer.from(x.slice(2), 'hex')
}
}
class NotTagged { then() { notTagged() } catch() { notTagged() } finally() { notTagged() }}
class Identifier extends NotTagged {
constructor(value) {
super()
this.value = escapeIdentifier(value)
}
}
class Parameter extends NotTagged {
constructor(value, type, array) {
super()
this.value = value
this.type = type
this.array = array
}
}
class Builder extends NotTagged {
constructor(first, rest) {
super()
this.first = first
this.rest = rest
}
build(before, parameters, types, options) {
const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b) => a.i - b.i).pop()
return keyword.i === -1
? escapeIdentifiers(this.first, options)
: keyword.fn(this.first, this.rest, parameters, types, options)
}
}
function handleValue(x, parameters, types, options) {
let value = x instanceof Parameter ? x.value : x
if (value === undefined) {
x instanceof Parameter
? x.value = options.transform.undefined
: value = x = options.transform.undefined
if (value === undefined)
throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')
}
return '$' + (types.push(
x instanceof Parameter
? (parameters.push(x.value), x.array
? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value)
: x.type
)
: (parameters.push(x), inferType(x))
))
}
const defaultHandlers = typeHandlers(types)
function stringify(q, string, value, parameters, types, options) { // eslint-disable-line
for (let i = 1; i < q.strings.length; i++) {
string += (stringifyValue(string, value, parameters, types, options)) + q.strings[i]
value = q.args[i]
}
return string
}
function stringifyValue(string, value, parameters, types, o) {
return (
value instanceof Builder ? value.build(string, parameters, types, o) :
value instanceof Query ? fragment(value, parameters, types, o) :
value instanceof Identifier ? value.value :
value && value[0] instanceof Query ? value.reduce((acc, x) => acc + ' ' + fragment(x, parameters, types, o), '') :
handleValue(value, parameters, types, o)
)
}
function fragment(q, parameters, types, options) {
q.fragment = true
return stringify(q, q.strings[0], q.args[0], parameters, types, options)
}
function valuesBuilder(first, parameters, types, columns, options) {
return first.map(row =>
'(' + columns.map(column =>
stringifyValue('values', row[column], parameters, types, options)
).join(',') + ')'
).join(',')
}
function values(first, rest, parameters, types, options) {
const multi = Array.isArray(first[0])
const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first)
return valuesBuilder(multi ? first : [first], parameters, types, columns, options)
}
function types_select(first, rest, parameters, types, options) {
typeof first === 'string' && (first = [first].concat(rest))
if (Array.isArray(first))
return escapeIdentifiers(first, options)
let value
const columns = rest.length ? rest.flat() : Object.keys(first)
return columns.map(x => {
value = first[x]
return (
value instanceof Query ? fragment(value, parameters, types, options) :
value instanceof Identifier ? value.value :
handleValue(value, parameters, types, options)
) + ' as ' + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x)
}).join(',')
}
const builders = Object.entries({
values,
in: (...xs) => {
const x = values(...xs)
return x === '()' ? '(null)' : x
},
select: types_select,
as: types_select,
returning: types_select,
'\\(': types_select,
update(first, rest, parameters, types, options) {
return (rest.length ? rest.flat() : Object.keys(first)).map(x =>
escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) +
'=' + stringifyValue('values', first[x], parameters, types, options)
)
},
insert(first, rest, parameters, types, options) {
const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first)
return '(' + escapeIdentifiers(columns, options) + ')values' +
valuesBuilder(Array.isArray(first) ? first : [first], parameters, types, columns, options)
}
}).map(([x, fn]) => ([new RegExp('((?:^|[\\s(])' + x + '(?:$|[\\s(]))(?![\\s\\S]*\\1)', 'i'), fn]))
function notTagged() {
throw Errors.generic('NOT_TAGGED_CALL', 'Query not called as a tagged template literal')
}
const serializers = defaultHandlers.serializers
const parsers = defaultHandlers.parsers
const END = {}
function firstIsString(x) {
if (Array.isArray(x))
return firstIsString(x[0])
return typeof x === 'string' ? 1009 : 0
}
const mergeUserTypes = function(types) {
const user = typeHandlers(types || {})
return {
serializers: Object.assign({}, serializers, user.serializers),
parsers: Object.assign({}, parsers, user.parsers)
}
}
function typeHandlers(types) {
return Object.keys(types).reduce((acc, k) => {
types[k].from && [].concat(types[k].from).forEach(x => acc.parsers[x] = types[k].parse)
if (types[k].serialize) {
acc.serializers[types[k].to] = types[k].serialize
types[k].from && [].concat(types[k].from).forEach(x => acc.serializers[x] = types[k].serialize)
}
return acc
}, { parsers: {}, serializers: {} })
}
function escapeIdentifiers(xs, { transform: { column } }) {
return xs.map(x => escapeIdentifier(column.to ? column.to(x) : x)).join(',')
}
const escapeIdentifier = function escape(str) {
return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'
}
const inferType = function inferType(x) {
return (
x instanceof Parameter ? x.type :
x instanceof Date ? 1184 :
x instanceof Uint8Array ? 17 :
(x === true || x === false) ? 16 :
typeof x === 'bigint' ? 20 :
Array.isArray(x) ? inferType(x[0]) :
0
)
}
const escapeBackslash = /\\/g
const escapeQuote = /"/g
function arrayEscape(x) {
return x
.replace(escapeBackslash, '\\\\')
.replace(escapeQuote, '\\"')
}
const arraySerializer = function arraySerializer(xs, serializer, options, typarray) {
if (Array.isArray(xs) === false)
return xs
if (!xs.length)
return '{}'
const first = xs[0]
// Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter
const delimiter = typarray === 1020 ? ';' : ','
if (Array.isArray(first) && !first.type)
return '{' + xs.map(x => arraySerializer(x, serializer, options, typarray)).join(delimiter) + '}'
return '{' + xs.map(x => {
if (x === undefined) {
x = options.transform.undefined
if (x === undefined)
throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')
}
return x === null
? 'null'
: '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : '' + x) + '"'
}).join(delimiter) + '}'
}
const arrayParserState = {
i: 0,
char: null,
str: '',
quoted: false,
last: 0
}
const arrayParser = function arrayParser(x, parser, typarray) {
arrayParserState.i = arrayParserState.last = 0
return arrayParserLoop(arrayParserState, x, parser, typarray)
}
function arrayParserLoop(s, x, parser, typarray) {
const xs = []
// Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter
const delimiter = typarray === 1020 ? ';' : ','
for (; s.i < x.length; s.i++) {
s.char = x[s.i]
if (s.quoted) {
if (s.char === '\\') {
s.str += x[++s.i]
} else if (s.char === '"') {
xs.push(parser ? parser(s.str) : s.str)
s.str = ''
s.quoted = x[s.i + 1] === '"'
s.last = s.i + 2
} else {
s.str += s.char
}
} else if (s.char === '"') {
s.quoted = true
} else if (s.char === '{') {
s.last = ++s.i
xs.push(arrayParserLoop(s, x, parser, typarray))
} else if (s.char === '}') {
s.quoted = false
s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))
s.last = s.i + 1
break
} else if (s.char === delimiter && s.p !== '}' && s.p !== '"') {
xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))
s.last = s.i + 1
}
s.p = s.char
}
s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1))
return xs
}
const toCamel = x => {
let str = x[0]
for (let i = 1; i < x.length; i++)
str += x[i] === '_' ? x[++i].toUpperCase() : x[i]
return str
}
const toPascal = x => {
let str = x[0].toUpperCase()
for (let i = 1; i < x.length; i++)
str += x[i] === '_' ? x[++i].toUpperCase() : x[i]
return str
}
const toKebab = x => x.replace(/_/g, '-')
const fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase()
const fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase()
const fromKebab = x => x.replace(/-/g, '_')
function createJsonTransform(fn) {
return function jsonTransform(x, column) {
return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)
? Array.isArray(x)
? x.map(x => jsonTransform(x, column))
: Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {})
: x
}
}
toCamel.column = { from: toCamel }
toCamel.value = { from: createJsonTransform(toCamel) }
fromCamel.column = { to: fromCamel }
const camel = { ...toCamel }
camel.column.to = fromCamel
toPascal.column = { from: toPascal }
toPascal.value = { from: createJsonTransform(toPascal) }
fromPascal.column = { to: fromPascal }
const pascal = { ...toPascal }
pascal.column.to = fromPascal
toKebab.column = { from: toKebab }
toKebab.value = { from: createJsonTransform(toKebab) }
fromKebab.column = { to: fromKebab }
const kebab = { ...toKebab }
kebab.column.to = fromKebab
// EXTERNAL MODULE: external "net"
var external_net_ = __webpack_require__(9278);
// EXTERNAL MODULE: external "tls"
var external_tls_ = __webpack_require__(4756);
// EXTERNAL MODULE: external "crypto"
var external_crypto_ = __webpack_require__(6982);
// EXTERNAL MODULE: external "stream"
var external_stream_ = __webpack_require__(2203);
// EXTERNAL MODULE: external "perf_hooks"
var external_perf_hooks_ = __webpack_require__(2987);
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/result.js
class Result extends Array {
constructor() {
super()
Object.defineProperties(this, {
count: { value: null, writable: true },
state: { value: null, writable: true },
command: { value: null, writable: true },
columns: { value: null, writable: true },
statement: { value: null, writable: true }
})
}
static get [Symbol.species]() {
return Array
}
}
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/queue.js
/* harmony default export */ const src_queue = (Queue);
function Queue(initial = []) {
let xs = initial.slice()
let index = 0
return {
get length() {
return xs.length - index
},
remove: (x) => {
const index = xs.indexOf(x)
return index === -1
? null
: (xs.splice(index, 1), x)
},
push: (x) => (xs.push(x), x),
shift: () => {
const out = xs[index++]
if (index === xs.length) {
index = 0
xs = []
} else {
xs[index - 1] = undefined
}
return out
}
}
}
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/bytes.js
const size = 256
let buffer = Buffer.allocUnsafe(size)
const messages = 'BCcDdEFfHPpQSX'.split('').reduce((acc, x) => {
const v = x.charCodeAt(0)
acc[x] = () => {
buffer[0] = v
b.i = 5
return b
}
return acc
}, {})
const b = Object.assign(bytes_reset, messages, {
N: String.fromCharCode(0),
i: 0,
inc(x) {
b.i += x
return b
},
str(x) {
const length = Buffer.byteLength(x)
fit(length)
b.i += buffer.write(x, b.i, length, 'utf8')
return b
},
i16(x) {
fit(2)
buffer.writeUInt16BE(x, b.i)
b.i += 2
return b
},
i32(x, i) {
if (i || i === 0) {
buffer.writeUInt32BE(x, i)
return b
}
fit(4)
buffer.writeUInt32BE(x, b.i)
b.i += 4
return b
},
z(x) {
fit(x)
buffer.fill(0, b.i, b.i + x)
b.i += x
return b
},
raw(x) {
buffer = Buffer.concat([buffer.subarray(0, b.i), x])
b.i = buffer.length
return b
},
end(at = 1) {
buffer.writeUInt32BE(b.i - at, at)
const out = buffer.subarray(0, b.i)
b.i = 0
buffer = Buffer.allocUnsafe(size)
return out
}
})
/* harmony default export */ const bytes = (b);
function fit(x) {
if (buffer.length - b.i < x) {
const prev = buffer
, length = prev.length
buffer = Buffer.allocUnsafe(length + (length >> 1) + x)
prev.copy(buffer)
}
}
function bytes_reset() {
b.i = 0
return b
}
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/connection.js
/* harmony default export */ const src_connection = (Connection);
let uid = 1
const Sync = bytes().S().end()
, Flush = bytes().H().end()
, SSLRequest = bytes().i32(8).i32(80877103).end(8)
, ExecuteUnnamed = Buffer.concat([bytes().E().str(bytes.N).i32(0).end(), Sync])
, DescribeUnnamed = bytes().D().str('S').str(bytes.N).end()
, noop = () => { /* noop */ }
const retryRoutines = new Set([
'FetchPreparedStatement',
'RevalidateCachedQuery',
'transformAssignedExpr'
])
const errorFields = {
83 : 'severity_local', // S
86 : 'severity', // V
67 : 'code', // C
77 : 'message', // M
68 : 'detail', // D
72 : 'hint', // H
80 : 'position', // P
112 : 'internal_position', // p
113 : 'internal_query', // q
87 : 'where', // W
115 : 'schema_name', // s
116 : 'table_name', // t
99 : 'column_name', // c
100 : 'data type_name', // d
110 : 'constraint_name', // n
70 : 'file', // F
76 : 'line', // L
82 : 'routine' // R
}
function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
const {
sslnegotiation,
ssl,
max,
user,
host,
port,
database,
parsers,
transform,
onnotice,
onnotify,
onparameter,
max_pipeline,
keep_alive,
backoff,
target_session_attrs
} = options
const sent = src_queue()
, id = uid++
, backend = { pid: null, secret: null }
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
let socket = null
, cancelMessage
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
, needsTypes = options.fetch_types
, backendParameters = {}
, statements = {}
, statementId = Math.random().toString(36).slice(2)
, statementCount = 1
, closedTime = 0
, remaining = 0
, hostIndex = 0
, retries = 0
, length = 0
, delay = 0
, rows = 0
, serverSignature = null
, nextWriteTimer = null
, terminated = false
, incomings = null
, results = null
, initial = null
, ending = null
, stream = null
, chunk = null
, ended = null
, nonce = null
, query = null
, final = null
const connection = {
queue: queues.closed,
idleTimer,
connect(query) {
initial = query
reconnect()
},
terminate,
execute,
cancel,
end,
count: 0,
id
}
queues.closed && queues.closed.push(connection)
return connection
async function createSocket() {
let x
try {
x = options.socket
? (await Promise.resolve(options.socket(options)))
: new external_net_.Socket()
} catch (e) {
error(e)
return
}
x.on('error', error)
x.on('close', closed)
x.on('drain', drain)
return x
}
async function cancel({ pid, secret }, resolve, reject) {
try {
cancelMessage = bytes().i32(16).i32(80877102).i32(pid).i32(secret).end(16)
await connect()
socket.once('error', reject)
socket.once('close', resolve)
} catch (error) {
reject(error)
}
}
function execute(q) {
if (terminated)
return queryError(q, Errors.connection('CONNECTION_DESTROYED', options))
if (stream)
return queryError(q, Errors.generic('COPY_IN_PROGRESS', 'You cannot execute queries during copy'))
if (q.cancelled)
return
try {
q.state = backend
query
? sent.push(q)
: (query = q, query.active = true)
build(q)
return write(toBuffer(q))
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
&& (!q.options.onexecute || q.options.onexecute(connection))
} catch (error) {
sent.length === 0 && write(Sync)
errored(error)
return true
}
}
function toBuffer(q) {
if (q.parameters.length >= 65534)
throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')
return q.options.simple
? bytes().Q().str(q.statement.string + bytes.N).end()
: q.describeFirst
? Buffer.concat([describe(q), Flush])
: q.prepare
? q.prepared
? prepared(q)
: Buffer.concat([describe(q), prepared(q)])
: unnamed(q)
}
function describe(q) {
return Buffer.concat([
Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),
Describe('S', q.statement.name)
])
}
function prepared(q) {
return Buffer.concat([
Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),
q.cursorFn
? Execute('', q.cursorRows)
: ExecuteUnnamed
])
}
function unnamed(q) {
return Buffer.concat([
Parse(q.statement.string, q.parameters, q.statement.types),
DescribeUnnamed,
prepared(q)
])
}
function build(q) {
const parameters = []
, types = []
const string = stringify(q, q.strings[0], q.args[0], parameters, types, options)
!q.tagged && q.args.forEach(x => handleValue(x, parameters, types, options))
q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)
q.string = string
q.signature = q.prepare && types + string
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)
q.statement = q.prepared
? statements[q.signature]
: { string, types, name: q.prepare ? statementId + statementCount++ : '' }
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
function write(x, fn) {
chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x)
if (fn || chunk.length >= 1024)
return nextWrite(fn)
nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite))
return true
}
function nextWrite(fn) {
const x = socket.write(chunk, fn)
nextWriteTimer !== null && clearImmediate(nextWriteTimer)
chunk = nextWriteTimer = null
return x
}
function connectTimedOut() {
errored(Errors.connection('CONNECT_TIMEOUT', options, socket))
socket.destroy()
}
async function secure() {
if (sslnegotiation !== 'direct') {
write(SSLRequest)
const canSSL = await new Promise(r => socket.once('data', x => r(x[0] === 83))) // S
if (!canSSL && ssl === 'prefer')
return connected()
}
const options = {
socket,
servername: external_net_.isIP(socket.host) ? undefined : socket.host
}
if (sslnegotiation === 'direct')
options.ALPNProtocols = ['postgresql']
if (ssl === 'require' || ssl === 'allow' || ssl === 'prefer')
options.rejectUnauthorized = false
else if (typeof ssl === 'object')
Object.assign(options, ssl)
socket.removeAllListeners()
socket = external_tls_.connect(options)
socket.on('secureConnect', connected)
socket.on('error', error)
socket.on('close', closed)
socket.on('drain', drain)
}
/* c8 ignore next 3 */
function drain() {
!query && onopen(connection)
}
function data(x) {
if (incomings) {
incomings.push(x)
remaining -= x.length
if (remaining > 0)
return
}
incoming = incomings
? Buffer.concat(incomings, length - remaining)
: incoming.length === 0
? x
: Buffer.concat([incoming, x], incoming.length + x.length)
while (incoming.length > 4) {
length = incoming.readUInt32BE(1)
if (length >= incoming.length) {
remaining = length - incoming.length
incomings = [incoming]
break
}
try {
handle(incoming.subarray(0, length + 1))
} catch (e) {
query && (query.cursorFn || query.describeFirst) && write(Sync)
errored(e)
}
incoming = incoming.subarray(length + 1)
remaining = 0
incomings = null
}
}
async function connect() {
terminated = false
backendParameters = {}
socket || (socket = await createSocket())
if (!socket)
return
connectTimer.start()
if (options.socket)
return ssl ? secure() : connected()
socket.on('connect', ssl ? secure : connected)
if (options.path)
return socket.connect(options.path)
socket.ssl = ssl
socket.connect(port[hostIndex], host[hostIndex])
socket.host = host[hostIndex]
socket.port = port[hostIndex]
hostIndex = (hostIndex + 1) % port.length
}
function reconnect() {
setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - external_perf_hooks_.performance.now()) : 0)
}
function connected() {
try {
statements = {}
needsTypes = options.fetch_types
statementId = Math.random().toString(36).slice(2)
statementCount = 1
lifeTimer.start()
socket.on('data', data)
keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * keep_alive)
const s = StartupMessage()
write(s)
} catch (err) {
error(err)
}
}
function error(err) {
if (connection.queue === queues.connecting && options.host[retries + 1])
return
errored(err)
while (sent.length)
queryError(sent.shift(), err)
}
function errored(err) {
stream && (stream.destroy(err), stream = null)
query && queryError(query, err)
initial && (queryError(initial, err), initial = null)
}
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
if (!err || typeof err !== 'object')
err = new Error(err)
'query' in err || 'parameters' in err || Object.defineProperties(err, {
stack: { value: err.stack + query.origin.replace(/.*\n/, '\n'), enumerable: options.debug },
query: { value: query.string, enumerable: options.debug },
parameters: { value: query.parameters, enumerable: options.debug },
args: { value: query.args, enumerable: options.debug },
types: { value: query.statement && query.statement.types, enumerable: options.debug }
})
query.reject(err)
}
function end() {
return ending || (
!connection.reserved && onend(connection),
!connection.reserved && !initial && !query && sent.length === 0
? (terminate(), new Promise(r => socket && socket.readyState !== 'closed' ? socket.once('close', r) : r()))
: ending = new Promise(r => ended = r)
)
}
function terminate() {
terminated = true
if (stream || query || initial || sent.length)
error(Errors.connection('CONNECTION_DESTROYED', options))
clearImmediate(nextWriteTimer)
if (socket) {
socket.removeListener('data', data)
socket.removeListener('connect', connected)
socket.readyState === 'open' && socket.end(bytes().X().end())
}
ended && (ended(), ending = ended = null)
}
async function closed(hadError) {
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
clearImmediate(nextWriteTimer)
socket.removeListener('data', data)
socket.removeListener('connect', connected)
idleTimer.cancel()
lifeTimer.cancel()
connectTimer.cancel()
socket.removeAllListeners()
socket = null
if (initial)
return reconnect()
!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
closedTime = external_perf_hooks_.performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
onclose(connection, Errors.connection('CONNECTION_CLOSED', options, socket))
}
/* Handlers */
function handle(xs, x = xs[0]) {
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
x === 65 ? NotificationResponse : // A
x === 83 ? ParameterStatus : // S
x === 90 ? ReadyForQuery : // Z
x === 67 ? CommandComplete : // C
x === 50 ? BindComplete : // 2
x === 49 ? ParseComplete : // 1
x === 116 ? ParameterDescription : // t
x === 84 ? RowDescription : // T
x === 82 ? Authentication : // R
x === 110 ? NoData : // n
x === 75 ? BackendKeyData : // K
x === 69 ? ErrorResponse : // E
x === 115 ? PortalSuspended : // s
x === 51 ? CloseComplete : // 3
x === 71 ? CopyInResponse : // G
x === 78 ? NoticeResponse : // N
x === 72 ? CopyOutResponse : // H
x === 99 ? CopyDone : // c
x === 73 ? EmptyQueryResponse : // I
x === 86 ? FunctionCallResponse : // V
x === 118 ? NegotiateProtocolVersion : // v
x === 87 ? CopyBothResponse : // W
/* c8 ignore next */
UnknownMessage
)(xs)
}
function DataRow(x) {
let index = 7
let length
let column
let value
const row = query.isRaw ? new Array(query.statement.columns.length) : {}
for (let i = 0; i < query.statement.columns.length; i++) {
column = query.statement.columns[i]
length = x.readInt32BE(index)
index += 4
value = length === -1
? null
: query.isRaw === true
? x.subarray(index, index += length)
: column.parser === undefined
? x.toString('utf8', index, index += length)
: column.parser.array === true
? column.parser(x.toString('utf8', index + 1, index += length))
: column.parser(x.toString('utf8', index, index += length))
query.isRaw
? (row[i] = query.isRaw === true
? value
: transform.value.from ? transform.value.from(value, column) : value)
: (row[column.name] = transform.value.from ? transform.value.from(value, column) : value)
}
query.forEachFn
? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result)
: (result[rows++] = transform.row.from ? transform.row.from(row) : row)
}
function ParameterStatus(x) {
const [k, v] = x.toString('utf8', 5, x.length - 1).split(bytes.N)
backendParameters[k] = v
if (options.parameters[k] !== v) {
options.parameters[k] = v
onparameter && onparameter(k, v)
}
}
function ReadyForQuery(x) {
if (query) {
if (errorResponse) {
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine)
? retry(query, errorResponse)
: errored(errorResponse)
} else {
query.resolve(results || result)
}
} else if (errorResponse) {
errored(errorResponse)
}
query = results = errorResponse = null
result = new Result()
connectTimer.cancel()
if (initial) {
if (target_session_attrs) {
if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)
return fetchState()
else if (tryNext(target_session_attrs, backendParameters))
return terminate()
}
if (needsTypes) {
initial.reserve && (initial = null)
return fetchArrayTypes()
}
initial && !initial.reserve && execute(initial)
options.shared.retries = retries = 0
initial = null
return
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
if (query)
return // Consider opening if able and sent.length < 50
connection.reserved
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
: (connection.reserved = null, onopen(connection))
: connection.reserved()
: ending
? terminate()
: onopen(connection)
}
function CommandComplete(x) {
rows = 0
for (let i = x.length - 1; i > 0; i--) {
if (x[i] === 32 && x[i + 1] < 58 && result.count === null)
result.count = +x.toString('utf8', i + 1, x.length - 1)
if (x[i - 1] >= 65) {
result.command = x.toString('utf8', 5, i)
result.state = backend
break
}
}
final && (final(), final = null)
if (result.command === 'BEGIN' && max !== 1 && !connection.reserved)
return errored(Errors.generic('UNSAFE_TRANSACTION', 'Only use sql.begin, sql.reserved or max: 1'))
if (query.options.simple)
return BindComplete()
if (query.cursorFn) {
result.count && query.cursorFn(result)
write(Sync)
}
}
function ParseComplete() {
query.parsing = false
}
function BindComplete() {
!result.statement && (result.statement = query.statement)
result.columns = query.statement.columns
}
function ParameterDescription(x) {
const length = x.readUInt16BE(5)
for (let i = 0; i < length; ++i)
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
}
function RowDescription(x) {
if (result.command) {
results = results || [result]
results.push(result = new Result())
result.count = null
query.statement.columns = null
}
const length = x.readUInt16BE(5)
let index = 7
let start
query.statement.columns = Array(length)
for (let i = 0; i < length; ++i) {
start = index
while (x[index++] !== 0);
const table = x.readUInt32BE(index)
const number = x.readUInt16BE(index + 4)
const type = x.readUInt32BE(index + 6)
query.statement.columns[i] = {
name: transform.column.from
? transform.column.from(x.toString('utf8', start, index - 1))
: x.toString('utf8', start, index - 1),
parser: parsers[type],
table,
number,
type
}
index += 18
}
result.statement = query.statement
if (query.onlyDescribe)
return (query.resolve(query.statement), write(Sync))
}
async function Authentication(x, type = x.readUInt32BE(5)) {
(
type === 3 ? AuthenticationCleartextPassword :
type === 5 ? AuthenticationMD5Password :
type === 10 ? SASL :
type === 11 ? SASLContinue :
type === 12 ? SASLFinal :
type !== 0 ? UnknownAuth :
noop
)(x, type)
}
/* c8 ignore next 5 */
async function AuthenticationCleartextPassword() {
const payload = await Pass()
write(
bytes().p().str(payload).z(1).end()
)
}
async function AuthenticationMD5Password(x) {
const payload = 'md5' + (
await md5(
Buffer.concat([
Buffer.from(await md5((await Pass()) + user)),
x.subarray(9)
])
)
)
write(
bytes().p().str(payload).z(1).end()
)
}
async function SASL() {
nonce = (await external_crypto_.randomBytes(18)).toString('base64')
bytes().p().str('SCRAM-SHA-256' + bytes.N)
const i = bytes.i
write(bytes.inc(4).str('n,,n=*,r=' + nonce).i32(bytes.i - i - 4, i).end())
}
async function SASLContinue(x) {
const res = x.toString('utf8', 9).split(',').reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {})
const saltedPassword = await external_crypto_.pbkdf2Sync(
await Pass(),
Buffer.from(res.s, 'base64'),
parseInt(res.i), 32,
'sha256'
)
const clientKey = await hmac(saltedPassword, 'Client Key')
const auth = 'n=*,r=' + nonce + ','
+ 'r=' + res.r + ',s=' + res.s + ',i=' + res.i
+ ',c=biws,r=' + res.r
serverSignature = (await hmac(await hmac(saltedPassword, 'Server Key'), auth)).toString('base64')
const payload = 'c=biws,r=' + res.r + ',p=' + xor(
clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))
).toString('base64')
write(
bytes().p().str(payload).end()
)
}
function SASLFinal(x) {
if (x.toString('utf8', 9).split(bytes.N, 1)[0].slice(2) === serverSignature)
return
/* c8 ignore next 5 */
errored(Errors.generic('SASL_SIGNATURE_MISMATCH', 'The server did not return the correct signature'))
socket.destroy()
}
function Pass() {
return Promise.resolve(typeof options.pass === 'function'
? options.pass()
: options.pass
)
}
function NoData() {
result.statement = query.statement
result.statement.columns = []
if (query.onlyDescribe)
return (query.resolve(query.statement), write(Sync))
}
function BackendKeyData(x) {
backend.pid = x.readUInt32BE(5)
backend.secret = x.readUInt32BE(9)
}
async function fetchArrayTypes() {
needsTypes = false
const types = await new Query([`
select b.oid, b.typarray
from pg_catalog.pg_type a
left join pg_catalog.pg_type b on b.oid = a.typelem
where a.typcategory = 'A'
group by b.oid, b.typarray
order by b.oid
`], [], execute)
types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))
}
function addArrayType(oid, typarray) {
if (!!options.parsers[typarray] && !!options.serializers[typarray]) return
const parser = options.parsers[oid]
options.shared.typeArrayMap[oid] = typarray
options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray)
options.parsers[typarray].array = true
options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray)
}
function tryNext(x, xs) {
return (
(x === 'read-write' && xs.default_transaction_read_only === 'on') ||
(x === 'read-only' && xs.default_transaction_read_only === 'off') ||
(x === 'primary' && xs.in_hot_standby === 'on') ||
(x === 'standby' && xs.in_hot_standby === 'off') ||
(x === 'prefer-standby' && xs.in_hot_standby === 'off' && options.host[retries])
)
}
function fetchState() {
const query = new Query([`
show transaction_read_only;
select pg_catalog.pg_is_in_recovery()
`], [], execute, null, { simple: true })
query.resolve = ([[a], [b]]) => {
backendParameters.default_transaction_read_only = a.transaction_read_only
backendParameters.in_hot_standby = b.pg_is_in_recovery ? 'on' : 'off'
}
query.execute()
}
function ErrorResponse(x) {
if (query) {
(query.cursorFn || query.describeFirst) && write(Sync)
errorResponse = Errors.postgres(parseError(x))
} else {
errored(Errors.postgres(parseError(x)))
}
}
function retry(q, error) {
delete statements[q.signature]
q.retried = error
execute(q)
}
function NotificationResponse(x) {
if (!onnotify)
return
let index = 9
while (x[index++] !== 0);
onnotify(
x.toString('utf8', 9, index - 1),
x.toString('utf8', index, x.length - 1)
)
}
async function PortalSuspended() {
try {
const x = await Promise.resolve(query.cursorFn(result))
rows = 0
x === CLOSE
? write(Close(query.portal))
: (result = new Result(), write(Execute('', query.cursorRows)))
} catch (err) {
write(Sync)
query.reject(err)
}
}
function CloseComplete() {
result.count && query.cursorFn(result)
query.resolve(result)
}
function CopyInResponse() {
stream = new external_stream_.Writable({
autoDestroy: true,
write(chunk, encoding, callback) {
socket.write(bytes().d().raw(chunk).end(), callback)
},
destroy(error, callback) {
callback(error)
socket.write(bytes().f().str(error + bytes.N).end())
stream = null
},
final(callback) {
socket.write(bytes().c().end())
final = callback
stream = null
}
})
query.resolve(stream)
}
function CopyOutResponse() {
stream = new external_stream_.Readable({
read() { socket.resume() }
})
query.resolve(stream)
}
/* c8 ignore next 3 */
function CopyBothResponse() {
stream = new external_stream_.Duplex({
autoDestroy: true,
read() { socket.resume() },
/* c8 ignore next 11 */
write(chunk, encoding, callback) {
socket.write(bytes().d().raw(chunk).end(), callback)
},
destroy(error, callback) {
callback(error)
socket.write(bytes().f().str(error + bytes.N).end())
stream = null
},
final(callback) {
socket.write(bytes().c().end())
final = callback
}
})
query.resolve(stream)
}
function CopyData(x) {
stream && (stream.push(x.subarray(5)) || socket.pause())
}
function CopyDone() {
stream && stream.push(null)
stream = null
}
function NoticeResponse(x) {
onnotice
? onnotice(parseError(x))
: console.log(parseError(x)) // eslint-disable-line
}
/* c8 ignore next 3 */
function EmptyQueryResponse() {
/* noop */
}
/* c8 ignore next 3 */
function FunctionCallResponse() {
errored(Errors.notSupported('FunctionCallResponse'))
}
/* c8 ignore next 3 */
function NegotiateProtocolVersion() {
errored(Errors.notSupported('NegotiateProtocolVersion'))
}
/* c8 ignore next 3 */
function UnknownMessage(x) {
console.error('Postgres.js : Unknown Message:', x[0]) // eslint-disable-line
}
/* c8 ignore next 3 */
function UnknownAuth(x, type) {
console.error('Postgres.js : Unknown Auth:', type) // eslint-disable-line
}
/* Messages */
function Bind(parameters, types, statement = '', portal = '') {
let prev
, type
bytes().B().str(portal + bytes.N).str(statement + bytes.N).i16(0).i16(parameters.length)
parameters.forEach((x, i) => {
if (x === null)
return bytes.i32(0xFFFFFFFF)
type = types[i]
parameters[i] = x = type in options.serializers
? options.serializers[type](x)
: '' + x
prev = bytes.i
bytes.inc(4).str(x).i32(bytes.i - prev - 4, prev)
})
bytes.i16(0)
return bytes.end()
}
function Parse(str, parameters, types, name = '') {
bytes().P().str(name + bytes.N).str(str + bytes.N).i16(parameters.length)
parameters.forEach((x, i) => bytes.i32(types[i] || 0))
return bytes.end()
}
function Describe(x, name = '') {
return bytes().D().str(x).str(name + bytes.N).end()
}
function Execute(portal = '', rows = 0) {
return Buffer.concat([
bytes().E().str(portal + bytes.N).i32(rows).end(),
Flush
])
}
function Close(portal = '') {
return Buffer.concat([
bytes().C().str('P').str(portal + bytes.N).end(),
bytes().S().end()
])
}
function StartupMessage() {
return cancelMessage || bytes().inc(4).i16(3).z(2).str(
Object.entries(Object.assign({
user,
database,
client_encoding: 'UTF8'
},
options.connection
)).filter(([, v]) => v).map(([k, v]) => k + bytes.N + v).join(bytes.N)
).z(2).end(0)
}
}
function parseError(x) {
const error = {}
let start = 5
for (let i = 5; i < x.length - 1; i++) {
if (x[i] === 0) {
error[errorFields[x[start]]] = x.toString('utf8', start + 1, i)
start = i + 1
}
}
return error
}
function md5(x) {
return external_crypto_.createHash('md5').update(x).digest('hex')
}
function hmac(key, x) {
return external_crypto_.createHmac('sha256', key).update(x).digest()
}
function sha256(x) {
return external_crypto_.createHash('sha256').update(x).digest()
}
function xor(a, b) {
const length = Math.max(a.length, b.length)
const buffer = Buffer.allocUnsafe(length)
for (let i = 0; i < length; i++)
buffer[i] = a[i] ^ b[i]
return buffer
}
function timer(fn, seconds) {
seconds = typeof seconds === 'function' ? seconds() : seconds
if (!seconds)
return { cancel: noop, start: noop }
let timer
return {
cancel() {
timer && (clearTimeout(timer), timer = null)
},
start() {
timer && clearTimeout(timer)
timer = setTimeout(done, seconds * 1000, arguments)
}
}
function done(args) {
fn.apply(null, args)
timer = null
}
}
;// CONCATENATED MODULE: ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/subscribe.js
const subscribe_noop = () => { /* noop */ }
function Subscribe(postgres, options) {
const subscribers = new Map()
, slot = 'postgresjs_' + Math.random().toString(36).slice(2)
, state = {}
let connection
, stream
, ended = false
const sql = subscribe.sql = postgres({
...options,
transform: { column: {}, value: {}, row: {} },
max: 1,
fetch_types: false,
idle_timeout: null,
max_lifetime: null,
connection: {
...options.connection,
replication: 'database'
},
onclose: async function() {
if (ended)
return
stream = null
state.pid = state.secret = undefined
connected(await init(sql, slot, options.publications))
subscribers.forEach(event => event.forEach(({ onsubscribe }) => onsubscribe()))
},
no_subscribe: true
})
const end = sql.end
, close = sql.close
sql.end = async() => {
ended = true
stream && (await new Promise(r => (stream.once('close', r), stream.end())))
return end()
}
sql.close = async() => {
stream && (await new Promise(r => (stream.once('close', r), stream.end())))
return close()
}
return subscribe
async function subscribe(event, fn, onsubscribe = subscribe_noop, onerror = subscribe_noop) {
event = parseEvent(event)
if (!connection)
connection = init(sql, slot, options.publications)
const subscriber = { fn, onsubscribe }
const f