13927 lines
545 KiB
JavaScript
13927 lines
545 KiB
JavaScript
module.exports = [
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/@panva/hkdf/dist/node/esm/runtime/fallback.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"default",
|
|
()=>__TURBOPACK__default__export__
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__ = __turbopack_context__.i("[externals]/crypto [external] (crypto, cjs)");
|
|
;
|
|
const __TURBOPACK__default__export__ = (digest, ikm, salt, info, keylen)=>{
|
|
const hashlen = parseInt(digest.substr(3), 10) >> 3 || 20;
|
|
const prk = (0, __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__["createHmac"])(digest, salt.byteLength ? salt : new Uint8Array(hashlen)).update(ikm).digest();
|
|
const N = Math.ceil(keylen / hashlen);
|
|
const T = new Uint8Array(hashlen * N + info.byteLength + 1);
|
|
let prev = 0;
|
|
let start = 0;
|
|
for(let c = 1; c <= N; c++){
|
|
T.set(info, start);
|
|
T[start + info.byteLength] = c;
|
|
T.set((0, __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__["createHmac"])(digest, prk).update(T.subarray(prev, start + info.byteLength + 1)).digest(), start);
|
|
prev = start;
|
|
start += hashlen;
|
|
}
|
|
return T.slice(0, keylen);
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/@panva/hkdf/dist/node/esm/runtime/hkdf.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"default",
|
|
()=>__TURBOPACK__default__export__
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__ = __turbopack_context__.i("[externals]/crypto [external] (crypto, cjs)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$panva$2f$hkdf$2f$dist$2f$node$2f$esm$2f$runtime$2f$fallback$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@panva/hkdf/dist/node/esm/runtime/fallback.js [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
let hkdf;
|
|
if (typeof __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__["hkdf"] === 'function' && !process.versions.electron) {
|
|
hkdf = async (...args)=>new Promise((resolve, reject)=>{
|
|
__TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__["hkdf"](...args, (err, arrayBuffer)=>{
|
|
if (err) reject(err);
|
|
else resolve(new Uint8Array(arrayBuffer));
|
|
});
|
|
});
|
|
}
|
|
const __TURBOPACK__default__export__ = async (digest, ikm, salt, info, keylen)=>(hkdf || __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$panva$2f$hkdf$2f$dist$2f$node$2f$esm$2f$runtime$2f$fallback$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["default"])(digest, ikm, salt, info, keylen);
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/@panva/hkdf/dist/node/esm/index.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"default",
|
|
()=>hkdf,
|
|
"hkdf",
|
|
()=>hkdf
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$panva$2f$hkdf$2f$dist$2f$node$2f$esm$2f$runtime$2f$hkdf$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@panva/hkdf/dist/node/esm/runtime/hkdf.js [app-route] (ecmascript)");
|
|
;
|
|
function normalizeDigest(digest) {
|
|
switch(digest){
|
|
case 'sha256':
|
|
case 'sha384':
|
|
case 'sha512':
|
|
case 'sha1':
|
|
return digest;
|
|
default:
|
|
throw new TypeError('unsupported "digest" value');
|
|
}
|
|
}
|
|
function normalizeUint8Array(input, label) {
|
|
if (typeof input === 'string') return new TextEncoder().encode(input);
|
|
if (!(input instanceof Uint8Array)) throw new TypeError(`"${label}"" must be an instance of Uint8Array or a string`);
|
|
return input;
|
|
}
|
|
function normalizeIkm(input) {
|
|
const ikm = normalizeUint8Array(input, 'ikm');
|
|
if (!ikm.byteLength) throw new TypeError(`"ikm" must be at least one byte in length`);
|
|
return ikm;
|
|
}
|
|
function normalizeInfo(input) {
|
|
const info = normalizeUint8Array(input, 'info');
|
|
if (info.byteLength > 1024) {
|
|
throw TypeError('"info" must not contain more than 1024 bytes');
|
|
}
|
|
return info;
|
|
}
|
|
function normalizeKeylen(input, digest) {
|
|
if (typeof input !== 'number' || !Number.isInteger(input) || input < 1) {
|
|
throw new TypeError('"keylen" must be a positive integer');
|
|
}
|
|
const hashlen = parseInt(digest.substr(3), 10) >> 3 || 20;
|
|
if (input > 255 * hashlen) {
|
|
throw new TypeError('"keylen" too large');
|
|
}
|
|
return input;
|
|
}
|
|
async function hkdf(digest, ikm, salt, info, keylen) {
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$panva$2f$hkdf$2f$dist$2f$node$2f$esm$2f$runtime$2f$hkdf$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["default"])(normalizeDigest(digest), normalizeIkm(ikm), normalizeUint8Array(salt, 'salt'), normalizeInfo(info), normalizeKeylen(keylen, digest));
|
|
}
|
|
;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/preact/dist/preact.mjs [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"Component",
|
|
()=>k,
|
|
"Fragment",
|
|
()=>b,
|
|
"cloneElement",
|
|
()=>E,
|
|
"createContext",
|
|
()=>G,
|
|
"createElement",
|
|
()=>_,
|
|
"createRef",
|
|
()=>m,
|
|
"h",
|
|
()=>_,
|
|
"hydrate",
|
|
()=>D,
|
|
"isValidElement",
|
|
()=>t,
|
|
"options",
|
|
()=>l,
|
|
"render",
|
|
()=>B,
|
|
"toChildArray",
|
|
()=>H
|
|
]);
|
|
var n, l, u, t, i, o, r, f, e, c, s, a, h = {}, v = [], p = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, y = Array.isArray;
|
|
function d(n, l) {
|
|
for(var u in l)n[u] = l[u];
|
|
return n;
|
|
}
|
|
function w(n) {
|
|
n && n.parentNode && n.parentNode.removeChild(n);
|
|
}
|
|
function _(l, u, t) {
|
|
var i, o, r, f = {};
|
|
for(r in u)"key" == r ? i = u[r] : "ref" == r ? o = u[r] : f[r] = u[r];
|
|
if (arguments.length > 2 && (f.children = arguments.length > 3 ? n.call(arguments, 2) : t), "function" == typeof l && null != l.defaultProps) for(r in l.defaultProps)void 0 === f[r] && (f[r] = l.defaultProps[r]);
|
|
return g(l, f, i, o, null);
|
|
}
|
|
function g(n, t, i, o, r) {
|
|
var f = {
|
|
type: n,
|
|
props: t,
|
|
key: i,
|
|
ref: o,
|
|
__k: null,
|
|
__: null,
|
|
__b: 0,
|
|
__e: null,
|
|
__d: void 0,
|
|
__c: null,
|
|
constructor: void 0,
|
|
__v: null == r ? ++u : r,
|
|
__i: -1,
|
|
__u: 0
|
|
};
|
|
return null == r && null != l.vnode && l.vnode(f), f;
|
|
}
|
|
function m() {
|
|
return {
|
|
current: null
|
|
};
|
|
}
|
|
function b(n) {
|
|
return n.children;
|
|
}
|
|
function k(n, l) {
|
|
this.props = n, this.context = l;
|
|
}
|
|
function x(n, l) {
|
|
if (null == l) return n.__ ? x(n.__, n.__i + 1) : null;
|
|
for(var u; l < n.__k.length; l++)if (null != (u = n.__k[l]) && null != u.__e) return u.__e;
|
|
return "function" == typeof n.type ? x(n) : null;
|
|
}
|
|
function C(n) {
|
|
var l, u;
|
|
if (null != (n = n.__) && null != n.__c) {
|
|
for(n.__e = n.__c.base = null, l = 0; l < n.__k.length; l++)if (null != (u = n.__k[l]) && null != u.__e) {
|
|
n.__e = n.__c.base = u.__e;
|
|
break;
|
|
}
|
|
return C(n);
|
|
}
|
|
}
|
|
function S(n) {
|
|
(!n.__d && (n.__d = !0) && i.push(n) && !M.__r++ || o !== l.debounceRendering) && ((o = l.debounceRendering) || r)(M);
|
|
}
|
|
function M() {
|
|
var n, u, t, o, r, e, c, s;
|
|
for(i.sort(f); n = i.shift();)n.__d && (u = i.length, o = void 0, e = (r = (t = n).__v).__e, c = [], s = [], t.__P && ((o = d({}, r)).__v = r.__v + 1, l.vnode && l.vnode(o), O(t.__P, o, r, t.__n, t.__P.namespaceURI, 32 & r.__u ? [
|
|
e
|
|
] : null, c, null == e ? x(r) : e, !!(32 & r.__u), s), o.__v = r.__v, o.__.__k[o.__i] = o, j(c, o, s), o.__e != e && C(o)), i.length > u && i.sort(f));
|
|
M.__r = 0;
|
|
}
|
|
function P(n, l, u, t, i, o, r, f, e, c, s) {
|
|
var a, p, y, d, w, _ = t && t.__k || v, g = l.length;
|
|
for(u.__d = e, $(u, l, _), e = u.__d, a = 0; a < g; a++)null != (y = u.__k[a]) && (p = -1 === y.__i ? h : _[y.__i] || h, y.__i = a, O(n, y, p, i, o, r, f, e, c, s), d = y.__e, y.ref && p.ref != y.ref && (p.ref && N(p.ref, null, y), s.push(y.ref, y.__c || d, y)), null == w && null != d && (w = d), 65536 & y.__u || p.__k === y.__k ? e = I(y, e, n) : "function" == typeof y.type && void 0 !== y.__d ? e = y.__d : d && (e = d.nextSibling), y.__d = void 0, y.__u &= -196609);
|
|
u.__d = e, u.__e = w;
|
|
}
|
|
function $(n, l, u) {
|
|
var t, i, o, r, f, e = l.length, c = u.length, s = c, a = 0;
|
|
for(n.__k = [], t = 0; t < e; t++)null != (i = l[t]) && "boolean" != typeof i && "function" != typeof i ? (r = t + a, (i = n.__k[t] = "string" == typeof i || "number" == typeof i || "bigint" == typeof i || i.constructor == String ? g(null, i, null, null, null) : y(i) ? g(b, {
|
|
children: i
|
|
}, null, null, null) : void 0 === i.constructor && i.__b > 0 ? g(i.type, i.props, i.key, i.ref ? i.ref : null, i.__v) : i).__ = n, i.__b = n.__b + 1, o = null, -1 !== (f = i.__i = L(i, u, r, s)) && (s--, (o = u[f]) && (o.__u |= 131072)), null == o || null === o.__v ? (-1 == f && a--, "function" != typeof i.type && (i.__u |= 65536)) : f !== r && (f == r - 1 ? a-- : f == r + 1 ? a++ : (f > r ? a-- : a++, i.__u |= 65536))) : i = n.__k[t] = null;
|
|
if (s) for(t = 0; t < c; t++)null != (o = u[t]) && 0 == (131072 & o.__u) && (o.__e == n.__d && (n.__d = x(o)), V(o, o));
|
|
}
|
|
function I(n, l, u) {
|
|
var t, i;
|
|
if ("function" == typeof n.type) {
|
|
for(t = n.__k, i = 0; t && i < t.length; i++)t[i] && (t[i].__ = n, l = I(t[i], l, u));
|
|
return l;
|
|
}
|
|
n.__e != l && (l && n.type && !u.contains(l) && (l = x(n)), u.insertBefore(n.__e, l || null), l = n.__e);
|
|
do {
|
|
l = l && l.nextSibling;
|
|
}while (null != l && 8 === l.nodeType)
|
|
return l;
|
|
}
|
|
function H(n, l) {
|
|
return l = l || [], null == n || "boolean" == typeof n || (y(n) ? n.some(function(n) {
|
|
H(n, l);
|
|
}) : l.push(n)), l;
|
|
}
|
|
function L(n, l, u, t) {
|
|
var i = n.key, o = n.type, r = u - 1, f = u + 1, e = l[u];
|
|
if (null === e || e && i == e.key && o === e.type && 0 == (131072 & e.__u)) return u;
|
|
if (t > (null != e && 0 == (131072 & e.__u) ? 1 : 0)) for(; r >= 0 || f < l.length;){
|
|
if (r >= 0) {
|
|
if ((e = l[r]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return r;
|
|
r--;
|
|
}
|
|
if (f < l.length) {
|
|
if ((e = l[f]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return f;
|
|
f++;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
function T(n, l, u) {
|
|
"-" === l[0] ? n.setProperty(l, null == u ? "" : u) : n[l] = null == u ? "" : "number" != typeof u || p.test(l) ? u : u + "px";
|
|
}
|
|
function A(n, l, u, t, i) {
|
|
var o;
|
|
n: if ("style" === l) if ("string" == typeof u) n.style.cssText = u;
|
|
else {
|
|
if ("string" == typeof t && (n.style.cssText = t = ""), t) for(l in t)u && l in u || T(n.style, l, "");
|
|
if (u) for(l in u)t && u[l] === t[l] || T(n.style, l, u[l]);
|
|
}
|
|
else if ("o" === l[0] && "n" === l[1]) o = l !== (l = l.replace(/(PointerCapture)$|Capture$/i, "$1")), l = l.toLowerCase() in n || "onFocusOut" === l || "onFocusIn" === l ? l.toLowerCase().slice(2) : l.slice(2), n.l || (n.l = {}), n.l[l + o] = u, u ? t ? u.u = t.u : (u.u = e, n.addEventListener(l, o ? s : c, o)) : n.removeEventListener(l, o ? s : c, o);
|
|
else {
|
|
if ("http://www.w3.org/2000/svg" == i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
|
|
else if ("width" != l && "height" != l && "href" != l && "list" != l && "form" != l && "tabIndex" != l && "download" != l && "rowSpan" != l && "colSpan" != l && "role" != l && "popover" != l && l in n) try {
|
|
n[l] = null == u ? "" : u;
|
|
break n;
|
|
} catch (n) {}
|
|
"function" == typeof u || (null == u || !1 === u && "-" !== l[4] ? n.removeAttribute(l) : n.setAttribute(l, "popover" == l && 1 == u ? "" : u));
|
|
}
|
|
}
|
|
function F(n) {
|
|
return function(u) {
|
|
if (this.l) {
|
|
var t = this.l[u.type + n];
|
|
if (null == u.t) u.t = e++;
|
|
else if (u.t < t.u) return;
|
|
return t(l.event ? l.event(u) : u);
|
|
}
|
|
};
|
|
}
|
|
function O(n, u, t, i, o, r, f, e, c, s) {
|
|
var a, h, v, p, w, _, g, m, x, C, S, M, $, I, H, L, T = u.type;
|
|
if (void 0 !== u.constructor) return null;
|
|
128 & t.__u && (c = !!(32 & t.__u), r = [
|
|
e = u.__e = t.__e
|
|
]), (a = l.__b) && a(u);
|
|
n: if ("function" == typeof T) try {
|
|
if (m = u.props, x = "prototype" in T && T.prototype.render, C = (a = T.contextType) && i[a.__c], S = a ? C ? C.props.value : a.__ : i, t.__c ? g = (h = u.__c = t.__c).__ = h.__E : (x ? u.__c = h = new T(m, S) : (u.__c = h = new k(m, S), h.constructor = T, h.render = q), C && C.sub(h), h.props = m, h.state || (h.state = {}), h.context = S, h.__n = i, v = h.__d = !0, h.__h = [], h._sb = []), x && null == h.__s && (h.__s = h.state), x && null != T.getDerivedStateFromProps && (h.__s == h.state && (h.__s = d({}, h.__s)), d(h.__s, T.getDerivedStateFromProps(m, h.__s))), p = h.props, w = h.state, h.__v = u, v) x && null == T.getDerivedStateFromProps && null != h.componentWillMount && h.componentWillMount(), x && null != h.componentDidMount && h.__h.push(h.componentDidMount);
|
|
else {
|
|
if (x && null == T.getDerivedStateFromProps && m !== p && null != h.componentWillReceiveProps && h.componentWillReceiveProps(m, S), !h.__e && (null != h.shouldComponentUpdate && !1 === h.shouldComponentUpdate(m, h.__s, S) || u.__v === t.__v)) {
|
|
for(u.__v !== t.__v && (h.props = m, h.state = h.__s, h.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.some(function(n) {
|
|
n && (n.__ = u);
|
|
}), M = 0; M < h._sb.length; M++)h.__h.push(h._sb[M]);
|
|
h._sb = [], h.__h.length && f.push(h);
|
|
break n;
|
|
}
|
|
null != h.componentWillUpdate && h.componentWillUpdate(m, h.__s, S), x && null != h.componentDidUpdate && h.__h.push(function() {
|
|
h.componentDidUpdate(p, w, _);
|
|
});
|
|
}
|
|
if (h.context = S, h.props = m, h.__P = n, h.__e = !1, $ = l.__r, I = 0, x) {
|
|
for(h.state = h.__s, h.__d = !1, $ && $(u), a = h.render(h.props, h.state, h.context), H = 0; H < h._sb.length; H++)h.__h.push(h._sb[H]);
|
|
h._sb = [];
|
|
} else do {
|
|
h.__d = !1, $ && $(u), a = h.render(h.props, h.state, h.context), h.state = h.__s;
|
|
}while (h.__d && ++I < 25)
|
|
h.state = h.__s, null != h.getChildContext && (i = d(d({}, i), h.getChildContext())), x && !v && null != h.getSnapshotBeforeUpdate && (_ = h.getSnapshotBeforeUpdate(p, w)), P(n, y(L = null != a && a.type === b && null == a.key ? a.props.children : a) ? L : [
|
|
L
|
|
], u, t, i, o, r, f, e, c, s), h.base = u.__e, u.__u &= -161, h.__h.length && f.push(h), g && (h.__E = h.__ = null);
|
|
} catch (n) {
|
|
if (u.__v = null, c || null != r) {
|
|
for(u.__u |= c ? 160 : 128; e && 8 === e.nodeType && e.nextSibling;)e = e.nextSibling;
|
|
r[r.indexOf(e)] = null, u.__e = e;
|
|
} else u.__e = t.__e, u.__k = t.__k;
|
|
l.__e(n, u, t);
|
|
}
|
|
else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = z(t.__e, u, t, i, o, r, f, c, s);
|
|
(a = l.diffed) && a(u);
|
|
}
|
|
function j(n, u, t) {
|
|
u.__d = void 0;
|
|
for(var i = 0; i < t.length; i++)N(t[i], t[++i], t[++i]);
|
|
l.__c && l.__c(u, n), n.some(function(u) {
|
|
try {
|
|
n = u.__h, u.__h = [], n.some(function(n) {
|
|
n.call(u);
|
|
});
|
|
} catch (n) {
|
|
l.__e(n, u.__v);
|
|
}
|
|
});
|
|
}
|
|
function z(u, t, i, o, r, f, e, c, s) {
|
|
var a, v, p, d, _, g, m, b = i.props, k = t.props, C = t.type;
|
|
if ("svg" === C ? r = "http://www.w3.org/2000/svg" : "math" === C ? r = "http://www.w3.org/1998/Math/MathML" : r || (r = "http://www.w3.org/1999/xhtml"), null != f) {
|
|
for(a = 0; a < f.length; a++)if ((_ = f[a]) && "setAttribute" in _ == !!C && (C ? _.localName === C : 3 === _.nodeType)) {
|
|
u = _, f[a] = null;
|
|
break;
|
|
}
|
|
}
|
|
if (null == u) {
|
|
if (null === C) return document.createTextNode(k);
|
|
u = document.createElementNS(r, C, k.is && k), c && (l.__m && l.__m(t, f), c = !1), f = null;
|
|
}
|
|
if (null === C) b === k || c && u.data === k || (u.data = k);
|
|
else {
|
|
if (f = f && n.call(u.childNodes), b = i.props || h, !c && null != f) for(b = {}, a = 0; a < u.attributes.length; a++)b[(_ = u.attributes[a]).name] = _.value;
|
|
for(a in b)if (_ = b[a], "children" == a) ;
|
|
else if ("dangerouslySetInnerHTML" == a) p = _;
|
|
else if (!(a in k)) {
|
|
if ("value" == a && "defaultValue" in k || "checked" == a && "defaultChecked" in k) continue;
|
|
A(u, a, null, _, r);
|
|
}
|
|
for(a in k)_ = k[a], "children" == a ? d = _ : "dangerouslySetInnerHTML" == a ? v = _ : "value" == a ? g = _ : "checked" == a ? m = _ : c && "function" != typeof _ || b[a] === _ || A(u, a, _, b[a], r);
|
|
if (v) c || p && (v.__html === p.__html || v.__html === u.innerHTML) || (u.innerHTML = v.__html), t.__k = [];
|
|
else if (p && (u.innerHTML = ""), P(u, y(d) ? d : [
|
|
d
|
|
], t, i, o, "foreignObject" === C ? "http://www.w3.org/1999/xhtml" : r, f, e, f ? f[0] : i.__k && x(i, 0), c, s), null != f) for(a = f.length; a--;)w(f[a]);
|
|
c || (a = "value", "progress" === C && null == g ? u.removeAttribute("value") : void 0 !== g && (g !== u[a] || "progress" === C && !g || "option" === C && g !== b[a]) && A(u, a, g, b[a], r), a = "checked", void 0 !== m && m !== u[a] && A(u, a, m, b[a], r));
|
|
}
|
|
return u;
|
|
}
|
|
function N(n, u, t) {
|
|
try {
|
|
if ("function" == typeof n) {
|
|
var i = "function" == typeof n.__u;
|
|
i && n.__u(), i && null == u || (n.__u = n(u));
|
|
} else n.current = u;
|
|
} catch (n) {
|
|
l.__e(n, t);
|
|
}
|
|
}
|
|
function V(n, u, t) {
|
|
var i, o;
|
|
if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || N(i, null, u)), null != (i = n.__c)) {
|
|
if (i.componentWillUnmount) try {
|
|
i.componentWillUnmount();
|
|
} catch (n) {
|
|
l.__e(n, u);
|
|
}
|
|
i.base = i.__P = null;
|
|
}
|
|
if (i = n.__k) for(o = 0; o < i.length; o++)i[o] && V(i[o], u, t || "function" != typeof n.type);
|
|
t || w(n.__e), n.__c = n.__ = n.__e = n.__d = void 0;
|
|
}
|
|
function q(n, l, u) {
|
|
return this.constructor(n, u);
|
|
}
|
|
function B(u, t, i) {
|
|
var o, r, f, e;
|
|
l.__ && l.__(u, t), r = (o = "function" == typeof i) ? null : i && i.__k || t.__k, f = [], e = [], O(t, u = (!o && i || t).__k = _(b, null, [
|
|
u
|
|
]), r || h, h, t.namespaceURI, !o && i ? [
|
|
i
|
|
] : r ? null : t.firstChild ? n.call(t.childNodes) : null, f, !o && i ? i : r ? r.__e : t.firstChild, o, e), j(f, u, e);
|
|
}
|
|
function D(n, l) {
|
|
B(n, l, D);
|
|
}
|
|
function E(l, u, t) {
|
|
var i, o, r, f, e = d({}, l.props);
|
|
for(r in l.type && l.type.defaultProps && (f = l.type.defaultProps), u)"key" == r ? i = u[r] : "ref" == r ? o = u[r] : e[r] = void 0 === u[r] && void 0 !== f ? f[r] : u[r];
|
|
return arguments.length > 2 && (e.children = arguments.length > 3 ? n.call(arguments, 2) : t), g(l.type, e, i || l.key, o || l.ref, null);
|
|
}
|
|
function G(n, l) {
|
|
var u = {
|
|
__c: l = "__cC" + a++,
|
|
__: n,
|
|
Consumer: function(n, l) {
|
|
return n.children(l);
|
|
},
|
|
Provider: function(n) {
|
|
var u, t;
|
|
return this.getChildContext || (u = new Set, (t = {})[l] = this, this.getChildContext = function() {
|
|
return t;
|
|
}, this.componentWillUnmount = function() {
|
|
u = null;
|
|
}, this.shouldComponentUpdate = function(n) {
|
|
this.props.value !== n.value && u.forEach(function(n) {
|
|
n.__e = !0, S(n);
|
|
});
|
|
}, this.sub = function(n) {
|
|
u.add(n);
|
|
var l = n.componentWillUnmount;
|
|
n.componentWillUnmount = function() {
|
|
u && u.delete(n), l && l.call(n);
|
|
};
|
|
}), n.children;
|
|
}
|
|
};
|
|
return u.Provider.__ = u.Consumer.contextType = u;
|
|
}
|
|
n = v.slice, l = {
|
|
__e: function(n, l, u, t) {
|
|
for(var i, o, r; l = l.__;)if ((i = l.__c) && !i.__) try {
|
|
if ((o = i.constructor) && null != o.getDerivedStateFromError && (i.setState(o.getDerivedStateFromError(n)), r = i.__d), null != i.componentDidCatch && (i.componentDidCatch(n, t || {}), r = i.__d), r) return i.__E = i;
|
|
} catch (l) {
|
|
n = l;
|
|
}
|
|
throw n;
|
|
}
|
|
}, u = 0, t = function(n) {
|
|
return null != n && null == n.constructor;
|
|
}, k.prototype.setState = function(n, l) {
|
|
var u;
|
|
u = null != this.__s && this.__s !== this.state ? this.__s : this.__s = d({}, this.state), "function" == typeof n && (n = n(d({}, u), this.props)), n && d(u, n), null != n && this.__v && (l && this._sb.push(l), S(this));
|
|
}, k.prototype.forceUpdate = function(n) {
|
|
this.__v && (this.__e = !0, n && this.__h.push(n), S(this));
|
|
}, k.prototype.render = b, i = [], r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(n, l) {
|
|
return n.__v.__b - l.__v.__b;
|
|
}, M.__r = 0, e = 0, c = F(!1), s = F(!0), a = 0;
|
|
;
|
|
//# sourceMappingURL=preact.module.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs [app-route] (ecmascript) <locals>", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"jsx",
|
|
()=>u,
|
|
"jsxAttr",
|
|
()=>p,
|
|
"jsxDEV",
|
|
()=>u,
|
|
"jsxEscape",
|
|
()=>_,
|
|
"jsxTemplate",
|
|
()=>a,
|
|
"jsxs",
|
|
()=>u
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/preact/dist/preact.mjs [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
var t = /["&<]/;
|
|
function n(r) {
|
|
if (0 === r.length || !1 === t.test(r)) return r;
|
|
for(var e = 0, n = 0, o = "", f = ""; n < r.length; n++){
|
|
switch(r.charCodeAt(n)){
|
|
case 34:
|
|
f = """;
|
|
break;
|
|
case 38:
|
|
f = "&";
|
|
break;
|
|
case 60:
|
|
f = "<";
|
|
break;
|
|
default:
|
|
continue;
|
|
}
|
|
n !== e && (o += r.slice(e, n)), o += f, e = n + 1;
|
|
}
|
|
return n !== e && (o += r.slice(e, n)), o;
|
|
}
|
|
var o = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, f = 0, i = Array.isArray;
|
|
function u(e, t, n, o, i, u) {
|
|
t || (t = {});
|
|
var a, c, l = t;
|
|
"ref" in t && (a = t.ref, delete t.ref);
|
|
var p = {
|
|
type: e,
|
|
props: l,
|
|
key: n,
|
|
ref: a,
|
|
__k: null,
|
|
__: null,
|
|
__b: 0,
|
|
__e: null,
|
|
__d: void 0,
|
|
__c: null,
|
|
constructor: void 0,
|
|
__v: --f,
|
|
__i: -1,
|
|
__u: 0,
|
|
__source: i,
|
|
__self: u
|
|
};
|
|
if ("function" == typeof e && (a = e.defaultProps)) for(c in a)void 0 === l[c] && (l[c] = a[c]);
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].vnode && __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].vnode(p), p;
|
|
}
|
|
function a(r) {
|
|
var t = u(__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"], {
|
|
tpl: r,
|
|
exprs: [].slice.call(arguments, 1)
|
|
});
|
|
return t.key = t.__v, t;
|
|
}
|
|
var c = {}, l = /[A-Z]/g;
|
|
function p(e, t) {
|
|
if (__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].attr) {
|
|
var f = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].attr(e, t);
|
|
if ("string" == typeof f) return f;
|
|
}
|
|
if ("ref" === e || "key" === e) return "";
|
|
if ("style" === e && "object" == typeof t) {
|
|
var i = "";
|
|
for(var u in t){
|
|
var a = t[u];
|
|
if (null != a && "" !== a) {
|
|
var p = "-" == u[0] ? u : c[u] || (c[u] = u.replace(l, "-$&").toLowerCase()), _ = ";";
|
|
"number" != typeof a || p.startsWith("--") || o.test(p) || (_ = "px;"), i = i + p + ":" + a + _;
|
|
}
|
|
}
|
|
return e + '="' + i + '"';
|
|
}
|
|
return null == t || !1 === t || "function" == typeof t || "object" == typeof t ? "" : !0 === t ? e : e + '="' + n(t) + '"';
|
|
}
|
|
function _(r) {
|
|
if (null == r || "boolean" == typeof r || "function" == typeof r) return null;
|
|
if ("object" == typeof r) {
|
|
if (void 0 === r.constructor) return r;
|
|
if (i(r)) {
|
|
for(var e = 0; e < r.length; e++)r[e] = _(r[e]);
|
|
return r;
|
|
}
|
|
}
|
|
return n("" + r);
|
|
}
|
|
;
|
|
//# sourceMappingURL=jsxRuntime.module.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/preact-render-to-string/dist/index.mjs [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"default",
|
|
()=>__TURBOPACK__default__export__,
|
|
"render",
|
|
()=>F,
|
|
"renderToStaticMarkup",
|
|
()=>M,
|
|
"renderToString",
|
|
()=>D,
|
|
"renderToStringAsync",
|
|
()=>S
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/preact/dist/preact.mjs [app-route] (ecmascript)");
|
|
;
|
|
var r = /[\s\n\\/='"\0<>]/, o = /^(xlink|xmlns|xml)([A-Z])/, i = /^accessK|^auto[A-Z]|^cell|^ch|^col|cont|cross|dateT|encT|form[A-Z]|frame|hrefL|inputM|maxL|minL|noV|playsI|popoverT|readO|rowS|src[A-Z]|tabI|useM|item[A-Z]/, a = /^ac|^ali|arabic|basel|cap|clipPath$|clipRule$|color|dominant|enable|fill|flood|font|glyph[^R]|horiz|image|letter|lighting|marker[^WUH]|overline|panose|pointe|paint|rendering|shape|stop|strikethrough|stroke|text[^L]|transform|underline|unicode|units|^v[^i]|^w|^xH/, c = new Set([
|
|
"draggable",
|
|
"spellcheck"
|
|
]), s = /["&<]/;
|
|
function l(e) {
|
|
if (0 === e.length || !1 === s.test(e)) return e;
|
|
for(var t = 0, n = 0, r = "", o = ""; n < e.length; n++){
|
|
switch(e.charCodeAt(n)){
|
|
case 34:
|
|
o = """;
|
|
break;
|
|
case 38:
|
|
o = "&";
|
|
break;
|
|
case 60:
|
|
o = "<";
|
|
break;
|
|
default:
|
|
continue;
|
|
}
|
|
n !== t && (r += e.slice(t, n)), r += o, t = n + 1;
|
|
}
|
|
return n !== t && (r += e.slice(t, n)), r;
|
|
}
|
|
var u = {}, f = new Set([
|
|
"animation-iteration-count",
|
|
"border-image-outset",
|
|
"border-image-slice",
|
|
"border-image-width",
|
|
"box-flex",
|
|
"box-flex-group",
|
|
"box-ordinal-group",
|
|
"column-count",
|
|
"fill-opacity",
|
|
"flex",
|
|
"flex-grow",
|
|
"flex-negative",
|
|
"flex-order",
|
|
"flex-positive",
|
|
"flex-shrink",
|
|
"flood-opacity",
|
|
"font-weight",
|
|
"grid-column",
|
|
"grid-row",
|
|
"line-clamp",
|
|
"line-height",
|
|
"opacity",
|
|
"order",
|
|
"orphans",
|
|
"stop-opacity",
|
|
"stroke-dasharray",
|
|
"stroke-dashoffset",
|
|
"stroke-miterlimit",
|
|
"stroke-opacity",
|
|
"stroke-width",
|
|
"tab-size",
|
|
"widows",
|
|
"z-index",
|
|
"zoom"
|
|
]), p = /[A-Z]/g;
|
|
function h(e) {
|
|
var t = "";
|
|
for(var n in e){
|
|
var r = e[n];
|
|
if (null != r && "" !== r) {
|
|
var o = "-" == n[0] ? n : u[n] || (u[n] = n.replace(p, "-$&").toLowerCase()), i = ";";
|
|
"number" != typeof r || o.startsWith("--") || f.has(o) || (i = "px;"), t = t + o + ":" + r + i;
|
|
}
|
|
}
|
|
return t || void 0;
|
|
}
|
|
function d() {
|
|
this.__d = !0;
|
|
}
|
|
function _(e, t) {
|
|
return {
|
|
__v: e,
|
|
context: t,
|
|
props: e.props,
|
|
setState: d,
|
|
forceUpdate: d,
|
|
__d: !0,
|
|
__h: new Array(0)
|
|
};
|
|
}
|
|
function v(e, t, n) {
|
|
if (!e.s) {
|
|
if (n instanceof m) {
|
|
if (!n.s) return void (n.o = v.bind(null, e, t));
|
|
1 & t && (t = n.s), n = n.v;
|
|
}
|
|
if (n && n.then) return void n.then(v.bind(null, e, t), v.bind(null, e, 2));
|
|
e.s = t, e.v = n;
|
|
const r = e.o;
|
|
r && r(e);
|
|
}
|
|
}
|
|
var m = /*#__PURE__*/ function() {
|
|
function e() {}
|
|
return e.prototype.then = function(t, n) {
|
|
var r = new e, o = this.s;
|
|
if (o) {
|
|
var i = 1 & o ? t : n;
|
|
if (i) {
|
|
try {
|
|
v(r, 1, i(this.v));
|
|
} catch (e) {
|
|
v(r, 2, e);
|
|
}
|
|
return r;
|
|
}
|
|
return this;
|
|
}
|
|
return this.o = function(e) {
|
|
try {
|
|
var o = e.v;
|
|
1 & e.s ? v(r, 1, t ? t(o) : o) : n ? v(r, 1, n(o)) : v(r, 2, o);
|
|
} catch (e) {
|
|
v(r, 2, e);
|
|
}
|
|
}, r;
|
|
}, e;
|
|
}();
|
|
function y(e) {
|
|
return e instanceof m && 1 & e.s;
|
|
}
|
|
function g(e, t, n) {
|
|
for(var r;;){
|
|
var o = e();
|
|
if (y(o) && (o = o.v), !o) return i;
|
|
if (o.then) {
|
|
r = 0;
|
|
break;
|
|
}
|
|
var i = n();
|
|
if (i && i.then) {
|
|
if (!y(i)) {
|
|
r = 1;
|
|
break;
|
|
}
|
|
i = i.s;
|
|
}
|
|
if (t) {
|
|
var a = t();
|
|
if (a && a.then && !y(a)) {
|
|
r = 2;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
var c = new m, s = v.bind(null, c, 2);
|
|
return (0 === r ? o.then(u) : 1 === r ? i.then(l) : a.then(f)).then(void 0, s), c;
|
|
//TURBOPACK unreachable
|
|
;
|
|
function l(r) {
|
|
i = r;
|
|
do {
|
|
if (t && (a = t()) && a.then && !y(a)) return void a.then(f).then(void 0, s);
|
|
if (!(o = e()) || y(o) && !o.v) return void v(c, 1, i);
|
|
if (o.then) return void o.then(u).then(void 0, s);
|
|
y(i = n()) && (i = i.v);
|
|
}while (!i || !i.then)
|
|
i.then(l).then(void 0, s);
|
|
}
|
|
function u(e) {
|
|
e ? (i = n()) && i.then ? i.then(l).then(void 0, s) : l(i) : v(c, 1, i);
|
|
}
|
|
function f() {
|
|
(o = e()) ? o.then ? o.then(u).then(void 0, s) : u(o) : v(c, 1, i);
|
|
}
|
|
}
|
|
function b(e, t) {
|
|
try {
|
|
var n = e();
|
|
} catch (e) {
|
|
return t(!0, e);
|
|
}
|
|
return n && n.then ? n.then(t.bind(null, !1), t.bind(null, !0)) : t(!1, n);
|
|
}
|
|
var k, w, x, C, S = function(r, o) {
|
|
try {
|
|
var i = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__s;
|
|
__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__s = !0, k = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__b, w = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].diffed, x = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__r, C = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].unmount;
|
|
var a = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["h"])(__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"], null);
|
|
return a.__k = [
|
|
r
|
|
], Promise.resolve(b(function() {
|
|
return Promise.resolve(U(r, o || A, !1, void 0, a, !0, void 0)).then(function(e) {
|
|
var t, n = function() {
|
|
if (E(e)) {
|
|
var n = function() {
|
|
var e = o.join(j);
|
|
return t = 1, e;
|
|
}, r = 0, o = e, i = g(function() {
|
|
return !!o.some(function(e) {
|
|
return e && "function" == typeof e.then;
|
|
}) && r++ < 25;
|
|
}, void 0, function() {
|
|
return Promise.resolve(Promise.all(o)).then(function(e) {
|
|
o = e.flat();
|
|
});
|
|
});
|
|
return i && i.then ? i.then(n) : n();
|
|
}
|
|
}();
|
|
return n && n.then ? n.then(function(n) {
|
|
return t ? n : e;
|
|
}) : t ? n : e;
|
|
});
|
|
}, function(t, n) {
|
|
if (__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__c && __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__c(r, L), __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__s = i, L.length = 0, t) throw n;
|
|
return n;
|
|
}));
|
|
} catch (e) {
|
|
return Promise.reject(e);
|
|
}
|
|
}, A = {}, L = [], E = Array.isArray, T = Object.assign, j = "";
|
|
function D(r, o, i) {
|
|
var a = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__s;
|
|
__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__s = !0, k = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__b, w = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].diffed, x = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__r, C = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].unmount;
|
|
var c = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["h"])(__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"], null);
|
|
c.__k = [
|
|
r
|
|
];
|
|
try {
|
|
var s = U(r, o || A, !1, void 0, c, !1, i);
|
|
return E(s) ? s.join(j) : s;
|
|
} catch (e) {
|
|
if (e.then) throw new Error('Use "renderToStringAsync" for suspenseful rendering.');
|
|
throw e;
|
|
} finally{
|
|
__TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__c && __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__c(r, L), __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__s = a, L.length = 0;
|
|
}
|
|
}
|
|
function P(e, t) {
|
|
var n, r = e.type, o = !0;
|
|
return e.__c ? (o = !1, (n = e.__c).state = n.__s) : n = new r(e.props, t), e.__c = n, n.__v = e, n.props = e.props, n.context = t, n.__d = !0, null == n.state && (n.state = A), null == n.__s && (n.__s = n.state), r.getDerivedStateFromProps ? n.state = T({}, n.state, r.getDerivedStateFromProps(n.props, n.state)) : o && n.componentWillMount ? (n.componentWillMount(), n.state = n.__s !== n.state ? n.__s : n.state) : !o && n.componentWillUpdate && n.componentWillUpdate(), x && x(e), n.render(n.props, n.state, t);
|
|
}
|
|
function U(t, s, u, f, p, d, v) {
|
|
if (null == t || !0 === t || !1 === t || t === j) return j;
|
|
var m = typeof t;
|
|
if ("object" != m) return "function" == m ? j : "string" == m ? l(t) : t + j;
|
|
if (E(t)) {
|
|
var y, g = j;
|
|
p.__k = t;
|
|
for(var b = 0; b < t.length; b++){
|
|
var S = t[b];
|
|
if (null != S && "boolean" != typeof S) {
|
|
var L, D = U(S, s, u, f, p, d, v);
|
|
"string" == typeof D ? g += D : (y || (y = []), g && y.push(g), g = j, E(D) ? (L = y).push.apply(L, D) : y.push(D));
|
|
}
|
|
}
|
|
return y ? (g && y.push(g), y) : g;
|
|
}
|
|
if (void 0 !== t.constructor) return j;
|
|
t.__ = p, k && k(t);
|
|
var F = t.type, M = t.props;
|
|
if ("function" == typeof F) {
|
|
var W, $, z, H = s;
|
|
if (F === __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"]) {
|
|
if ("tpl" in M) {
|
|
for(var N = j, q = 0; q < M.tpl.length; q++)if (N += M.tpl[q], M.exprs && q < M.exprs.length) {
|
|
var B = M.exprs[q];
|
|
if (null == B) continue;
|
|
"object" != typeof B || void 0 !== B.constructor && !E(B) ? N += B : N += U(B, s, u, f, t, d, v);
|
|
}
|
|
return N;
|
|
}
|
|
if ("UNSTABLE_comment" in M) return "\x3c!--" + l(M.UNSTABLE_comment) + "--\x3e";
|
|
$ = M.children;
|
|
} else {
|
|
if (null != (W = F.contextType)) {
|
|
var I = s[W.__c];
|
|
H = I ? I.props.value : W.__;
|
|
}
|
|
var O = F.prototype && "function" == typeof F.prototype.render;
|
|
if (O) $ = P(t, H), z = t.__c;
|
|
else {
|
|
t.__c = z = _(t, H);
|
|
for(var R = 0; z.__d && R++ < 25;)z.__d = !1, x && x(t), $ = F.call(z, M, H);
|
|
z.__d = !0;
|
|
}
|
|
if (null != z.getChildContext && (s = T({}, s, z.getChildContext())), O && __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].errorBoundaries && (F.getDerivedStateFromError || z.componentDidCatch)) {
|
|
$ = null != $ && $.type === __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"] && null == $.key && null == $.props.tpl ? $.props.children : $;
|
|
try {
|
|
return U($, s, u, f, t, d, v);
|
|
} catch (e) {
|
|
return F.getDerivedStateFromError && (z.__s = F.getDerivedStateFromError(e)), z.componentDidCatch && z.componentDidCatch(e, A), z.__d ? ($ = P(t, s), null != (z = t.__c).getChildContext && (s = T({}, s, z.getChildContext())), U($ = null != $ && $.type === __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"] && null == $.key && null == $.props.tpl ? $.props.children : $, s, u, f, t, d, v)) : j;
|
|
} finally{
|
|
w && w(t), t.__ = null, C && C(t);
|
|
}
|
|
}
|
|
}
|
|
$ = null != $ && $.type === __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Fragment"] && null == $.key && null == $.props.tpl ? $.props.children : $;
|
|
try {
|
|
var V = U($, s, u, f, t, d, v);
|
|
return w && w(t), t.__ = null, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].unmount && __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].unmount(t), V;
|
|
} catch (n) {
|
|
if (!d && v && v.onError) {
|
|
var K = v.onError(n, t, function(e) {
|
|
return U(e, s, u, f, t, d, v);
|
|
});
|
|
if (void 0 !== K) return K;
|
|
var G = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$preact$2f$dist$2f$preact$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["options"].__e;
|
|
return G && G(n, t), j;
|
|
}
|
|
if (!d) throw n;
|
|
if (!n || "function" != typeof n.then) throw n;
|
|
return n.then(function e() {
|
|
try {
|
|
return U($, s, u, f, t, d, v);
|
|
} catch (n) {
|
|
if (!n || "function" != typeof n.then) throw n;
|
|
return n.then(function() {
|
|
return U($, s, u, f, t, d, v);
|
|
}, e);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
var J, Q = "<" + F, X = j;
|
|
for(var Y in M){
|
|
var ee = M[Y];
|
|
if ("function" != typeof ee || "class" === Y || "className" === Y) {
|
|
switch(Y){
|
|
case "children":
|
|
J = ee;
|
|
continue;
|
|
case "key":
|
|
case "ref":
|
|
case "__self":
|
|
case "__source":
|
|
continue;
|
|
case "htmlFor":
|
|
if ("for" in M) continue;
|
|
Y = "for";
|
|
break;
|
|
case "className":
|
|
if ("class" in M) continue;
|
|
Y = "class";
|
|
break;
|
|
case "defaultChecked":
|
|
Y = "checked";
|
|
break;
|
|
case "defaultSelected":
|
|
Y = "selected";
|
|
break;
|
|
case "defaultValue":
|
|
case "value":
|
|
switch(Y = "value", F){
|
|
case "textarea":
|
|
J = ee;
|
|
continue;
|
|
case "select":
|
|
f = ee;
|
|
continue;
|
|
case "option":
|
|
f != ee || "selected" in M || (Q += " selected");
|
|
}
|
|
break;
|
|
case "dangerouslySetInnerHTML":
|
|
X = ee && ee.__html;
|
|
continue;
|
|
case "style":
|
|
"object" == typeof ee && (ee = h(ee));
|
|
break;
|
|
case "acceptCharset":
|
|
Y = "accept-charset";
|
|
break;
|
|
case "httpEquiv":
|
|
Y = "http-equiv";
|
|
break;
|
|
default:
|
|
if (o.test(Y)) Y = Y.replace(o, "$1:$2").toLowerCase();
|
|
else {
|
|
if (r.test(Y)) continue;
|
|
"-" !== Y[4] && !c.has(Y) || null == ee ? u ? a.test(Y) && (Y = "panose1" === Y ? "panose-1" : Y.replace(/([A-Z])/g, "-$1").toLowerCase()) : i.test(Y) && (Y = Y.toLowerCase()) : ee += j;
|
|
}
|
|
}
|
|
null != ee && !1 !== ee && (Q = !0 === ee || ee === j ? Q + " " + Y : Q + " " + Y + '="' + ("string" == typeof ee ? l(ee) : ee + j) + '"');
|
|
}
|
|
}
|
|
if (r.test(F)) throw new Error(F + " is not a valid HTML tag name in " + Q + ">");
|
|
if (X || ("string" == typeof J ? X = l(J) : null != J && !1 !== J && !0 !== J && (X = U(J, s, "svg" === F || "foreignObject" !== F && u, f, t, d, v))), w && w(t), t.__ = null, C && C(t), !X && Z.has(F)) return Q + "/>";
|
|
var te = "</" + F + ">", ne = Q + ">";
|
|
return E(X) ? [
|
|
ne
|
|
].concat(X, [
|
|
te
|
|
]) : "string" != typeof X ? [
|
|
ne,
|
|
X,
|
|
te
|
|
] : ne + X + te;
|
|
}
|
|
var Z = new Set([
|
|
"area",
|
|
"base",
|
|
"br",
|
|
"col",
|
|
"command",
|
|
"embed",
|
|
"hr",
|
|
"img",
|
|
"input",
|
|
"keygen",
|
|
"link",
|
|
"meta",
|
|
"param",
|
|
"source",
|
|
"track",
|
|
"wbr"
|
|
]), F = D, M = D;
|
|
const __TURBOPACK__default__export__ = D;
|
|
;
|
|
//# sourceMappingURL=index.module.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/oauth4webapi/build/index.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"AUTHORIZATION_RESPONSE_ERROR",
|
|
()=>AUTHORIZATION_RESPONSE_ERROR,
|
|
"AuthorizationResponseError",
|
|
()=>AuthorizationResponseError,
|
|
"ClientSecretBasic",
|
|
()=>ClientSecretBasic,
|
|
"ClientSecretJwt",
|
|
()=>ClientSecretJwt,
|
|
"ClientSecretPost",
|
|
()=>ClientSecretPost,
|
|
"DPoP",
|
|
()=>DPoP,
|
|
"HTTP_REQUEST_FORBIDDEN",
|
|
()=>HTTP_REQUEST_FORBIDDEN,
|
|
"INVALID_REQUEST",
|
|
()=>INVALID_REQUEST,
|
|
"INVALID_RESPONSE",
|
|
()=>INVALID_RESPONSE,
|
|
"INVALID_SERVER_METADATA",
|
|
()=>INVALID_SERVER_METADATA,
|
|
"JSON_ATTRIBUTE_COMPARISON",
|
|
()=>JSON_ATTRIBUTE_COMPARISON,
|
|
"JWT_CLAIM_COMPARISON",
|
|
()=>JWT_CLAIM_COMPARISON,
|
|
"JWT_TIMESTAMP_CHECK",
|
|
()=>JWT_TIMESTAMP_CHECK,
|
|
"JWT_USERINFO_EXPECTED",
|
|
()=>JWT_USERINFO_EXPECTED,
|
|
"KEY_SELECTION",
|
|
()=>KEY_SELECTION,
|
|
"MISSING_SERVER_METADATA",
|
|
()=>MISSING_SERVER_METADATA,
|
|
"None",
|
|
()=>None,
|
|
"OperationProcessingError",
|
|
()=>OperationProcessingError,
|
|
"PARSE_ERROR",
|
|
()=>PARSE_ERROR,
|
|
"PrivateKeyJwt",
|
|
()=>PrivateKeyJwt,
|
|
"REQUEST_PROTOCOL_FORBIDDEN",
|
|
()=>REQUEST_PROTOCOL_FORBIDDEN,
|
|
"RESPONSE_BODY_ERROR",
|
|
()=>RESPONSE_BODY_ERROR,
|
|
"RESPONSE_IS_NOT_CONFORM",
|
|
()=>RESPONSE_IS_NOT_CONFORM,
|
|
"RESPONSE_IS_NOT_JSON",
|
|
()=>RESPONSE_IS_NOT_JSON,
|
|
"ResponseBodyError",
|
|
()=>ResponseBodyError,
|
|
"TlsClientAuth",
|
|
()=>TlsClientAuth,
|
|
"UNSUPPORTED_OPERATION",
|
|
()=>UNSUPPORTED_OPERATION,
|
|
"UnsupportedOperationError",
|
|
()=>UnsupportedOperationError,
|
|
"WWWAuthenticateChallengeError",
|
|
()=>WWWAuthenticateChallengeError,
|
|
"WWW_AUTHENTICATE_CHALLENGE",
|
|
()=>WWW_AUTHENTICATE_CHALLENGE,
|
|
"_expectedIssuer",
|
|
()=>_expectedIssuer,
|
|
"_nodiscoverycheck",
|
|
()=>_nodiscoverycheck,
|
|
"_nopkce",
|
|
()=>_nopkce,
|
|
"allowInsecureRequests",
|
|
()=>allowInsecureRequests,
|
|
"authorizationCodeGrantRequest",
|
|
()=>authorizationCodeGrantRequest,
|
|
"backchannelAuthenticationGrantRequest",
|
|
()=>backchannelAuthenticationGrantRequest,
|
|
"backchannelAuthenticationRequest",
|
|
()=>backchannelAuthenticationRequest,
|
|
"calculatePKCECodeChallenge",
|
|
()=>calculatePKCECodeChallenge,
|
|
"checkProtocol",
|
|
()=>checkProtocol,
|
|
"clientCredentialsGrantRequest",
|
|
()=>clientCredentialsGrantRequest,
|
|
"clockSkew",
|
|
()=>clockSkew,
|
|
"clockTolerance",
|
|
()=>clockTolerance,
|
|
"customFetch",
|
|
()=>customFetch,
|
|
"deviceAuthorizationRequest",
|
|
()=>deviceAuthorizationRequest,
|
|
"deviceCodeGrantRequest",
|
|
()=>deviceCodeGrantRequest,
|
|
"discoveryRequest",
|
|
()=>discoveryRequest,
|
|
"dynamicClientRegistrationRequest",
|
|
()=>dynamicClientRegistrationRequest,
|
|
"expectNoNonce",
|
|
()=>expectNoNonce,
|
|
"expectNoState",
|
|
()=>expectNoState,
|
|
"formPostResponse",
|
|
()=>formPostResponse,
|
|
"generateKeyPair",
|
|
()=>generateKeyPair,
|
|
"generateRandomCodeVerifier",
|
|
()=>generateRandomCodeVerifier,
|
|
"generateRandomNonce",
|
|
()=>generateRandomNonce,
|
|
"generateRandomState",
|
|
()=>generateRandomState,
|
|
"genericTokenEndpointRequest",
|
|
()=>genericTokenEndpointRequest,
|
|
"getContentType",
|
|
()=>getContentType,
|
|
"getValidatedIdTokenClaims",
|
|
()=>getValidatedIdTokenClaims,
|
|
"introspectionRequest",
|
|
()=>introspectionRequest,
|
|
"isDPoPNonceError",
|
|
()=>isDPoPNonceError,
|
|
"issueRequestObject",
|
|
()=>issueRequestObject,
|
|
"jweDecrypt",
|
|
()=>jweDecrypt,
|
|
"jwksCache",
|
|
()=>jwksCache,
|
|
"modifyAssertion",
|
|
()=>modifyAssertion,
|
|
"nopkce",
|
|
()=>nopkce,
|
|
"processAuthorizationCodeResponse",
|
|
()=>processAuthorizationCodeResponse,
|
|
"processBackchannelAuthenticationGrantResponse",
|
|
()=>processBackchannelAuthenticationGrantResponse,
|
|
"processBackchannelAuthenticationResponse",
|
|
()=>processBackchannelAuthenticationResponse,
|
|
"processClientCredentialsResponse",
|
|
()=>processClientCredentialsResponse,
|
|
"processDeviceAuthorizationResponse",
|
|
()=>processDeviceAuthorizationResponse,
|
|
"processDeviceCodeResponse",
|
|
()=>processDeviceCodeResponse,
|
|
"processDiscoveryResponse",
|
|
()=>processDiscoveryResponse,
|
|
"processDynamicClientRegistrationResponse",
|
|
()=>processDynamicClientRegistrationResponse,
|
|
"processGenericTokenEndpointResponse",
|
|
()=>processGenericTokenEndpointResponse,
|
|
"processIntrospectionResponse",
|
|
()=>processIntrospectionResponse,
|
|
"processPushedAuthorizationResponse",
|
|
()=>processPushedAuthorizationResponse,
|
|
"processRefreshTokenResponse",
|
|
()=>processRefreshTokenResponse,
|
|
"processResourceDiscoveryResponse",
|
|
()=>processResourceDiscoveryResponse,
|
|
"processRevocationResponse",
|
|
()=>processRevocationResponse,
|
|
"processUserInfoResponse",
|
|
()=>processUserInfoResponse,
|
|
"protectedResourceRequest",
|
|
()=>protectedResourceRequest,
|
|
"pushedAuthorizationRequest",
|
|
()=>pushedAuthorizationRequest,
|
|
"refreshTokenGrantRequest",
|
|
()=>refreshTokenGrantRequest,
|
|
"resolveEndpoint",
|
|
()=>resolveEndpoint,
|
|
"resourceDiscoveryRequest",
|
|
()=>resourceDiscoveryRequest,
|
|
"revocationRequest",
|
|
()=>revocationRequest,
|
|
"skipAuthTimeCheck",
|
|
()=>skipAuthTimeCheck,
|
|
"skipStateCheck",
|
|
()=>skipStateCheck,
|
|
"skipSubjectCheck",
|
|
()=>skipSubjectCheck,
|
|
"userInfoRequest",
|
|
()=>userInfoRequest,
|
|
"validateApplicationLevelSignature",
|
|
()=>validateApplicationLevelSignature,
|
|
"validateAuthResponse",
|
|
()=>validateAuthResponse,
|
|
"validateCodeIdTokenResponse",
|
|
()=>validateCodeIdTokenResponse,
|
|
"validateDetachedSignatureResponse",
|
|
()=>validateDetachedSignatureResponse,
|
|
"validateJwtAccessToken",
|
|
()=>validateJwtAccessToken,
|
|
"validateJwtAuthResponse",
|
|
()=>validateJwtAuthResponse
|
|
]);
|
|
let USER_AGENT;
|
|
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
|
|
const NAME = 'oauth4webapi';
|
|
const VERSION = 'v3.8.5';
|
|
USER_AGENT = `${NAME}/${VERSION}`;
|
|
}
|
|
function looseInstanceOf(input, expected) {
|
|
if (input == null) {
|
|
return false;
|
|
}
|
|
try {
|
|
return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
const ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';
|
|
const ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';
|
|
function CodedTypeError(message, code, cause) {
|
|
const err = new TypeError(message, {
|
|
cause
|
|
});
|
|
Object.assign(err, {
|
|
code
|
|
});
|
|
return err;
|
|
}
|
|
const allowInsecureRequests = Symbol();
|
|
const clockSkew = Symbol();
|
|
const clockTolerance = Symbol();
|
|
const customFetch = Symbol();
|
|
const modifyAssertion = Symbol();
|
|
const jweDecrypt = Symbol();
|
|
const jwksCache = Symbol();
|
|
const encoder = new TextEncoder();
|
|
const decoder = new TextDecoder();
|
|
function buf(input) {
|
|
if (typeof input === 'string') {
|
|
return encoder.encode(input);
|
|
}
|
|
return decoder.decode(input);
|
|
}
|
|
let encodeBase64Url;
|
|
if (Uint8Array.prototype.toBase64) {
|
|
encodeBase64Url = (input)=>{
|
|
if (input instanceof ArrayBuffer) {
|
|
input = new Uint8Array(input);
|
|
}
|
|
return input.toBase64({
|
|
alphabet: 'base64url',
|
|
omitPadding: true
|
|
});
|
|
};
|
|
} else {
|
|
const CHUNK_SIZE = 0x8000;
|
|
encodeBase64Url = (input)=>{
|
|
if (input instanceof ArrayBuffer) {
|
|
input = new Uint8Array(input);
|
|
}
|
|
const arr = [];
|
|
for(let i = 0; i < input.byteLength; i += CHUNK_SIZE){
|
|
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
}
|
|
return btoa(arr.join('')).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
};
|
|
}
|
|
let decodeBase64Url;
|
|
if (Uint8Array.fromBase64) {
|
|
decodeBase64Url = (input)=>{
|
|
try {
|
|
return Uint8Array.fromBase64(input, {
|
|
alphabet: 'base64url'
|
|
});
|
|
} catch (cause) {
|
|
throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);
|
|
}
|
|
};
|
|
} else {
|
|
decodeBase64Url = (input)=>{
|
|
try {
|
|
const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''));
|
|
const bytes = new Uint8Array(binary.length);
|
|
for(let i = 0; i < binary.length; i++){
|
|
bytes[i] = binary.charCodeAt(i);
|
|
}
|
|
return bytes;
|
|
} catch (cause) {
|
|
throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);
|
|
}
|
|
};
|
|
}
|
|
function b64u(input) {
|
|
if (typeof input === 'string') {
|
|
return decodeBase64Url(input);
|
|
}
|
|
return encodeBase64Url(input);
|
|
}
|
|
class UnsupportedOperationError extends Error {
|
|
code;
|
|
constructor(message, options){
|
|
super(message, options);
|
|
this.name = this.constructor.name;
|
|
this.code = UNSUPPORTED_OPERATION;
|
|
Error.captureStackTrace?.(this, this.constructor);
|
|
}
|
|
}
|
|
class OperationProcessingError extends Error {
|
|
code;
|
|
constructor(message, options){
|
|
super(message, options);
|
|
this.name = this.constructor.name;
|
|
if (options?.code) {
|
|
this.code = options?.code;
|
|
}
|
|
Error.captureStackTrace?.(this, this.constructor);
|
|
}
|
|
}
|
|
function OPE(message, code, cause) {
|
|
return new OperationProcessingError(message, {
|
|
code,
|
|
cause
|
|
});
|
|
}
|
|
async function calculateJwkThumbprint(jwk) {
|
|
let components;
|
|
switch(jwk.kty){
|
|
case 'EC':
|
|
components = {
|
|
crv: jwk.crv,
|
|
kty: jwk.kty,
|
|
x: jwk.x,
|
|
y: jwk.y
|
|
};
|
|
break;
|
|
case 'OKP':
|
|
components = {
|
|
crv: jwk.crv,
|
|
kty: jwk.kty,
|
|
x: jwk.x
|
|
};
|
|
break;
|
|
case 'AKP':
|
|
components = {
|
|
alg: jwk.alg,
|
|
kty: jwk.kty,
|
|
pub: jwk.pub
|
|
};
|
|
break;
|
|
case 'RSA':
|
|
components = {
|
|
e: jwk.e,
|
|
kty: jwk.kty,
|
|
n: jwk.n
|
|
};
|
|
break;
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported JWK key type', {
|
|
cause: jwk
|
|
});
|
|
}
|
|
return b64u(await crypto.subtle.digest('SHA-256', buf(JSON.stringify(components))));
|
|
}
|
|
function assertCryptoKey(key, it) {
|
|
if (!(key instanceof CryptoKey)) {
|
|
throw CodedTypeError(`${it} must be a CryptoKey`, ERR_INVALID_ARG_TYPE);
|
|
}
|
|
}
|
|
function assertPrivateKey(key, it) {
|
|
assertCryptoKey(key, it);
|
|
if (key.type !== 'private') {
|
|
throw CodedTypeError(`${it} must be a private CryptoKey`, ERR_INVALID_ARG_VALUE);
|
|
}
|
|
}
|
|
function assertPublicKey(key, it) {
|
|
assertCryptoKey(key, it);
|
|
if (key.type !== 'public') {
|
|
throw CodedTypeError(`${it} must be a public CryptoKey`, ERR_INVALID_ARG_VALUE);
|
|
}
|
|
}
|
|
function normalizeTyp(value) {
|
|
return value.toLowerCase().replace(/^application\//, '');
|
|
}
|
|
function isJsonObject(input) {
|
|
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
function prepareHeaders(input) {
|
|
if (looseInstanceOf(input, Headers)) {
|
|
input = Object.fromEntries(input.entries());
|
|
}
|
|
const headers = new Headers(input ?? {});
|
|
if (USER_AGENT && !headers.has('user-agent')) {
|
|
headers.set('user-agent', USER_AGENT);
|
|
}
|
|
if (headers.has('authorization')) {
|
|
throw CodedTypeError('"options.headers" must not include the "authorization" header name', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
return headers;
|
|
}
|
|
function signal(url, value) {
|
|
if (value !== undefined) {
|
|
if (typeof value === 'function') {
|
|
value = value(url.href);
|
|
}
|
|
if (!(value instanceof AbortSignal)) {
|
|
throw CodedTypeError('"options.signal" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
return value;
|
|
}
|
|
return undefined;
|
|
}
|
|
function replaceDoubleSlash(pathname) {
|
|
if (pathname.includes('//')) {
|
|
return pathname.replace('//', '/');
|
|
}
|
|
return pathname;
|
|
}
|
|
function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
|
|
if (url.pathname === '/') {
|
|
url.pathname = wellKnown;
|
|
} else {
|
|
url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, '')}`);
|
|
}
|
|
return url;
|
|
}
|
|
function appendWellKnown(url, wellKnown) {
|
|
url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
|
|
return url;
|
|
}
|
|
async function performDiscovery(input, urlName, transform, options) {
|
|
if (!(input instanceof URL)) {
|
|
throw CodedTypeError(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE);
|
|
}
|
|
checkProtocol(input, options?.[allowInsecureRequests] !== true);
|
|
const url = transform(new URL(input.href));
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
return (options?.[customFetch] || fetch)(url.href, {
|
|
body: undefined,
|
|
headers: Object.fromEntries(headers.entries()),
|
|
method: 'GET',
|
|
redirect: 'manual',
|
|
signal: signal(url, options?.signal)
|
|
});
|
|
}
|
|
async function discoveryRequest(issuerIdentifier, options) {
|
|
return performDiscovery(issuerIdentifier, 'issuerIdentifier', (url)=>{
|
|
switch(options?.algorithm){
|
|
case undefined:
|
|
case 'oidc':
|
|
appendWellKnown(url, '.well-known/openid-configuration');
|
|
break;
|
|
case 'oauth2':
|
|
prependWellKnown(url, '.well-known/oauth-authorization-server');
|
|
break;
|
|
default:
|
|
throw CodedTypeError('"options.algorithm" must be "oidc" (default), or "oauth2"', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
return url;
|
|
}, options);
|
|
}
|
|
function assertNumber(input, allow0, it, code, cause) {
|
|
try {
|
|
if (typeof input !== 'number' || !Number.isFinite(input)) {
|
|
throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);
|
|
}
|
|
if (input > 0) return;
|
|
if (allow0) {
|
|
if (input !== 0) {
|
|
throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);
|
|
}
|
|
return;
|
|
}
|
|
throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);
|
|
} catch (err) {
|
|
if (code) {
|
|
throw OPE(err.message, code, cause);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
function assertString(input, it, code, cause) {
|
|
try {
|
|
if (typeof input !== 'string') {
|
|
throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);
|
|
}
|
|
if (input.length === 0) {
|
|
throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);
|
|
}
|
|
} catch (err) {
|
|
if (code) {
|
|
throw OPE(err.message, code, cause);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
|
|
const expected = expectedIssuerIdentifier;
|
|
if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
|
|
throw CodedTypeError('"expectedIssuerIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
if (response.status !== 200) {
|
|
throw OPE('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
|
|
}
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.issuer, '"response" body "issuer" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {
|
|
throw OPE('"response" body "issuer" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, {
|
|
expected: expected.href,
|
|
body: json,
|
|
attribute: 'issuer'
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
function assertApplicationJson(response) {
|
|
assertContentType(response, 'application/json');
|
|
}
|
|
function notJson(response, ...types) {
|
|
let msg = '"response" content-type must be ';
|
|
if (types.length > 2) {
|
|
const last = types.pop();
|
|
msg += `${types.join(', ')}, or ${last}`;
|
|
} else if (types.length === 2) {
|
|
msg += `${types[0]} or ${types[1]}`;
|
|
} else {
|
|
msg += types[0];
|
|
}
|
|
return OPE(msg, RESPONSE_IS_NOT_JSON, response);
|
|
}
|
|
function assertContentTypes(response, ...types) {
|
|
if (!types.includes(getContentType(response))) {
|
|
throw notJson(response, ...types);
|
|
}
|
|
}
|
|
function assertContentType(response, contentType) {
|
|
if (getContentType(response) !== contentType) {
|
|
throw notJson(response, contentType);
|
|
}
|
|
}
|
|
function randomBytes() {
|
|
return b64u(crypto.getRandomValues(new Uint8Array(32)));
|
|
}
|
|
function generateRandomCodeVerifier() {
|
|
return randomBytes();
|
|
}
|
|
function generateRandomState() {
|
|
return randomBytes();
|
|
}
|
|
function generateRandomNonce() {
|
|
return randomBytes();
|
|
}
|
|
async function calculatePKCECodeChallenge(codeVerifier) {
|
|
assertString(codeVerifier, 'codeVerifier');
|
|
return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));
|
|
}
|
|
function getKeyAndKid(input) {
|
|
if (input instanceof CryptoKey) {
|
|
return {
|
|
key: input
|
|
};
|
|
}
|
|
if (!(input?.key instanceof CryptoKey)) {
|
|
return {};
|
|
}
|
|
if (input.kid !== undefined) {
|
|
assertString(input.kid, '"kid"');
|
|
}
|
|
return {
|
|
key: input.key,
|
|
kid: input.kid
|
|
};
|
|
}
|
|
function psAlg(key) {
|
|
switch(key.algorithm.hash.name){
|
|
case 'SHA-256':
|
|
return 'PS256';
|
|
case 'SHA-384':
|
|
return 'PS384';
|
|
case 'SHA-512':
|
|
return 'PS512';
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
function rsAlg(key) {
|
|
switch(key.algorithm.hash.name){
|
|
case 'SHA-256':
|
|
return 'RS256';
|
|
case 'SHA-384':
|
|
return 'RS384';
|
|
case 'SHA-512':
|
|
return 'RS512';
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
function esAlg(key) {
|
|
switch(key.algorithm.namedCurve){
|
|
case 'P-256':
|
|
return 'ES256';
|
|
case 'P-384':
|
|
return 'ES384';
|
|
case 'P-521':
|
|
return 'ES512';
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve', {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
function keyToJws(key) {
|
|
switch(key.algorithm.name){
|
|
case 'RSA-PSS':
|
|
return psAlg(key);
|
|
case 'RSASSA-PKCS1-v1_5':
|
|
return rsAlg(key);
|
|
case 'ECDSA':
|
|
return esAlg(key);
|
|
case 'Ed25519':
|
|
case 'ML-DSA-44':
|
|
case 'ML-DSA-65':
|
|
case 'ML-DSA-87':
|
|
return key.algorithm.name;
|
|
case 'EdDSA':
|
|
return 'Ed25519';
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
function getClockSkew(client) {
|
|
const skew = client?.[clockSkew];
|
|
return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;
|
|
}
|
|
function getClockTolerance(client) {
|
|
const tolerance = client?.[clockTolerance];
|
|
return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
|
|
}
|
|
function epochTime() {
|
|
return Math.floor(Date.now() / 1000);
|
|
}
|
|
function assertAs(as) {
|
|
if (typeof as !== 'object' || as === null) {
|
|
throw CodedTypeError('"as" must be an object', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
assertString(as.issuer, '"as.issuer"');
|
|
}
|
|
function assertClient(client) {
|
|
if (typeof client !== 'object' || client === null) {
|
|
throw CodedTypeError('"client" must be an object', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
assertString(client.client_id, '"client.client_id"');
|
|
}
|
|
function formUrlEncode(token) {
|
|
return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring)=>{
|
|
switch(substring){
|
|
case '-':
|
|
case '_':
|
|
case '.':
|
|
case '!':
|
|
case '~':
|
|
case '*':
|
|
case "'":
|
|
case '(':
|
|
case ')':
|
|
return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;
|
|
case '%20':
|
|
return '+';
|
|
default:
|
|
throw new Error();
|
|
}
|
|
});
|
|
}
|
|
function ClientSecretPost(clientSecret) {
|
|
assertString(clientSecret, '"clientSecret"');
|
|
return (_as, client, body, _headers)=>{
|
|
body.set('client_id', client.client_id);
|
|
body.set('client_secret', clientSecret);
|
|
};
|
|
}
|
|
function ClientSecretBasic(clientSecret) {
|
|
assertString(clientSecret, '"clientSecret"');
|
|
return (_as, client, _body, headers)=>{
|
|
const username = formUrlEncode(client.client_id);
|
|
const password = formUrlEncode(clientSecret);
|
|
const credentials = btoa(`${username}:${password}`);
|
|
headers.set('authorization', `Basic ${credentials}`);
|
|
};
|
|
}
|
|
function clientAssertionPayload(as, client) {
|
|
const now = epochTime() + getClockSkew(client);
|
|
return {
|
|
jti: randomBytes(),
|
|
aud: as.issuer,
|
|
exp: now + 60,
|
|
iat: now,
|
|
nbf: now,
|
|
iss: client.client_id,
|
|
sub: client.client_id
|
|
};
|
|
}
|
|
function PrivateKeyJwt(clientPrivateKey, options) {
|
|
const { key, kid } = getKeyAndKid(clientPrivateKey);
|
|
assertPrivateKey(key, '"clientPrivateKey.key"');
|
|
return async (as, client, body, _headers)=>{
|
|
const header = {
|
|
alg: keyToJws(key),
|
|
kid
|
|
};
|
|
const payload = clientAssertionPayload(as, client);
|
|
options?.[modifyAssertion]?.(header, payload);
|
|
body.set('client_id', client.client_id);
|
|
body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
|
|
body.set('client_assertion', await signJwt(header, payload, key));
|
|
};
|
|
}
|
|
function ClientSecretJwt(clientSecret, options) {
|
|
assertString(clientSecret, '"clientSecret"');
|
|
const modify = options?.[modifyAssertion];
|
|
let key;
|
|
return async (as, client, body, _headers)=>{
|
|
key ||= await crypto.subtle.importKey('raw', buf(clientSecret), {
|
|
hash: 'SHA-256',
|
|
name: 'HMAC'
|
|
}, false, [
|
|
'sign'
|
|
]);
|
|
const header = {
|
|
alg: 'HS256'
|
|
};
|
|
const payload = clientAssertionPayload(as, client);
|
|
modify?.(header, payload);
|
|
const data = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;
|
|
const hmac = await crypto.subtle.sign(key.algorithm, key, buf(data));
|
|
body.set('client_id', client.client_id);
|
|
body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
|
|
body.set('client_assertion', `${data}.${b64u(new Uint8Array(hmac))}`);
|
|
};
|
|
}
|
|
function None() {
|
|
return (_as, client, body, _headers)=>{
|
|
body.set('client_id', client.client_id);
|
|
};
|
|
}
|
|
function TlsClientAuth() {
|
|
return None();
|
|
}
|
|
async function signJwt(header, payload, key) {
|
|
if (!key.usages.includes('sign')) {
|
|
throw CodedTypeError('CryptoKey instances used for signing assertions must include "sign" in their "usages"', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;
|
|
const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));
|
|
return `${input}.${signature}`;
|
|
}
|
|
async function issueRequestObject(as, client, parameters, privateKey, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
parameters = new URLSearchParams(parameters);
|
|
const { key, kid } = getKeyAndKid(privateKey);
|
|
assertPrivateKey(key, '"privateKey.key"');
|
|
parameters.set('client_id', client.client_id);
|
|
const now = epochTime() + getClockSkew(client);
|
|
const claims = {
|
|
...Object.fromEntries(parameters.entries()),
|
|
jti: randomBytes(),
|
|
aud: as.issuer,
|
|
exp: now + 60,
|
|
iat: now,
|
|
nbf: now,
|
|
iss: client.client_id
|
|
};
|
|
let resource;
|
|
if (parameters.has('resource') && (resource = parameters.getAll('resource')) && resource.length > 1) {
|
|
claims.resource = resource;
|
|
}
|
|
{
|
|
let value = parameters.get('max_age');
|
|
if (value !== null) {
|
|
claims.max_age = parseInt(value, 10);
|
|
assertNumber(claims.max_age, true, '"max_age" parameter');
|
|
}
|
|
}
|
|
{
|
|
let value = parameters.get('claims');
|
|
if (value !== null) {
|
|
try {
|
|
claims.claims = JSON.parse(value);
|
|
} catch (cause) {
|
|
throw OPE('failed to parse the "claims" parameter as JSON', PARSE_ERROR, cause);
|
|
}
|
|
if (!isJsonObject(claims.claims)) {
|
|
throw CodedTypeError('"claims" parameter must be a JSON with a top level object', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
}
|
|
}
|
|
{
|
|
let value = parameters.get('authorization_details');
|
|
if (value !== null) {
|
|
try {
|
|
claims.authorization_details = JSON.parse(value);
|
|
} catch (cause) {
|
|
throw OPE('failed to parse the "authorization_details" parameter as JSON', PARSE_ERROR, cause);
|
|
}
|
|
if (!Array.isArray(claims.authorization_details)) {
|
|
throw CodedTypeError('"authorization_details" parameter must be a JSON with a top level array', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
}
|
|
}
|
|
const header = {
|
|
alg: keyToJws(key),
|
|
typ: 'oauth-authz-req+jwt',
|
|
kid
|
|
};
|
|
options?.[modifyAssertion]?.(header, claims);
|
|
return signJwt(header, claims, key);
|
|
}
|
|
let jwkCache;
|
|
async function getSetPublicJwkCache(key, alg) {
|
|
const { kty, e, n, x, y, crv, pub } = await crypto.subtle.exportKey('jwk', key);
|
|
const jwk = {
|
|
kty,
|
|
e,
|
|
n,
|
|
x,
|
|
y,
|
|
crv,
|
|
pub
|
|
};
|
|
if (kty === 'AKP') jwk.alg = alg;
|
|
jwkCache.set(key, jwk);
|
|
return jwk;
|
|
}
|
|
async function publicJwk(key, alg) {
|
|
jwkCache ||= new WeakMap();
|
|
return jwkCache.get(key) || getSetPublicJwkCache(key, alg);
|
|
}
|
|
const URLParse = URL.parse ? (url, base)=>URL.parse(url, base) : (url, base)=>{
|
|
try {
|
|
return new URL(url, base);
|
|
} catch {
|
|
return null;
|
|
}
|
|
};
|
|
function checkProtocol(url, enforceHttps) {
|
|
if (enforceHttps && url.protocol !== 'https:') {
|
|
throw OPE('only requests to HTTPS are allowed', HTTP_REQUEST_FORBIDDEN, url);
|
|
}
|
|
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
throw OPE('only HTTP and HTTPS requests are allowed', REQUEST_PROTOCOL_FORBIDDEN, url);
|
|
}
|
|
}
|
|
function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
|
|
let url;
|
|
if (typeof value !== 'string' || !(url = URLParse(value))) {
|
|
throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `"as.mtls_endpoint_aliases.${endpoint}"` : `"as.${endpoint}"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, {
|
|
attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint
|
|
});
|
|
}
|
|
checkProtocol(url, enforceHttps);
|
|
return url;
|
|
}
|
|
function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
|
|
if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {
|
|
return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
}
|
|
return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
}
|
|
async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const body = new URLSearchParams(parameters);
|
|
body.set('client_id', client.client_id);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
if (options?.DPoP !== undefined) {
|
|
assertDPoP(options.DPoP);
|
|
await options.DPoP.addProof(url, headers, 'POST');
|
|
}
|
|
const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
options?.DPoP?.cacheNonce(response, url);
|
|
return response;
|
|
}
|
|
class DPoPHandler {
|
|
#header;
|
|
#privateKey;
|
|
#publicKey;
|
|
#clockSkew;
|
|
#modifyAssertion;
|
|
#map;
|
|
#jkt;
|
|
constructor(client, keyPair, options){
|
|
assertPrivateKey(keyPair?.privateKey, '"DPoP.privateKey"');
|
|
assertPublicKey(keyPair?.publicKey, '"DPoP.publicKey"');
|
|
if (!keyPair.publicKey.extractable) {
|
|
throw CodedTypeError('"DPoP.publicKey.extractable" must be true', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
this.#modifyAssertion = options?.[modifyAssertion];
|
|
this.#clockSkew = getClockSkew(client);
|
|
this.#privateKey = keyPair.privateKey;
|
|
this.#publicKey = keyPair.publicKey;
|
|
branded.add(this);
|
|
}
|
|
#get(key) {
|
|
this.#map ||= new Map();
|
|
let item = this.#map.get(key);
|
|
if (item) {
|
|
this.#map.delete(key);
|
|
this.#map.set(key, item);
|
|
}
|
|
return item;
|
|
}
|
|
#set(key, val) {
|
|
this.#map ||= new Map();
|
|
this.#map.delete(key);
|
|
if (this.#map.size === 100) {
|
|
this.#map.delete(this.#map.keys().next().value);
|
|
}
|
|
this.#map.set(key, val);
|
|
}
|
|
async calculateThumbprint() {
|
|
if (!this.#jkt) {
|
|
const jwk = await crypto.subtle.exportKey('jwk', this.#publicKey);
|
|
this.#jkt ||= await calculateJwkThumbprint(jwk);
|
|
}
|
|
return this.#jkt;
|
|
}
|
|
async addProof(url, headers, htm, accessToken) {
|
|
const alg = keyToJws(this.#privateKey);
|
|
this.#header ||= {
|
|
alg,
|
|
typ: 'dpop+jwt',
|
|
jwk: await publicJwk(this.#publicKey, alg)
|
|
};
|
|
const nonce = this.#get(url.origin);
|
|
const now = epochTime() + this.#clockSkew;
|
|
const payload = {
|
|
iat: now,
|
|
jti: randomBytes(),
|
|
htm,
|
|
nonce,
|
|
htu: `${url.origin}${url.pathname}`,
|
|
ath: accessToken ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken))) : undefined
|
|
};
|
|
this.#modifyAssertion?.(this.#header, payload);
|
|
headers.set('dpop', await signJwt(this.#header, payload, this.#privateKey));
|
|
}
|
|
cacheNonce(response, url) {
|
|
try {
|
|
const nonce = response.headers.get('dpop-nonce');
|
|
if (nonce) {
|
|
this.#set(url.origin, nonce);
|
|
}
|
|
} catch {}
|
|
}
|
|
}
|
|
function isDPoPNonceError(err) {
|
|
if (err instanceof WWWAuthenticateChallengeError) {
|
|
const { 0: challenge, length } = err.cause;
|
|
return length === 1 && challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce';
|
|
}
|
|
if (err instanceof ResponseBodyError) {
|
|
return err.error === 'use_dpop_nonce';
|
|
}
|
|
return false;
|
|
}
|
|
function DPoP(client, keyPair, options) {
|
|
return new DPoPHandler(client, keyPair, options);
|
|
}
|
|
class ResponseBodyError extends Error {
|
|
cause;
|
|
code;
|
|
error;
|
|
status;
|
|
error_description;
|
|
response;
|
|
constructor(message, options){
|
|
super(message, options);
|
|
this.name = this.constructor.name;
|
|
this.code = RESPONSE_BODY_ERROR;
|
|
this.cause = options.cause;
|
|
this.error = options.cause.error;
|
|
this.status = options.response.status;
|
|
this.error_description = options.cause.error_description;
|
|
Object.defineProperty(this, 'response', {
|
|
enumerable: false,
|
|
value: options.response
|
|
});
|
|
Error.captureStackTrace?.(this, this.constructor);
|
|
}
|
|
}
|
|
class AuthorizationResponseError extends Error {
|
|
cause;
|
|
code;
|
|
error;
|
|
error_description;
|
|
constructor(message, options){
|
|
super(message, options);
|
|
this.name = this.constructor.name;
|
|
this.code = AUTHORIZATION_RESPONSE_ERROR;
|
|
this.cause = options.cause;
|
|
this.error = options.cause.get('error');
|
|
this.error_description = options.cause.get('error_description') ?? undefined;
|
|
Error.captureStackTrace?.(this, this.constructor);
|
|
}
|
|
}
|
|
class WWWAuthenticateChallengeError extends Error {
|
|
cause;
|
|
code;
|
|
response;
|
|
status;
|
|
constructor(message, options){
|
|
super(message, options);
|
|
this.name = this.constructor.name;
|
|
this.code = WWW_AUTHENTICATE_CHALLENGE;
|
|
this.cause = options.cause;
|
|
this.status = options.response.status;
|
|
this.response = options.response;
|
|
Object.defineProperty(this, 'response', {
|
|
enumerable: false
|
|
});
|
|
Error.captureStackTrace?.(this, this.constructor);
|
|
}
|
|
}
|
|
const tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
|
|
const token68Match = '[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}';
|
|
const quotedMatch = '"((?:[^"\\\\]|\\\\[\\s\\S])*)"';
|
|
const quotedParamMatcher = '(' + tokenMatch + ')\\s*=\\s*' + quotedMatch;
|
|
const paramMatcher = '(' + tokenMatch + ')\\s*=\\s*(' + tokenMatch + ')';
|
|
const schemeRE = new RegExp('^[,\\s]*(' + tokenMatch + ')');
|
|
const quotedParamRE = new RegExp('^[,\\s]*' + quotedParamMatcher + '[,\\s]*(.*)');
|
|
const unquotedParamRE = new RegExp('^[,\\s]*' + paramMatcher + '[,\\s]*(.*)');
|
|
const token68ParamRE = new RegExp('^(' + token68Match + ')(?:$|[,\\s])(.*)');
|
|
function parseWwwAuthenticateChallenges(response) {
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
const header = response.headers.get('www-authenticate');
|
|
if (header === null) {
|
|
return undefined;
|
|
}
|
|
const challenges = [];
|
|
let rest = header;
|
|
while(rest){
|
|
let match = rest.match(schemeRE);
|
|
const scheme = match?.['1'].toLowerCase();
|
|
if (!scheme) {
|
|
return undefined;
|
|
}
|
|
const afterScheme = rest.substring(match[0].length);
|
|
if (afterScheme && !afterScheme.match(/^[\s,]/)) {
|
|
return undefined;
|
|
}
|
|
const spaceMatch = afterScheme.match(/^\s+(.*)$/);
|
|
const hasParameters = !!spaceMatch;
|
|
rest = spaceMatch ? spaceMatch[1] : undefined;
|
|
const parameters = {};
|
|
let token68;
|
|
if (hasParameters) {
|
|
while(rest){
|
|
let key;
|
|
let value;
|
|
if (match = rest.match(quotedParamRE)) {
|
|
;
|
|
[, key, value, rest] = match;
|
|
if (value.includes('\\')) {
|
|
try {
|
|
value = JSON.parse(`"${value}"`);
|
|
} catch {}
|
|
}
|
|
parameters[key.toLowerCase()] = value;
|
|
continue;
|
|
}
|
|
if (match = rest.match(unquotedParamRE)) {
|
|
;
|
|
[, key, value, rest] = match;
|
|
parameters[key.toLowerCase()] = value;
|
|
continue;
|
|
}
|
|
if (match = rest.match(token68ParamRE)) {
|
|
if (Object.keys(parameters).length) {
|
|
break;
|
|
}
|
|
;
|
|
[, token68, rest] = match;
|
|
break;
|
|
}
|
|
return undefined;
|
|
}
|
|
} else {
|
|
rest = afterScheme || undefined;
|
|
}
|
|
const challenge = {
|
|
scheme,
|
|
parameters
|
|
};
|
|
if (token68) {
|
|
challenge.token68 = token68;
|
|
}
|
|
challenges.push(challenge);
|
|
}
|
|
if (!challenges.length) {
|
|
return undefined;
|
|
}
|
|
return challenges;
|
|
}
|
|
async function processPushedAuthorizationResponse(as, client, response) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 201, 'Pushed Authorization Request Endpoint');
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.request_uri, '"response" body "request_uri" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;
|
|
assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
json.expires_in = expiresIn;
|
|
return json;
|
|
}
|
|
async function parseOAuthResponseErrorBody(response) {
|
|
if (response.status > 399 && response.status < 500) {
|
|
assertReadableResponse(response);
|
|
assertApplicationJson(response);
|
|
try {
|
|
const json = await response.clone().json();
|
|
if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) {
|
|
return json;
|
|
}
|
|
} catch {}
|
|
}
|
|
return undefined;
|
|
}
|
|
async function checkOAuthBodyError(response, expected, label) {
|
|
if (response.status !== expected) {
|
|
checkAuthenticationChallenges(response);
|
|
let err;
|
|
if (err = await parseOAuthResponseErrorBody(response)) {
|
|
await response.body?.cancel();
|
|
throw new ResponseBodyError('server responded with an error in the response body', {
|
|
cause: err,
|
|
response
|
|
});
|
|
}
|
|
throw OPE(`"response" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);
|
|
}
|
|
}
|
|
function assertDPoP(option) {
|
|
if (!branded.has(option)) {
|
|
throw CodedTypeError('"options.DPoP" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
}
|
|
async function resourceRequest(accessToken, method, url, headers, body, options) {
|
|
assertString(accessToken, '"accessToken"');
|
|
if (!(url instanceof URL)) {
|
|
throw CodedTypeError('"url" must be an instance of URL', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
checkProtocol(url, options?.[allowInsecureRequests] !== true);
|
|
headers = prepareHeaders(headers);
|
|
if (options?.DPoP) {
|
|
assertDPoP(options.DPoP);
|
|
await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);
|
|
}
|
|
headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${accessToken}`);
|
|
const response = await (options?.[customFetch] || fetch)(url.href, {
|
|
duplex: looseInstanceOf(body, ReadableStream) ? 'half' : undefined,
|
|
body,
|
|
headers: Object.fromEntries(headers.entries()),
|
|
method,
|
|
redirect: 'manual',
|
|
signal: signal(url, options?.signal)
|
|
});
|
|
options?.DPoP?.cacheNonce(response, url);
|
|
return response;
|
|
}
|
|
async function protectedResourceRequest(accessToken, method, url, headers, body, options) {
|
|
const response = await resourceRequest(accessToken, method, url, headers, body, options);
|
|
checkAuthenticationChallenges(response);
|
|
return response;
|
|
}
|
|
async function userInfoRequest(as, client, accessToken, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
const url = resolveEndpoint(as, 'userinfo_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const headers = prepareHeaders(options?.headers);
|
|
if (client.userinfo_signed_response_alg) {
|
|
headers.set('accept', 'application/jwt');
|
|
} else {
|
|
headers.set('accept', 'application/json');
|
|
headers.append('accept', 'application/jwt');
|
|
}
|
|
return resourceRequest(accessToken, 'GET', url, headers, null, {
|
|
...options,
|
|
[clockSkew]: getClockSkew(client)
|
|
});
|
|
}
|
|
let jwksMap;
|
|
function setJwksCache(as, jwks, uat, cache) {
|
|
jwksMap ||= new WeakMap();
|
|
jwksMap.set(as, {
|
|
jwks,
|
|
uat,
|
|
get age () {
|
|
return epochTime() - this.uat;
|
|
}
|
|
});
|
|
if (cache) {
|
|
Object.assign(cache, {
|
|
jwks: structuredClone(jwks),
|
|
uat
|
|
});
|
|
}
|
|
}
|
|
function isFreshJwksCache(input) {
|
|
if (typeof input !== 'object' || input === null) {
|
|
return false;
|
|
}
|
|
if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {
|
|
return false;
|
|
}
|
|
if (!('jwks' in input) || !isJsonObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isJsonObject)) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
function clearJwksCache(as, cache) {
|
|
jwksMap?.delete(as);
|
|
delete cache?.jwks;
|
|
delete cache?.uat;
|
|
}
|
|
async function getPublicSigKeyFromIssuerJwksUri(as, options, header) {
|
|
const { alg, kid } = header;
|
|
checkSupportedJwsAlg(header);
|
|
if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {
|
|
setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);
|
|
}
|
|
let jwks;
|
|
let age;
|
|
if (jwksMap?.has(as)) {
|
|
;
|
|
({ jwks, age } = jwksMap.get(as));
|
|
if (age >= 300) {
|
|
clearJwksCache(as, options?.[jwksCache]);
|
|
return getPublicSigKeyFromIssuerJwksUri(as, options, header);
|
|
}
|
|
} else {
|
|
jwks = await jwksRequest(as, options).then(processJwksResponse);
|
|
age = 0;
|
|
setJwksCache(as, jwks, epochTime(), options?.[jwksCache]);
|
|
}
|
|
let kty;
|
|
switch(alg.slice(0, 2)){
|
|
case 'RS':
|
|
case 'PS':
|
|
kty = 'RSA';
|
|
break;
|
|
case 'ES':
|
|
kty = 'EC';
|
|
break;
|
|
case 'Ed':
|
|
kty = 'OKP';
|
|
break;
|
|
case 'ML':
|
|
kty = 'AKP';
|
|
break;
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported JWS algorithm', {
|
|
cause: {
|
|
alg
|
|
}
|
|
});
|
|
}
|
|
const candidates = jwks.keys.filter((jwk)=>{
|
|
if (jwk.kty !== kty) {
|
|
return false;
|
|
}
|
|
if (kid !== undefined && kid !== jwk.kid) {
|
|
return false;
|
|
}
|
|
if (jwk.alg !== undefined && alg !== jwk.alg) {
|
|
return false;
|
|
}
|
|
if (jwk.use !== undefined && jwk.use !== 'sig') {
|
|
return false;
|
|
}
|
|
if (jwk.key_ops?.includes('verify') === false) {
|
|
return false;
|
|
}
|
|
switch(true){
|
|
case alg === 'ES256' && jwk.crv !== 'P-256':
|
|
case alg === 'ES384' && jwk.crv !== 'P-384':
|
|
case alg === 'ES512' && jwk.crv !== 'P-521':
|
|
case alg === 'Ed25519' && jwk.crv !== 'Ed25519':
|
|
case alg === 'EdDSA' && jwk.crv !== 'Ed25519':
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
const { 0: jwk, length } = candidates;
|
|
if (!length) {
|
|
if (age >= 60) {
|
|
clearJwksCache(as, options?.[jwksCache]);
|
|
return getPublicSigKeyFromIssuerJwksUri(as, options, header);
|
|
}
|
|
throw OPE('error when selecting a JWT verification key, no applicable keys found', KEY_SELECTION, {
|
|
header,
|
|
candidates,
|
|
jwks_uri: new URL(as.jwks_uri)
|
|
});
|
|
}
|
|
if (length !== 1) {
|
|
throw OPE('error when selecting a JWT verification key, multiple applicable keys found, a "kid" JWT Header Parameter is required', KEY_SELECTION, {
|
|
header,
|
|
candidates,
|
|
jwks_uri: new URL(as.jwks_uri)
|
|
});
|
|
}
|
|
return importJwk(alg, jwk);
|
|
}
|
|
const skipSubjectCheck = Symbol();
|
|
function getContentType(input) {
|
|
return input.headers.get('content-type')?.split(';')[0];
|
|
}
|
|
async function processUserInfoResponse(as, client, expectedSubject, response, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
checkAuthenticationChallenges(response);
|
|
if (response.status !== 200) {
|
|
throw OPE('"response" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
|
|
}
|
|
assertReadableResponse(response);
|
|
let json;
|
|
if (getContentType(response) === 'application/jwt') {
|
|
const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt]).then(validateOptionalAudience.bind(undefined, client.client_id)).then(validateOptionalIssuer.bind(undefined, as));
|
|
jwtRefs.set(response, jwt);
|
|
json = claims;
|
|
} else {
|
|
if (client.userinfo_signed_response_alg) {
|
|
throw OPE('JWT UserInfo Response expected', JWT_USERINFO_EXPECTED, response);
|
|
}
|
|
json = await getResponseJsonBody(response);
|
|
}
|
|
assertString(json.sub, '"response" body "sub" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
switch(expectedSubject){
|
|
case skipSubjectCheck:
|
|
break;
|
|
default:
|
|
assertString(expectedSubject, '"expectedSubject"');
|
|
if (json.sub !== expectedSubject) {
|
|
throw OPE('unexpected "response" body "sub" property value', JSON_ATTRIBUTE_COMPARISON, {
|
|
expected: expectedSubject,
|
|
body: json,
|
|
attribute: 'sub'
|
|
});
|
|
}
|
|
}
|
|
return json;
|
|
}
|
|
async function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {
|
|
await clientAuthentication(as, client, body, headers);
|
|
headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
|
|
return (options?.[customFetch] || fetch)(url.href, {
|
|
body,
|
|
headers: Object.fromEntries(headers.entries()),
|
|
method: 'POST',
|
|
redirect: 'manual',
|
|
signal: signal(url, options?.signal)
|
|
});
|
|
}
|
|
async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
|
|
const url = resolveEndpoint(as, 'token_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
parameters.set('grant_type', grantType);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
if (options?.DPoP !== undefined) {
|
|
assertDPoP(options.DPoP);
|
|
await options.DPoP.addProof(url, headers, 'POST');
|
|
}
|
|
const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);
|
|
options?.DPoP?.cacheNonce(response, url);
|
|
return response;
|
|
}
|
|
async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
assertString(refreshToken, '"refreshToken"');
|
|
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
parameters.set('refresh_token', refreshToken);
|
|
return tokenEndpointRequest(as, client, clientAuthentication, 'refresh_token', parameters, options);
|
|
}
|
|
const idTokenClaims = new WeakMap();
|
|
const jwtRefs = new WeakMap();
|
|
function getValidatedIdTokenClaims(ref) {
|
|
if (!ref.id_token) {
|
|
return undefined;
|
|
}
|
|
const claims = idTokenClaims.get(ref);
|
|
if (!claims) {
|
|
throw CodedTypeError('"ref" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
return claims;
|
|
}
|
|
async function validateApplicationLevelSignature(as, ref, options) {
|
|
assertAs(as);
|
|
if (!jwtRefs.has(ref)) {
|
|
throw CodedTypeError('"ref" does not contain a processed JWT Response to verify the signature of', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwtRefs.get(ref).split('.');
|
|
const header = JSON.parse(buf(b64u(protectedHeader)));
|
|
if (header.alg.startsWith('HS')) {
|
|
throw new UnsupportedOperationError('unsupported JWS algorithm', {
|
|
cause: {
|
|
alg: header.alg
|
|
}
|
|
});
|
|
}
|
|
let key;
|
|
key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);
|
|
await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));
|
|
}
|
|
async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 200, 'Token Endpoint');
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.access_token, '"response" body "access_token" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
assertString(json.token_type, '"response" body "token_type" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
json.token_type = json.token_type.toLowerCase();
|
|
if (json.expires_in !== undefined) {
|
|
let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;
|
|
assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
json.expires_in = expiresIn;
|
|
}
|
|
if (json.refresh_token !== undefined) {
|
|
assertString(json.refresh_token, '"response" body "refresh_token" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
if (json.scope !== undefined && typeof json.scope !== 'string') {
|
|
throw OPE('"response" body "scope" property must be a string', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
if (json.id_token !== undefined) {
|
|
assertString(json.id_token, '"response" body "id_token" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
const requiredClaims = [
|
|
'aud',
|
|
'exp',
|
|
'iat',
|
|
'iss',
|
|
'sub'
|
|
];
|
|
if (client.require_auth_time === true) {
|
|
requiredClaims.push('auth_time');
|
|
}
|
|
if (client.default_max_age !== undefined) {
|
|
assertNumber(client.default_max_age, true, '"client.default_max_age"');
|
|
requiredClaims.push('auth_time');
|
|
}
|
|
if (additionalRequiredIdTokenClaims?.length) {
|
|
requiredClaims.push(...additionalRequiredIdTokenClaims);
|
|
}
|
|
const { claims, jwt } = await validateJwt(json.id_token, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), decryptFn).then(validatePresence.bind(undefined, requiredClaims)).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, client.client_id));
|
|
if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
|
|
if (claims.azp === undefined) {
|
|
throw OPE('ID Token "aud" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, {
|
|
claims,
|
|
claim: 'aud'
|
|
});
|
|
}
|
|
if (claims.azp !== client.client_id) {
|
|
throw OPE('unexpected ID Token "azp" (authorized party) claim value', JWT_CLAIM_COMPARISON, {
|
|
expected: client.client_id,
|
|
claims,
|
|
claim: 'azp'
|
|
});
|
|
}
|
|
}
|
|
if (claims.auth_time !== undefined) {
|
|
assertNumber(claims.auth_time, true, 'ID Token "auth_time" (authentication time)', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
jwtRefs.set(response, jwt);
|
|
idTokenClaims.set(json, claims);
|
|
}
|
|
if (recognizedTokenTypes?.[json.token_type] !== undefined) {
|
|
recognizedTokenTypes[json.token_type](response, json);
|
|
} else if (json.token_type !== 'dpop' && json.token_type !== 'bearer') {
|
|
throw new UnsupportedOperationError('unsupported `token_type` value', {
|
|
cause: {
|
|
body: json
|
|
}
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
function checkAuthenticationChallenges(response) {
|
|
let challenges;
|
|
if (challenges = parseWwwAuthenticateChallenges(response)) {
|
|
throw new WWWAuthenticateChallengeError('server responded with a challenge in the WWW-Authenticate HTTP Header', {
|
|
cause: challenges,
|
|
response
|
|
});
|
|
}
|
|
}
|
|
async function processRefreshTokenResponse(as, client, response, options) {
|
|
return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
}
|
|
function validateOptionalAudience(expected, result) {
|
|
if (result.claims.aud !== undefined) {
|
|
return validateAudience(expected, result);
|
|
}
|
|
return result;
|
|
}
|
|
function validateAudience(expected, result) {
|
|
if (Array.isArray(result.claims.aud)) {
|
|
if (!result.claims.aud.includes(expected)) {
|
|
throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
|
|
expected,
|
|
claims: result.claims,
|
|
claim: 'aud'
|
|
});
|
|
}
|
|
} else if (result.claims.aud !== expected) {
|
|
throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
|
|
expected,
|
|
claims: result.claims,
|
|
claim: 'aud'
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
function validateOptionalIssuer(as, result) {
|
|
if (result.claims.iss !== undefined) {
|
|
return validateIssuer(as, result);
|
|
}
|
|
return result;
|
|
}
|
|
function validateIssuer(as, result) {
|
|
const expected = as[_expectedIssuer]?.(result) ?? as.issuer;
|
|
if (result.claims.iss !== expected) {
|
|
throw OPE('unexpected JWT "iss" (issuer) claim value', JWT_CLAIM_COMPARISON, {
|
|
expected,
|
|
claims: result.claims,
|
|
claim: 'iss'
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
const branded = new WeakSet();
|
|
function brand(searchParams) {
|
|
branded.add(searchParams);
|
|
return searchParams;
|
|
}
|
|
const nopkce = Symbol();
|
|
async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!branded.has(callbackParameters)) {
|
|
throw CodedTypeError('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
assertString(redirectUri, '"redirectUri"');
|
|
const code = getURLSearchParameter(callbackParameters, 'code');
|
|
if (!code) {
|
|
throw OPE('no authorization code in "callbackParameters"', INVALID_RESPONSE);
|
|
}
|
|
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
parameters.set('redirect_uri', redirectUri);
|
|
parameters.set('code', code);
|
|
if (codeVerifier !== nopkce) {
|
|
assertString(codeVerifier, '"codeVerifier"');
|
|
parameters.set('code_verifier', codeVerifier);
|
|
}
|
|
return tokenEndpointRequest(as, client, clientAuthentication, 'authorization_code', parameters, options);
|
|
}
|
|
const jwtClaimNames = {
|
|
aud: 'audience',
|
|
c_hash: 'code hash',
|
|
client_id: 'client id',
|
|
exp: 'expiration time',
|
|
iat: 'issued at',
|
|
iss: 'issuer',
|
|
jti: 'jwt id',
|
|
nonce: 'nonce',
|
|
s_hash: 'state hash',
|
|
sub: 'subject',
|
|
ath: 'access token hash',
|
|
htm: 'http method',
|
|
htu: 'http uri',
|
|
cnf: 'confirmation',
|
|
auth_time: 'authentication time'
|
|
};
|
|
function validatePresence(required, result) {
|
|
for (const claim of required){
|
|
if (result.claims[claim] === undefined) {
|
|
throw OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {
|
|
claims: result.claims
|
|
});
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
const expectNoNonce = Symbol();
|
|
const skipAuthTimeCheck = Symbol();
|
|
async function processAuthorizationCodeResponse(as, client, response, options) {
|
|
if (typeof options?.expectedNonce === 'string' || typeof options?.maxAge === 'number' || options?.requireIdToken) {
|
|
return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);
|
|
}
|
|
return processAuthorizationCodeOAuth2Response(as, client, response, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
}
|
|
async function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {
|
|
const additionalRequiredClaims = [];
|
|
switch(expectedNonce){
|
|
case undefined:
|
|
expectedNonce = expectNoNonce;
|
|
break;
|
|
case expectNoNonce:
|
|
break;
|
|
default:
|
|
assertString(expectedNonce, '"expectedNonce" argument');
|
|
additionalRequiredClaims.push('nonce');
|
|
}
|
|
maxAge ??= client.default_max_age;
|
|
switch(maxAge){
|
|
case undefined:
|
|
maxAge = skipAuthTimeCheck;
|
|
break;
|
|
case skipAuthTimeCheck:
|
|
break;
|
|
default:
|
|
assertNumber(maxAge, true, '"maxAge" argument');
|
|
additionalRequiredClaims.push('auth_time');
|
|
}
|
|
const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);
|
|
assertString(result.id_token, '"response" body "id_token" property', INVALID_RESPONSE, {
|
|
body: result
|
|
});
|
|
const claims = getValidatedIdTokenClaims(result);
|
|
if (maxAge !== skipAuthTimeCheck) {
|
|
const now = epochTime() + getClockSkew(client);
|
|
const tolerance = getClockTolerance(client);
|
|
if (claims.auth_time + maxAge < now - tolerance) {
|
|
throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, {
|
|
claims,
|
|
now,
|
|
tolerance,
|
|
claim: 'auth_time'
|
|
});
|
|
}
|
|
}
|
|
if (expectedNonce === expectNoNonce) {
|
|
if (claims.nonce !== undefined) {
|
|
throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
|
|
expected: undefined,
|
|
claims,
|
|
claim: 'nonce'
|
|
});
|
|
}
|
|
} else if (claims.nonce !== expectedNonce) {
|
|
throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
|
|
expected: expectedNonce,
|
|
claims,
|
|
claim: 'nonce'
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
async function processAuthorizationCodeOAuth2Response(as, client, response, decryptFn, recognizedTokenTypes) {
|
|
const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);
|
|
const claims = getValidatedIdTokenClaims(result);
|
|
if (claims) {
|
|
if (client.default_max_age !== undefined) {
|
|
assertNumber(client.default_max_age, true, '"client.default_max_age"');
|
|
const now = epochTime() + getClockSkew(client);
|
|
const tolerance = getClockTolerance(client);
|
|
if (claims.auth_time + client.default_max_age < now - tolerance) {
|
|
throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, {
|
|
claims,
|
|
now,
|
|
tolerance,
|
|
claim: 'auth_time'
|
|
});
|
|
}
|
|
}
|
|
if (claims.nonce !== undefined) {
|
|
throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
|
|
expected: undefined,
|
|
claims,
|
|
claim: 'nonce'
|
|
});
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
const WWW_AUTHENTICATE_CHALLENGE = 'OAUTH_WWW_AUTHENTICATE_CHALLENGE';
|
|
const RESPONSE_BODY_ERROR = 'OAUTH_RESPONSE_BODY_ERROR';
|
|
const UNSUPPORTED_OPERATION = 'OAUTH_UNSUPPORTED_OPERATION';
|
|
const AUTHORIZATION_RESPONSE_ERROR = 'OAUTH_AUTHORIZATION_RESPONSE_ERROR';
|
|
const JWT_USERINFO_EXPECTED = 'OAUTH_JWT_USERINFO_EXPECTED';
|
|
const PARSE_ERROR = 'OAUTH_PARSE_ERROR';
|
|
const INVALID_RESPONSE = 'OAUTH_INVALID_RESPONSE';
|
|
const INVALID_REQUEST = 'OAUTH_INVALID_REQUEST';
|
|
const RESPONSE_IS_NOT_JSON = 'OAUTH_RESPONSE_IS_NOT_JSON';
|
|
const RESPONSE_IS_NOT_CONFORM = 'OAUTH_RESPONSE_IS_NOT_CONFORM';
|
|
const HTTP_REQUEST_FORBIDDEN = 'OAUTH_HTTP_REQUEST_FORBIDDEN';
|
|
const REQUEST_PROTOCOL_FORBIDDEN = 'OAUTH_REQUEST_PROTOCOL_FORBIDDEN';
|
|
const JWT_TIMESTAMP_CHECK = 'OAUTH_JWT_TIMESTAMP_CHECK_FAILED';
|
|
const JWT_CLAIM_COMPARISON = 'OAUTH_JWT_CLAIM_COMPARISON_FAILED';
|
|
const JSON_ATTRIBUTE_COMPARISON = 'OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED';
|
|
const KEY_SELECTION = 'OAUTH_KEY_SELECTION_FAILED';
|
|
const MISSING_SERVER_METADATA = 'OAUTH_MISSING_SERVER_METADATA';
|
|
const INVALID_SERVER_METADATA = 'OAUTH_INVALID_SERVER_METADATA';
|
|
function checkJwtType(expected, result) {
|
|
if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) {
|
|
throw OPE('unexpected JWT "typ" header parameter value', INVALID_RESPONSE, {
|
|
header: result.header
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
return tokenEndpointRequest(as, client, clientAuthentication, 'client_credentials', new URLSearchParams(parameters), options);
|
|
}
|
|
async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
assertString(grantType, '"grantType"');
|
|
return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);
|
|
}
|
|
async function processGenericTokenEndpointResponse(as, client, response, options) {
|
|
return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
}
|
|
async function processClientCredentialsResponse(as, client, response, options) {
|
|
return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
}
|
|
async function revocationRequest(as, client, clientAuthentication, token, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
assertString(token, '"token"');
|
|
const url = resolveEndpoint(as, 'revocation_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const body = new URLSearchParams(options?.additionalParameters);
|
|
body.set('token', token);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.delete('accept');
|
|
return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
}
|
|
async function processRevocationResponse(response) {
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 200, 'Revocation Endpoint');
|
|
return undefined;
|
|
}
|
|
function assertReadableResponse(response) {
|
|
if (response.bodyUsed) {
|
|
throw CodedTypeError('"response" body has been used already', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
}
|
|
async function introspectionRequest(as, client, clientAuthentication, token, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
assertString(token, '"token"');
|
|
const url = resolveEndpoint(as, 'introspection_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const body = new URLSearchParams(options?.additionalParameters);
|
|
body.set('token', token);
|
|
const headers = prepareHeaders(options?.headers);
|
|
if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) {
|
|
headers.set('accept', 'application/token-introspection+jwt');
|
|
} else {
|
|
headers.set('accept', 'application/json');
|
|
}
|
|
return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
}
|
|
async function processIntrospectionResponse(as, client, response, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 200, 'Introspection Endpoint');
|
|
let json;
|
|
if (getContentType(response) === 'application/token-introspection+jwt') {
|
|
assertReadableResponse(response);
|
|
const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt]).then(checkJwtType.bind(undefined, 'token-introspection+jwt')).then(validatePresence.bind(undefined, [
|
|
'aud',
|
|
'iat',
|
|
'iss'
|
|
])).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, client.client_id));
|
|
jwtRefs.set(response, jwt);
|
|
if (!isJsonObject(claims.token_introspection)) {
|
|
throw OPE('JWT "token_introspection" claim must be a JSON object', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
json = claims.token_introspection;
|
|
} else {
|
|
assertReadableResponse(response);
|
|
json = await getResponseJsonBody(response);
|
|
}
|
|
if (typeof json.active !== 'boolean') {
|
|
throw OPE('"response" body "active" property must be a boolean', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
async function jwksRequest(as, options) {
|
|
assertAs(as);
|
|
const url = resolveEndpoint(as, 'jwks_uri', false, options?.[allowInsecureRequests] !== true);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
headers.append('accept', 'application/jwk-set+json');
|
|
return (options?.[customFetch] || fetch)(url.href, {
|
|
body: undefined,
|
|
headers: Object.fromEntries(headers.entries()),
|
|
method: 'GET',
|
|
redirect: 'manual',
|
|
signal: signal(url, options?.signal)
|
|
});
|
|
}
|
|
async function processJwksResponse(response) {
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
if (response.status !== 200) {
|
|
throw OPE('"response" is not a conform JSON Web Key Set response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
|
|
}
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response, (response)=>assertContentTypes(response, 'application/json', 'application/jwk-set+json'));
|
|
if (!Array.isArray(json.keys)) {
|
|
throw OPE('"response" body "keys" property must be an array', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
if (!Array.prototype.every.call(json.keys, isJsonObject)) {
|
|
throw OPE('"response" body "keys" property members must be JWK formatted objects', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
function supported(alg) {
|
|
switch(alg){
|
|
case 'PS256':
|
|
case 'ES256':
|
|
case 'RS256':
|
|
case 'PS384':
|
|
case 'ES384':
|
|
case 'RS384':
|
|
case 'PS512':
|
|
case 'ES512':
|
|
case 'RS512':
|
|
case 'Ed25519':
|
|
case 'EdDSA':
|
|
case 'ML-DSA-44':
|
|
case 'ML-DSA-65':
|
|
case 'ML-DSA-87':
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
function checkSupportedJwsAlg(header) {
|
|
if (!supported(header.alg)) {
|
|
throw new UnsupportedOperationError('unsupported JWS "alg" identifier', {
|
|
cause: {
|
|
alg: header.alg
|
|
}
|
|
});
|
|
}
|
|
}
|
|
function checkRsaKeyAlgorithm(key) {
|
|
const { algorithm } = key;
|
|
if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) {
|
|
throw new UnsupportedOperationError(`unsupported ${algorithm.name} modulusLength`, {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
function ecdsaHashName(key) {
|
|
const { algorithm } = key;
|
|
switch(algorithm.namedCurve){
|
|
case 'P-256':
|
|
return 'SHA-256';
|
|
case 'P-384':
|
|
return 'SHA-384';
|
|
case 'P-521':
|
|
return 'SHA-512';
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported ECDSA namedCurve', {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
function keyToSubtle(key) {
|
|
switch(key.algorithm.name){
|
|
case 'ECDSA':
|
|
return {
|
|
name: key.algorithm.name,
|
|
hash: ecdsaHashName(key)
|
|
};
|
|
case 'RSA-PSS':
|
|
{
|
|
checkRsaKeyAlgorithm(key);
|
|
switch(key.algorithm.hash.name){
|
|
case 'SHA-256':
|
|
case 'SHA-384':
|
|
case 'SHA-512':
|
|
return {
|
|
name: key.algorithm.name,
|
|
saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3
|
|
};
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported RSA-PSS hash name', {
|
|
cause: key
|
|
});
|
|
}
|
|
}
|
|
case 'RSASSA-PKCS1-v1_5':
|
|
checkRsaKeyAlgorithm(key);
|
|
return key.algorithm.name;
|
|
case 'ML-DSA-44':
|
|
case 'ML-DSA-65':
|
|
case 'ML-DSA-87':
|
|
case 'Ed25519':
|
|
return key.algorithm.name;
|
|
}
|
|
throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', {
|
|
cause: key
|
|
});
|
|
}
|
|
async function validateJwsSignature(protectedHeader, payload, key, signature) {
|
|
const data = buf(`${protectedHeader}.${payload}`);
|
|
const algorithm = keyToSubtle(key);
|
|
const verified = await crypto.subtle.verify(algorithm, key, signature, data);
|
|
if (!verified) {
|
|
throw OPE('JWT signature verification failed', INVALID_RESPONSE, {
|
|
key,
|
|
data,
|
|
signature,
|
|
algorithm
|
|
});
|
|
}
|
|
}
|
|
async function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {
|
|
let { 0: protectedHeader, 1: payload, length } = jws.split('.');
|
|
if (length === 5) {
|
|
if (decryptJwt !== undefined) {
|
|
jws = await decryptJwt(jws);
|
|
({ 0: protectedHeader, 1: payload, length } = jws.split('.'));
|
|
} else {
|
|
throw new UnsupportedOperationError('JWE decryption is not configured', {
|
|
cause: jws
|
|
});
|
|
}
|
|
}
|
|
if (length !== 3) {
|
|
throw OPE('Invalid JWT', INVALID_RESPONSE, jws);
|
|
}
|
|
let header;
|
|
try {
|
|
header = JSON.parse(buf(b64u(protectedHeader)));
|
|
} catch (cause) {
|
|
throw OPE('failed to parse JWT Header body as base64url encoded JSON', PARSE_ERROR, cause);
|
|
}
|
|
if (!isJsonObject(header)) {
|
|
throw OPE('JWT Header must be a top level object', INVALID_RESPONSE, jws);
|
|
}
|
|
checkAlg(header);
|
|
if (header.crit !== undefined) {
|
|
throw new UnsupportedOperationError('no JWT "crit" header parameter extensions are supported', {
|
|
cause: {
|
|
header
|
|
}
|
|
});
|
|
}
|
|
let claims;
|
|
try {
|
|
claims = JSON.parse(buf(b64u(payload)));
|
|
} catch (cause) {
|
|
throw OPE('failed to parse JWT Payload body as base64url encoded JSON', PARSE_ERROR, cause);
|
|
}
|
|
if (!isJsonObject(claims)) {
|
|
throw OPE('JWT Payload must be a top level object', INVALID_RESPONSE, jws);
|
|
}
|
|
const now = epochTime() + clockSkew;
|
|
if (claims.exp !== undefined) {
|
|
if (typeof claims.exp !== 'number') {
|
|
throw OPE('unexpected JWT "exp" (expiration time) claim type', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
if (claims.exp <= now - clockTolerance) {
|
|
throw OPE('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, {
|
|
claims,
|
|
now,
|
|
tolerance: clockTolerance,
|
|
claim: 'exp'
|
|
});
|
|
}
|
|
}
|
|
if (claims.iat !== undefined) {
|
|
if (typeof claims.iat !== 'number') {
|
|
throw OPE('unexpected JWT "iat" (issued at) claim type', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
}
|
|
if (claims.iss !== undefined) {
|
|
if (typeof claims.iss !== 'string') {
|
|
throw OPE('unexpected JWT "iss" (issuer) claim type', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
}
|
|
if (claims.nbf !== undefined) {
|
|
if (typeof claims.nbf !== 'number') {
|
|
throw OPE('unexpected JWT "nbf" (not before) claim type', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
if (claims.nbf > now + clockTolerance) {
|
|
throw OPE('unexpected JWT "nbf" (not before) claim value', JWT_TIMESTAMP_CHECK, {
|
|
claims,
|
|
now,
|
|
tolerance: clockTolerance,
|
|
claim: 'nbf'
|
|
});
|
|
}
|
|
}
|
|
if (claims.aud !== undefined) {
|
|
if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) {
|
|
throw OPE('unexpected JWT "aud" (audience) claim type', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
}
|
|
return {
|
|
header,
|
|
claims,
|
|
jwt: jws
|
|
};
|
|
}
|
|
async function validateJwtAuthResponse(as, client, parameters, expectedState, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (parameters instanceof URL) {
|
|
parameters = parameters.searchParams;
|
|
}
|
|
if (!(parameters instanceof URLSearchParams)) {
|
|
throw CodedTypeError('"parameters" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
const response = getURLSearchParameter(parameters, 'response');
|
|
if (!response) {
|
|
throw OPE('"parameters" does not contain a JARM response', INVALID_RESPONSE);
|
|
}
|
|
const { claims, header, jwt } = await validateJwt(response, checkSigningAlgorithm.bind(undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt]).then(validatePresence.bind(undefined, [
|
|
'aud',
|
|
'exp',
|
|
'iss'
|
|
])).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, client.client_id));
|
|
const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');
|
|
const signature = b64u(encodedSignature);
|
|
const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);
|
|
await validateJwsSignature(protectedHeader, payload, key, signature);
|
|
const result = new URLSearchParams();
|
|
for (const [key, value] of Object.entries(claims)){
|
|
if (typeof value === 'string' && key !== 'aud') {
|
|
result.set(key, value);
|
|
}
|
|
}
|
|
return validateAuthResponse(as, client, result, expectedState);
|
|
}
|
|
async function idTokenHash(data, header, claimName) {
|
|
let algorithm;
|
|
switch(header.alg){
|
|
case 'RS256':
|
|
case 'PS256':
|
|
case 'ES256':
|
|
algorithm = 'SHA-256';
|
|
break;
|
|
case 'RS384':
|
|
case 'PS384':
|
|
case 'ES384':
|
|
algorithm = 'SHA-384';
|
|
break;
|
|
case 'RS512':
|
|
case 'PS512':
|
|
case 'ES512':
|
|
case 'Ed25519':
|
|
case 'EdDSA':
|
|
algorithm = 'SHA-512';
|
|
break;
|
|
case 'ML-DSA-44':
|
|
case 'ML-DSA-65':
|
|
case 'ML-DSA-87':
|
|
algorithm = {
|
|
name: 'cSHAKE256',
|
|
length: 512,
|
|
outputLength: 512
|
|
};
|
|
break;
|
|
default:
|
|
throw new UnsupportedOperationError(`unsupported JWS algorithm for ${claimName} calculation`, {
|
|
cause: {
|
|
alg: header.alg
|
|
}
|
|
});
|
|
}
|
|
const digest = await crypto.subtle.digest(algorithm, buf(data));
|
|
return b64u(digest.slice(0, digest.byteLength / 2));
|
|
}
|
|
async function idTokenHashMatches(data, actual, header, claimName) {
|
|
const expected = await idTokenHash(data, header, claimName);
|
|
return actual === expected;
|
|
}
|
|
async function validateDetachedSignatureResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {
|
|
return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, true);
|
|
}
|
|
async function validateCodeIdTokenResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {
|
|
return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, false);
|
|
}
|
|
async function consumeStream(request) {
|
|
if (request.bodyUsed) {
|
|
throw CodedTypeError('form_post Request instances must contain a readable body', ERR_INVALID_ARG_VALUE, {
|
|
cause: request
|
|
});
|
|
}
|
|
return request.text();
|
|
}
|
|
async function formPostResponse(request) {
|
|
if (request.method !== 'POST') {
|
|
throw CodedTypeError('form_post responses are expected to use the POST method', ERR_INVALID_ARG_VALUE, {
|
|
cause: request
|
|
});
|
|
}
|
|
if (getContentType(request) !== 'application/x-www-form-urlencoded') {
|
|
throw CodedTypeError('form_post responses are expected to use the application/x-www-form-urlencoded content-type', ERR_INVALID_ARG_VALUE, {
|
|
cause: request
|
|
});
|
|
}
|
|
return consumeStream(request);
|
|
}
|
|
async function validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, fapi) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (parameters instanceof URL) {
|
|
if (!parameters.hash.length) {
|
|
throw CodedTypeError('"parameters" as an instance of URL must contain a hash (fragment) with the Authorization Response parameters', ERR_INVALID_ARG_VALUE);
|
|
}
|
|
parameters = new URLSearchParams(parameters.hash.slice(1));
|
|
} else if (looseInstanceOf(parameters, Request)) {
|
|
parameters = new URLSearchParams(await formPostResponse(parameters));
|
|
} else if (parameters instanceof URLSearchParams) {
|
|
parameters = new URLSearchParams(parameters);
|
|
} else {
|
|
throw CodedTypeError('"parameters" must be an instance of URLSearchParams, URL, or Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
const id_token = getURLSearchParameter(parameters, 'id_token');
|
|
parameters.delete('id_token');
|
|
switch(expectedState){
|
|
case undefined:
|
|
case expectNoState:
|
|
break;
|
|
default:
|
|
assertString(expectedState, '"expectedState" argument');
|
|
}
|
|
const result = validateAuthResponse({
|
|
...as,
|
|
authorization_response_iss_parameter_supported: false
|
|
}, client, parameters, expectedState);
|
|
if (!id_token) {
|
|
throw OPE('"parameters" does not contain an ID Token', INVALID_RESPONSE);
|
|
}
|
|
const code = getURLSearchParameter(parameters, 'code');
|
|
if (!code) {
|
|
throw OPE('"parameters" does not contain an Authorization Code', INVALID_RESPONSE);
|
|
}
|
|
const requiredClaims = [
|
|
'aud',
|
|
'exp',
|
|
'iat',
|
|
'iss',
|
|
'sub',
|
|
'nonce',
|
|
'c_hash'
|
|
];
|
|
const state = parameters.get('state');
|
|
if (fapi && (typeof expectedState === 'string' || state !== null)) {
|
|
requiredClaims.push('s_hash');
|
|
}
|
|
if (maxAge !== undefined) {
|
|
assertNumber(maxAge, true, '"maxAge" argument');
|
|
} else if (client.default_max_age !== undefined) {
|
|
assertNumber(client.default_max_age, true, '"client.default_max_age"');
|
|
}
|
|
maxAge ??= client.default_max_age ?? skipAuthTimeCheck;
|
|
if (client.require_auth_time || maxAge !== skipAuthTimeCheck) {
|
|
requiredClaims.push('auth_time');
|
|
}
|
|
const { claims, header, jwt } = await validateJwt(id_token, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt]).then(validatePresence.bind(undefined, requiredClaims)).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, client.client_id));
|
|
const clockSkew = getClockSkew(client);
|
|
const now = epochTime() + clockSkew;
|
|
if (claims.iat < now - 3600) {
|
|
throw OPE('unexpected JWT "iat" (issued at) claim value, it is too far in the past', JWT_TIMESTAMP_CHECK, {
|
|
now,
|
|
claims,
|
|
claim: 'iat'
|
|
});
|
|
}
|
|
assertString(claims.c_hash, 'ID Token "c_hash" (code hash) claim value', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
if (claims.auth_time !== undefined) {
|
|
assertNumber(claims.auth_time, true, 'ID Token "auth_time" (authentication time)', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
}
|
|
if (maxAge !== skipAuthTimeCheck) {
|
|
const now = epochTime() + getClockSkew(client);
|
|
const tolerance = getClockTolerance(client);
|
|
if (claims.auth_time + maxAge < now - tolerance) {
|
|
throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, {
|
|
claims,
|
|
now,
|
|
tolerance,
|
|
claim: 'auth_time'
|
|
});
|
|
}
|
|
}
|
|
assertString(expectedNonce, '"expectedNonce" argument');
|
|
if (claims.nonce !== expectedNonce) {
|
|
throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
|
|
expected: expectedNonce,
|
|
claims,
|
|
claim: 'nonce'
|
|
});
|
|
}
|
|
if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
|
|
if (claims.azp === undefined) {
|
|
throw OPE('ID Token "aud" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, {
|
|
claims,
|
|
claim: 'aud'
|
|
});
|
|
}
|
|
if (claims.azp !== client.client_id) {
|
|
throw OPE('unexpected ID Token "azp" (authorized party) claim value', JWT_CLAIM_COMPARISON, {
|
|
expected: client.client_id,
|
|
claims,
|
|
claim: 'azp'
|
|
});
|
|
}
|
|
}
|
|
const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');
|
|
const signature = b64u(encodedSignature);
|
|
const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);
|
|
await validateJwsSignature(protectedHeader, payload, key, signature);
|
|
if (await idTokenHashMatches(code, claims.c_hash, header, 'c_hash') !== true) {
|
|
throw OPE('invalid ID Token "c_hash" (code hash) claim value', JWT_CLAIM_COMPARISON, {
|
|
code,
|
|
alg: header.alg,
|
|
claim: 'c_hash',
|
|
claims
|
|
});
|
|
}
|
|
if (fapi && state !== null || claims.s_hash !== undefined) {
|
|
assertString(claims.s_hash, 'ID Token "s_hash" (state hash) claim value', INVALID_RESPONSE, {
|
|
claims
|
|
});
|
|
assertString(state, '"state" response parameter', INVALID_RESPONSE, {
|
|
parameters
|
|
});
|
|
if (await idTokenHashMatches(state, claims.s_hash, header, 's_hash') !== true) {
|
|
throw OPE('invalid ID Token "s_hash" (state hash) claim value', JWT_CLAIM_COMPARISON, {
|
|
state,
|
|
alg: header.alg,
|
|
claim: 's_hash',
|
|
claims
|
|
});
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function checkSigningAlgorithm(client, issuer, fallback, header) {
|
|
if (client !== undefined) {
|
|
if (typeof client === 'string' ? header.alg !== client : !client.includes(header.alg)) {
|
|
throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
|
|
header,
|
|
expected: client,
|
|
reason: 'client configuration'
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
if (Array.isArray(issuer)) {
|
|
if (!issuer.includes(header.alg)) {
|
|
throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
|
|
header,
|
|
expected: issuer,
|
|
reason: 'authorization server metadata'
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
if (fallback !== undefined) {
|
|
if (typeof fallback === 'string' ? header.alg !== fallback : typeof fallback === 'function' ? !fallback(header.alg) : !fallback.includes(header.alg)) {
|
|
throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
|
|
header,
|
|
expected: fallback,
|
|
reason: 'default value'
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
throw OPE('missing client or server configuration to verify used JWT "alg" header parameter', undefined, {
|
|
client,
|
|
issuer,
|
|
fallback
|
|
});
|
|
}
|
|
function getURLSearchParameter(parameters, name) {
|
|
const { 0: value, length } = parameters.getAll(name);
|
|
if (length > 1) {
|
|
throw OPE(`"${name}" parameter must be provided only once`, INVALID_RESPONSE);
|
|
}
|
|
return value;
|
|
}
|
|
const skipStateCheck = Symbol();
|
|
const expectNoState = Symbol();
|
|
function validateAuthResponse(as, client, parameters, expectedState) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (parameters instanceof URL) {
|
|
parameters = parameters.searchParams;
|
|
}
|
|
if (!(parameters instanceof URLSearchParams)) {
|
|
throw CodedTypeError('"parameters" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
if (getURLSearchParameter(parameters, 'response')) {
|
|
throw OPE('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, {
|
|
parameters
|
|
});
|
|
}
|
|
const iss = getURLSearchParameter(parameters, 'iss');
|
|
const state = getURLSearchParameter(parameters, 'state');
|
|
if (!iss && as.authorization_response_iss_parameter_supported) {
|
|
throw OPE('response parameter "iss" (issuer) missing', INVALID_RESPONSE, {
|
|
parameters
|
|
});
|
|
}
|
|
if (iss && iss !== as.issuer) {
|
|
throw OPE('unexpected "iss" (issuer) response parameter value', INVALID_RESPONSE, {
|
|
expected: as.issuer,
|
|
parameters
|
|
});
|
|
}
|
|
switch(expectedState){
|
|
case undefined:
|
|
case expectNoState:
|
|
if (state !== undefined) {
|
|
throw OPE('unexpected "state" response parameter encountered', INVALID_RESPONSE, {
|
|
expected: undefined,
|
|
parameters
|
|
});
|
|
}
|
|
break;
|
|
case skipStateCheck:
|
|
break;
|
|
default:
|
|
assertString(expectedState, '"expectedState" argument');
|
|
if (state !== expectedState) {
|
|
throw OPE(state === undefined ? 'response parameter "state" missing' : 'unexpected "state" response parameter value', INVALID_RESPONSE, {
|
|
expected: expectedState,
|
|
parameters
|
|
});
|
|
}
|
|
}
|
|
const error = getURLSearchParameter(parameters, 'error');
|
|
if (error) {
|
|
throw new AuthorizationResponseError('authorization response from the server is an error', {
|
|
cause: parameters
|
|
});
|
|
}
|
|
const id_token = getURLSearchParameter(parameters, 'id_token');
|
|
const token = getURLSearchParameter(parameters, 'token');
|
|
if (id_token !== undefined || token !== undefined) {
|
|
throw new UnsupportedOperationError('implicit and hybrid flows are not supported');
|
|
}
|
|
return brand(new URLSearchParams(parameters));
|
|
}
|
|
function algToSubtle(alg) {
|
|
switch(alg){
|
|
case 'PS256':
|
|
case 'PS384':
|
|
case 'PS512':
|
|
return {
|
|
name: 'RSA-PSS',
|
|
hash: `SHA-${alg.slice(-3)}`
|
|
};
|
|
case 'RS256':
|
|
case 'RS384':
|
|
case 'RS512':
|
|
return {
|
|
name: 'RSASSA-PKCS1-v1_5',
|
|
hash: `SHA-${alg.slice(-3)}`
|
|
};
|
|
case 'ES256':
|
|
case 'ES384':
|
|
return {
|
|
name: 'ECDSA',
|
|
namedCurve: `P-${alg.slice(-3)}`
|
|
};
|
|
case 'ES512':
|
|
return {
|
|
name: 'ECDSA',
|
|
namedCurve: 'P-521'
|
|
};
|
|
case 'EdDSA':
|
|
return 'Ed25519';
|
|
case 'Ed25519':
|
|
case 'ML-DSA-44':
|
|
case 'ML-DSA-65':
|
|
case 'ML-DSA-87':
|
|
return alg;
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported JWS algorithm', {
|
|
cause: {
|
|
alg
|
|
}
|
|
});
|
|
}
|
|
}
|
|
async function importJwk(alg, jwk) {
|
|
const { ext, key_ops, use, ...key } = jwk;
|
|
return crypto.subtle.importKey('jwk', key, algToSubtle(alg), true, [
|
|
'verify'
|
|
]);
|
|
}
|
|
async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
const url = resolveEndpoint(as, 'device_authorization_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const body = new URLSearchParams(parameters);
|
|
body.set('client_id', client.client_id);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
}
|
|
async function processDeviceAuthorizationResponse(as, client, response) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 200, 'Device Authorization Endpoint');
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.device_code, '"response" body "device_code" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
assertString(json.user_code, '"response" body "user_code" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
assertString(json.verification_uri, '"response" body "verification_uri" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;
|
|
assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
json.expires_in = expiresIn;
|
|
if (json.verification_uri_complete !== undefined) {
|
|
assertString(json.verification_uri_complete, '"response" body "verification_uri_complete" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
if (json.interval !== undefined) {
|
|
assertNumber(json.interval, false, '"response" body "interval" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
assertString(deviceCode, '"deviceCode"');
|
|
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
parameters.set('device_code', deviceCode);
|
|
return tokenEndpointRequest(as, client, clientAuthentication, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options);
|
|
}
|
|
async function processDeviceCodeResponse(as, client, response, options) {
|
|
return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
}
|
|
async function generateKeyPair(alg, options) {
|
|
assertString(alg, '"alg"');
|
|
const algorithm = algToSubtle(alg);
|
|
if (alg.startsWith('PS') || alg.startsWith('RS')) {
|
|
Object.assign(algorithm, {
|
|
modulusLength: options?.modulusLength ?? 2048,
|
|
publicExponent: new Uint8Array([
|
|
0x01,
|
|
0x00,
|
|
0x01
|
|
])
|
|
});
|
|
}
|
|
return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [
|
|
'sign',
|
|
'verify'
|
|
]);
|
|
}
|
|
function normalizeHtu(htu) {
|
|
const url = new URL(htu);
|
|
url.search = '';
|
|
url.hash = '';
|
|
return url.href;
|
|
}
|
|
async function validateDPoP(request, accessToken, accessTokenClaims, options) {
|
|
const headerValue = request.headers.get('dpop');
|
|
if (headerValue === null) {
|
|
throw OPE('operation indicated DPoP use but the request has no DPoP HTTP Header', INVALID_REQUEST, {
|
|
headers: request.headers
|
|
});
|
|
}
|
|
if (request.headers.get('authorization')?.toLowerCase().startsWith('dpop ') === false) {
|
|
throw OPE(`operation indicated DPoP use but the request's Authorization HTTP Header scheme is not DPoP`, INVALID_REQUEST, {
|
|
headers: request.headers
|
|
});
|
|
}
|
|
if (typeof accessTokenClaims.cnf?.jkt !== 'string') {
|
|
throw OPE('operation indicated DPoP use but the JWT Access Token has no jkt confirmation claim', INVALID_REQUEST, {
|
|
claims: accessTokenClaims
|
|
});
|
|
}
|
|
const clockSkew = getClockSkew(options);
|
|
const proof = await validateJwt(headerValue, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), clockSkew, getClockTolerance(options), undefined).then(checkJwtType.bind(undefined, 'dpop+jwt')).then(validatePresence.bind(undefined, [
|
|
'iat',
|
|
'jti',
|
|
'ath',
|
|
'htm',
|
|
'htu'
|
|
]));
|
|
const now = epochTime() + clockSkew;
|
|
const diff = Math.abs(now - proof.claims.iat);
|
|
if (diff > 300) {
|
|
throw OPE('DPoP Proof iat is not recent enough', JWT_TIMESTAMP_CHECK, {
|
|
now,
|
|
claims: proof.claims,
|
|
claim: 'iat'
|
|
});
|
|
}
|
|
if (proof.claims.htm !== request.method) {
|
|
throw OPE('DPoP Proof htm mismatch', JWT_CLAIM_COMPARISON, {
|
|
expected: request.method,
|
|
claims: proof.claims,
|
|
claim: 'htm'
|
|
});
|
|
}
|
|
if (typeof proof.claims.htu !== 'string' || normalizeHtu(proof.claims.htu) !== normalizeHtu(request.url)) {
|
|
throw OPE('DPoP Proof htu mismatch', JWT_CLAIM_COMPARISON, {
|
|
expected: normalizeHtu(request.url),
|
|
claims: proof.claims,
|
|
claim: 'htu'
|
|
});
|
|
}
|
|
{
|
|
const expected = b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)));
|
|
if (proof.claims.ath !== expected) {
|
|
throw OPE('DPoP Proof ath mismatch', JWT_CLAIM_COMPARISON, {
|
|
expected,
|
|
claims: proof.claims,
|
|
claim: 'ath'
|
|
});
|
|
}
|
|
}
|
|
{
|
|
const expected = await calculateJwkThumbprint(proof.header.jwk);
|
|
if (accessTokenClaims.cnf.jkt !== expected) {
|
|
throw OPE('JWT Access Token confirmation mismatch', JWT_CLAIM_COMPARISON, {
|
|
expected,
|
|
claims: accessTokenClaims,
|
|
claim: 'cnf.jkt'
|
|
});
|
|
}
|
|
}
|
|
const { 0: protectedHeader, 1: payload, 2: encodedSignature } = headerValue.split('.');
|
|
const signature = b64u(encodedSignature);
|
|
const { jwk, alg } = proof.header;
|
|
if (!jwk) {
|
|
throw OPE('DPoP Proof is missing the jwk header parameter', INVALID_REQUEST, {
|
|
header: proof.header
|
|
});
|
|
}
|
|
const key = await importJwk(alg, jwk);
|
|
if (key.type !== 'public') {
|
|
throw OPE('DPoP Proof jwk header parameter must contain a public key', INVALID_REQUEST, {
|
|
header: proof.header
|
|
});
|
|
}
|
|
await validateJwsSignature(protectedHeader, payload, key, signature);
|
|
}
|
|
async function validateJwtAccessToken(as, request, expectedAudience, options) {
|
|
assertAs(as);
|
|
if (!looseInstanceOf(request, Request)) {
|
|
throw CodedTypeError('"request" must be an instance of Request', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
assertString(expectedAudience, '"expectedAudience"');
|
|
const authorization = request.headers.get('authorization');
|
|
if (authorization === null) {
|
|
throw OPE('"request" is missing an Authorization HTTP Header', INVALID_REQUEST, {
|
|
headers: request.headers
|
|
});
|
|
}
|
|
let { 0: scheme, 1: accessToken, length } = authorization.split(' ');
|
|
scheme = scheme.toLowerCase();
|
|
switch(scheme){
|
|
case 'dpop':
|
|
case 'bearer':
|
|
break;
|
|
default:
|
|
throw new UnsupportedOperationError('unsupported Authorization HTTP Header scheme', {
|
|
cause: {
|
|
headers: request.headers
|
|
}
|
|
});
|
|
}
|
|
if (length !== 2) {
|
|
throw OPE('invalid Authorization HTTP Header format', INVALID_REQUEST, {
|
|
headers: request.headers
|
|
});
|
|
}
|
|
const requiredClaims = [
|
|
'iss',
|
|
'exp',
|
|
'aud',
|
|
'sub',
|
|
'iat',
|
|
'jti',
|
|
'client_id'
|
|
];
|
|
if (options?.requireDPoP || scheme === 'dpop' || request.headers.has('dpop')) {
|
|
requiredClaims.push('cnf');
|
|
}
|
|
const { claims, header } = await validateJwt(accessToken, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), getClockSkew(options), getClockTolerance(options), undefined).then(checkJwtType.bind(undefined, 'at+jwt')).then(validatePresence.bind(undefined, requiredClaims)).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, expectedAudience)).catch(reassignRSCode);
|
|
for (const claim of [
|
|
'client_id',
|
|
'jti',
|
|
'sub'
|
|
]){
|
|
if (typeof claims[claim] !== 'string') {
|
|
throw OPE(`unexpected JWT "${claim}" claim type`, INVALID_REQUEST, {
|
|
claims
|
|
});
|
|
}
|
|
}
|
|
if ('cnf' in claims) {
|
|
if (!isJsonObject(claims.cnf)) {
|
|
throw OPE('unexpected JWT "cnf" (confirmation) claim value', INVALID_REQUEST, {
|
|
claims
|
|
});
|
|
}
|
|
const { 0: cnf, length } = Object.keys(claims.cnf);
|
|
if (length) {
|
|
if (length !== 1) {
|
|
throw new UnsupportedOperationError('multiple confirmation claims are not supported', {
|
|
cause: {
|
|
claims
|
|
}
|
|
});
|
|
}
|
|
if (cnf !== 'jkt') {
|
|
throw new UnsupportedOperationError('unsupported JWT Confirmation method', {
|
|
cause: {
|
|
claims
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const { 0: protectedHeader, 1: payload, 2: encodedSignature } = accessToken.split('.');
|
|
const signature = b64u(encodedSignature);
|
|
const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);
|
|
await validateJwsSignature(protectedHeader, payload, key, signature);
|
|
if (options?.requireDPoP || scheme === 'dpop' || claims.cnf?.jkt !== undefined || request.headers.has('dpop')) {
|
|
await validateDPoP(request, accessToken, claims, options).catch(reassignRSCode);
|
|
}
|
|
return claims;
|
|
}
|
|
function reassignRSCode(err) {
|
|
if (err instanceof OperationProcessingError && err?.code === INVALID_REQUEST) {
|
|
err.code = INVALID_RESPONSE;
|
|
}
|
|
throw err;
|
|
}
|
|
async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
const url = resolveEndpoint(as, 'backchannel_authentication_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const body = new URLSearchParams(parameters);
|
|
body.set('client_id', client.client_id);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
}
|
|
async function processBackchannelAuthenticationResponse(as, client, response) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 200, 'Backchannel Authentication Endpoint');
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.auth_req_id, '"response" body "auth_req_id" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;
|
|
assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
json.expires_in = expiresIn;
|
|
if (json.interval !== undefined) {
|
|
assertNumber(json.interval, false, '"response" body "interval" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {
|
|
assertAs(as);
|
|
assertClient(client);
|
|
assertString(authReqId, '"authReqId"');
|
|
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
parameters.set('auth_req_id', authReqId);
|
|
return tokenEndpointRequest(as, client, clientAuthentication, 'urn:openid:params:grant-type:ciba', parameters, options);
|
|
}
|
|
async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {
|
|
return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
}
|
|
async function dynamicClientRegistrationRequest(as, metadata, options) {
|
|
assertAs(as);
|
|
const url = resolveEndpoint(as, 'registration_endpoint', metadata.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
const headers = prepareHeaders(options?.headers);
|
|
headers.set('accept', 'application/json');
|
|
headers.set('content-type', 'application/json');
|
|
const method = 'POST';
|
|
if (options?.DPoP) {
|
|
assertDPoP(options.DPoP);
|
|
await options.DPoP.addProof(url, headers, method, options.initialAccessToken);
|
|
}
|
|
if (options?.initialAccessToken) {
|
|
headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${options.initialAccessToken}`);
|
|
}
|
|
const response = await (options?.[customFetch] || fetch)(url.href, {
|
|
body: JSON.stringify(metadata),
|
|
headers: Object.fromEntries(headers.entries()),
|
|
method,
|
|
redirect: 'manual',
|
|
signal: signal(url, options?.signal)
|
|
});
|
|
options?.DPoP?.cacheNonce(response, url);
|
|
return response;
|
|
}
|
|
async function processDynamicClientRegistrationResponse(response) {
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
await checkOAuthBodyError(response, 201, 'Dynamic Client Registration Endpoint');
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.client_id, '"response" body "client_id" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
if (json.client_secret !== undefined) {
|
|
assertString(json.client_secret, '"response" body "client_secret" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
if (json.client_secret) {
|
|
assertNumber(json.client_secret_expires_at, true, '"response" body "client_secret_expires_at" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
async function resourceDiscoveryRequest(resourceIdentifier, options) {
|
|
return performDiscovery(resourceIdentifier, 'resourceIdentifier', (url)=>{
|
|
prependWellKnown(url, '.well-known/oauth-protected-resource', true);
|
|
return url;
|
|
}, options);
|
|
}
|
|
async function processResourceDiscoveryResponse(expectedResourceIdentifier, response) {
|
|
const expected = expectedResourceIdentifier;
|
|
if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
|
|
throw CodedTypeError('"expectedResourceIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
if (!looseInstanceOf(response, Response)) {
|
|
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
}
|
|
if (response.status !== 200) {
|
|
throw OPE('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
|
|
}
|
|
assertReadableResponse(response);
|
|
const json = await getResponseJsonBody(response);
|
|
assertString(json.resource, '"response" body "resource" property', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
if (expected !== _nodiscoverycheck && new URL(json.resource).href !== expected.href) {
|
|
throw OPE('"response" body "resource" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, {
|
|
expected: expected.href,
|
|
body: json,
|
|
attribute: 'resource'
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
async function getResponseJsonBody(response, check = assertApplicationJson) {
|
|
let json;
|
|
try {
|
|
json = await response.json();
|
|
} catch (cause) {
|
|
check(response);
|
|
throw OPE('failed to parse "response" body as JSON', PARSE_ERROR, cause);
|
|
}
|
|
if (!isJsonObject(json)) {
|
|
throw OPE('"response" body must be a top level object', INVALID_RESPONSE, {
|
|
body: json
|
|
});
|
|
}
|
|
return json;
|
|
}
|
|
const _nopkce = nopkce;
|
|
const _nodiscoverycheck = Symbol();
|
|
const _expectedIssuer = Symbol(); //# sourceMappingURL=index.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/env.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"reqWithEnvURL",
|
|
()=>reqWithEnvURL,
|
|
"setEnvDefaults",
|
|
()=>setEnvDefaults
|
|
]);
|
|
// @ts-expect-error Next.js does not yet correctly use the `package.json#exports` field
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next/server.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/index.js [app-route] (ecmascript) <locals>");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/lib/utils/env.js [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
function reqWithEnvURL(req) {
|
|
const url = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL;
|
|
if (!url) return req;
|
|
const { origin: envOrigin } = new URL(url);
|
|
const { href, origin } = req.nextUrl;
|
|
return new __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["NextRequest"](href.replace(origin, envOrigin), req);
|
|
}
|
|
function setEnvDefaults(config) {
|
|
try {
|
|
config.secret ?? (config.secret = process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET);
|
|
const url = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL;
|
|
if (!url) return;
|
|
const { pathname } = new URL(url);
|
|
if (pathname === "/") return;
|
|
config.basePath || (config.basePath = pathname);
|
|
} catch {
|
|
// Catching and swallowing potential URL parsing errors, we'll fall
|
|
// back to `/api/auth` below.
|
|
} finally{
|
|
config.basePath || (config.basePath = "/api/auth");
|
|
(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(process.env, config, true);
|
|
}
|
|
}
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/index.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"initAuth",
|
|
()=>initAuth
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/index.js [app-route] (ecmascript) <locals>");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/lib/utils/env.js [app-route] (ecmascript)");
|
|
// @ts-expect-error Next.js does not yet correctly use the `package.json#exports` field
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next/headers.js [app-route] (ecmascript)");
|
|
// @ts-expect-error Next.js does not yet correctly use the `package.json#exports` field
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next/server.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/env.js [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
;
|
|
;
|
|
async function getSession(headers, config) {
|
|
const url = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["createActionURL"])("session", // @ts-expect-error `x-forwarded-proto` is not nullable, next.js sets it by default
|
|
headers.get("x-forwarded-proto"), headers, process.env, config);
|
|
const request = new Request(url, {
|
|
headers: {
|
|
cookie: headers.get("cookie") ?? ""
|
|
}
|
|
});
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["Auth"])(request, {
|
|
...config,
|
|
callbacks: {
|
|
...config.callbacks,
|
|
// Since we are server-side, we don't need to filter out the session data
|
|
// See https://authjs.dev/getting-started/migrating-to-v5#authenticating-server-side
|
|
// TODO: Taint the session data to prevent accidental leakage to the client
|
|
// https://react.dev/reference/react/experimental_taintObjectReference
|
|
async session (...args) {
|
|
const session = // If the user defined a custom session callback, use that instead
|
|
await config.callbacks?.session?.(...args) ?? {
|
|
...args[0].session,
|
|
expires: args[0].session.expires?.toISOString?.() ?? args[0].session.expires
|
|
};
|
|
const user = args[0].user ?? args[0].token;
|
|
return {
|
|
user,
|
|
...session
|
|
};
|
|
}
|
|
}
|
|
});
|
|
}
|
|
function isReqWrapper(arg) {
|
|
return typeof arg === "function";
|
|
}
|
|
function initAuth(config, onLazyLoad // To set the default env vars
|
|
) {
|
|
if (typeof config === "function") {
|
|
return async (...args)=>{
|
|
if (!args.length) {
|
|
// React Server Components
|
|
const _headers = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["headers"])();
|
|
const _config = await config(undefined); // Review: Should we pass headers() here instead?
|
|
onLazyLoad?.(_config);
|
|
return getSession(_headers, _config).then((r)=>r.json());
|
|
}
|
|
if (args[0] instanceof Request) {
|
|
// middleware.ts inline
|
|
// export { auth as default } from "auth"
|
|
const req = args[0];
|
|
const ev = args[1];
|
|
const _config = await config(req);
|
|
onLazyLoad?.(_config);
|
|
// args[0] is supposed to be NextRequest but the instanceof check is failing.
|
|
return handleAuth([
|
|
req,
|
|
ev
|
|
], _config);
|
|
}
|
|
if (isReqWrapper(args[0])) {
|
|
// middleware.ts wrapper/route.ts
|
|
// import { auth } from "auth"
|
|
// export default auth((req) => { console.log(req.auth) }})
|
|
const userMiddlewareOrRoute = args[0];
|
|
return async (...args)=>{
|
|
const _config = await config(args[0]);
|
|
onLazyLoad?.(_config);
|
|
return handleAuth(args, _config, userMiddlewareOrRoute);
|
|
};
|
|
}
|
|
// API Routes, getServerSideProps
|
|
const request = "req" in args[0] ? args[0].req : args[0];
|
|
const response = "res" in args[0] ? args[0].res : args[1];
|
|
const _config = await config(request);
|
|
onLazyLoad?.(_config);
|
|
// @ts-expect-error -- request is NextRequest
|
|
return getSession(new Headers(request.headers), _config).then(async (authResponse)=>{
|
|
const auth = await authResponse.json();
|
|
for (const cookie of authResponse.headers.getSetCookie())if ("headers" in response) response.headers.append("set-cookie", cookie);
|
|
else response.appendHeader("set-cookie", cookie);
|
|
return auth;
|
|
});
|
|
};
|
|
}
|
|
return (...args)=>{
|
|
if (!args.length) {
|
|
// React Server Components
|
|
return Promise.resolve((0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["headers"])()).then((h)=>getSession(h, config).then((r)=>r.json()));
|
|
}
|
|
if (args[0] instanceof Request) {
|
|
// middleware.ts inline
|
|
// export { auth as default } from "auth"
|
|
const req = args[0];
|
|
const ev = args[1];
|
|
return handleAuth([
|
|
req,
|
|
ev
|
|
], config);
|
|
}
|
|
if (isReqWrapper(args[0])) {
|
|
// middleware.ts wrapper/route.ts
|
|
// import { auth } from "auth"
|
|
// export default auth((req) => { console.log(req.auth) }})
|
|
const userMiddlewareOrRoute = args[0];
|
|
return async (...args)=>{
|
|
return handleAuth(args, config, userMiddlewareOrRoute).then((res)=>{
|
|
return res;
|
|
});
|
|
};
|
|
}
|
|
// API Routes, getServerSideProps
|
|
const request = "req" in args[0] ? args[0].req : args[0];
|
|
const response = "res" in args[0] ? args[0].res : args[1];
|
|
return getSession(// @ts-expect-error
|
|
new Headers(request.headers), config).then(async (authResponse)=>{
|
|
const auth = await authResponse.json();
|
|
for (const cookie of authResponse.headers.getSetCookie())if ("headers" in response) response.headers.append("set-cookie", cookie);
|
|
else response.appendHeader("set-cookie", cookie);
|
|
return auth;
|
|
});
|
|
};
|
|
}
|
|
async function handleAuth(args, config, userMiddlewareOrRoute) {
|
|
const request = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["reqWithEnvURL"])(args[0]);
|
|
const sessionResponse = await getSession(request.headers, config);
|
|
const auth = await sessionResponse.json();
|
|
let authorized = true;
|
|
if (config.callbacks?.authorized) {
|
|
authorized = await config.callbacks.authorized({
|
|
request,
|
|
auth
|
|
});
|
|
}
|
|
let response = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["NextResponse"].next?.();
|
|
if (authorized instanceof Response) {
|
|
// User returned a custom response, like redirecting to a page or 401, respect it
|
|
response = authorized;
|
|
const redirect = authorized.headers.get("Location");
|
|
const { pathname } = request.nextUrl;
|
|
// If the user is redirecting to the same NextAuth.js action path as the current request,
|
|
// don't allow the redirect to prevent an infinite loop
|
|
if (redirect && isSameAuthAction(pathname, new URL(redirect).pathname, config)) {
|
|
authorized = true;
|
|
}
|
|
} else if (userMiddlewareOrRoute) {
|
|
// Execute user's middleware/handler with the augmented request
|
|
const augmentedReq = request;
|
|
augmentedReq.auth = auth;
|
|
response = await userMiddlewareOrRoute(augmentedReq, args[1]) ?? __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["NextResponse"].next();
|
|
} else if (!authorized) {
|
|
const signInPage = config.pages?.signIn ?? `${config.basePath}/signin`;
|
|
if (request.nextUrl.pathname !== signInPage) {
|
|
// Redirect to signin page by default if not authorized
|
|
const signInUrl = request.nextUrl.clone();
|
|
signInUrl.pathname = signInPage;
|
|
signInUrl.searchParams.set("callbackUrl", request.nextUrl.href);
|
|
response = __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["NextResponse"].redirect(signInUrl);
|
|
}
|
|
}
|
|
const finalResponse = new Response(response?.body, response);
|
|
// Preserve cookies from the session response
|
|
for (const cookie of sessionResponse.headers.getSetCookie())finalResponse.headers.append("set-cookie", cookie);
|
|
return finalResponse;
|
|
}
|
|
function isSameAuthAction(requestPath, redirectPath, config) {
|
|
const action = redirectPath.replace(`${requestPath}/`, "");
|
|
const pages = Object.values(config.pages ?? {});
|
|
return (actions.has(action) || pages.includes(redirectPath)) && redirectPath === requestPath;
|
|
}
|
|
const actions = new Set([
|
|
"providers",
|
|
"session",
|
|
"csrf",
|
|
"signin",
|
|
"signout",
|
|
"callback",
|
|
"verify-request",
|
|
"error"
|
|
]);
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/actions.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"signIn",
|
|
()=>signIn,
|
|
"signOut",
|
|
()=>signOut,
|
|
"update",
|
|
()=>update
|
|
]);
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/index.js [app-route] (ecmascript) <locals>");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/lib/symbols.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/lib/utils/env.js [app-route] (ecmascript)");
|
|
// @ts-expect-error Next.js does not yet correctly use the `package.json#exports` field
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next/headers.js [app-route] (ecmascript)");
|
|
// @ts-expect-error Next.js does not yet correctly use the `package.json#exports` field
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$dist$2f$api$2f$navigation$2e$react$2d$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next/dist/api/navigation.react-server.js [app-route] (ecmascript) <locals>");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$dist$2f$client$2f$components$2f$navigation$2e$react$2d$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next/dist/client/components/navigation.react-server.js [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
;
|
|
async function signIn(provider, options = {}, authorizationParams, config) {
|
|
const headers = new Headers(await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["headers"])());
|
|
const { redirect: shouldRedirect = true, redirectTo, ...rest } = options instanceof FormData ? Object.fromEntries(options) : options;
|
|
const callbackUrl = redirectTo?.toString() ?? headers.get("Referer") ?? "/";
|
|
const signInURL = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["createActionURL"])("signin", // @ts-expect-error `x-forwarded-proto` is not nullable, next.js sets it by default
|
|
headers.get("x-forwarded-proto"), headers, process.env, config);
|
|
if (!provider) {
|
|
signInURL.searchParams.append("callbackUrl", callbackUrl);
|
|
if (shouldRedirect) (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$dist$2f$client$2f$components$2f$navigation$2e$react$2d$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["redirect"])(signInURL.toString());
|
|
return signInURL.toString();
|
|
}
|
|
let url = `${signInURL}/${provider}?${new URLSearchParams(authorizationParams)}`;
|
|
let foundProvider = {};
|
|
for (const providerConfig of config.providers){
|
|
const { options, ...defaults } = typeof providerConfig === "function" ? providerConfig() : providerConfig;
|
|
const id = options?.id ?? defaults.id;
|
|
if (id === provider) {
|
|
foundProvider = {
|
|
id,
|
|
type: options?.type ?? defaults.type
|
|
};
|
|
break;
|
|
}
|
|
}
|
|
if (!foundProvider.id) {
|
|
const url = `${signInURL}?${new URLSearchParams({
|
|
callbackUrl
|
|
})}`;
|
|
if (shouldRedirect) (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$dist$2f$client$2f$components$2f$navigation$2e$react$2d$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["redirect"])(url);
|
|
return url;
|
|
}
|
|
if (foundProvider.type === "credentials") {
|
|
url = url.replace("signin", "callback");
|
|
}
|
|
headers.set("Content-Type", "application/x-www-form-urlencoded");
|
|
const body = new URLSearchParams({
|
|
...rest,
|
|
callbackUrl
|
|
});
|
|
const req = new Request(url, {
|
|
method: "POST",
|
|
headers,
|
|
body
|
|
});
|
|
const res = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["Auth"])(req, {
|
|
...config,
|
|
raw: __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["raw"],
|
|
skipCSRFCheck: __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["skipCSRFCheck"]
|
|
});
|
|
const cookieJar = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["cookies"])();
|
|
for (const c of res?.cookies ?? [])cookieJar.set(c.name, c.value, c.options);
|
|
const responseUrl = res instanceof Response ? res.headers.get("Location") : res.redirect;
|
|
// NOTE: if for some unexpected reason the responseUrl is not set,
|
|
// we redirect to the original url
|
|
const redirectUrl = responseUrl ?? url;
|
|
if (shouldRedirect) return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$dist$2f$client$2f$components$2f$navigation$2e$react$2d$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["redirect"])(redirectUrl);
|
|
return redirectUrl;
|
|
}
|
|
async function signOut(options, config) {
|
|
const headers = new Headers(await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["headers"])());
|
|
headers.set("Content-Type", "application/x-www-form-urlencoded");
|
|
const url = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["createActionURL"])("signout", // @ts-expect-error `x-forwarded-proto` is not nullable, next.js sets it by default
|
|
headers.get("x-forwarded-proto"), headers, process.env, config);
|
|
const callbackUrl = options?.redirectTo ?? headers.get("Referer") ?? "/";
|
|
const body = new URLSearchParams({
|
|
callbackUrl
|
|
});
|
|
const req = new Request(url, {
|
|
method: "POST",
|
|
headers,
|
|
body
|
|
});
|
|
const res = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["Auth"])(req, {
|
|
...config,
|
|
raw: __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["raw"],
|
|
skipCSRFCheck: __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["skipCSRFCheck"]
|
|
});
|
|
const cookieJar = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["cookies"])();
|
|
for (const c of res?.cookies ?? [])cookieJar.set(c.name, c.value, c.options);
|
|
if (options?.redirect ?? true) return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$dist$2f$client$2f$components$2f$navigation$2e$react$2d$server$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["redirect"])(res.redirect);
|
|
return res;
|
|
}
|
|
async function update(data, config) {
|
|
const headers = new Headers(await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["headers"])());
|
|
headers.set("Content-Type", "application/json");
|
|
const url = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$utils$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["createActionURL"])("session", // @ts-expect-error `x-forwarded-proto` is not nullable, next.js sets it by default
|
|
headers.get("x-forwarded-proto"), headers, process.env, config);
|
|
const body = JSON.stringify({
|
|
data
|
|
});
|
|
const req = new Request(url, {
|
|
method: "POST",
|
|
headers,
|
|
body
|
|
});
|
|
const res = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["Auth"])(req, {
|
|
...config,
|
|
raw: __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["raw"],
|
|
skipCSRFCheck: __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["skipCSRFCheck"]
|
|
});
|
|
const cookieJar = await (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2f$headers$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["cookies"])();
|
|
for (const c of res?.cookies ?? [])cookieJar.set(c.name, c.value, c.options);
|
|
return res.body;
|
|
}
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/next-auth/index.js [app-route] (ecmascript) <locals>", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"default",
|
|
()=>NextAuth
|
|
]);
|
|
/**
|
|
* _If you are looking to migrate from v4, visit the [Upgrade Guide (v5)](https://authjs.dev/getting-started/migrating-to-v5)._
|
|
*
|
|
* ## Installation
|
|
*
|
|
* ```bash npm2yarn
|
|
* npm install next-auth@beta
|
|
* ```
|
|
*
|
|
* ## Environment variable inference
|
|
*
|
|
* `NEXTAUTH_URL` and `NEXTAUTH_SECRET` have been inferred since v4.
|
|
*
|
|
* Since NextAuth.js v5 can also automatically infer environment variables that are prefixed with `AUTH_`.
|
|
*
|
|
* For example `AUTH_GITHUB_ID` and `AUTH_GITHUB_SECRET` will be used as the `clientId` and `clientSecret` options for the GitHub provider.
|
|
*
|
|
* :::tip
|
|
* The environment variable name inferring has the following format for OAuth providers: `AUTH_{PROVIDER}_{ID|SECRET}`.
|
|
*
|
|
* `PROVIDER` is the uppercase snake case version of the provider's id, followed by either `ID` or `SECRET` respectively.
|
|
* :::
|
|
*
|
|
* `AUTH_SECRET` and `AUTH_URL` are also aliased for `NEXTAUTH_SECRET` and `NEXTAUTH_URL` for consistency.
|
|
*
|
|
* To add social login to your app, the configuration becomes:
|
|
*
|
|
* ```ts title="auth.ts"
|
|
* import NextAuth from "next-auth"
|
|
* import GitHub from "next-auth/providers/github"
|
|
* export const { handlers, auth } = NextAuth({ providers: [ GitHub ] })
|
|
* ```
|
|
*
|
|
* And the `.env.local` file:
|
|
*
|
|
* ```sh title=".env.local"
|
|
* AUTH_GITHUB_ID=...
|
|
* AUTH_GITHUB_SECRET=...
|
|
* AUTH_SECRET=...
|
|
* ```
|
|
*
|
|
* :::tip
|
|
* In production, `AUTH_SECRET` is a required environment variable - if not set, NextAuth.js will throw an error. See [MissingSecretError](https://authjs.dev/reference/core/errors#missingsecret) for more details.
|
|
* :::
|
|
*
|
|
* If you need to override the default values for a provider, you can still call it as a function `GitHub({...})` as before.
|
|
*
|
|
* ## Lazy initialization
|
|
* You can also initialize NextAuth.js lazily (previously known as advanced intialization), which allows you to access the request context in the configuration in some cases, like Route Handlers, Middleware, API Routes or `getServerSideProps`.
|
|
* The above example becomes:
|
|
*
|
|
* ```ts title="auth.ts"
|
|
* import NextAuth from "next-auth"
|
|
* import GitHub from "next-auth/providers/github"
|
|
* export const { handlers, auth } = NextAuth(req => {
|
|
* if (req) {
|
|
* console.log(req) // do something with the request
|
|
* }
|
|
* return { providers: [ GitHub ] }
|
|
* })
|
|
* ```
|
|
*
|
|
* :::tip
|
|
* This is useful if you want to customize the configuration based on the request, for example, to add a different provider in staging/dev environments.
|
|
* :::
|
|
*
|
|
* @module next-auth
|
|
*/ var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/index.js [app-route] (ecmascript) <locals>");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$lib$2f$symbols$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/lib/symbols.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/env.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/index.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/next-auth/lib/actions.js [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$errors$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/errors.js [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
;
|
|
;
|
|
;
|
|
;
|
|
function NextAuth(config) {
|
|
if (typeof config === "function") {
|
|
const httpHandler = async (req)=>{
|
|
const _config = await config(req);
|
|
(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(_config);
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["Auth"])((0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["reqWithEnvURL"])(req), _config);
|
|
};
|
|
return {
|
|
handlers: {
|
|
GET: httpHandler,
|
|
POST: httpHandler
|
|
},
|
|
// @ts-expect-error
|
|
auth: (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["initAuth"])(config, (c)=>(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(c)),
|
|
signIn: async (provider, options, authorizationParams)=>{
|
|
const _config = await config(undefined);
|
|
(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(_config);
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["signIn"])(provider, options, authorizationParams, _config);
|
|
},
|
|
signOut: async (options)=>{
|
|
const _config = await config(undefined);
|
|
(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(_config);
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["signOut"])(options, _config);
|
|
},
|
|
unstable_update: async (data)=>{
|
|
const _config = await config(undefined);
|
|
(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(_config);
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["update"])(data, _config);
|
|
}
|
|
};
|
|
}
|
|
(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["setEnvDefaults"])(config);
|
|
const httpHandler = (req)=>(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["Auth"])((0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$env$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["reqWithEnvURL"])(req), config);
|
|
return {
|
|
handlers: {
|
|
GET: httpHandler,
|
|
POST: httpHandler
|
|
},
|
|
// @ts-expect-error
|
|
auth: (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["initAuth"])(config),
|
|
signIn: (provider, options, authorizationParams)=>{
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["signIn"])(provider, options, authorizationParams, config);
|
|
},
|
|
signOut: (options)=>{
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["signOut"])(options, config);
|
|
},
|
|
unstable_update: (data)=>{
|
|
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$next$2d$auth$2f$lib$2f$actions$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["update"])(data, config);
|
|
}
|
|
};
|
|
}
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/next-auth/providers/credentials.js [app-route] (ecmascript) <locals>", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([]);
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$auth$2f$core$2f$providers$2f$credentials$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@auth/core/providers/credentials.js [app-route] (ecmascript)");
|
|
;
|
|
;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/bcryptjs/index.js [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"compare",
|
|
()=>compare,
|
|
"compareSync",
|
|
()=>compareSync,
|
|
"decodeBase64",
|
|
()=>decodeBase64,
|
|
"default",
|
|
()=>__TURBOPACK__default__export__,
|
|
"encodeBase64",
|
|
()=>encodeBase64,
|
|
"genSalt",
|
|
()=>genSalt,
|
|
"genSaltSync",
|
|
()=>genSaltSync,
|
|
"getRounds",
|
|
()=>getRounds,
|
|
"getSalt",
|
|
()=>getSalt,
|
|
"hash",
|
|
()=>hash,
|
|
"hashSync",
|
|
()=>hashSync,
|
|
"setRandomFallback",
|
|
()=>setRandomFallback,
|
|
"truncates",
|
|
()=>truncates
|
|
]);
|
|
/*
|
|
Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>
|
|
Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>
|
|
Copyright (c) 2025 Daniel Wirtz <dcode@dcode.io>
|
|
|
|
Redistribution and use in source and binary forms, with or without
|
|
modification, are permitted provided that the following conditions
|
|
are met:
|
|
1. Redistributions of source code must retain the above copyright
|
|
notice, this list of conditions and the following disclaimer.
|
|
2. Redistributions in binary form must reproduce the above copyright
|
|
notice, this list of conditions and the following disclaimer in the
|
|
documentation and/or other materials provided with the distribution.
|
|
3. The name of the author may not be used to endorse or promote products
|
|
derived from this software without specific prior written permission.
|
|
|
|
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
|
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
|
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
|
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
|
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
|
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
|
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
*/ // The Node.js crypto module is used as a fallback for the Web Crypto API. When
|
|
// building for the browser, inclusion of the crypto module should be disabled,
|
|
// which the package hints at in its package.json for bundlers that support it.
|
|
var __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__ = __turbopack_context__.i("[externals]/crypto [external] (crypto, cjs)");
|
|
;
|
|
/**
|
|
* The random implementation to use as a fallback.
|
|
* @type {?function(number):!Array.<number>}
|
|
* @inner
|
|
*/ var randomFallback = null;
|
|
/**
|
|
* Generates cryptographically secure random bytes.
|
|
* @function
|
|
* @param {number} len Bytes length
|
|
* @returns {!Array.<number>} Random bytes
|
|
* @throws {Error} If no random implementation is available
|
|
* @inner
|
|
*/ function randomBytes(len) {
|
|
// Web Crypto API. Globally available in the browser and in Node.js >=23.
|
|
try {
|
|
return crypto.getRandomValues(new Uint8Array(len));
|
|
} catch {}
|
|
// Node.js crypto module for non-browser environments.
|
|
try {
|
|
return __TURBOPACK__imported__module__$5b$externals$5d2f$crypto__$5b$external$5d$__$28$crypto$2c$__cjs$29$__["default"].randomBytes(len);
|
|
} catch {}
|
|
// Custom fallback specified with `setRandomFallback`.
|
|
if (!randomFallback) {
|
|
throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");
|
|
}
|
|
return randomFallback(len);
|
|
}
|
|
function setRandomFallback(random) {
|
|
randomFallback = random;
|
|
}
|
|
function genSaltSync(rounds, seed_length) {
|
|
rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS;
|
|
if (typeof rounds !== "number") throw Error("Illegal arguments: " + typeof rounds + ", " + typeof seed_length);
|
|
if (rounds < 4) rounds = 4;
|
|
else if (rounds > 31) rounds = 31;
|
|
var salt = [];
|
|
salt.push("$2b$");
|
|
if (rounds < 10) salt.push("0");
|
|
salt.push(rounds.toString());
|
|
salt.push("$");
|
|
salt.push(base64_encode(randomBytes(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw
|
|
return salt.join("");
|
|
}
|
|
function genSalt(rounds, seed_length, callback) {
|
|
if (typeof seed_length === "function") callback = seed_length, seed_length = undefined; // Not supported.
|
|
if (typeof rounds === "function") callback = rounds, rounds = undefined;
|
|
if (typeof rounds === "undefined") rounds = GENSALT_DEFAULT_LOG2_ROUNDS;
|
|
else if (typeof rounds !== "number") throw Error("illegal arguments: " + typeof rounds);
|
|
function _async(callback) {
|
|
nextTick(function() {
|
|
// Pretty thin, but salting is fast enough
|
|
try {
|
|
callback(null, genSaltSync(rounds));
|
|
} catch (err) {
|
|
callback(err);
|
|
}
|
|
});
|
|
}
|
|
if (callback) {
|
|
if (typeof callback !== "function") throw Error("Illegal callback: " + typeof callback);
|
|
_async(callback);
|
|
} else return new Promise(function(resolve, reject) {
|
|
_async(function(err, res) {
|
|
if (err) {
|
|
reject(err);
|
|
return;
|
|
}
|
|
resolve(res);
|
|
});
|
|
});
|
|
}
|
|
function hashSync(password, salt) {
|
|
if (typeof salt === "undefined") salt = GENSALT_DEFAULT_LOG2_ROUNDS;
|
|
if (typeof salt === "number") salt = genSaltSync(salt);
|
|
if (typeof password !== "string" || typeof salt !== "string") throw Error("Illegal arguments: " + typeof password + ", " + typeof salt);
|
|
return _hash(password, salt);
|
|
}
|
|
function hash(password, salt, callback, progressCallback) {
|
|
function _async(callback) {
|
|
if (typeof password === "string" && typeof salt === "number") genSalt(salt, function(err, salt) {
|
|
_hash(password, salt, callback, progressCallback);
|
|
});
|
|
else if (typeof password === "string" && typeof salt === "string") _hash(password, salt, callback, progressCallback);
|
|
else nextTick(callback.bind(this, Error("Illegal arguments: " + typeof password + ", " + typeof salt)));
|
|
}
|
|
if (callback) {
|
|
if (typeof callback !== "function") throw Error("Illegal callback: " + typeof callback);
|
|
_async(callback);
|
|
} else return new Promise(function(resolve, reject) {
|
|
_async(function(err, res) {
|
|
if (err) {
|
|
reject(err);
|
|
return;
|
|
}
|
|
resolve(res);
|
|
});
|
|
});
|
|
}
|
|
/**
|
|
* Compares two strings of the same length in constant time.
|
|
* @param {string} known Must be of the correct length
|
|
* @param {string} unknown Must be the same length as `known`
|
|
* @returns {boolean}
|
|
* @inner
|
|
*/ function safeStringCompare(known, unknown) {
|
|
var diff = known.length ^ unknown.length;
|
|
for(var i = 0; i < known.length; ++i){
|
|
diff |= known.charCodeAt(i) ^ unknown.charCodeAt(i);
|
|
}
|
|
return diff === 0;
|
|
}
|
|
function compareSync(password, hash) {
|
|
if (typeof password !== "string" || typeof hash !== "string") throw Error("Illegal arguments: " + typeof password + ", " + typeof hash);
|
|
if (hash.length !== 60) return false;
|
|
return safeStringCompare(hashSync(password, hash.substring(0, hash.length - 31)), hash);
|
|
}
|
|
function compare(password, hashValue, callback, progressCallback) {
|
|
function _async(callback) {
|
|
if (typeof password !== "string" || typeof hashValue !== "string") {
|
|
nextTick(callback.bind(this, Error("Illegal arguments: " + typeof password + ", " + typeof hashValue)));
|
|
return;
|
|
}
|
|
if (hashValue.length !== 60) {
|
|
nextTick(callback.bind(this, null, false));
|
|
return;
|
|
}
|
|
hash(password, hashValue.substring(0, 29), function(err, comp) {
|
|
if (err) callback(err);
|
|
else callback(null, safeStringCompare(comp, hashValue));
|
|
}, progressCallback);
|
|
}
|
|
if (callback) {
|
|
if (typeof callback !== "function") throw Error("Illegal callback: " + typeof callback);
|
|
_async(callback);
|
|
} else return new Promise(function(resolve, reject) {
|
|
_async(function(err, res) {
|
|
if (err) {
|
|
reject(err);
|
|
return;
|
|
}
|
|
resolve(res);
|
|
});
|
|
});
|
|
}
|
|
function getRounds(hash) {
|
|
if (typeof hash !== "string") throw Error("Illegal arguments: " + typeof hash);
|
|
return parseInt(hash.split("$")[2], 10);
|
|
}
|
|
function getSalt(hash) {
|
|
if (typeof hash !== "string") throw Error("Illegal arguments: " + typeof hash);
|
|
if (hash.length !== 60) throw Error("Illegal hash length: " + hash.length + " != 60");
|
|
return hash.substring(0, 29);
|
|
}
|
|
function truncates(password) {
|
|
if (typeof password !== "string") throw Error("Illegal arguments: " + typeof password);
|
|
return utf8Length(password) > 72;
|
|
}
|
|
/**
|
|
* Continues with the callback after yielding to the event loop.
|
|
* @function
|
|
* @param {function(...[*])} callback Callback to execute
|
|
* @inner
|
|
*/ var nextTick = typeof setImmediate === "function" ? setImmediate : typeof scheduler === "object" && typeof scheduler.postTask === "function" ? scheduler.postTask.bind(scheduler) : setTimeout;
|
|
/** Calculates the byte length of a string encoded as UTF8. */ function utf8Length(string) {
|
|
var len = 0, c = 0;
|
|
for(var i = 0; i < string.length; ++i){
|
|
c = string.charCodeAt(i);
|
|
if (c < 128) len += 1;
|
|
else if (c < 2048) len += 2;
|
|
else if ((c & 0xfc00) === 0xd800 && (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
|
|
++i;
|
|
len += 4;
|
|
} else len += 3;
|
|
}
|
|
return len;
|
|
}
|
|
/** Converts a string to an array of UTF8 bytes. */ function utf8Array(string) {
|
|
var offset = 0, c1, c2;
|
|
var buffer = new Array(utf8Length(string));
|
|
for(var i = 0, k = string.length; i < k; ++i){
|
|
c1 = string.charCodeAt(i);
|
|
if (c1 < 128) {
|
|
buffer[offset++] = c1;
|
|
} else if (c1 < 2048) {
|
|
buffer[offset++] = c1 >> 6 | 192;
|
|
buffer[offset++] = c1 & 63 | 128;
|
|
} else if ((c1 & 0xfc00) === 0xd800 && ((c2 = string.charCodeAt(i + 1)) & 0xfc00) === 0xdc00) {
|
|
c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
|
|
++i;
|
|
buffer[offset++] = c1 >> 18 | 240;
|
|
buffer[offset++] = c1 >> 12 & 63 | 128;
|
|
buffer[offset++] = c1 >> 6 & 63 | 128;
|
|
buffer[offset++] = c1 & 63 | 128;
|
|
} else {
|
|
buffer[offset++] = c1 >> 12 | 224;
|
|
buffer[offset++] = c1 >> 6 & 63 | 128;
|
|
buffer[offset++] = c1 & 63 | 128;
|
|
}
|
|
}
|
|
return buffer;
|
|
}
|
|
// A base64 implementation for the bcrypt algorithm. This is partly non-standard.
|
|
/**
|
|
* bcrypt's own non-standard base64 dictionary.
|
|
* @type {!Array.<string>}
|
|
* @const
|
|
* @inner
|
|
**/ var BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
|
|
/**
|
|
* @type {!Array.<number>}
|
|
* @const
|
|
* @inner
|
|
**/ var BASE64_INDEX = [
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
0,
|
|
1,
|
|
54,
|
|
55,
|
|
56,
|
|
57,
|
|
58,
|
|
59,
|
|
60,
|
|
61,
|
|
62,
|
|
63,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
2,
|
|
3,
|
|
4,
|
|
5,
|
|
6,
|
|
7,
|
|
8,
|
|
9,
|
|
10,
|
|
11,
|
|
12,
|
|
13,
|
|
14,
|
|
15,
|
|
16,
|
|
17,
|
|
18,
|
|
19,
|
|
20,
|
|
21,
|
|
22,
|
|
23,
|
|
24,
|
|
25,
|
|
26,
|
|
27,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
28,
|
|
29,
|
|
30,
|
|
31,
|
|
32,
|
|
33,
|
|
34,
|
|
35,
|
|
36,
|
|
37,
|
|
38,
|
|
39,
|
|
40,
|
|
41,
|
|
42,
|
|
43,
|
|
44,
|
|
45,
|
|
46,
|
|
47,
|
|
48,
|
|
49,
|
|
50,
|
|
51,
|
|
52,
|
|
53,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1,
|
|
-1
|
|
];
|
|
/**
|
|
* Encodes a byte array to base64 with up to len bytes of input.
|
|
* @param {!Array.<number>} b Byte array
|
|
* @param {number} len Maximum input length
|
|
* @returns {string}
|
|
* @inner
|
|
*/ function base64_encode(b, len) {
|
|
var off = 0, rs = [], c1, c2;
|
|
if (len <= 0 || len > b.length) throw Error("Illegal len: " + len);
|
|
while(off < len){
|
|
c1 = b[off++] & 0xff;
|
|
rs.push(BASE64_CODE[c1 >> 2 & 0x3f]);
|
|
c1 = (c1 & 0x03) << 4;
|
|
if (off >= len) {
|
|
rs.push(BASE64_CODE[c1 & 0x3f]);
|
|
break;
|
|
}
|
|
c2 = b[off++] & 0xff;
|
|
c1 |= c2 >> 4 & 0x0f;
|
|
rs.push(BASE64_CODE[c1 & 0x3f]);
|
|
c1 = (c2 & 0x0f) << 2;
|
|
if (off >= len) {
|
|
rs.push(BASE64_CODE[c1 & 0x3f]);
|
|
break;
|
|
}
|
|
c2 = b[off++] & 0xff;
|
|
c1 |= c2 >> 6 & 0x03;
|
|
rs.push(BASE64_CODE[c1 & 0x3f]);
|
|
rs.push(BASE64_CODE[c2 & 0x3f]);
|
|
}
|
|
return rs.join("");
|
|
}
|
|
/**
|
|
* Decodes a base64 encoded string to up to len bytes of output.
|
|
* @param {string} s String to decode
|
|
* @param {number} len Maximum output length
|
|
* @returns {!Array.<number>}
|
|
* @inner
|
|
*/ function base64_decode(s, len) {
|
|
var off = 0, slen = s.length, olen = 0, rs = [], c1, c2, c3, c4, o, code;
|
|
if (len <= 0) throw Error("Illegal len: " + len);
|
|
while(off < slen - 1 && olen < len){
|
|
code = s.charCodeAt(off++);
|
|
c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
|
|
code = s.charCodeAt(off++);
|
|
c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
|
|
if (c1 == -1 || c2 == -1) break;
|
|
o = c1 << 2 >>> 0;
|
|
o |= (c2 & 0x30) >> 4;
|
|
rs.push(String.fromCharCode(o));
|
|
if (++olen >= len || off >= slen) break;
|
|
code = s.charCodeAt(off++);
|
|
c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
|
|
if (c3 == -1) break;
|
|
o = (c2 & 0x0f) << 4 >>> 0;
|
|
o |= (c3 & 0x3c) >> 2;
|
|
rs.push(String.fromCharCode(o));
|
|
if (++olen >= len || off >= slen) break;
|
|
code = s.charCodeAt(off++);
|
|
c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
|
|
o = (c3 & 0x03) << 6 >>> 0;
|
|
o |= c4;
|
|
rs.push(String.fromCharCode(o));
|
|
++olen;
|
|
}
|
|
var res = [];
|
|
for(off = 0; off < olen; off++)res.push(rs[off].charCodeAt(0));
|
|
return res;
|
|
}
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var BCRYPT_SALT_LEN = 16;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var GENSALT_DEFAULT_LOG2_ROUNDS = 10;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var BLOWFISH_NUM_ROUNDS = 16;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var MAX_EXECUTION_TIME = 100;
|
|
/**
|
|
* @type {Array.<number>}
|
|
* @const
|
|
* @inner
|
|
*/ var P_ORIG = [
|
|
0x243f6a88,
|
|
0x85a308d3,
|
|
0x13198a2e,
|
|
0x03707344,
|
|
0xa4093822,
|
|
0x299f31d0,
|
|
0x082efa98,
|
|
0xec4e6c89,
|
|
0x452821e6,
|
|
0x38d01377,
|
|
0xbe5466cf,
|
|
0x34e90c6c,
|
|
0xc0ac29b7,
|
|
0xc97c50dd,
|
|
0x3f84d5b5,
|
|
0xb5470917,
|
|
0x9216d5d9,
|
|
0x8979fb1b
|
|
];
|
|
/**
|
|
* @type {Array.<number>}
|
|
* @const
|
|
* @inner
|
|
*/ var S_ORIG = [
|
|
0xd1310ba6,
|
|
0x98dfb5ac,
|
|
0x2ffd72db,
|
|
0xd01adfb7,
|
|
0xb8e1afed,
|
|
0x6a267e96,
|
|
0xba7c9045,
|
|
0xf12c7f99,
|
|
0x24a19947,
|
|
0xb3916cf7,
|
|
0x0801f2e2,
|
|
0x858efc16,
|
|
0x636920d8,
|
|
0x71574e69,
|
|
0xa458fea3,
|
|
0xf4933d7e,
|
|
0x0d95748f,
|
|
0x728eb658,
|
|
0x718bcd58,
|
|
0x82154aee,
|
|
0x7b54a41d,
|
|
0xc25a59b5,
|
|
0x9c30d539,
|
|
0x2af26013,
|
|
0xc5d1b023,
|
|
0x286085f0,
|
|
0xca417918,
|
|
0xb8db38ef,
|
|
0x8e79dcb0,
|
|
0x603a180e,
|
|
0x6c9e0e8b,
|
|
0xb01e8a3e,
|
|
0xd71577c1,
|
|
0xbd314b27,
|
|
0x78af2fda,
|
|
0x55605c60,
|
|
0xe65525f3,
|
|
0xaa55ab94,
|
|
0x57489862,
|
|
0x63e81440,
|
|
0x55ca396a,
|
|
0x2aab10b6,
|
|
0xb4cc5c34,
|
|
0x1141e8ce,
|
|
0xa15486af,
|
|
0x7c72e993,
|
|
0xb3ee1411,
|
|
0x636fbc2a,
|
|
0x2ba9c55d,
|
|
0x741831f6,
|
|
0xce5c3e16,
|
|
0x9b87931e,
|
|
0xafd6ba33,
|
|
0x6c24cf5c,
|
|
0x7a325381,
|
|
0x28958677,
|
|
0x3b8f4898,
|
|
0x6b4bb9af,
|
|
0xc4bfe81b,
|
|
0x66282193,
|
|
0x61d809cc,
|
|
0xfb21a991,
|
|
0x487cac60,
|
|
0x5dec8032,
|
|
0xef845d5d,
|
|
0xe98575b1,
|
|
0xdc262302,
|
|
0xeb651b88,
|
|
0x23893e81,
|
|
0xd396acc5,
|
|
0x0f6d6ff3,
|
|
0x83f44239,
|
|
0x2e0b4482,
|
|
0xa4842004,
|
|
0x69c8f04a,
|
|
0x9e1f9b5e,
|
|
0x21c66842,
|
|
0xf6e96c9a,
|
|
0x670c9c61,
|
|
0xabd388f0,
|
|
0x6a51a0d2,
|
|
0xd8542f68,
|
|
0x960fa728,
|
|
0xab5133a3,
|
|
0x6eef0b6c,
|
|
0x137a3be4,
|
|
0xba3bf050,
|
|
0x7efb2a98,
|
|
0xa1f1651d,
|
|
0x39af0176,
|
|
0x66ca593e,
|
|
0x82430e88,
|
|
0x8cee8619,
|
|
0x456f9fb4,
|
|
0x7d84a5c3,
|
|
0x3b8b5ebe,
|
|
0xe06f75d8,
|
|
0x85c12073,
|
|
0x401a449f,
|
|
0x56c16aa6,
|
|
0x4ed3aa62,
|
|
0x363f7706,
|
|
0x1bfedf72,
|
|
0x429b023d,
|
|
0x37d0d724,
|
|
0xd00a1248,
|
|
0xdb0fead3,
|
|
0x49f1c09b,
|
|
0x075372c9,
|
|
0x80991b7b,
|
|
0x25d479d8,
|
|
0xf6e8def7,
|
|
0xe3fe501a,
|
|
0xb6794c3b,
|
|
0x976ce0bd,
|
|
0x04c006ba,
|
|
0xc1a94fb6,
|
|
0x409f60c4,
|
|
0x5e5c9ec2,
|
|
0x196a2463,
|
|
0x68fb6faf,
|
|
0x3e6c53b5,
|
|
0x1339b2eb,
|
|
0x3b52ec6f,
|
|
0x6dfc511f,
|
|
0x9b30952c,
|
|
0xcc814544,
|
|
0xaf5ebd09,
|
|
0xbee3d004,
|
|
0xde334afd,
|
|
0x660f2807,
|
|
0x192e4bb3,
|
|
0xc0cba857,
|
|
0x45c8740f,
|
|
0xd20b5f39,
|
|
0xb9d3fbdb,
|
|
0x5579c0bd,
|
|
0x1a60320a,
|
|
0xd6a100c6,
|
|
0x402c7279,
|
|
0x679f25fe,
|
|
0xfb1fa3cc,
|
|
0x8ea5e9f8,
|
|
0xdb3222f8,
|
|
0x3c7516df,
|
|
0xfd616b15,
|
|
0x2f501ec8,
|
|
0xad0552ab,
|
|
0x323db5fa,
|
|
0xfd238760,
|
|
0x53317b48,
|
|
0x3e00df82,
|
|
0x9e5c57bb,
|
|
0xca6f8ca0,
|
|
0x1a87562e,
|
|
0xdf1769db,
|
|
0xd542a8f6,
|
|
0x287effc3,
|
|
0xac6732c6,
|
|
0x8c4f5573,
|
|
0x695b27b0,
|
|
0xbbca58c8,
|
|
0xe1ffa35d,
|
|
0xb8f011a0,
|
|
0x10fa3d98,
|
|
0xfd2183b8,
|
|
0x4afcb56c,
|
|
0x2dd1d35b,
|
|
0x9a53e479,
|
|
0xb6f84565,
|
|
0xd28e49bc,
|
|
0x4bfb9790,
|
|
0xe1ddf2da,
|
|
0xa4cb7e33,
|
|
0x62fb1341,
|
|
0xcee4c6e8,
|
|
0xef20cada,
|
|
0x36774c01,
|
|
0xd07e9efe,
|
|
0x2bf11fb4,
|
|
0x95dbda4d,
|
|
0xae909198,
|
|
0xeaad8e71,
|
|
0x6b93d5a0,
|
|
0xd08ed1d0,
|
|
0xafc725e0,
|
|
0x8e3c5b2f,
|
|
0x8e7594b7,
|
|
0x8ff6e2fb,
|
|
0xf2122b64,
|
|
0x8888b812,
|
|
0x900df01c,
|
|
0x4fad5ea0,
|
|
0x688fc31c,
|
|
0xd1cff191,
|
|
0xb3a8c1ad,
|
|
0x2f2f2218,
|
|
0xbe0e1777,
|
|
0xea752dfe,
|
|
0x8b021fa1,
|
|
0xe5a0cc0f,
|
|
0xb56f74e8,
|
|
0x18acf3d6,
|
|
0xce89e299,
|
|
0xb4a84fe0,
|
|
0xfd13e0b7,
|
|
0x7cc43b81,
|
|
0xd2ada8d9,
|
|
0x165fa266,
|
|
0x80957705,
|
|
0x93cc7314,
|
|
0x211a1477,
|
|
0xe6ad2065,
|
|
0x77b5fa86,
|
|
0xc75442f5,
|
|
0xfb9d35cf,
|
|
0xebcdaf0c,
|
|
0x7b3e89a0,
|
|
0xd6411bd3,
|
|
0xae1e7e49,
|
|
0x00250e2d,
|
|
0x2071b35e,
|
|
0x226800bb,
|
|
0x57b8e0af,
|
|
0x2464369b,
|
|
0xf009b91e,
|
|
0x5563911d,
|
|
0x59dfa6aa,
|
|
0x78c14389,
|
|
0xd95a537f,
|
|
0x207d5ba2,
|
|
0x02e5b9c5,
|
|
0x83260376,
|
|
0x6295cfa9,
|
|
0x11c81968,
|
|
0x4e734a41,
|
|
0xb3472dca,
|
|
0x7b14a94a,
|
|
0x1b510052,
|
|
0x9a532915,
|
|
0xd60f573f,
|
|
0xbc9bc6e4,
|
|
0x2b60a476,
|
|
0x81e67400,
|
|
0x08ba6fb5,
|
|
0x571be91f,
|
|
0xf296ec6b,
|
|
0x2a0dd915,
|
|
0xb6636521,
|
|
0xe7b9f9b6,
|
|
0xff34052e,
|
|
0xc5855664,
|
|
0x53b02d5d,
|
|
0xa99f8fa1,
|
|
0x08ba4799,
|
|
0x6e85076a,
|
|
0x4b7a70e9,
|
|
0xb5b32944,
|
|
0xdb75092e,
|
|
0xc4192623,
|
|
0xad6ea6b0,
|
|
0x49a7df7d,
|
|
0x9cee60b8,
|
|
0x8fedb266,
|
|
0xecaa8c71,
|
|
0x699a17ff,
|
|
0x5664526c,
|
|
0xc2b19ee1,
|
|
0x193602a5,
|
|
0x75094c29,
|
|
0xa0591340,
|
|
0xe4183a3e,
|
|
0x3f54989a,
|
|
0x5b429d65,
|
|
0x6b8fe4d6,
|
|
0x99f73fd6,
|
|
0xa1d29c07,
|
|
0xefe830f5,
|
|
0x4d2d38e6,
|
|
0xf0255dc1,
|
|
0x4cdd2086,
|
|
0x8470eb26,
|
|
0x6382e9c6,
|
|
0x021ecc5e,
|
|
0x09686b3f,
|
|
0x3ebaefc9,
|
|
0x3c971814,
|
|
0x6b6a70a1,
|
|
0x687f3584,
|
|
0x52a0e286,
|
|
0xb79c5305,
|
|
0xaa500737,
|
|
0x3e07841c,
|
|
0x7fdeae5c,
|
|
0x8e7d44ec,
|
|
0x5716f2b8,
|
|
0xb03ada37,
|
|
0xf0500c0d,
|
|
0xf01c1f04,
|
|
0x0200b3ff,
|
|
0xae0cf51a,
|
|
0x3cb574b2,
|
|
0x25837a58,
|
|
0xdc0921bd,
|
|
0xd19113f9,
|
|
0x7ca92ff6,
|
|
0x94324773,
|
|
0x22f54701,
|
|
0x3ae5e581,
|
|
0x37c2dadc,
|
|
0xc8b57634,
|
|
0x9af3dda7,
|
|
0xa9446146,
|
|
0x0fd0030e,
|
|
0xecc8c73e,
|
|
0xa4751e41,
|
|
0xe238cd99,
|
|
0x3bea0e2f,
|
|
0x3280bba1,
|
|
0x183eb331,
|
|
0x4e548b38,
|
|
0x4f6db908,
|
|
0x6f420d03,
|
|
0xf60a04bf,
|
|
0x2cb81290,
|
|
0x24977c79,
|
|
0x5679b072,
|
|
0xbcaf89af,
|
|
0xde9a771f,
|
|
0xd9930810,
|
|
0xb38bae12,
|
|
0xdccf3f2e,
|
|
0x5512721f,
|
|
0x2e6b7124,
|
|
0x501adde6,
|
|
0x9f84cd87,
|
|
0x7a584718,
|
|
0x7408da17,
|
|
0xbc9f9abc,
|
|
0xe94b7d8c,
|
|
0xec7aec3a,
|
|
0xdb851dfa,
|
|
0x63094366,
|
|
0xc464c3d2,
|
|
0xef1c1847,
|
|
0x3215d908,
|
|
0xdd433b37,
|
|
0x24c2ba16,
|
|
0x12a14d43,
|
|
0x2a65c451,
|
|
0x50940002,
|
|
0x133ae4dd,
|
|
0x71dff89e,
|
|
0x10314e55,
|
|
0x81ac77d6,
|
|
0x5f11199b,
|
|
0x043556f1,
|
|
0xd7a3c76b,
|
|
0x3c11183b,
|
|
0x5924a509,
|
|
0xf28fe6ed,
|
|
0x97f1fbfa,
|
|
0x9ebabf2c,
|
|
0x1e153c6e,
|
|
0x86e34570,
|
|
0xeae96fb1,
|
|
0x860e5e0a,
|
|
0x5a3e2ab3,
|
|
0x771fe71c,
|
|
0x4e3d06fa,
|
|
0x2965dcb9,
|
|
0x99e71d0f,
|
|
0x803e89d6,
|
|
0x5266c825,
|
|
0x2e4cc978,
|
|
0x9c10b36a,
|
|
0xc6150eba,
|
|
0x94e2ea78,
|
|
0xa5fc3c53,
|
|
0x1e0a2df4,
|
|
0xf2f74ea7,
|
|
0x361d2b3d,
|
|
0x1939260f,
|
|
0x19c27960,
|
|
0x5223a708,
|
|
0xf71312b6,
|
|
0xebadfe6e,
|
|
0xeac31f66,
|
|
0xe3bc4595,
|
|
0xa67bc883,
|
|
0xb17f37d1,
|
|
0x018cff28,
|
|
0xc332ddef,
|
|
0xbe6c5aa5,
|
|
0x65582185,
|
|
0x68ab9802,
|
|
0xeecea50f,
|
|
0xdb2f953b,
|
|
0x2aef7dad,
|
|
0x5b6e2f84,
|
|
0x1521b628,
|
|
0x29076170,
|
|
0xecdd4775,
|
|
0x619f1510,
|
|
0x13cca830,
|
|
0xeb61bd96,
|
|
0x0334fe1e,
|
|
0xaa0363cf,
|
|
0xb5735c90,
|
|
0x4c70a239,
|
|
0xd59e9e0b,
|
|
0xcbaade14,
|
|
0xeecc86bc,
|
|
0x60622ca7,
|
|
0x9cab5cab,
|
|
0xb2f3846e,
|
|
0x648b1eaf,
|
|
0x19bdf0ca,
|
|
0xa02369b9,
|
|
0x655abb50,
|
|
0x40685a32,
|
|
0x3c2ab4b3,
|
|
0x319ee9d5,
|
|
0xc021b8f7,
|
|
0x9b540b19,
|
|
0x875fa099,
|
|
0x95f7997e,
|
|
0x623d7da8,
|
|
0xf837889a,
|
|
0x97e32d77,
|
|
0x11ed935f,
|
|
0x16681281,
|
|
0x0e358829,
|
|
0xc7e61fd6,
|
|
0x96dedfa1,
|
|
0x7858ba99,
|
|
0x57f584a5,
|
|
0x1b227263,
|
|
0x9b83c3ff,
|
|
0x1ac24696,
|
|
0xcdb30aeb,
|
|
0x532e3054,
|
|
0x8fd948e4,
|
|
0x6dbc3128,
|
|
0x58ebf2ef,
|
|
0x34c6ffea,
|
|
0xfe28ed61,
|
|
0xee7c3c73,
|
|
0x5d4a14d9,
|
|
0xe864b7e3,
|
|
0x42105d14,
|
|
0x203e13e0,
|
|
0x45eee2b6,
|
|
0xa3aaabea,
|
|
0xdb6c4f15,
|
|
0xfacb4fd0,
|
|
0xc742f442,
|
|
0xef6abbb5,
|
|
0x654f3b1d,
|
|
0x41cd2105,
|
|
0xd81e799e,
|
|
0x86854dc7,
|
|
0xe44b476a,
|
|
0x3d816250,
|
|
0xcf62a1f2,
|
|
0x5b8d2646,
|
|
0xfc8883a0,
|
|
0xc1c7b6a3,
|
|
0x7f1524c3,
|
|
0x69cb7492,
|
|
0x47848a0b,
|
|
0x5692b285,
|
|
0x095bbf00,
|
|
0xad19489d,
|
|
0x1462b174,
|
|
0x23820e00,
|
|
0x58428d2a,
|
|
0x0c55f5ea,
|
|
0x1dadf43e,
|
|
0x233f7061,
|
|
0x3372f092,
|
|
0x8d937e41,
|
|
0xd65fecf1,
|
|
0x6c223bdb,
|
|
0x7cde3759,
|
|
0xcbee7460,
|
|
0x4085f2a7,
|
|
0xce77326e,
|
|
0xa6078084,
|
|
0x19f8509e,
|
|
0xe8efd855,
|
|
0x61d99735,
|
|
0xa969a7aa,
|
|
0xc50c06c2,
|
|
0x5a04abfc,
|
|
0x800bcadc,
|
|
0x9e447a2e,
|
|
0xc3453484,
|
|
0xfdd56705,
|
|
0x0e1e9ec9,
|
|
0xdb73dbd3,
|
|
0x105588cd,
|
|
0x675fda79,
|
|
0xe3674340,
|
|
0xc5c43465,
|
|
0x713e38d8,
|
|
0x3d28f89e,
|
|
0xf16dff20,
|
|
0x153e21e7,
|
|
0x8fb03d4a,
|
|
0xe6e39f2b,
|
|
0xdb83adf7,
|
|
0xe93d5a68,
|
|
0x948140f7,
|
|
0xf64c261c,
|
|
0x94692934,
|
|
0x411520f7,
|
|
0x7602d4f7,
|
|
0xbcf46b2e,
|
|
0xd4a20068,
|
|
0xd4082471,
|
|
0x3320f46a,
|
|
0x43b7d4b7,
|
|
0x500061af,
|
|
0x1e39f62e,
|
|
0x97244546,
|
|
0x14214f74,
|
|
0xbf8b8840,
|
|
0x4d95fc1d,
|
|
0x96b591af,
|
|
0x70f4ddd3,
|
|
0x66a02f45,
|
|
0xbfbc09ec,
|
|
0x03bd9785,
|
|
0x7fac6dd0,
|
|
0x31cb8504,
|
|
0x96eb27b3,
|
|
0x55fd3941,
|
|
0xda2547e6,
|
|
0xabca0a9a,
|
|
0x28507825,
|
|
0x530429f4,
|
|
0x0a2c86da,
|
|
0xe9b66dfb,
|
|
0x68dc1462,
|
|
0xd7486900,
|
|
0x680ec0a4,
|
|
0x27a18dee,
|
|
0x4f3ffea2,
|
|
0xe887ad8c,
|
|
0xb58ce006,
|
|
0x7af4d6b6,
|
|
0xaace1e7c,
|
|
0xd3375fec,
|
|
0xce78a399,
|
|
0x406b2a42,
|
|
0x20fe9e35,
|
|
0xd9f385b9,
|
|
0xee39d7ab,
|
|
0x3b124e8b,
|
|
0x1dc9faf7,
|
|
0x4b6d1856,
|
|
0x26a36631,
|
|
0xeae397b2,
|
|
0x3a6efa74,
|
|
0xdd5b4332,
|
|
0x6841e7f7,
|
|
0xca7820fb,
|
|
0xfb0af54e,
|
|
0xd8feb397,
|
|
0x454056ac,
|
|
0xba489527,
|
|
0x55533a3a,
|
|
0x20838d87,
|
|
0xfe6ba9b7,
|
|
0xd096954b,
|
|
0x55a867bc,
|
|
0xa1159a58,
|
|
0xcca92963,
|
|
0x99e1db33,
|
|
0xa62a4a56,
|
|
0x3f3125f9,
|
|
0x5ef47e1c,
|
|
0x9029317c,
|
|
0xfdf8e802,
|
|
0x04272f70,
|
|
0x80bb155c,
|
|
0x05282ce3,
|
|
0x95c11548,
|
|
0xe4c66d22,
|
|
0x48c1133f,
|
|
0xc70f86dc,
|
|
0x07f9c9ee,
|
|
0x41041f0f,
|
|
0x404779a4,
|
|
0x5d886e17,
|
|
0x325f51eb,
|
|
0xd59bc0d1,
|
|
0xf2bcc18f,
|
|
0x41113564,
|
|
0x257b7834,
|
|
0x602a9c60,
|
|
0xdff8e8a3,
|
|
0x1f636c1b,
|
|
0x0e12b4c2,
|
|
0x02e1329e,
|
|
0xaf664fd1,
|
|
0xcad18115,
|
|
0x6b2395e0,
|
|
0x333e92e1,
|
|
0x3b240b62,
|
|
0xeebeb922,
|
|
0x85b2a20e,
|
|
0xe6ba0d99,
|
|
0xde720c8c,
|
|
0x2da2f728,
|
|
0xd0127845,
|
|
0x95b794fd,
|
|
0x647d0862,
|
|
0xe7ccf5f0,
|
|
0x5449a36f,
|
|
0x877d48fa,
|
|
0xc39dfd27,
|
|
0xf33e8d1e,
|
|
0x0a476341,
|
|
0x992eff74,
|
|
0x3a6f6eab,
|
|
0xf4f8fd37,
|
|
0xa812dc60,
|
|
0xa1ebddf8,
|
|
0x991be14c,
|
|
0xdb6e6b0d,
|
|
0xc67b5510,
|
|
0x6d672c37,
|
|
0x2765d43b,
|
|
0xdcd0e804,
|
|
0xf1290dc7,
|
|
0xcc00ffa3,
|
|
0xb5390f92,
|
|
0x690fed0b,
|
|
0x667b9ffb,
|
|
0xcedb7d9c,
|
|
0xa091cf0b,
|
|
0xd9155ea3,
|
|
0xbb132f88,
|
|
0x515bad24,
|
|
0x7b9479bf,
|
|
0x763bd6eb,
|
|
0x37392eb3,
|
|
0xcc115979,
|
|
0x8026e297,
|
|
0xf42e312d,
|
|
0x6842ada7,
|
|
0xc66a2b3b,
|
|
0x12754ccc,
|
|
0x782ef11c,
|
|
0x6a124237,
|
|
0xb79251e7,
|
|
0x06a1bbe6,
|
|
0x4bfb6350,
|
|
0x1a6b1018,
|
|
0x11caedfa,
|
|
0x3d25bdd8,
|
|
0xe2e1c3c9,
|
|
0x44421659,
|
|
0x0a121386,
|
|
0xd90cec6e,
|
|
0xd5abea2a,
|
|
0x64af674e,
|
|
0xda86a85f,
|
|
0xbebfe988,
|
|
0x64e4c3fe,
|
|
0x9dbc8057,
|
|
0xf0f7c086,
|
|
0x60787bf8,
|
|
0x6003604d,
|
|
0xd1fd8346,
|
|
0xf6381fb0,
|
|
0x7745ae04,
|
|
0xd736fccc,
|
|
0x83426b33,
|
|
0xf01eab71,
|
|
0xb0804187,
|
|
0x3c005e5f,
|
|
0x77a057be,
|
|
0xbde8ae24,
|
|
0x55464299,
|
|
0xbf582e61,
|
|
0x4e58f48f,
|
|
0xf2ddfda2,
|
|
0xf474ef38,
|
|
0x8789bdc2,
|
|
0x5366f9c3,
|
|
0xc8b38e74,
|
|
0xb475f255,
|
|
0x46fcd9b9,
|
|
0x7aeb2661,
|
|
0x8b1ddf84,
|
|
0x846a0e79,
|
|
0x915f95e2,
|
|
0x466e598e,
|
|
0x20b45770,
|
|
0x8cd55591,
|
|
0xc902de4c,
|
|
0xb90bace1,
|
|
0xbb8205d0,
|
|
0x11a86248,
|
|
0x7574a99e,
|
|
0xb77f19b6,
|
|
0xe0a9dc09,
|
|
0x662d09a1,
|
|
0xc4324633,
|
|
0xe85a1f02,
|
|
0x09f0be8c,
|
|
0x4a99a025,
|
|
0x1d6efe10,
|
|
0x1ab93d1d,
|
|
0x0ba5a4df,
|
|
0xa186f20f,
|
|
0x2868f169,
|
|
0xdcb7da83,
|
|
0x573906fe,
|
|
0xa1e2ce9b,
|
|
0x4fcd7f52,
|
|
0x50115e01,
|
|
0xa70683fa,
|
|
0xa002b5c4,
|
|
0x0de6d027,
|
|
0x9af88c27,
|
|
0x773f8641,
|
|
0xc3604c06,
|
|
0x61a806b5,
|
|
0xf0177a28,
|
|
0xc0f586e0,
|
|
0x006058aa,
|
|
0x30dc7d62,
|
|
0x11e69ed7,
|
|
0x2338ea63,
|
|
0x53c2dd94,
|
|
0xc2c21634,
|
|
0xbbcbee56,
|
|
0x90bcb6de,
|
|
0xebfc7da1,
|
|
0xce591d76,
|
|
0x6f05e409,
|
|
0x4b7c0188,
|
|
0x39720a3d,
|
|
0x7c927c24,
|
|
0x86e3725f,
|
|
0x724d9db9,
|
|
0x1ac15bb4,
|
|
0xd39eb8fc,
|
|
0xed545578,
|
|
0x08fca5b5,
|
|
0xd83d7cd3,
|
|
0x4dad0fc4,
|
|
0x1e50ef5e,
|
|
0xb161e6f8,
|
|
0xa28514d9,
|
|
0x6c51133c,
|
|
0x6fd5c7e7,
|
|
0x56e14ec4,
|
|
0x362abfce,
|
|
0xddc6c837,
|
|
0xd79a3234,
|
|
0x92638212,
|
|
0x670efa8e,
|
|
0x406000e0,
|
|
0x3a39ce37,
|
|
0xd3faf5cf,
|
|
0xabc27737,
|
|
0x5ac52d1b,
|
|
0x5cb0679e,
|
|
0x4fa33742,
|
|
0xd3822740,
|
|
0x99bc9bbe,
|
|
0xd5118e9d,
|
|
0xbf0f7315,
|
|
0xd62d1c7e,
|
|
0xc700c47b,
|
|
0xb78c1b6b,
|
|
0x21a19045,
|
|
0xb26eb1be,
|
|
0x6a366eb4,
|
|
0x5748ab2f,
|
|
0xbc946e79,
|
|
0xc6a376d2,
|
|
0x6549c2c8,
|
|
0x530ff8ee,
|
|
0x468dde7d,
|
|
0xd5730a1d,
|
|
0x4cd04dc6,
|
|
0x2939bbdb,
|
|
0xa9ba4650,
|
|
0xac9526e8,
|
|
0xbe5ee304,
|
|
0xa1fad5f0,
|
|
0x6a2d519a,
|
|
0x63ef8ce2,
|
|
0x9a86ee22,
|
|
0xc089c2b8,
|
|
0x43242ef6,
|
|
0xa51e03aa,
|
|
0x9cf2d0a4,
|
|
0x83c061ba,
|
|
0x9be96a4d,
|
|
0x8fe51550,
|
|
0xba645bd6,
|
|
0x2826a2f9,
|
|
0xa73a3ae1,
|
|
0x4ba99586,
|
|
0xef5562e9,
|
|
0xc72fefd3,
|
|
0xf752f7da,
|
|
0x3f046f69,
|
|
0x77fa0a59,
|
|
0x80e4a915,
|
|
0x87b08601,
|
|
0x9b09e6ad,
|
|
0x3b3ee593,
|
|
0xe990fd5a,
|
|
0x9e34d797,
|
|
0x2cf0b7d9,
|
|
0x022b8b51,
|
|
0x96d5ac3a,
|
|
0x017da67d,
|
|
0xd1cf3ed6,
|
|
0x7c7d2d28,
|
|
0x1f9f25cf,
|
|
0xadf2b89b,
|
|
0x5ad6b472,
|
|
0x5a88f54c,
|
|
0xe029ac71,
|
|
0xe019a5e6,
|
|
0x47b0acfd,
|
|
0xed93fa9b,
|
|
0xe8d3c48d,
|
|
0x283b57cc,
|
|
0xf8d56629,
|
|
0x79132e28,
|
|
0x785f0191,
|
|
0xed756055,
|
|
0xf7960e44,
|
|
0xe3d35e8c,
|
|
0x15056dd4,
|
|
0x88f46dba,
|
|
0x03a16125,
|
|
0x0564f0bd,
|
|
0xc3eb9e15,
|
|
0x3c9057a2,
|
|
0x97271aec,
|
|
0xa93a072a,
|
|
0x1b3f6d9b,
|
|
0x1e6321f5,
|
|
0xf59c66fb,
|
|
0x26dcf319,
|
|
0x7533d928,
|
|
0xb155fdf5,
|
|
0x03563482,
|
|
0x8aba3cbb,
|
|
0x28517711,
|
|
0xc20ad9f8,
|
|
0xabcc5167,
|
|
0xccad925f,
|
|
0x4de81751,
|
|
0x3830dc8e,
|
|
0x379d5862,
|
|
0x9320f991,
|
|
0xea7a90c2,
|
|
0xfb3e7bce,
|
|
0x5121ce64,
|
|
0x774fbe32,
|
|
0xa8b6e37e,
|
|
0xc3293d46,
|
|
0x48de5369,
|
|
0x6413e680,
|
|
0xa2ae0810,
|
|
0xdd6db224,
|
|
0x69852dfd,
|
|
0x09072166,
|
|
0xb39a460a,
|
|
0x6445c0dd,
|
|
0x586cdecf,
|
|
0x1c20c8ae,
|
|
0x5bbef7dd,
|
|
0x1b588d40,
|
|
0xccd2017f,
|
|
0x6bb4e3bb,
|
|
0xdda26a7e,
|
|
0x3a59ff45,
|
|
0x3e350a44,
|
|
0xbcb4cdd5,
|
|
0x72eacea8,
|
|
0xfa6484bb,
|
|
0x8d6612ae,
|
|
0xbf3c6f47,
|
|
0xd29be463,
|
|
0x542f5d9e,
|
|
0xaec2771b,
|
|
0xf64e6370,
|
|
0x740e0d8d,
|
|
0xe75b1357,
|
|
0xf8721671,
|
|
0xaf537d5d,
|
|
0x4040cb08,
|
|
0x4eb4e2cc,
|
|
0x34d2466a,
|
|
0x0115af84,
|
|
0xe1b00428,
|
|
0x95983a1d,
|
|
0x06b89fb4,
|
|
0xce6ea048,
|
|
0x6f3f3b82,
|
|
0x3520ab82,
|
|
0x011a1d4b,
|
|
0x277227f8,
|
|
0x611560b1,
|
|
0xe7933fdc,
|
|
0xbb3a792b,
|
|
0x344525bd,
|
|
0xa08839e1,
|
|
0x51ce794b,
|
|
0x2f32c9b7,
|
|
0xa01fbac9,
|
|
0xe01cc87e,
|
|
0xbcc7d1f6,
|
|
0xcf0111c3,
|
|
0xa1e8aac7,
|
|
0x1a908749,
|
|
0xd44fbd9a,
|
|
0xd0dadecb,
|
|
0xd50ada38,
|
|
0x0339c32a,
|
|
0xc6913667,
|
|
0x8df9317c,
|
|
0xe0b12b4f,
|
|
0xf79e59b7,
|
|
0x43f5bb3a,
|
|
0xf2d519ff,
|
|
0x27d9459c,
|
|
0xbf97222c,
|
|
0x15e6fc2a,
|
|
0x0f91fc71,
|
|
0x9b941525,
|
|
0xfae59361,
|
|
0xceb69ceb,
|
|
0xc2a86459,
|
|
0x12baa8d1,
|
|
0xb6c1075e,
|
|
0xe3056a0c,
|
|
0x10d25065,
|
|
0xcb03a442,
|
|
0xe0ec6e0e,
|
|
0x1698db3b,
|
|
0x4c98a0be,
|
|
0x3278e964,
|
|
0x9f1f9532,
|
|
0xe0d392df,
|
|
0xd3a0342b,
|
|
0x8971f21e,
|
|
0x1b0a7441,
|
|
0x4ba3348c,
|
|
0xc5be7120,
|
|
0xc37632d8,
|
|
0xdf359f8d,
|
|
0x9b992f2e,
|
|
0xe60b6f47,
|
|
0x0fe3f11d,
|
|
0xe54cda54,
|
|
0x1edad891,
|
|
0xce6279cf,
|
|
0xcd3e7e6f,
|
|
0x1618b166,
|
|
0xfd2c1d05,
|
|
0x848fd2c5,
|
|
0xf6fb2299,
|
|
0xf523f357,
|
|
0xa6327623,
|
|
0x93a83531,
|
|
0x56cccd02,
|
|
0xacf08162,
|
|
0x5a75ebb5,
|
|
0x6e163697,
|
|
0x88d273cc,
|
|
0xde966292,
|
|
0x81b949d0,
|
|
0x4c50901b,
|
|
0x71c65614,
|
|
0xe6c6c7bd,
|
|
0x327a140a,
|
|
0x45e1d006,
|
|
0xc3f27b9a,
|
|
0xc9aa53fd,
|
|
0x62a80f00,
|
|
0xbb25bfe2,
|
|
0x35bdd2f6,
|
|
0x71126905,
|
|
0xb2040222,
|
|
0xb6cbcf7c,
|
|
0xcd769c2b,
|
|
0x53113ec0,
|
|
0x1640e3d3,
|
|
0x38abbd60,
|
|
0x2547adf0,
|
|
0xba38209c,
|
|
0xf746ce76,
|
|
0x77afa1c5,
|
|
0x20756060,
|
|
0x85cbfe4e,
|
|
0x8ae88dd8,
|
|
0x7aaaf9b0,
|
|
0x4cf9aa7e,
|
|
0x1948c25c,
|
|
0x02fb8a8c,
|
|
0x01c36ae4,
|
|
0xd6ebe1f9,
|
|
0x90d4f869,
|
|
0xa65cdea0,
|
|
0x3f09252d,
|
|
0xc208e69f,
|
|
0xb74e6132,
|
|
0xce77e25b,
|
|
0x578fdfe3,
|
|
0x3ac372e6
|
|
];
|
|
/**
|
|
* @type {Array.<number>}
|
|
* @const
|
|
* @inner
|
|
*/ var C_ORIG = [
|
|
0x4f727068,
|
|
0x65616e42,
|
|
0x65686f6c,
|
|
0x64657253,
|
|
0x63727944,
|
|
0x6f756274
|
|
];
|
|
/**
|
|
* @param {Array.<number>} lr
|
|
* @param {number} off
|
|
* @param {Array.<number>} P
|
|
* @param {Array.<number>} S
|
|
* @returns {Array.<number>}
|
|
* @inner
|
|
*/ function _encipher(lr, off, P, S) {
|
|
// This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt
|
|
var n, l = lr[off], r = lr[off + 1];
|
|
l ^= P[0];
|
|
/*
|
|
for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;)
|
|
// Feistel substitution on left word
|
|
n = S[l >>> 24],
|
|
n += S[0x100 | ((l >> 16) & 0xff)],
|
|
n ^= S[0x200 | ((l >> 8) & 0xff)],
|
|
n += S[0x300 | (l & 0xff)],
|
|
r ^= n ^ P[++i],
|
|
// Feistel substitution on right word
|
|
n = S[r >>> 24],
|
|
n += S[0x100 | ((r >> 16) & 0xff)],
|
|
n ^= S[0x200 | ((r >> 8) & 0xff)],
|
|
n += S[0x300 | (r & 0xff)],
|
|
l ^= n ^ P[++i];
|
|
*/ //The following is an unrolled version of the above loop.
|
|
//Iteration 0
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[1];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[2];
|
|
//Iteration 1
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[3];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[4];
|
|
//Iteration 2
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[5];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[6];
|
|
//Iteration 3
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[7];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[8];
|
|
//Iteration 4
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[9];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[10];
|
|
//Iteration 5
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[11];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[12];
|
|
//Iteration 6
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[13];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[14];
|
|
//Iteration 7
|
|
n = S[l >>> 24];
|
|
n += S[0x100 | l >> 16 & 0xff];
|
|
n ^= S[0x200 | l >> 8 & 0xff];
|
|
n += S[0x300 | l & 0xff];
|
|
r ^= n ^ P[15];
|
|
n = S[r >>> 24];
|
|
n += S[0x100 | r >> 16 & 0xff];
|
|
n ^= S[0x200 | r >> 8 & 0xff];
|
|
n += S[0x300 | r & 0xff];
|
|
l ^= n ^ P[16];
|
|
lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
|
|
lr[off + 1] = l;
|
|
return lr;
|
|
}
|
|
/**
|
|
* @param {Array.<number>} data
|
|
* @param {number} offp
|
|
* @returns {{key: number, offp: number}}
|
|
* @inner
|
|
*/ function _streamtoword(data, offp) {
|
|
for(var i = 0, word = 0; i < 4; ++i)word = word << 8 | data[offp] & 0xff, offp = (offp + 1) % data.length;
|
|
return {
|
|
key: word,
|
|
offp: offp
|
|
};
|
|
}
|
|
/**
|
|
* @param {Array.<number>} key
|
|
* @param {Array.<number>} P
|
|
* @param {Array.<number>} S
|
|
* @inner
|
|
*/ function _key(key, P, S) {
|
|
var offset = 0, lr = [
|
|
0,
|
|
0
|
|
], plen = P.length, slen = S.length, sw;
|
|
for(var i = 0; i < plen; i++)sw = _streamtoword(key, offset), offset = sw.offp, P[i] = P[i] ^ sw.key;
|
|
for(i = 0; i < plen; i += 2)lr = _encipher(lr, 0, P, S), P[i] = lr[0], P[i + 1] = lr[1];
|
|
for(i = 0; i < slen; i += 2)lr = _encipher(lr, 0, P, S), S[i] = lr[0], S[i + 1] = lr[1];
|
|
}
|
|
/**
|
|
* Expensive key schedule Blowfish.
|
|
* @param {Array.<number>} data
|
|
* @param {Array.<number>} key
|
|
* @param {Array.<number>} P
|
|
* @param {Array.<number>} S
|
|
* @inner
|
|
*/ function _ekskey(data, key, P, S) {
|
|
var offp = 0, lr = [
|
|
0,
|
|
0
|
|
], plen = P.length, slen = S.length, sw;
|
|
for(var i = 0; i < plen; i++)sw = _streamtoword(key, offp), offp = sw.offp, P[i] = P[i] ^ sw.key;
|
|
offp = 0;
|
|
for(i = 0; i < plen; i += 2)sw = _streamtoword(data, offp), offp = sw.offp, lr[0] ^= sw.key, sw = _streamtoword(data, offp), offp = sw.offp, lr[1] ^= sw.key, lr = _encipher(lr, 0, P, S), P[i] = lr[0], P[i + 1] = lr[1];
|
|
for(i = 0; i < slen; i += 2)sw = _streamtoword(data, offp), offp = sw.offp, lr[0] ^= sw.key, sw = _streamtoword(data, offp), offp = sw.offp, lr[1] ^= sw.key, lr = _encipher(lr, 0, P, S), S[i] = lr[0], S[i + 1] = lr[1];
|
|
}
|
|
/**
|
|
* Internaly crypts a string.
|
|
* @param {Array.<number>} b Bytes to crypt
|
|
* @param {Array.<number>} salt Salt bytes to use
|
|
* @param {number} rounds Number of rounds
|
|
* @param {function(Error, Array.<number>=)=} callback Callback receiving the error, if any, and the resulting bytes. If
|
|
* omitted, the operation will be performed synchronously.
|
|
* @param {function(number)=} progressCallback Callback called with the current progress
|
|
* @returns {!Array.<number>|undefined} Resulting bytes if callback has been omitted, otherwise `undefined`
|
|
* @inner
|
|
*/ function _crypt(b, salt, rounds, callback, progressCallback) {
|
|
var cdata = C_ORIG.slice(), clen = cdata.length, err;
|
|
// Validate
|
|
if (rounds < 4 || rounds > 31) {
|
|
err = Error("Illegal number of rounds (4-31): " + rounds);
|
|
if (callback) {
|
|
nextTick(callback.bind(this, err));
|
|
return;
|
|
} else throw err;
|
|
}
|
|
if (salt.length !== BCRYPT_SALT_LEN) {
|
|
err = Error("Illegal salt length: " + salt.length + " != " + BCRYPT_SALT_LEN);
|
|
if (callback) {
|
|
nextTick(callback.bind(this, err));
|
|
return;
|
|
} else throw err;
|
|
}
|
|
rounds = 1 << rounds >>> 0;
|
|
var P, S, i = 0, j;
|
|
//Use typed arrays when available - huge speedup!
|
|
if (typeof Int32Array === "function") {
|
|
P = new Int32Array(P_ORIG);
|
|
S = new Int32Array(S_ORIG);
|
|
} else {
|
|
P = P_ORIG.slice();
|
|
S = S_ORIG.slice();
|
|
}
|
|
_ekskey(salt, b, P, S);
|
|
/**
|
|
* Calcualtes the next round.
|
|
* @returns {Array.<number>|undefined} Resulting array if callback has been omitted, otherwise `undefined`
|
|
* @inner
|
|
*/ function next() {
|
|
if (progressCallback) progressCallback(i / rounds);
|
|
if (i < rounds) {
|
|
var start = Date.now();
|
|
for(; i < rounds;){
|
|
i = i + 1;
|
|
_key(b, P, S);
|
|
_key(salt, P, S);
|
|
if (Date.now() - start > MAX_EXECUTION_TIME) break;
|
|
}
|
|
} else {
|
|
for(i = 0; i < 64; i++)for(j = 0; j < clen >> 1; j++)_encipher(cdata, j << 1, P, S);
|
|
var ret = [];
|
|
for(i = 0; i < clen; i++)ret.push((cdata[i] >> 24 & 0xff) >>> 0), ret.push((cdata[i] >> 16 & 0xff) >>> 0), ret.push((cdata[i] >> 8 & 0xff) >>> 0), ret.push((cdata[i] & 0xff) >>> 0);
|
|
if (callback) {
|
|
callback(null, ret);
|
|
return;
|
|
} else return ret;
|
|
}
|
|
if (callback) nextTick(next);
|
|
}
|
|
// Async
|
|
if (typeof callback !== "undefined") {
|
|
next();
|
|
// Sync
|
|
} else {
|
|
var res;
|
|
while(true)if (typeof (res = next()) !== "undefined") return res || [];
|
|
}
|
|
}
|
|
/**
|
|
* Internally hashes a password.
|
|
* @param {string} password Password to hash
|
|
* @param {?string} salt Salt to use, actually never null
|
|
* @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted,
|
|
* hashing is performed synchronously.
|
|
* @param {function(number)=} progressCallback Callback called with the current progress
|
|
* @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined`
|
|
* @inner
|
|
*/ function _hash(password, salt, callback, progressCallback) {
|
|
var err;
|
|
if (typeof password !== "string" || typeof salt !== "string") {
|
|
err = Error("Invalid string / salt: Not a string");
|
|
if (callback) {
|
|
nextTick(callback.bind(this, err));
|
|
return;
|
|
} else throw err;
|
|
}
|
|
// Validate the salt
|
|
var minor, offset;
|
|
if (salt.charAt(0) !== "$" || salt.charAt(1) !== "2") {
|
|
err = Error("Invalid salt version: " + salt.substring(0, 2));
|
|
if (callback) {
|
|
nextTick(callback.bind(this, err));
|
|
return;
|
|
} else throw err;
|
|
}
|
|
if (salt.charAt(2) === "$") minor = String.fromCharCode(0), offset = 3;
|
|
else {
|
|
minor = salt.charAt(2);
|
|
if (minor !== "a" && minor !== "b" && minor !== "y" || salt.charAt(3) !== "$") {
|
|
err = Error("Invalid salt revision: " + salt.substring(2, 4));
|
|
if (callback) {
|
|
nextTick(callback.bind(this, err));
|
|
return;
|
|
} else throw err;
|
|
}
|
|
offset = 4;
|
|
}
|
|
// Extract number of rounds
|
|
if (salt.charAt(offset + 2) > "$") {
|
|
err = Error("Missing salt rounds");
|
|
if (callback) {
|
|
nextTick(callback.bind(this, err));
|
|
return;
|
|
} else throw err;
|
|
}
|
|
var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), rounds = r1 + r2, real_salt = salt.substring(offset + 3, offset + 25);
|
|
password += minor >= "a" ? "\x00" : "";
|
|
var passwordb = utf8Array(password), saltb = base64_decode(real_salt, BCRYPT_SALT_LEN);
|
|
/**
|
|
* Finishes hashing.
|
|
* @param {Array.<number>} bytes Byte array
|
|
* @returns {string}
|
|
* @inner
|
|
*/ function finish(bytes) {
|
|
var res = [];
|
|
res.push("$2");
|
|
if (minor >= "a") res.push(minor);
|
|
res.push("$");
|
|
if (rounds < 10) res.push("0");
|
|
res.push(rounds.toString());
|
|
res.push("$");
|
|
res.push(base64_encode(saltb, saltb.length));
|
|
res.push(base64_encode(bytes, C_ORIG.length * 4 - 1));
|
|
return res.join("");
|
|
}
|
|
// Sync
|
|
if (typeof callback == "undefined") return finish(_crypt(passwordb, saltb, rounds));
|
|
else {
|
|
_crypt(passwordb, saltb, rounds, function(err, bytes) {
|
|
if (err) callback(err, null);
|
|
else callback(null, finish(bytes));
|
|
}, progressCallback);
|
|
}
|
|
}
|
|
function encodeBase64(bytes, length) {
|
|
return base64_encode(bytes, length);
|
|
}
|
|
function decodeBase64(string, length) {
|
|
return base64_decode(string, length);
|
|
}
|
|
const __TURBOPACK__default__export__ = {
|
|
setRandomFallback,
|
|
genSaltSync,
|
|
genSalt,
|
|
hashSync,
|
|
hash,
|
|
compareSync,
|
|
compare,
|
|
getRounds,
|
|
getSalt,
|
|
truncates,
|
|
encodeBase64,
|
|
decodeBase64
|
|
};
|
|
}),
|
|
"[externals]/@prisma/client [external] (@prisma/client, cjs, [project]/Documents/00 - projet/plumeia/node_modules/@prisma/client)", ((__turbopack_context__, module, exports) => {
|
|
|
|
const mod = __turbopack_context__.x("@prisma/client-5d1deb26a67ff978", () => require("@prisma/client-5d1deb26a67ff978"));
|
|
|
|
module.exports = mod;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/@prisma/debug/dist/index.mjs [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"Debug",
|
|
()=>Debug,
|
|
"clearLogs",
|
|
()=>clearLogs,
|
|
"default",
|
|
()=>index_default,
|
|
"getLogs",
|
|
()=>getLogs
|
|
]);
|
|
var __defProp = Object.defineProperty;
|
|
var __export = (target, all)=>{
|
|
for(var name in all)__defProp(target, name, {
|
|
get: all[name],
|
|
enumerable: true
|
|
});
|
|
};
|
|
// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs
|
|
var colors_exports = {};
|
|
__export(colors_exports, {
|
|
$: ()=>$,
|
|
bgBlack: ()=>bgBlack,
|
|
bgBlue: ()=>bgBlue,
|
|
bgCyan: ()=>bgCyan,
|
|
bgGreen: ()=>bgGreen,
|
|
bgMagenta: ()=>bgMagenta,
|
|
bgRed: ()=>bgRed,
|
|
bgWhite: ()=>bgWhite,
|
|
bgYellow: ()=>bgYellow,
|
|
black: ()=>black,
|
|
blue: ()=>blue,
|
|
bold: ()=>bold,
|
|
cyan: ()=>cyan,
|
|
dim: ()=>dim,
|
|
gray: ()=>gray,
|
|
green: ()=>green,
|
|
grey: ()=>grey,
|
|
hidden: ()=>hidden,
|
|
inverse: ()=>inverse,
|
|
italic: ()=>italic,
|
|
magenta: ()=>magenta,
|
|
red: ()=>red,
|
|
reset: ()=>reset,
|
|
strikethrough: ()=>strikethrough,
|
|
underline: ()=>underline,
|
|
white: ()=>white,
|
|
yellow: ()=>yellow
|
|
});
|
|
var FORCE_COLOR;
|
|
var NODE_DISABLE_COLORS;
|
|
var NO_COLOR;
|
|
var TERM;
|
|
var isTTY = true;
|
|
if (typeof process !== "undefined") {
|
|
({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
|
|
isTTY = process.stdout && process.stdout.isTTY;
|
|
}
|
|
var $ = {
|
|
enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
|
|
};
|
|
function init(x, y) {
|
|
let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
|
|
let open = `\x1B[${x}m`, close = `\x1B[${y}m`;
|
|
return function(txt) {
|
|
if (!$.enabled || txt == null) return txt;
|
|
return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
|
|
};
|
|
}
|
|
var reset = init(0, 0);
|
|
var bold = init(1, 22);
|
|
var dim = init(2, 22);
|
|
var italic = init(3, 23);
|
|
var underline = init(4, 24);
|
|
var inverse = init(7, 27);
|
|
var hidden = init(8, 28);
|
|
var strikethrough = init(9, 29);
|
|
var black = init(30, 39);
|
|
var red = init(31, 39);
|
|
var green = init(32, 39);
|
|
var yellow = init(33, 39);
|
|
var blue = init(34, 39);
|
|
var magenta = init(35, 39);
|
|
var cyan = init(36, 39);
|
|
var white = init(37, 39);
|
|
var gray = init(90, 39);
|
|
var grey = init(90, 39);
|
|
var bgBlack = init(40, 49);
|
|
var bgRed = init(41, 49);
|
|
var bgGreen = init(42, 49);
|
|
var bgYellow = init(43, 49);
|
|
var bgBlue = init(44, 49);
|
|
var bgMagenta = init(45, 49);
|
|
var bgCyan = init(46, 49);
|
|
var bgWhite = init(47, 49);
|
|
// src/index.ts
|
|
var MAX_ARGS_HISTORY = 100;
|
|
var COLORS = [
|
|
"green",
|
|
"yellow",
|
|
"blue",
|
|
"magenta",
|
|
"cyan",
|
|
"red"
|
|
];
|
|
var argsHistory = [];
|
|
var lastTimestamp = Date.now();
|
|
var lastColor = 0;
|
|
var processEnv = typeof process !== "undefined" ? process.env : {};
|
|
globalThis.DEBUG ??= processEnv.DEBUG ?? "";
|
|
globalThis.DEBUG_COLORS ??= processEnv.DEBUG_COLORS ? processEnv.DEBUG_COLORS === "true" : true;
|
|
var topProps = {
|
|
enable (namespace) {
|
|
if (typeof namespace === "string") {
|
|
globalThis.DEBUG = namespace;
|
|
}
|
|
},
|
|
disable () {
|
|
const prev = globalThis.DEBUG;
|
|
globalThis.DEBUG = "";
|
|
return prev;
|
|
},
|
|
// this is the core logic to check if logging should happen or not
|
|
enabled (namespace) {
|
|
const listenedNamespaces = globalThis.DEBUG.split(",").map((s)=>{
|
|
return s.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
});
|
|
const isListened = listenedNamespaces.some((listenedNamespace)=>{
|
|
if (listenedNamespace === "" || listenedNamespace[0] === "-") return false;
|
|
return namespace.match(RegExp(listenedNamespace.split("*").join(".*") + "$"));
|
|
});
|
|
const isExcluded = listenedNamespaces.some((listenedNamespace)=>{
|
|
if (listenedNamespace === "" || listenedNamespace[0] !== "-") return false;
|
|
return namespace.match(RegExp(listenedNamespace.slice(1).split("*").join(".*") + "$"));
|
|
});
|
|
return isListened && !isExcluded;
|
|
},
|
|
log: (...args)=>{
|
|
const [namespace, format, ...rest] = args;
|
|
const logWithFormatting = console.warn ?? console.log;
|
|
logWithFormatting(`${namespace} ${format}`, ...rest);
|
|
},
|
|
formatters: {}
|
|
};
|
|
function debugCreate(namespace) {
|
|
const instanceProps = {
|
|
color: COLORS[lastColor++ % COLORS.length],
|
|
enabled: topProps.enabled(namespace),
|
|
namespace,
|
|
log: topProps.log,
|
|
extend: ()=>{}
|
|
};
|
|
const debugCall = (...args)=>{
|
|
const { enabled, namespace: namespace2, color, log } = instanceProps;
|
|
if (args.length !== 0) {
|
|
argsHistory.push([
|
|
namespace2,
|
|
...args
|
|
]);
|
|
}
|
|
if (argsHistory.length > MAX_ARGS_HISTORY) {
|
|
argsHistory.shift();
|
|
}
|
|
if (topProps.enabled(namespace2) || enabled) {
|
|
const stringArgs = args.map((arg)=>{
|
|
if (typeof arg === "string") {
|
|
return arg;
|
|
}
|
|
return safeStringify(arg);
|
|
});
|
|
const ms = `+${Date.now() - lastTimestamp}ms`;
|
|
lastTimestamp = Date.now();
|
|
if (globalThis.DEBUG_COLORS) {
|
|
log(colors_exports[color](bold(namespace2)), ...stringArgs, colors_exports[color](ms));
|
|
} else {
|
|
log(namespace2, ...stringArgs, ms);
|
|
}
|
|
}
|
|
};
|
|
return new Proxy(debugCall, {
|
|
get: (_, prop)=>instanceProps[prop],
|
|
set: (_, prop, value)=>instanceProps[prop] = value
|
|
});
|
|
}
|
|
var Debug = new Proxy(debugCreate, {
|
|
get: (_, prop)=>topProps[prop],
|
|
set: (_, prop, value)=>topProps[prop] = value
|
|
});
|
|
function safeStringify(value, indent = 2) {
|
|
const cache = /* @__PURE__ */ new Set();
|
|
return JSON.stringify(value, (key, value2)=>{
|
|
if (typeof value2 === "object" && value2 !== null) {
|
|
if (cache.has(value2)) {
|
|
return `[Circular *]`;
|
|
}
|
|
cache.add(value2);
|
|
} else if (typeof value2 === "bigint") {
|
|
return value2.toString();
|
|
}
|
|
return value2;
|
|
}, indent);
|
|
}
|
|
function getLogs(numChars = 7500) {
|
|
const logs = argsHistory.map(([namespace, ...args])=>{
|
|
return `${namespace} ${args.map((arg)=>{
|
|
if (typeof arg === "string") {
|
|
return arg;
|
|
} else {
|
|
return JSON.stringify(arg);
|
|
}
|
|
}).join(" ")}`;
|
|
}).join("\n");
|
|
if (logs.length < numChars) {
|
|
return logs;
|
|
}
|
|
return logs.slice(-numChars);
|
|
}
|
|
function clearLogs() {
|
|
argsHistory.length = 0;
|
|
}
|
|
var index_default = Debug;
|
|
;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/@prisma/driver-adapter-utils/dist/index.mjs [app-route] (ecmascript) <locals>", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
__turbopack_context__.s([
|
|
"ColumnTypeEnum",
|
|
()=>ColumnTypeEnum,
|
|
"DriverAdapterError",
|
|
()=>DriverAdapterError,
|
|
"bindAdapter",
|
|
()=>bindAdapter,
|
|
"bindMigrationAwareSqlAdapterFactory",
|
|
()=>bindMigrationAwareSqlAdapterFactory,
|
|
"bindSqlAdapterFactory",
|
|
()=>bindSqlAdapterFactory,
|
|
"err",
|
|
()=>err,
|
|
"isDriverAdapterError",
|
|
()=>isDriverAdapterError,
|
|
"mockAdapter",
|
|
()=>mockAdapter,
|
|
"mockAdapterErrors",
|
|
()=>mockAdapterErrors,
|
|
"mockAdapterFactory",
|
|
()=>mockAdapterFactory,
|
|
"mockMigrationAwareAdapterFactory",
|
|
()=>mockMigrationAwareAdapterFactory,
|
|
"ok",
|
|
()=>ok
|
|
]);
|
|
// src/debug.ts
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$debug$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@prisma/debug/dist/index.mjs [app-route] (ecmascript)");
|
|
;
|
|
// src/error.ts
|
|
var DriverAdapterError = class extends Error {
|
|
name = "DriverAdapterError";
|
|
cause;
|
|
constructor(payload){
|
|
super(typeof payload["message"] === "string" ? payload["message"] : payload.kind);
|
|
this.cause = payload;
|
|
}
|
|
};
|
|
function isDriverAdapterError(error) {
|
|
return error["name"] === "DriverAdapterError" && typeof error["cause"] === "object";
|
|
}
|
|
// src/result.ts
|
|
function ok(value) {
|
|
return {
|
|
ok: true,
|
|
value,
|
|
map (fn) {
|
|
return ok(fn(value));
|
|
},
|
|
flatMap (fn) {
|
|
return fn(value);
|
|
}
|
|
};
|
|
}
|
|
function err(error) {
|
|
return {
|
|
ok: false,
|
|
error,
|
|
map () {
|
|
return err(error);
|
|
},
|
|
flatMap () {
|
|
return err(error);
|
|
}
|
|
};
|
|
}
|
|
// src/binder.ts
|
|
var debug = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$debug$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Debug"])("driver-adapter-utils");
|
|
var ErrorRegistryInternal = class {
|
|
registeredErrors = [];
|
|
consumeError(id) {
|
|
return this.registeredErrors[id];
|
|
}
|
|
registerNewError(error) {
|
|
let i = 0;
|
|
while(this.registeredErrors[i] !== void 0){
|
|
i++;
|
|
}
|
|
this.registeredErrors[i] = {
|
|
error
|
|
};
|
|
return i;
|
|
}
|
|
};
|
|
function copySymbolsFromSource(source, target) {
|
|
const symbols = Object.getOwnPropertySymbols(source);
|
|
const symbolObject = Object.fromEntries(symbols.map((symbol)=>[
|
|
symbol,
|
|
true
|
|
]));
|
|
Object.assign(target, symbolObject);
|
|
}
|
|
var bindMigrationAwareSqlAdapterFactory = (adapterFactory)=>{
|
|
const errorRegistry = new ErrorRegistryInternal();
|
|
const boundFactory = {
|
|
adapterName: adapterFactory.adapterName,
|
|
provider: adapterFactory.provider,
|
|
errorRegistry,
|
|
connect: async (...args)=>{
|
|
const ctx = await wrapAsync(errorRegistry, adapterFactory.connect.bind(adapterFactory))(...args);
|
|
return ctx.map((ctx2)=>bindAdapter(ctx2, errorRegistry));
|
|
},
|
|
connectToShadowDb: async (...args)=>{
|
|
const ctx = await wrapAsync(errorRegistry, adapterFactory.connectToShadowDb.bind(adapterFactory))(...args);
|
|
return ctx.map((ctx2)=>bindAdapter(ctx2, errorRegistry));
|
|
}
|
|
};
|
|
copySymbolsFromSource(adapterFactory, boundFactory);
|
|
return boundFactory;
|
|
};
|
|
var bindSqlAdapterFactory = (adapterFactory)=>{
|
|
const errorRegistry = new ErrorRegistryInternal();
|
|
const boundFactory = {
|
|
adapterName: adapterFactory.adapterName,
|
|
provider: adapterFactory.provider,
|
|
errorRegistry,
|
|
connect: async (...args)=>{
|
|
const ctx = await wrapAsync(errorRegistry, adapterFactory.connect.bind(adapterFactory))(...args);
|
|
return ctx.map((ctx2)=>bindAdapter(ctx2, errorRegistry));
|
|
}
|
|
};
|
|
copySymbolsFromSource(adapterFactory, boundFactory);
|
|
return boundFactory;
|
|
};
|
|
var bindAdapter = (adapter, errorRegistry = new ErrorRegistryInternal())=>{
|
|
const boundAdapter = {
|
|
adapterName: adapter.adapterName,
|
|
errorRegistry,
|
|
queryRaw: wrapAsync(errorRegistry, adapter.queryRaw.bind(adapter)),
|
|
executeRaw: wrapAsync(errorRegistry, adapter.executeRaw.bind(adapter)),
|
|
executeScript: wrapAsync(errorRegistry, adapter.executeScript.bind(adapter)),
|
|
dispose: wrapAsync(errorRegistry, adapter.dispose.bind(adapter)),
|
|
provider: adapter.provider,
|
|
startTransaction: async (...args)=>{
|
|
const ctx = await wrapAsync(errorRegistry, adapter.startTransaction.bind(adapter))(...args);
|
|
return ctx.map((ctx2)=>bindTransaction(errorRegistry, ctx2));
|
|
}
|
|
};
|
|
if (adapter.getConnectionInfo) {
|
|
boundAdapter.getConnectionInfo = wrapSync(errorRegistry, adapter.getConnectionInfo.bind(adapter));
|
|
}
|
|
return boundAdapter;
|
|
};
|
|
var bindTransaction = (errorRegistry, transaction)=>{
|
|
return {
|
|
adapterName: transaction.adapterName,
|
|
provider: transaction.provider,
|
|
options: transaction.options,
|
|
queryRaw: wrapAsync(errorRegistry, transaction.queryRaw.bind(transaction)),
|
|
executeRaw: wrapAsync(errorRegistry, transaction.executeRaw.bind(transaction)),
|
|
commit: wrapAsync(errorRegistry, transaction.commit.bind(transaction)),
|
|
rollback: wrapAsync(errorRegistry, transaction.rollback.bind(transaction))
|
|
};
|
|
};
|
|
function wrapAsync(registry, fn) {
|
|
return async (...args)=>{
|
|
try {
|
|
return ok(await fn(...args));
|
|
} catch (error) {
|
|
debug("[error@wrapAsync]", error);
|
|
if (isDriverAdapterError(error)) {
|
|
return err(error.cause);
|
|
}
|
|
const id = registry.registerNewError(error);
|
|
return err({
|
|
kind: "GenericJs",
|
|
id
|
|
});
|
|
}
|
|
};
|
|
}
|
|
function wrapSync(registry, fn) {
|
|
return (...args)=>{
|
|
try {
|
|
return ok(fn(...args));
|
|
} catch (error) {
|
|
debug("[error@wrapSync]", error);
|
|
if (isDriverAdapterError(error)) {
|
|
return err(error.cause);
|
|
}
|
|
const id = registry.registerNewError(error);
|
|
return err({
|
|
kind: "GenericJs",
|
|
id
|
|
});
|
|
}
|
|
};
|
|
}
|
|
// src/const.ts
|
|
var ColumnTypeEnum = {
|
|
// Scalars
|
|
Int32: 0,
|
|
Int64: 1,
|
|
Float: 2,
|
|
Double: 3,
|
|
Numeric: 4,
|
|
Boolean: 5,
|
|
Character: 6,
|
|
Text: 7,
|
|
Date: 8,
|
|
Time: 9,
|
|
DateTime: 10,
|
|
Json: 11,
|
|
Enum: 12,
|
|
Bytes: 13,
|
|
Set: 14,
|
|
Uuid: 15,
|
|
// Arrays
|
|
Int32Array: 64,
|
|
Int64Array: 65,
|
|
FloatArray: 66,
|
|
DoubleArray: 67,
|
|
NumericArray: 68,
|
|
BooleanArray: 69,
|
|
CharacterArray: 70,
|
|
TextArray: 71,
|
|
DateArray: 72,
|
|
TimeArray: 73,
|
|
DateTimeArray: 74,
|
|
JsonArray: 75,
|
|
EnumArray: 76,
|
|
BytesArray: 77,
|
|
UuidArray: 78,
|
|
// Custom
|
|
UnknownNumber: 128
|
|
};
|
|
// src/mock.ts
|
|
var mockAdapterErrors = {
|
|
queryRaw: new Error("Not implemented: queryRaw"),
|
|
executeRaw: new Error("Not implemented: executeRaw"),
|
|
startTransaction: new Error("Not implemented: startTransaction"),
|
|
executeScript: new Error("Not implemented: executeScript"),
|
|
dispose: new Error("Not implemented: dispose")
|
|
};
|
|
function mockAdapter(provider) {
|
|
return {
|
|
provider,
|
|
adapterName: "@prisma/adapter-mock",
|
|
queryRaw: ()=>Promise.reject(mockAdapterErrors.queryRaw),
|
|
executeRaw: ()=>Promise.reject(mockAdapterErrors.executeRaw),
|
|
startTransaction: ()=>Promise.reject(mockAdapterErrors.startTransaction),
|
|
executeScript: ()=>Promise.reject(mockAdapterErrors.executeScript),
|
|
dispose: ()=>Promise.reject(mockAdapterErrors.dispose),
|
|
[Symbol.for("adapter.mockAdapter")]: true
|
|
};
|
|
}
|
|
function mockAdapterFactory(provider) {
|
|
return {
|
|
provider,
|
|
adapterName: "@prisma/adapter-mock",
|
|
connect: ()=>Promise.resolve(mockAdapter(provider)),
|
|
[Symbol.for("adapter.mockAdapterFactory")]: true
|
|
};
|
|
}
|
|
function mockMigrationAwareAdapterFactory(provider) {
|
|
return {
|
|
provider,
|
|
adapterName: "@prisma/adapter-mock",
|
|
connect: ()=>Promise.resolve(mockAdapter(provider)),
|
|
connectToShadowDb: ()=>Promise.resolve(mockAdapter(provider)),
|
|
[Symbol.for("adapter.mockMigrationAwareAdapterFactory")]: true
|
|
};
|
|
}
|
|
;
|
|
}),
|
|
"[externals]/pg [external] (pg, esm_import, [project]/Documents/00 - projet/plumeia/node_modules/pg)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
return __turbopack_context__.a(async (__turbopack_handle_async_dependencies__, __turbopack_async_result__) => { try {
|
|
|
|
const mod = await __turbopack_context__.y("pg-909e2581735964d3");
|
|
|
|
__turbopack_context__.n(mod);
|
|
__turbopack_async_result__();
|
|
} catch(e) { __turbopack_async_result__(e); } }, true);}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/postgres-array/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
const BACKSLASH = '\\';
|
|
const DQUOT = '"';
|
|
const LBRACE = '{';
|
|
const RBRACE = '}';
|
|
const LBRACKET = '[';
|
|
const EQUALS = '=';
|
|
const COMMA = ',';
|
|
/** When the raw value is this, it means a literal `null` */ const NULL_STRING = 'NULL';
|
|
/**
|
|
* Parses an array according to
|
|
* https://www.postgresql.org/docs/17/arrays.html#ARRAYS-IO
|
|
*
|
|
* Trusts the data (mostly), so only hook up to trusted Postgres servers.
|
|
*/ function makeParseArrayWithTransform(transform) {
|
|
const haveTransform = transform != null;
|
|
return function parseArray(str) {
|
|
const rbraceIndex = str.length - 1;
|
|
if (rbraceIndex === 1) {
|
|
return [];
|
|
}
|
|
if (str[rbraceIndex] !== RBRACE) {
|
|
throw new Error('Invalid array text - must end with }');
|
|
}
|
|
// If starts with `[`, it is specifying the index boundas. Skip past first `=`.
|
|
let position = 0;
|
|
if (str[position] === LBRACKET) {
|
|
position = str.indexOf(EQUALS) + 1;
|
|
}
|
|
if (str[position++] !== LBRACE) {
|
|
throw new Error('Invalid array text - must start with {');
|
|
}
|
|
const output = [];
|
|
let current = output;
|
|
const stack = [];
|
|
let currentStringStart = position;
|
|
let currentString = '';
|
|
let expectValue = true;
|
|
for(; position < rbraceIndex; ++position){
|
|
let char = str[position];
|
|
// > The array output routine will put double quotes around element values if
|
|
// > they are empty strings, contain curly braces, delimiter characters, double
|
|
// > quotes, backslashes, or white space, or match the word NULL. Double quotes
|
|
// > and backslashes embedded in element values will be backslash-escaped.
|
|
if (char === DQUOT) {
|
|
// It's escaped
|
|
currentStringStart = ++position;
|
|
let dquot = str.indexOf(DQUOT, currentStringStart);
|
|
let backSlash = str.indexOf(BACKSLASH, currentStringStart);
|
|
while(backSlash !== -1 && backSlash < dquot){
|
|
position = backSlash;
|
|
const part = str.slice(currentStringStart, position);
|
|
currentString += part;
|
|
currentStringStart = ++position;
|
|
if (dquot === position++) {
|
|
// This was an escaped doublequote; find the next one!
|
|
dquot = str.indexOf(DQUOT, position);
|
|
}
|
|
// Either way, find the next backslash
|
|
backSlash = str.indexOf(BACKSLASH, position);
|
|
}
|
|
position = dquot;
|
|
const part = str.slice(currentStringStart, position);
|
|
currentString += part;
|
|
current.push(haveTransform ? transform(currentString) : currentString);
|
|
currentString = '';
|
|
expectValue = false;
|
|
} else if (char === LBRACE) {
|
|
const newArray = [];
|
|
current.push(newArray);
|
|
stack.push(current);
|
|
current = newArray;
|
|
currentStringStart = position + 1;
|
|
expectValue = true;
|
|
} else if (char === COMMA) {
|
|
expectValue = true;
|
|
} else if (char === RBRACE) {
|
|
expectValue = false;
|
|
const arr = stack.pop();
|
|
if (arr === undefined) {
|
|
throw new Error("Invalid array text - too many '}'");
|
|
}
|
|
current = arr;
|
|
} else if (expectValue) {
|
|
currentStringStart = position;
|
|
while((char = str[position]) !== COMMA && char !== RBRACE && position < rbraceIndex){
|
|
++position;
|
|
}
|
|
const part = str.slice(currentStringStart, position--);
|
|
current.push(part === NULL_STRING ? null : haveTransform ? transform(part) : part);
|
|
expectValue = false;
|
|
} else {
|
|
throw new Error('Was expecting delimeter');
|
|
}
|
|
}
|
|
return output;
|
|
};
|
|
}
|
|
const parseArray = makeParseArrayWithTransform();
|
|
exports.parse = (source, transform)=>transform != null ? makeParseArrayWithTransform(transform)(source) : parseArray(source);
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/@prisma/adapter-pg/dist/index.mjs [app-route] (ecmascript)", ((__turbopack_context__) => {
|
|
"use strict";
|
|
|
|
return __turbopack_context__.a(async (__turbopack_handle_async_dependencies__, __turbopack_async_result__) => { try {
|
|
|
|
__turbopack_context__.s([
|
|
"PrismaPg",
|
|
()=>PrismaPgAdapterFactory
|
|
]);
|
|
// src/pg.ts
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$debug$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@prisma/debug/dist/index.mjs [app-route] (ecmascript)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/@prisma/driver-adapter-utils/dist/index.mjs [app-route] (ecmascript) <locals>");
|
|
var __TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__ = __turbopack_context__.i("[externals]/pg [external] (pg, esm_import, [project]/Documents/00 - projet/plumeia/node_modules/pg)");
|
|
var __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$postgres$2d$array$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/Documents/00 - projet/plumeia/node_modules/postgres-array/index.js [app-route] (ecmascript)");
|
|
var __turbopack_async_dependencies__ = __turbopack_handle_async_dependencies__([
|
|
__TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__
|
|
]);
|
|
[__TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__] = __turbopack_async_dependencies__.then ? (await __turbopack_async_dependencies__)() : __turbopack_async_dependencies__;
|
|
;
|
|
;
|
|
// package.json
|
|
var name = "@prisma/adapter-pg";
|
|
// src/constants.ts
|
|
var FIRST_NORMAL_OBJECT_ID = 16384;
|
|
;
|
|
;
|
|
;
|
|
var { types } = __TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__["default"];
|
|
var { builtins: ScalarColumnType, getTypeParser } = types;
|
|
var AdditionalScalarColumnType = {
|
|
NAME: 19
|
|
};
|
|
var ArrayColumnType = {
|
|
BIT_ARRAY: 1561,
|
|
BOOL_ARRAY: 1e3,
|
|
BYTEA_ARRAY: 1001,
|
|
BPCHAR_ARRAY: 1014,
|
|
CHAR_ARRAY: 1002,
|
|
CIDR_ARRAY: 651,
|
|
DATE_ARRAY: 1182,
|
|
FLOAT4_ARRAY: 1021,
|
|
FLOAT8_ARRAY: 1022,
|
|
INET_ARRAY: 1041,
|
|
INT2_ARRAY: 1005,
|
|
INT4_ARRAY: 1007,
|
|
INT8_ARRAY: 1016,
|
|
JSONB_ARRAY: 3807,
|
|
JSON_ARRAY: 199,
|
|
MONEY_ARRAY: 791,
|
|
NUMERIC_ARRAY: 1231,
|
|
OID_ARRAY: 1028,
|
|
TEXT_ARRAY: 1009,
|
|
TIMESTAMP_ARRAY: 1115,
|
|
TIMESTAMPTZ_ARRAY: 1185,
|
|
TIME_ARRAY: 1183,
|
|
UUID_ARRAY: 2951,
|
|
VARBIT_ARRAY: 1563,
|
|
VARCHAR_ARRAY: 1015,
|
|
XML_ARRAY: 143
|
|
};
|
|
var UnsupportedNativeDataType = class _UnsupportedNativeDataType extends Error {
|
|
// map of type codes to type names
|
|
static typeNames = {
|
|
16: "bool",
|
|
17: "bytea",
|
|
18: "char",
|
|
19: "name",
|
|
20: "int8",
|
|
21: "int2",
|
|
22: "int2vector",
|
|
23: "int4",
|
|
24: "regproc",
|
|
25: "text",
|
|
26: "oid",
|
|
27: "tid",
|
|
28: "xid",
|
|
29: "cid",
|
|
30: "oidvector",
|
|
32: "pg_ddl_command",
|
|
71: "pg_type",
|
|
75: "pg_attribute",
|
|
81: "pg_proc",
|
|
83: "pg_class",
|
|
114: "json",
|
|
142: "xml",
|
|
194: "pg_node_tree",
|
|
269: "table_am_handler",
|
|
325: "index_am_handler",
|
|
600: "point",
|
|
601: "lseg",
|
|
602: "path",
|
|
603: "box",
|
|
604: "polygon",
|
|
628: "line",
|
|
650: "cidr",
|
|
700: "float4",
|
|
701: "float8",
|
|
705: "unknown",
|
|
718: "circle",
|
|
774: "macaddr8",
|
|
790: "money",
|
|
829: "macaddr",
|
|
869: "inet",
|
|
1033: "aclitem",
|
|
1042: "bpchar",
|
|
1043: "varchar",
|
|
1082: "date",
|
|
1083: "time",
|
|
1114: "timestamp",
|
|
1184: "timestamptz",
|
|
1186: "interval",
|
|
1266: "timetz",
|
|
1560: "bit",
|
|
1562: "varbit",
|
|
1700: "numeric",
|
|
1790: "refcursor",
|
|
2202: "regprocedure",
|
|
2203: "regoper",
|
|
2204: "regoperator",
|
|
2205: "regclass",
|
|
2206: "regtype",
|
|
2249: "record",
|
|
2275: "cstring",
|
|
2276: "any",
|
|
2277: "anyarray",
|
|
2278: "void",
|
|
2279: "trigger",
|
|
2280: "language_handler",
|
|
2281: "internal",
|
|
2283: "anyelement",
|
|
2287: "_record",
|
|
2776: "anynonarray",
|
|
2950: "uuid",
|
|
2970: "txid_snapshot",
|
|
3115: "fdw_handler",
|
|
3220: "pg_lsn",
|
|
3310: "tsm_handler",
|
|
3361: "pg_ndistinct",
|
|
3402: "pg_dependencies",
|
|
3500: "anyenum",
|
|
3614: "tsvector",
|
|
3615: "tsquery",
|
|
3642: "gtsvector",
|
|
3734: "regconfig",
|
|
3769: "regdictionary",
|
|
3802: "jsonb",
|
|
3831: "anyrange",
|
|
3838: "event_trigger",
|
|
3904: "int4range",
|
|
3906: "numrange",
|
|
3908: "tsrange",
|
|
3910: "tstzrange",
|
|
3912: "daterange",
|
|
3926: "int8range",
|
|
4072: "jsonpath",
|
|
4089: "regnamespace",
|
|
4096: "regrole",
|
|
4191: "regcollation",
|
|
4451: "int4multirange",
|
|
4532: "nummultirange",
|
|
4533: "tsmultirange",
|
|
4534: "tstzmultirange",
|
|
4535: "datemultirange",
|
|
4536: "int8multirange",
|
|
4537: "anymultirange",
|
|
4538: "anycompatiblemultirange",
|
|
4600: "pg_brin_bloom_summary",
|
|
4601: "pg_brin_minmax_multi_summary",
|
|
5017: "pg_mcv_list",
|
|
5038: "pg_snapshot",
|
|
5069: "xid8",
|
|
5077: "anycompatible",
|
|
5078: "anycompatiblearray",
|
|
5079: "anycompatiblenonarray",
|
|
5080: "anycompatiblerange"
|
|
};
|
|
type;
|
|
constructor(code){
|
|
super();
|
|
this.type = _UnsupportedNativeDataType.typeNames[code] || "Unknown";
|
|
this.message = `Unsupported column type ${this.type}`;
|
|
}
|
|
};
|
|
function fieldToColumnType(fieldTypeId) {
|
|
switch(fieldTypeId){
|
|
case ScalarColumnType.INT2:
|
|
case ScalarColumnType.INT4:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Int32;
|
|
case ScalarColumnType.INT8:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Int64;
|
|
case ScalarColumnType.FLOAT4:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Float;
|
|
case ScalarColumnType.FLOAT8:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Double;
|
|
case ScalarColumnType.BOOL:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Boolean;
|
|
case ScalarColumnType.DATE:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Date;
|
|
case ScalarColumnType.TIME:
|
|
case ScalarColumnType.TIMETZ:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Time;
|
|
case ScalarColumnType.TIMESTAMP:
|
|
case ScalarColumnType.TIMESTAMPTZ:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].DateTime;
|
|
case ScalarColumnType.NUMERIC:
|
|
case ScalarColumnType.MONEY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Numeric;
|
|
case ScalarColumnType.JSON:
|
|
case ScalarColumnType.JSONB:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Json;
|
|
case ScalarColumnType.UUID:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Uuid;
|
|
case ScalarColumnType.OID:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Int64;
|
|
case ScalarColumnType.BPCHAR:
|
|
case ScalarColumnType.TEXT:
|
|
case ScalarColumnType.VARCHAR:
|
|
case ScalarColumnType.BIT:
|
|
case ScalarColumnType.VARBIT:
|
|
case ScalarColumnType.INET:
|
|
case ScalarColumnType.CIDR:
|
|
case ScalarColumnType.XML:
|
|
case AdditionalScalarColumnType.NAME:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Text;
|
|
case ScalarColumnType.BYTEA:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Bytes;
|
|
case ArrayColumnType.INT2_ARRAY:
|
|
case ArrayColumnType.INT4_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Int32Array;
|
|
case ArrayColumnType.FLOAT4_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].FloatArray;
|
|
case ArrayColumnType.FLOAT8_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].DoubleArray;
|
|
case ArrayColumnType.NUMERIC_ARRAY:
|
|
case ArrayColumnType.MONEY_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].NumericArray;
|
|
case ArrayColumnType.BOOL_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].BooleanArray;
|
|
case ArrayColumnType.CHAR_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].CharacterArray;
|
|
case ArrayColumnType.BPCHAR_ARRAY:
|
|
case ArrayColumnType.TEXT_ARRAY:
|
|
case ArrayColumnType.VARCHAR_ARRAY:
|
|
case ArrayColumnType.VARBIT_ARRAY:
|
|
case ArrayColumnType.BIT_ARRAY:
|
|
case ArrayColumnType.INET_ARRAY:
|
|
case ArrayColumnType.CIDR_ARRAY:
|
|
case ArrayColumnType.XML_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].TextArray;
|
|
case ArrayColumnType.DATE_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].DateArray;
|
|
case ArrayColumnType.TIME_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].TimeArray;
|
|
case ArrayColumnType.TIMESTAMP_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].DateTimeArray;
|
|
case ArrayColumnType.TIMESTAMPTZ_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].DateTimeArray;
|
|
case ArrayColumnType.JSON_ARRAY:
|
|
case ArrayColumnType.JSONB_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].JsonArray;
|
|
case ArrayColumnType.BYTEA_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].BytesArray;
|
|
case ArrayColumnType.UUID_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].UuidArray;
|
|
case ArrayColumnType.INT8_ARRAY:
|
|
case ArrayColumnType.OID_ARRAY:
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Int64Array;
|
|
default:
|
|
if (fieldTypeId >= FIRST_NORMAL_OBJECT_ID) {
|
|
return __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["ColumnTypeEnum"].Text;
|
|
}
|
|
throw new UnsupportedNativeDataType(fieldTypeId);
|
|
}
|
|
}
|
|
function normalize_array(element_normalizer) {
|
|
return (str)=>(0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$postgres$2d$array$2f$index$2e$js__$5b$app$2d$route$5d$__$28$ecmascript$29$__["parse"])(str, element_normalizer);
|
|
}
|
|
function normalize_numeric(numeric) {
|
|
return numeric;
|
|
}
|
|
function normalize_date(date) {
|
|
return date;
|
|
}
|
|
function normalize_timestamp(time) {
|
|
return `${time.replace(" ", "T")}+00:00`;
|
|
}
|
|
function normalize_timestamptz(time) {
|
|
return time.replace(" ", "T").replace(/[+-]\d{2}(:\d{2})?$/, "+00:00");
|
|
}
|
|
function normalize_time(time) {
|
|
return time;
|
|
}
|
|
function normalize_timez(time) {
|
|
return time.replace(/[+-]\d{2}(:\d{2})?$/, "");
|
|
}
|
|
function normalize_money(money) {
|
|
return money.slice(1);
|
|
}
|
|
function normalize_xml(xml) {
|
|
return xml;
|
|
}
|
|
function toJson(json) {
|
|
return json;
|
|
}
|
|
var parsePgBytes = getTypeParser(ScalarColumnType.BYTEA);
|
|
var normalizeByteaArray = getTypeParser(ArrayColumnType.BYTEA_ARRAY);
|
|
function convertBytes(serializedBytes) {
|
|
return parsePgBytes(serializedBytes);
|
|
}
|
|
function normalizeBit(bit) {
|
|
return bit;
|
|
}
|
|
var customParsers = {
|
|
[ScalarColumnType.NUMERIC]: normalize_numeric,
|
|
[ArrayColumnType.NUMERIC_ARRAY]: normalize_array(normalize_numeric),
|
|
[ScalarColumnType.TIME]: normalize_time,
|
|
[ArrayColumnType.TIME_ARRAY]: normalize_array(normalize_time),
|
|
[ScalarColumnType.TIMETZ]: normalize_timez,
|
|
[ScalarColumnType.DATE]: normalize_date,
|
|
[ArrayColumnType.DATE_ARRAY]: normalize_array(normalize_date),
|
|
[ScalarColumnType.TIMESTAMP]: normalize_timestamp,
|
|
[ArrayColumnType.TIMESTAMP_ARRAY]: normalize_array(normalize_timestamp),
|
|
[ScalarColumnType.TIMESTAMPTZ]: normalize_timestamptz,
|
|
[ArrayColumnType.TIMESTAMPTZ_ARRAY]: normalize_array(normalize_timestamptz),
|
|
[ScalarColumnType.MONEY]: normalize_money,
|
|
[ArrayColumnType.MONEY_ARRAY]: normalize_array(normalize_money),
|
|
[ScalarColumnType.JSON]: toJson,
|
|
[ArrayColumnType.JSON_ARRAY]: normalize_array(toJson),
|
|
[ScalarColumnType.JSONB]: toJson,
|
|
[ArrayColumnType.JSONB_ARRAY]: normalize_array(toJson),
|
|
[ScalarColumnType.BYTEA]: convertBytes,
|
|
[ArrayColumnType.BYTEA_ARRAY]: normalizeByteaArray,
|
|
[ArrayColumnType.BIT_ARRAY]: normalize_array(normalizeBit),
|
|
[ArrayColumnType.VARBIT_ARRAY]: normalize_array(normalizeBit),
|
|
[ArrayColumnType.XML_ARRAY]: normalize_array(normalize_xml)
|
|
};
|
|
function mapArg(arg, argType) {
|
|
if (arg === null) {
|
|
return null;
|
|
}
|
|
if (Array.isArray(arg) && argType.arity === "list") {
|
|
return arg.map((value)=>mapArg(value, argType));
|
|
}
|
|
if (typeof arg === "string" && argType.scalarType === "datetime") {
|
|
arg = new Date(arg);
|
|
}
|
|
if (arg instanceof Date) {
|
|
switch(argType.dbType){
|
|
case "TIME":
|
|
case "TIMETZ":
|
|
return formatTime(arg);
|
|
case "DATE":
|
|
return formatDate(arg);
|
|
default:
|
|
return formatDateTime(arg);
|
|
}
|
|
}
|
|
if (typeof arg === "string" && argType.scalarType === "bytes") {
|
|
return Buffer.from(arg, "base64");
|
|
}
|
|
if (ArrayBuffer.isView(arg)) {
|
|
return new Uint8Array(arg.buffer, arg.byteOffset, arg.byteLength);
|
|
}
|
|
return arg;
|
|
}
|
|
function formatDateTime(date) {
|
|
const pad = (n, z = 2)=>String(n).padStart(z, "0");
|
|
const ms = date.getUTCMilliseconds();
|
|
return pad(date.getUTCFullYear(), 4) + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + " " + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + (ms ? "." + String(ms).padStart(3, "0") : "");
|
|
}
|
|
function formatDate(date) {
|
|
const pad = (n, z = 2)=>String(n).padStart(z, "0");
|
|
return pad(date.getUTCFullYear(), 4) + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate());
|
|
}
|
|
function formatTime(date) {
|
|
const pad = (n, z = 2)=>String(n).padStart(z, "0");
|
|
const ms = date.getUTCMilliseconds();
|
|
return pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + (ms ? "." + String(ms).padStart(3, "0") : "");
|
|
}
|
|
// src/errors.ts
|
|
var TLS_ERRORS = /* @__PURE__ */ new Set([
|
|
"UNABLE_TO_GET_ISSUER_CERT",
|
|
"UNABLE_TO_GET_CRL",
|
|
"UNABLE_TO_DECRYPT_CERT_SIGNATURE",
|
|
"UNABLE_TO_DECRYPT_CRL_SIGNATURE",
|
|
"UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
|
|
"CERT_SIGNATURE_FAILURE",
|
|
"CRL_SIGNATURE_FAILURE",
|
|
"CERT_NOT_YET_VALID",
|
|
"CERT_HAS_EXPIRED",
|
|
"CRL_NOT_YET_VALID",
|
|
"CRL_HAS_EXPIRED",
|
|
"ERROR_IN_CERT_NOT_BEFORE_FIELD",
|
|
"ERROR_IN_CERT_NOT_AFTER_FIELD",
|
|
"ERROR_IN_CRL_LAST_UPDATE_FIELD",
|
|
"ERROR_IN_CRL_NEXT_UPDATE_FIELD",
|
|
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
"CERT_CHAIN_TOO_LONG",
|
|
"CERT_REVOKED",
|
|
"INVALID_CA",
|
|
"INVALID_PURPOSE",
|
|
"CERT_UNTRUSTED",
|
|
"CERT_REJECTED",
|
|
"HOSTNAME_MISMATCH",
|
|
"ERR_TLS_CERT_ALTNAME_FORMAT",
|
|
"ERR_TLS_CERT_ALTNAME_INVALID"
|
|
]);
|
|
var SOCKET_ERRORS = /* @__PURE__ */ new Set([
|
|
"ENOTFOUND",
|
|
"ECONNREFUSED",
|
|
"ECONNRESET",
|
|
"ETIMEDOUT"
|
|
]);
|
|
function convertDriverError(error) {
|
|
if (isSocketError(error)) {
|
|
return mapSocketError(error);
|
|
}
|
|
if (isTlsError(error)) {
|
|
return {
|
|
kind: "TlsConnectionError",
|
|
reason: error.message
|
|
};
|
|
}
|
|
if (isDriverError(error)) {
|
|
return {
|
|
originalCode: error.code,
|
|
originalMessage: error.message,
|
|
...mapDriverError(error)
|
|
};
|
|
}
|
|
throw error;
|
|
}
|
|
function mapDriverError(error) {
|
|
switch(error.code){
|
|
case "22001":
|
|
return {
|
|
kind: "LengthMismatch",
|
|
column: error.column
|
|
};
|
|
case "22003":
|
|
return {
|
|
kind: "ValueOutOfRange",
|
|
cause: error.message
|
|
};
|
|
case "22P02":
|
|
return {
|
|
kind: "InvalidInputValue",
|
|
message: error.message
|
|
};
|
|
case "23505":
|
|
{
|
|
const fields = error.detail?.match(/Key \(([^)]+)\)/)?.at(1)?.split(", ");
|
|
return {
|
|
kind: "UniqueConstraintViolation",
|
|
constraint: fields !== void 0 ? {
|
|
fields
|
|
} : void 0
|
|
};
|
|
}
|
|
case "23502":
|
|
{
|
|
const fields = error.detail?.match(/Key \(([^)]+)\)/)?.at(1)?.split(", ");
|
|
return {
|
|
kind: "NullConstraintViolation",
|
|
constraint: fields !== void 0 ? {
|
|
fields
|
|
} : void 0
|
|
};
|
|
}
|
|
case "23503":
|
|
{
|
|
let constraint;
|
|
if (error.column) {
|
|
constraint = {
|
|
fields: [
|
|
error.column
|
|
]
|
|
};
|
|
} else if (error.constraint) {
|
|
constraint = {
|
|
index: error.constraint
|
|
};
|
|
}
|
|
return {
|
|
kind: "ForeignKeyConstraintViolation",
|
|
constraint
|
|
};
|
|
}
|
|
case "3D000":
|
|
return {
|
|
kind: "DatabaseDoesNotExist",
|
|
db: error.message.split(" ").at(1)?.split('"').at(1)
|
|
};
|
|
case "28000":
|
|
return {
|
|
kind: "DatabaseAccessDenied",
|
|
db: error.message.split(",").find((s)=>s.startsWith(" database"))?.split('"').at(1)
|
|
};
|
|
case "28P01":
|
|
return {
|
|
kind: "AuthenticationFailed",
|
|
user: error.message.split(" ").pop()?.split('"').at(1)
|
|
};
|
|
case "40001":
|
|
return {
|
|
kind: "TransactionWriteConflict"
|
|
};
|
|
case "42P01":
|
|
return {
|
|
kind: "TableDoesNotExist",
|
|
table: error.message.split(" ").at(1)?.split('"').at(1)
|
|
};
|
|
case "42703":
|
|
return {
|
|
kind: "ColumnNotFound",
|
|
column: error.message.split(" ").at(1)?.split('"').at(1)
|
|
};
|
|
case "42P04":
|
|
return {
|
|
kind: "DatabaseAlreadyExists",
|
|
db: error.message.split(" ").at(1)?.split('"').at(1)
|
|
};
|
|
case "53300":
|
|
return {
|
|
kind: "TooManyConnections",
|
|
cause: error.message
|
|
};
|
|
default:
|
|
return {
|
|
kind: "postgres",
|
|
code: error.code ?? "N/A",
|
|
severity: error.severity ?? "N/A",
|
|
message: error.message,
|
|
detail: error.detail,
|
|
column: error.column,
|
|
hint: error.hint
|
|
};
|
|
}
|
|
}
|
|
function isDriverError(error) {
|
|
return typeof error.code === "string" && typeof error.message === "string" && typeof error.severity === "string" && (typeof error.detail === "string" || error.detail === void 0) && (typeof error.column === "string" || error.column === void 0) && (typeof error.hint === "string" || error.hint === void 0);
|
|
}
|
|
function mapSocketError(error) {
|
|
switch(error.code){
|
|
case "ENOTFOUND":
|
|
case "ECONNREFUSED":
|
|
return {
|
|
kind: "DatabaseNotReachable",
|
|
host: error.address ?? error.hostname,
|
|
port: error.port
|
|
};
|
|
case "ECONNRESET":
|
|
return {
|
|
kind: "ConnectionClosed"
|
|
};
|
|
case "ETIMEDOUT":
|
|
return {
|
|
kind: "SocketTimeout"
|
|
};
|
|
}
|
|
}
|
|
function isSocketError(error) {
|
|
return typeof error.code === "string" && typeof error.syscall === "string" && typeof error.errno === "number" && SOCKET_ERRORS.has(error.code);
|
|
}
|
|
function isTlsError(error) {
|
|
if (typeof error.code === "string") {
|
|
return TLS_ERRORS.has(error.code);
|
|
}
|
|
switch(error.message){
|
|
case "The server does not support SSL connections":
|
|
case "There was an error establishing an SSL connection":
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
// src/pg.ts
|
|
var types2 = __TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__["default"].types;
|
|
var debug = (0, __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$debug$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__["Debug"])("prisma:driver-adapter:pg");
|
|
var PgQueryable = class {
|
|
constructor(client, pgOptions){
|
|
this.client = client;
|
|
this.pgOptions = pgOptions;
|
|
}
|
|
provider = "postgres";
|
|
adapterName = name;
|
|
/**
|
|
* Execute a query given as SQL, interpolating the given parameters.
|
|
*/ async queryRaw(query) {
|
|
const tag = "[js::query_raw]";
|
|
debug(`${tag} %O`, query);
|
|
const { fields, rows } = await this.performIO(query);
|
|
const columnNames = fields.map((field)=>field.name);
|
|
let columnTypes = [];
|
|
try {
|
|
columnTypes = fields.map((field)=>fieldToColumnType(field.dataTypeID));
|
|
} catch (e) {
|
|
if (e instanceof UnsupportedNativeDataType) {
|
|
throw new __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["DriverAdapterError"]({
|
|
kind: "UnsupportedNativeDataType",
|
|
type: e.type
|
|
});
|
|
}
|
|
throw e;
|
|
}
|
|
const udtParser = this.pgOptions?.userDefinedTypeParser;
|
|
if (udtParser) {
|
|
for(let i = 0; i < fields.length; i++){
|
|
const field = fields[i];
|
|
if (field.dataTypeID >= FIRST_NORMAL_OBJECT_ID && !Object.hasOwn(customParsers, field.dataTypeID)) {
|
|
for(let j = 0; j < rows.length; j++){
|
|
rows[j][i] = await udtParser(field.dataTypeID, rows[j][i], this);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return {
|
|
columnNames,
|
|
columnTypes,
|
|
rows
|
|
};
|
|
}
|
|
/**
|
|
* Execute a query given as SQL, interpolating the given parameters and
|
|
* returning the number of affected rows.
|
|
* Note: Queryable expects a u64, but napi.rs only supports u32.
|
|
*/ async executeRaw(query) {
|
|
const tag = "[js::execute_raw]";
|
|
debug(`${tag} %O`, query);
|
|
return (await this.performIO(query)).rowCount ?? 0;
|
|
}
|
|
/**
|
|
* Run a query against the database, returning the result set.
|
|
* Should the query fail due to a connection error, the connection is
|
|
* marked as unhealthy.
|
|
*/ async performIO(query) {
|
|
const { sql, args } = query;
|
|
const values = args.map((arg, i)=>mapArg(arg, query.argTypes[i]));
|
|
try {
|
|
const result = await this.client.query({
|
|
text: sql,
|
|
values,
|
|
rowMode: "array",
|
|
types: {
|
|
// This is the error expected:
|
|
// No overload matches this call.
|
|
// The last overload gave the following error.
|
|
// Type '(oid: number, format?: any) => (json: string) => unknown' is not assignable to type '{ <T>(oid: number): TypeParser<string, string | T>; <T>(oid: number, format: "text"): TypeParser<string, string | T>; <T>(oid: number, format: "binary"): TypeParser<...>; }'.
|
|
// Type '(json: string) => unknown' is not assignable to type 'TypeParser<Buffer, any>'.
|
|
// Types of parameters 'json' and 'value' are incompatible.
|
|
// Type 'Buffer' is not assignable to type 'string'.ts(2769)
|
|
//
|
|
// Because pg-types types expect us to handle both binary and text protocol versions,
|
|
// where as far we can see, pg will ever pass only text version.
|
|
//
|
|
// @ts-expect-error
|
|
getTypeParser: (oid, format)=>{
|
|
if (format === "text" && customParsers[oid]) {
|
|
return customParsers[oid];
|
|
}
|
|
return types2.getTypeParser(oid, format);
|
|
}
|
|
}
|
|
}, values);
|
|
return result;
|
|
} catch (e) {
|
|
this.onError(e);
|
|
}
|
|
}
|
|
onError(error) {
|
|
debug("Error in performIO: %O", error);
|
|
throw new __TURBOPACK__imported__module__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f40$prisma$2f$driver$2d$adapter$2d$utils$2f$dist$2f$index$2e$mjs__$5b$app$2d$route$5d$__$28$ecmascript$29$__$3c$locals$3e$__["DriverAdapterError"](convertDriverError(error));
|
|
}
|
|
};
|
|
var PgTransaction = class extends PgQueryable {
|
|
constructor(client, options, pgOptions, cleanup){
|
|
super(client, pgOptions);
|
|
this.options = options;
|
|
this.pgOptions = pgOptions;
|
|
this.cleanup = cleanup;
|
|
}
|
|
async commit() {
|
|
debug(`[js::commit]`);
|
|
this.cleanup?.();
|
|
this.client.release();
|
|
}
|
|
async rollback() {
|
|
debug(`[js::rollback]`);
|
|
this.cleanup?.();
|
|
this.client.release();
|
|
}
|
|
};
|
|
var PrismaPgAdapter = class extends PgQueryable {
|
|
constructor(client, pgOptions, release){
|
|
super(client);
|
|
this.pgOptions = pgOptions;
|
|
this.release = release;
|
|
}
|
|
async startTransaction(isolationLevel) {
|
|
const options = {
|
|
usePhantomQuery: false
|
|
};
|
|
const tag = "[js::startTransaction]";
|
|
debug("%s options: %O", tag, options);
|
|
const conn = await this.client.connect().catch((error)=>this.onError(error));
|
|
const onError = (err)=>{
|
|
debug(`Error from pool connection: ${err.message} %O`, err);
|
|
this.pgOptions?.onConnectionError?.(err);
|
|
};
|
|
conn.on("error", onError);
|
|
const cleanup = ()=>{
|
|
conn.removeListener("error", onError);
|
|
};
|
|
try {
|
|
const tx = new PgTransaction(conn, options, this.pgOptions, cleanup);
|
|
await tx.executeRaw({
|
|
sql: "BEGIN",
|
|
args: [],
|
|
argTypes: []
|
|
});
|
|
if (isolationLevel) {
|
|
await tx.executeRaw({
|
|
sql: `SET TRANSACTION ISOLATION LEVEL ${isolationLevel}`,
|
|
args: [],
|
|
argTypes: []
|
|
});
|
|
}
|
|
return tx;
|
|
} catch (error) {
|
|
cleanup();
|
|
conn.release(error);
|
|
this.onError(error);
|
|
}
|
|
}
|
|
async executeScript(script) {
|
|
const statements = script.split(";").map((stmt)=>stmt.trim()).filter((stmt)=>stmt.length > 0);
|
|
for (const stmt of statements){
|
|
try {
|
|
await this.client.query(stmt);
|
|
} catch (error) {
|
|
this.onError(error);
|
|
}
|
|
}
|
|
}
|
|
getConnectionInfo() {
|
|
return {
|
|
schemaName: this.pgOptions?.schema,
|
|
supportsRelationJoins: true
|
|
};
|
|
}
|
|
async dispose() {
|
|
return this.release?.();
|
|
}
|
|
underlyingDriver() {
|
|
return this.client;
|
|
}
|
|
};
|
|
var PrismaPgAdapterFactory = class {
|
|
constructor(poolOrConfig, options){
|
|
this.options = options;
|
|
if (poolOrConfig instanceof __TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__["default"].Pool) {
|
|
this.externalPool = poolOrConfig;
|
|
this.config = poolOrConfig.options;
|
|
} else {
|
|
this.externalPool = null;
|
|
this.config = poolOrConfig;
|
|
}
|
|
}
|
|
provider = "postgres";
|
|
adapterName = name;
|
|
config;
|
|
externalPool;
|
|
async connect() {
|
|
const client = this.externalPool ?? new __TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__["default"].Pool(this.config);
|
|
const onIdleClientError = (err)=>{
|
|
debug(`Error from idle pool client: ${err.message} %O`, err);
|
|
this.options?.onPoolError?.(err);
|
|
};
|
|
client.on("error", onIdleClientError);
|
|
return new PrismaPgAdapter(client, this.options, async ()=>{
|
|
if (this.externalPool) {
|
|
if (this.options?.disposeExternalPool) {
|
|
await this.externalPool.end();
|
|
this.externalPool = null;
|
|
} else {
|
|
this.externalPool.removeListener("error", onIdleClientError);
|
|
}
|
|
} else {
|
|
await client.end();
|
|
}
|
|
});
|
|
}
|
|
async connectToShadowDb() {
|
|
const conn = await this.connect();
|
|
const database = `prisma_migrate_shadow_db_${globalThis.crypto.randomUUID()}`;
|
|
await conn.executeScript(`CREATE DATABASE "${database}"`);
|
|
const client = new __TURBOPACK__imported__module__$5b$externals$5d2f$pg__$5b$external$5d$__$28$pg$2c$__esm_import$2c$__$5b$project$5d2f$Documents$2f$00__$2d$__projet$2f$plumeia$2f$node_modules$2f$pg$29$__["default"].Pool({
|
|
...this.config,
|
|
database
|
|
});
|
|
return new PrismaPgAdapter(client, void 0, async ()=>{
|
|
await conn.executeScript(`DROP DATABASE "${database}"`);
|
|
await client.end();
|
|
});
|
|
}
|
|
};
|
|
;
|
|
__turbopack_async_result__();
|
|
} catch(e) { __turbopack_async_result__(e); } }, false);}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/retry/lib/retry_operation.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
function RetryOperation(timeouts, options) {
|
|
// Compatibility for the old (timeouts, retryForever) signature
|
|
if (typeof options === 'boolean') {
|
|
options = {
|
|
forever: options
|
|
};
|
|
}
|
|
this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
|
|
this._timeouts = timeouts;
|
|
this._options = options || {};
|
|
this._maxRetryTime = options && options.maxRetryTime || Infinity;
|
|
this._fn = null;
|
|
this._errors = [];
|
|
this._attempts = 1;
|
|
this._operationTimeout = null;
|
|
this._operationTimeoutCb = null;
|
|
this._timeout = null;
|
|
this._operationStart = null;
|
|
this._timer = null;
|
|
if (this._options.forever) {
|
|
this._cachedTimeouts = this._timeouts.slice(0);
|
|
}
|
|
}
|
|
module.exports = RetryOperation;
|
|
RetryOperation.prototype.reset = function() {
|
|
this._attempts = 1;
|
|
this._timeouts = this._originalTimeouts.slice(0);
|
|
};
|
|
RetryOperation.prototype.stop = function() {
|
|
if (this._timeout) {
|
|
clearTimeout(this._timeout);
|
|
}
|
|
if (this._timer) {
|
|
clearTimeout(this._timer);
|
|
}
|
|
this._timeouts = [];
|
|
this._cachedTimeouts = null;
|
|
};
|
|
RetryOperation.prototype.retry = function(err) {
|
|
if (this._timeout) {
|
|
clearTimeout(this._timeout);
|
|
}
|
|
if (!err) {
|
|
return false;
|
|
}
|
|
var currentTime = new Date().getTime();
|
|
if (err && currentTime - this._operationStart >= this._maxRetryTime) {
|
|
this._errors.push(err);
|
|
this._errors.unshift(new Error('RetryOperation timeout occurred'));
|
|
return false;
|
|
}
|
|
this._errors.push(err);
|
|
var timeout = this._timeouts.shift();
|
|
if (timeout === undefined) {
|
|
if (this._cachedTimeouts) {
|
|
// retry forever, only keep last error
|
|
this._errors.splice(0, this._errors.length - 1);
|
|
timeout = this._cachedTimeouts.slice(-1);
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
var self = this;
|
|
this._timer = setTimeout(function() {
|
|
self._attempts++;
|
|
if (self._operationTimeoutCb) {
|
|
self._timeout = setTimeout(function() {
|
|
self._operationTimeoutCb(self._attempts);
|
|
}, self._operationTimeout);
|
|
if (self._options.unref) {
|
|
self._timeout.unref();
|
|
}
|
|
}
|
|
self._fn(self._attempts);
|
|
}, timeout);
|
|
if (this._options.unref) {
|
|
this._timer.unref();
|
|
}
|
|
return true;
|
|
};
|
|
RetryOperation.prototype.attempt = function(fn, timeoutOps) {
|
|
this._fn = fn;
|
|
if (timeoutOps) {
|
|
if (timeoutOps.timeout) {
|
|
this._operationTimeout = timeoutOps.timeout;
|
|
}
|
|
if (timeoutOps.cb) {
|
|
this._operationTimeoutCb = timeoutOps.cb;
|
|
}
|
|
}
|
|
var self = this;
|
|
if (this._operationTimeoutCb) {
|
|
this._timeout = setTimeout(function() {
|
|
self._operationTimeoutCb();
|
|
}, self._operationTimeout);
|
|
}
|
|
this._operationStart = new Date().getTime();
|
|
this._fn(this._attempts);
|
|
};
|
|
RetryOperation.prototype.try = function(fn) {
|
|
console.log('Using RetryOperation.try() is deprecated');
|
|
this.attempt(fn);
|
|
};
|
|
RetryOperation.prototype.start = function(fn) {
|
|
console.log('Using RetryOperation.start() is deprecated');
|
|
this.attempt(fn);
|
|
};
|
|
RetryOperation.prototype.start = RetryOperation.prototype.try;
|
|
RetryOperation.prototype.errors = function() {
|
|
return this._errors;
|
|
};
|
|
RetryOperation.prototype.attempts = function() {
|
|
return this._attempts;
|
|
};
|
|
RetryOperation.prototype.mainError = function() {
|
|
if (this._errors.length === 0) {
|
|
return null;
|
|
}
|
|
var counts = {};
|
|
var mainError = null;
|
|
var mainErrorCount = 0;
|
|
for(var i = 0; i < this._errors.length; i++){
|
|
var error = this._errors[i];
|
|
var message = error.message;
|
|
var count = (counts[message] || 0) + 1;
|
|
counts[message] = count;
|
|
if (count >= mainErrorCount) {
|
|
mainError = error;
|
|
mainErrorCount = count;
|
|
}
|
|
}
|
|
return mainError;
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/retry/lib/retry.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
var RetryOperation = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/retry/lib/retry_operation.js [app-route] (ecmascript)");
|
|
exports.operation = function(options) {
|
|
var timeouts = exports.timeouts(options);
|
|
return new RetryOperation(timeouts, {
|
|
forever: options && (options.forever || options.retries === Infinity),
|
|
unref: options && options.unref,
|
|
maxRetryTime: options && options.maxRetryTime
|
|
});
|
|
};
|
|
exports.timeouts = function(options) {
|
|
if (options instanceof Array) {
|
|
return [].concat(options);
|
|
}
|
|
var opts = {
|
|
retries: 10,
|
|
factor: 2,
|
|
minTimeout: 1 * 1000,
|
|
maxTimeout: Infinity,
|
|
randomize: false
|
|
};
|
|
for(var key in options){
|
|
opts[key] = options[key];
|
|
}
|
|
if (opts.minTimeout > opts.maxTimeout) {
|
|
throw new Error('minTimeout is greater than maxTimeout');
|
|
}
|
|
var timeouts = [];
|
|
for(var i = 0; i < opts.retries; i++){
|
|
timeouts.push(this.createTimeout(i, opts));
|
|
}
|
|
if (options && options.forever && !timeouts.length) {
|
|
timeouts.push(this.createTimeout(i, opts));
|
|
}
|
|
// sort the array numerically ascending
|
|
timeouts.sort(function(a, b) {
|
|
return a - b;
|
|
});
|
|
return timeouts;
|
|
};
|
|
exports.createTimeout = function(attempt, opts) {
|
|
var random = opts.randomize ? Math.random() + 1 : 1;
|
|
var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
|
|
timeout = Math.min(timeout, opts.maxTimeout);
|
|
return timeout;
|
|
};
|
|
exports.wrap = function(obj, options, methods) {
|
|
if (options instanceof Array) {
|
|
methods = options;
|
|
options = null;
|
|
}
|
|
if (!methods) {
|
|
methods = [];
|
|
for(var key in obj){
|
|
if (typeof obj[key] === 'function') {
|
|
methods.push(key);
|
|
}
|
|
}
|
|
}
|
|
for(var i = 0; i < methods.length; i++){
|
|
var method = methods[i];
|
|
var original = obj[method];
|
|
obj[method] = (function retryWrapper(original) {
|
|
var op = exports.operation(options);
|
|
var args = Array.prototype.slice.call(arguments, 1);
|
|
var callback = args.pop();
|
|
args.push(function(err) {
|
|
if (op.retry(err)) {
|
|
return;
|
|
}
|
|
if (err) {
|
|
arguments[0] = op.mainError();
|
|
}
|
|
callback.apply(this, arguments);
|
|
});
|
|
op.attempt(function() {
|
|
original.apply(obj, args);
|
|
});
|
|
}).bind(obj, original);
|
|
obj[method].options = options;
|
|
}
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/retry/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
module.exports = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/retry/lib/retry.js [app-route] (ecmascript)");
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/p-retry/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
const retry = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/retry/index.js [app-route] (ecmascript)");
|
|
const networkErrorMsgs = [
|
|
'Failed to fetch',
|
|
'NetworkError when attempting to fetch resource.',
|
|
'The Internet connection appears to be offline.',
|
|
'Network request failed' // `cross-fetch`
|
|
];
|
|
class AbortError extends Error {
|
|
constructor(message){
|
|
super();
|
|
if (message instanceof Error) {
|
|
this.originalError = message;
|
|
({ message } = message);
|
|
} else {
|
|
this.originalError = new Error(message);
|
|
this.originalError.stack = this.stack;
|
|
}
|
|
this.name = 'AbortError';
|
|
this.message = message;
|
|
}
|
|
}
|
|
const decorateErrorWithCounts = (error, attemptNumber, options)=>{
|
|
// Minus 1 from attemptNumber because the first attempt does not count as a retry
|
|
const retriesLeft = options.retries - (attemptNumber - 1);
|
|
error.attemptNumber = attemptNumber;
|
|
error.retriesLeft = retriesLeft;
|
|
return error;
|
|
};
|
|
const isNetworkError = (errorMessage)=>networkErrorMsgs.includes(errorMessage);
|
|
const pRetry = (input, options)=>new Promise((resolve, reject)=>{
|
|
options = {
|
|
onFailedAttempt: ()=>{},
|
|
retries: 10,
|
|
...options
|
|
};
|
|
const operation = retry.operation(options);
|
|
operation.attempt(async (attemptNumber)=>{
|
|
try {
|
|
resolve(await input(attemptNumber));
|
|
} catch (error) {
|
|
if (!(error instanceof Error)) {
|
|
reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
|
|
return;
|
|
}
|
|
if (error instanceof AbortError) {
|
|
operation.stop();
|
|
reject(error.originalError);
|
|
} else if (error instanceof TypeError && !isNetworkError(error.message)) {
|
|
operation.stop();
|
|
reject(error);
|
|
} else {
|
|
decorateErrorWithCounts(error, attemptNumber, options);
|
|
try {
|
|
await options.onFailedAttempt(error);
|
|
} catch (error) {
|
|
reject(error);
|
|
return;
|
|
}
|
|
if (!operation.retry(error)) {
|
|
reject(operation.mainError());
|
|
}
|
|
}
|
|
}
|
|
});
|
|
});
|
|
module.exports = pRetry;
|
|
// TODO: remove this in the next major version
|
|
module.exports.default = pRetry;
|
|
module.exports.AbortError = AbortError;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/extend/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
var hasOwn = Object.prototype.hasOwnProperty;
|
|
var toStr = Object.prototype.toString;
|
|
var defineProperty = Object.defineProperty;
|
|
var gOPD = Object.getOwnPropertyDescriptor;
|
|
var isArray = function isArray(arr) {
|
|
if (typeof Array.isArray === 'function') {
|
|
return Array.isArray(arr);
|
|
}
|
|
return toStr.call(arr) === '[object Array]';
|
|
};
|
|
var isPlainObject = function isPlainObject(obj) {
|
|
if (!obj || toStr.call(obj) !== '[object Object]') {
|
|
return false;
|
|
}
|
|
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
|
|
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
|
|
// Not own constructor property must be Object
|
|
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
|
|
return false;
|
|
}
|
|
// Own properties are enumerated firstly, so to speed up,
|
|
// if last one is own, then all properties are own.
|
|
var key;
|
|
for(key in obj){}
|
|
return typeof key === 'undefined' || hasOwn.call(obj, key);
|
|
};
|
|
// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
|
|
var setProperty = function setProperty(target, options) {
|
|
if (defineProperty && options.name === '__proto__') {
|
|
defineProperty(target, options.name, {
|
|
enumerable: true,
|
|
configurable: true,
|
|
value: options.newValue,
|
|
writable: true
|
|
});
|
|
} else {
|
|
target[options.name] = options.newValue;
|
|
}
|
|
};
|
|
// Return undefined instead of __proto__ if '__proto__' is not an own property
|
|
var getProperty = function getProperty(obj, name) {
|
|
if (name === '__proto__') {
|
|
if (!hasOwn.call(obj, name)) {
|
|
return void 0;
|
|
} else if (gOPD) {
|
|
// In early versions of node, obj['__proto__'] is buggy when obj has
|
|
// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
|
|
return gOPD(obj, name).value;
|
|
}
|
|
}
|
|
return obj[name];
|
|
};
|
|
module.exports = function extend() {
|
|
var options, name, src, copy, copyIsArray, clone;
|
|
var target = arguments[0];
|
|
var i = 1;
|
|
var length = arguments.length;
|
|
var deep = false;
|
|
// Handle a deep copy situation
|
|
if (typeof target === 'boolean') {
|
|
deep = target;
|
|
target = arguments[1] || {};
|
|
// skip the boolean and the target
|
|
i = 2;
|
|
}
|
|
if (target == null || typeof target !== 'object' && typeof target !== 'function') {
|
|
target = {};
|
|
}
|
|
for(; i < length; ++i){
|
|
options = arguments[i];
|
|
// Only deal with non-null/undefined values
|
|
if (options != null) {
|
|
// Extend the base object
|
|
for(name in options){
|
|
src = getProperty(target, name);
|
|
copy = getProperty(options, name);
|
|
// Prevent never-ending loop
|
|
if (target !== copy) {
|
|
// Recurse if we're merging plain objects or arrays
|
|
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
|
|
if (copyIsArray) {
|
|
copyIsArray = false;
|
|
clone = src && isArray(src) ? src : [];
|
|
} else {
|
|
clone = src && isPlainObject(src) ? src : {};
|
|
}
|
|
// Never move original objects, clone them
|
|
setProperty(target, {
|
|
name: name,
|
|
newValue: extend(deep, clone, copy)
|
|
});
|
|
// Don't bring in undefined values
|
|
} else if (typeof copy !== 'undefined') {
|
|
setProperty(target, {
|
|
name: name,
|
|
newValue: copy
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Return the modified object
|
|
return target;
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/package.json (json)", ((__turbopack_context__) => {
|
|
|
|
__turbopack_context__.v({"name":"gaxios","version":"7.1.3","description":"A simple common HTTP client specifically for Google APIs and services.","main":"build/cjs/src/index.js","types":"build/cjs/src/index.d.ts","files":["build/"],"exports":{".":{"import":{"types":"./build/esm/src/index.d.ts","default":"./build/esm/src/index.js"},"require":{"types":"./build/cjs/src/index.d.ts","default":"./build/cjs/src/index.js"}}},"scripts":{"lint":"gts check --no-inline-config","test":"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000","compile":"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs","fix":"gts fix","prepare":"npm run compile","pretest":"npm run compile","webpack":"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js","docs":"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","prelint":"cd samples; npm link ../; npm install","clean":"gts clean"},"repository":{"type":"git","directory":"packages/gaxios","url":"https://github.com/googleapis/google-cloud-node-core.git"},"keywords":["google"],"engines":{"node":">=18"},"author":"Google, LLC","license":"Apache-2.0","devDependencies":{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6","assert":"^2.0.0","browserify":"^17.0.0","c8":"^10.0.0","cors":"^2.8.5","express":"^5.0.0","gts":"^6.0.0","is-docker":"^3.0.0","jsdoc":"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0","karma":"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1","linkinator":"^6.1.2","mocha":"^11.1.0","multiparty":"^4.2.1","mv":"^2.1.1","ncp":"^2.0.0","nock":"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^4.0.0","puppeteer":"^24.0.0","sinon":"^21.0.0","stream-browserify":"^3.0.0","tmp":"0.2.5","ts-loader":"^9.5.2","typescript":"^5.8.3","webpack":"^5.35.0","webpack-cli":"^6.0.1"},"dependencies":{"extend":"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2","rimraf":"^5.0.1"},"homepage":"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"});}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/util.cjs [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2023 Google LLC
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
const pkg = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/package.json (json)");
|
|
module.exports = {
|
|
pkg
|
|
}; //# sourceMappingURL=util.cjs.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/common.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2018 Google LLC
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
var __importDefault = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : {
|
|
"default": mod
|
|
};
|
|
};
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0;
|
|
exports.defaultErrorRedactor = defaultErrorRedactor;
|
|
const extend_1 = __importDefault(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/extend/index.js [app-route] (ecmascript)"));
|
|
const util_cjs_1 = __importDefault(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/util.cjs [app-route] (ecmascript)"));
|
|
const pkg = util_cjs_1.default.pkg;
|
|
/**
|
|
* Support `instanceof` operator for `GaxiosError`s in different versions of this library.
|
|
*
|
|
* @see {@link GaxiosError[Symbol.hasInstance]}
|
|
*/ exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`);
|
|
class GaxiosError extends Error {
|
|
config;
|
|
response;
|
|
/**
|
|
* An error code.
|
|
* Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
|
|
*
|
|
* It is only a `number` when the cause is sourced from an API-level error (AIP-193).
|
|
*
|
|
* @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
|
|
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
|
|
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
|
|
*
|
|
* @example
|
|
* 'ECONNRESET'
|
|
*
|
|
* @example
|
|
* 'TimeoutError'
|
|
*
|
|
* @example
|
|
* 500
|
|
*/ code;
|
|
/**
|
|
* An HTTP Status code.
|
|
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
|
|
*
|
|
* @example
|
|
* 500
|
|
*/ status;
|
|
/**
|
|
* @deprecated use {@link GaxiosError.cause} instead.
|
|
*
|
|
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
|
|
*
|
|
* @privateRemarks
|
|
*
|
|
* We will want to remove this property later as the modern `cause` property is better suited
|
|
* for displaying and relaying nested errors. Keeping this here makes the resulting
|
|
* error log larger than it needs to be.
|
|
*
|
|
*/ error;
|
|
/**
|
|
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
|
|
*
|
|
* @see {@link GAXIOS_ERROR_SYMBOL}
|
|
* @see {@link GaxiosError[Symbol.hasInstance]}
|
|
* @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
|
|
* @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
|
|
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
|
|
*/ [exports.GAXIOS_ERROR_SYMBOL] = pkg.version;
|
|
/**
|
|
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
|
|
*
|
|
* @see {@link GAXIOS_ERROR_SYMBOL}
|
|
* @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
|
|
*/ static [Symbol.hasInstance](instance) {
|
|
if (instance && typeof instance === 'object' && exports.GAXIOS_ERROR_SYMBOL in instance && instance[exports.GAXIOS_ERROR_SYMBOL] === pkg.version) {
|
|
return true;
|
|
}
|
|
// fallback to native
|
|
return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance);
|
|
}
|
|
constructor(message, config, response, cause){
|
|
super(message, {
|
|
cause
|
|
});
|
|
this.config = config;
|
|
this.response = response;
|
|
this.error = cause instanceof Error ? cause : undefined;
|
|
// deep-copy config as we do not want to mutate
|
|
// the existing config for future retries/use
|
|
this.config = (0, extend_1.default)(true, {}, config);
|
|
if (this.response) {
|
|
this.response.config = (0, extend_1.default)(true, {}, this.response.config);
|
|
}
|
|
if (this.response) {
|
|
try {
|
|
this.response.data = translateData(this.config.responseType, // workaround for `node-fetch`'s `.data` deprecation...
|
|
this.response?.bodyUsed ? this.response?.data : undefined);
|
|
} catch {
|
|
// best effort - don't throw an error within an error
|
|
// we could set `this.response.config.responseType = 'unknown'`, but
|
|
// that would mutate future calls with this config object.
|
|
}
|
|
this.status = this.response.status;
|
|
}
|
|
if (cause instanceof DOMException) {
|
|
// The DOMException's equivalent to code is its name
|
|
// E.g.: name = `TimeoutError`, code = number
|
|
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException/name
|
|
this.code = cause.name;
|
|
} else if (cause && typeof cause === 'object' && 'code' in cause && (typeof cause.code === 'string' || typeof cause.code === 'number')) {
|
|
this.code = cause.code;
|
|
}
|
|
}
|
|
/**
|
|
* An AIP-193 conforming error extractor.
|
|
*
|
|
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
|
|
*
|
|
* @internal
|
|
* @expiremental
|
|
*
|
|
* @param res the response object
|
|
* @returns the extracted error information
|
|
*/ static extractAPIErrorFromResponse(res, defaultErrorMessage = 'The request failed') {
|
|
let message = defaultErrorMessage;
|
|
// Use res.data as the error message
|
|
if (typeof res.data === 'string') {
|
|
message = res.data;
|
|
}
|
|
if (res.data && typeof res.data === 'object' && 'error' in res.data && res.data.error && !res.ok) {
|
|
if (typeof res.data.error === 'string') {
|
|
return {
|
|
message: res.data.error,
|
|
code: res.status,
|
|
status: res.statusText
|
|
};
|
|
}
|
|
if (typeof res.data.error === 'object') {
|
|
// extract status from data.message
|
|
message = 'message' in res.data.error && typeof res.data.error.message === 'string' ? res.data.error.message : message;
|
|
// extract status from data.error
|
|
const status = 'status' in res.data.error && typeof res.data.error.status === 'string' ? res.data.error.status : res.statusText;
|
|
// extract code from data.error
|
|
const code = 'code' in res.data.error && typeof res.data.error.code === 'number' ? res.data.error.code : res.status;
|
|
if ('errors' in res.data.error && Array.isArray(res.data.error.errors)) {
|
|
const errorMessages = [];
|
|
for (const e of res.data.error.errors){
|
|
if (typeof e === 'object' && 'message' in e && typeof e.message === 'string') {
|
|
errorMessages.push(e.message);
|
|
}
|
|
}
|
|
return Object.assign({
|
|
message: errorMessages.join('\n') || message,
|
|
code,
|
|
status
|
|
}, res.data.error);
|
|
}
|
|
return Object.assign({
|
|
message,
|
|
code,
|
|
status
|
|
}, res.data.error);
|
|
}
|
|
}
|
|
return {
|
|
message,
|
|
code: res.status,
|
|
status: res.statusText
|
|
};
|
|
}
|
|
}
|
|
exports.GaxiosError = GaxiosError;
|
|
function translateData(responseType, data) {
|
|
switch(responseType){
|
|
case 'stream':
|
|
return data;
|
|
case 'json':
|
|
return JSON.parse(JSON.stringify(data));
|
|
case 'arraybuffer':
|
|
return JSON.parse(Buffer.from(data).toString('utf8'));
|
|
case 'blob':
|
|
return JSON.parse(data.text());
|
|
default:
|
|
return data;
|
|
}
|
|
}
|
|
/**
|
|
* An experimental error redactor.
|
|
*
|
|
* @param config Config to potentially redact properties of
|
|
* @param response Config to potentially redact properties of
|
|
*
|
|
* @experimental
|
|
*/ function defaultErrorRedactor(data) {
|
|
const REDACT = '<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.';
|
|
function redactHeaders(headers) {
|
|
if (!headers) return;
|
|
headers.forEach((_, key)=>{
|
|
// any casing of `Authentication`
|
|
// any casing of `Authorization`
|
|
// anything containing secret, such as 'client secret'
|
|
if (/^authentication$/i.test(key) || /^authorization$/i.test(key) || /secret/i.test(key)) headers.set(key, REDACT);
|
|
});
|
|
}
|
|
function redactString(obj, key) {
|
|
if (typeof obj === 'object' && obj !== null && typeof obj[key] === 'string') {
|
|
const text = obj[key];
|
|
if (/grant_type=/i.test(text) || /assertion=/i.test(text) || /secret/i.test(text)) {
|
|
obj[key] = REDACT;
|
|
}
|
|
}
|
|
}
|
|
function redactObject(obj) {
|
|
if (!obj || typeof obj !== 'object') {
|
|
return;
|
|
} else if (obj instanceof FormData || obj instanceof URLSearchParams || 'forEach' in obj && 'set' in obj) {
|
|
obj.forEach((_, key)=>{
|
|
if ([
|
|
'grant_type',
|
|
'assertion'
|
|
].includes(key) || /secret/.test(key)) {
|
|
obj.set(key, REDACT);
|
|
}
|
|
});
|
|
} else {
|
|
if ('grant_type' in obj) {
|
|
obj['grant_type'] = REDACT;
|
|
}
|
|
if ('assertion' in obj) {
|
|
obj['assertion'] = REDACT;
|
|
}
|
|
if ('client_secret' in obj) {
|
|
obj['client_secret'] = REDACT;
|
|
}
|
|
}
|
|
}
|
|
if (data.config) {
|
|
redactHeaders(data.config.headers);
|
|
redactString(data.config, 'data');
|
|
redactObject(data.config.data);
|
|
redactString(data.config, 'body');
|
|
redactObject(data.config.body);
|
|
if (data.config.url.searchParams.has('token')) {
|
|
data.config.url.searchParams.set('token', REDACT);
|
|
}
|
|
if (data.config.url.searchParams.has('client_secret')) {
|
|
data.config.url.searchParams.set('client_secret', REDACT);
|
|
}
|
|
}
|
|
if (data.response) {
|
|
defaultErrorRedactor({
|
|
config: data.response.config
|
|
});
|
|
redactHeaders(data.response.headers);
|
|
// workaround for `node-fetch`'s `.data` deprecation...
|
|
if (data.response.bodyUsed) {
|
|
redactString(data.response, 'data');
|
|
redactObject(data.response.data);
|
|
}
|
|
}
|
|
return data;
|
|
} //# sourceMappingURL=common.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/retry.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2018 Google LLC
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.getRetryConfig = getRetryConfig;
|
|
async function getRetryConfig(err) {
|
|
let config = getConfig(err);
|
|
if (!err || !err.config || !config && !err.config.retry) {
|
|
return {
|
|
shouldRetry: false
|
|
};
|
|
}
|
|
config = config || {};
|
|
config.currentRetryAttempt = config.currentRetryAttempt || 0;
|
|
config.retry = config.retry === undefined || config.retry === null ? 3 : config.retry;
|
|
config.httpMethodsToRetry = config.httpMethodsToRetry || [
|
|
'GET',
|
|
'HEAD',
|
|
'PUT',
|
|
'OPTIONS',
|
|
'DELETE'
|
|
];
|
|
config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null ? 2 : config.noResponseRetries;
|
|
config.retryDelayMultiplier = config.retryDelayMultiplier ? config.retryDelayMultiplier : 2;
|
|
config.timeOfFirstRequest = config.timeOfFirstRequest ? config.timeOfFirstRequest : Date.now();
|
|
config.totalTimeout = config.totalTimeout ? config.totalTimeout : Number.MAX_SAFE_INTEGER;
|
|
config.maxRetryDelay = config.maxRetryDelay ? config.maxRetryDelay : Number.MAX_SAFE_INTEGER;
|
|
// If this wasn't in the list of status codes where we want
|
|
// to automatically retry, return.
|
|
const retryRanges = [
|
|
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
|
|
// 1xx - Retry (Informational, request still processing)
|
|
// 2xx - Do not retry (Success)
|
|
// 3xx - Do not retry (Redirect)
|
|
// 4xx - Do not retry (Client errors)
|
|
// 408 - Retry ("Request Timeout")
|
|
// 429 - Retry ("Too Many Requests")
|
|
// 5xx - Retry (Server errors)
|
|
[
|
|
100,
|
|
199
|
|
],
|
|
[
|
|
408,
|
|
408
|
|
],
|
|
[
|
|
429,
|
|
429
|
|
],
|
|
[
|
|
500,
|
|
599
|
|
]
|
|
];
|
|
config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;
|
|
// Put the config back into the err
|
|
err.config.retryConfig = config;
|
|
// Determine if we should retry the request
|
|
const shouldRetryFn = config.shouldRetry || shouldRetryRequest;
|
|
if (!await shouldRetryFn(err)) {
|
|
return {
|
|
shouldRetry: false,
|
|
config: err.config
|
|
};
|
|
}
|
|
const delay = getNextRetryDelay(config);
|
|
// We're going to retry! Increment the counter.
|
|
err.config.retryConfig.currentRetryAttempt += 1;
|
|
// Create a promise that invokes the retry after the backOffDelay
|
|
const backoff = config.retryBackoff ? config.retryBackoff(err, delay) : new Promise((resolve)=>{
|
|
setTimeout(resolve, delay);
|
|
});
|
|
// Notify the user if they added an `onRetryAttempt` handler
|
|
if (config.onRetryAttempt) {
|
|
await config.onRetryAttempt(err);
|
|
}
|
|
// Return the promise in which recalls Gaxios to retry the request
|
|
await backoff;
|
|
return {
|
|
shouldRetry: true,
|
|
config: err.config
|
|
};
|
|
}
|
|
/**
|
|
* Determine based on config if we should retry the request.
|
|
* @param err The GaxiosError passed to the interceptor.
|
|
*/ function shouldRetryRequest(err) {
|
|
const config = getConfig(err);
|
|
if (err.config.signal?.aborted && err.code !== 'TimeoutError' || err.code === 'AbortError') {
|
|
return false;
|
|
}
|
|
// If there's no config, or retries are disabled, return.
|
|
if (!config || config.retry === 0) {
|
|
return false;
|
|
}
|
|
// Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)
|
|
if (!err.response && (config.currentRetryAttempt || 0) >= config.noResponseRetries) {
|
|
return false;
|
|
}
|
|
// Only retry with configured HttpMethods.
|
|
if (!config.httpMethodsToRetry || !config.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || 'GET')) {
|
|
return false;
|
|
}
|
|
// If this wasn't in the list of status codes where we want
|
|
// to automatically retry, return.
|
|
if (err.response && err.response.status) {
|
|
let isInRange = false;
|
|
for (const [min, max] of config.statusCodesToRetry){
|
|
const status = err.response.status;
|
|
if (status >= min && status <= max) {
|
|
isInRange = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!isInRange) {
|
|
return false;
|
|
}
|
|
}
|
|
// If we are out of retry attempts, return
|
|
config.currentRetryAttempt = config.currentRetryAttempt || 0;
|
|
if (config.currentRetryAttempt >= config.retry) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
/**
|
|
* Acquire the raxConfig object from an GaxiosError if available.
|
|
* @param err The Gaxios error with a config object.
|
|
*/ function getConfig(err) {
|
|
if (err && err.config && err.config.retryConfig) {
|
|
return err.config.retryConfig;
|
|
}
|
|
return;
|
|
}
|
|
/**
|
|
* Gets the delay to wait before the next retry.
|
|
*
|
|
* @param {RetryConfig} config The current set of retry options
|
|
* @returns {number} the amount of ms to wait before the next retry attempt.
|
|
*/ function getNextRetryDelay(config) {
|
|
// Calculate time to wait with exponential backoff.
|
|
// If this is the first retry, look for a configured retryDelay.
|
|
const retryDelay = config.currentRetryAttempt ? 0 : config.retryDelay ?? 100;
|
|
// Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000)
|
|
const calculatedDelay = retryDelay + (Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / 2 * 1000;
|
|
const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest);
|
|
return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay);
|
|
} //# sourceMappingURL=retry.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/interceptor.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2024 Google LLC
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.GaxiosInterceptorManager = void 0;
|
|
/**
|
|
* Class to manage collections of GaxiosInterceptors for both requests and responses.
|
|
*/ class GaxiosInterceptorManager extends Set {
|
|
}
|
|
exports.GaxiosInterceptorManager = GaxiosInterceptorManager; //# sourceMappingURL=interceptor.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/gaxios.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2018 Google LLC
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
var __importDefault = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : {
|
|
"default": mod
|
|
};
|
|
};
|
|
var _a;
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.Gaxios = void 0;
|
|
const extend_1 = __importDefault(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/extend/index.js [app-route] (ecmascript)"));
|
|
const https_1 = __turbopack_context__.r("[externals]/https [external] (https, cjs)");
|
|
const common_js_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/common.js [app-route] (ecmascript)");
|
|
const retry_js_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/retry.js [app-route] (ecmascript)");
|
|
const stream_1 = __turbopack_context__.r("[externals]/stream [external] (stream, cjs)");
|
|
const interceptor_js_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/interceptor.js [app-route] (ecmascript)");
|
|
const randomUUID = async ()=>globalThis.crypto?.randomUUID() || (await __turbopack_context__.A("[externals]/crypto [external] (crypto, cjs, async loader)")).randomUUID();
|
|
const HTTP_STATUS_NO_CONTENT = 204;
|
|
class Gaxios {
|
|
agentCache = new Map();
|
|
/**
|
|
* Default HTTP options that will be used for every HTTP request.
|
|
*/ defaults;
|
|
/**
|
|
* Interceptors
|
|
*/ interceptors;
|
|
/**
|
|
* The Gaxios class is responsible for making HTTP requests.
|
|
* @param defaults The default set of options to be used for this instance.
|
|
*/ constructor(defaults){
|
|
this.defaults = defaults || {};
|
|
this.interceptors = {
|
|
request: new interceptor_js_1.GaxiosInterceptorManager(),
|
|
response: new interceptor_js_1.GaxiosInterceptorManager()
|
|
};
|
|
}
|
|
/**
|
|
* A {@link fetch `fetch`} compliant API for {@link Gaxios}.
|
|
*
|
|
* @remarks
|
|
*
|
|
* This is useful as a drop-in replacement for `fetch` API usage.
|
|
*
|
|
* @example
|
|
*
|
|
* ```ts
|
|
* const gaxios = new Gaxios();
|
|
* const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
|
|
* await myFetch('https://example.com');
|
|
* ```
|
|
*
|
|
* @param args `fetch` API or `Gaxios#request` parameters
|
|
* @returns the {@link Response} with Gaxios-added properties
|
|
*/ fetch(...args) {
|
|
// Up to 2 parameters in either overload
|
|
const input = args[0];
|
|
const init = args[1];
|
|
let url = undefined;
|
|
const headers = new Headers();
|
|
// prepare URL
|
|
if (typeof input === 'string') {
|
|
url = new URL(input);
|
|
} else if (input instanceof URL) {
|
|
url = input;
|
|
} else if (input && input.url) {
|
|
url = new URL(input.url);
|
|
}
|
|
// prepare headers
|
|
if (input && typeof input === 'object' && 'headers' in input) {
|
|
_a.mergeHeaders(headers, input.headers);
|
|
}
|
|
if (init) {
|
|
_a.mergeHeaders(headers, new Headers(init.headers));
|
|
}
|
|
// prepare request
|
|
if (typeof input === 'object' && !(input instanceof URL)) {
|
|
// input must have been a non-URL object
|
|
return this.request({
|
|
...init,
|
|
...input,
|
|
headers,
|
|
url
|
|
});
|
|
} else {
|
|
// input must have been a string or URL
|
|
return this.request({
|
|
...init,
|
|
headers,
|
|
url
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Perform an HTTP request with the given options.
|
|
* @param opts Set of HTTP options that will be used for this HTTP request.
|
|
*/ async request(opts = {}) {
|
|
let prepared = await this.#prepareRequest(opts);
|
|
prepared = await this.#applyRequestInterceptors(prepared);
|
|
return this.#applyResponseInterceptors(this._request(prepared));
|
|
}
|
|
async _defaultAdapter(config) {
|
|
const fetchImpl = config.fetchImplementation || this.defaults.fetchImplementation || await _a.#getFetch();
|
|
// node-fetch v3 warns when `data` is present
|
|
// https://github.com/node-fetch/node-fetch/issues/1000
|
|
const preparedOpts = {
|
|
...config
|
|
};
|
|
delete preparedOpts.data;
|
|
const res = await fetchImpl(config.url, preparedOpts);
|
|
const data = await this.getResponseData(config, res);
|
|
if (!Object.getOwnPropertyDescriptor(res, 'data')?.configurable) {
|
|
// Work-around for `node-fetch` v3 as accessing `data` would otherwise throw
|
|
Object.defineProperties(res, {
|
|
data: {
|
|
configurable: true,
|
|
writable: true,
|
|
enumerable: true,
|
|
value: data
|
|
}
|
|
});
|
|
}
|
|
// Keep object as an instance of `Response`
|
|
return Object.assign(res, {
|
|
config,
|
|
data
|
|
});
|
|
}
|
|
/**
|
|
* Internal, retryable version of the `request` method.
|
|
* @param opts Set of HTTP options that will be used for this HTTP request.
|
|
*/ async _request(opts) {
|
|
try {
|
|
let translatedResponse;
|
|
if (opts.adapter) {
|
|
translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
|
|
} else {
|
|
translatedResponse = await this._defaultAdapter(opts);
|
|
}
|
|
if (!opts.validateStatus(translatedResponse.status)) {
|
|
if (opts.responseType === 'stream') {
|
|
const response = [];
|
|
for await (const chunk of translatedResponse.data){
|
|
response.push(chunk);
|
|
}
|
|
translatedResponse.data = response.toString();
|
|
}
|
|
const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
|
|
throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
|
|
}
|
|
return translatedResponse;
|
|
} catch (e) {
|
|
let err;
|
|
if (e instanceof common_js_1.GaxiosError) {
|
|
err = e;
|
|
} else if (e instanceof Error) {
|
|
err = new common_js_1.GaxiosError(e.message, opts, undefined, e);
|
|
} else {
|
|
err = new common_js_1.GaxiosError('Unexpected Gaxios Error', opts, undefined, e);
|
|
}
|
|
const { shouldRetry, config } = await (0, retry_js_1.getRetryConfig)(err);
|
|
if (shouldRetry && config) {
|
|
err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt;
|
|
// The error's config could be redacted - therefore we only want to
|
|
// copy the retry state over to the existing config
|
|
opts.retryConfig = err.config?.retryConfig;
|
|
// re-prepare timeout for the next request
|
|
this.#appendTimeoutToSignal(opts);
|
|
return this._request(opts);
|
|
}
|
|
if (opts.errorRedactor) {
|
|
opts.errorRedactor(err);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
async getResponseData(opts, res) {
|
|
if (res.status === HTTP_STATUS_NO_CONTENT) {
|
|
return '';
|
|
}
|
|
if (opts.maxContentLength && res.headers.has('content-length') && opts.maxContentLength < Number.parseInt(res.headers?.get('content-length') || '')) {
|
|
throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, {
|
|
config: opts
|
|
}));
|
|
}
|
|
switch(opts.responseType){
|
|
case 'stream':
|
|
return res.body;
|
|
case 'json':
|
|
{
|
|
const data = await res.text();
|
|
try {
|
|
return JSON.parse(data);
|
|
} catch {
|
|
return data;
|
|
}
|
|
}
|
|
case 'arraybuffer':
|
|
return res.arrayBuffer();
|
|
case 'blob':
|
|
return res.blob();
|
|
case 'text':
|
|
return res.text();
|
|
default:
|
|
return this.getResponseDataFromContentType(res);
|
|
}
|
|
}
|
|
#urlMayUseProxy(url, noProxy = []) {
|
|
const candidate = new URL(url);
|
|
const noProxyList = [
|
|
...noProxy
|
|
];
|
|
const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(',') || [];
|
|
for (const rule of noProxyEnvList){
|
|
noProxyList.push(rule.trim());
|
|
}
|
|
for (const rule of noProxyList){
|
|
// Match regex
|
|
if (rule instanceof RegExp) {
|
|
if (rule.test(candidate.toString())) {
|
|
return false;
|
|
}
|
|
} else if (rule instanceof URL) {
|
|
if (rule.origin === candidate.origin) {
|
|
return false;
|
|
}
|
|
} else if (rule.startsWith('*.') || rule.startsWith('.')) {
|
|
const cleanedRule = rule.replace(/^\*\./, '.');
|
|
if (candidate.hostname.endsWith(cleanedRule)) {
|
|
return false;
|
|
}
|
|
} else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
/**
|
|
* Applies the request interceptors. The request interceptors are applied after the
|
|
* call to prepareRequest is completed.
|
|
*
|
|
* @param {GaxiosOptionsPrepared} options The current set of options.
|
|
*
|
|
* @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
|
|
*/ async #applyRequestInterceptors(options) {
|
|
let promiseChain = Promise.resolve(options);
|
|
for (const interceptor of this.interceptors.request.values()){
|
|
if (interceptor) {
|
|
promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
|
|
}
|
|
}
|
|
return promiseChain;
|
|
}
|
|
/**
|
|
* Applies the response interceptors. The response interceptors are applied after the
|
|
* call to request is made.
|
|
*
|
|
* @param {GaxiosOptionsPrepared} options The current set of options.
|
|
*
|
|
* @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
|
|
*/ async #applyResponseInterceptors(response) {
|
|
let promiseChain = Promise.resolve(response);
|
|
for (const interceptor of this.interceptors.response.values()){
|
|
if (interceptor) {
|
|
promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
|
|
}
|
|
}
|
|
return promiseChain;
|
|
}
|
|
/**
|
|
* Validates the options, merges them with defaults, and prepare request.
|
|
*
|
|
* @param options The original options passed from the client.
|
|
* @returns Prepared options, ready to make a request
|
|
*/ async #prepareRequest(options) {
|
|
// Prepare Headers - copy in order to not mutate the original objects
|
|
const preparedHeaders = new Headers(this.defaults.headers);
|
|
_a.mergeHeaders(preparedHeaders, options.headers);
|
|
// Merge options
|
|
const opts = (0, extend_1.default)(true, {}, this.defaults, options);
|
|
if (!opts.url) {
|
|
throw new Error('URL is required.');
|
|
}
|
|
if (opts.baseURL) {
|
|
opts.url = new URL(opts.url, opts.baseURL);
|
|
}
|
|
// don't modify the properties of a default or provided URL
|
|
opts.url = new URL(opts.url);
|
|
if (opts.params) {
|
|
if (opts.paramsSerializer) {
|
|
let additionalQueryParams = opts.paramsSerializer(opts.params);
|
|
if (additionalQueryParams.startsWith('?')) {
|
|
additionalQueryParams = additionalQueryParams.slice(1);
|
|
}
|
|
const prefix = opts.url.toString().includes('?') ? '&' : '?';
|
|
opts.url = opts.url + prefix + additionalQueryParams;
|
|
} else {
|
|
const url = opts.url instanceof URL ? opts.url : new URL(opts.url);
|
|
for (const [key, value] of new URLSearchParams(opts.params)){
|
|
url.searchParams.append(key, value);
|
|
}
|
|
opts.url = url;
|
|
}
|
|
}
|
|
if (typeof options.maxContentLength === 'number') {
|
|
opts.size = options.maxContentLength;
|
|
}
|
|
if (typeof options.maxRedirects === 'number') {
|
|
opts.follow = options.maxRedirects;
|
|
}
|
|
const shouldDirectlyPassData = typeof opts.data === 'string' || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
|
|
/**
|
|
* @deprecated `node-fetch` or another third-party's request types
|
|
*/ [
|
|
'Blob',
|
|
'File',
|
|
'FormData'
|
|
].includes(opts.data?.constructor?.name || '');
|
|
if (opts.multipart?.length) {
|
|
const boundary = await randomUUID();
|
|
preparedHeaders.set('content-type', `multipart/related; boundary=${boundary}`);
|
|
opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
|
|
} else if (shouldDirectlyPassData) {
|
|
opts.body = opts.data;
|
|
} else if (typeof opts.data === 'object') {
|
|
if (preparedHeaders.get('Content-Type') === 'application/x-www-form-urlencoded') {
|
|
// If www-form-urlencoded content type has been set, but data is
|
|
// provided as an object, serialize the content
|
|
opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data);
|
|
} else {
|
|
if (!preparedHeaders.has('content-type')) {
|
|
preparedHeaders.set('content-type', 'application/json');
|
|
}
|
|
opts.body = JSON.stringify(opts.data);
|
|
}
|
|
} else if (opts.data) {
|
|
opts.body = opts.data;
|
|
}
|
|
opts.validateStatus = opts.validateStatus || this.validateStatus;
|
|
opts.responseType = opts.responseType || 'unknown';
|
|
if (!preparedHeaders.has('accept') && opts.responseType === 'json') {
|
|
preparedHeaders.set('accept', 'application/json');
|
|
}
|
|
const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
|
|
if (opts.agent) {
|
|
// don't do any of the following options - use the user-provided agent.
|
|
} else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
|
|
const HttpsProxyAgent = await _a.#getProxyAgent();
|
|
if (this.agentCache.has(proxy)) {
|
|
opts.agent = this.agentCache.get(proxy);
|
|
} else {
|
|
opts.agent = new HttpsProxyAgent(proxy, {
|
|
cert: opts.cert,
|
|
key: opts.key
|
|
});
|
|
this.agentCache.set(proxy, opts.agent);
|
|
}
|
|
} else if (opts.cert && opts.key) {
|
|
// Configure client for mTLS
|
|
if (this.agentCache.has(opts.key)) {
|
|
opts.agent = this.agentCache.get(opts.key);
|
|
} else {
|
|
opts.agent = new https_1.Agent({
|
|
cert: opts.cert,
|
|
key: opts.key
|
|
});
|
|
this.agentCache.set(opts.key, opts.agent);
|
|
}
|
|
}
|
|
if (typeof opts.errorRedactor !== 'function' && opts.errorRedactor !== false) {
|
|
opts.errorRedactor = common_js_1.defaultErrorRedactor;
|
|
}
|
|
if (opts.body && !('duplex' in opts)) {
|
|
/**
|
|
* required for Node.js and the type isn't available today
|
|
* @link https://github.com/nodejs/node/issues/46221
|
|
* @link https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1483
|
|
*/ opts.duplex = 'half';
|
|
}
|
|
this.#appendTimeoutToSignal(opts);
|
|
return Object.assign(opts, {
|
|
headers: preparedHeaders,
|
|
url: opts.url instanceof URL ? opts.url : new URL(opts.url)
|
|
});
|
|
}
|
|
#appendTimeoutToSignal(opts) {
|
|
if (opts.timeout) {
|
|
const timeoutSignal = AbortSignal.timeout(opts.timeout);
|
|
if (opts.signal && !opts.signal.aborted) {
|
|
opts.signal = AbortSignal.any([
|
|
opts.signal,
|
|
timeoutSignal
|
|
]);
|
|
} else {
|
|
opts.signal = timeoutSignal;
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* By default, throw for any non-2xx status code
|
|
* @param status status code from the HTTP response
|
|
*/ validateStatus(status) {
|
|
return status >= 200 && status < 300;
|
|
}
|
|
/**
|
|
* Attempts to parse a response by looking at the Content-Type header.
|
|
* @param {Response} response the HTTP response.
|
|
* @returns a promise that resolves to the response data.
|
|
*/ async getResponseDataFromContentType(response) {
|
|
let contentType = response.headers.get('Content-Type');
|
|
if (contentType === null) {
|
|
// Maintain existing functionality by calling text()
|
|
return response.text();
|
|
}
|
|
contentType = contentType.toLowerCase();
|
|
if (contentType.includes('application/json')) {
|
|
let data = await response.text();
|
|
try {
|
|
data = JSON.parse(data);
|
|
} catch {
|
|
// continue
|
|
}
|
|
return data;
|
|
} else if (contentType.match(/^text\//)) {
|
|
return response.text();
|
|
} else {
|
|
// If the content type is something not easily handled, just return the raw data (blob)
|
|
return response.blob();
|
|
}
|
|
}
|
|
/**
|
|
* Creates an async generator that yields the pieces of a multipart/related request body.
|
|
* This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
|
|
* multipart/related requests are not currently supported.
|
|
*
|
|
* @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
|
|
* @param {string} boundary the boundary string to be placed between each part.
|
|
*/ async *getMultipartRequest(multipartOptions, boundary) {
|
|
const finale = `--${boundary}--`;
|
|
for (const currentPart of multipartOptions){
|
|
const partContentType = currentPart.headers.get('Content-Type') || 'application/octet-stream';
|
|
const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`;
|
|
yield preamble;
|
|
if (typeof currentPart.content === 'string') {
|
|
yield currentPart.content;
|
|
} else {
|
|
yield* currentPart.content;
|
|
}
|
|
yield '\r\n';
|
|
}
|
|
yield finale;
|
|
}
|
|
/**
|
|
* A cache for the lazily-loaded proxy agent.
|
|
*
|
|
* Should use {@link Gaxios[#getProxyAgent]} to retrieve.
|
|
*/ // using `import` to dynamically import the types here
|
|
static #proxyAgent;
|
|
/**
|
|
* A cache for the lazily-loaded fetch library.
|
|
*
|
|
* Should use {@link Gaxios[#getFetch]} to retrieve.
|
|
*/ //
|
|
static #fetch;
|
|
/**
|
|
* Imports, caches, and returns a proxy agent - if not already imported
|
|
*
|
|
* @returns A proxy agent
|
|
*/ static async #getProxyAgent() {
|
|
this.#proxyAgent ||= (await __turbopack_context__.A("[project]/Documents/00 - projet/plumeia/node_modules/https-proxy-agent/dist/index.js [app-route] (ecmascript, async loader)")).HttpsProxyAgent;
|
|
return this.#proxyAgent;
|
|
}
|
|
static async #getFetch() {
|
|
const hasWindow = ("TURBOPACK compile-time value", "undefined") !== 'undefined' && !!window;
|
|
this.#fetch ||= ("TURBOPACK compile-time falsy", 0) ? "TURBOPACK unreachable" : (await __turbopack_context__.A("[project]/Documents/00 - projet/plumeia/node_modules/node-fetch/src/index.js [app-route] (ecmascript, async loader)")).default;
|
|
return this.#fetch;
|
|
}
|
|
/**
|
|
* Merges headers.
|
|
* If the base headers do not exist a new `Headers` object will be returned.
|
|
*
|
|
* @remarks
|
|
*
|
|
* Using this utility can be helpful when the headers are not known to exist:
|
|
* - if they exist as `Headers`, that instance will be used
|
|
* - it improves performance and allows users to use their existing references to their `Headers`
|
|
* - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
|
|
* - if the base headers do not exist a new `Headers` object will be created
|
|
*
|
|
* @param base headers to append/overwrite to
|
|
* @param append headers to append/overwrite with
|
|
* @returns the base headers instance with merged `Headers`
|
|
*/ static mergeHeaders(base, ...append) {
|
|
base = base instanceof Headers ? base : new Headers(base);
|
|
for (const headers of append){
|
|
const add = headers instanceof Headers ? headers : new Headers(headers);
|
|
add.forEach((value, key)=>{
|
|
// set-cookie is the only header that would repeat.
|
|
// A bit of background: https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie
|
|
key === 'set-cookie' ? base.append(key, value) : base.set(key, value);
|
|
});
|
|
}
|
|
return base;
|
|
}
|
|
}
|
|
exports.Gaxios = Gaxios;
|
|
_a = Gaxios; //# sourceMappingURL=gaxios.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2018 Google LLC
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
var __createBinding = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = {
|
|
enumerable: true,
|
|
get: function() {
|
|
return m[k];
|
|
}
|
|
};
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__exportStar || function(m, exports1) {
|
|
for(var p in m)if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports1, p)) __createBinding(exports1, m, p);
|
|
};
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.instance = exports.Gaxios = exports.GaxiosError = void 0;
|
|
exports.request = request;
|
|
const gaxios_js_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/gaxios.js [app-route] (ecmascript)");
|
|
Object.defineProperty(exports, "Gaxios", {
|
|
enumerable: true,
|
|
get: function() {
|
|
return gaxios_js_1.Gaxios;
|
|
}
|
|
});
|
|
var common_js_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/common.js [app-route] (ecmascript)");
|
|
Object.defineProperty(exports, "GaxiosError", {
|
|
enumerable: true,
|
|
get: function() {
|
|
return common_js_1.GaxiosError;
|
|
}
|
|
});
|
|
__exportStar(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/interceptor.js [app-route] (ecmascript)"), exports);
|
|
/**
|
|
* The default instance used when the `request` method is directly
|
|
* invoked.
|
|
*/ exports.instance = new gaxios_js_1.Gaxios();
|
|
/**
|
|
* Make an HTTP request using the given options.
|
|
* @param opts Options for the request
|
|
*/ async function request(opts) {
|
|
return exports.instance.request(opts);
|
|
} //# sourceMappingURL=index.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gcp-metadata/build/src/gcp-residency.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
/**
|
|
* Copyright 2022 Google LLC
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/ Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.GCE_LINUX_BIOS_PATHS = void 0;
|
|
exports.isGoogleCloudServerless = isGoogleCloudServerless;
|
|
exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux;
|
|
exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress;
|
|
exports.isGoogleComputeEngine = isGoogleComputeEngine;
|
|
exports.detectGCPResidency = detectGCPResidency;
|
|
const fs_1 = __turbopack_context__.r("[externals]/fs [external] (fs, cjs)");
|
|
const os_1 = __turbopack_context__.r("[externals]/os [external] (os, cjs)");
|
|
/**
|
|
* Known paths unique to Google Compute Engine Linux instances
|
|
*/ exports.GCE_LINUX_BIOS_PATHS = {
|
|
BIOS_DATE: '/sys/class/dmi/id/bios_date',
|
|
BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor'
|
|
};
|
|
const GCE_MAC_ADDRESS_REGEX = /^42:01/;
|
|
/**
|
|
* Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance).
|
|
*
|
|
* Uses the:
|
|
* - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
|
|
* - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}.
|
|
*
|
|
* @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise.
|
|
*/ function isGoogleCloudServerless() {
|
|
/**
|
|
* `CLOUD_RUN_JOB` is used for Cloud Run Jobs
|
|
* - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
|
|
*
|
|
* `FUNCTION_NAME` is used in older Cloud Functions environments:
|
|
* - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}.
|
|
*
|
|
* `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments:
|
|
* - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
|
|
* - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}.
|
|
*/ const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE;
|
|
return !!isGFEnvironment;
|
|
}
|
|
/**
|
|
* Determines if the process is running on a Linux Google Compute Engine instance.
|
|
*
|
|
* @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise.
|
|
*/ function isGoogleComputeEngineLinux() {
|
|
if ((0, os_1.platform)() !== 'linux') return false;
|
|
//TURBOPACK unreachable
|
|
;
|
|
}
|
|
/**
|
|
* Determines if the process is running on a Google Compute Engine instance with a known
|
|
* MAC address.
|
|
*
|
|
* @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise.
|
|
*/ function isGoogleComputeEngineMACAddress() {
|
|
const interfaces = (0, os_1.networkInterfaces)();
|
|
for (const item of Object.values(interfaces)){
|
|
if (!item) continue;
|
|
for (const { mac } of item){
|
|
if (GCE_MAC_ADDRESS_REGEX.test(mac)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
/**
|
|
* Determines if the process is running on a Google Compute Engine instance.
|
|
*
|
|
* @returns {boolean} `true` if the process is running on GCE, `false` otherwise.
|
|
*/ function isGoogleComputeEngine() {
|
|
return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress();
|
|
}
|
|
/**
|
|
* Determines if the process is running on Google Cloud Platform.
|
|
*
|
|
* @returns {boolean} `true` if the process is running on GCP, `false` otherwise.
|
|
*/ function detectGCPResidency() {
|
|
return isGoogleCloudServerless() || isGoogleComputeEngine();
|
|
} //# sourceMappingURL=gcp-residency.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/gcp-metadata/build/src/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
var __createBinding = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = {
|
|
enumerable: true,
|
|
get: function() {
|
|
return m[k];
|
|
}
|
|
};
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", {
|
|
enumerable: true,
|
|
value: v
|
|
});
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o) {
|
|
var ar = [];
|
|
for(var k in o)if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for(var k = ownKeys(mod), i = 0; i < k.length; i++)if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __exportStar = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__exportStar || function(m, exports1) {
|
|
for(var p in m)if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports1, p)) __createBinding(exports1, m, p);
|
|
};
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0;
|
|
exports.instance = instance;
|
|
exports.project = project;
|
|
exports.universe = universe;
|
|
exports.bulk = bulk;
|
|
exports.isAvailable = isAvailable;
|
|
exports.resetIsAvailableCache = resetIsAvailableCache;
|
|
exports.getGCPResidency = getGCPResidency;
|
|
exports.setGCPResidency = setGCPResidency;
|
|
exports.requestTimeout = requestTimeout;
|
|
/**
|
|
* Copyright 2018 Google LLC
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/ const gaxios_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gaxios/build/cjs/src/index.js [app-route] (ecmascript)");
|
|
const jsonBigint = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/json-bigint/index.js [app-route] (ecmascript)");
|
|
const gcp_residency_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gcp-metadata/build/src/gcp-residency.js [app-route] (ecmascript)");
|
|
const logger = __importStar(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/google-logging-utils/build/src/index.js [app-route] (ecmascript)"));
|
|
exports.BASE_PATH = '/computeMetadata/v1';
|
|
exports.HOST_ADDRESS = 'http://169.254.169.254';
|
|
exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.';
|
|
exports.HEADER_NAME = 'Metadata-Flavor';
|
|
exports.HEADER_VALUE = 'Google';
|
|
exports.HEADERS = Object.freeze({
|
|
[exports.HEADER_NAME]: exports.HEADER_VALUE
|
|
});
|
|
const log = logger.log('gcp-metadata');
|
|
/**
|
|
* Metadata server detection override options.
|
|
*
|
|
* Available via `process.env.METADATA_SERVER_DETECTION`.
|
|
*/ exports.METADATA_SERVER_DETECTION = Object.freeze({
|
|
'assume-present': "don't try to ping the metadata server, but assume it's present",
|
|
none: "don't try to ping the metadata server, but don't try to use it either",
|
|
'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)",
|
|
'ping-only': 'skip the BIOS probe, and go straight to pinging'
|
|
});
|
|
/**
|
|
* Returns the base URL while taking into account the GCE_METADATA_HOST
|
|
* environment variable if it exists.
|
|
*
|
|
* @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1.
|
|
*/ function getBaseUrl(baseUrl) {
|
|
if (!baseUrl) {
|
|
baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports.HOST_ADDRESS;
|
|
}
|
|
// If no scheme is provided default to HTTP:
|
|
if (!/^https?:\/\//.test(baseUrl)) {
|
|
baseUrl = `http://${baseUrl}`;
|
|
}
|
|
return new URL(exports.BASE_PATH, baseUrl).href;
|
|
}
|
|
// Accepts an options object passed from the user to the API. In previous
|
|
// versions of the API, it referred to a `Request` or an `Axios` request
|
|
// options object. Now it refers to an object with very limited property
|
|
// names. This is here to help ensure users don't pass invalid options when
|
|
// they upgrade from 0.4 to 0.5 to 0.8.
|
|
function validate(options) {
|
|
Object.keys(options).forEach((key)=>{
|
|
switch(key){
|
|
case 'params':
|
|
case 'property':
|
|
case 'headers':
|
|
break;
|
|
case 'qs':
|
|
throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");
|
|
default:
|
|
throw new Error(`'${key}' is not a valid configuration option.`);
|
|
}
|
|
});
|
|
}
|
|
async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) {
|
|
const headers = new Headers(exports.HEADERS);
|
|
let metadataKey = '';
|
|
let params = {};
|
|
if (typeof type === 'object') {
|
|
const metadataAccessor = type;
|
|
new Headers(metadataAccessor.headers).forEach((value, key)=>headers.set(key, value));
|
|
metadataKey = metadataAccessor.metadataKey;
|
|
params = metadataAccessor.params || params;
|
|
noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries;
|
|
fastFail = metadataAccessor.fastFail || fastFail;
|
|
} else {
|
|
metadataKey = type;
|
|
}
|
|
if (typeof options === 'string') {
|
|
metadataKey += `/${options}`;
|
|
} else {
|
|
validate(options);
|
|
if (options.property) {
|
|
metadataKey += `/${options.property}`;
|
|
}
|
|
new Headers(options.headers).forEach((value, key)=>headers.set(key, value));
|
|
params = options.params || params;
|
|
}
|
|
const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;
|
|
const req = {
|
|
url: `${getBaseUrl()}/${metadataKey}`,
|
|
headers,
|
|
retryConfig: {
|
|
noResponseRetries
|
|
},
|
|
params,
|
|
responseType: 'text',
|
|
timeout: requestTimeout()
|
|
};
|
|
log.info('instance request %j', req);
|
|
const res = await requestMethod(req);
|
|
log.info('instance metadata is %s', res.data);
|
|
const metadataFlavor = res.headers.get(exports.HEADER_NAME);
|
|
if (metadataFlavor !== exports.HEADER_VALUE) {
|
|
throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : 'no header'}`);
|
|
}
|
|
if (typeof res.data === 'string') {
|
|
try {
|
|
return jsonBigint.parse(res.data);
|
|
} catch {
|
|
/* ignore */ }
|
|
}
|
|
return res.data;
|
|
}
|
|
async function fastFailMetadataRequest(options) {
|
|
const secondaryOptions = {
|
|
...options,
|
|
url: options.url?.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS))
|
|
};
|
|
// We race a connection between DNS/IP to metadata server. There are a couple
|
|
// reasons for this:
|
|
//
|
|
// 1. the DNS is slow in some GCP environments; by checking both, we might
|
|
// detect the runtime environment significantly faster.
|
|
// 2. we can't just check the IP, which is tarpitted and slow to respond
|
|
// on a user's local machine.
|
|
//
|
|
// Returns first resolved promise or if all promises get rejected we return an AggregateError.
|
|
//
|
|
// Note, however, if a failure happens prior to a success, a rejection should
|
|
// occur, this is for folks running locally.
|
|
//
|
|
const r1 = (0, gaxios_1.request)(options);
|
|
const r2 = (0, gaxios_1.request)(secondaryOptions);
|
|
return Promise.any([
|
|
r1,
|
|
r2
|
|
]);
|
|
}
|
|
/**
|
|
* Obtain metadata for the current GCE instance.
|
|
*
|
|
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
|
|
*
|
|
* @example
|
|
* ```
|
|
* const serviceAccount: {} = await instance('service-accounts/');
|
|
* const serviceAccountEmail: string = await instance('service-accounts/default/email');
|
|
* ```
|
|
*/ // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function instance(options) {
|
|
return metadataAccessor('instance', options);
|
|
}
|
|
/**
|
|
* Obtain metadata for the current GCP project.
|
|
*
|
|
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
|
|
*
|
|
* @example
|
|
* ```
|
|
* const projectId: string = await project('project-id');
|
|
* const numericProjectId: number = await project('numeric-project-id');
|
|
* ```
|
|
*/ // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function project(options) {
|
|
return metadataAccessor('project', options);
|
|
}
|
|
/**
|
|
* Obtain metadata for the current universe.
|
|
*
|
|
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
|
|
*
|
|
* @example
|
|
* ```
|
|
* const universeDomain: string = await universe('universe-domain');
|
|
* ```
|
|
*/ function universe(options) {
|
|
return metadataAccessor('universe', options);
|
|
}
|
|
/**
|
|
* Retrieve metadata items in parallel.
|
|
*
|
|
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
|
|
*
|
|
* @example
|
|
* ```
|
|
* const data = await bulk([
|
|
* {
|
|
* metadataKey: 'instance',
|
|
* },
|
|
* {
|
|
* metadataKey: 'project/project-id',
|
|
* },
|
|
* ] as const);
|
|
*
|
|
* // data.instance;
|
|
* // data['project/project-id'];
|
|
* ```
|
|
*
|
|
* @param properties The metadata properties to retrieve
|
|
* @returns The metadata in `metadatakey:value` format
|
|
*/ async function bulk(properties) {
|
|
const r = {};
|
|
await Promise.all(properties.map((item)=>{
|
|
return (async ()=>{
|
|
const res = await metadataAccessor(item);
|
|
const key = item.metadataKey;
|
|
r[key] = res;
|
|
})();
|
|
}));
|
|
return r;
|
|
}
|
|
/*
|
|
* How many times should we retry detecting GCP environment.
|
|
*/ function detectGCPAvailableRetries() {
|
|
return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0;
|
|
}
|
|
let cachedIsAvailableResponse;
|
|
/**
|
|
* Determine if the metadata server is currently available.
|
|
*/ async function isAvailable() {
|
|
if (process.env.METADATA_SERVER_DETECTION) {
|
|
const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();
|
|
if (!(value in exports.METADATA_SERVER_DETECTION)) {
|
|
throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`);
|
|
}
|
|
switch(value){
|
|
case 'assume-present':
|
|
return true;
|
|
case 'none':
|
|
return false;
|
|
case 'bios-only':
|
|
return getGCPResidency();
|
|
case 'ping-only':
|
|
}
|
|
}
|
|
try {
|
|
// If a user is instantiating several GCP libraries at the same time,
|
|
// this may result in multiple calls to isAvailable(), to detect the
|
|
// runtime environment. We use the same promise for each of these calls
|
|
// to reduce the network load.
|
|
if (cachedIsAvailableResponse === undefined) {
|
|
cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), // If the default HOST_ADDRESS has been overridden, we should not
|
|
// make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in
|
|
// a non-GCP environment):
|
|
!(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST));
|
|
}
|
|
await cachedIsAvailableResponse;
|
|
return true;
|
|
} catch (e) {
|
|
const err = e;
|
|
if (process.env.DEBUG_AUTH) {
|
|
console.info(err);
|
|
}
|
|
if (err.type === 'request-timeout') {
|
|
// If running in a GCP environment, metadata endpoint should return
|
|
// within ms.
|
|
return false;
|
|
}
|
|
if (err.response && err.response.status === 404) {
|
|
return false;
|
|
} else {
|
|
if (!(err.response && err.response.status === 404) && // A warning is emitted if we see an unexpected err.code, or err.code
|
|
// is not populated:
|
|
(!err.code || ![
|
|
'EHOSTDOWN',
|
|
'EHOSTUNREACH',
|
|
'ENETUNREACH',
|
|
'ENOENT',
|
|
'ENOTFOUND',
|
|
'ECONNREFUSED'
|
|
].includes(err.code.toString()))) {
|
|
let code = 'UNKNOWN';
|
|
if (err.code) code = err.code.toString();
|
|
process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning');
|
|
}
|
|
// Failure to resolve the metadata service means that it is not available.
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* reset the memoized isAvailable() lookup.
|
|
*/ function resetIsAvailableCache() {
|
|
cachedIsAvailableResponse = undefined;
|
|
}
|
|
/**
|
|
* A cache for the detected GCP Residency.
|
|
*/ exports.gcpResidencyCache = null;
|
|
/**
|
|
* Detects GCP Residency.
|
|
* Caches results to reduce costs for subsequent calls.
|
|
*
|
|
* @see setGCPResidency for setting
|
|
*/ function getGCPResidency() {
|
|
if (exports.gcpResidencyCache === null) {
|
|
setGCPResidency();
|
|
}
|
|
return exports.gcpResidencyCache;
|
|
}
|
|
/**
|
|
* Sets the detected GCP Residency.
|
|
* Useful for forcing metadata server detection behavior.
|
|
*
|
|
* Set `null` to autodetect the environment (default behavior).
|
|
* @see getGCPResidency for getting
|
|
*/ function setGCPResidency(value = null) {
|
|
exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)();
|
|
}
|
|
/**
|
|
* Obtain the timeout for requests to the metadata server.
|
|
*
|
|
* In certain environments and conditions requests can take longer than
|
|
* the default timeout to complete. This function will determine the
|
|
* appropriate timeout based on the environment.
|
|
*
|
|
* @returns {number} a request timeout duration in milliseconds.
|
|
*/ function requestTimeout() {
|
|
return getGCPResidency() ? 0 : 3000;
|
|
}
|
|
__exportStar(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/gcp-metadata/build/src/gcp-residency.js [app-route] (ecmascript)"), exports); //# sourceMappingURL=index.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/bignumber.js/bignumber.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
;
|
|
(function(globalObject) {
|
|
'use strict';
|
|
/*
|
|
* bignumber.js v9.3.1
|
|
* A JavaScript library for arbitrary-precision arithmetic.
|
|
* https://github.com/MikeMcl/bignumber.js
|
|
* Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
|
|
* MIT Licensed.
|
|
*
|
|
* BigNumber.prototype methods | BigNumber methods
|
|
* |
|
|
* absoluteValue abs | clone
|
|
* comparedTo | config set
|
|
* decimalPlaces dp | DECIMAL_PLACES
|
|
* dividedBy div | ROUNDING_MODE
|
|
* dividedToIntegerBy idiv | EXPONENTIAL_AT
|
|
* exponentiatedBy pow | RANGE
|
|
* integerValue | CRYPTO
|
|
* isEqualTo eq | MODULO_MODE
|
|
* isFinite | POW_PRECISION
|
|
* isGreaterThan gt | FORMAT
|
|
* isGreaterThanOrEqualTo gte | ALPHABET
|
|
* isInteger | isBigNumber
|
|
* isLessThan lt | maximum max
|
|
* isLessThanOrEqualTo lte | minimum min
|
|
* isNaN | random
|
|
* isNegative | sum
|
|
* isPositive |
|
|
* isZero |
|
|
* minus |
|
|
* modulo mod |
|
|
* multipliedBy times |
|
|
* negated |
|
|
* plus |
|
|
* precision sd |
|
|
* shiftedBy |
|
|
* squareRoot sqrt |
|
|
* toExponential |
|
|
* toFixed |
|
|
* toFormat |
|
|
* toFraction |
|
|
* toJSON |
|
|
* toNumber |
|
|
* toPrecision |
|
|
* toString |
|
|
* valueOf |
|
|
*
|
|
*/ var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = '[BigNumber Error] ', tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 0x1fffffffffffff, // MAX_INT32 = 0x7fffffff, // 2^31 - 1
|
|
POWS_TEN = [
|
|
1,
|
|
10,
|
|
100,
|
|
1e3,
|
|
1e4,
|
|
1e5,
|
|
1e6,
|
|
1e7,
|
|
1e8,
|
|
1e9,
|
|
1e10,
|
|
1e11,
|
|
1e12,
|
|
1e13
|
|
], SQRT_BASE = 1e7, // EDITABLE
|
|
// The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
|
|
// the arguments to toExponential, toFixed, toFormat, and toPrecision.
|
|
MAX = 1E9; // 0 to MAX_INT32
|
|
/*
|
|
* Create and return a BigNumber constructor.
|
|
*/ function clone(configObject) {
|
|
var div, convertBase, parseNumeric, P = BigNumber.prototype = {
|
|
constructor: BigNumber,
|
|
toString: null,
|
|
valueOf: null
|
|
}, ONE = new BigNumber(1), //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------
|
|
// The default values below must be integers within the inclusive ranges stated.
|
|
// The values can also be changed at run-time using BigNumber.set.
|
|
// The maximum number of decimal places for operations involving division.
|
|
DECIMAL_PLACES = 20, // The rounding mode used when rounding to the above decimal places, and when using
|
|
// toExponential, toFixed, toFormat and toPrecision, and round (default value).
|
|
// UP 0 Away from zero.
|
|
// DOWN 1 Towards zero.
|
|
// CEIL 2 Towards +Infinity.
|
|
// FLOOR 3 Towards -Infinity.
|
|
// HALF_UP 4 Towards nearest neighbour. If equidistant, up.
|
|
// HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
|
|
// HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
|
|
// HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
|
|
// HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
|
|
ROUNDING_MODE = 4, // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
|
|
// The exponent value at and beneath which toString returns exponential notation.
|
|
// Number type: -7
|
|
TO_EXP_NEG = -7, // The exponent value at and above which toString returns exponential notation.
|
|
// Number type: 21
|
|
TO_EXP_POS = 21, // RANGE : [MIN_EXP, MAX_EXP]
|
|
// The minimum exponent value, beneath which underflow to zero occurs.
|
|
// Number type: -324 (5e-324)
|
|
MIN_EXP = -1e7, // The maximum exponent value, above which overflow to Infinity occurs.
|
|
// Number type: 308 (1.7976931348623157e+308)
|
|
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
|
|
MAX_EXP = 1e7, // Whether to use cryptographically-secure random number generation, if available.
|
|
CRYPTO = false, // The modulo mode used when calculating the modulus: a mod n.
|
|
// The quotient (q = a / n) is calculated according to the corresponding rounding mode.
|
|
// The remainder (r) is calculated as: r = a - n * q.
|
|
//
|
|
// UP 0 The remainder is positive if the dividend is negative, else is negative.
|
|
// DOWN 1 The remainder has the same sign as the dividend.
|
|
// This modulo mode is commonly known as 'truncated division' and is
|
|
// equivalent to (a % n) in JavaScript.
|
|
// FLOOR 3 The remainder has the same sign as the divisor (Python %).
|
|
// HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
|
|
// EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
|
|
// The remainder is always positive.
|
|
//
|
|
// The truncated division, floored division, Euclidian division and IEEE 754 remainder
|
|
// modes are commonly used for the modulus operation.
|
|
// Although the other rounding modes can also be used, they may not give useful results.
|
|
MODULO_MODE = 1, // The maximum number of significant digits of the result of the exponentiatedBy operation.
|
|
// If POW_PRECISION is 0, there will be unlimited significant digits.
|
|
POW_PRECISION = 0, // The format specification used by the BigNumber.prototype.toFormat method.
|
|
FORMAT = {
|
|
prefix: '',
|
|
groupSize: 3,
|
|
secondaryGroupSize: 0,
|
|
groupSeparator: ',',
|
|
decimalSeparator: '.',
|
|
fractionGroupSize: 0,
|
|
fractionGroupSeparator: '\xA0',
|
|
suffix: ''
|
|
}, // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',
|
|
// '-', '.', whitespace, or repeated character.
|
|
// '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
|
|
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', alphabetHasNormalDecimalDigits = true;
|
|
//------------------------------------------------------------------------------------------
|
|
// CONSTRUCTOR
|
|
/*
|
|
* The BigNumber constructor and exported function.
|
|
* Create and return a new instance of a BigNumber object.
|
|
*
|
|
* v {number|string|BigNumber} A numeric value.
|
|
* [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.
|
|
*/ function BigNumber(v, b) {
|
|
var alphabet, c, caseChanged, e, i, isNum, len, str, x = this;
|
|
// Enable constructor call without `new`.
|
|
if (!(x instanceof BigNumber)) return new BigNumber(v, b);
|
|
if (b == null) {
|
|
if (v && v._isBigNumber === true) {
|
|
x.s = v.s;
|
|
if (!v.c || v.e > MAX_EXP) {
|
|
x.c = x.e = null;
|
|
} else if (v.e < MIN_EXP) {
|
|
x.c = [
|
|
x.e = 0
|
|
];
|
|
} else {
|
|
x.e = v.e;
|
|
x.c = v.c.slice();
|
|
}
|
|
return;
|
|
}
|
|
if ((isNum = typeof v == 'number') && v * 0 == 0) {
|
|
// Use `1 / n` to handle minus zero also.
|
|
x.s = 1 / v < 0 ? (v = -v, -1) : 1;
|
|
// Fast path for integers, where n < 2147483648 (2**31).
|
|
if (v === ~~v) {
|
|
for(e = 0, i = v; i >= 10; i /= 10, e++);
|
|
if (e > MAX_EXP) {
|
|
x.c = x.e = null;
|
|
} else {
|
|
x.e = e;
|
|
x.c = [
|
|
v
|
|
];
|
|
}
|
|
return;
|
|
}
|
|
str = String(v);
|
|
} else {
|
|
if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);
|
|
x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
|
|
}
|
|
// Decimal point?
|
|
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
|
|
// Exponential form?
|
|
if ((i = str.search(/e/i)) > 0) {
|
|
// Determine exponent.
|
|
if (e < 0) e = i;
|
|
e += +str.slice(i + 1);
|
|
str = str.substring(0, i);
|
|
} else if (e < 0) {
|
|
// Integer.
|
|
e = str.length;
|
|
}
|
|
} else {
|
|
// '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
|
|
intCheck(b, 2, ALPHABET.length, 'Base');
|
|
// Allow exponential notation to be used with base 10 argument, while
|
|
// also rounding to DECIMAL_PLACES as with other bases.
|
|
if (b == 10 && alphabetHasNormalDecimalDigits) {
|
|
x = new BigNumber(v);
|
|
return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
|
|
}
|
|
str = String(v);
|
|
if (isNum = typeof v == 'number') {
|
|
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
|
|
if (v * 0 != 0) return parseNumeric(x, str, isNum, b);
|
|
x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
|
|
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
|
|
if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {
|
|
throw Error(tooManyDigits + v);
|
|
}
|
|
} else {
|
|
x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
|
|
}
|
|
alphabet = ALPHABET.slice(0, b);
|
|
e = i = 0;
|
|
// Check that str is a valid base b number.
|
|
// Don't use RegExp, so alphabet can contain special characters.
|
|
for(len = str.length; i < len; i++){
|
|
if (alphabet.indexOf(c = str.charAt(i)) < 0) {
|
|
if (c == '.') {
|
|
// If '.' is not the first character and it has not be found before.
|
|
if (i > e) {
|
|
e = len;
|
|
continue;
|
|
}
|
|
} else if (!caseChanged) {
|
|
// Allow e.g. hexadecimal 'FF' as well as 'ff'.
|
|
if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) {
|
|
caseChanged = true;
|
|
i = -1;
|
|
e = 0;
|
|
continue;
|
|
}
|
|
}
|
|
return parseNumeric(x, String(v), isNum, b);
|
|
}
|
|
}
|
|
// Prevent later check for length on converted number.
|
|
isNum = false;
|
|
str = convertBase(str, b, 10, x.s);
|
|
// Decimal point?
|
|
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
|
|
else e = str.length;
|
|
}
|
|
// Determine leading zeros.
|
|
for(i = 0; str.charCodeAt(i) === 48; i++);
|
|
// Determine trailing zeros.
|
|
for(len = str.length; str.charCodeAt(--len) === 48;);
|
|
if (str = str.slice(i, ++len)) {
|
|
len -= i;
|
|
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
|
|
if (isNum && BigNumber.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
|
|
throw Error(tooManyDigits + x.s * v);
|
|
}
|
|
// Overflow?
|
|
if ((e = e - i - 1) > MAX_EXP) {
|
|
// Infinity.
|
|
x.c = x.e = null;
|
|
// Underflow?
|
|
} else if (e < MIN_EXP) {
|
|
// Zero.
|
|
x.c = [
|
|
x.e = 0
|
|
];
|
|
} else {
|
|
x.e = e;
|
|
x.c = [];
|
|
// Transform base
|
|
// e is the base 10 exponent.
|
|
// i is where to slice str to get the first element of the coefficient array.
|
|
i = (e + 1) % LOG_BASE;
|
|
if (e < 0) i += LOG_BASE; // i < 1
|
|
if (i < len) {
|
|
if (i) x.c.push(+str.slice(0, i));
|
|
for(len -= LOG_BASE; i < len;){
|
|
x.c.push(+str.slice(i, i += LOG_BASE));
|
|
}
|
|
i = LOG_BASE - (str = str.slice(i)).length;
|
|
} else {
|
|
i -= len;
|
|
}
|
|
for(; i--; str += '0');
|
|
x.c.push(+str);
|
|
}
|
|
} else {
|
|
// Zero.
|
|
x.c = [
|
|
x.e = 0
|
|
];
|
|
}
|
|
}
|
|
// CONSTRUCTOR PROPERTIES
|
|
BigNumber.clone = clone;
|
|
BigNumber.ROUND_UP = 0;
|
|
BigNumber.ROUND_DOWN = 1;
|
|
BigNumber.ROUND_CEIL = 2;
|
|
BigNumber.ROUND_FLOOR = 3;
|
|
BigNumber.ROUND_HALF_UP = 4;
|
|
BigNumber.ROUND_HALF_DOWN = 5;
|
|
BigNumber.ROUND_HALF_EVEN = 6;
|
|
BigNumber.ROUND_HALF_CEIL = 7;
|
|
BigNumber.ROUND_HALF_FLOOR = 8;
|
|
BigNumber.EUCLID = 9;
|
|
/*
|
|
* Configure infrequently-changing library-wide settings.
|
|
*
|
|
* Accept an object with the following optional properties (if the value of a property is
|
|
* a number, it must be an integer within the inclusive range stated):
|
|
*
|
|
* DECIMAL_PLACES {number} 0 to MAX
|
|
* ROUNDING_MODE {number} 0 to 8
|
|
* EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]
|
|
* RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]
|
|
* CRYPTO {boolean} true or false
|
|
* MODULO_MODE {number} 0 to 9
|
|
* POW_PRECISION {number} 0 to MAX
|
|
* ALPHABET {string} A string of two or more unique characters which does
|
|
* not contain '.'.
|
|
* FORMAT {object} An object with some of the following properties:
|
|
* prefix {string}
|
|
* groupSize {number}
|
|
* secondaryGroupSize {number}
|
|
* groupSeparator {string}
|
|
* decimalSeparator {string}
|
|
* fractionGroupSize {number}
|
|
* fractionGroupSeparator {string}
|
|
* suffix {string}
|
|
*
|
|
* (The values assigned to the above FORMAT object properties are not checked for validity.)
|
|
*
|
|
* E.g.
|
|
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
|
|
*
|
|
* Ignore properties/parameters set to null or undefined, except for ALPHABET.
|
|
*
|
|
* Return an object with the properties current values.
|
|
*/ BigNumber.config = BigNumber.set = function(obj) {
|
|
var p, v;
|
|
if (obj != null) {
|
|
if (typeof obj == 'object') {
|
|
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
|
|
// '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'
|
|
if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {
|
|
v = obj[p];
|
|
intCheck(v, 0, MAX, p);
|
|
DECIMAL_PLACES = v;
|
|
}
|
|
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
|
|
// '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'
|
|
if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {
|
|
v = obj[p];
|
|
intCheck(v, 0, 8, p);
|
|
ROUNDING_MODE = v;
|
|
}
|
|
// EXPONENTIAL_AT {number|number[]}
|
|
// Integer, -MAX to MAX inclusive or
|
|
// [integer -MAX to 0 inclusive, 0 to MAX inclusive].
|
|
// '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'
|
|
if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {
|
|
v = obj[p];
|
|
if (v && v.pop) {
|
|
intCheck(v[0], -MAX, 0, p);
|
|
intCheck(v[1], 0, MAX, p);
|
|
TO_EXP_NEG = v[0];
|
|
TO_EXP_POS = v[1];
|
|
} else {
|
|
intCheck(v, -MAX, MAX, p);
|
|
TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
|
|
}
|
|
}
|
|
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
|
|
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
|
|
// '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'
|
|
if (obj.hasOwnProperty(p = 'RANGE')) {
|
|
v = obj[p];
|
|
if (v && v.pop) {
|
|
intCheck(v[0], -MAX, -1, p);
|
|
intCheck(v[1], 1, MAX, p);
|
|
MIN_EXP = v[0];
|
|
MAX_EXP = v[1];
|
|
} else {
|
|
intCheck(v, -MAX, MAX, p);
|
|
if (v) {
|
|
MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
|
|
} else {
|
|
throw Error(bignumberError + p + ' cannot be zero: ' + v);
|
|
}
|
|
}
|
|
}
|
|
// CRYPTO {boolean} true or false.
|
|
// '[BigNumber Error] CRYPTO not true or false: {v}'
|
|
// '[BigNumber Error] crypto unavailable'
|
|
if (obj.hasOwnProperty(p = 'CRYPTO')) {
|
|
v = obj[p];
|
|
if (v === !!v) {
|
|
if (v) {
|
|
if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
|
|
CRYPTO = v;
|
|
} else {
|
|
CRYPTO = !v;
|
|
throw Error(bignumberError + 'crypto unavailable');
|
|
}
|
|
} else {
|
|
CRYPTO = v;
|
|
}
|
|
} else {
|
|
throw Error(bignumberError + p + ' not true or false: ' + v);
|
|
}
|
|
}
|
|
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
|
|
// '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'
|
|
if (obj.hasOwnProperty(p = 'MODULO_MODE')) {
|
|
v = obj[p];
|
|
intCheck(v, 0, 9, p);
|
|
MODULO_MODE = v;
|
|
}
|
|
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
|
|
// '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'
|
|
if (obj.hasOwnProperty(p = 'POW_PRECISION')) {
|
|
v = obj[p];
|
|
intCheck(v, 0, MAX, p);
|
|
POW_PRECISION = v;
|
|
}
|
|
// FORMAT {object}
|
|
// '[BigNumber Error] FORMAT not an object: {v}'
|
|
if (obj.hasOwnProperty(p = 'FORMAT')) {
|
|
v = obj[p];
|
|
if (typeof v == 'object') FORMAT = v;
|
|
else throw Error(bignumberError + p + ' not an object: ' + v);
|
|
}
|
|
// ALPHABET {string}
|
|
// '[BigNumber Error] ALPHABET invalid: {v}'
|
|
if (obj.hasOwnProperty(p = 'ALPHABET')) {
|
|
v = obj[p];
|
|
// Disallow if less than two characters,
|
|
// or if it contains '+', '-', '.', whitespace, or a repeated character.
|
|
if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {
|
|
alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';
|
|
ALPHABET = v;
|
|
} else {
|
|
throw Error(bignumberError + p + ' invalid: ' + v);
|
|
}
|
|
}
|
|
} else {
|
|
// '[BigNumber Error] Object expected: {v}'
|
|
throw Error(bignumberError + 'Object expected: ' + obj);
|
|
}
|
|
}
|
|
return {
|
|
DECIMAL_PLACES: DECIMAL_PLACES,
|
|
ROUNDING_MODE: ROUNDING_MODE,
|
|
EXPONENTIAL_AT: [
|
|
TO_EXP_NEG,
|
|
TO_EXP_POS
|
|
],
|
|
RANGE: [
|
|
MIN_EXP,
|
|
MAX_EXP
|
|
],
|
|
CRYPTO: CRYPTO,
|
|
MODULO_MODE: MODULO_MODE,
|
|
POW_PRECISION: POW_PRECISION,
|
|
FORMAT: FORMAT,
|
|
ALPHABET: ALPHABET
|
|
};
|
|
};
|
|
/*
|
|
* Return true if v is a BigNumber instance, otherwise return false.
|
|
*
|
|
* If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.
|
|
*
|
|
* v {any}
|
|
*
|
|
* '[BigNumber Error] Invalid BigNumber: {v}'
|
|
*/ BigNumber.isBigNumber = function(v) {
|
|
if (!v || v._isBigNumber !== true) return false;
|
|
if (!BigNumber.DEBUG) return true;
|
|
var i, n, c = v.c, e = v.e, s = v.s;
|
|
out: if (({}).toString.call(c) == '[object Array]') {
|
|
if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
|
|
// If the first element is zero, the BigNumber value must be zero.
|
|
if (c[0] === 0) {
|
|
if (e === 0 && c.length === 1) return true;
|
|
break out;
|
|
}
|
|
// Calculate number of digits that c[0] should have, based on the exponent.
|
|
i = (e + 1) % LOG_BASE;
|
|
if (i < 1) i += LOG_BASE;
|
|
// Calculate number of digits of c[0].
|
|
//if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {
|
|
if (String(c[0]).length == i) {
|
|
for(i = 0; i < c.length; i++){
|
|
n = c[i];
|
|
if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
|
|
}
|
|
// Last element cannot be zero, unless it is the only element.
|
|
if (n !== 0) return true;
|
|
}
|
|
}
|
|
// Infinity/NaN
|
|
} else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
|
|
return true;
|
|
}
|
|
throw Error(bignumberError + 'Invalid BigNumber: ' + v);
|
|
};
|
|
/*
|
|
* Return a new BigNumber whose value is the maximum of the arguments.
|
|
*
|
|
* arguments {number|string|BigNumber}
|
|
*/ BigNumber.maximum = BigNumber.max = function() {
|
|
return maxOrMin(arguments, -1);
|
|
};
|
|
/*
|
|
* Return a new BigNumber whose value is the minimum of the arguments.
|
|
*
|
|
* arguments {number|string|BigNumber}
|
|
*/ BigNumber.minimum = BigNumber.min = function() {
|
|
return maxOrMin(arguments, 1);
|
|
};
|
|
/*
|
|
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
|
|
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
|
|
* zeros are produced).
|
|
*
|
|
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'
|
|
* '[BigNumber Error] crypto unavailable'
|
|
*/ BigNumber.random = function() {
|
|
var pow2_53 = 0x20000000000000;
|
|
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
|
|
// Check if Math.random() produces more than 32 bits of randomness.
|
|
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
|
|
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
|
|
var random53bitInt = Math.random() * pow2_53 & 0x1fffff ? function() {
|
|
return mathfloor(Math.random() * pow2_53);
|
|
} : function() {
|
|
return (Math.random() * 0x40000000 | 0) * 0x800000 + (Math.random() * 0x800000 | 0);
|
|
};
|
|
return function(dp) {
|
|
var a, b, e, k, v, i = 0, c = [], rand = new BigNumber(ONE);
|
|
if (dp == null) dp = DECIMAL_PLACES;
|
|
else intCheck(dp, 0, MAX);
|
|
k = mathceil(dp / LOG_BASE);
|
|
if (CRYPTO) {
|
|
// Browsers supporting crypto.getRandomValues.
|
|
if (crypto.getRandomValues) {
|
|
a = crypto.getRandomValues(new Uint32Array(k *= 2));
|
|
for(; i < k;){
|
|
// 53 bits:
|
|
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
|
|
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
|
|
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
|
|
// 11111 11111111 11111111
|
|
// 0x20000 is 2^21.
|
|
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
|
|
// Rejection sampling:
|
|
// 0 <= v < 9007199254740992
|
|
// Probability that v >= 9e15, is
|
|
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
|
|
if (v >= 9e15) {
|
|
b = crypto.getRandomValues(new Uint32Array(2));
|
|
a[i] = b[0];
|
|
a[i + 1] = b[1];
|
|
} else {
|
|
// 0 <= v <= 8999999999999999
|
|
// 0 <= (v % 1e14) <= 99999999999999
|
|
c.push(v % 1e14);
|
|
i += 2;
|
|
}
|
|
}
|
|
i = k / 2;
|
|
// Node.js supporting crypto.randomBytes.
|
|
} else if (crypto.randomBytes) {
|
|
// buffer
|
|
a = crypto.randomBytes(k *= 7);
|
|
for(; i < k;){
|
|
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
|
|
// 0x100000000 is 2^32, 0x1000000 is 2^24
|
|
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
|
|
// 0 <= v < 9007199254740992
|
|
v = (a[i] & 31) * 0x1000000000000 + a[i + 1] * 0x10000000000 + a[i + 2] * 0x100000000 + a[i + 3] * 0x1000000 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
|
|
if (v >= 9e15) {
|
|
crypto.randomBytes(7).copy(a, i);
|
|
} else {
|
|
// 0 <= (v % 1e14) <= 99999999999999
|
|
c.push(v % 1e14);
|
|
i += 7;
|
|
}
|
|
}
|
|
i = k / 7;
|
|
} else {
|
|
CRYPTO = false;
|
|
throw Error(bignumberError + 'crypto unavailable');
|
|
}
|
|
}
|
|
// Use Math.random.
|
|
if (!CRYPTO) {
|
|
for(; i < k;){
|
|
v = random53bitInt();
|
|
if (v < 9e15) c[i++] = v % 1e14;
|
|
}
|
|
}
|
|
k = c[--i];
|
|
dp %= LOG_BASE;
|
|
// Convert trailing digits to zeros according to dp.
|
|
if (k && dp) {
|
|
v = POWS_TEN[LOG_BASE - dp];
|
|
c[i] = mathfloor(k / v) * v;
|
|
}
|
|
// Remove trailing elements which are zero.
|
|
for(; c[i] === 0; c.pop(), i--);
|
|
// Zero?
|
|
if (i < 0) {
|
|
c = [
|
|
e = 0
|
|
];
|
|
} else {
|
|
// Remove leading elements which are zero and adjust exponent accordingly.
|
|
for(e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
|
|
// Count the digits of the first element of c to determine leading zeros, and...
|
|
for(i = 1, v = c[0]; v >= 10; v /= 10, i++);
|
|
// adjust the exponent accordingly.
|
|
if (i < LOG_BASE) e -= LOG_BASE - i;
|
|
}
|
|
rand.e = e;
|
|
rand.c = c;
|
|
return rand;
|
|
};
|
|
}();
|
|
/*
|
|
* Return a BigNumber whose value is the sum of the arguments.
|
|
*
|
|
* arguments {number|string|BigNumber}
|
|
*/ BigNumber.sum = function() {
|
|
var i = 1, args = arguments, sum = new BigNumber(args[0]);
|
|
for(; i < args.length;)sum = sum.plus(args[i++]);
|
|
return sum;
|
|
};
|
|
// PRIVATE FUNCTIONS
|
|
// Called by BigNumber and BigNumber.prototype.toString.
|
|
convertBase = function() {
|
|
var decimal = '0123456789';
|
|
/*
|
|
* Convert string of baseIn to an array of numbers of baseOut.
|
|
* Eg. toBaseOut('255', 10, 16) returns [15, 15].
|
|
* Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].
|
|
*/ function toBaseOut(str, baseIn, baseOut, alphabet) {
|
|
var j, arr = [
|
|
0
|
|
], arrL, i = 0, len = str.length;
|
|
for(; i < len;){
|
|
for(arrL = arr.length; arrL--; arr[arrL] *= baseIn);
|
|
arr[0] += alphabet.indexOf(str.charAt(i++));
|
|
for(j = 0; j < arr.length; j++){
|
|
if (arr[j] > baseOut - 1) {
|
|
if (arr[j + 1] == null) arr[j + 1] = 0;
|
|
arr[j + 1] += arr[j] / baseOut | 0;
|
|
arr[j] %= baseOut;
|
|
}
|
|
}
|
|
}
|
|
return arr.reverse();
|
|
}
|
|
// Convert a numeric string of baseIn to a numeric string of baseOut.
|
|
// If the caller is toString, we are converting from base 10 to baseOut.
|
|
// If the caller is BigNumber, we are converting from baseIn to base 10.
|
|
return function(str, baseIn, baseOut, sign, callerIsToString) {
|
|
var alphabet, d, e, k, r, x, xc, y, i = str.indexOf('.'), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
|
|
// Non-integer.
|
|
if (i >= 0) {
|
|
k = POW_PRECISION;
|
|
// Unlimited precision.
|
|
POW_PRECISION = 0;
|
|
str = str.replace('.', '');
|
|
y = new BigNumber(baseIn);
|
|
x = y.pow(str.length - i);
|
|
POW_PRECISION = k;
|
|
// Convert str as if an integer, then restore the fraction part by dividing the
|
|
// result by its base raised to a power.
|
|
y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), 10, baseOut, decimal);
|
|
y.e = y.c.length;
|
|
}
|
|
// Convert the number as integer.
|
|
xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET));
|
|
// xc now represents str as an integer and converted to baseOut. e is the exponent.
|
|
e = k = xc.length;
|
|
// Remove trailing zeros.
|
|
for(; xc[--k] == 0; xc.pop());
|
|
// Zero?
|
|
if (!xc[0]) return alphabet.charAt(0);
|
|
// Does str represent an integer? If so, no need for the division.
|
|
if (i < 0) {
|
|
--e;
|
|
} else {
|
|
x.c = xc;
|
|
x.e = e;
|
|
// The sign is needed for correct rounding.
|
|
x.s = sign;
|
|
x = div(x, y, dp, rm, baseOut);
|
|
xc = x.c;
|
|
r = x.r;
|
|
e = x.e;
|
|
}
|
|
// xc now represents str converted to baseOut.
|
|
// The index of the rounding digit.
|
|
d = e + dp + 1;
|
|
// The rounding digit: the digit to the right of the digit that may be rounded up.
|
|
i = xc[d];
|
|
// Look at the rounding digits and mode to determine whether to round up.
|
|
k = baseOut / 2;
|
|
r = r || d < 0 || xc[d + 1] != null;
|
|
r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));
|
|
// If the index of the rounding digit is not greater than zero, or xc represents
|
|
// zero, then the result of the base conversion is zero or, if rounding up, a value
|
|
// such as 0.00001.
|
|
if (d < 1 || !xc[0]) {
|
|
// 1^-dp or 0
|
|
str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
|
|
} else {
|
|
// Truncate xc to the required number of decimal places.
|
|
xc.length = d;
|
|
// Round up?
|
|
if (r) {
|
|
// Rounding up may mean the previous digit has to be rounded up and so on.
|
|
for(--baseOut; ++xc[--d] > baseOut;){
|
|
xc[d] = 0;
|
|
if (!d) {
|
|
++e;
|
|
xc = [
|
|
1
|
|
].concat(xc);
|
|
}
|
|
}
|
|
}
|
|
// Determine trailing zeros.
|
|
for(k = xc.length; !xc[--k];);
|
|
// E.g. [4, 11, 15] becomes 4bf.
|
|
for(i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));
|
|
// Add leading zeros, decimal point and trailing zeros as required.
|
|
str = toFixedPoint(str, e, alphabet.charAt(0));
|
|
}
|
|
// The caller will add the sign.
|
|
return str;
|
|
};
|
|
}();
|
|
// Perform division in the specified base. Called by div and convertBase.
|
|
div = function() {
|
|
// Assume non-zero x and k.
|
|
function multiply(x, k, base) {
|
|
var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0;
|
|
for(x = x.slice(); i--;){
|
|
xlo = x[i] % SQRT_BASE;
|
|
xhi = x[i] / SQRT_BASE | 0;
|
|
m = khi * xlo + xhi * klo;
|
|
temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;
|
|
carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
|
|
x[i] = temp % base;
|
|
}
|
|
if (carry) x = [
|
|
carry
|
|
].concat(x);
|
|
return x;
|
|
}
|
|
function compare(a, b, aL, bL) {
|
|
var i, cmp;
|
|
if (aL != bL) {
|
|
cmp = aL > bL ? 1 : -1;
|
|
} else {
|
|
for(i = cmp = 0; i < aL; i++){
|
|
if (a[i] != b[i]) {
|
|
cmp = a[i] > b[i] ? 1 : -1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return cmp;
|
|
}
|
|
function subtract(a, b, aL, base) {
|
|
var i = 0;
|
|
// Subtract b from a.
|
|
for(; aL--;){
|
|
a[aL] -= i;
|
|
i = a[aL] < b[aL] ? 1 : 0;
|
|
a[aL] = i * base + a[aL] - b[aL];
|
|
}
|
|
// Remove leading zeros.
|
|
for(; !a[0] && a.length > 1; a.splice(0, 1));
|
|
}
|
|
// x: dividend, y: divisor.
|
|
return function(x, y, dp, rm, base) {
|
|
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c;
|
|
// Either NaN, Infinity or 0?
|
|
if (!xc || !xc[0] || !yc || !yc[0]) {
|
|
return new BigNumber(// Return NaN if either NaN, or both Infinity or 0.
|
|
!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
|
|
xc && xc[0] == 0 || !yc ? s * 0 : s / 0);
|
|
}
|
|
q = new BigNumber(s);
|
|
qc = q.c = [];
|
|
e = x.e - y.e;
|
|
s = dp + e + 1;
|
|
if (!base) {
|
|
base = BASE;
|
|
e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
|
|
s = s / LOG_BASE | 0;
|
|
}
|
|
// Result exponent may be one less then the current value of e.
|
|
// The coefficients of the BigNumbers from convertBase may have trailing zeros.
|
|
for(i = 0; yc[i] == (xc[i] || 0); i++);
|
|
if (yc[i] > (xc[i] || 0)) e--;
|
|
if (s < 0) {
|
|
qc.push(1);
|
|
more = true;
|
|
} else {
|
|
xL = xc.length;
|
|
yL = yc.length;
|
|
i = 0;
|
|
s += 2;
|
|
// Normalise xc and yc so highest order digit of yc is >= base / 2.
|
|
n = mathfloor(base / (yc[0] + 1));
|
|
// Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.
|
|
// if (n > 1 || n++ == 1 && yc[0] < base / 2) {
|
|
if (n > 1) {
|
|
yc = multiply(yc, n, base);
|
|
xc = multiply(xc, n, base);
|
|
yL = yc.length;
|
|
xL = xc.length;
|
|
}
|
|
xi = yL;
|
|
rem = xc.slice(0, yL);
|
|
remL = rem.length;
|
|
// Add zeros to make remainder as long as divisor.
|
|
for(; remL < yL; rem[remL++] = 0);
|
|
yz = yc.slice();
|
|
yz = [
|
|
0
|
|
].concat(yz);
|
|
yc0 = yc[0];
|
|
if (yc[1] >= base / 2) yc0++;
|
|
// Not necessary, but to prevent trial digit n > base, when using base 3.
|
|
// else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;
|
|
do {
|
|
n = 0;
|
|
// Compare divisor and remainder.
|
|
cmp = compare(yc, rem, yL, remL);
|
|
// If divisor < remainder.
|
|
if (cmp < 0) {
|
|
// Calculate trial digit, n.
|
|
rem0 = rem[0];
|
|
if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
|
|
// n is how many times the divisor goes into the current remainder.
|
|
n = mathfloor(rem0 / yc0);
|
|
// Algorithm:
|
|
// product = divisor multiplied by trial digit (n).
|
|
// Compare product and remainder.
|
|
// If product is greater than remainder:
|
|
// Subtract divisor from product, decrement trial digit.
|
|
// Subtract product from remainder.
|
|
// If product was less than remainder at the last compare:
|
|
// Compare new remainder and divisor.
|
|
// If remainder is greater than divisor:
|
|
// Subtract divisor from remainder, increment trial digit.
|
|
if (n > 1) {
|
|
// n may be > base only when base is 3.
|
|
if (n >= base) n = base - 1;
|
|
// product = divisor * trial digit.
|
|
prod = multiply(yc, n, base);
|
|
prodL = prod.length;
|
|
remL = rem.length;
|
|
// Compare product and remainder.
|
|
// If product > remainder then trial digit n too high.
|
|
// n is 1 too high about 5% of the time, and is not known to have
|
|
// ever been more than 1 too high.
|
|
while(compare(prod, rem, prodL, remL) == 1){
|
|
n--;
|
|
// Subtract divisor from product.
|
|
subtract(prod, yL < prodL ? yz : yc, prodL, base);
|
|
prodL = prod.length;
|
|
cmp = 1;
|
|
}
|
|
} else {
|
|
// n is 0 or 1, cmp is -1.
|
|
// If n is 0, there is no need to compare yc and rem again below,
|
|
// so change cmp to 1 to avoid it.
|
|
// If n is 1, leave cmp as -1, so yc and rem are compared again.
|
|
if (n == 0) {
|
|
// divisor < remainder, so n must be at least 1.
|
|
cmp = n = 1;
|
|
}
|
|
// product = divisor
|
|
prod = yc.slice();
|
|
prodL = prod.length;
|
|
}
|
|
if (prodL < remL) prod = [
|
|
0
|
|
].concat(prod);
|
|
// Subtract product from remainder.
|
|
subtract(rem, prod, remL, base);
|
|
remL = rem.length;
|
|
// If product was < remainder.
|
|
if (cmp == -1) {
|
|
// Compare divisor and new remainder.
|
|
// If divisor < new remainder, subtract divisor from remainder.
|
|
// Trial digit n too low.
|
|
// n is 1 too low about 5% of the time, and very rarely 2 too low.
|
|
while(compare(yc, rem, yL, remL) < 1){
|
|
n++;
|
|
// Subtract divisor from remainder.
|
|
subtract(rem, yL < remL ? yz : yc, remL, base);
|
|
remL = rem.length;
|
|
}
|
|
}
|
|
} else if (cmp === 0) {
|
|
n++;
|
|
rem = [
|
|
0
|
|
];
|
|
} // else cmp === 1 and n will be 0
|
|
// Add the next digit, n, to the result array.
|
|
qc[i++] = n;
|
|
// Update the remainder.
|
|
if (rem[0]) {
|
|
rem[remL++] = xc[xi] || 0;
|
|
} else {
|
|
rem = [
|
|
xc[xi]
|
|
];
|
|
remL = 1;
|
|
}
|
|
}while ((xi++ < xL || rem[0] != null) && s--)
|
|
more = rem[0] != null;
|
|
// Leading zero?
|
|
if (!qc[0]) qc.splice(0, 1);
|
|
}
|
|
if (base == BASE) {
|
|
// To calculate q.e, first get the number of digits of qc[0].
|
|
for(i = 1, s = qc[0]; s >= 10; s /= 10, i++);
|
|
round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);
|
|
// Caller is convertBase.
|
|
} else {
|
|
q.e = e;
|
|
q.r = +more;
|
|
}
|
|
return q;
|
|
};
|
|
}();
|
|
/*
|
|
* Return a string representing the value of BigNumber n in fixed-point or exponential
|
|
* notation rounded to the specified decimal places or significant digits.
|
|
*
|
|
* n: a BigNumber.
|
|
* i: the index of the last digit required (i.e. the digit that may be rounded up).
|
|
* rm: the rounding mode.
|
|
* id: 1 (toExponential) or 2 (toPrecision).
|
|
*/ function format(n, i, rm, id) {
|
|
var c0, e, ne, len, str;
|
|
if (rm == null) rm = ROUNDING_MODE;
|
|
else intCheck(rm, 0, 8);
|
|
if (!n.c) return n.toString();
|
|
c0 = n.c[0];
|
|
ne = n.e;
|
|
if (i == null) {
|
|
str = coeffToString(n.c);
|
|
str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, '0');
|
|
} else {
|
|
n = round(new BigNumber(n), i, rm);
|
|
// n.e may have changed if the value was rounded up.
|
|
e = n.e;
|
|
str = coeffToString(n.c);
|
|
len = str.length;
|
|
// toPrecision returns exponential notation if the number of significant digits
|
|
// specified is less than the number of digits necessary to represent the integer
|
|
// part of the value in fixed-point notation.
|
|
// Exponential notation.
|
|
if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {
|
|
// Append zeros?
|
|
for(; len < i; str += '0', len++);
|
|
str = toExponential(str, e);
|
|
// Fixed-point notation.
|
|
} else {
|
|
i -= ne + (id === 2 && e > ne);
|
|
str = toFixedPoint(str, e, '0');
|
|
// Append zeros?
|
|
if (e + 1 > len) {
|
|
if (--i > 0) for(str += '.'; i--; str += '0');
|
|
} else {
|
|
i += e - len;
|
|
if (i > 0) {
|
|
if (e + 1 == len) str += '.';
|
|
for(; i--; str += '0');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return n.s < 0 && c0 ? '-' + str : str;
|
|
}
|
|
// Handle BigNumber.max and BigNumber.min.
|
|
// If any number is NaN, return NaN.
|
|
function maxOrMin(args, n) {
|
|
var k, y, i = 1, x = new BigNumber(args[0]);
|
|
for(; i < args.length; i++){
|
|
y = new BigNumber(args[i]);
|
|
if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {
|
|
x = y;
|
|
}
|
|
}
|
|
return x;
|
|
}
|
|
/*
|
|
* Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
|
|
* Called by minus, plus and times.
|
|
*/ function normalise(n, c, e) {
|
|
var i = 1, j = c.length;
|
|
// Remove trailing zeros.
|
|
for(; !c[--j]; c.pop());
|
|
// Calculate the base 10 exponent. First get the number of digits of c[0].
|
|
for(j = c[0]; j >= 10; j /= 10, i++);
|
|
// Overflow?
|
|
if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {
|
|
// Infinity.
|
|
n.c = n.e = null;
|
|
// Underflow?
|
|
} else if (e < MIN_EXP) {
|
|
// Zero.
|
|
n.c = [
|
|
n.e = 0
|
|
];
|
|
} else {
|
|
n.e = e;
|
|
n.c = c;
|
|
}
|
|
return n;
|
|
}
|
|
// Handle values that fail the validity test in BigNumber.
|
|
parseNumeric = function() {
|
|
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
|
|
return function(x, str, isNum, b) {
|
|
var base, s = isNum ? str : str.replace(whitespaceOrPlus, '');
|
|
// No exception on ±Infinity or NaN.
|
|
if (isInfinityOrNaN.test(s)) {
|
|
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
|
|
} else {
|
|
if (!isNum) {
|
|
// basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
|
|
s = s.replace(basePrefix, function(m, p1, p2) {
|
|
base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
|
|
return !b || b == base ? p1 : m;
|
|
});
|
|
if (b) {
|
|
base = b;
|
|
// E.g. '1.' to '1', '.1' to '0.1'
|
|
s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');
|
|
}
|
|
if (str != s) return new BigNumber(s, base);
|
|
}
|
|
// '[BigNumber Error] Not a number: {n}'
|
|
// '[BigNumber Error] Not a base {b} number: {n}'
|
|
if (BigNumber.DEBUG) {
|
|
throw Error(bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);
|
|
}
|
|
// NaN
|
|
x.s = null;
|
|
}
|
|
x.c = x.e = null;
|
|
};
|
|
}();
|
|
/*
|
|
* Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
|
|
* If r is truthy, it is known that there are more digits after the rounding digit.
|
|
*/ function round(x, sd, rm, r) {
|
|
var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN;
|
|
// if x is not Infinity or NaN...
|
|
if (xc) {
|
|
// rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
|
|
// n is a base 1e14 number, the value of the element of array x.c containing rd.
|
|
// ni is the index of n within x.c.
|
|
// d is the number of digits of n.
|
|
// i is the index of rd within n including leading zeros.
|
|
// j is the actual index of rd within n (if < 0, rd is a leading zero).
|
|
out: {
|
|
// Get the number of digits of the first element of xc.
|
|
for(d = 1, k = xc[0]; k >= 10; k /= 10, d++);
|
|
i = sd - d;
|
|
// If the rounding digit is in the first element of xc...
|
|
if (i < 0) {
|
|
i += LOG_BASE;
|
|
j = sd;
|
|
n = xc[ni = 0];
|
|
// Get the rounding digit at index j of n.
|
|
rd = mathfloor(n / pows10[d - j - 1] % 10);
|
|
} else {
|
|
ni = mathceil((i + 1) / LOG_BASE);
|
|
if (ni >= xc.length) {
|
|
if (r) {
|
|
// Needed by sqrt.
|
|
for(; xc.length <= ni; xc.push(0));
|
|
n = rd = 0;
|
|
d = 1;
|
|
i %= LOG_BASE;
|
|
j = i - LOG_BASE + 1;
|
|
} else {
|
|
break out;
|
|
}
|
|
} else {
|
|
n = k = xc[ni];
|
|
// Get the number of digits of n.
|
|
for(d = 1; k >= 10; k /= 10, d++);
|
|
// Get the index of rd within n.
|
|
i %= LOG_BASE;
|
|
// Get the index of rd within n, adjusted for leading zeros.
|
|
// The number of leading zeros of n is given by LOG_BASE - d.
|
|
j = i - LOG_BASE + d;
|
|
// Get the rounding digit at index j of n.
|
|
rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);
|
|
}
|
|
}
|
|
r = r || sd < 0 || // Are there any non-zero digits after the rounding digit?
|
|
// The expression n % pows10[d - j - 1] returns all digits of n to the right
|
|
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
|
|
xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);
|
|
r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
|
|
(i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7));
|
|
if (sd < 1 || !xc[0]) {
|
|
xc.length = 0;
|
|
if (r) {
|
|
// Convert sd to decimal places.
|
|
sd -= x.e + 1;
|
|
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
|
|
xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
|
|
x.e = -sd || 0;
|
|
} else {
|
|
// Zero.
|
|
xc[0] = x.e = 0;
|
|
}
|
|
return x;
|
|
}
|
|
// Remove excess digits.
|
|
if (i == 0) {
|
|
xc.length = ni;
|
|
k = 1;
|
|
ni--;
|
|
} else {
|
|
xc.length = ni + 1;
|
|
k = pows10[LOG_BASE - i];
|
|
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
|
|
// j > 0 means i > number of leading zeros of n.
|
|
xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;
|
|
}
|
|
// Round up?
|
|
if (r) {
|
|
for(;;){
|
|
// If the digit to be rounded up is in the first element of xc...
|
|
if (ni == 0) {
|
|
// i will be the length of xc[0] before k is added.
|
|
for(i = 1, j = xc[0]; j >= 10; j /= 10, i++);
|
|
j = xc[0] += k;
|
|
for(k = 1; j >= 10; j /= 10, k++);
|
|
// if i != k the length has increased.
|
|
if (i != k) {
|
|
x.e++;
|
|
if (xc[0] == BASE) xc[0] = 1;
|
|
}
|
|
break;
|
|
} else {
|
|
xc[ni] += k;
|
|
if (xc[ni] != BASE) break;
|
|
xc[ni--] = 0;
|
|
k = 1;
|
|
}
|
|
}
|
|
}
|
|
// Remove trailing zeros.
|
|
for(i = xc.length; xc[--i] === 0; xc.pop());
|
|
}
|
|
// Overflow? Infinity.
|
|
if (x.e > MAX_EXP) {
|
|
x.c = x.e = null;
|
|
// Underflow? Zero.
|
|
} else if (x.e < MIN_EXP) {
|
|
x.c = [
|
|
x.e = 0
|
|
];
|
|
}
|
|
}
|
|
return x;
|
|
}
|
|
function valueOf(n) {
|
|
var str, e = n.e;
|
|
if (e === null) return n.toString();
|
|
str = coeffToString(n.c);
|
|
str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, '0');
|
|
return n.s < 0 ? '-' + str : str;
|
|
}
|
|
// PROTOTYPE/INSTANCE METHODS
|
|
/*
|
|
* Return a new BigNumber whose value is the absolute value of this BigNumber.
|
|
*/ P.absoluteValue = P.abs = function() {
|
|
var x = new BigNumber(this);
|
|
if (x.s < 0) x.s = 1;
|
|
return x;
|
|
};
|
|
/*
|
|
* Return
|
|
* 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
|
|
* -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
|
|
* 0 if they have the same value,
|
|
* or null if the value of either is NaN.
|
|
*/ P.comparedTo = function(y, b) {
|
|
return compare(this, new BigNumber(y, b));
|
|
};
|
|
/*
|
|
* If dp is undefined or null or true or false, return the number of decimal places of the
|
|
* value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
|
|
*
|
|
* Otherwise, if dp is a number, return a new BigNumber whose value is the value of this
|
|
* BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or
|
|
* ROUNDING_MODE if rm is omitted.
|
|
*
|
|
* [dp] {number} Decimal places: integer, 0 to MAX inclusive.
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
|
|
*/ P.decimalPlaces = P.dp = function(dp, rm) {
|
|
var c, n, v, x = this;
|
|
if (dp != null) {
|
|
intCheck(dp, 0, MAX);
|
|
if (rm == null) rm = ROUNDING_MODE;
|
|
else intCheck(rm, 0, 8);
|
|
return round(new BigNumber(x), dp + x.e + 1, rm);
|
|
}
|
|
if (!(c = x.c)) return null;
|
|
n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
|
|
// Subtract the number of trailing zeros of the last number.
|
|
if (v = c[v]) for(; v % 10 == 0; v /= 10, n--);
|
|
if (n < 0) n = 0;
|
|
return n;
|
|
};
|
|
/*
|
|
* n / 0 = I
|
|
* n / N = N
|
|
* n / I = 0
|
|
* 0 / n = 0
|
|
* 0 / 0 = N
|
|
* 0 / N = N
|
|
* 0 / I = 0
|
|
* N / n = N
|
|
* N / 0 = N
|
|
* N / N = N
|
|
* N / I = N
|
|
* I / n = I
|
|
* I / 0 = I
|
|
* I / N = N
|
|
* I / I = N
|
|
*
|
|
* Return a new BigNumber whose value is the value of this BigNumber divided by the value of
|
|
* BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
|
|
*/ P.dividedBy = P.div = function(y, b) {
|
|
return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);
|
|
};
|
|
/*
|
|
* Return a new BigNumber whose value is the integer part of dividing the value of this
|
|
* BigNumber by the value of BigNumber(y, b).
|
|
*/ P.dividedToIntegerBy = P.idiv = function(y, b) {
|
|
return div(this, new BigNumber(y, b), 0, 1);
|
|
};
|
|
/*
|
|
* Return a BigNumber whose value is the value of this BigNumber exponentiated by n.
|
|
*
|
|
* If m is present, return the result modulo m.
|
|
* If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
|
|
* If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.
|
|
*
|
|
* The modular power operation works efficiently when x, n, and m are integers, otherwise it
|
|
* is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.
|
|
*
|
|
* n {number|string|BigNumber} The exponent. An integer.
|
|
* [m] {number|string|BigNumber} The modulus.
|
|
*
|
|
* '[BigNumber Error] Exponent not an integer: {n}'
|
|
*/ P.exponentiatedBy = P.pow = function(n, m) {
|
|
var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this;
|
|
n = new BigNumber(n);
|
|
// Allow NaN and ±Infinity, but not other non-integers.
|
|
if (n.c && !n.isInteger()) {
|
|
throw Error(bignumberError + 'Exponent not an integer: ' + valueOf(n));
|
|
}
|
|
if (m != null) m = new BigNumber(m);
|
|
// Exponent of MAX_SAFE_INTEGER is 15.
|
|
nIsBig = n.e > 14;
|
|
// If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.
|
|
if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {
|
|
// The sign of the result of pow when x is negative depends on the evenness of n.
|
|
// If +n overflows to ±Infinity, the evenness of n would be not be known.
|
|
y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));
|
|
return m ? y.mod(m) : y;
|
|
}
|
|
nIsNeg = n.s < 0;
|
|
if (m) {
|
|
// x % m returns NaN if abs(m) is zero, or m is NaN.
|
|
if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);
|
|
isModExp = !nIsNeg && x.isInteger() && m.isInteger();
|
|
if (isModExp) x = x.mod(m);
|
|
// Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.
|
|
// Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.
|
|
} else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {
|
|
// If x is negative and n is odd, k = -0, else k = 0.
|
|
k = x.s < 0 && isOdd(n) ? -0 : 0;
|
|
// If x >= 1, k = ±Infinity.
|
|
if (x.e > -1) k = 1 / k;
|
|
// If n is negative return ±0, else return ±Infinity.
|
|
return new BigNumber(nIsNeg ? 1 / k : k);
|
|
} else if (POW_PRECISION) {
|
|
// Truncating each coefficient array to a length of k after each multiplication
|
|
// equates to truncating significant digits to POW_PRECISION + [28, 41],
|
|
// i.e. there will be a minimum of 28 guard digits retained.
|
|
k = mathceil(POW_PRECISION / LOG_BASE + 2);
|
|
}
|
|
if (nIsBig) {
|
|
half = new BigNumber(0.5);
|
|
if (nIsNeg) n.s = 1;
|
|
nIsOdd = isOdd(n);
|
|
} else {
|
|
i = Math.abs(+valueOf(n));
|
|
nIsOdd = i % 2;
|
|
}
|
|
y = new BigNumber(ONE);
|
|
// Performs 54 loop iterations for n of 9007199254740991.
|
|
for(;;){
|
|
if (nIsOdd) {
|
|
y = y.times(x);
|
|
if (!y.c) break;
|
|
if (k) {
|
|
if (y.c.length > k) y.c.length = k;
|
|
} else if (isModExp) {
|
|
y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));
|
|
}
|
|
}
|
|
if (i) {
|
|
i = mathfloor(i / 2);
|
|
if (i === 0) break;
|
|
nIsOdd = i % 2;
|
|
} else {
|
|
n = n.times(half);
|
|
round(n, n.e + 1, 1);
|
|
if (n.e > 14) {
|
|
nIsOdd = isOdd(n);
|
|
} else {
|
|
i = +valueOf(n);
|
|
if (i === 0) break;
|
|
nIsOdd = i % 2;
|
|
}
|
|
}
|
|
x = x.times(x);
|
|
if (k) {
|
|
if (x.c && x.c.length > k) x.c.length = k;
|
|
} else if (isModExp) {
|
|
x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));
|
|
}
|
|
}
|
|
if (isModExp) return y;
|
|
if (nIsNeg) y = ONE.div(y);
|
|
return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
|
|
};
|
|
/*
|
|
* Return a new BigNumber whose value is the value of this BigNumber rounded to an integer
|
|
* using rounding mode rm, or ROUNDING_MODE if rm is omitted.
|
|
*
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'
|
|
*/ P.integerValue = function(rm) {
|
|
var n = new BigNumber(this);
|
|
if (rm == null) rm = ROUNDING_MODE;
|
|
else intCheck(rm, 0, 8);
|
|
return round(n, n.e + 1, rm);
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
|
|
* otherwise return false.
|
|
*/ P.isEqualTo = P.eq = function(y, b) {
|
|
return compare(this, new BigNumber(y, b)) === 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is a finite number, otherwise return false.
|
|
*/ P.isFinite = function() {
|
|
return !!this.c;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
|
|
* otherwise return false.
|
|
*/ P.isGreaterThan = P.gt = function(y, b) {
|
|
return compare(this, new BigNumber(y, b)) > 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is greater than or equal to the value of
|
|
* BigNumber(y, b), otherwise return false.
|
|
*/ P.isGreaterThanOrEqualTo = P.gte = function(y, b) {
|
|
return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is an integer, otherwise return false.
|
|
*/ P.isInteger = function() {
|
|
return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
|
|
* otherwise return false.
|
|
*/ P.isLessThan = P.lt = function(y, b) {
|
|
return compare(this, new BigNumber(y, b)) < 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is less than or equal to the value of
|
|
* BigNumber(y, b), otherwise return false.
|
|
*/ P.isLessThanOrEqualTo = P.lte = function(y, b) {
|
|
return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is NaN, otherwise return false.
|
|
*/ P.isNaN = function() {
|
|
return !this.s;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is negative, otherwise return false.
|
|
*/ P.isNegative = function() {
|
|
return this.s < 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is positive, otherwise return false.
|
|
*/ P.isPositive = function() {
|
|
return this.s > 0;
|
|
};
|
|
/*
|
|
* Return true if the value of this BigNumber is 0 or -0, otherwise return false.
|
|
*/ P.isZero = function() {
|
|
return !!this.c && this.c[0] == 0;
|
|
};
|
|
/*
|
|
* n - 0 = n
|
|
* n - N = N
|
|
* n - I = -I
|
|
* 0 - n = -n
|
|
* 0 - 0 = 0
|
|
* 0 - N = N
|
|
* 0 - I = -I
|
|
* N - n = N
|
|
* N - 0 = N
|
|
* N - N = N
|
|
* N - I = N
|
|
* I - n = I
|
|
* I - 0 = I
|
|
* I - N = N
|
|
* I - I = N
|
|
*
|
|
* Return a new BigNumber whose value is the value of this BigNumber minus the value of
|
|
* BigNumber(y, b).
|
|
*/ P.minus = function(y, b) {
|
|
var i, j, t, xLTy, x = this, a = x.s;
|
|
y = new BigNumber(y, b);
|
|
b = y.s;
|
|
// Either NaN?
|
|
if (!a || !b) return new BigNumber(NaN);
|
|
// Signs differ?
|
|
if (a != b) {
|
|
y.s = -b;
|
|
return x.plus(y);
|
|
}
|
|
var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
|
|
if (!xe || !ye) {
|
|
// Either Infinity?
|
|
if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);
|
|
// Either zero?
|
|
if (!xc[0] || !yc[0]) {
|
|
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
|
|
return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
|
|
ROUNDING_MODE == 3 ? -0 : 0);
|
|
}
|
|
}
|
|
xe = bitFloor(xe);
|
|
ye = bitFloor(ye);
|
|
xc = xc.slice();
|
|
// Determine which is the bigger number.
|
|
if (a = xe - ye) {
|
|
if (xLTy = a < 0) {
|
|
a = -a;
|
|
t = xc;
|
|
} else {
|
|
ye = xe;
|
|
t = yc;
|
|
}
|
|
t.reverse();
|
|
// Prepend zeros to equalise exponents.
|
|
for(b = a; b--; t.push(0));
|
|
t.reverse();
|
|
} else {
|
|
// Exponents equal. Check digit by digit.
|
|
j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;
|
|
for(a = b = 0; b < j; b++){
|
|
if (xc[b] != yc[b]) {
|
|
xLTy = xc[b] < yc[b];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// x < y? Point xc to the array of the bigger number.
|
|
if (xLTy) {
|
|
t = xc;
|
|
xc = yc;
|
|
yc = t;
|
|
y.s = -y.s;
|
|
}
|
|
b = (j = yc.length) - (i = xc.length);
|
|
// Append zeros to xc if shorter.
|
|
// No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
|
|
if (b > 0) for(; b--; xc[i++] = 0);
|
|
b = BASE - 1;
|
|
// Subtract yc from xc.
|
|
for(; j > a;){
|
|
if (xc[--j] < yc[j]) {
|
|
for(i = j; i && !xc[--i]; xc[i] = b);
|
|
--xc[i];
|
|
xc[j] += BASE;
|
|
}
|
|
xc[j] -= yc[j];
|
|
}
|
|
// Remove leading zeros and adjust exponent accordingly.
|
|
for(; xc[0] == 0; xc.splice(0, 1), --ye);
|
|
// Zero?
|
|
if (!xc[0]) {
|
|
// Following IEEE 754 (2008) 6.3,
|
|
// n - n = +0 but n - n = -0 when rounding towards -Infinity.
|
|
y.s = ROUNDING_MODE == 3 ? -1 : 1;
|
|
y.c = [
|
|
y.e = 0
|
|
];
|
|
return y;
|
|
}
|
|
// No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
|
|
// for finite x and y.
|
|
return normalise(y, xc, ye);
|
|
};
|
|
/*
|
|
* n % 0 = N
|
|
* n % N = N
|
|
* n % I = n
|
|
* 0 % n = 0
|
|
* -0 % n = -0
|
|
* 0 % 0 = N
|
|
* 0 % N = N
|
|
* 0 % I = 0
|
|
* N % n = N
|
|
* N % 0 = N
|
|
* N % N = N
|
|
* N % I = N
|
|
* I % n = N
|
|
* I % 0 = N
|
|
* I % N = N
|
|
* I % I = N
|
|
*
|
|
* Return a new BigNumber whose value is the value of this BigNumber modulo the value of
|
|
* BigNumber(y, b). The result depends on the value of MODULO_MODE.
|
|
*/ P.modulo = P.mod = function(y, b) {
|
|
var q, s, x = this;
|
|
y = new BigNumber(y, b);
|
|
// Return NaN if x is Infinity or NaN, or y is NaN or zero.
|
|
if (!x.c || !y.s || y.c && !y.c[0]) {
|
|
return new BigNumber(NaN);
|
|
// Return x if y is Infinity or x is zero.
|
|
} else if (!y.c || x.c && !x.c[0]) {
|
|
return new BigNumber(x);
|
|
}
|
|
if (MODULO_MODE == 9) {
|
|
// Euclidian division: q = sign(y) * floor(x / abs(y))
|
|
// r = x - qy where 0 <= r < abs(y)
|
|
s = y.s;
|
|
y.s = 1;
|
|
q = div(x, y, 0, 3);
|
|
y.s = s;
|
|
q.s *= s;
|
|
} else {
|
|
q = div(x, y, 0, MODULO_MODE);
|
|
}
|
|
y = x.minus(q.times(y));
|
|
// To match JavaScript %, ensure sign of zero is sign of dividend.
|
|
if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;
|
|
return y;
|
|
};
|
|
/*
|
|
* n * 0 = 0
|
|
* n * N = N
|
|
* n * I = I
|
|
* 0 * n = 0
|
|
* 0 * 0 = 0
|
|
* 0 * N = N
|
|
* 0 * I = N
|
|
* N * n = N
|
|
* N * 0 = N
|
|
* N * N = N
|
|
* N * I = N
|
|
* I * n = I
|
|
* I * 0 = N
|
|
* I * N = N
|
|
* I * I = I
|
|
*
|
|
* Return a new BigNumber whose value is the value of this BigNumber multiplied by the value
|
|
* of BigNumber(y, b).
|
|
*/ P.multipliedBy = P.times = function(y, b) {
|
|
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber(y, b)).c;
|
|
// Either NaN, ±Infinity or ±0?
|
|
if (!xc || !yc || !xc[0] || !yc[0]) {
|
|
// Return NaN if either is NaN, or one is 0 and the other is Infinity.
|
|
if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
|
|
y.c = y.e = y.s = null;
|
|
} else {
|
|
y.s *= x.s;
|
|
// Return ±Infinity if either is ±Infinity.
|
|
if (!xc || !yc) {
|
|
y.c = y.e = null;
|
|
// Return ±0 if either is ±0.
|
|
} else {
|
|
y.c = [
|
|
0
|
|
];
|
|
y.e = 0;
|
|
}
|
|
}
|
|
return y;
|
|
}
|
|
e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
|
|
y.s *= x.s;
|
|
xcL = xc.length;
|
|
ycL = yc.length;
|
|
// Ensure xc points to longer array and xcL to its length.
|
|
if (xcL < ycL) {
|
|
zc = xc;
|
|
xc = yc;
|
|
yc = zc;
|
|
i = xcL;
|
|
xcL = ycL;
|
|
ycL = i;
|
|
}
|
|
// Initialise the result array with zeros.
|
|
for(i = xcL + ycL, zc = []; i--; zc.push(0));
|
|
base = BASE;
|
|
sqrtBase = SQRT_BASE;
|
|
for(i = ycL; --i >= 0;){
|
|
c = 0;
|
|
ylo = yc[i] % sqrtBase;
|
|
yhi = yc[i] / sqrtBase | 0;
|
|
for(k = xcL, j = i + k; j > i;){
|
|
xlo = xc[--k] % sqrtBase;
|
|
xhi = xc[k] / sqrtBase | 0;
|
|
m = yhi * xlo + xhi * ylo;
|
|
xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c;
|
|
c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
|
|
zc[j--] = xlo % base;
|
|
}
|
|
zc[j] = c;
|
|
}
|
|
if (c) {
|
|
++e;
|
|
} else {
|
|
zc.splice(0, 1);
|
|
}
|
|
return normalise(y, zc, e);
|
|
};
|
|
/*
|
|
* Return a new BigNumber whose value is the value of this BigNumber negated,
|
|
* i.e. multiplied by -1.
|
|
*/ P.negated = function() {
|
|
var x = new BigNumber(this);
|
|
x.s = -x.s || null;
|
|
return x;
|
|
};
|
|
/*
|
|
* n + 0 = n
|
|
* n + N = N
|
|
* n + I = I
|
|
* 0 + n = n
|
|
* 0 + 0 = 0
|
|
* 0 + N = N
|
|
* 0 + I = I
|
|
* N + n = N
|
|
* N + 0 = N
|
|
* N + N = N
|
|
* N + I = N
|
|
* I + n = I
|
|
* I + 0 = I
|
|
* I + N = N
|
|
* I + I = I
|
|
*
|
|
* Return a new BigNumber whose value is the value of this BigNumber plus the value of
|
|
* BigNumber(y, b).
|
|
*/ P.plus = function(y, b) {
|
|
var t, x = this, a = x.s;
|
|
y = new BigNumber(y, b);
|
|
b = y.s;
|
|
// Either NaN?
|
|
if (!a || !b) return new BigNumber(NaN);
|
|
// Signs differ?
|
|
if (a != b) {
|
|
y.s = -b;
|
|
return x.minus(y);
|
|
}
|
|
var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
|
|
if (!xe || !ye) {
|
|
// Return ±Infinity if either ±Infinity.
|
|
if (!xc || !yc) return new BigNumber(a / 0);
|
|
// Either zero?
|
|
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
|
|
if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);
|
|
}
|
|
xe = bitFloor(xe);
|
|
ye = bitFloor(ye);
|
|
xc = xc.slice();
|
|
// Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
|
|
if (a = xe - ye) {
|
|
if (a > 0) {
|
|
ye = xe;
|
|
t = yc;
|
|
} else {
|
|
a = -a;
|
|
t = xc;
|
|
}
|
|
t.reverse();
|
|
for(; a--; t.push(0));
|
|
t.reverse();
|
|
}
|
|
a = xc.length;
|
|
b = yc.length;
|
|
// Point xc to the longer array, and b to the shorter length.
|
|
if (a - b < 0) {
|
|
t = yc;
|
|
yc = xc;
|
|
xc = t;
|
|
b = a;
|
|
}
|
|
// Only start adding at yc.length - 1 as the further digits of xc can be ignored.
|
|
for(a = 0; b;){
|
|
a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;
|
|
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
|
|
}
|
|
if (a) {
|
|
xc = [
|
|
a
|
|
].concat(xc);
|
|
++ye;
|
|
}
|
|
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
|
|
// ye = MAX_EXP + 1 possible
|
|
return normalise(y, xc, ye);
|
|
};
|
|
/*
|
|
* If sd is undefined or null or true or false, return the number of significant digits of
|
|
* the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
|
|
* If sd is true include integer-part trailing zeros in the count.
|
|
*
|
|
* Otherwise, if sd is a number, return a new BigNumber whose value is the value of this
|
|
* BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or
|
|
* ROUNDING_MODE if rm is omitted.
|
|
*
|
|
* sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.
|
|
* boolean: whether to count integer-part trailing zeros: true or false.
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
|
|
*/ P.precision = P.sd = function(sd, rm) {
|
|
var c, n, v, x = this;
|
|
if (sd != null && sd !== !!sd) {
|
|
intCheck(sd, 1, MAX);
|
|
if (rm == null) rm = ROUNDING_MODE;
|
|
else intCheck(rm, 0, 8);
|
|
return round(new BigNumber(x), sd, rm);
|
|
}
|
|
if (!(c = x.c)) return null;
|
|
v = c.length - 1;
|
|
n = v * LOG_BASE + 1;
|
|
if (v = c[v]) {
|
|
// Subtract the number of trailing zeros of the last element.
|
|
for(; v % 10 == 0; v /= 10, n--);
|
|
// Add the number of digits of the first element.
|
|
for(v = c[0]; v >= 10; v /= 10, n++);
|
|
}
|
|
if (sd && x.e + 1 > n) n = x.e + 1;
|
|
return n;
|
|
};
|
|
/*
|
|
* Return a new BigNumber whose value is the value of this BigNumber shifted by k places
|
|
* (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
|
|
*
|
|
* k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'
|
|
*/ P.shiftedBy = function(k) {
|
|
intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
|
|
return this.times('1e' + k);
|
|
};
|
|
/*
|
|
* sqrt(-n) = N
|
|
* sqrt(N) = N
|
|
* sqrt(-I) = N
|
|
* sqrt(I) = I
|
|
* sqrt(0) = 0
|
|
* sqrt(-0) = -0
|
|
*
|
|
* Return a new BigNumber whose value is the square root of the value of this BigNumber,
|
|
* rounded according to DECIMAL_PLACES and ROUNDING_MODE.
|
|
*/ P.squareRoot = P.sqrt = function() {
|
|
var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber('0.5');
|
|
// Negative/NaN/Infinity/zero?
|
|
if (s !== 1 || !c || !c[0]) {
|
|
return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
|
|
}
|
|
// Initial estimate.
|
|
s = Math.sqrt(+valueOf(x));
|
|
// Math.sqrt underflow/overflow?
|
|
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
|
|
if (s == 0 || s == 1 / 0) {
|
|
n = coeffToString(c);
|
|
if ((n.length + e) % 2 == 0) n += '0';
|
|
s = Math.sqrt(+n);
|
|
e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);
|
|
if (s == 1 / 0) {
|
|
n = '5e' + e;
|
|
} else {
|
|
n = s.toExponential();
|
|
n = n.slice(0, n.indexOf('e') + 1) + e;
|
|
}
|
|
r = new BigNumber(n);
|
|
} else {
|
|
r = new BigNumber(s + '');
|
|
}
|
|
// Check for zero.
|
|
// r could be zero if MIN_EXP is changed after the this value was created.
|
|
// This would cause a division by zero (x/t) and hence Infinity below, which would cause
|
|
// coeffToString to throw.
|
|
if (r.c[0]) {
|
|
e = r.e;
|
|
s = e + dp;
|
|
if (s < 3) s = 0;
|
|
// Newton-Raphson iteration.
|
|
for(;;){
|
|
t = r;
|
|
r = half.times(t.plus(div(x, t, dp, 1)));
|
|
if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {
|
|
// The exponent of r may here be one less than the final result exponent,
|
|
// e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
|
|
// are indexed correctly.
|
|
if (r.e < e) --s;
|
|
n = n.slice(s - 3, s + 1);
|
|
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits
|
|
// are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
|
|
// iteration.
|
|
if (n == '9999' || !rep && n == '4999') {
|
|
// On the first iteration only, check to see if rounding up gives the
|
|
// exact result as the nines may infinitely repeat.
|
|
if (!rep) {
|
|
round(t, t.e + DECIMAL_PLACES + 2, 0);
|
|
if (t.times(t).eq(x)) {
|
|
r = t;
|
|
break;
|
|
}
|
|
}
|
|
dp += 4;
|
|
s += 4;
|
|
rep = 1;
|
|
} else {
|
|
// If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
|
|
// result. If not, then there are further digits and m will be truthy.
|
|
if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
|
|
// Truncate to the first rounding digit.
|
|
round(r, r.e + DECIMAL_PLACES + 2, 1);
|
|
m = !r.times(r).eq(x);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
|
|
};
|
|
/*
|
|
* Return a string representing the value of this BigNumber in exponential notation and
|
|
* rounded using ROUNDING_MODE to dp fixed decimal places.
|
|
*
|
|
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
|
|
*/ P.toExponential = function(dp, rm) {
|
|
if (dp != null) {
|
|
intCheck(dp, 0, MAX);
|
|
dp++;
|
|
}
|
|
return format(this, dp, rm, 1);
|
|
};
|
|
/*
|
|
* Return a string representing the value of this BigNumber in fixed-point notation rounding
|
|
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
|
|
*
|
|
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
|
|
* but e.g. (-0.00001).toFixed(0) is '-0'.
|
|
*
|
|
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
|
|
*/ P.toFixed = function(dp, rm) {
|
|
if (dp != null) {
|
|
intCheck(dp, 0, MAX);
|
|
dp = dp + this.e + 1;
|
|
}
|
|
return format(this, dp, rm);
|
|
};
|
|
/*
|
|
* Return a string representing the value of this BigNumber in fixed-point notation rounded
|
|
* using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
|
|
* of the format or FORMAT object (see BigNumber.set).
|
|
*
|
|
* The formatting object may contain some or all of the properties shown below.
|
|
*
|
|
* FORMAT = {
|
|
* prefix: '',
|
|
* groupSize: 3,
|
|
* secondaryGroupSize: 0,
|
|
* groupSeparator: ',',
|
|
* decimalSeparator: '.',
|
|
* fractionGroupSize: 0,
|
|
* fractionGroupSeparator: '\xA0', // non-breaking space
|
|
* suffix: ''
|
|
* };
|
|
*
|
|
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
* [format] {object} Formatting options. See FORMAT pbject above.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
|
|
* '[BigNumber Error] Argument not an object: {format}'
|
|
*/ P.toFormat = function(dp, rm, format) {
|
|
var str, x = this;
|
|
if (format == null) {
|
|
if (dp != null && rm && typeof rm == 'object') {
|
|
format = rm;
|
|
rm = null;
|
|
} else if (dp && typeof dp == 'object') {
|
|
format = dp;
|
|
dp = rm = null;
|
|
} else {
|
|
format = FORMAT;
|
|
}
|
|
} else if (typeof format != 'object') {
|
|
throw Error(bignumberError + 'Argument not an object: ' + format);
|
|
}
|
|
str = x.toFixed(dp, rm);
|
|
if (x.c) {
|
|
var i, arr = str.split('.'), g1 = +format.groupSize, g2 = +format.secondaryGroupSize, groupSeparator = format.groupSeparator || '', intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
|
|
if (g2) {
|
|
i = g1;
|
|
g1 = g2;
|
|
g2 = i;
|
|
len -= i;
|
|
}
|
|
if (g1 > 0 && len > 0) {
|
|
i = len % g1 || g1;
|
|
intPart = intDigits.substr(0, i);
|
|
for(; i < len; i += g1)intPart += groupSeparator + intDigits.substr(i, g1);
|
|
if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
|
|
if (isNeg) intPart = '-' + intPart;
|
|
}
|
|
str = fractionPart ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), '$&' + (format.fractionGroupSeparator || '')) : fractionPart) : intPart;
|
|
}
|
|
return (format.prefix || '') + str + (format.suffix || '');
|
|
};
|
|
/*
|
|
* Return an array of two BigNumbers representing the value of this BigNumber as a simple
|
|
* fraction with an integer numerator and an integer denominator.
|
|
* The denominator will be a positive non-zero value less than or equal to the specified
|
|
* maximum denominator. If a maximum denominator is not specified, the denominator will be
|
|
* the lowest value necessary to represent the number exactly.
|
|
*
|
|
* [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.
|
|
*
|
|
* '[BigNumber Error] Argument {not an integer|out of range} : {md}'
|
|
*/ P.toFraction = function(md) {
|
|
var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, x = this, xc = x.c;
|
|
if (md != null) {
|
|
n = new BigNumber(md);
|
|
// Throw if md is less than one or is not an integer, unless it is Infinity.
|
|
if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {
|
|
throw Error(bignumberError + 'Argument ' + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));
|
|
}
|
|
}
|
|
if (!xc) return new BigNumber(x);
|
|
d = new BigNumber(ONE);
|
|
n1 = d0 = new BigNumber(ONE);
|
|
d1 = n0 = new BigNumber(ONE);
|
|
s = coeffToString(xc);
|
|
// Determine initial denominator.
|
|
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
|
|
e = d.e = s.length - x.e - 1;
|
|
d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
|
|
md = !md || n.comparedTo(d) > 0 ? e > 0 ? d : n1 : n;
|
|
exp = MAX_EXP;
|
|
MAX_EXP = 1 / 0;
|
|
n = new BigNumber(s);
|
|
// n0 = d1 = 0
|
|
n0.c[0] = 0;
|
|
for(;;){
|
|
q = div(n, d, 0, 1);
|
|
d2 = d0.plus(q.times(d1));
|
|
if (d2.comparedTo(md) == 1) break;
|
|
d0 = d1;
|
|
d1 = d2;
|
|
n1 = n0.plus(q.times(d2 = n1));
|
|
n0 = d2;
|
|
d = n.minus(q.times(d2 = d));
|
|
n = d2;
|
|
}
|
|
d2 = div(md.minus(d0), d1, 0, 1);
|
|
n0 = n0.plus(d2.times(n1));
|
|
d0 = d0.plus(d2.times(d1));
|
|
n0.s = n1.s = x.s;
|
|
e = e * 2;
|
|
// Determine which fraction is closer to x, n0/d0 or n1/d1
|
|
r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [
|
|
n1,
|
|
d1
|
|
] : [
|
|
n0,
|
|
d0
|
|
];
|
|
MAX_EXP = exp;
|
|
return r;
|
|
};
|
|
/*
|
|
* Return the value of this BigNumber converted to a number primitive.
|
|
*/ P.toNumber = function() {
|
|
return +valueOf(this);
|
|
};
|
|
/*
|
|
* Return a string representing the value of this BigNumber rounded to sd significant digits
|
|
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
|
|
* necessary to represent the integer part of the value in fixed-point notation, then use
|
|
* exponential notation.
|
|
*
|
|
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
|
|
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
|
|
*
|
|
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
|
|
*/ P.toPrecision = function(sd, rm) {
|
|
if (sd != null) intCheck(sd, 1, MAX);
|
|
return format(this, sd, rm, 2);
|
|
};
|
|
/*
|
|
* Return a string representing the value of this BigNumber in base b, or base 10 if b is
|
|
* omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
|
|
* ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
|
|
* that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
|
|
* TO_EXP_NEG, return exponential notation.
|
|
*
|
|
* [b] {number} Integer, 2 to ALPHABET.length inclusive.
|
|
*
|
|
* '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
|
|
*/ P.toString = function(b) {
|
|
var str, n = this, s = n.s, e = n.e;
|
|
// Infinity or NaN?
|
|
if (e === null) {
|
|
if (s) {
|
|
str = 'Infinity';
|
|
if (s < 0) str = '-' + str;
|
|
} else {
|
|
str = 'NaN';
|
|
}
|
|
} else {
|
|
if (b == null) {
|
|
str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, '0');
|
|
} else if (b === 10 && alphabetHasNormalDecimalDigits) {
|
|
n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);
|
|
str = toFixedPoint(coeffToString(n.c), n.e, '0');
|
|
} else {
|
|
intCheck(b, 2, ALPHABET.length, 'Base');
|
|
str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);
|
|
}
|
|
if (s < 0 && n.c[0]) str = '-' + str;
|
|
}
|
|
return str;
|
|
};
|
|
/*
|
|
* Return as toString, but do not accept a base argument, and include the minus sign for
|
|
* negative zero.
|
|
*/ P.valueOf = P.toJSON = function() {
|
|
return valueOf(this);
|
|
};
|
|
P._isBigNumber = true;
|
|
if (configObject != null) BigNumber.set(configObject);
|
|
return BigNumber;
|
|
}
|
|
// PRIVATE HELPER FUNCTIONS
|
|
// These functions don't need access to variables,
|
|
// e.g. DECIMAL_PLACES, in the scope of the `clone` function above.
|
|
function bitFloor(n) {
|
|
var i = n | 0;
|
|
return n > 0 || n === i ? i : i - 1;
|
|
}
|
|
// Return a coefficient array as a string of base 10 digits.
|
|
function coeffToString(a) {
|
|
var s, z, i = 1, j = a.length, r = a[0] + '';
|
|
for(; i < j;){
|
|
s = a[i++] + '';
|
|
z = LOG_BASE - s.length;
|
|
for(; z--; s = '0' + s);
|
|
r += s;
|
|
}
|
|
// Determine trailing zeros.
|
|
for(j = r.length; r.charCodeAt(--j) === 48;);
|
|
return r.slice(0, j + 1 || 1);
|
|
}
|
|
// Compare the value of BigNumbers x and y.
|
|
function compare(x, y) {
|
|
var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e;
|
|
// Either NaN?
|
|
if (!i || !j) return null;
|
|
a = xc && !xc[0];
|
|
b = yc && !yc[0];
|
|
// Either zero?
|
|
if (a || b) return a ? b ? 0 : -j : i;
|
|
// Signs differ?
|
|
if (i != j) return i;
|
|
a = i < 0;
|
|
b = k == l;
|
|
// Either Infinity?
|
|
if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;
|
|
// Compare exponents.
|
|
if (!b) return k > l ^ a ? 1 : -1;
|
|
j = (k = xc.length) < (l = yc.length) ? k : l;
|
|
// Compare digit by digit.
|
|
for(i = 0; i < j; i++)if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
|
|
// Compare lengths.
|
|
return k == l ? 0 : k > l ^ a ? 1 : -1;
|
|
}
|
|
/*
|
|
* Check that n is a primitive number, an integer, and in range, otherwise throw.
|
|
*/ function intCheck(n, min, max, name) {
|
|
if (n < min || n > max || n !== mathfloor(n)) {
|
|
throw Error(bignumberError + (name || 'Argument') + (typeof n == 'number' ? n < min || n > max ? ' out of range: ' : ' not an integer: ' : ' not a primitive number: ') + String(n));
|
|
}
|
|
}
|
|
// Assumes finite n.
|
|
function isOdd(n) {
|
|
var k = n.c.length - 1;
|
|
return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;
|
|
}
|
|
function toExponential(str, e) {
|
|
return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + (e < 0 ? 'e' : 'e+') + e;
|
|
}
|
|
function toFixedPoint(str, e, z) {
|
|
var len, zs;
|
|
// Negative exponent?
|
|
if (e < 0) {
|
|
// Prepend zeros.
|
|
for(zs = z + '.'; ++e; zs += z);
|
|
str = zs + str;
|
|
// Positive exponent
|
|
} else {
|
|
len = str.length;
|
|
// Append zeros.
|
|
if (++e > len) {
|
|
for(zs = z, e -= len; --e; zs += z);
|
|
str += zs;
|
|
} else if (e < len) {
|
|
str = str.slice(0, e) + '.' + str.slice(e);
|
|
}
|
|
}
|
|
return str;
|
|
}
|
|
// EXPORT
|
|
BigNumber = clone();
|
|
BigNumber['default'] = BigNumber.BigNumber = BigNumber;
|
|
// AMD.
|
|
if (typeof define == 'function' && define.amd) {
|
|
((r)=>r !== undefined && __turbopack_context__.v(r))(function() {
|
|
return BigNumber;
|
|
}(__turbopack_context__.r, exports, module));
|
|
// Node.js and other environments that support module.exports.
|
|
} else if (("TURBOPACK compile-time value", "object") != 'undefined' && module.exports) {
|
|
module.exports = BigNumber;
|
|
// Browser.
|
|
} else {
|
|
if (!globalObject) {
|
|
globalObject = typeof self != 'undefined' && self ? self : window;
|
|
}
|
|
globalObject.BigNumber = BigNumber;
|
|
}
|
|
})(/*TURBOPACK member replacement*/ __turbopack_context__.e);
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/json-bigint/lib/stringify.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
var BigNumber = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/bignumber.js/bignumber.js [app-route] (ecmascript)");
|
|
/*
|
|
json2.js
|
|
2013-05-26
|
|
|
|
Public Domain.
|
|
|
|
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
|
|
|
See http://www.JSON.org/js.html
|
|
|
|
|
|
This code should be minified before deployment.
|
|
See http://javascript.crockford.com/jsmin.html
|
|
|
|
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
|
|
NOT CONTROL.
|
|
|
|
|
|
This file creates a global JSON object containing two methods: stringify
|
|
and parse.
|
|
|
|
JSON.stringify(value, replacer, space)
|
|
value any JavaScript value, usually an object or array.
|
|
|
|
replacer an optional parameter that determines how object
|
|
values are stringified for objects. It can be a
|
|
function or an array of strings.
|
|
|
|
space an optional parameter that specifies the indentation
|
|
of nested structures. If it is omitted, the text will
|
|
be packed without extra whitespace. If it is a number,
|
|
it will specify the number of spaces to indent at each
|
|
level. If it is a string (such as '\t' or ' '),
|
|
it contains the characters used to indent at each level.
|
|
|
|
This method produces a JSON text from a JavaScript value.
|
|
|
|
When an object value is found, if the object contains a toJSON
|
|
method, its toJSON method will be called and the result will be
|
|
stringified. A toJSON method does not serialize: it returns the
|
|
value represented by the name/value pair that should be serialized,
|
|
or undefined if nothing should be serialized. The toJSON method
|
|
will be passed the key associated with the value, and this will be
|
|
bound to the value
|
|
|
|
For example, this would serialize Dates as ISO strings.
|
|
|
|
Date.prototype.toJSON = function (key) {
|
|
function f(n) {
|
|
// Format integers to have at least two digits.
|
|
return n < 10 ? '0' + n : n;
|
|
}
|
|
|
|
return this.getUTCFullYear() + '-' +
|
|
f(this.getUTCMonth() + 1) + '-' +
|
|
f(this.getUTCDate()) + 'T' +
|
|
f(this.getUTCHours()) + ':' +
|
|
f(this.getUTCMinutes()) + ':' +
|
|
f(this.getUTCSeconds()) + 'Z';
|
|
};
|
|
|
|
You can provide an optional replacer method. It will be passed the
|
|
key and value of each member, with this bound to the containing
|
|
object. The value that is returned from your method will be
|
|
serialized. If your method returns undefined, then the member will
|
|
be excluded from the serialization.
|
|
|
|
If the replacer parameter is an array of strings, then it will be
|
|
used to select the members to be serialized. It filters the results
|
|
such that only members with keys listed in the replacer array are
|
|
stringified.
|
|
|
|
Values that do not have JSON representations, such as undefined or
|
|
functions, will not be serialized. Such values in objects will be
|
|
dropped; in arrays they will be replaced with null. You can use
|
|
a replacer function to replace those with JSON values.
|
|
JSON.stringify(undefined) returns undefined.
|
|
|
|
The optional space parameter produces a stringification of the
|
|
value that is filled with line breaks and indentation to make it
|
|
easier to read.
|
|
|
|
If the space parameter is a non-empty string, then that string will
|
|
be used for indentation. If the space parameter is a number, then
|
|
the indentation will be that many spaces.
|
|
|
|
Example:
|
|
|
|
text = JSON.stringify(['e', {pluribus: 'unum'}]);
|
|
// text is '["e",{"pluribus":"unum"}]'
|
|
|
|
|
|
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
|
|
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
|
|
|
|
text = JSON.stringify([new Date()], function (key, value) {
|
|
return this[key] instanceof Date ?
|
|
'Date(' + this[key] + ')' : value;
|
|
});
|
|
// text is '["Date(---current time---)"]'
|
|
|
|
|
|
JSON.parse(text, reviver)
|
|
This method parses a JSON text to produce an object or array.
|
|
It can throw a SyntaxError exception.
|
|
|
|
The optional reviver parameter is a function that can filter and
|
|
transform the results. It receives each of the keys and values,
|
|
and its return value is used instead of the original value.
|
|
If it returns what it received, then the structure is not modified.
|
|
If it returns undefined then the member is deleted.
|
|
|
|
Example:
|
|
|
|
// Parse the text. Values that look like ISO date strings will
|
|
// be converted to Date objects.
|
|
|
|
myData = JSON.parse(text, function (key, value) {
|
|
var a;
|
|
if (typeof value === 'string') {
|
|
a =
|
|
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
|
|
if (a) {
|
|
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
|
|
+a[5], +a[6]));
|
|
}
|
|
}
|
|
return value;
|
|
});
|
|
|
|
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
|
|
var d;
|
|
if (typeof value === 'string' &&
|
|
value.slice(0, 5) === 'Date(' &&
|
|
value.slice(-1) === ')') {
|
|
d = new Date(value.slice(5, -1));
|
|
if (d) {
|
|
return d;
|
|
}
|
|
}
|
|
return value;
|
|
});
|
|
|
|
|
|
This is a reference implementation. You are free to copy, modify, or
|
|
redistribute.
|
|
*/ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
|
|
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
|
|
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
|
|
lastIndex, length, parse, prototype, push, replace, slice, stringify,
|
|
test, toJSON, toString, valueOf
|
|
*/ // Create a JSON object only if one does not already exist. We create the
|
|
// methods in a closure to avoid creating global variables.
|
|
var JSON = module.exports;
|
|
(function() {
|
|
'use strict';
|
|
function f(n) {
|
|
// Format integers to have at least two digits.
|
|
return n < 10 ? '0' + n : n;
|
|
}
|
|
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = {
|
|
'\b': '\\b',
|
|
'\t': '\\t',
|
|
'\n': '\\n',
|
|
'\f': '\\f',
|
|
'\r': '\\r',
|
|
'"': '\\"',
|
|
'\\': '\\\\'
|
|
}, rep;
|
|
function quote(string) {
|
|
// If the string contains no control characters, no quote characters, and no
|
|
// backslash characters, then we can safely slap some quotes around it.
|
|
// Otherwise we must also replace the offending characters with safe escape
|
|
// sequences.
|
|
escapable.lastIndex = 0;
|
|
return escapable.test(string) ? '"' + string.replace(escapable, function(a) {
|
|
var c = meta[a];
|
|
return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
|
}) + '"' : '"' + string + '"';
|
|
}
|
|
function str(key, holder) {
|
|
// Produce a string from holder[key].
|
|
var i, k, v, length, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));
|
|
// If the value has a toJSON method, call it to obtain a replacement value.
|
|
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
|
|
value = value.toJSON(key);
|
|
}
|
|
// If we were called with a replacer function, then call the replacer to
|
|
// obtain a replacement value.
|
|
if (typeof rep === 'function') {
|
|
value = rep.call(holder, key, value);
|
|
}
|
|
// What happens next depends on the value's type.
|
|
switch(typeof value){
|
|
case 'string':
|
|
if (isBigNumber) {
|
|
return value;
|
|
} else {
|
|
return quote(value);
|
|
}
|
|
case 'number':
|
|
// JSON numbers must be finite. Encode non-finite numbers as null.
|
|
return isFinite(value) ? String(value) : 'null';
|
|
case 'boolean':
|
|
case 'null':
|
|
case 'bigint':
|
|
// If the value is a boolean or null, convert it to a string. Note:
|
|
// typeof null does not produce 'null'. The case is included here in
|
|
// the remote chance that this gets fixed someday.
|
|
return String(value);
|
|
// If the type is 'object', we might be dealing with an object or an array or
|
|
// null.
|
|
case 'object':
|
|
// Due to a specification blunder in ECMAScript, typeof null is 'object',
|
|
// so watch out for that case.
|
|
if (!value) {
|
|
return 'null';
|
|
}
|
|
// Make an array to hold the partial results of stringifying this object value.
|
|
gap += indent;
|
|
partial = [];
|
|
// Is the value an array?
|
|
if (Object.prototype.toString.apply(value) === '[object Array]') {
|
|
// The value is an array. Stringify every element. Use null as a placeholder
|
|
// for non-JSON values.
|
|
length = value.length;
|
|
for(i = 0; i < length; i += 1){
|
|
partial[i] = str(i, value) || 'null';
|
|
}
|
|
// Join all of the elements together, separated with commas, and wrap them in
|
|
// brackets.
|
|
v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
|
|
gap = mind;
|
|
return v;
|
|
}
|
|
// If the replacer is an array, use it to select the members to be stringified.
|
|
if (rep && typeof rep === 'object') {
|
|
length = rep.length;
|
|
for(i = 0; i < length; i += 1){
|
|
if (typeof rep[i] === 'string') {
|
|
k = rep[i];
|
|
v = str(k, value);
|
|
if (v) {
|
|
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
// Otherwise, iterate through all of the keys in the object.
|
|
Object.keys(value).forEach(function(k) {
|
|
var v = str(k, value);
|
|
if (v) {
|
|
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
|
}
|
|
});
|
|
}
|
|
// Join all of the member texts together, separated with commas,
|
|
// and wrap them in braces.
|
|
v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
|
|
gap = mind;
|
|
return v;
|
|
}
|
|
}
|
|
// If the JSON object does not yet have a stringify method, give it one.
|
|
if (typeof JSON.stringify !== 'function') {
|
|
JSON.stringify = function(value, replacer, space) {
|
|
// The stringify method takes a value and an optional replacer, and an optional
|
|
// space parameter, and returns a JSON text. The replacer can be a function
|
|
// that can replace values, or an array of strings that will select the keys.
|
|
// A default replacer method can be provided. Use of the space parameter can
|
|
// produce text that is more easily readable.
|
|
var i;
|
|
gap = '';
|
|
indent = '';
|
|
// If the space parameter is a number, make an indent string containing that
|
|
// many spaces.
|
|
if (typeof space === 'number') {
|
|
for(i = 0; i < space; i += 1){
|
|
indent += ' ';
|
|
}
|
|
// If the space parameter is a string, it will be used as the indent string.
|
|
} else if (typeof space === 'string') {
|
|
indent = space;
|
|
}
|
|
// If there is a replacer, it must be a function or an array.
|
|
// Otherwise, throw an error.
|
|
rep = replacer;
|
|
if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
|
|
throw new Error('JSON.stringify');
|
|
}
|
|
// Make a fake root object containing our value under the key of ''.
|
|
// Return the result of stringifying the value.
|
|
return str('', {
|
|
'': value
|
|
});
|
|
};
|
|
}
|
|
})();
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/json-bigint/lib/parse.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
var BigNumber = null;
|
|
// regexpxs extracted from
|
|
// (c) BSD-3-Clause
|
|
// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors
|
|
const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;
|
|
const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;
|
|
/*
|
|
json_parse.js
|
|
2012-06-20
|
|
|
|
Public Domain.
|
|
|
|
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
|
|
|
This file creates a json_parse function.
|
|
During create you can (optionally) specify some behavioural switches
|
|
|
|
require('json-bigint')(options)
|
|
|
|
The optional options parameter holds switches that drive certain
|
|
aspects of the parsing process:
|
|
* options.strict = true will warn about duplicate-key usage in the json.
|
|
The default (strict = false) will silently ignore those and overwrite
|
|
values for keys that are in duplicate use.
|
|
|
|
The resulting function follows this signature:
|
|
json_parse(text, reviver)
|
|
This method parses a JSON text to produce an object or array.
|
|
It can throw a SyntaxError exception.
|
|
|
|
The optional reviver parameter is a function that can filter and
|
|
transform the results. It receives each of the keys and values,
|
|
and its return value is used instead of the original value.
|
|
If it returns what it received, then the structure is not modified.
|
|
If it returns undefined then the member is deleted.
|
|
|
|
Example:
|
|
|
|
// Parse the text. Values that look like ISO date strings will
|
|
// be converted to Date objects.
|
|
|
|
myData = json_parse(text, function (key, value) {
|
|
var a;
|
|
if (typeof value === 'string') {
|
|
a =
|
|
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
|
|
if (a) {
|
|
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
|
|
+a[5], +a[6]));
|
|
}
|
|
}
|
|
return value;
|
|
});
|
|
|
|
This is a reference implementation. You are free to copy, modify, or
|
|
redistribute.
|
|
|
|
This code should be minified before deployment.
|
|
See http://javascript.crockford.com/jsmin.html
|
|
|
|
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
|
|
NOT CONTROL.
|
|
*/ /*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,
|
|
hasOwnProperty, message, n, name, prototype, push, r, t, text
|
|
*/ var json_parse = function(options) {
|
|
'use strict';
|
|
// This is a function that can parse a JSON text, producing a JavaScript
|
|
// data structure. It is a simple, recursive descent parser. It does not use
|
|
// eval or regular expressions, so it can be used as a model for implementing
|
|
// a JSON parser in other languages.
|
|
// We are defining the function inside of another function to avoid creating
|
|
// global variables.
|
|
// Default options one can override by passing options to the parse()
|
|
var _options = {
|
|
strict: false,
|
|
storeAsString: false,
|
|
alwaysParseAsBig: false,
|
|
useNativeBigInt: false,
|
|
protoAction: 'error',
|
|
constructorAction: 'error'
|
|
};
|
|
// If there are options, then use them to override the default _options
|
|
if (options !== undefined && options !== null) {
|
|
if (options.strict === true) {
|
|
_options.strict = true;
|
|
}
|
|
if (options.storeAsString === true) {
|
|
_options.storeAsString = true;
|
|
}
|
|
_options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;
|
|
_options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false;
|
|
if (typeof options.constructorAction !== 'undefined') {
|
|
if (options.constructorAction === 'error' || options.constructorAction === 'ignore' || options.constructorAction === 'preserve') {
|
|
_options.constructorAction = options.constructorAction;
|
|
} else {
|
|
throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`);
|
|
}
|
|
}
|
|
if (typeof options.protoAction !== 'undefined') {
|
|
if (options.protoAction === 'error' || options.protoAction === 'ignore' || options.protoAction === 'preserve') {
|
|
_options.protoAction = options.protoAction;
|
|
} else {
|
|
throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`);
|
|
}
|
|
}
|
|
}
|
|
var at, ch, escapee = {
|
|
'"': '"',
|
|
'\\': '\\',
|
|
'/': '/',
|
|
b: '\b',
|
|
f: '\f',
|
|
n: '\n',
|
|
r: '\r',
|
|
t: '\t'
|
|
}, text, error = function(m) {
|
|
// Call error when something is wrong.
|
|
throw {
|
|
name: 'SyntaxError',
|
|
message: m,
|
|
at: at,
|
|
text: text
|
|
};
|
|
}, next = function(c) {
|
|
// If a c parameter is provided, verify that it matches the current character.
|
|
if (c && c !== ch) {
|
|
error("Expected '" + c + "' instead of '" + ch + "'");
|
|
}
|
|
// Get the next character. When there are no more characters,
|
|
// return the empty string.
|
|
ch = text.charAt(at);
|
|
at += 1;
|
|
return ch;
|
|
}, number = function() {
|
|
// Parse a number value.
|
|
var number, string = '';
|
|
if (ch === '-') {
|
|
string = '-';
|
|
next('-');
|
|
}
|
|
while(ch >= '0' && ch <= '9'){
|
|
string += ch;
|
|
next();
|
|
}
|
|
if (ch === '.') {
|
|
string += '.';
|
|
while(next() && ch >= '0' && ch <= '9'){
|
|
string += ch;
|
|
}
|
|
}
|
|
if (ch === 'e' || ch === 'E') {
|
|
string += ch;
|
|
next();
|
|
if (ch === '-' || ch === '+') {
|
|
string += ch;
|
|
next();
|
|
}
|
|
while(ch >= '0' && ch <= '9'){
|
|
string += ch;
|
|
next();
|
|
}
|
|
}
|
|
number = +string;
|
|
if (!isFinite(number)) {
|
|
error('Bad number');
|
|
} else {
|
|
if (BigNumber == null) BigNumber = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/bignumber.js/bignumber.js [app-route] (ecmascript)");
|
|
//if (number > 9007199254740992 || number < -9007199254740992)
|
|
// Bignumber has stricter check: everything with length > 15 digits disallowed
|
|
if (string.length > 15) return _options.storeAsString ? string : _options.useNativeBigInt ? BigInt(string) : new BigNumber(string);
|
|
else return !_options.alwaysParseAsBig ? number : _options.useNativeBigInt ? BigInt(number) : new BigNumber(number);
|
|
}
|
|
}, string = function() {
|
|
// Parse a string value.
|
|
var hex, i, string = '', uffff;
|
|
// When parsing for string values, we must look for " and \ characters.
|
|
if (ch === '"') {
|
|
var startAt = at;
|
|
while(next()){
|
|
if (ch === '"') {
|
|
if (at - 1 > startAt) string += text.substring(startAt, at - 1);
|
|
next();
|
|
return string;
|
|
}
|
|
if (ch === '\\') {
|
|
if (at - 1 > startAt) string += text.substring(startAt, at - 1);
|
|
next();
|
|
if (ch === 'u') {
|
|
uffff = 0;
|
|
for(i = 0; i < 4; i += 1){
|
|
hex = parseInt(next(), 16);
|
|
if (!isFinite(hex)) {
|
|
break;
|
|
}
|
|
uffff = uffff * 16 + hex;
|
|
}
|
|
string += String.fromCharCode(uffff);
|
|
} else if (typeof escapee[ch] === 'string') {
|
|
string += escapee[ch];
|
|
} else {
|
|
break;
|
|
}
|
|
startAt = at;
|
|
}
|
|
}
|
|
}
|
|
error('Bad string');
|
|
}, white = function() {
|
|
// Skip whitespace.
|
|
while(ch && ch <= ' '){
|
|
next();
|
|
}
|
|
}, word = function() {
|
|
// true, false, or null.
|
|
switch(ch){
|
|
case 't':
|
|
next('t');
|
|
next('r');
|
|
next('u');
|
|
next('e');
|
|
return true;
|
|
case 'f':
|
|
next('f');
|
|
next('a');
|
|
next('l');
|
|
next('s');
|
|
next('e');
|
|
return false;
|
|
case 'n':
|
|
next('n');
|
|
next('u');
|
|
next('l');
|
|
next('l');
|
|
return null;
|
|
}
|
|
error("Unexpected '" + ch + "'");
|
|
}, value, array = function() {
|
|
// Parse an array value.
|
|
var array = [];
|
|
if (ch === '[') {
|
|
next('[');
|
|
white();
|
|
if (ch === ']') {
|
|
next(']');
|
|
return array; // empty array
|
|
}
|
|
while(ch){
|
|
array.push(value());
|
|
white();
|
|
if (ch === ']') {
|
|
next(']');
|
|
return array;
|
|
}
|
|
next(',');
|
|
white();
|
|
}
|
|
}
|
|
error('Bad array');
|
|
}, object = function() {
|
|
// Parse an object value.
|
|
var key, object = Object.create(null);
|
|
if (ch === '{') {
|
|
next('{');
|
|
white();
|
|
if (ch === '}') {
|
|
next('}');
|
|
return object; // empty object
|
|
}
|
|
while(ch){
|
|
key = string();
|
|
white();
|
|
next(':');
|
|
if (_options.strict === true && Object.hasOwnProperty.call(object, key)) {
|
|
error('Duplicate key "' + key + '"');
|
|
}
|
|
if (suspectProtoRx.test(key) === true) {
|
|
if (_options.protoAction === 'error') {
|
|
error('Object contains forbidden prototype property');
|
|
} else if (_options.protoAction === 'ignore') {
|
|
value();
|
|
} else {
|
|
object[key] = value();
|
|
}
|
|
} else if (suspectConstructorRx.test(key) === true) {
|
|
if (_options.constructorAction === 'error') {
|
|
error('Object contains forbidden constructor property');
|
|
} else if (_options.constructorAction === 'ignore') {
|
|
value();
|
|
} else {
|
|
object[key] = value();
|
|
}
|
|
} else {
|
|
object[key] = value();
|
|
}
|
|
white();
|
|
if (ch === '}') {
|
|
next('}');
|
|
return object;
|
|
}
|
|
next(',');
|
|
white();
|
|
}
|
|
}
|
|
error('Bad object');
|
|
};
|
|
value = function() {
|
|
// Parse a JSON value. It could be an object, an array, a string, a number,
|
|
// or a word.
|
|
white();
|
|
switch(ch){
|
|
case '{':
|
|
return object();
|
|
case '[':
|
|
return array();
|
|
case '"':
|
|
return string();
|
|
case '-':
|
|
return number();
|
|
default:
|
|
return ch >= '0' && ch <= '9' ? number() : word();
|
|
}
|
|
};
|
|
// Return the json_parse function. It will have access to all of the above
|
|
// functions and variables.
|
|
return function(source, reviver) {
|
|
var result;
|
|
text = source + '';
|
|
at = 0;
|
|
ch = ' ';
|
|
result = value();
|
|
white();
|
|
if (ch) {
|
|
error('Syntax error');
|
|
}
|
|
// If there is a reviver function, we recursively walk the new structure,
|
|
// passing each name/value pair to the reviver function for possible
|
|
// transformation, starting with a temporary root object that holds the result
|
|
// in an empty key. If there is not a reviver function, we simply return the
|
|
// result.
|
|
return typeof reviver === 'function' ? function walk(holder, key) {
|
|
var k, v, value = holder[key];
|
|
if (value && typeof value === 'object') {
|
|
Object.keys(value).forEach(function(k) {
|
|
v = walk(value, k);
|
|
if (v !== undefined) {
|
|
value[k] = v;
|
|
} else {
|
|
delete value[k];
|
|
}
|
|
});
|
|
}
|
|
return reviver.call(holder, key, value);
|
|
}({
|
|
'': result
|
|
}, '') : result;
|
|
};
|
|
};
|
|
module.exports = json_parse;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/json-bigint/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
var json_stringify = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/json-bigint/lib/stringify.js [app-route] (ecmascript)").stringify;
|
|
var json_parse = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/json-bigint/lib/parse.js [app-route] (ecmascript)");
|
|
module.exports = function(options) {
|
|
return {
|
|
parse: json_parse(options),
|
|
stringify: json_stringify
|
|
};
|
|
};
|
|
//create the default method members with no options applied for backwards compatibility
|
|
module.exports.parse = json_parse();
|
|
module.exports.stringify = json_stringify;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/google-logging-utils/build/src/colours.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2024 Google LLC
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// https://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.Colours = void 0;
|
|
/**
|
|
* Handles figuring out if we can use ANSI colours and handing out the escape codes.
|
|
*
|
|
* This is for package-internal use only, and may change at any time.
|
|
*
|
|
* @private
|
|
* @internal
|
|
*/ class Colours {
|
|
/**
|
|
* @param stream The stream (e.g. process.stderr)
|
|
* @returns true if the stream should have colourization enabled
|
|
*/ static isEnabled(stream) {
|
|
return stream && // May happen in browsers.
|
|
stream.isTTY && (typeof stream.getColorDepth === 'function' ? stream.getColorDepth() > 2 : true);
|
|
}
|
|
static refresh() {
|
|
Colours.enabled = Colours.isEnabled(process === null || process === void 0 ? void 0 : process.stderr);
|
|
if (!this.enabled) {
|
|
Colours.reset = '';
|
|
Colours.bright = '';
|
|
Colours.dim = '';
|
|
Colours.red = '';
|
|
Colours.green = '';
|
|
Colours.yellow = '';
|
|
Colours.blue = '';
|
|
Colours.magenta = '';
|
|
Colours.cyan = '';
|
|
Colours.white = '';
|
|
Colours.grey = '';
|
|
} else {
|
|
Colours.reset = '\u001b[0m';
|
|
Colours.bright = '\u001b[1m';
|
|
Colours.dim = '\u001b[2m';
|
|
Colours.red = '\u001b[31m';
|
|
Colours.green = '\u001b[32m';
|
|
Colours.yellow = '\u001b[33m';
|
|
Colours.blue = '\u001b[34m';
|
|
Colours.magenta = '\u001b[35m';
|
|
Colours.cyan = '\u001b[36m';
|
|
Colours.white = '\u001b[37m';
|
|
Colours.grey = '\u001b[90m';
|
|
}
|
|
}
|
|
}
|
|
exports.Colours = Colours;
|
|
Colours.enabled = false;
|
|
Colours.reset = '';
|
|
Colours.bright = '';
|
|
Colours.dim = '';
|
|
Colours.red = '';
|
|
Colours.green = '';
|
|
Colours.yellow = '';
|
|
Colours.blue = '';
|
|
Colours.magenta = '';
|
|
Colours.cyan = '';
|
|
Colours.white = '';
|
|
Colours.grey = '';
|
|
Colours.refresh(); //# sourceMappingURL=colours.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/google-logging-utils/build/src/logging-utils.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2021-2024 Google LLC
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// https://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
var __createBinding = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = {
|
|
enumerable: true,
|
|
get: function() {
|
|
return m[k];
|
|
}
|
|
};
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", {
|
|
enumerable: true,
|
|
value: v
|
|
});
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o) {
|
|
var ar = [];
|
|
for(var k in o)if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for(var k = ownKeys(mod), i = 0; i < k.length; i++)if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0;
|
|
exports.getNodeBackend = getNodeBackend;
|
|
exports.getDebugBackend = getDebugBackend;
|
|
exports.getStructuredBackend = getStructuredBackend;
|
|
exports.setBackend = setBackend;
|
|
exports.log = log;
|
|
const events_1 = __turbopack_context__.r("[externals]/events [external] (events, cjs)");
|
|
const process = __importStar(__turbopack_context__.r("[externals]/process [external] (process, cjs)"));
|
|
const util = __importStar(__turbopack_context__.r("[externals]/util [external] (util, cjs)"));
|
|
const colours_1 = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/google-logging-utils/build/src/colours.js [app-route] (ecmascript)");
|
|
// Some functions (as noted) are based on the Node standard library, from
|
|
// the following file:
|
|
//
|
|
// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js
|
|
/**
|
|
* This module defines an ad-hoc debug logger for Google Cloud Platform
|
|
* client libraries in Node. An ad-hoc debug logger is a tool which lets
|
|
* users use an external, unified interface (in this case, environment
|
|
* variables) to determine what logging they want to see at runtime. This
|
|
* isn't necessarily fed into the console, but is meant to be under the
|
|
* control of the user. The kind of logging that will be produced by this
|
|
* is more like "call retry happened", not "events you'd want to record
|
|
* in Cloud Logger".
|
|
*
|
|
* More for Googlers implementing libraries with it:
|
|
* go/cloud-client-logging-design
|
|
*/ /**
|
|
* Possible log levels. These are a subset of Cloud Observability levels.
|
|
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
|
|
*/ var LogSeverity;
|
|
(function(LogSeverity) {
|
|
LogSeverity["DEFAULT"] = "DEFAULT";
|
|
LogSeverity["DEBUG"] = "DEBUG";
|
|
LogSeverity["INFO"] = "INFO";
|
|
LogSeverity["WARNING"] = "WARNING";
|
|
LogSeverity["ERROR"] = "ERROR";
|
|
})(LogSeverity || (exports.LogSeverity = LogSeverity = {}));
|
|
/**
|
|
* Our logger instance. This actually contains the meat of dealing
|
|
* with log lines, including EventEmitter. This contains the function
|
|
* that will be passed back to users of the package.
|
|
*/ class AdhocDebugLogger extends events_1.EventEmitter {
|
|
/**
|
|
* @param upstream The backend will pass a function that will be
|
|
* called whenever our logger function is invoked.
|
|
*/ constructor(namespace, upstream){
|
|
super();
|
|
this.namespace = namespace;
|
|
this.upstream = upstream;
|
|
this.func = Object.assign(this.invoke.bind(this), {
|
|
// Also add an instance pointer back to us.
|
|
instance: this,
|
|
// And pull over the EventEmitter functionality.
|
|
on: (event, listener)=>this.on(event, listener)
|
|
});
|
|
// Convenience methods for log levels.
|
|
this.func.debug = (...args)=>this.invokeSeverity(LogSeverity.DEBUG, ...args);
|
|
this.func.info = (...args)=>this.invokeSeverity(LogSeverity.INFO, ...args);
|
|
this.func.warn = (...args)=>this.invokeSeverity(LogSeverity.WARNING, ...args);
|
|
this.func.error = (...args)=>this.invokeSeverity(LogSeverity.ERROR, ...args);
|
|
this.func.sublog = (namespace)=>log(namespace, this.func);
|
|
}
|
|
invoke(fields, ...args) {
|
|
// Push out any upstream logger first.
|
|
if (this.upstream) {
|
|
try {
|
|
this.upstream(fields, ...args);
|
|
} catch (e) {
|
|
// Swallow exceptions to avoid interfering with other logging.
|
|
}
|
|
}
|
|
// Emit sink events.
|
|
try {
|
|
this.emit('log', fields, args);
|
|
} catch (e) {
|
|
// Swallow exceptions to avoid interfering with other logging.
|
|
}
|
|
}
|
|
invokeSeverity(severity, ...args) {
|
|
this.invoke({
|
|
severity
|
|
}, ...args);
|
|
}
|
|
}
|
|
exports.AdhocDebugLogger = AdhocDebugLogger;
|
|
/**
|
|
* This can be used in place of a real logger while waiting for Promises or disabling logging.
|
|
*/ exports.placeholder = new AdhocDebugLogger('', ()=>{}).func;
|
|
/**
|
|
* The base class for debug logging backends. It's possible to use this, but the
|
|
* same non-guarantees above still apply (unstable interface, etc).
|
|
*
|
|
* @private
|
|
* @internal
|
|
*/ class DebugLogBackendBase {
|
|
constructor(){
|
|
var _a;
|
|
this.cached = new Map();
|
|
this.filters = [];
|
|
this.filtersSet = false;
|
|
// Look for the Node config variable for what systems to enable. We'll store
|
|
// these for the log method below, which will call setFilters() once.
|
|
let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*';
|
|
if (nodeFlag === 'all') {
|
|
nodeFlag = '*';
|
|
}
|
|
this.filters = nodeFlag.split(',');
|
|
}
|
|
log(namespace, fields, ...args) {
|
|
try {
|
|
if (!this.filtersSet) {
|
|
this.setFilters();
|
|
this.filtersSet = true;
|
|
}
|
|
let logger = this.cached.get(namespace);
|
|
if (!logger) {
|
|
logger = this.makeLogger(namespace);
|
|
this.cached.set(namespace, logger);
|
|
}
|
|
logger(fields, ...args);
|
|
} catch (e) {
|
|
// Silently ignore all errors; we don't want them to interfere with
|
|
// the user's running app.
|
|
// e;
|
|
console.error(e);
|
|
}
|
|
}
|
|
}
|
|
exports.DebugLogBackendBase = DebugLogBackendBase;
|
|
// The basic backend. This one definitely works, but it's less feature-filled.
|
|
//
|
|
// Rather than using util.debuglog, this implements the same basic logic directly.
|
|
// The reason for this decision is that debuglog checks the value of the
|
|
// NODE_DEBUG environment variable before any user code runs; we therefore
|
|
// can't pipe our own enables into it (and util.debuglog will never print unless
|
|
// the user duplicates it into NODE_DEBUG, which isn't reasonable).
|
|
//
|
|
class NodeBackend extends DebugLogBackendBase {
|
|
constructor(){
|
|
super(...arguments);
|
|
// Default to allowing all systems, since we gate earlier based on whether the
|
|
// variable is empty.
|
|
this.enabledRegexp = /.*/g;
|
|
}
|
|
isEnabled(namespace) {
|
|
return this.enabledRegexp.test(namespace);
|
|
}
|
|
makeLogger(namespace) {
|
|
if (!this.enabledRegexp.test(namespace)) {
|
|
return ()=>{};
|
|
}
|
|
return (fields, ...args)=>{
|
|
var _a;
|
|
// TODO: `fields` needs to be turned into a string here, one way or another.
|
|
const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
|
|
const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`;
|
|
let level;
|
|
switch(fields.severity){
|
|
case LogSeverity.ERROR:
|
|
level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`;
|
|
break;
|
|
case LogSeverity.INFO:
|
|
level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`;
|
|
break;
|
|
case LogSeverity.WARNING:
|
|
level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`;
|
|
break;
|
|
default:
|
|
level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT;
|
|
break;
|
|
}
|
|
const msg = util.formatWithOptions({
|
|
colors: colours_1.Colours.enabled
|
|
}, ...args);
|
|
const filteredFields = Object.assign({}, fields);
|
|
delete filteredFields.severity;
|
|
const fieldsJson = Object.getOwnPropertyNames(filteredFields).length ? JSON.stringify(filteredFields) : '';
|
|
const fieldsColour = fieldsJson ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` : '';
|
|
console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : '');
|
|
};
|
|
}
|
|
// Regexp patterns below are from here:
|
|
// https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36
|
|
setFilters() {
|
|
const totalFilters = this.filters.join(',');
|
|
const regexp = totalFilters.replace(/[|\\{}()[\]^$+?.]/g, '\\$&').replace(/\*/g, '.*').replace(/,/g, '$|^');
|
|
this.enabledRegexp = new RegExp(`^${regexp}$`, 'i');
|
|
}
|
|
}
|
|
/**
|
|
* @returns A backend based on Node util.debuglog; this is the default.
|
|
*/ function getNodeBackend() {
|
|
return new NodeBackend();
|
|
}
|
|
class DebugBackend extends DebugLogBackendBase {
|
|
constructor(pkg){
|
|
super();
|
|
this.debugPkg = pkg;
|
|
}
|
|
makeLogger(namespace) {
|
|
const debugLogger = this.debugPkg(namespace);
|
|
return (fields, ...args)=>{
|
|
// TODO: `fields` needs to be turned into a string here.
|
|
debugLogger(args[0], ...args.slice(1));
|
|
};
|
|
}
|
|
setFilters() {
|
|
var _a;
|
|
const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : '';
|
|
process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`;
|
|
}
|
|
}
|
|
/**
|
|
* Creates a "debug" package backend. The user must call require('debug') and pass
|
|
* the resulting object to this function.
|
|
*
|
|
* ```
|
|
* setBackend(getDebugBackend(require('debug')))
|
|
* ```
|
|
*
|
|
* https://www.npmjs.com/package/debug
|
|
*
|
|
* Note: Google does not explicitly endorse or recommend this package; it's just
|
|
* being provided as an option.
|
|
*
|
|
* @returns A backend based on the npm "debug" package.
|
|
*/ function getDebugBackend(debugPkg) {
|
|
return new DebugBackend(debugPkg);
|
|
}
|
|
/**
|
|
* This pretty much works like the Node logger, but it outputs structured
|
|
* logging JSON matching Google Cloud's ingestion specs. Rather than handling
|
|
* its own output, it wraps another backend. The passed backend must be a subclass
|
|
* of `DebugLogBackendBase` (any of the backends exposed by this package will work).
|
|
*/ class StructuredBackend extends DebugLogBackendBase {
|
|
constructor(upstream){
|
|
var _a;
|
|
super();
|
|
this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : undefined;
|
|
}
|
|
makeLogger(namespace) {
|
|
var _a;
|
|
const debugLogger = (_a = this.upstream) === null || _a === void 0 ? void 0 : _a.makeLogger(namespace);
|
|
return (fields, ...args)=>{
|
|
var _a;
|
|
const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO;
|
|
const json = Object.assign({
|
|
severity,
|
|
message: util.format(...args)
|
|
}, fields);
|
|
const jsonString = JSON.stringify(json);
|
|
if (debugLogger) {
|
|
debugLogger(fields, jsonString);
|
|
} else {
|
|
console.log('%s', jsonString);
|
|
}
|
|
};
|
|
}
|
|
setFilters() {
|
|
var _a;
|
|
(_a = this.upstream) === null || _a === void 0 ? void 0 : _a.setFilters();
|
|
}
|
|
}
|
|
/**
|
|
* Creates a "structured logging" backend. This pretty much works like the
|
|
* Node logger, but it outputs structured logging JSON matching Google
|
|
* Cloud's ingestion specs instead of plain text.
|
|
*
|
|
* ```
|
|
* setBackend(getStructuredBackend())
|
|
* ```
|
|
*
|
|
* @param upstream If you want to use something besides the Node backend to
|
|
* write the actual log lines into, pass that here.
|
|
* @returns A backend based on Google Cloud structured logging.
|
|
*/ function getStructuredBackend(upstream) {
|
|
return new StructuredBackend(upstream);
|
|
}
|
|
/**
|
|
* The environment variables that we standardized on, for all ad-hoc logging.
|
|
*/ exports.env = {
|
|
/**
|
|
* Filter wildcards specific to the Node syntax, and similar to the built-in
|
|
* utils.debuglog() environment variable. If missing, disables logging.
|
|
*/ nodeEnables: 'GOOGLE_SDK_NODE_LOGGING'
|
|
};
|
|
// Keep a copy of all namespaced loggers so users can reliably .on() them.
|
|
// Note that these cached functions will need to deal with changes in the backend.
|
|
const loggerCache = new Map();
|
|
// Our current global backend. This might be:
|
|
let cachedBackend = undefined;
|
|
/**
|
|
* Set the backend to use for our log output.
|
|
* - A backend object
|
|
* - null to disable logging
|
|
* - undefined for "nothing yet", defaults to the Node backend
|
|
*
|
|
* @param backend Results from one of the get*Backend() functions.
|
|
*/ function setBackend(backend) {
|
|
cachedBackend = backend;
|
|
loggerCache.clear();
|
|
}
|
|
/**
|
|
* Creates a logging function. Multiple calls to this with the same namespace
|
|
* will produce the same logger, with the same event emitter hooks.
|
|
*
|
|
* Namespaces can be a simple string ("system" name), or a qualified string
|
|
* (system:subsystem), which can be used for filtering, or for "system:*".
|
|
*
|
|
* @param namespace The namespace, a descriptive text string.
|
|
* @returns A function you can call that works similar to console.log().
|
|
*/ function log(namespace, parent) {
|
|
// If the enable environment variable isn't set, do nothing. The user
|
|
// can still choose to set a backend of their choice using the manual
|
|
// `setBackend()`.
|
|
if (!cachedBackend) {
|
|
const enablesFlag = process.env[exports.env.nodeEnables];
|
|
if (!enablesFlag) {
|
|
return exports.placeholder;
|
|
}
|
|
}
|
|
// This might happen mostly if the typings are dropped in a user's code,
|
|
// or if they're calling from JavaScript.
|
|
if (!namespace) {
|
|
return exports.placeholder;
|
|
}
|
|
// Handle sub-loggers.
|
|
if (parent) {
|
|
namespace = `${parent.instance.namespace}:${namespace}`;
|
|
}
|
|
// Reuse loggers so things like event sinks are persistent.
|
|
const existing = loggerCache.get(namespace);
|
|
if (existing) {
|
|
return existing.func;
|
|
}
|
|
// Do we have a backend yet?
|
|
if (cachedBackend === null) {
|
|
// Explicitly disabled.
|
|
return exports.placeholder;
|
|
} else if (cachedBackend === undefined) {
|
|
// One hasn't been made yet, so default to Node.
|
|
cachedBackend = getNodeBackend();
|
|
}
|
|
// The logger is further wrapped so we can handle the backend changing out.
|
|
const logger = (()=>{
|
|
let previousBackend = undefined;
|
|
const newLogger = new AdhocDebugLogger(namespace, (fields, ...args)=>{
|
|
if (previousBackend !== cachedBackend) {
|
|
// Did the user pass a custom backend?
|
|
if (cachedBackend === null) {
|
|
// Explicitly disabled.
|
|
return;
|
|
} else if (cachedBackend === undefined) {
|
|
// One hasn't been made yet, so default to Node.
|
|
cachedBackend = getNodeBackend();
|
|
}
|
|
previousBackend = cachedBackend;
|
|
}
|
|
cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args);
|
|
});
|
|
return newLogger;
|
|
})();
|
|
loggerCache.set(namespace, logger);
|
|
return logger.func;
|
|
} //# sourceMappingURL=logging-utils.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/google-logging-utils/build/src/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
// Copyright 2024 Google LLC
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// https://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
var __createBinding = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = {
|
|
enumerable: true,
|
|
get: function() {
|
|
return m[k];
|
|
}
|
|
};
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = /*TURBOPACK member replacement*/ __turbopack_context__.e && /*TURBOPACK member replacement*/ __turbopack_context__.e.__exportStar || function(m, exports1) {
|
|
for(var p in m)if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports1, p)) __createBinding(exports1, m, p);
|
|
};
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
__exportStar(__turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/google-logging-utils/build/src/logging-utils.js [app-route] (ecmascript)"), exports); //# sourceMappingURL=index.js.map
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/base64-js/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
exports.byteLength = byteLength;
|
|
exports.toByteArray = toByteArray;
|
|
exports.fromByteArray = fromByteArray;
|
|
var lookup = [];
|
|
var revLookup = [];
|
|
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
|
|
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
for(var i = 0, len = code.length; i < len; ++i){
|
|
lookup[i] = code[i];
|
|
revLookup[code.charCodeAt(i)] = i;
|
|
}
|
|
// Support decoding URL-safe base64 strings, as Node.js does.
|
|
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
|
|
revLookup['-'.charCodeAt(0)] = 62;
|
|
revLookup['_'.charCodeAt(0)] = 63;
|
|
function getLens(b64) {
|
|
var len = b64.length;
|
|
if (len % 4 > 0) {
|
|
throw new Error('Invalid string. Length must be a multiple of 4');
|
|
}
|
|
// Trim off extra bytes after placeholder bytes are found
|
|
// See: https://github.com/beatgammit/base64-js/issues/42
|
|
var validLen = b64.indexOf('=');
|
|
if (validLen === -1) validLen = len;
|
|
var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
|
|
return [
|
|
validLen,
|
|
placeHoldersLen
|
|
];
|
|
}
|
|
// base64 is 4/3 + up to two characters of the original data
|
|
function byteLength(b64) {
|
|
var lens = getLens(b64);
|
|
var validLen = lens[0];
|
|
var placeHoldersLen = lens[1];
|
|
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
|
|
}
|
|
function _byteLength(b64, validLen, placeHoldersLen) {
|
|
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
|
|
}
|
|
function toByteArray(b64) {
|
|
var tmp;
|
|
var lens = getLens(b64);
|
|
var validLen = lens[0];
|
|
var placeHoldersLen = lens[1];
|
|
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
|
|
var curByte = 0;
|
|
// if there are placeholders, only get up to the last complete 4 chars
|
|
var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
|
|
var i;
|
|
for(i = 0; i < len; i += 4){
|
|
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
|
|
arr[curByte++] = tmp >> 16 & 0xFF;
|
|
arr[curByte++] = tmp >> 8 & 0xFF;
|
|
arr[curByte++] = tmp & 0xFF;
|
|
}
|
|
if (placeHoldersLen === 2) {
|
|
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
|
|
arr[curByte++] = tmp & 0xFF;
|
|
}
|
|
if (placeHoldersLen === 1) {
|
|
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
|
|
arr[curByte++] = tmp >> 8 & 0xFF;
|
|
arr[curByte++] = tmp & 0xFF;
|
|
}
|
|
return arr;
|
|
}
|
|
function tripletToBase64(num) {
|
|
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
|
|
}
|
|
function encodeChunk(uint8, start, end) {
|
|
var tmp;
|
|
var output = [];
|
|
for(var i = start; i < end; i += 3){
|
|
tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);
|
|
output.push(tripletToBase64(tmp));
|
|
}
|
|
return output.join('');
|
|
}
|
|
function fromByteArray(uint8) {
|
|
var tmp;
|
|
var len = uint8.length;
|
|
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
|
|
;
|
|
var parts = [];
|
|
var maxChunkLength = 16383 // must be multiple of 3
|
|
;
|
|
// go through the array every three bytes, we'll deal with trailing stuff later
|
|
for(var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength){
|
|
parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
|
|
}
|
|
// pad the end with zeros, but make sure to not forget the extra bytes
|
|
if (extraBytes === 1) {
|
|
tmp = uint8[len - 1];
|
|
parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==');
|
|
} else if (extraBytes === 2) {
|
|
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
|
|
parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '=');
|
|
}
|
|
return parts.join('');
|
|
}
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/safe-buffer/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ /* eslint-disable node/no-deprecated-api */ var buffer = __turbopack_context__.r("[externals]/buffer [external] (buffer, cjs)");
|
|
var Buffer = buffer.Buffer;
|
|
// alternative to using Object.keys for old browsers
|
|
function copyProps(src, dst) {
|
|
for(var key in src){
|
|
dst[key] = src[key];
|
|
}
|
|
}
|
|
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
|
|
module.exports = buffer;
|
|
} else {
|
|
// Copy properties from require('buffer')
|
|
copyProps(buffer, exports);
|
|
exports.Buffer = SafeBuffer;
|
|
}
|
|
function SafeBuffer(arg, encodingOrOffset, length) {
|
|
return Buffer(arg, encodingOrOffset, length);
|
|
}
|
|
SafeBuffer.prototype = Object.create(Buffer.prototype);
|
|
// Copy static methods from Buffer
|
|
copyProps(Buffer, SafeBuffer);
|
|
SafeBuffer.from = function(arg, encodingOrOffset, length) {
|
|
if (typeof arg === 'number') {
|
|
throw new TypeError('Argument must not be a number');
|
|
}
|
|
return Buffer(arg, encodingOrOffset, length);
|
|
};
|
|
SafeBuffer.alloc = function(size, fill, encoding) {
|
|
if (typeof size !== 'number') {
|
|
throw new TypeError('Argument must be a number');
|
|
}
|
|
var buf = Buffer(size);
|
|
if (fill !== undefined) {
|
|
if (typeof encoding === 'string') {
|
|
buf.fill(fill, encoding);
|
|
} else {
|
|
buf.fill(fill);
|
|
}
|
|
} else {
|
|
buf.fill(0);
|
|
}
|
|
return buf;
|
|
};
|
|
SafeBuffer.allocUnsafe = function(size) {
|
|
if (typeof size !== 'number') {
|
|
throw new TypeError('Argument must be a number');
|
|
}
|
|
return Buffer(size);
|
|
};
|
|
SafeBuffer.allocUnsafeSlow = function(size) {
|
|
if (typeof size !== 'number') {
|
|
throw new TypeError('Argument must be a number');
|
|
}
|
|
return buffer.SlowBuffer(size);
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
function getParamSize(keySize) {
|
|
var result = (keySize / 8 | 0) + (keySize % 8 === 0 ? 0 : 1);
|
|
return result;
|
|
}
|
|
var paramBytesForAlg = {
|
|
ES256: getParamSize(256),
|
|
ES384: getParamSize(384),
|
|
ES512: getParamSize(521)
|
|
};
|
|
function getParamBytesForAlg(alg) {
|
|
var paramBytes = paramBytesForAlg[alg];
|
|
if (paramBytes) {
|
|
return paramBytes;
|
|
}
|
|
throw new Error('Unknown algorithm "' + alg + '"');
|
|
}
|
|
module.exports = getParamBytesForAlg;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
var Buffer = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/safe-buffer/index.js [app-route] (ecmascript)").Buffer;
|
|
var getParamBytesForAlg = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js [app-route] (ecmascript)");
|
|
var MAX_OCTET = 0x80, CLASS_UNIVERSAL = 0, PRIMITIVE_BIT = 0x20, TAG_SEQ = 0x10, TAG_INT = 0x02, ENCODED_TAG_SEQ = TAG_SEQ | PRIMITIVE_BIT | CLASS_UNIVERSAL << 6, ENCODED_TAG_INT = TAG_INT | CLASS_UNIVERSAL << 6;
|
|
function base64Url(base64) {
|
|
return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
}
|
|
function signatureAsBuffer(signature) {
|
|
if (Buffer.isBuffer(signature)) {
|
|
return signature;
|
|
} else if ('string' === typeof signature) {
|
|
return Buffer.from(signature, 'base64');
|
|
}
|
|
throw new TypeError('ECDSA signature must be a Base64 string or a Buffer');
|
|
}
|
|
function derToJose(signature, alg) {
|
|
signature = signatureAsBuffer(signature);
|
|
var paramBytes = getParamBytesForAlg(alg);
|
|
// the DER encoded param should at most be the param size, plus a padding
|
|
// zero, since due to being a signed integer
|
|
var maxEncodedParamLength = paramBytes + 1;
|
|
var inputLength = signature.length;
|
|
var offset = 0;
|
|
if (signature[offset++] !== ENCODED_TAG_SEQ) {
|
|
throw new Error('Could not find expected "seq"');
|
|
}
|
|
var seqLength = signature[offset++];
|
|
if (seqLength === (MAX_OCTET | 1)) {
|
|
seqLength = signature[offset++];
|
|
}
|
|
if (inputLength - offset < seqLength) {
|
|
throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');
|
|
}
|
|
if (signature[offset++] !== ENCODED_TAG_INT) {
|
|
throw new Error('Could not find expected "int" for "r"');
|
|
}
|
|
var rLength = signature[offset++];
|
|
if (inputLength - offset - 2 < rLength) {
|
|
throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');
|
|
}
|
|
if (maxEncodedParamLength < rLength) {
|
|
throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
|
|
}
|
|
var rOffset = offset;
|
|
offset += rLength;
|
|
if (signature[offset++] !== ENCODED_TAG_INT) {
|
|
throw new Error('Could not find expected "int" for "s"');
|
|
}
|
|
var sLength = signature[offset++];
|
|
if (inputLength - offset !== sLength) {
|
|
throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');
|
|
}
|
|
if (maxEncodedParamLength < sLength) {
|
|
throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
|
|
}
|
|
var sOffset = offset;
|
|
offset += sLength;
|
|
if (offset !== inputLength) {
|
|
throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');
|
|
}
|
|
var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength;
|
|
var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);
|
|
for(offset = 0; offset < rPadding; ++offset){
|
|
dst[offset] = 0;
|
|
}
|
|
signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);
|
|
offset = paramBytes;
|
|
for(var o = offset; offset < o + sPadding; ++offset){
|
|
dst[offset] = 0;
|
|
}
|
|
signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);
|
|
dst = dst.toString('base64');
|
|
dst = base64Url(dst);
|
|
return dst;
|
|
}
|
|
function countPadding(buf, start, stop) {
|
|
var padding = 0;
|
|
while(start + padding < stop && buf[start + padding] === 0){
|
|
++padding;
|
|
}
|
|
var needsSign = buf[start + padding] >= MAX_OCTET;
|
|
if (needsSign) {
|
|
--padding;
|
|
}
|
|
return padding;
|
|
}
|
|
function joseToDer(signature, alg) {
|
|
signature = signatureAsBuffer(signature);
|
|
var paramBytes = getParamBytesForAlg(alg);
|
|
var signatureBytes = signature.length;
|
|
if (signatureBytes !== paramBytes * 2) {
|
|
throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');
|
|
}
|
|
var rPadding = countPadding(signature, 0, paramBytes);
|
|
var sPadding = countPadding(signature, paramBytes, signature.length);
|
|
var rLength = paramBytes - rPadding;
|
|
var sLength = paramBytes - sPadding;
|
|
var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;
|
|
var shortLength = rsBytes < MAX_OCTET;
|
|
var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);
|
|
var offset = 0;
|
|
dst[offset++] = ENCODED_TAG_SEQ;
|
|
if (shortLength) {
|
|
// Bit 8 has value "0"
|
|
// bits 7-1 give the length.
|
|
dst[offset++] = rsBytes;
|
|
} else {
|
|
// Bit 8 of first octet has value "1"
|
|
// bits 7-1 give the number of additional length octets.
|
|
dst[offset++] = MAX_OCTET | 1;
|
|
// length, base 256
|
|
dst[offset++] = rsBytes & 0xff;
|
|
}
|
|
dst[offset++] = ENCODED_TAG_INT;
|
|
dst[offset++] = rLength;
|
|
if (rPadding < 0) {
|
|
dst[offset++] = 0;
|
|
offset += signature.copy(dst, offset, 0, paramBytes);
|
|
} else {
|
|
offset += signature.copy(dst, offset, rPadding, paramBytes);
|
|
}
|
|
dst[offset++] = ENCODED_TAG_INT;
|
|
dst[offset++] = sLength;
|
|
if (sPadding < 0) {
|
|
dst[offset++] = 0;
|
|
signature.copy(dst, offset, paramBytes);
|
|
} else {
|
|
signature.copy(dst, offset, paramBytes + sPadding);
|
|
}
|
|
return dst;
|
|
}
|
|
module.exports = {
|
|
derToJose: derToJose,
|
|
joseToDer: joseToDer
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/data-stream.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
/*global module, process*/ var Buffer = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/safe-buffer/index.js [app-route] (ecmascript)").Buffer;
|
|
var Stream = __turbopack_context__.r("[externals]/stream [external] (stream, cjs)");
|
|
var util = __turbopack_context__.r("[externals]/util [external] (util, cjs)");
|
|
function DataStream(data) {
|
|
this.buffer = null;
|
|
this.writable = true;
|
|
this.readable = true;
|
|
// No input
|
|
if (!data) {
|
|
this.buffer = Buffer.alloc(0);
|
|
return this;
|
|
}
|
|
// Stream
|
|
if (typeof data.pipe === 'function') {
|
|
this.buffer = Buffer.alloc(0);
|
|
data.pipe(this);
|
|
return this;
|
|
}
|
|
// Buffer or String
|
|
// or Object (assumedly a passworded key)
|
|
if (data.length || typeof data === 'object') {
|
|
this.buffer = data;
|
|
this.writable = false;
|
|
process.nextTick((function() {
|
|
this.emit('end', data);
|
|
this.readable = false;
|
|
this.emit('close');
|
|
}).bind(this));
|
|
return this;
|
|
}
|
|
throw new TypeError('Unexpected data type (' + typeof data + ')');
|
|
}
|
|
util.inherits(DataStream, Stream);
|
|
DataStream.prototype.write = function write(data) {
|
|
this.buffer = Buffer.concat([
|
|
this.buffer,
|
|
Buffer.from(data)
|
|
]);
|
|
this.emit('data', data);
|
|
};
|
|
DataStream.prototype.end = function end(data) {
|
|
if (data) this.write(data);
|
|
this.emit('end', data);
|
|
this.emit('close');
|
|
this.writable = false;
|
|
this.readable = false;
|
|
};
|
|
module.exports = DataStream;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/tostring.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
/*global module*/ var Buffer = __turbopack_context__.r("[externals]/buffer [external] (buffer, cjs)").Buffer;
|
|
module.exports = function toString(obj) {
|
|
if (typeof obj === 'string') return obj;
|
|
if (typeof obj === 'number' || Buffer.isBuffer(obj)) return obj.toString();
|
|
return JSON.stringify(obj);
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/sign-stream.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
/*global module*/ var Buffer = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/safe-buffer/index.js [app-route] (ecmascript)").Buffer;
|
|
var DataStream = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/data-stream.js [app-route] (ecmascript)");
|
|
var jwa = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jwa/index.js [app-route] (ecmascript)");
|
|
var Stream = __turbopack_context__.r("[externals]/stream [external] (stream, cjs)");
|
|
var toString = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/tostring.js [app-route] (ecmascript)");
|
|
var util = __turbopack_context__.r("[externals]/util [external] (util, cjs)");
|
|
function base64url(string, encoding) {
|
|
return Buffer.from(string, encoding).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
}
|
|
function jwsSecuredInput(header, payload, encoding) {
|
|
encoding = encoding || 'utf8';
|
|
var encodedHeader = base64url(toString(header), 'binary');
|
|
var encodedPayload = base64url(toString(payload), encoding);
|
|
return util.format('%s.%s', encodedHeader, encodedPayload);
|
|
}
|
|
function jwsSign(opts) {
|
|
var header = opts.header;
|
|
var payload = opts.payload;
|
|
var secretOrKey = opts.secret || opts.privateKey;
|
|
var encoding = opts.encoding;
|
|
var algo = jwa(header.alg);
|
|
var securedInput = jwsSecuredInput(header, payload, encoding);
|
|
var signature = algo.sign(securedInput, secretOrKey);
|
|
return util.format('%s.%s', securedInput, signature);
|
|
}
|
|
function SignStream(opts) {
|
|
var secret = opts.secret;
|
|
secret = secret == null ? opts.privateKey : secret;
|
|
secret = secret == null ? opts.key : secret;
|
|
if (/^hs/i.test(opts.header.alg) === true && secret == null) {
|
|
throw new TypeError('secret must be a string or buffer or a KeyObject');
|
|
}
|
|
var secretStream = new DataStream(secret);
|
|
this.readable = true;
|
|
this.header = opts.header;
|
|
this.encoding = opts.encoding;
|
|
this.secret = this.privateKey = this.key = secretStream;
|
|
this.payload = new DataStream(opts.payload);
|
|
this.secret.once('close', (function() {
|
|
if (!this.payload.writable && this.readable) this.sign();
|
|
}).bind(this));
|
|
this.payload.once('close', (function() {
|
|
if (!this.secret.writable && this.readable) this.sign();
|
|
}).bind(this));
|
|
}
|
|
util.inherits(SignStream, Stream);
|
|
SignStream.prototype.sign = function sign() {
|
|
try {
|
|
var signature = jwsSign({
|
|
header: this.header,
|
|
payload: this.payload.buffer,
|
|
secret: this.secret.buffer,
|
|
encoding: this.encoding
|
|
});
|
|
this.emit('done', signature);
|
|
this.emit('data', signature);
|
|
this.emit('end');
|
|
this.readable = false;
|
|
return signature;
|
|
} catch (e) {
|
|
this.readable = false;
|
|
this.emit('error', e);
|
|
this.emit('close');
|
|
}
|
|
};
|
|
SignStream.sign = jwsSign;
|
|
module.exports = SignStream;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/verify-stream.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
/*global module*/ var Buffer = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/safe-buffer/index.js [app-route] (ecmascript)").Buffer;
|
|
var DataStream = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/data-stream.js [app-route] (ecmascript)");
|
|
var jwa = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jwa/index.js [app-route] (ecmascript)");
|
|
var Stream = __turbopack_context__.r("[externals]/stream [external] (stream, cjs)");
|
|
var toString = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/tostring.js [app-route] (ecmascript)");
|
|
var util = __turbopack_context__.r("[externals]/util [external] (util, cjs)");
|
|
var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
|
|
function isObject(thing) {
|
|
return Object.prototype.toString.call(thing) === '[object Object]';
|
|
}
|
|
function safeJsonParse(thing) {
|
|
if (isObject(thing)) return thing;
|
|
try {
|
|
return JSON.parse(thing);
|
|
} catch (e) {
|
|
return undefined;
|
|
}
|
|
}
|
|
function headerFromJWS(jwsSig) {
|
|
var encodedHeader = jwsSig.split('.', 1)[0];
|
|
return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));
|
|
}
|
|
function securedInputFromJWS(jwsSig) {
|
|
return jwsSig.split('.', 2).join('.');
|
|
}
|
|
function signatureFromJWS(jwsSig) {
|
|
return jwsSig.split('.')[2];
|
|
}
|
|
function payloadFromJWS(jwsSig, encoding) {
|
|
encoding = encoding || 'utf8';
|
|
var payload = jwsSig.split('.')[1];
|
|
return Buffer.from(payload, 'base64').toString(encoding);
|
|
}
|
|
function isValidJws(string) {
|
|
return JWS_REGEX.test(string) && !!headerFromJWS(string);
|
|
}
|
|
function jwsVerify(jwsSig, algorithm, secretOrKey) {
|
|
if (!algorithm) {
|
|
var err = new Error("Missing algorithm parameter for jws.verify");
|
|
err.code = "MISSING_ALGORITHM";
|
|
throw err;
|
|
}
|
|
jwsSig = toString(jwsSig);
|
|
var signature = signatureFromJWS(jwsSig);
|
|
var securedInput = securedInputFromJWS(jwsSig);
|
|
var algo = jwa(algorithm);
|
|
return algo.verify(securedInput, signature, secretOrKey);
|
|
}
|
|
function jwsDecode(jwsSig, opts) {
|
|
opts = opts || {};
|
|
jwsSig = toString(jwsSig);
|
|
if (!isValidJws(jwsSig)) return null;
|
|
var header = headerFromJWS(jwsSig);
|
|
if (!header) return null;
|
|
var payload = payloadFromJWS(jwsSig);
|
|
if (header.typ === 'JWT' || opts.json) payload = JSON.parse(payload, opts.encoding);
|
|
return {
|
|
header: header,
|
|
payload: payload,
|
|
signature: signatureFromJWS(jwsSig)
|
|
};
|
|
}
|
|
function VerifyStream(opts) {
|
|
opts = opts || {};
|
|
var secretOrKey = opts.secret;
|
|
secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey;
|
|
secretOrKey = secretOrKey == null ? opts.key : secretOrKey;
|
|
if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) {
|
|
throw new TypeError('secret must be a string or buffer or a KeyObject');
|
|
}
|
|
var secretStream = new DataStream(secretOrKey);
|
|
this.readable = true;
|
|
this.algorithm = opts.algorithm;
|
|
this.encoding = opts.encoding;
|
|
this.secret = this.publicKey = this.key = secretStream;
|
|
this.signature = new DataStream(opts.signature);
|
|
this.secret.once('close', (function() {
|
|
if (!this.signature.writable && this.readable) this.verify();
|
|
}).bind(this));
|
|
this.signature.once('close', (function() {
|
|
if (!this.secret.writable && this.readable) this.verify();
|
|
}).bind(this));
|
|
}
|
|
util.inherits(VerifyStream, Stream);
|
|
VerifyStream.prototype.verify = function verify() {
|
|
try {
|
|
var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);
|
|
var obj = jwsDecode(this.signature.buffer, this.encoding);
|
|
this.emit('done', valid, obj);
|
|
this.emit('data', valid);
|
|
this.emit('end');
|
|
this.readable = false;
|
|
return valid;
|
|
} catch (e) {
|
|
this.readable = false;
|
|
this.emit('error', e);
|
|
this.emit('close');
|
|
}
|
|
};
|
|
VerifyStream.decode = jwsDecode;
|
|
VerifyStream.isValid = isValidJws;
|
|
VerifyStream.verify = jwsVerify;
|
|
module.exports = VerifyStream;
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/jws/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
/*global exports*/ var SignStream = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/sign-stream.js [app-route] (ecmascript)");
|
|
var VerifyStream = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/jws/lib/verify-stream.js [app-route] (ecmascript)");
|
|
var ALGORITHMS = [
|
|
'HS256',
|
|
'HS384',
|
|
'HS512',
|
|
'RS256',
|
|
'RS384',
|
|
'RS512',
|
|
'PS256',
|
|
'PS384',
|
|
'PS512',
|
|
'ES256',
|
|
'ES384',
|
|
'ES512'
|
|
];
|
|
exports.ALGORITHMS = ALGORITHMS;
|
|
exports.sign = SignStream.sign;
|
|
exports.verify = VerifyStream.verify;
|
|
exports.decode = VerifyStream.decode;
|
|
exports.isValid = VerifyStream.isValid;
|
|
exports.createSign = function createSign(opts) {
|
|
return new SignStream(opts);
|
|
};
|
|
exports.createVerify = function createVerify(opts) {
|
|
return new VerifyStream(opts);
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/buffer-equal-constant-time/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
"use strict";
|
|
|
|
/*jshint node:true */ var Buffer = __turbopack_context__.r("[externals]/buffer [external] (buffer, cjs)").Buffer; // browserify
|
|
var SlowBuffer = __turbopack_context__.r("[externals]/buffer [external] (buffer, cjs)").SlowBuffer;
|
|
module.exports = bufferEq;
|
|
function bufferEq(a, b) {
|
|
// shortcutting on type is necessary for correctness
|
|
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
|
|
return false;
|
|
}
|
|
// buffer sizes should be well-known information, so despite this
|
|
// shortcutting, it doesn't leak any information about the *contents* of the
|
|
// buffers.
|
|
if (a.length !== b.length) {
|
|
return false;
|
|
}
|
|
var c = 0;
|
|
for(var i = 0; i < a.length; i++){
|
|
/*jshint bitwise:false */ c |= a[i] ^ b[i]; // XOR
|
|
}
|
|
return c === 0;
|
|
}
|
|
bufferEq.install = function() {
|
|
Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {
|
|
return bufferEq(this, that);
|
|
};
|
|
};
|
|
var origBufEqual = Buffer.prototype.equal;
|
|
var origSlowBufEqual = SlowBuffer.prototype.equal;
|
|
bufferEq.restore = function() {
|
|
Buffer.prototype.equal = origBufEqual;
|
|
SlowBuffer.prototype.equal = origSlowBufEqual;
|
|
};
|
|
}),
|
|
"[project]/Documents/00 - projet/plumeia/node_modules/jwa/index.js [app-route] (ecmascript)", ((__turbopack_context__, module, exports) => {
|
|
|
|
var Buffer = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/safe-buffer/index.js [app-route] (ecmascript)").Buffer;
|
|
var crypto = __turbopack_context__.r("[externals]/crypto [external] (crypto, cjs)");
|
|
var formatEcdsa = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js [app-route] (ecmascript)");
|
|
var util = __turbopack_context__.r("[externals]/util [external] (util, cjs)");
|
|
var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".';
|
|
var MSG_INVALID_SECRET = 'secret must be a string or buffer';
|
|
var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';
|
|
var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';
|
|
var supportsKeyObjects = typeof crypto.createPublicKey === 'function';
|
|
if (supportsKeyObjects) {
|
|
MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';
|
|
MSG_INVALID_SECRET += 'or a KeyObject';
|
|
}
|
|
function checkIsPublicKey(key) {
|
|
if (Buffer.isBuffer(key)) {
|
|
return;
|
|
}
|
|
if (typeof key === 'string') {
|
|
return;
|
|
}
|
|
if (!supportsKeyObjects) {
|
|
throw typeError(MSG_INVALID_VERIFIER_KEY);
|
|
}
|
|
if (typeof key !== 'object') {
|
|
throw typeError(MSG_INVALID_VERIFIER_KEY);
|
|
}
|
|
if (typeof key.type !== 'string') {
|
|
throw typeError(MSG_INVALID_VERIFIER_KEY);
|
|
}
|
|
if (typeof key.asymmetricKeyType !== 'string') {
|
|
throw typeError(MSG_INVALID_VERIFIER_KEY);
|
|
}
|
|
if (typeof key.export !== 'function') {
|
|
throw typeError(MSG_INVALID_VERIFIER_KEY);
|
|
}
|
|
}
|
|
;
|
|
function checkIsPrivateKey(key) {
|
|
if (Buffer.isBuffer(key)) {
|
|
return;
|
|
}
|
|
if (typeof key === 'string') {
|
|
return;
|
|
}
|
|
if (typeof key === 'object') {
|
|
return;
|
|
}
|
|
throw typeError(MSG_INVALID_SIGNER_KEY);
|
|
}
|
|
;
|
|
function checkIsSecretKey(key) {
|
|
if (Buffer.isBuffer(key)) {
|
|
return;
|
|
}
|
|
if (typeof key === 'string') {
|
|
return key;
|
|
}
|
|
if (!supportsKeyObjects) {
|
|
throw typeError(MSG_INVALID_SECRET);
|
|
}
|
|
if (typeof key !== 'object') {
|
|
throw typeError(MSG_INVALID_SECRET);
|
|
}
|
|
if (key.type !== 'secret') {
|
|
throw typeError(MSG_INVALID_SECRET);
|
|
}
|
|
if (typeof key.export !== 'function') {
|
|
throw typeError(MSG_INVALID_SECRET);
|
|
}
|
|
}
|
|
function fromBase64(base64) {
|
|
return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
}
|
|
function toBase64(base64url) {
|
|
base64url = base64url.toString();
|
|
var padding = 4 - base64url.length % 4;
|
|
if (padding !== 4) {
|
|
for(var i = 0; i < padding; ++i){
|
|
base64url += '=';
|
|
}
|
|
}
|
|
return base64url.replace(/\-/g, '+').replace(/_/g, '/');
|
|
}
|
|
function typeError(template) {
|
|
var args = [].slice.call(arguments, 1);
|
|
var errMsg = util.format.bind(util, template).apply(null, args);
|
|
return new TypeError(errMsg);
|
|
}
|
|
function bufferOrString(obj) {
|
|
return Buffer.isBuffer(obj) || typeof obj === 'string';
|
|
}
|
|
function normalizeInput(thing) {
|
|
if (!bufferOrString(thing)) thing = JSON.stringify(thing);
|
|
return thing;
|
|
}
|
|
function createHmacSigner(bits) {
|
|
return function sign(thing, secret) {
|
|
checkIsSecretKey(secret);
|
|
thing = normalizeInput(thing);
|
|
var hmac = crypto.createHmac('sha' + bits, secret);
|
|
var sig = (hmac.update(thing), hmac.digest('base64'));
|
|
return fromBase64(sig);
|
|
};
|
|
}
|
|
var bufferEqual;
|
|
var timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) {
|
|
if (a.byteLength !== b.byteLength) {
|
|
return false;
|
|
}
|
|
return crypto.timingSafeEqual(a, b);
|
|
} : function timingSafeEqual(a, b) {
|
|
if (!bufferEqual) {
|
|
bufferEqual = __turbopack_context__.r("[project]/Documents/00 - projet/plumeia/node_modules/buffer-equal-constant-time/index.js [app-route] (ecmascript)");
|
|
}
|
|
return bufferEqual(a, b);
|
|
};
|
|
function createHmacVerifier(bits) {
|
|
return function verify(thing, signature, secret) {
|
|
var computedSig = createHmacSigner(bits)(thing, secret);
|
|
return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig));
|
|
};
|
|
}
|
|
function createKeySigner(bits) {
|
|
return function sign(thing, privateKey) {
|
|
checkIsPrivateKey(privateKey);
|
|
thing = normalizeInput(thing);
|
|
// Even though we are specifying "RSA" here, this works with ECDSA
|
|
// keys as well.
|
|
var signer = crypto.createSign('RSA-SHA' + bits);
|
|
var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));
|
|
return fromBase64(sig);
|
|
};
|
|
}
|
|
function createKeyVerifier(bits) {
|
|
return function verify(thing, signature, publicKey) {
|
|
checkIsPublicKey(publicKey);
|
|
thing = normalizeInput(thing);
|
|
signature = toBase64(signature);
|
|
var verifier = crypto.createVerify('RSA-SHA' + bits);
|
|
verifier.update(thing);
|
|
return verifier.verify(publicKey, signature, 'base64');
|
|
};
|
|
}
|
|
function createPSSKeySigner(bits) {
|
|
return function sign(thing, privateKey) {
|
|
checkIsPrivateKey(privateKey);
|
|
thing = normalizeInput(thing);
|
|
var signer = crypto.createSign('RSA-SHA' + bits);
|
|
var sig = (signer.update(thing), signer.sign({
|
|
key: privateKey,
|
|
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
|
|
saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
|
|
}, 'base64'));
|
|
return fromBase64(sig);
|
|
};
|
|
}
|
|
function createPSSKeyVerifier(bits) {
|
|
return function verify(thing, signature, publicKey) {
|
|
checkIsPublicKey(publicKey);
|
|
thing = normalizeInput(thing);
|
|
signature = toBase64(signature);
|
|
var verifier = crypto.createVerify('RSA-SHA' + bits);
|
|
verifier.update(thing);
|
|
return verifier.verify({
|
|
key: publicKey,
|
|
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
|
|
saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
|
|
}, signature, 'base64');
|
|
};
|
|
}
|
|
function createECDSASigner(bits) {
|
|
var inner = createKeySigner(bits);
|
|
return function sign() {
|
|
var signature = inner.apply(null, arguments);
|
|
signature = formatEcdsa.derToJose(signature, 'ES' + bits);
|
|
return signature;
|
|
};
|
|
}
|
|
function createECDSAVerifer(bits) {
|
|
var inner = createKeyVerifier(bits);
|
|
return function verify(thing, signature, publicKey) {
|
|
signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');
|
|
var result = inner(thing, signature, publicKey);
|
|
return result;
|
|
};
|
|
}
|
|
function createNoneSigner() {
|
|
return function sign() {
|
|
return '';
|
|
};
|
|
}
|
|
function createNoneVerifier() {
|
|
return function verify(thing, signature) {
|
|
return signature === '';
|
|
};
|
|
}
|
|
module.exports = function jwa(algorithm) {
|
|
var signerFactories = {
|
|
hs: createHmacSigner,
|
|
rs: createKeySigner,
|
|
ps: createPSSKeySigner,
|
|
es: createECDSASigner,
|
|
none: createNoneSigner
|
|
};
|
|
var verifierFactories = {
|
|
hs: createHmacVerifier,
|
|
rs: createKeyVerifier,
|
|
ps: createPSSKeyVerifier,
|
|
es: createECDSAVerifer,
|
|
none: createNoneVerifier
|
|
};
|
|
var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);
|
|
if (!match) throw typeError(MSG_INVALID_ALGORITHM, algorithm);
|
|
var algo = (match[1] || match[3]).toLowerCase();
|
|
var bits = match[2];
|
|
return {
|
|
sign: signerFactories[algo](bits),
|
|
verify: verifierFactories[algo](bits)
|
|
};
|
|
};
|
|
}),
|
|
];
|
|
|
|
//# sourceMappingURL=%5Broot-of-the-server%5D__a7ffcb98._.js.map
|