Flow Youtube Chat

Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.

目前为 2023-03-31 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Flow Youtube Chat
  3. // @description Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.
  4. // @version 1.15.20
  5. // @match https://www.youtube.com/*
  6. // @grant GM.setValue
  7. // @grant GM.getValue
  8. // @grant GM.deleteValue
  9. // @grant GM.listValues
  10. // @grant GM.setClipboard
  11. // @license AGPL-3.0-or-later
  12. // @namespace FlowYoutubeChatScript
  13. // @noframes
  14. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11.4.29/dist/sweetalert2.all.min.js#sha384-oOcVIFjLmJbkImF/OMv4gZHmkUcQAiX1EJZt7C9siwnS9yGghuo22mPgX7a623rc
  15. // @require https://unpkg.com/loglevel@1.8.0/dist/loglevel.min.js#sha384-xnEzWQtTztbu/yV2BtSvqqZGP52iLXbnb4NJ59OYT0ZDo1fGaKCR6QBxjyRuNFJ8
  16. // @require https://unpkg.com/rxjs@7.5.6/dist/bundles/rxjs.umd.min.js#sha384-loWwI45AmzSZ93ze6KW4+6eZVsQT8PriLOVCZGZstdycw5uylV3xKkHLQh53ui6b
  17. // @require https://unpkg.com/mithril@2.2.2/mithril.min.js#sha384-60kek02kUAH+DNSgj7HCtrpcirTroG3uWnDpsdvoAl2Z9Xe3GdpXDSy4ouNMHoBZ
  18. // @require https://cdn.jsdelivr.net/npm/check-types@11.1.2/src/check-types.min.js#sha384-KGnImnhVjA5llfqKEbjBiY+1Mp6oa+NvW/TEY1XTPAKWNgrAwa3Qvn//MXL07wBM
  19. // @require https://cdn.jsdelivr.net/npm/deep-diff@1.0.2/index.min.js#sha384-Q/uiWfFlwn9XjOpL49VpFKn01EkScmaC3hh1prAn7S++WoZgXRrrjQvZ7cI7C7Zn
  20. // @require https://cdn.jsdelivr.net/npm/astring@1.8.3/dist/astring.min.js#sha384-5Ucbdr4B4nO60a/3Lv4z9adjzcDkpVPH19acFTr320dXMe+cKE5y5zV+gycjJO8N
  21. // @require https://cdn.jsdelivr.net/npm/jsep@1.3.6/dist/iife/jsep.iife.min.js#sha384-6PGvkKayYZDccXp2sQ43aTf44oUNudO3L940VBGQYHfhg3YZEgSEbuannHJk7NBe
  22. // @require https://cdn.jsdelivr.net/npm/hash-it@5.0.2/dist/hash-it.min.js#sha384-biRMep0zr/5fw/hIdnBIb56UHRgiIyhAagZrngd9dSxxQ9aDFMP0hbYR8PEj5lVu
  23. // @require https://cdn.jsdelivr.net/npm/micro-memoize@4.0.14/dist/micro-memoize.min.js#sha384-W1hqD6GTNQ97ZqDR18GhfU1G9qcDLs4sL7BPYND2ncvGNNiLUmUp37Ph+hzm+OPt
  24. // @run-at document-end
  25. // ==/UserScript==
  26.  
  27. /* jshint esversion: 6 */
  28.  
  29. ;(() => {
  30. var __webpack_modules__ = {
  31. 661: module => {
  32. module.exports = !1
  33. },
  34. 204: module => {
  35. "use strict"
  36. module.exports = function equal(a, b) {
  37. if (a === b) return !0
  38. if (a && b && "object" == typeof a && "object" == typeof b) {
  39. if (a.constructor !== b.constructor) return !1
  40. var length, i, keys
  41. if (Array.isArray(a)) {
  42. if ((length = a.length) != b.length) return !1
  43. for (i = length; 0 != i--; ) if (!equal(a[i], b[i])) return !1
  44. return !0
  45. }
  46. if (a.constructor === RegExp)
  47. return a.source === b.source && a.flags === b.flags
  48. if (a.valueOf !== Object.prototype.valueOf)
  49. return a.valueOf() === b.valueOf()
  50. if (a.toString !== Object.prototype.toString)
  51. return a.toString() === b.toString()
  52. if (
  53. (length = (keys = Object.keys(a)).length) !==
  54. Object.keys(b).length
  55. )
  56. return !1
  57. for (i = length; 0 != i--; )
  58. if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return !1
  59. for (i = length; 0 != i--; ) {
  60. var key = keys[i]
  61. if (!equal(a[key], b[key])) return !1
  62. }
  63. return !0
  64. }
  65. return a != a && b != b
  66. }
  67. },
  68. 52: (__unused_webpack_module, exports) => {
  69. "use strict"
  70. exports.Xd = exports.hu = exports.tE = void 0
  71. const expectedToBe = type => `expected to be ${type}`
  72. exports.tE = (condition, message) => {
  73. if (!condition) throw new TypeError(message)
  74. }
  75. let baseAssert = exports.tE
  76. exports.hu = (condition, message) => baseAssert(condition, message)
  77. exports.Xd = function (
  78. input,
  79. message = expectedToBe("neither null nor undefined")
  80. ) {
  81. ;(0, exports.hu)(null != input, message)
  82. }
  83. },
  84. 694: module => {
  85. module.exports = (function (e) {
  86. var r = {}
  87. function t(n) {
  88. if (r[n]) return r[n].exports
  89. var a = (r[n] = { i: n, l: !1, exports: {} })
  90. return e[n].call(a.exports, a, a.exports, t), (a.l = !0), a.exports
  91. }
  92. return (
  93. (t.m = e),
  94. (t.c = r),
  95. (t.d = function (e, r, n) {
  96. t.o(e, r) ||
  97. Object.defineProperty(e, r, { enumerable: !0, get: n })
  98. }),
  99. (t.r = function (e) {
  100. "undefined" != typeof Symbol &&
  101. Symbol.toStringTag &&
  102. Object.defineProperty(e, Symbol.toStringTag, {
  103. value: "Module",
  104. }),
  105. Object.defineProperty(e, "__esModule", { value: !0 })
  106. }),
  107. (t.t = function (e, r) {
  108. if ((1 & r && (e = t(e)), 8 & r)) return e
  109. if (4 & r && "object" == typeof e && e && e.__esModule) return e
  110. var n = Object.create(null)
  111. if (
  112. (t.r(n),
  113. Object.defineProperty(n, "default", {
  114. enumerable: !0,
  115. value: e,
  116. }),
  117. 2 & r && "string" != typeof e)
  118. )
  119. for (var a in e)
  120. t.d(
  121. n,
  122. a,
  123. function (r) {
  124. return e[r]
  125. }.bind(null, a)
  126. )
  127. return n
  128. }),
  129. (t.n = function (e) {
  130. var r =
  131. e && e.__esModule
  132. ? function () {
  133. return e.default
  134. }
  135. : function () {
  136. return e
  137. }
  138. return t.d(r, "a", r), r
  139. }),
  140. (t.o = function (e, r) {
  141. return Object.prototype.hasOwnProperty.call(e, r)
  142. }),
  143. (t.p = ""),
  144. t((t.s = 0))
  145. )
  146. })([
  147. function (e, r, t) {
  148. "use strict"
  149. t.r(r),
  150. t.d(r, "validateHTMLColorName", function () {
  151. return l
  152. }),
  153. t.d(r, "validateHTMLColorSpecialName", function () {
  154. return i
  155. }),
  156. t.d(r, "validateHTMLColorHex", function () {
  157. return u
  158. }),
  159. t.d(r, "validateHTMLColorRgb", function () {
  160. return g
  161. }),
  162. t.d(r, "validateHTMLColorHsl", function () {
  163. return y
  164. }),
  165. t.d(r, "validateHTMLColorHwb", function () {
  166. return L
  167. }),
  168. t.d(r, "validateHTMLColorLab", function () {
  169. return S
  170. }),
  171. t.d(r, "validateHTMLColorLch", function () {
  172. return m
  173. }),
  174. t.d(r, "validateHTMLColor", function () {
  175. return G
  176. })
  177. const n = e => e && "string" == typeof e,
  178. a = [
  179. "AliceBlue",
  180. "AntiqueWhite",
  181. "Aqua",
  182. "Aquamarine",
  183. "Azure",
  184. "Beige",
  185. "Bisque",
  186. "Black",
  187. "BlanchedAlmond",
  188. "Blue",
  189. "BlueViolet",
  190. "Brown",
  191. "BurlyWood",
  192. "CadetBlue",
  193. "Chartreuse",
  194. "Chocolate",
  195. "Coral",
  196. "CornflowerBlue",
  197. "Cornsilk",
  198. "Crimson",
  199. "Cyan",
  200. "DarkBlue",
  201. "DarkCyan",
  202. "DarkGoldenrod",
  203. "DarkGray",
  204. "DarkGrey",
  205. "DarkGreen",
  206. "DarkKhaki",
  207. "DarkMagenta",
  208. "DarkOliveGreen",
  209. "DarkOrange",
  210. "DarkOrchid",
  211. "DarkRed",
  212. "DarkSalmon",
  213. "DarkSeaGreen",
  214. "DarkSlateBlue",
  215. "DarkSlateGray",
  216. "DarkSlateGrey",
  217. "DarkTurquoise",
  218. "DarkViolet",
  219. "DeepPink",
  220. "DeepSkyBlue",
  221. "DimGray",
  222. "DimGrey",
  223. "DodgerBlue",
  224. "FireBrick",
  225. "FloralWhite",
  226. "ForestGreen",
  227. "Fuchsia",
  228. "Gainsboro",
  229. "GhostWhite",
  230. "Gold",
  231. "Goldenrod",
  232. "Gray",
  233. "Grey",
  234. "Green",
  235. "GreenYellow",
  236. "HoneyDew",
  237. "HotPink",
  238. "IndianRed",
  239. "Indigo",
  240. "Ivory",
  241. "Khaki",
  242. "Lavender",
  243. "LavenderBlush",
  244. "LawnGreen",
  245. "LemonChiffon",
  246. "LightBlue",
  247. "LightCoral",
  248. "LightCyan",
  249. "LightGoldenrodYellow",
  250. "LightGray",
  251. "LightGrey",
  252. "LightGreen",
  253. "LightPink",
  254. "LightSalmon",
  255. "LightSalmon",
  256. "LightSeaGreen",
  257. "LightSkyBlue",
  258. "LightSlateGray",
  259. "LightSlateGrey",
  260. "LightSteelBlue",
  261. "LightYellow",
  262. "Lime",
  263. "LimeGreen",
  264. "Linen",
  265. "Magenta",
  266. "Maroon",
  267. "MediumAquamarine",
  268. "MediumBlue",
  269. "MediumOrchid",
  270. "MediumPurple",
  271. "MediumSeaGreen",
  272. "MediumSlateBlue",
  273. "MediumSlateBlue",
  274. "MediumSpringGreen",
  275. "MediumTurquoise",
  276. "MediumVioletRed",
  277. "MidnightBlue",
  278. "MintCream",
  279. "MistyRose",
  280. "Moccasin",
  281. "NavajoWhite",
  282. "Navy",
  283. "OldLace",
  284. "Olive",
  285. "OliveDrab",
  286. "Orange",
  287. "OrangeRed",
  288. "Orchid",
  289. "PaleGoldenrod",
  290. "PaleGreen",
  291. "PaleTurquoise",
  292. "PaleVioletRed",
  293. "PapayaWhip",
  294. "PeachPuff",
  295. "Peru",
  296. "Pink",
  297. "Plum",
  298. "PowderBlue",
  299. "Purple",
  300. "RebeccaPurple",
  301. "Red",
  302. "RosyBrown",
  303. "RoyalBlue",
  304. "SaddleBrown",
  305. "Salmon",
  306. "SandyBrown",
  307. "SeaGreen",
  308. "SeaShell",
  309. "Sienna",
  310. "Silver",
  311. "SkyBlue",
  312. "SlateBlue",
  313. "SlateGray",
  314. "SlateGrey",
  315. "Snow",
  316. "SpringGreen",
  317. "SteelBlue",
  318. "Tan",
  319. "Teal",
  320. "Thistle",
  321. "Tomato",
  322. "Turquoise",
  323. "Violet",
  324. "Wheat",
  325. "White",
  326. "WhiteSmoke",
  327. "Yellow",
  328. "YellowGreen",
  329. ],
  330. o = ["currentColor", "inherit", "transparent"],
  331. l = e => {
  332. let r = !1
  333. return (
  334. n(e) &&
  335. a.map(
  336. t => (
  337. e.toLowerCase() === t.toLowerCase() && (r = !0), null
  338. )
  339. ),
  340. r
  341. )
  342. },
  343. i = e => {
  344. let r = !1
  345. return (
  346. n(e) &&
  347. o.map(
  348. t => (
  349. e.toLowerCase() === t.toLowerCase() && (r = !0), null
  350. )
  351. ),
  352. r
  353. )
  354. },
  355. u = e => {
  356. if (n(e)) {
  357. const r = /^#([\da-f]{3}){1,2}$|^#([\da-f]{4}){1,2}$/i
  358. return e && r.test(e)
  359. }
  360. return !1
  361. },
  362. d = "(([\\d]{0,5})((\\.([\\d]{1,5}))?))",
  363. s = `(${d}%)`,
  364. c = "(([0-9]|[1-9][0-9]|100)%)",
  365. f = `(${c}|(0?((\\.([\\d]{1,5}))?))|1)`,
  366. h = `([\\s]{0,5})\\)?)(([\\s]{0,5})(\\/?)([\\s]{1,5})(((${c}))|(0?((\\.([\\d]{1,5}))?))|1))?([\\s]{0,5})\\)`,
  367. $ =
  368. "(-?(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-9][0-9]|3[0-5][0-9])((\\.([\\d]{1,5}))?)|360)(deg)?)",
  369. g = e => {
  370. if (n(e)) {
  371. const r = "([\\s]{0,5})([\\d]{1,5})%?([\\s]{0,5}),?",
  372. t = "((([\\s]{0,5}),?([\\s]{0,5}))|(([\\s]{1,5})))",
  373. n = new RegExp(
  374. `^(rgb)a?\\(${r}${t}${r}${t}${r}${t}((\\/?([\\s]{0,5})(0?\\.?([\\d]{1,5})%?([\\s]{0,5}))?|1|0))?\\)$`
  375. )
  376. return e && n.test(e)
  377. }
  378. return !1
  379. },
  380. y = e => {
  381. if (n(e)) {
  382. const r = new RegExp(
  383. `^(hsl)a?\\((([\\s]{0,5})(${$}|(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-9][0-9]|3[0-9][0-9]|400)grad)|((([0-5])?\\.([\\d]{1,5})|6\\.([0-9]|1[0-9]|2[0-8])|[0-6])rad)|((0?((\\.([\\d]{1,5}))?)|1)turn))((([\\s]{0,5}),([\\s]{0,5}))|(([\\s]{1,5}))))(([\\s]{0,5})(0|${c})((([\\s]{0,5}),([\\s]{0,5}))|(([\\s]{1,5}))))(([\\s]{0,5})(0|${c})([\\s]{0,5})\\)?)(([\\s]{0,5})(\\/?|,?)([\\s]{0,5})(((${c}))|(0?((\\.([\\d]{1,5}))?))|1))?\\)$`
  384. )
  385. return e && r.test(e)
  386. }
  387. return !1
  388. },
  389. L = e => {
  390. if (n(e)) {
  391. const r = new RegExp(
  392. `^(hwb\\(([\\s]{0,5})${$}([\\s]{1,5}))((0|${c})([\\s]{1,5}))((0|${c})${h}$`
  393. )
  394. return e && r.test(e)
  395. }
  396. return !1
  397. },
  398. S = e => {
  399. if (n(e)) {
  400. const r =
  401. "(-?(([0-9]|[1-9][0-9]|1[0-5][0-9])((\\.([\\d]{1,5}))?)?|160))",
  402. t = new RegExp(
  403. `^(lab\\(([\\s]{0,5})${s}([\\s]{1,5})${r}([\\s]{1,5})${r}${h}$`
  404. )
  405. return e && t.test(e)
  406. }
  407. return !1
  408. },
  409. m = e => {
  410. if (n(e)) {
  411. const o = new RegExp(
  412. `^lch\\((([\\s]{0,5})((([0-9]|[1-9][0-9])?((\\.([\\d]{1,5}))?)|100)(%)?)([\\s]{1,5})${
  413. "" + d
  414. }([\\s]{1,5})((${$})|(0|${f})|(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-9][0-9]|3[0-5][0-9])((\\.([\\d]{1,5}))?)|360))([\\s]{0,5})((\\/([\\s]{0,5})${f}))?)\\)$`
  415. )
  416. return e && o.test(e)
  417. }
  418. return !1
  419. },
  420. G = e => !!((e && u(e)) || g(e) || y(e) || L(e) || S(e) || m(e))
  421. r.default = e =>
  422. !!(
  423. (e && u(e)) ||
  424. l(e) ||
  425. i(e) ||
  426. g(e) ||
  427. y(e) ||
  428. L(e) ||
  429. S(e) ||
  430. m(e)
  431. )
  432. },
  433. ])
  434. },
  435. 938: () => {},
  436. },
  437. __webpack_module_cache__ = {}
  438. function __webpack_require__(moduleId) {
  439. var cachedModule = __webpack_module_cache__[moduleId]
  440. if (void 0 !== cachedModule) return cachedModule.exports
  441. var module = (__webpack_module_cache__[moduleId] = { exports: {} })
  442. __webpack_modules__[moduleId](module, module.exports, __webpack_require__)
  443. return module.exports
  444. }
  445. __webpack_require__.n = module => {
  446. var getter =
  447. module && module.__esModule ? () => module.default : () => module
  448. __webpack_require__.d(getter, { a: getter })
  449. return getter
  450. }
  451. __webpack_require__.d = (exports, definition) => {
  452. for (var key in definition)
  453. __webpack_require__.o(definition, key) &&
  454. !__webpack_require__.o(exports, key) &&
  455. Object.defineProperty(exports, key, {
  456. enumerable: !0,
  457. get: definition[key],
  458. })
  459. }
  460. __webpack_require__.o = (obj, prop) =>
  461. Object.prototype.hasOwnProperty.call(obj, prop)
  462. ;(() => {
  463. "use strict"
  464. const Function_dual = (arity, body) => {
  465. const isDataFirst =
  466. "number" == typeof arity ? args => args.length >= arity : arity
  467. return function () {
  468. return isDataFirst(arguments)
  469. ? body.apply(this, arguments)
  470. : self => body(self, ...arguments)
  471. }
  472. },
  473. apply = a => self => self(a),
  474. Function_identity = a => a,
  475. constant = value => () => value,
  476. Function_constTrue = constant(!0),
  477. Function_constFalse = constant(!1),
  478. Function_constUndefined = constant(void 0),
  479. Function_constVoid = Function_constUndefined,
  480. flip =
  481. f =>
  482. (...b) =>
  483. (...a) =>
  484. f(...a)(...b)
  485. function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {
  486. switch (arguments.length) {
  487. case 1:
  488. return ab
  489. case 2:
  490. return function () {
  491. return bc(ab.apply(this, arguments))
  492. }
  493. case 3:
  494. return function () {
  495. return cd(bc(ab.apply(this, arguments)))
  496. }
  497. case 4:
  498. return function () {
  499. return de(cd(bc(ab.apply(this, arguments))))
  500. }
  501. case 5:
  502. return function () {
  503. return ef(de(cd(bc(ab.apply(this, arguments)))))
  504. }
  505. case 6:
  506. return function () {
  507. return fg(ef(de(cd(bc(ab.apply(this, arguments))))))
  508. }
  509. case 7:
  510. return function () {
  511. return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))
  512. }
  513. case 8:
  514. return function () {
  515. return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))))
  516. }
  517. case 9:
  518. return function () {
  519. return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))))
  520. }
  521. }
  522. }
  523. function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
  524. switch (arguments.length) {
  525. case 1:
  526. return a
  527. case 2:
  528. return ab(a)
  529. case 3:
  530. return bc(ab(a))
  531. case 4:
  532. return cd(bc(ab(a)))
  533. case 5:
  534. return de(cd(bc(ab(a))))
  535. case 6:
  536. return ef(de(cd(bc(ab(a)))))
  537. case 7:
  538. return fg(ef(de(cd(bc(ab(a))))))
  539. case 8:
  540. return gh(fg(ef(de(cd(bc(ab(a)))))))
  541. case 9:
  542. return hi(gh(fg(ef(de(cd(bc(ab(a))))))))
  543. default: {
  544. let ret = arguments[0]
  545. for (let i = 1; i < arguments.length; i++) ret = arguments[i](ret)
  546. return ret
  547. }
  548. }
  549. }
  550. const globalStoreId = Symbol.for("@effect/data/Global/globalStoreId")
  551. globalStoreId in globalThis || (globalThis[globalStoreId] = new Map())
  552. const globalStore = globalThis[globalStoreId],
  553. globalValue = (id, compute) => {
  554. globalStore.has(id) || globalStore.set(id, compute())
  555. return globalStore.get(id)
  556. }
  557. function isNothing(value) {
  558. return null == value
  559. }
  560. class PCGRandom {
  561. constructor(seedHi, seedLo, incHi, incLo) {
  562. if (isNothing(seedLo) && isNothing(seedHi)) {
  563. seedLo = (4294967295 * Math.random()) >>> 0
  564. seedHi = 0
  565. } else if (isNothing(seedLo)) {
  566. seedLo = seedHi
  567. seedHi = 0
  568. }
  569. if (isNothing(incLo) && isNothing(incHi)) {
  570. incLo = this._state ? this._state[3] : 4150755663
  571. incHi = this._state ? this._state[2] : 335903614
  572. } else if (isNothing(incLo)) {
  573. incLo = incHi
  574. incHi = 0
  575. }
  576. this._state = new Int32Array([
  577. 0,
  578. 0,
  579. incHi >>> 0,
  580. (1 | (incLo || 0)) >>> 0,
  581. ])
  582. this._next()
  583. add64(
  584. this._state,
  585. this._state[0],
  586. this._state[1],
  587. seedHi >>> 0,
  588. seedLo >>> 0
  589. )
  590. this._next()
  591. return this
  592. }
  593. getState() {
  594. return [this._state[0], this._state[1], this._state[2], this._state[3]]
  595. }
  596. setState(state) {
  597. this._state[0] = state[0]
  598. this._state[1] = state[1]
  599. this._state[2] = state[2]
  600. this._state[3] = 1 | state[3]
  601. }
  602. integer(max) {
  603. if (!max) return this._next()
  604. if (0 == ((max >>>= 0) & (max - 1))) return this._next() & (max - 1)
  605. let num = 0
  606. const skew = (-max >>> 0) % max >>> 0
  607. for (num = this._next(); num < skew; num = this._next());
  608. return num % max
  609. }
  610. number() {
  611. return (
  612. (1 * (67108863 & this._next()) * 134217728 +
  613. 1 * (134217727 & this._next())) /
  614. 9007199254740992
  615. )
  616. }
  617. _next() {
  618. const oldHi = this._state[0] >>> 0,
  619. oldLo = this._state[1] >>> 0
  620. !(function (out, aHi, aLo, bHi, bLo) {
  621. let c1 = (32557 * (aLo >>> 16)) >>> 0,
  622. c0 = (19605 * (65535 & aLo)) >>> 0,
  623. lo = (32557 * (65535 & aLo)) >>> 0,
  624. hi = (19605 * (aLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16))) >>> 0
  625. c0 = (c0 << 16) >>> 0
  626. lo = (lo + c0) >>> 0
  627. lo >>> 0 < c0 >>> 0 && (hi = (hi + 1) >>> 0)
  628. c1 = (c1 << 16) >>> 0
  629. lo = (lo + c1) >>> 0
  630. lo >>> 0 < c1 >>> 0 && (hi = (hi + 1) >>> 0)
  631. hi = (hi + Math.imul(aLo, 1481765933)) >>> 0
  632. hi = (hi + Math.imul(aHi, bLo)) >>> 0
  633. out[0] = hi
  634. out[1] = lo
  635. })(this._state, oldHi, oldLo, 0, 1284865837)
  636. add64(
  637. this._state,
  638. this._state[0],
  639. this._state[1],
  640. this._state[2],
  641. this._state[3]
  642. )
  643. let xsHi = oldHi >>> 18,
  644. xsLo = ((oldLo >>> 18) | (oldHi << 14)) >>> 0
  645. xsHi = (xsHi ^ oldHi) >>> 0
  646. xsLo = (xsLo ^ oldLo) >>> 0
  647. const xorshifted = ((xsLo >>> 27) | (xsHi << 5)) >>> 0,
  648. rot = oldHi >>> 27
  649. return (
  650. ((xorshifted >>> rot) |
  651. (xorshifted << (((-rot >>> 0) & 31) >>> 0))) >>>
  652. 0
  653. )
  654. }
  655. }
  656. function add64(out, aHi, aLo, bHi, bLo) {
  657. let hi = (aHi + bHi) >>> 0
  658. const lo = (aLo + bLo) >>> 0
  659. lo >>> 0 < aLo >>> 0 && (hi = (hi + 1) | 0)
  660. out[0] = hi
  661. out[1] = lo
  662. }
  663. const randomHashCache = globalValue(
  664. Symbol.for("@effect/data/Hash/randomHashCache"),
  665. () => new WeakMap()
  666. ),
  667. pcgr = globalValue(
  668. Symbol.for("@effect/data/Hash/pcgr"),
  669. () => new PCGRandom()
  670. ),
  671. symbol = Symbol.for("@effect/data/Hash"),
  672. Hash_hash = self => {
  673. switch (typeof self) {
  674. case "number":
  675. return number(self)
  676. case "bigint":
  677. return string(self.toString(10))
  678. case "boolean":
  679. case "symbol":
  680. return string(String(self))
  681. case "string":
  682. return string(self)
  683. case "undefined":
  684. return string("undefined")
  685. case "function":
  686. case "object":
  687. return null === self
  688. ? string("null")
  689. : isHash(self)
  690. ? self[symbol]()
  691. : random(self)
  692. default:
  693. throw new Error("Bug in Equal.hashGeneric")
  694. }
  695. },
  696. random = self => {
  697. randomHashCache.has(self) ||
  698. randomHashCache.set(
  699. self,
  700. number(pcgr.integer(Number.MAX_SAFE_INTEGER))
  701. )
  702. return randomHashCache.get(self)
  703. },
  704. combine = b => self => (53 * self) ^ b,
  705. optimize = n => (3221225471 & n) | ((n >>> 1) & 1073741824),
  706. isHash = u => "object" == typeof u && null !== u && symbol in u,
  707. number = n => {
  708. if (n != n || n === 1 / 0) return 0
  709. let h = 0 | n
  710. h !== n && (h ^= 4294967295 * n)
  711. for (; n > 4294967295; ) h ^= n /= 4294967295
  712. return optimize(n)
  713. },
  714. string = str => {
  715. let h = 5381,
  716. i = str.length
  717. for (; i; ) h = (33 * h) ^ str.charCodeAt(--i)
  718. return optimize(h)
  719. },
  720. array = arr => {
  721. let h = 6151
  722. for (let i = 0; i < arr.length; i++) h = combine(Hash_hash(arr[i]))(h)
  723. return optimize(h)
  724. },
  725. Equal_symbol = Symbol.for("@effect/data/Equal")
  726. function equals() {
  727. return 1 === arguments.length
  728. ? self => compareBoth(self, arguments[0])
  729. : compareBoth(arguments[0], arguments[1])
  730. }
  731. function compareBoth(self, that) {
  732. if (self === that) return !0
  733. const selfType = typeof self
  734. return (
  735. selfType === typeof that &&
  736. !(
  737. ("object" !== selfType && "function" !== selfType) ||
  738. null === self ||
  739. null === that ||
  740. !isEqual(self) ||
  741. !isEqual(that)
  742. ) &&
  743. Hash_hash(self) === Hash_hash(that) &&
  744. self[Equal_symbol](that)
  745. )
  746. }
  747. const isEqual = u =>
  748. "object" == typeof u && null !== u && Equal_symbol in u,
  749. protoStruct = (() => {
  750. const proto = {
  751. [symbol]() {
  752. return (o => {
  753. const keys = Object.keys(o)
  754. let h = 12289
  755. for (let i = 0; i < keys.length; i++)
  756. h ^= combine(Hash_hash(o[keys[i]]))(string(keys[i]))
  757. return optimize(h)
  758. })(this)
  759. },
  760. [Equal_symbol](that) {
  761. const selfKeys = Object.keys(this),
  762. thatKeys = Object.keys(that)
  763. if (selfKeys.length !== thatKeys.length) return !1
  764. for (const key of selfKeys)
  765. if (!(key in that) || !equals(this[key], that[key])) return !1
  766. return !0
  767. },
  768. }
  769. return Object.setPrototypeOf(proto, Object.prototype)
  770. })(),
  771. struct = as => unsafeStruct(Object.assign({}, as)),
  772. unsafeStruct = as => Object.setPrototypeOf(as, protoStruct),
  773. none = struct({ _tag: "None" }),
  774. some = a => struct({ _tag: "Some", value: a }),
  775. not = self => a => !self(a),
  776. make = compare => ({
  777. compare: (self, that) => (self === that ? 0 : compare(self, that)),
  778. }),
  779. Order_number = make((self, that) => (self < that ? -1 : 1)),
  780. Order_contramap = Function_dual(2, (self, f) =>
  781. make((b1, b2) => self.compare(f(b1), f(b2)))
  782. ),
  783. greaterThanOrEqualTo = O =>
  784. Function_dual(2, (self, that) => -1 !== O.compare(self, that)),
  785. Equivalence_make =
  786. (Order_number.compare,
  787. isEquivalent => (self, that) =>
  788. self === that || isEquivalent(self, that)),
  789. isStrictEquivalent = (x, y) => x === y,
  790. strict = () => isStrictEquivalent,
  791. Equivalence_string = strict(),
  792. Semigroup_make = (
  793. combine,
  794. combineMany = (self, collection) => {
  795. return ((b = self),
  796. (f = combine),
  797. function (iterable) {
  798. if (Array.isArray(iterable)) return iterable.reduce(f, b)
  799. let result = b
  800. for (const n of iterable) result = f(result, n)
  801. return result
  802. })(collection)
  803. var b, f
  804. }
  805. ) => ({ combine, combineMany }),
  806. Semigroup_string = Semigroup_make((self, that) => self + that),
  807. numberSum = Semigroup_make((self, that) => self + that),
  808. numberMultiply = Semigroup_make(
  809. (self, that) => self * that,
  810. (self, collection) => {
  811. if (0 === self) return 0
  812. let out = self
  813. for (const n of collection) {
  814. if (0 === n) return 0
  815. out *= n
  816. }
  817. return out
  818. }
  819. ),
  820. booleanEvery = Semigroup_make(
  821. (self, that) => self && that,
  822. (self, collection) => {
  823. if (!1 === self) return !1
  824. for (const b of collection) if (!1 === b) return !1
  825. return !0
  826. }
  827. ),
  828. booleanSome = Semigroup_make(
  829. (self, that) => self || that,
  830. (self, collection) => {
  831. if (!0 === self) return !0
  832. for (const b of collection) if (!0 === b) return !0
  833. return !1
  834. }
  835. ),
  836. intercalate = Function_dual(2, (S, separator) =>
  837. Semigroup_make((self, that) => S.combineMany(self, [separator, that]))
  838. ),
  839. fromSemigroup = (S, empty) => ({
  840. combine: S.combine,
  841. combineMany: S.combineMany,
  842. empty,
  843. combineAll: collection => S.combineMany(empty, collection),
  844. }),
  845. Monoid_string = fromSemigroup(Semigroup_string, ""),
  846. Monoid_numberSum = fromSemigroup(numberSum, 0),
  847. Monoid_numberMultiply = fromSemigroup(numberMultiply, 1),
  848. Monoid_booleanEvery = fromSemigroup(booleanEvery, !0),
  849. Monoid_booleanSome = fromSemigroup(booleanSome, !1),
  850. Order = (numberSum.combine, numberMultiply.combine, Order_number),
  851. MonoidMultiply = Monoid_numberMultiply,
  852. Covariant_imap =
  853. (Monoid_numberSum.combineAll,
  854. MonoidMultiply.combineAll,
  855. map => Function_dual(3, (self, to, _) => map(self, to))),
  856. let_ = F =>
  857. Function_dual(3, (self, name, f) =>
  858. F.map(self, a => Object.assign({}, a, { [name]: f(a) }))
  859. ),
  860. filter = Filterable =>
  861. Function_dual(2, (self, predicate) =>
  862. Filterable.filterMap(self, b => (predicate(b) ? some(b) : none))
  863. ),
  864. Option_none = () => none,
  865. Option_some = some,
  866. Option_isNone = fa => "None" === fa._tag,
  867. Option_isSome = fa => "Some" === fa._tag,
  868. match = Function_dual(3, (self, onNone, onSome) =>
  869. Option_isNone(self) ? onNone() : onSome(self.value)
  870. ),
  871. getOrElse = Function_dual(2, (self, onNone) =>
  872. Option_isNone(self) ? onNone() : self.value
  873. ),
  874. orElse = Function_dual(2, (self, that) =>
  875. Option_isNone(self) ? that() : self
  876. ),
  877. fromNullable = nullableValue =>
  878. null == nullableValue ? Option_none() : Option_some(nullableValue),
  879. getOrUndefined = getOrElse(Function_constUndefined),
  880. getOrThrow = Function_dual(2, (self, onNone) => {
  881. if (Option_isSome(self)) return self.value
  882. throw onNone()
  883. })(() => new Error("getOrThrow called on a None")),
  884. Option_map = Function_dual(2, (self, f) =>
  885. Option_isNone(self) ? Option_none() : Option_some(f(self.value))
  886. ),
  887. flatMap = Function_dual(2, (self, f) =>
  888. Option_isNone(self) ? Option_none() : f(self.value)
  889. ),
  890. flatMapNullable = Function_dual(2, (self, f) =>
  891. Option_isNone(self) ? Option_none() : fromNullable(f(self.value))
  892. ),
  893. Option_filter = filter({
  894. partitionMap: Function_dual(2, (self, f) => {
  895. if (Option_isNone(self)) return [Option_none(), Option_none()]
  896. const e = f(self.value)
  897. return "Left" === e._tag
  898. ? [Option_some(e.left), Option_none()]
  899. : [Option_none(), Option_some(e.right)]
  900. }),
  901. filterMap: Function_dual(2, (self, f) =>
  902. Option_isNone(self) ? Option_none() : f(self.value)
  903. ),
  904. }),
  905. liftPredicate = predicate => b =>
  906. predicate(b) ? Option_some(b) : Option_none(),
  907. exists = Function_dual(
  908. 2,
  909. (self, predicate) => !Option_isNone(self) && predicate(self.value)
  910. ),
  911. Either_right = a => struct({ _tag: "Right", right: a }),
  912. Either_left = e => struct({ _tag: "Left", left: e }),
  913. Either_isRight = ma => "Right" === ma._tag,
  914. isNonEmptyArray = self => self.length > 0,
  915. String_Equivalence = Equivalence_string,
  916. Semigroup = Semigroup_string,
  917. Monoid = Monoid_string,
  918. slice =
  919. (Semigroup.combine,
  920. Function_dual(3, (self, start, end) => self.slice(start, end))),
  921. isEmpty = self => 0 === self.length,
  922. split = Function_dual(2, (self, separator) => {
  923. const out = self.split(separator)
  924. return isNonEmptyArray(out) ? out : [self]
  925. }),
  926. includes = Function_dual(2, (self, searchString) =>
  927. self.includes(searchString)
  928. )
  929. class LinesIterator {
  930. constructor(s, stripped = !1) {
  931. this.s = s
  932. this.stripped = stripped
  933. this.index = 0
  934. this.length = s.length
  935. }
  936. next() {
  937. if (this.done) return { done: !0, value: void 0 }
  938. const start = this.index
  939. for (; !this.done && !isLineBreak(this.s[this.index]); )
  940. this.index = this.index + 1
  941. let end = this.index
  942. if (!this.done) {
  943. const char = this.s[this.index]
  944. this.index = this.index + 1
  945. !this.done &&
  946. isLineBreak2(char, this.s[this.index]) &&
  947. (this.index = this.index + 1)
  948. this.stripped || (end = this.index)
  949. }
  950. return { done: !1, value: this.s.substring(start, end) }
  951. }
  952. [Symbol.iterator]() {
  953. return new LinesIterator(this.s, this.stripped)
  954. }
  955. get done() {
  956. return this.index >= this.length
  957. }
  958. }
  959. const isLineBreak = char => {
  960. const code = char.charCodeAt(0)
  961. return 13 === code || 10 === code
  962. },
  963. isLineBreak2 = (char0, char1) =>
  964. 13 === char0.charCodeAt(0) && 10 === char1.charCodeAt(0),
  965. Invariant_bindTo = F =>
  966. Function_dual(2, (self, name) =>
  967. F.imap(
  968. self,
  969. a => ({ [name]: a }),
  970. ({ [name]: a }) => a
  971. )
  972. ),
  973. SemiProduct_andThenBind = F =>
  974. Function_dual(3, (self, name, that) =>
  975. F.imap(
  976. F.product(self, that),
  977. ([a, b]) => Object.assign({}, a, { [name]: b }),
  978. ({ [name]: b, ...rest }) => [rest, b]
  979. )
  980. ),
  981. makeBy = (n, f) => {
  982. const max = Math.max(1, Math.floor(n)),
  983. out = [f(0)]
  984. for (let i = 1; i < max; i++) out.push(f(i))
  985. return out
  986. },
  987. mjs_ReadonlyArray_fromIterable = collection =>
  988. Array.isArray(collection) ? collection : Array.from(collection),
  989. prepend = Function_dual(2, (self, head) => [head, ...self]),
  990. append = Function_dual(2, (self, last) => [...self, last]),
  991. isEmptyReadonlyArray = self => 0 === self.length,
  992. isNonEmptyReadonlyArray = isNonEmptyArray,
  993. ReadonlyArray_clamp = (i, as) =>
  994. Math.floor(Math.min(Math.max(0, i), as.length)),
  995. unsafeGet = Function_dual(2, (self, index) => {
  996. const i = Math.floor(index)
  997. if (((i, as) => i < 0 || i >= as.length)(i, self))
  998. throw new Error(`Index ${i} out of bounds`)
  999. return self[i]
  1000. }),
  1001. headNonEmpty = unsafeGet(0),
  1002. tailNonEmpty = self => self.slice(1),
  1003. take = Function_dual(2, (self, n) => {
  1004. const input = mjs_ReadonlyArray_fromIterable(self)
  1005. return input.slice(0, ReadonlyArray_clamp(n, input))
  1006. }),
  1007. drop = Function_dual(2, (self, n) => {
  1008. const input = mjs_ReadonlyArray_fromIterable(self)
  1009. return input.slice(ReadonlyArray_clamp(n, input), input.length)
  1010. }),
  1011. findFirstIndex = Function_dual(2, (self, predicate) => {
  1012. let i = 0
  1013. for (const a of self) {
  1014. if (predicate(a)) return Option_some(i)
  1015. i++
  1016. }
  1017. return Option_none()
  1018. }),
  1019. findFirst = Function_dual(2, (self, predicate) => {
  1020. const input = mjs_ReadonlyArray_fromIterable(self)
  1021. for (let i = 0; i < input.length; i++)
  1022. if (predicate(input[i])) return Option_some(input[i])
  1023. return Option_none()
  1024. }),
  1025. findLast = Function_dual(2, (self, predicate) => {
  1026. const input = mjs_ReadonlyArray_fromIterable(self)
  1027. for (let i = input.length - 1; i >= 0; i--)
  1028. if (predicate(input[i])) return Option_some(input[i])
  1029. return Option_none()
  1030. }),
  1031. ReadonlyArray_reverse = self => Array.from(self).reverse(),
  1032. sort = Function_dual(2, (self, O) => {
  1033. const out = Array.from(self)
  1034. out.sort(O.compare)
  1035. return out
  1036. }),
  1037. zip = Function_dual(2, (self, that) =>
  1038. ReadonlyArray_zipWith(self, that, (a, b) => [a, b])
  1039. ),
  1040. ReadonlyArray_zipWith = Function_dual(3, (self, that, f) => {
  1041. const as = mjs_ReadonlyArray_fromIterable(self),
  1042. bs = mjs_ReadonlyArray_fromIterable(that)
  1043. return isNonEmptyReadonlyArray(as) && isNonEmptyReadonlyArray(bs)
  1044. ? zipNonEmptyWith(bs, f)(as)
  1045. : []
  1046. }),
  1047. zipNonEmptyWith = Function_dual(3, (self, that, f) => {
  1048. const cs = [f(headNonEmpty(self), headNonEmpty(that))],
  1049. len = Math.min(self.length, that.length)
  1050. for (let i = 1; i < len; i++) cs[i] = f(self[i], that[i])
  1051. return cs
  1052. }),
  1053. uniq = Function_dual(2, (self, isEquivalent) => {
  1054. const input = mjs_ReadonlyArray_fromIterable(self)
  1055. return isNonEmptyReadonlyArray(input)
  1056. ? uniqNonEmpty(isEquivalent)(input)
  1057. : []
  1058. }),
  1059. uniqNonEmpty = Function_dual(2, (self, isEquivalent) => {
  1060. const out = [headNonEmpty(self)],
  1061. rest = tailNonEmpty(self)
  1062. for (const a of rest) out.every(o => !isEquivalent(a, o)) && out.push(a)
  1063. return out
  1064. }),
  1065. ReadonlyArray_of = a => [a],
  1066. ReadonlyArray_map = Function_dual(2, (self, f) => self.map(f)),
  1067. ReadonlyArray_Invariant = { imap: Covariant_imap(ReadonlyArray_map) },
  1068. ReadonlyArray_flatMap = Function_dual(2, (self, f) => {
  1069. if (isEmptyReadonlyArray(self)) return []
  1070. const out = []
  1071. for (let i = 0; i < self.length; i++) out.push(...f(self[i], i))
  1072. return out
  1073. }),
  1074. ReadonlyArray_filterMap = Function_dual(2, (self, f) => {
  1075. const as = mjs_ReadonlyArray_fromIterable(self),
  1076. out = []
  1077. for (let i = 0; i < as.length; i++) {
  1078. const o = f(as[i], i)
  1079. Option_isSome(o) && out.push(o.value)
  1080. }
  1081. return out
  1082. }),
  1083. ReadonlyArray_compact = ReadonlyArray_filterMap(Function_identity),
  1084. ReadonlyArray_filter = Function_dual(2, (self, predicate) => {
  1085. const as = mjs_ReadonlyArray_fromIterable(self),
  1086. out = []
  1087. for (let i = 0; i < as.length; i++)
  1088. predicate(as[i], i) && out.push(as[i])
  1089. return out
  1090. }),
  1091. ReadonlyArray_reduce = Function_dual(3, (self, b, f) =>
  1092. mjs_ReadonlyArray_fromIterable(self).reduce((b, a, i) => f(b, a, i), b)
  1093. ),
  1094. ReadonlyArray_some = predicate => self => self.some(predicate),
  1095. ReadonlyArray_intercalate = M =>
  1096. Function_dual(2, (self, middle) => {
  1097. const as = mjs_ReadonlyArray_fromIterable(self)
  1098. return isNonEmptyReadonlyArray(as)
  1099. ? intercalateNonEmpty(M)(as, middle)
  1100. : M.empty
  1101. }),
  1102. intercalateNonEmpty = S =>
  1103. Function_dual(2, (self, middle) =>
  1104. intercalate(S, middle).combineMany(
  1105. headNonEmpty(self),
  1106. tailNonEmpty(self)
  1107. )
  1108. ),
  1109. join = ReadonlyArray_intercalate(Monoid),
  1110. ReadonlyArray_bindTo = Invariant_bindTo(ReadonlyArray_Invariant),
  1111. TypeId = Symbol.for("@effect/data/Chunk"),
  1112. emptyArray = []
  1113. class ChunkImpl {
  1114. constructor(backing) {
  1115. this.backing = backing
  1116. this._id = TypeId
  1117. switch (backing._tag) {
  1118. case "IEmpty":
  1119. this.length = 0
  1120. this.depth = 0
  1121. this.left = this
  1122. this.right = this
  1123. break
  1124. case "IConcat":
  1125. this.length = backing.left.length + backing.right.length
  1126. this.depth = 1 + Math.max(backing.left.depth, backing.right.depth)
  1127. this.left = backing.left
  1128. this.right = backing.right
  1129. break
  1130. case "IArray":
  1131. this.length = backing.array.length
  1132. this.depth = 0
  1133. this.left = _empty
  1134. this.right = _empty
  1135. break
  1136. case "ISingleton":
  1137. this.length = 1
  1138. this.depth = 0
  1139. this.left = _empty
  1140. this.right = _empty
  1141. }
  1142. }
  1143. toString() {
  1144. return `Chunk(${toReadonlyArray(this).map(String).join(", ")})`
  1145. }
  1146. toJSON() {
  1147. return { _tag: "Chunk", values: toReadonlyArray(this) }
  1148. }
  1149. [Symbol.for("nodejs.util.inspect.custom")]() {
  1150. return this.toJSON()
  1151. }
  1152. [Equal_symbol](that) {
  1153. return (
  1154. !(!isChunk(that) || this.length !== that.length) &&
  1155. toReadonlyArray(this).every((value, i) =>
  1156. equals(value, Chunk_unsafeGet(that, i))
  1157. )
  1158. )
  1159. }
  1160. [symbol]() {
  1161. return array(toReadonlyArray(this))
  1162. }
  1163. [Symbol.iterator]() {
  1164. switch (this.backing._tag) {
  1165. case "IArray":
  1166. return this.backing.array[Symbol.iterator]()
  1167. case "IEmpty":
  1168. return emptyArray[Symbol.iterator]()
  1169. default:
  1170. return toReadonlyArray(this)[Symbol.iterator]()
  1171. }
  1172. }
  1173. }
  1174. const copyToArray = (self, array, initial) => {
  1175. switch (self.backing._tag) {
  1176. case "IArray":
  1177. !(function (src, srcPos, dest, destPos, len) {
  1178. for (let i = 0; i < Math.min(src.length, 0 + len); i++)
  1179. dest[destPos + i - 0] = src[i]
  1180. })(self.backing.array, 0, array, initial, self.length)
  1181. break
  1182. case "IConcat":
  1183. copyToArray(self.left, array, initial)
  1184. copyToArray(self.right, array, initial + self.left.length)
  1185. break
  1186. case "ISingleton":
  1187. array[initial] = self.backing.a
  1188. }
  1189. },
  1190. isChunk = u =>
  1191. "object" == typeof u && null != u && "_id" in u && u._id === TypeId,
  1192. _empty = new ChunkImpl({ _tag: "IEmpty" }),
  1193. Chunk_empty = () => _empty,
  1194. Chunk_fromIterable = self =>
  1195. isChunk(self)
  1196. ? self
  1197. : new ChunkImpl({ _tag: "IArray", array: Array.from(self) }),
  1198. toReadonlyArray = self => {
  1199. switch (self.backing._tag) {
  1200. case "IEmpty":
  1201. return emptyArray
  1202. case "IArray":
  1203. return self.backing.array
  1204. default: {
  1205. const arr = new Array(self.length)
  1206. copyToArray(self, arr, 0)
  1207. self.backing = { _tag: "IArray", array: arr }
  1208. self.left = _empty
  1209. self.right = _empty
  1210. self.depth = 0
  1211. return arr
  1212. }
  1213. }
  1214. },
  1215. Chunk_get = Function_dual(2, (self, index) =>
  1216. index < 0 || index >= self.length
  1217. ? Option_none()
  1218. : Option_some(Chunk_unsafeGet(self, index))
  1219. ),
  1220. unsafeFromArray = self => new ChunkImpl({ _tag: "IArray", array: self }),
  1221. Chunk_unsafeGet = Function_dual(2, (self, index) => {
  1222. switch (self.backing._tag) {
  1223. case "IEmpty":
  1224. throw new Error("Index out of bounds")
  1225. case "ISingleton":
  1226. if (0 !== index) throw new Error("Index out of bounds")
  1227. return self.backing.a
  1228. case "IArray":
  1229. if (index >= self.length || index < 0)
  1230. throw new Error("Index out of bounds")
  1231. return self.backing.array[index]
  1232. case "IConcat":
  1233. return index < self.left.length
  1234. ? Chunk_unsafeGet(self.left, index)
  1235. : Chunk_unsafeGet(self.right, index - self.left.length)
  1236. }
  1237. }),
  1238. Chunk_append = Function_dual(2, (self, a) =>
  1239. Chunk_concat(self, Chunk_of(a))
  1240. ),
  1241. Chunk_prepend = Function_dual(2, (self, a) =>
  1242. Chunk_concat(Chunk_of(a), self)
  1243. ),
  1244. Chunk_take = Function_dual(2, (self, n) =>
  1245. n <= 0
  1246. ? _empty
  1247. : n >= self.length
  1248. ? self
  1249. : unsafeFromArray(take(n)(toReadonlyArray(self)))
  1250. ),
  1251. Chunk_drop = Function_dual(2, (self, n) =>
  1252. n <= 0
  1253. ? self
  1254. : n >= self.length
  1255. ? _empty
  1256. : unsafeFromArray(drop(n)(toReadonlyArray(self)))
  1257. ),
  1258. Chunk_concat = Function_dual(2, (self, that) => {
  1259. if ("IEmpty" === self.backing._tag) return that
  1260. if ("IEmpty" === that.backing._tag) return self
  1261. const diff = that.depth - self.depth
  1262. if (Math.abs(diff) <= 1)
  1263. return new ChunkImpl({ _tag: "IConcat", left: self, right: that })
  1264. if (diff < -1) {
  1265. if (self.left.depth >= self.right.depth) {
  1266. const nr = Chunk_concat(that)(self.right)
  1267. return new ChunkImpl({
  1268. _tag: "IConcat",
  1269. left: self.left,
  1270. right: nr,
  1271. })
  1272. }
  1273. {
  1274. const nrr = Chunk_concat(that)(self.right.right)
  1275. if (nrr.depth === self.depth - 3) {
  1276. const nr = new ChunkImpl({
  1277. _tag: "IConcat",
  1278. left: self.right.left,
  1279. right: nrr,
  1280. })
  1281. return new ChunkImpl({
  1282. _tag: "IConcat",
  1283. left: self.left,
  1284. right: nr,
  1285. })
  1286. }
  1287. {
  1288. const nl = new ChunkImpl({
  1289. _tag: "IConcat",
  1290. left: self.left,
  1291. right: self.right.left,
  1292. })
  1293. return new ChunkImpl({ _tag: "IConcat", left: nl, right: nrr })
  1294. }
  1295. }
  1296. }
  1297. if (that.right.depth >= that.left.depth) {
  1298. const nl = Chunk_concat(that.left)(self)
  1299. return new ChunkImpl({ _tag: "IConcat", left: nl, right: that.right })
  1300. }
  1301. {
  1302. const nll = Chunk_concat(that.left.left)(self)
  1303. if (nll.depth === that.depth - 3) {
  1304. const nl = new ChunkImpl({
  1305. _tag: "IConcat",
  1306. left: nll,
  1307. right: that.left.right,
  1308. })
  1309. return new ChunkImpl({
  1310. _tag: "IConcat",
  1311. left: nl,
  1312. right: that.right,
  1313. })
  1314. }
  1315. {
  1316. const nr = new ChunkImpl({
  1317. _tag: "IConcat",
  1318. left: that.left.right,
  1319. right: that.right,
  1320. })
  1321. return new ChunkImpl({ _tag: "IConcat", left: nll, right: nr })
  1322. }
  1323. }
  1324. }),
  1325. dedupeAdjacent = self => {
  1326. const builder = []
  1327. let lastA = Option_none()
  1328. for (const a of self)
  1329. if (Option_isNone(lastA) || !equals(a, lastA.value)) {
  1330. builder.push(a)
  1331. lastA = Option_some(a)
  1332. }
  1333. return unsafeFromArray(builder)
  1334. },
  1335. Chunk_head = Chunk_get(0),
  1336. Chunk_isEmpty = self => 0 === self.length,
  1337. Chunk_isNonEmpty = self => self.length > 0,
  1338. Chunk_reduce = Function_dual(3, (self, b, f) =>
  1339. ReadonlyArray_reduce(b, f)(toReadonlyArray(self))
  1340. ),
  1341. Chunk_of = a => new ChunkImpl({ _tag: "ISingleton", a }),
  1342. Chunk_makeBy = Function_dual(2, (n, f) =>
  1343. ((...as) => unsafeFromArray(as))(...makeBy(n, f))
  1344. ),
  1345. Chunk_map = Function_dual(2, (self, f) =>
  1346. "ISingleton" === self.backing._tag
  1347. ? Chunk_of(f(self.backing.a))
  1348. : unsafeFromArray(ReadonlyArray_map(f)(toReadonlyArray(self)))
  1349. ),
  1350. mapWithIndex = Function_dual(2, (self, f) =>
  1351. "ISingleton" === self.backing._tag
  1352. ? Chunk_of(f(self.backing.a, 0))
  1353. : unsafeFromArray(ReadonlyArray_map(f)(toReadonlyArray(self)))
  1354. ),
  1355. Chunk_reverse = self =>
  1356. unsafeFromArray(ReadonlyArray_reverse(toReadonlyArray(self))),
  1357. Chunk_sort = Function_dual(2, (self, O) =>
  1358. unsafeFromArray(sort(O)(toReadonlyArray(self)))
  1359. ),
  1360. Chunk_splitAt = Function_dual(2, (self, n) => [
  1361. Chunk_take(n)(self),
  1362. Chunk_drop(n)(self),
  1363. ]),
  1364. splitWhere = Function_dual(2, (self, f) => {
  1365. let i = 0
  1366. for (const a of toReadonlyArray(self)) {
  1367. if (f(a)) break
  1368. i++
  1369. }
  1370. return Chunk_splitAt(i)(self)
  1371. }),
  1372. unsafeHead = self => Chunk_unsafeGet(0)(self),
  1373. unsafeLast = self => Chunk_unsafeGet(self.length - 1)(self),
  1374. Chunk_headNonEmpty = unsafeHead,
  1375. Chunk_tailNonEmpty = self => Chunk_drop(self, 1)
  1376. var _a
  1377. const runtimeDebug = globalValue(
  1378. Symbol.for("@effect/data/Debug/runtimeDebug"),
  1379. () => ({
  1380. reportUnhandled: !0,
  1381. minumumLogLevel: "Info",
  1382. traceStackLimit: 5,
  1383. tracingEnabled: !0,
  1384. parseStack: error => {
  1385. const stack = error.stack
  1386. if (stack) {
  1387. const lines = stack.split("\n")
  1388. let starts = 0
  1389. for (let i = 0; i < lines.length; i++)
  1390. lines[i].startsWith("Error") && (starts = i)
  1391. const frames = []
  1392. for (let i = starts + 1; i < lines.length; i++)
  1393. if (lines[i].includes("at")) {
  1394. const blocks = lines[i]
  1395. .split(" ")
  1396. .filter(i => i.length > 0 && "at" !== i),
  1397. name =
  1398. 2 !== blocks.length || blocks[0].includes("<anonymous>")
  1399. ? void 0
  1400. : blocks[0],
  1401. matchFrame = (
  1402. 2 === blocks.length ? blocks[1] : blocks[0]
  1403. )?.match(/\(?(.*):(\d+):(\d+)/)
  1404. matchFrame
  1405. ? frames.push({
  1406. name,
  1407. fileName: matchFrame[1],
  1408. line: Number.parseInt(matchFrame[2]),
  1409. column: Number.parseInt(matchFrame[3]),
  1410. })
  1411. : frames.push(void 0)
  1412. } else frames.push(void 0)
  1413. return frames
  1414. }
  1415. return []
  1416. },
  1417. filterStackFrame: _ =>
  1418. null != _ && !_.fileName.match(/\/internal_effect_untraced/),
  1419. })
  1420. ),
  1421. sourceLocationProto = Object.setPrototypeOf(
  1422. {
  1423. toFrame() {
  1424. if ("parsed" in this) return this.parsed
  1425. const stack = runtimeDebug.parseStack(this)
  1426. stack && stack.length >= 2 && stack[0] && stack[1]
  1427. ? (this.parsed = {
  1428. ...stack[this.depth - 1],
  1429. name: stack[this.depth - 2]?.name,
  1430. })
  1431. : (this.parsed = void 0)
  1432. return this.parsed
  1433. },
  1434. },
  1435. Error.prototype
  1436. ),
  1437. sourceLocation = error => {
  1438. error.depth = Error.stackTraceLimit
  1439. Object.setPrototypeOf(error, sourceLocationProto)
  1440. return error
  1441. },
  1442. bodyWithTrace = body => {
  1443. if (!runtimeDebug.tracingEnabled) return body(void 0, restoreOff)
  1444. runtimeDebug.tracingEnabled = !1
  1445. try {
  1446. const limit = Error.stackTraceLimit
  1447. Error.stackTraceLimit = 3
  1448. const source = sourceLocation(new Error())
  1449. Error.stackTraceLimit = limit
  1450. return body(source, restoreOn)
  1451. } finally {
  1452. runtimeDebug.tracingEnabled = !0
  1453. }
  1454. },
  1455. methodWithTrace = body =>
  1456. function () {
  1457. if (!runtimeDebug.tracingEnabled)
  1458. return body(void 0, restoreOff).apply(this, arguments)
  1459. runtimeDebug.tracingEnabled = !1
  1460. try {
  1461. const limit = Error.stackTraceLimit
  1462. Error.stackTraceLimit = 2
  1463. const error = sourceLocation(new Error())
  1464. Error.stackTraceLimit = limit
  1465. return body(error, restoreOn).apply(this, arguments)
  1466. } finally {
  1467. runtimeDebug.tracingEnabled = !0
  1468. }
  1469. },
  1470. dualWithTrace = (dfLen, body) => {
  1471. const isDataFirst =
  1472. "number" == typeof dfLen ? args => args.length === dfLen : dfLen
  1473. return function () {
  1474. if (!runtimeDebug.tracingEnabled) {
  1475. const f = body(void 0, restoreOff)
  1476. return isDataFirst(arguments)
  1477. ? untraced(() => f.apply(this, arguments))
  1478. : self => untraced(() => f(self, ...arguments))
  1479. }
  1480. runtimeDebug.tracingEnabled = !1
  1481. try {
  1482. const limit = Error.stackTraceLimit
  1483. Error.stackTraceLimit = 2
  1484. const source = sourceLocation(new Error())
  1485. Error.stackTraceLimit = limit
  1486. const f = body(source, restoreOn)
  1487. return isDataFirst(arguments)
  1488. ? untraced(() => f.apply(this, arguments))
  1489. : self => untraced(() => f(self, ...arguments))
  1490. } finally {
  1491. runtimeDebug.tracingEnabled = !0
  1492. }
  1493. }
  1494. },
  1495. untraced = body => {
  1496. if (!runtimeDebug.tracingEnabled) return body(restoreOff)
  1497. runtimeDebug.tracingEnabled = !1
  1498. try {
  1499. return body(restoreOn)
  1500. } finally {
  1501. runtimeDebug.tracingEnabled = !0
  1502. }
  1503. },
  1504. untracedDual = (dfLen, body) =>
  1505. function () {
  1506. if (!runtimeDebug.tracingEnabled) {
  1507. const f = body(restoreOff)
  1508. return arguments.length === dfLen
  1509. ? untraced(() => f.apply(this, arguments))
  1510. : self => untraced(() => f(self, ...arguments))
  1511. }
  1512. runtimeDebug.tracingEnabled = !1
  1513. try {
  1514. const f = body(restoreOn)
  1515. return arguments.length === dfLen
  1516. ? untraced(() => f.apply(this, arguments))
  1517. : self => untraced(() => f(self, ...arguments))
  1518. } finally {
  1519. runtimeDebug.tracingEnabled = !0
  1520. }
  1521. },
  1522. untracedMethod = body =>
  1523. function () {
  1524. if (!runtimeDebug.tracingEnabled)
  1525. return untraced(() => body(restoreOff).apply(this, arguments))
  1526. runtimeDebug.tracingEnabled = !1
  1527. try {
  1528. return untraced(() => body(restoreOn).apply(this, arguments))
  1529. } finally {
  1530. runtimeDebug.tracingEnabled = !0
  1531. }
  1532. },
  1533. restoreOn = body =>
  1534. function () {
  1535. if (runtimeDebug.tracingEnabled) return body.apply(this, arguments)
  1536. runtimeDebug.tracingEnabled = !0
  1537. try {
  1538. return body.apply(this, arguments)
  1539. } finally {
  1540. runtimeDebug.tracingEnabled = !1
  1541. }
  1542. },
  1543. restoreOff = body =>
  1544. function () {
  1545. if (!runtimeDebug.tracingEnabled) return body.apply(this, arguments)
  1546. runtimeDebug.tracingEnabled = !1
  1547. try {
  1548. return body.apply(this, arguments)
  1549. } finally {
  1550. runtimeDebug.tracingEnabled = !0
  1551. }
  1552. },
  1553. EffectTypeId = Symbol.for("@effect/io/Effect")
  1554. class TracedPrimitive {
  1555. [((_a = EffectTypeId), Equal_symbol)](that) {
  1556. return this === that
  1557. }
  1558. [symbol]() {
  1559. return random(this)
  1560. }
  1561. constructor(i0, trace) {
  1562. this.i0 = i0
  1563. this.trace = trace
  1564. this._tag = "Traced"
  1565. this.i1 = void 0
  1566. this.i2 = void 0
  1567. this[_a] = effectVariance
  1568. }
  1569. traced(trace) {
  1570. return trace ? new TracedPrimitive(this, trace) : this
  1571. }
  1572. }
  1573. const effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ }
  1574. var Context_a
  1575. const TagTypeId = Symbol.for("@effect/data/Context/Tag"),
  1576. Context_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  1577. Context_EffectTypeId = Symbol.for("@effect/io/Effect")
  1578. class TagImpl {
  1579. [((Context_a = Context_EffectTypeId), Equal_symbol)](that) {
  1580. return this === that
  1581. }
  1582. [symbol]() {
  1583. return random(this)
  1584. }
  1585. get [TagTypeId]() {
  1586. return { _S: _ => _, _I: _ => _ }
  1587. }
  1588. constructor(id) {
  1589. this._tag = "Tag"
  1590. this.i0 = void 0
  1591. this.i1 = void 0
  1592. this.i2 = void 0
  1593. this.trace = void 0
  1594. this[Context_a] = Context_effectVariance
  1595. if (void 0 !== id) return globalValue(id, () => this)
  1596. }
  1597. traced(trace) {
  1598. return trace
  1599. ? ((self, source) => new TracedPrimitive(this, source))(0, trace)
  1600. : this
  1601. }
  1602. }
  1603. const ContextTypeId = Symbol.for("@effect/data/Context")
  1604. class ContextImpl {
  1605. [Equal_symbol](that) {
  1606. if (isContext(that) && this.unsafeMap.size === that.unsafeMap.size) {
  1607. for (const k of this.unsafeMap.keys())
  1608. if (
  1609. !that.unsafeMap.has(k) ||
  1610. !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))
  1611. )
  1612. return !1
  1613. return !0
  1614. }
  1615. return !1
  1616. }
  1617. [symbol]() {
  1618. return number(this.unsafeMap.size)
  1619. }
  1620. constructor(unsafeMap) {
  1621. this.unsafeMap = unsafeMap
  1622. this._id = ContextTypeId
  1623. this._S = _ => _
  1624. }
  1625. }
  1626. const isContext = u =>
  1627. "object" == typeof u &&
  1628. null !== u &&
  1629. "_id" in u &&
  1630. u._id === ContextTypeId,
  1631. Context_unsafeGet = Function_dual(2, (self, tag) => {
  1632. if (!self.unsafeMap.has(tag)) throw new Error("Service not found")
  1633. return self.unsafeMap.get(tag)
  1634. }),
  1635. Context_merge = Function_dual(2, (self, that) => {
  1636. const map = new Map(self.unsafeMap)
  1637. for (const [tag, s] of that.unsafeMap) map.set(tag, s)
  1638. return new ContextImpl(map)
  1639. }),
  1640. Tag = key => new TagImpl(key),
  1641. mjs_Context_empty = () => new ContextImpl(new Map()),
  1642. mjs_Context_unsafeGet = Context_unsafeGet,
  1643. mjs_Context_merge = Context_merge,
  1644. ContextPatchTypeId = Symbol.for("@effect/data/Differ/ContextPatch")
  1645. function ContextPatch_variance(a) {
  1646. return a
  1647. }
  1648. class ContextPatch_Empty {
  1649. constructor() {
  1650. this._tag = "Empty"
  1651. this._Input = ContextPatch_variance
  1652. this._Output = ContextPatch_variance
  1653. this._id = ContextPatchTypeId
  1654. }
  1655. [symbol]() {
  1656. return string("ContextPatch(Empty)")
  1657. }
  1658. [Equal_symbol](that) {
  1659. return (
  1660. "object" == typeof that &&
  1661. null !== that &&
  1662. "_id" in that &&
  1663. that._id === this._id &&
  1664. "_tag" in that &&
  1665. that._tag === this._id
  1666. )
  1667. }
  1668. }
  1669. class ContextPatch_AndThen {
  1670. constructor(first, second) {
  1671. this.first = first
  1672. this.second = second
  1673. this._tag = "AndThen"
  1674. this._id = ContextPatchTypeId
  1675. this._Input = ContextPatch_variance
  1676. this._Output = ContextPatch_variance
  1677. }
  1678. [symbol]() {
  1679. return string("ContextPatch(AndThen)")
  1680. }
  1681. [Equal_symbol](that) {
  1682. return (
  1683. "object" == typeof that &&
  1684. null !== that &&
  1685. "_id" in that &&
  1686. that._id === this._id &&
  1687. "_tag" in that &&
  1688. that._tag === this._id &&
  1689. equals(this.first, that.first) &&
  1690. equals(this.second, that.second)
  1691. )
  1692. }
  1693. }
  1694. class AddService {
  1695. constructor(tag, service) {
  1696. this.tag = tag
  1697. this.service = service
  1698. this._tag = "AddService"
  1699. this._id = ContextPatchTypeId
  1700. this._Input = ContextPatch_variance
  1701. this._Output = ContextPatch_variance
  1702. }
  1703. [symbol]() {
  1704. return string("ContextPatch(AddService)")
  1705. }
  1706. [Equal_symbol](that) {
  1707. return (
  1708. "object" == typeof that &&
  1709. null !== that &&
  1710. "_id" in that &&
  1711. that._id === this._id &&
  1712. "_tag" in that &&
  1713. that._tag === this._id &&
  1714. equals(this.tag, that.tag) &&
  1715. equals(this.service, that.service)
  1716. )
  1717. }
  1718. }
  1719. class RemoveService {
  1720. constructor(tag) {
  1721. this.tag = tag
  1722. this._tag = "RemoveService"
  1723. this._id = ContextPatchTypeId
  1724. this._Input = ContextPatch_variance
  1725. this._Output = ContextPatch_variance
  1726. }
  1727. [symbol]() {
  1728. return string("ContextPatch(RemoveService)")
  1729. }
  1730. [Equal_symbol](that) {
  1731. return (
  1732. "object" == typeof that &&
  1733. null !== that &&
  1734. "_id" in that &&
  1735. that._id === this._id &&
  1736. "_tag" in that &&
  1737. that._tag === this._id &&
  1738. equals(this.tag, that.tag)
  1739. )
  1740. }
  1741. }
  1742. class UpdateService {
  1743. constructor(tag, update) {
  1744. this.tag = tag
  1745. this.update = update
  1746. this._tag = "UpdateService"
  1747. this._id = ContextPatchTypeId
  1748. this._Input = ContextPatch_variance
  1749. this._Output = ContextPatch_variance
  1750. }
  1751. [symbol]() {
  1752. return string("ContextPatch(AndThen)")
  1753. }
  1754. [Equal_symbol](that) {
  1755. return (
  1756. "object" == typeof that &&
  1757. null !== that &&
  1758. "_id" in that &&
  1759. that._id === this._id &&
  1760. "_tag" in that &&
  1761. that._tag === this._id &&
  1762. equals(this.tag, that.tag) &&
  1763. equals(this.update, that.update)
  1764. )
  1765. }
  1766. }
  1767. const ContextPatch_empty = () => new ContextPatch_Empty(),
  1768. ContextPatch_combine = Function_dual(
  1769. 2,
  1770. (self, that) => new ContextPatch_AndThen(self, that)
  1771. ),
  1772. ContextPatch_patch = Function_dual(2, (self, context) => {
  1773. let wasServiceUpdated = !1,
  1774. patches = Chunk_of(self)
  1775. const updatedContext = new Map(context.unsafeMap)
  1776. for (; Chunk_isNonEmpty(patches); ) {
  1777. const head = Chunk_headNonEmpty(patches),
  1778. tail = Chunk_tailNonEmpty(patches)
  1779. switch (head._tag) {
  1780. case "Empty":
  1781. patches = tail
  1782. break
  1783. case "AddService":
  1784. updatedContext.set(head.tag, head.service)
  1785. patches = tail
  1786. break
  1787. case "AndThen":
  1788. patches = Chunk_prepend(
  1789. Chunk_prepend(tail, head.second),
  1790. head.first
  1791. )
  1792. break
  1793. case "RemoveService":
  1794. updatedContext.delete(head.tag)
  1795. patches = tail
  1796. break
  1797. case "UpdateService":
  1798. updatedContext.set(
  1799. head.tag,
  1800. head.update(updatedContext.get(head.tag))
  1801. )
  1802. wasServiceUpdated = !0
  1803. patches = tail
  1804. }
  1805. }
  1806. if (!wasServiceUpdated) return new ContextImpl(updatedContext)
  1807. const map = new Map()
  1808. for (const [tag] of context.unsafeMap)
  1809. if (updatedContext.has(tag)) {
  1810. map.set(tag, updatedContext.get(tag))
  1811. updatedContext.delete(tag)
  1812. }
  1813. for (const [tag, s] of updatedContext) map.set(tag, s)
  1814. return new ContextImpl(map)
  1815. }),
  1816. Differ_ContextPatch_empty = ContextPatch_empty,
  1817. Differ_ContextPatch_combine = ContextPatch_combine,
  1818. Differ_ContextPatch_patch = ContextPatch_patch,
  1819. BUCKET_SIZE = Math.pow(2, 5),
  1820. MASK = BUCKET_SIZE - 1,
  1821. MAX_INDEX_NODE = BUCKET_SIZE / 2,
  1822. MIN_ARRAY_NODE = BUCKET_SIZE / 4
  1823. function hashFragment(shift, h) {
  1824. return (h >>> shift) & MASK
  1825. }
  1826. function toBitmap(x) {
  1827. return 1 << x
  1828. }
  1829. function fromBitmap(bitmap, bit) {
  1830. return (function (x) {
  1831. x =
  1832. ((x =
  1833. (858993459 & (x -= (x >> 1) & 1431655765)) +
  1834. ((x >> 2) & 858993459)) +
  1835. (x >> 4)) &
  1836. 252645135
  1837. return 127 & ((x += x >> 8) + (x >> 16))
  1838. })(bitmap & (bit - 1))
  1839. }
  1840. function arrayUpdate(mutate, at, v, arr) {
  1841. let out = arr
  1842. if (!mutate) {
  1843. const len = arr.length
  1844. out = new Array(len)
  1845. for (let i = 0; i < len; ++i) out[i] = arr[i]
  1846. }
  1847. out[at] = v
  1848. return out
  1849. }
  1850. function arraySpliceOut(mutate, at, arr) {
  1851. const newLen = arr.length - 1
  1852. let i = 0,
  1853. g = 0,
  1854. out = arr
  1855. if (mutate) i = g = at
  1856. else {
  1857. out = new Array(newLen)
  1858. for (; i < at; ) out[g++] = arr[i++]
  1859. }
  1860. ++i
  1861. for (; i <= newLen; ) out[g++] = arr[i++]
  1862. mutate && (out.length = newLen)
  1863. return out
  1864. }
  1865. class Stack {
  1866. constructor(value, previous) {
  1867. this.value = value
  1868. this.previous = previous
  1869. }
  1870. }
  1871. class EmptyNode {
  1872. constructor() {
  1873. this._tag = "EmptyNode"
  1874. }
  1875. modify(edit, _shift, f, hash, key, size) {
  1876. const v = f(Option_none())
  1877. if (Option_isNone(v)) return new EmptyNode()
  1878. ++size.value
  1879. return new LeafNode(edit, hash, key, v)
  1880. }
  1881. }
  1882. function isEmptyNode(a) {
  1883. return a instanceof EmptyNode
  1884. }
  1885. function canEditNode(node, edit) {
  1886. return !isEmptyNode(node) && edit === node.edit
  1887. }
  1888. class LeafNode {
  1889. constructor(edit, hash, key, value) {
  1890. this.edit = edit
  1891. this.hash = hash
  1892. this.key = key
  1893. this.value = value
  1894. this._tag = "LeafNode"
  1895. }
  1896. modify(edit, shift, f, hash, key, size) {
  1897. if (equals(key, this.key)) {
  1898. const v = f(this.value)
  1899. if (v === this.value) return this
  1900. if (Option_isNone(v)) {
  1901. --size.value
  1902. return new EmptyNode()
  1903. }
  1904. if (canEditNode(this, edit)) {
  1905. this.value = v
  1906. return this
  1907. }
  1908. return new LeafNode(edit, hash, key, v)
  1909. }
  1910. const v = f(Option_none())
  1911. if (Option_isNone(v)) return this
  1912. ++size.value
  1913. return mergeLeaves(
  1914. edit,
  1915. shift,
  1916. this.hash,
  1917. this,
  1918. hash,
  1919. new LeafNode(edit, hash, key, v)
  1920. )
  1921. }
  1922. }
  1923. class CollisionNode {
  1924. constructor(edit, hash, children) {
  1925. this.edit = edit
  1926. this.hash = hash
  1927. this.children = children
  1928. this._tag = "CollisionNode"
  1929. }
  1930. modify(edit, shift, f, hash, key, size) {
  1931. if (hash === this.hash) {
  1932. const canEdit = canEditNode(this, edit),
  1933. list = this.updateCollisionList(
  1934. canEdit,
  1935. edit,
  1936. this.hash,
  1937. this.children,
  1938. f,
  1939. key,
  1940. size
  1941. )
  1942. return list === this.children
  1943. ? this
  1944. : list.length > 1
  1945. ? new CollisionNode(edit, this.hash, list)
  1946. : list[0]
  1947. }
  1948. const v = f(Option_none())
  1949. if (Option_isNone(v)) return this
  1950. ++size.value
  1951. return mergeLeaves(
  1952. edit,
  1953. shift,
  1954. this.hash,
  1955. this,
  1956. hash,
  1957. new LeafNode(edit, hash, key, v)
  1958. )
  1959. }
  1960. updateCollisionList(mutate, edit, hash, list, f, key, size) {
  1961. const len = list.length
  1962. for (let i = 0; i < len; ++i) {
  1963. const child = list[i]
  1964. if ("key" in child && equals(key, child.key)) {
  1965. const value = child.value,
  1966. newValue = f(value)
  1967. if (newValue === value) return list
  1968. if (Option_isNone(newValue)) {
  1969. --size.value
  1970. return arraySpliceOut(mutate, i, list)
  1971. }
  1972. return arrayUpdate(
  1973. mutate,
  1974. i,
  1975. new LeafNode(edit, hash, key, newValue),
  1976. list
  1977. )
  1978. }
  1979. }
  1980. const newValue = f(Option_none())
  1981. if (Option_isNone(newValue)) return list
  1982. ++size.value
  1983. return arrayUpdate(
  1984. mutate,
  1985. len,
  1986. new LeafNode(edit, hash, key, newValue),
  1987. list
  1988. )
  1989. }
  1990. }
  1991. class IndexedNode {
  1992. constructor(edit, mask, children) {
  1993. this.edit = edit
  1994. this.mask = mask
  1995. this.children = children
  1996. this._tag = "IndexedNode"
  1997. }
  1998. modify(edit, shift, f, hash, key, size) {
  1999. const mask = this.mask,
  2000. children = this.children,
  2001. frag = hashFragment(shift, hash),
  2002. bit = toBitmap(frag),
  2003. indx = fromBitmap(mask, bit),
  2004. exists = mask & bit,
  2005. canEdit = canEditNode(this, edit)
  2006. if (!exists) {
  2007. const _newChild = new EmptyNode().modify(
  2008. edit,
  2009. shift + 5,
  2010. f,
  2011. hash,
  2012. key,
  2013. size
  2014. )
  2015. return _newChild
  2016. ? children.length >= MAX_INDEX_NODE
  2017. ? (function (edit, frag, child, bitmap, subNodes) {
  2018. const arr = []
  2019. let bit = bitmap,
  2020. count = 0
  2021. for (let i = 0; bit; ++i) {
  2022. 1 & bit && (arr[i] = subNodes[count++])
  2023. bit >>>= 1
  2024. }
  2025. arr[frag] = child
  2026. return new ArrayNode(edit, count + 1, arr)
  2027. })(edit, frag, _newChild, mask, children)
  2028. : new IndexedNode(
  2029. edit,
  2030. mask | bit,
  2031. (function (mutate, at, v, arr) {
  2032. const len = arr.length
  2033. if (mutate) {
  2034. let i = len
  2035. for (; i >= at; ) arr[i--] = arr[i]
  2036. arr[at] = v
  2037. return arr
  2038. }
  2039. let i = 0,
  2040. g = 0
  2041. const out = new Array(len + 1)
  2042. for (; i < at; ) out[g++] = arr[i++]
  2043. out[at] = v
  2044. for (; i < len; ) out[++g] = arr[i++]
  2045. return out
  2046. })(canEdit, indx, _newChild, children)
  2047. )
  2048. : this
  2049. }
  2050. const current = children[indx],
  2051. child = current.modify(edit, shift + 5, f, hash, key, size)
  2052. if (current === child) return this
  2053. let newChildren,
  2054. bitmap = mask
  2055. if (isEmptyNode(child)) {
  2056. bitmap &= ~bit
  2057. if (!bitmap) return new EmptyNode()
  2058. if (
  2059. children.length <= 2 &&
  2060. (isEmptyNode((node = children[1 ^ indx])) ||
  2061. "LeafNode" === node._tag ||
  2062. "CollisionNode" === node._tag)
  2063. )
  2064. return children[1 ^ indx]
  2065. newChildren = arraySpliceOut(canEdit, indx, children)
  2066. } else newChildren = arrayUpdate(canEdit, indx, child, children)
  2067. var node
  2068. if (canEdit) {
  2069. this.mask = bitmap
  2070. this.children = newChildren
  2071. return this
  2072. }
  2073. return new IndexedNode(edit, bitmap, newChildren)
  2074. }
  2075. }
  2076. class ArrayNode {
  2077. constructor(edit, size, children) {
  2078. this.edit = edit
  2079. this.size = size
  2080. this.children = children
  2081. this._tag = "ArrayNode"
  2082. }
  2083. modify(edit, shift, f, hash, key, size) {
  2084. let count = this.size
  2085. const children = this.children,
  2086. frag = hashFragment(shift, hash),
  2087. child = children[frag],
  2088. newChild = (child || new EmptyNode()).modify(
  2089. edit,
  2090. shift + 5,
  2091. f,
  2092. hash,
  2093. key,
  2094. size
  2095. )
  2096. if (child === newChild) return this
  2097. const canEdit = canEditNode(this, edit)
  2098. let newChildren
  2099. if (isEmptyNode(child) && !isEmptyNode(newChild)) {
  2100. ++count
  2101. newChildren = arrayUpdate(canEdit, frag, newChild, children)
  2102. } else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
  2103. --count
  2104. if (count <= MIN_ARRAY_NODE)
  2105. return (function (edit, count, removed, elements) {
  2106. const children = new Array(count - 1)
  2107. let g = 0,
  2108. bitmap = 0
  2109. for (let i = 0, len = elements.length; i < len; ++i)
  2110. if (i !== removed) {
  2111. const elem = elements[i]
  2112. if (elem && !isEmptyNode(elem)) {
  2113. children[g++] = elem
  2114. bitmap |= 1 << i
  2115. }
  2116. }
  2117. return new IndexedNode(edit, bitmap, children)
  2118. })(edit, count, frag, children)
  2119. newChildren = arrayUpdate(canEdit, frag, new EmptyNode(), children)
  2120. } else newChildren = arrayUpdate(canEdit, frag, newChild, children)
  2121. if (canEdit) {
  2122. this.size = count
  2123. this.children = newChildren
  2124. return this
  2125. }
  2126. return new ArrayNode(edit, count, newChildren)
  2127. }
  2128. }
  2129. function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
  2130. if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1])
  2131. const subH1 = hashFragment(shift, h1),
  2132. subH2 = hashFragment(shift, h2)
  2133. if (subH1 === subH2)
  2134. return child =>
  2135. new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child])
  2136. {
  2137. const children = subH1 < subH2 ? [n1, n2] : [n2, n1]
  2138. return new IndexedNode(
  2139. edit,
  2140. toBitmap(subH1) | toBitmap(subH2),
  2141. children
  2142. )
  2143. }
  2144. }
  2145. function mergeLeaves(edit, shift, h1, n1, h2, n2) {
  2146. let stack,
  2147. currentShift = shift
  2148. for (;;) {
  2149. const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2)
  2150. if ("function" != typeof res) {
  2151. let final = res
  2152. for (; null != stack; ) {
  2153. final = stack.value(final)
  2154. stack = stack.previous
  2155. }
  2156. return final
  2157. }
  2158. stack = new Stack(res, stack)
  2159. currentShift += 5
  2160. }
  2161. }
  2162. const HashMapTypeId = Symbol.for("@effect/data/HashMap")
  2163. class HashMapImpl {
  2164. constructor(_editable, _edit, _root, _size) {
  2165. this._editable = _editable
  2166. this._edit = _edit
  2167. this._root = _root
  2168. this._size = _size
  2169. this._id = HashMapTypeId
  2170. }
  2171. [Symbol.iterator]() {
  2172. return new HashMapIterator(this, (k, v) => [k, v])
  2173. }
  2174. [symbol]() {
  2175. let hash = Hash_hash("HashMap")
  2176. for (const item of this)
  2177. hash ^= combine(Hash_hash(item[0]))(Hash_hash(item[1]))
  2178. return hash
  2179. }
  2180. [Equal_symbol](that) {
  2181. if (isHashMap(that)) {
  2182. if (that._size !== this._size) return !1
  2183. for (const item of this) {
  2184. const elem = getHash(item[0], Hash_hash(item[0]))(that)
  2185. if (Option_isNone(elem)) return !1
  2186. if (!equals(item[1], elem.value)) return !1
  2187. }
  2188. return !0
  2189. }
  2190. return !1
  2191. }
  2192. toString() {
  2193. return `HashMap(${Array.from(this)
  2194. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  2195. .join(", ")})`
  2196. }
  2197. toJSON() {
  2198. return { _tag: "HashMap", values: Array.from(this) }
  2199. }
  2200. [Symbol.for("nodejs.util.inspect.custom")]() {
  2201. return this.toJSON()
  2202. }
  2203. }
  2204. class HashMapIterator {
  2205. constructor(map, f) {
  2206. this.map = map
  2207. this.f = f
  2208. this.v = visitLazy(this.map._root, this.f, void 0)
  2209. }
  2210. next() {
  2211. if (Option_isNone(this.v)) return { done: !0, value: void 0 }
  2212. const v0 = this.v.value
  2213. this.v = applyCont(v0.cont)
  2214. return { done: !1, value: v0.value }
  2215. }
  2216. [Symbol.iterator]() {
  2217. return new HashMapIterator(this.map, this.f)
  2218. }
  2219. }
  2220. const applyCont = cont =>
  2221. cont
  2222. ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4])
  2223. : Option_none(),
  2224. visitLazy = (node, f, cont) => {
  2225. switch (node._tag) {
  2226. case "LeafNode":
  2227. return Option_isSome(node.value)
  2228. ? Option_some({ value: f(node.key, node.value.value), cont })
  2229. : applyCont(cont)
  2230. case "CollisionNode":
  2231. case "ArrayNode":
  2232. case "IndexedNode": {
  2233. const children = node.children
  2234. return visitLazyChildren(children.length, children, 0, f, cont)
  2235. }
  2236. default:
  2237. return applyCont(cont)
  2238. }
  2239. },
  2240. visitLazyChildren = (len, children, i, f, cont) => {
  2241. for (; i < len; ) {
  2242. const child = children[i++]
  2243. if (child && !isEmptyNode(child))
  2244. return visitLazy(child, f, [len, children, i, f, cont])
  2245. }
  2246. return applyCont(cont)
  2247. },
  2248. HashMap_empty = () => new HashMapImpl(!1, 0, new EmptyNode(), 0),
  2249. isHashMap = u =>
  2250. "object" == typeof u &&
  2251. null != u &&
  2252. "_id" in u &&
  2253. u._id === HashMapTypeId,
  2254. HashMap_get = Function_dual(2, (self, key) =>
  2255. getHash(self, key, Hash_hash(key))
  2256. ),
  2257. getHash = Function_dual(3, (self, key, hash) => {
  2258. let node = self._root,
  2259. shift = 0
  2260. for (;;)
  2261. switch (node._tag) {
  2262. case "LeafNode":
  2263. return equals(key, node.key) ? node.value : Option_none()
  2264. case "CollisionNode":
  2265. if (hash === node.hash) {
  2266. const children = node.children
  2267. for (let i = 0, len = children.length; i < len; ++i) {
  2268. const child = children[i]
  2269. if ("key" in child && equals(key, child.key))
  2270. return child.value
  2271. }
  2272. }
  2273. return Option_none()
  2274. case "IndexedNode": {
  2275. const bit = toBitmap(hashFragment(shift, hash))
  2276. if (node.mask & bit) {
  2277. node = node.children[fromBitmap(node.mask, bit)]
  2278. shift += 5
  2279. break
  2280. }
  2281. return Option_none()
  2282. }
  2283. case "ArrayNode":
  2284. node = node.children[hashFragment(shift, hash)]
  2285. if (node) {
  2286. shift += 5
  2287. break
  2288. }
  2289. return Option_none()
  2290. default:
  2291. return Option_none()
  2292. }
  2293. }),
  2294. HashMap_has = Function_dual(2, (self, key) =>
  2295. Option_isSome(getHash(self, key, Hash_hash(key)))
  2296. ),
  2297. set = Function_dual(3, (self, key, value) =>
  2298. modifyAt(self, key, () => Option_some(value))
  2299. ),
  2300. setTree = Function_dual(3, (self, newRoot, newSize) => {
  2301. if (self._editable) {
  2302. self._root = newRoot
  2303. self._size = newSize
  2304. return self
  2305. }
  2306. return newRoot === self._root
  2307. ? self
  2308. : new HashMapImpl(self._editable, self._edit, newRoot, newSize)
  2309. }),
  2310. HashMap_size = self => self._size,
  2311. beginMutation = self =>
  2312. new HashMapImpl(!0, self._edit + 1, self._root, self._size),
  2313. endMutation = self => {
  2314. self._editable = !1
  2315. return self
  2316. },
  2317. modifyAt = Function_dual(3, (self, key, f) =>
  2318. modifyHash(self, key, Hash_hash(key), f)
  2319. ),
  2320. modifyHash = Function_dual(4, (self, key, hash, f) => {
  2321. const size = { value: self._size },
  2322. newRoot = self._root.modify(
  2323. self._editable ? self._edit : NaN,
  2324. 0,
  2325. f,
  2326. hash,
  2327. key,
  2328. size
  2329. )
  2330. return setTree(newRoot, size.value)(self)
  2331. }),
  2332. HashMap_remove = Function_dual(2, (self, key) =>
  2333. modifyAt(self, key, Option_none)
  2334. ),
  2335. forEachWithIndex = Function_dual(2, (self, f) =>
  2336. HashMap_reduceWithIndex(self, void 0, (_, value, key) => f(value, key))
  2337. ),
  2338. HashMap_reduceWithIndex = Function_dual(3, (self, zero, f) => {
  2339. const root = self._root
  2340. if ("LeafNode" === root._tag)
  2341. return Option_isSome(root.value)
  2342. ? f(zero, root.value.value, root.key)
  2343. : zero
  2344. if ("EmptyNode" === root._tag) return zero
  2345. const toVisit = [root.children]
  2346. let children
  2347. for (; (children = toVisit.pop()); )
  2348. for (let i = 0, len = children.length; i < len; ) {
  2349. const child = children[i++]
  2350. child &&
  2351. !isEmptyNode(child) &&
  2352. ("LeafNode" === child._tag
  2353. ? Option_isSome(child.value) &&
  2354. (zero = f(zero, child.value.value, child.key))
  2355. : toVisit.push(child.children))
  2356. }
  2357. return zero
  2358. }),
  2359. HashSetTypeId = Symbol.for("@effect/data/HashSet")
  2360. class HashSetImpl {
  2361. constructor(_keyMap) {
  2362. this._keyMap = _keyMap
  2363. this._id = HashSetTypeId
  2364. }
  2365. [Symbol.iterator]() {
  2366. return (self => new HashMapIterator(self, key => key))(this._keyMap)
  2367. }
  2368. [symbol]() {
  2369. return combine(Hash_hash(this._keyMap))(Hash_hash("HashSet"))
  2370. }
  2371. [Equal_symbol](that) {
  2372. return (
  2373. !!isHashSet(that) &&
  2374. HashMap_size(this._keyMap) === HashMap_size(that._keyMap) &&
  2375. equals(this._keyMap, that._keyMap)
  2376. )
  2377. }
  2378. toString() {
  2379. return `HashSet(${Array.from(this).map(String).join(", ")})`
  2380. }
  2381. toJSON() {
  2382. return { _tag: "HashSet", values: Array.from(this) }
  2383. }
  2384. [Symbol.for("nodejs.util.inspect.custom")]() {
  2385. return this.toJSON()
  2386. }
  2387. }
  2388. const isHashSet = u =>
  2389. "object" == typeof u &&
  2390. null != u &&
  2391. "_id" in u &&
  2392. u._id === HashSetTypeId,
  2393. HashSet_empty = () => new HashSetImpl(HashMap_empty()),
  2394. HashSet_has = Function_dual(2, (self, value) =>
  2395. HashMap_has(self._keyMap, value)
  2396. ),
  2397. HashSet_beginMutation = self =>
  2398. new HashSetImpl(beginMutation(self._keyMap)),
  2399. HashSet_endMutation = self => {
  2400. self._keyMap._editable = !1
  2401. return self
  2402. },
  2403. HashSet_mutate = Function_dual(2, (self, f) => {
  2404. const transient = HashSet_beginMutation(self)
  2405. f(transient)
  2406. return HashSet_endMutation(transient)
  2407. }),
  2408. HashSet_add = Function_dual(2, (self, value) =>
  2409. self._keyMap._editable
  2410. ? (set(value, !0)(self._keyMap), self)
  2411. : new HashSetImpl(set(value, !0)(self._keyMap))
  2412. ),
  2413. HashSet_remove = Function_dual(2, (self, value) =>
  2414. self._keyMap._editable
  2415. ? (HashMap_remove(value)(self._keyMap), self)
  2416. : new HashSetImpl(HashMap_remove(value)(self._keyMap))
  2417. ),
  2418. HashSet_difference = Function_dual(2, (self, that) =>
  2419. HashSet_mutate(self, set => {
  2420. for (const value of that) HashSet_remove(set, value)
  2421. })
  2422. ),
  2423. HashSet_union = Function_dual(2, (self, that) =>
  2424. HashSet_mutate(HashSet_empty(), set => {
  2425. HashSet_forEach(self, value => HashSet_add(set, value))
  2426. for (const value of that) HashSet_add(set, value)
  2427. })
  2428. ),
  2429. HashSet_forEach = Function_dual(2, (self, f) =>
  2430. forEachWithIndex(self._keyMap, (_, k) => f(k))
  2431. ),
  2432. HashSet_reduce = Function_dual(3, (self, zero, f) =>
  2433. HashMap_reduceWithIndex(self._keyMap, zero, (z, _, a) => f(z, a))
  2434. ),
  2435. mjs_HashMap_empty = HashMap_empty,
  2436. mjs_HashMap_fromIterable = entries => {
  2437. const map = beginMutation(HashMap_empty())
  2438. for (const entry of entries) set(entry[0], entry[1])(map)
  2439. return endMutation(map)
  2440. },
  2441. mjs_HashMap_get = HashMap_get,
  2442. HashMap_set = set,
  2443. mjs_HashMap_size = HashMap_size,
  2444. mjs_HashSet_empty = HashSet_empty,
  2445. mjs_HashSet_make = (...elements) => {
  2446. const set = HashSet_beginMutation(HashSet_empty())
  2447. for (const value of elements) HashSet_add(set, value)
  2448. return HashSet_endMutation(set)
  2449. },
  2450. mjs_HashSet_has = HashSet_has,
  2451. mjs_HashSet_size = self => HashMap_size(self._keyMap),
  2452. mjs_HashSet_add = HashSet_add,
  2453. mjs_HashSet_remove = HashSet_remove,
  2454. mjs_HashSet_difference = HashSet_difference,
  2455. mjs_HashSet_union = HashSet_union,
  2456. mjs_HashSet_forEach = HashSet_forEach,
  2457. mjs_HashSet_reduce = HashSet_reduce,
  2458. HashSetPatchTypeId = Symbol.for("@effect/data/Differ/HashSetPatch")
  2459. function HashSetPatch_variance(a) {
  2460. return a
  2461. }
  2462. class HashSetPatch_Empty {
  2463. constructor() {
  2464. this._tag = "Empty"
  2465. this._Value = HashSetPatch_variance
  2466. this._id = HashSetPatchTypeId
  2467. }
  2468. [symbol]() {
  2469. return string("HashSetPatch(Empty)")
  2470. }
  2471. [Equal_symbol](that) {
  2472. return (
  2473. "object" == typeof that &&
  2474. null !== that &&
  2475. "_id" in that &&
  2476. that._id === this._id &&
  2477. "_tag" in that &&
  2478. that._tag === this._id
  2479. )
  2480. }
  2481. }
  2482. class HashSetPatch_AndThen {
  2483. constructor(first, second) {
  2484. this.first = first
  2485. this.second = second
  2486. this._tag = "AndThen"
  2487. this._Value = HashSetPatch_variance
  2488. this._id = HashSetPatchTypeId
  2489. }
  2490. [symbol]() {
  2491. return string("HashSetPatch(AndThen)")
  2492. }
  2493. [Equal_symbol](that) {
  2494. return (
  2495. "object" == typeof that &&
  2496. null !== that &&
  2497. "_id" in that &&
  2498. that._id === this._id &&
  2499. "_tag" in that &&
  2500. that._tag === this._id &&
  2501. equals(this.first, that.first) &&
  2502. equals(this.second, that.second)
  2503. )
  2504. }
  2505. }
  2506. class HashSetPatch_Add {
  2507. constructor(value) {
  2508. this.value = value
  2509. this._tag = "Add"
  2510. this._Value = HashSetPatch_variance
  2511. this._id = HashSetPatchTypeId
  2512. }
  2513. [symbol]() {
  2514. return string("HashSetPatch(Add)")
  2515. }
  2516. [Equal_symbol](that) {
  2517. return (
  2518. "object" == typeof that &&
  2519. null !== that &&
  2520. "_id" in that &&
  2521. that._id === this._id &&
  2522. "_tag" in that &&
  2523. that._tag === this._id &&
  2524. equals(this.value, that.value)
  2525. )
  2526. }
  2527. }
  2528. class HashSetPatch_Remove {
  2529. constructor(value) {
  2530. this.value = value
  2531. this._tag = "Remove"
  2532. this._Value = HashSetPatch_variance
  2533. this._id = HashSetPatchTypeId
  2534. }
  2535. [symbol]() {
  2536. return string("HashSetPatch(Remove)")
  2537. }
  2538. [Equal_symbol](that) {
  2539. return (
  2540. "object" == typeof that &&
  2541. null !== that &&
  2542. "_id" in that &&
  2543. that._id === this._id &&
  2544. "_tag" in that &&
  2545. that._tag === this._id &&
  2546. equals(this.value, that.value)
  2547. )
  2548. }
  2549. }
  2550. const HashSetPatch_empty = () => new HashSetPatch_Empty(),
  2551. HashSetPatch_combine = Function_dual(
  2552. 2,
  2553. (self, that) => new HashSetPatch_AndThen(self, that)
  2554. ),
  2555. HashSetPatch_patch = Function_dual(2, (self, oldValue) => {
  2556. let set = oldValue,
  2557. patches = Chunk_of(self)
  2558. for (; Chunk_isNonEmpty(patches); ) {
  2559. const head = Chunk_headNonEmpty(patches),
  2560. tail = Chunk_tailNonEmpty(patches)
  2561. switch (head._tag) {
  2562. case "Empty":
  2563. patches = tail
  2564. break
  2565. case "AndThen":
  2566. patches = Chunk_prepend(head.first)(
  2567. Chunk_prepend(head.second)(tail)
  2568. )
  2569. break
  2570. case "Add":
  2571. set = mjs_HashSet_add(head.value)(set)
  2572. patches = tail
  2573. break
  2574. case "Remove":
  2575. set = mjs_HashSet_remove(head.value)(set)
  2576. patches = tail
  2577. }
  2578. }
  2579. return set
  2580. }),
  2581. Differ_HashSetPatch_empty = HashSetPatch_empty,
  2582. Differ_HashSetPatch_combine = HashSetPatch_combine,
  2583. Differ_HashSetPatch_patch = HashSetPatch_patch,
  2584. DifferTypeId = Symbol.for("@effect/data/Differ")
  2585. class DifferImpl {
  2586. constructor(params) {
  2587. this._id = DifferTypeId
  2588. this._P = Function_identity
  2589. this._V = Function_identity
  2590. this.empty = params.empty
  2591. this.diff = params.diff
  2592. this.combine = params.combine
  2593. this.patch = params.patch
  2594. }
  2595. }
  2596. const Differ_make = params => new DifferImpl(params),
  2597. Differ_diff = Function_dual(3, (self, oldValue, newValue) =>
  2598. self.diff(oldValue, newValue)
  2599. ),
  2600. Differ_combine = Function_dual(3, (self, first, second) =>
  2601. self.combine(first, second)
  2602. ),
  2603. Differ_patch = Function_dual(3, (self, patch, oldValue) =>
  2604. self.patch(patch, oldValue)
  2605. ),
  2606. mjs_Differ_make = Differ_make,
  2607. Differ_environment = () =>
  2608. Differ_make({
  2609. empty: Differ_ContextPatch_empty(),
  2610. combine: (first, second) =>
  2611. Differ_ContextPatch_combine(second)(first),
  2612. diff: (oldValue, newValue) =>
  2613. ((oldValue, newValue) => {
  2614. const missingServices = new Map(oldValue.unsafeMap)
  2615. let patch = ContextPatch_empty()
  2616. for (const [tag, newService] of newValue.unsafeMap.entries())
  2617. if (missingServices.has(tag)) {
  2618. const old = missingServices.get(tag)
  2619. missingServices.delete(tag)
  2620. equals(old, newService) ||
  2621. (patch = ContextPatch_combine(
  2622. new UpdateService(tag, () => newService)
  2623. )(patch))
  2624. } else {
  2625. missingServices.delete(tag)
  2626. patch = ContextPatch_combine(new AddService(tag, newService))(
  2627. patch
  2628. )
  2629. }
  2630. for (const [tag] of missingServices.entries())
  2631. patch = ContextPatch_combine(new RemoveService(tag))(patch)
  2632. return patch
  2633. })(oldValue, newValue),
  2634. patch: (patch, oldValue) =>
  2635. Differ_ContextPatch_patch(oldValue)(patch),
  2636. }),
  2637. Differ_hashSet = () =>
  2638. Differ_make({
  2639. empty: Differ_HashSetPatch_empty(),
  2640. combine: (first, second) =>
  2641. Differ_HashSetPatch_combine(second)(first),
  2642. diff: (oldValue, newValue) =>
  2643. ((oldValue, newValue) => {
  2644. const [removed, patch] = mjs_HashSet_reduce(
  2645. [oldValue, HashSetPatch_empty()],
  2646. ([set, patch], value) =>
  2647. mjs_HashSet_has(value)(set)
  2648. ? [mjs_HashSet_remove(value)(set), patch]
  2649. : [
  2650. set,
  2651. HashSetPatch_combine(new HashSetPatch_Add(value))(
  2652. patch
  2653. ),
  2654. ]
  2655. )(newValue)
  2656. return mjs_HashSet_reduce(patch, (patch, value) =>
  2657. HashSetPatch_combine(new HashSetPatch_Remove(value))(patch)
  2658. )(removed)
  2659. })(oldValue, newValue),
  2660. patch: (patch, oldValue) =>
  2661. Differ_HashSetPatch_patch(oldValue)(patch),
  2662. }),
  2663. Differ_update = () => {
  2664. return (
  2665. (f = (_, a) => a),
  2666. Differ_make({
  2667. empty: Function_identity,
  2668. combine: (first, second) =>
  2669. first === Function_identity
  2670. ? second
  2671. : second === Function_identity
  2672. ? first
  2673. : a => second(first(a)),
  2674. diff: (oldValue, newValue) =>
  2675. equals(oldValue, newValue)
  2676. ? Function_identity
  2677. : constant(newValue),
  2678. patch: (patch, oldValue) => f(oldValue, patch(oldValue)),
  2679. })
  2680. )
  2681. var f
  2682. },
  2683. MutableRef_TypeId = Symbol.for("@effect/data/MutableRef")
  2684. class MutableRefImpl {
  2685. constructor(current) {
  2686. this.current = current
  2687. this._T = _ => _
  2688. this._id = MutableRef_TypeId
  2689. }
  2690. toString() {
  2691. return `MutableRef(${String(this.current)})`
  2692. }
  2693. toJSON() {
  2694. return { _tag: "MutableRef", current: this.current }
  2695. }
  2696. [Symbol.for("nodejs.util.inspect.custom")]() {
  2697. return this.toJSON()
  2698. }
  2699. }
  2700. const MutableRef_make = value => new MutableRefImpl(value),
  2701. MutableRef_get = self => self.current,
  2702. getAndSet = Function_dual(2, (self, value) => {
  2703. const ret = self.current
  2704. self.current = value
  2705. return ret
  2706. }),
  2707. getAndUpdate = Function_dual(2, (self, f) =>
  2708. getAndSet(self, f(MutableRef_get(self)))
  2709. ),
  2710. MutableRef_set = Function_dual(2, (self, value) => {
  2711. self.current = value
  2712. return self
  2713. }),
  2714. MutableRef_update = Function_dual(2, (self, f) =>
  2715. MutableRef_set(self, f(MutableRef_get(self)))
  2716. )
  2717. var fiberId_a, _b
  2718. const FiberIdTypeId = Symbol.for("@effect/io/Fiber/Id")
  2719. class None {
  2720. constructor() {
  2721. this[fiberId_a] = FiberIdTypeId
  2722. this._tag = "None"
  2723. }
  2724. [((fiberId_a = FiberIdTypeId), symbol)]() {
  2725. return combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Id"))
  2726. }
  2727. [Equal_symbol](that) {
  2728. return isFiberId(that) && "None" === that._tag
  2729. }
  2730. }
  2731. class Runtime {
  2732. constructor(id, startTimeMillis) {
  2733. this.id = id
  2734. this.startTimeMillis = startTimeMillis
  2735. this[_b] = FiberIdTypeId
  2736. this._tag = "Runtime"
  2737. }
  2738. [((_b = FiberIdTypeId), symbol)]() {
  2739. return combine(Hash_hash(this.startTimeMillis))(
  2740. combine(Hash_hash(this.id))(
  2741. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Id"))
  2742. )
  2743. )
  2744. }
  2745. [Equal_symbol](that) {
  2746. return (
  2747. isFiberId(that) &&
  2748. "Runtime" === that._tag &&
  2749. this.id === that.id &&
  2750. this.startTimeMillis === that.startTimeMillis
  2751. )
  2752. }
  2753. }
  2754. const fiberId_none = new None(),
  2755. isFiberId = self =>
  2756. "object" == typeof self && null != self && FiberIdTypeId in self,
  2757. ids = self => {
  2758. switch (self._tag) {
  2759. case "None":
  2760. return mjs_HashSet_empty()
  2761. case "Runtime":
  2762. return mjs_HashSet_make(self.id)
  2763. case "Composite":
  2764. return mjs_HashSet_union(ids(self.right))(ids(self.left))
  2765. }
  2766. },
  2767. _fiberCounter = globalValue(
  2768. Symbol.for("@effect/io/Fiber/Id/_fiberCounter"),
  2769. () => MutableRef_make(0)
  2770. ),
  2771. threadName = self =>
  2772. Array.from(ids(self))
  2773. .map(n => `#${n}`)
  2774. .join(","),
  2775. Id_none = fiberId_none,
  2776. Id_unsafeMake = () => {
  2777. const id = MutableRef_get(_fiberCounter)
  2778. MutableRef_set(id + 1)(_fiberCounter)
  2779. return new Runtime(id, new Date().getTime())
  2780. },
  2781. active = patch => 255 & patch,
  2782. enabled = patch => (patch >> 8) & 255,
  2783. runtimeFlagsPatch_make = (active, enabled) =>
  2784. (255 & active) + ((enabled & active & 255) << 8),
  2785. runtimeFlagsPatch_empty = runtimeFlagsPatch_make(0, 0),
  2786. exclude = Function_dual(2, (self, flag) =>
  2787. runtimeFlagsPatch_make(active(self) & ~flag, enabled(self))
  2788. ),
  2789. runtimeFlagsPatch_andThen = Function_dual(2, (self, that) => self | that),
  2790. cooperativeYielding = self => runtimeFlags_isEnabled(self, 32),
  2791. runtimeFlags_enable = Function_dual(2, (self, flag) => self | flag),
  2792. interruptible = self => interruption(self) && !windDown(self),
  2793. interruption = self => runtimeFlags_isEnabled(self, 1),
  2794. runtimeFlags_isEnabled = Function_dual(
  2795. 2,
  2796. (self, flag) => 0 != (self & flag)
  2797. ),
  2798. runtimeFlags_make = (...flags) => flags.reduce((a, b) => a | b, 0),
  2799. runtimeFlags_none = runtimeFlags_make(0),
  2800. opSupervision = self => runtimeFlags_isEnabled(self, 2),
  2801. runtimeMetrics = self => runtimeFlags_isEnabled(self, 4),
  2802. windDown = self => runtimeFlags_isEnabled(self, 16),
  2803. runtimeFlags_diff = Function_dual(2, (self, that) =>
  2804. runtimeFlagsPatch_make(self ^ that, that)
  2805. ),
  2806. runtimeFlags_patch = Function_dual(
  2807. 2,
  2808. (self, patch) =>
  2809. (self & (((~active(patch) >>> 0) & 255) | enabled(patch))) |
  2810. (active(patch) & enabled(patch))
  2811. ),
  2812. Patch_empty = runtimeFlagsPatch_empty,
  2813. Patch_disable = flag => runtimeFlagsPatch_make(flag, 0),
  2814. Patch_exclude = exclude
  2815. var cause_a
  2816. const CauseTypeId = Symbol.for("@effect/io/Cause"),
  2817. proto = {
  2818. [CauseTypeId]: { _E: _ => _ },
  2819. [symbol]() {
  2820. return combine(Hash_hash(flattenCause(this)))(
  2821. Hash_hash("@effect/io/Cause")
  2822. )
  2823. },
  2824. [Equal_symbol](that) {
  2825. return isCause(that) && causeEquals(this, that)
  2826. },
  2827. },
  2828. cause_empty = (() => {
  2829. const o = Object.create(proto)
  2830. o._tag = "Empty"
  2831. return o
  2832. })(),
  2833. fail = error => {
  2834. const o = Object.create(proto)
  2835. o._tag = "Fail"
  2836. o.error = error
  2837. return o
  2838. },
  2839. die = defect => {
  2840. const o = Object.create(proto)
  2841. o._tag = "Die"
  2842. o.defect = defect
  2843. return o
  2844. },
  2845. interrupt = fiberId => {
  2846. const o = Object.create(proto)
  2847. o._tag = "Interrupt"
  2848. o.fiberId = fiberId
  2849. return o
  2850. },
  2851. annotated = (cause, annotation) => {
  2852. const o = Object.create(proto)
  2853. o._tag = "Annotated"
  2854. o.cause = cause
  2855. o.annotation = annotation
  2856. return o
  2857. },
  2858. parallel = (left, right) => {
  2859. const o = Object.create(proto)
  2860. o._tag = "Parallel"
  2861. o.left = left
  2862. o.right = right
  2863. return o
  2864. },
  2865. sequential = (left, right) => {
  2866. const o = Object.create(proto)
  2867. o._tag = "Sequential"
  2868. o.left = left
  2869. o.right = right
  2870. return o
  2871. },
  2872. isCause = u => "object" == typeof u && null != u && CauseTypeId in u,
  2873. isEmptyType = self => "Empty" === self._tag,
  2874. isInterruptedOnly = self =>
  2875. reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self),
  2876. cause_defects = self =>
  2877. Chunk_reverse(
  2878. cause_reduce(self, Chunk_empty(), (list, cause) =>
  2879. "Die" === cause._tag
  2880. ? Option_some(Chunk_prepend(cause.defect)(list))
  2881. : Option_none()
  2882. )
  2883. ),
  2884. stripFailures = self =>
  2885. cause_match(
  2886. self,
  2887. cause_empty,
  2888. () => cause_empty,
  2889. defect => die(defect),
  2890. fiberId => interrupt(fiberId),
  2891. (cause, annotation) =>
  2892. isEmptyType(cause) ? cause : annotated(cause, annotation),
  2893. (left, right) => sequential(left, right),
  2894. (left, right) => parallel(left, right)
  2895. ),
  2896. causeEquals = (left, right) => {
  2897. let leftStack = Chunk_of(left),
  2898. rightStack = Chunk_of(right)
  2899. for (; Chunk_isNonEmpty(leftStack) && Chunk_isNonEmpty(rightStack); ) {
  2900. const [leftParallel, leftSequential] = cause_reduce(
  2901. [mjs_HashSet_empty(), Chunk_empty()],
  2902. ([parallel, sequential], cause) => {
  2903. const [par, seq] = evaluateCause(cause)
  2904. return Option_some([
  2905. mjs_HashSet_union(par)(parallel),
  2906. Chunk_concat(seq)(sequential),
  2907. ])
  2908. }
  2909. )(Chunk_headNonEmpty(leftStack)),
  2910. [rightParallel, rightSequential] = cause_reduce(
  2911. [mjs_HashSet_empty(), Chunk_empty()],
  2912. ([parallel, sequential], cause) => {
  2913. const [par, seq] = evaluateCause(cause)
  2914. return Option_some([
  2915. mjs_HashSet_union(par)(parallel),
  2916. Chunk_concat(seq)(sequential),
  2917. ])
  2918. }
  2919. )(Chunk_headNonEmpty(rightStack))
  2920. if (!equals(leftParallel, rightParallel)) return !1
  2921. leftStack = leftSequential
  2922. rightStack = rightSequential
  2923. }
  2924. return !0
  2925. },
  2926. flattenCause = cause => flattenCauseLoop(Chunk_of(cause), Chunk_empty()),
  2927. flattenCauseLoop = (causes, flattened) => {
  2928. for (;;) {
  2929. const [parallel, sequential] = Chunk_reduce(
  2930. [mjs_HashSet_empty(), Chunk_empty()],
  2931. ([parallel, sequential], cause) => {
  2932. const [par, seq] = evaluateCause(cause)
  2933. return [
  2934. mjs_HashSet_union(par)(parallel),
  2935. Chunk_concat(seq)(sequential),
  2936. ]
  2937. }
  2938. )(causes),
  2939. updated =
  2940. mjs_HashSet_size(parallel) > 0
  2941. ? Chunk_prepend(parallel)(flattened)
  2942. : flattened
  2943. if (Chunk_isEmpty(sequential)) return Chunk_reverse(updated)
  2944. causes = sequential
  2945. flattened = updated
  2946. }
  2947. throw new Error(
  2948. "BUG: Cause.flattenCauseLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  2949. )
  2950. },
  2951. find = Function_dual(2, (self, pf) => {
  2952. const stack = [self]
  2953. for (; stack.length > 0; ) {
  2954. const item = stack.pop(),
  2955. option = pf(item)
  2956. switch (option._tag) {
  2957. case "None":
  2958. switch (item._tag) {
  2959. case "Sequential":
  2960. case "Parallel":
  2961. stack.push(item.right)
  2962. stack.push(item.left)
  2963. break
  2964. case "Annotated":
  2965. stack.push(item.cause)
  2966. }
  2967. break
  2968. case "Some":
  2969. return option
  2970. }
  2971. }
  2972. return Option_none()
  2973. }),
  2974. evaluateCause = self => {
  2975. let cause = self
  2976. const stack = []
  2977. let _parallel = mjs_HashSet_empty(),
  2978. _sequential = Chunk_empty()
  2979. for (; void 0 !== cause; )
  2980. switch (cause._tag) {
  2981. case "Empty":
  2982. if (0 === stack.length) return [_parallel, _sequential]
  2983. cause = stack.pop()
  2984. break
  2985. case "Fail":
  2986. if (0 === stack.length)
  2987. return [mjs_HashSet_add(cause.error)(_parallel), _sequential]
  2988. _parallel = mjs_HashSet_add(cause.error)(_parallel)
  2989. cause = stack.pop()
  2990. break
  2991. case "Die":
  2992. if (0 === stack.length)
  2993. return [mjs_HashSet_add(cause.defect)(_parallel), _sequential]
  2994. _parallel = mjs_HashSet_add(cause.defect)(_parallel)
  2995. cause = stack.pop()
  2996. break
  2997. case "Interrupt":
  2998. if (0 === stack.length)
  2999. return [mjs_HashSet_add(cause.fiberId)(_parallel), _sequential]
  3000. _parallel = mjs_HashSet_add(cause.fiberId)(_parallel)
  3001. cause = stack.pop()
  3002. break
  3003. case "Annotated":
  3004. cause = cause.cause
  3005. break
  3006. case "Sequential":
  3007. switch (cause.left._tag) {
  3008. case "Empty":
  3009. cause = cause.right
  3010. break
  3011. case "Sequential":
  3012. cause = sequential(
  3013. cause.left.left,
  3014. sequential(cause.left.right, cause.right)
  3015. )
  3016. break
  3017. case "Parallel":
  3018. cause = parallel(
  3019. sequential(cause.left.left, cause.right),
  3020. sequential(cause.left.right, cause.right)
  3021. )
  3022. break
  3023. case "Annotated":
  3024. cause = sequential(cause.left.cause, cause.right)
  3025. break
  3026. default:
  3027. _sequential = Chunk_prepend(cause.right)(_sequential)
  3028. cause = cause.left
  3029. }
  3030. break
  3031. case "Parallel":
  3032. stack.push(cause.right)
  3033. cause = cause.left
  3034. }
  3035. throw new Error(
  3036. "BUG: Cause.evaluateCauseLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  3037. )
  3038. },
  3039. IsInterruptedOnlyCauseReducer = {
  3040. emptyCase: Function_constTrue,
  3041. failCase: Function_constFalse,
  3042. dieCase: Function_constFalse,
  3043. interruptCase: Function_constTrue,
  3044. annotatedCase: (_, value) => value,
  3045. sequentialCase: (_, left, right) => left && right,
  3046. parallelCase: (_, left, right) => left && right,
  3047. },
  3048. cause_match = Function_dual(
  3049. 8,
  3050. (
  3051. self,
  3052. emptyCase,
  3053. failCase,
  3054. dieCase,
  3055. interruptCase,
  3056. annotatedCase,
  3057. sequentialCase,
  3058. parallelCase
  3059. ) =>
  3060. reduceWithContext(self, void 0, {
  3061. emptyCase: () => emptyCase,
  3062. failCase: (_, error) => failCase(error),
  3063. dieCase: (_, defect) => dieCase(defect),
  3064. interruptCase: (_, fiberId) => interruptCase(fiberId),
  3065. annotatedCase: (_, value, annotation) =>
  3066. annotatedCase(value, annotation),
  3067. sequentialCase: (_, left, right) => sequentialCase(left, right),
  3068. parallelCase: (_, left, right) => parallelCase(left, right),
  3069. })
  3070. ),
  3071. cause_reduce = Function_dual(3, (self, zero, pf) => {
  3072. let accumulator = zero,
  3073. cause = self
  3074. const causes = []
  3075. for (; void 0 !== cause; ) {
  3076. const option = pf(accumulator, cause)
  3077. accumulator = Option_isSome(option) ? option.value : accumulator
  3078. switch (cause._tag) {
  3079. case "Sequential":
  3080. case "Parallel":
  3081. causes.push(cause.right)
  3082. cause = cause.left
  3083. break
  3084. case "Annotated":
  3085. cause = cause.cause
  3086. break
  3087. default:
  3088. cause = void 0
  3089. }
  3090. void 0 === cause && causes.length > 0 && (cause = causes.pop())
  3091. }
  3092. return accumulator
  3093. }),
  3094. reduceWithContext = Function_dual(3, (self, context, reducer) => {
  3095. const input = [self],
  3096. output = []
  3097. for (; input.length > 0; ) {
  3098. const cause = input.pop()
  3099. switch (cause._tag) {
  3100. case "Empty":
  3101. output.push(Either_right(reducer.emptyCase(context)))
  3102. break
  3103. case "Fail":
  3104. output.push(Either_right(reducer.failCase(context, cause.error)))
  3105. break
  3106. case "Die":
  3107. output.push(Either_right(reducer.dieCase(context, cause.defect)))
  3108. break
  3109. case "Interrupt":
  3110. output.push(
  3111. Either_right(reducer.interruptCase(context, cause.fiberId))
  3112. )
  3113. break
  3114. case "Annotated":
  3115. input.push(cause.cause)
  3116. output.push(
  3117. Either_left({
  3118. _tag: "AnnotatedCase",
  3119. annotation: cause.annotation,
  3120. })
  3121. )
  3122. break
  3123. case "Sequential":
  3124. input.push(cause.right)
  3125. input.push(cause.left)
  3126. output.push(Either_left({ _tag: "SequentialCase" }))
  3127. break
  3128. case "Parallel":
  3129. input.push(cause.right)
  3130. input.push(cause.left)
  3131. output.push(Either_left({ _tag: "ParallelCase" }))
  3132. }
  3133. }
  3134. const accumulator = []
  3135. for (; output.length > 0; ) {
  3136. const either = output.pop()
  3137. switch (either._tag) {
  3138. case "Left":
  3139. switch (either.left._tag) {
  3140. case "SequentialCase": {
  3141. const left = accumulator.pop(),
  3142. right = accumulator.pop(),
  3143. value = reducer.sequentialCase(context, left, right)
  3144. accumulator.push(value)
  3145. break
  3146. }
  3147. case "ParallelCase": {
  3148. const left = accumulator.pop(),
  3149. right = accumulator.pop(),
  3150. value = reducer.parallelCase(context, left, right)
  3151. accumulator.push(value)
  3152. break
  3153. }
  3154. case "AnnotatedCase": {
  3155. const cause = accumulator.pop(),
  3156. value = reducer.annotatedCase(
  3157. context,
  3158. cause,
  3159. either.left.annotation
  3160. )
  3161. accumulator.push(value)
  3162. break
  3163. }
  3164. }
  3165. break
  3166. case "Right":
  3167. accumulator.push(either.right)
  3168. }
  3169. }
  3170. if (0 === accumulator.length)
  3171. throw new Error(
  3172. "BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/io/issues"
  3173. )
  3174. return accumulator.pop()
  3175. }),
  3176. InterruptedExceptionTypeId = Symbol.for(
  3177. "@effect/io/Cause/errors/InterruptedException"
  3178. ),
  3179. isInterruptedException = u =>
  3180. "object" == typeof u && null != u && InterruptedExceptionTypeId in u,
  3181. StackAnnotationTypeId = Symbol.for("@effect/io/Cause/StackAnnotation")
  3182. class StackAnnotation {
  3183. constructor(stack, seq) {
  3184. this.stack = stack
  3185. this.seq = seq
  3186. this[cause_a] = StackAnnotationTypeId
  3187. }
  3188. }
  3189. cause_a = StackAnnotationTypeId
  3190. const globalErrorSeq = MutableRef_make(0),
  3191. isStackAnnotation = u =>
  3192. "object" == typeof u && null != u && StackAnnotationTypeId in u,
  3193. DeferredTypeId = Symbol.for("@effect/io/Deferred"),
  3194. deferredVariance = { _E: _ => _, _A: _ => _ },
  3195. pending = joiners => ({ _tag: "Pending", joiners }),
  3196. done = effect => ({ _tag: "Done", effect })
  3197. class DefaultScheduler {
  3198. constructor() {
  3199. this.running = !1
  3200. this.tasks = []
  3201. }
  3202. starveInternal(depth) {
  3203. const toRun = this.tasks
  3204. this.tasks = []
  3205. for (let i = 0; i < toRun.length; i++) toRun[i]()
  3206. 0 === this.tasks.length ? (this.running = !1) : this.starve(depth)
  3207. }
  3208. starve(depth = 0) {
  3209. depth >= 2048
  3210. ? setTimeout(() => this.starveInternal(0), 0)
  3211. : Promise.resolve(void 0).then(() => this.starveInternal(depth + 1))
  3212. }
  3213. scheduleTask(task) {
  3214. this.tasks.push(task)
  3215. if (!this.running) {
  3216. this.running = !0
  3217. this.starve()
  3218. }
  3219. }
  3220. }
  3221. const defaultScheduler = globalValue(
  3222. Symbol.for("@effect/io/Scheduler/defaultScheduler"),
  3223. () => new DefaultScheduler()
  3224. )
  3225. var core_a, core_b, core_c
  3226. const EffectErrorTypeId = Symbol.for("@effect/io/Effect/Error"),
  3227. isEffectError = u =>
  3228. "object" == typeof u && null != u && EffectErrorTypeId in u,
  3229. core_EffectTypeId = Symbol.for("@effect/io/Effect")
  3230. class RevertFlags {
  3231. constructor(patch) {
  3232. this.patch = patch
  3233. this._tag = "RevertFlags"
  3234. }
  3235. }
  3236. class EffectPrimitive {
  3237. constructor(_tag) {
  3238. this._tag = _tag
  3239. this.i0 = void 0
  3240. this.i1 = void 0
  3241. this.i2 = void 0
  3242. this.trace = void 0
  3243. this[core_a] = core_effectVariance
  3244. }
  3245. [((core_a = core_EffectTypeId), Equal_symbol)](that) {
  3246. return this === that
  3247. }
  3248. [symbol]() {
  3249. return random(this)
  3250. }
  3251. traced(trace) {
  3252. if (trace) {
  3253. const effect = new EffectPrimitive("Traced")
  3254. effect.i0 = this
  3255. effect.trace = trace
  3256. return effect
  3257. }
  3258. return this
  3259. }
  3260. }
  3261. class EffectPrimitiveFailure {
  3262. constructor(_tag) {
  3263. this._tag = _tag
  3264. this.i0 = void 0
  3265. this.i1 = void 0
  3266. this.i2 = void 0
  3267. this.trace = void 0
  3268. this[core_b] = core_effectVariance
  3269. }
  3270. [((core_b = core_EffectTypeId), Equal_symbol)](that) {
  3271. return this === that
  3272. }
  3273. [symbol]() {
  3274. return random(this)
  3275. }
  3276. get cause() {
  3277. return this.i0
  3278. }
  3279. traced(trace) {
  3280. if (trace) {
  3281. const effect = new EffectPrimitive("Traced")
  3282. effect.i0 = this
  3283. effect.trace = trace
  3284. return effect
  3285. }
  3286. return this
  3287. }
  3288. }
  3289. class EffectPrimitiveSuccess {
  3290. constructor(_tag) {
  3291. this._tag = _tag
  3292. this.i0 = void 0
  3293. this.i1 = void 0
  3294. this.i2 = void 0
  3295. this.trace = void 0
  3296. this[core_c] = core_effectVariance
  3297. }
  3298. [((core_c = core_EffectTypeId), Equal_symbol)](that) {
  3299. return this === that
  3300. }
  3301. [symbol]() {
  3302. return random(this)
  3303. }
  3304. get value() {
  3305. return this.i0
  3306. }
  3307. traced(trace) {
  3308. if (trace) {
  3309. const effect = new EffectPrimitive("Traced")
  3310. effect.i0 = this
  3311. effect.trace = trace
  3312. return effect
  3313. }
  3314. return this
  3315. }
  3316. }
  3317. const core_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  3318. isEffect = u =>
  3319. "object" == typeof u && null != u && core_EffectTypeId in u,
  3320. acquireUseRelease = dualWithTrace(
  3321. 3,
  3322. (trace, restoreTracing) => (acquire, use, release) =>
  3323. uninterruptibleMask(restore =>
  3324. core_flatMap(a =>
  3325. core_flatMap(exit =>
  3326. matchCauseEffect(
  3327. cause => {
  3328. switch (exit._tag) {
  3329. case "Failure":
  3330. return failCause(parallel(exit.i0, cause))
  3331. case "Success":
  3332. return failCause(cause)
  3333. }
  3334. },
  3335. () => exit
  3336. )(suspend(() => restoreTracing(release)(a, exit)))
  3337. )(core_exit(suspend(() => restore(restoreTracing(use)(a)))))
  3338. )(acquire)
  3339. ).traced(trace)
  3340. ),
  3341. core_as = dualWithTrace(
  3342. 2,
  3343. trace => (self, value) =>
  3344. core_flatMap(() => succeed(value))(self).traced(trace)
  3345. ),
  3346. core_asUnit = methodWithTrace(
  3347. trace => self => core_as(void 0)(self).traced(trace)
  3348. ),
  3349. core_async = methodWithTrace(
  3350. trace =>
  3351. (register, blockingOn = Id_none) => {
  3352. const effect = new EffectPrimitive("Async")
  3353. effect.i0 = register
  3354. effect.i1 = blockingOn
  3355. return trace ? effect.traced(trace) : effect
  3356. }
  3357. ),
  3358. asyncInterruptEither = methodWithTrace(
  3359. (trace, restore) =>
  3360. (register, blockingOn = Id_none) =>
  3361. suspend(() => {
  3362. let cancelerRef = core_unit()
  3363. return onInterrupt(() => cancelerRef)(
  3364. core_async(resume => {
  3365. const result = restore(register)(resume)
  3366. Either_isRight(result)
  3367. ? resume(result.right)
  3368. : (cancelerRef = result.left)
  3369. }, blockingOn)
  3370. )
  3371. }).traced(trace)
  3372. ),
  3373. asyncInterrupt = methodWithTrace(
  3374. (trace, restore) =>
  3375. (register, blockingOn = Id_none) =>
  3376. suspend(() => {
  3377. let cancelerRef = core_unit()
  3378. return onInterrupt(() => cancelerRef)(
  3379. core_async(resume => {
  3380. cancelerRef = restore(register)(resume)
  3381. }, blockingOn)
  3382. )
  3383. }).traced(trace)
  3384. ),
  3385. context = methodWithTrace(
  3386. trace => () => suspend(() => fiberRefGet(currentContext)).traced(trace)
  3387. ),
  3388. contextWithEffect = methodWithTrace(
  3389. (trace, restore) => f =>
  3390. core_flatMap(restore(f))(context()).traced(trace)
  3391. ),
  3392. core_exit = methodWithTrace(
  3393. trace => self => matchCause(failCause, succeed)(self).traced(trace)
  3394. ),
  3395. core_fail = methodWithTrace(
  3396. trace => error => failCause(fail(error)).traced(trace)
  3397. ),
  3398. failSync = methodWithTrace(
  3399. (trace, restore) => evaluate =>
  3400. failCauseSync(() => fail(restore(evaluate)())).traced(trace)
  3401. ),
  3402. failCause = methodWithTrace(trace => cause => {
  3403. const effect = new EffectPrimitiveFailure("Failure")
  3404. effect.i0 = cause
  3405. return trace ? effect.traced(trace) : effect
  3406. }),
  3407. failCauseSync = methodWithTrace(
  3408. (trace, restore) => evaluate =>
  3409. core_flatMap(sync(restore(evaluate)), failCause).traced(trace)
  3410. ),
  3411. fiberId = methodWithTrace(
  3412. trace => () =>
  3413. withFiberRuntime(state => succeed(state.id())).traced(trace)
  3414. ),
  3415. core_flatMap = dualWithTrace(2, (trace, restore) => (self, f) => {
  3416. const effect = new EffectPrimitive("OnSuccess")
  3417. effect.i0 = self
  3418. effect.i1 = restore(f)
  3419. return trace ? effect.traced(trace) : effect
  3420. }),
  3421. core_flatten = methodWithTrace(
  3422. trace => self => core_flatMap(self, Function_identity).traced(trace)
  3423. ),
  3424. matchCause = dualWithTrace(
  3425. 3,
  3426. (trace, restore) => (self, onFailure, onSuccess) =>
  3427. matchCauseEffect(
  3428. cause => succeed(restore(onFailure)(cause)),
  3429. a => succeed(restore(onSuccess)(a))
  3430. )(self).traced(trace)
  3431. ),
  3432. matchCauseEffect = dualWithTrace(
  3433. 3,
  3434. (trace, restore) => (self, onFailure, onSuccess) => {
  3435. const effect = new EffectPrimitive("OnSuccessAndFailure")
  3436. effect.i0 = self
  3437. effect.i1 = restore(onFailure)
  3438. effect.i2 = restore(onSuccess)
  3439. return trace ? effect.traced(trace) : effect
  3440. }
  3441. ),
  3442. matchEffect = dualWithTrace(
  3443. 3,
  3444. (trace, restore) => (self, onFailure, onSuccess) =>
  3445. matchCauseEffect(
  3446. self,
  3447. cause => {
  3448. const failures = (self =>
  3449. Chunk_reverse(
  3450. cause_reduce(self, Chunk_empty(), (list, cause) =>
  3451. "Fail" === cause._tag
  3452. ? Option_some(Chunk_prepend(cause.error)(list))
  3453. : Option_none()
  3454. )
  3455. ))(cause)
  3456. return cause_defects(cause).length > 0
  3457. ? failCause(
  3458. (self =>
  3459. cause_match(
  3460. self,
  3461. cause_empty,
  3462. failure => die(failure),
  3463. defect => die(defect),
  3464. fiberId => interrupt(fiberId),
  3465. (cause, annotation) =>
  3466. isEmptyType(cause)
  3467. ? cause
  3468. : annotated(cause, annotation),
  3469. (left, right) => sequential(left, right),
  3470. (left, right) => parallel(left, right)
  3471. ))(cause)
  3472. )
  3473. : failures.length > 0
  3474. ? restore(onFailure)(unsafeHead(failures))
  3475. : failCause(cause)
  3476. },
  3477. onSuccess
  3478. ).traced(trace)
  3479. ),
  3480. core_forEach = dualWithTrace(
  3481. 2,
  3482. (trace, restore) => (self, f) =>
  3483. suspend(() => {
  3484. const arr = Array.from(self),
  3485. ret = new Array(arr.length)
  3486. let i = 0
  3487. return core_as(unsafeFromArray(ret))(
  3488. whileLoop(
  3489. () => i < arr.length,
  3490. () => restore(f)(arr[i]),
  3491. b => {
  3492. ret[i++] = b
  3493. }
  3494. )
  3495. )
  3496. }).traced(trace)
  3497. ),
  3498. forEachDiscard = dualWithTrace(
  3499. 2,
  3500. (trace, restore) => (self, f) =>
  3501. suspend(() => {
  3502. const arr = Array.from(self)
  3503. let i = 0
  3504. return whileLoop(
  3505. () => i < arr.length,
  3506. () => restore(f)(arr[i++]),
  3507. () => {}
  3508. )
  3509. }).traced(trace)
  3510. ),
  3511. core_fromOption = methodWithTrace(trace => option => {
  3512. switch (option._tag) {
  3513. case "None":
  3514. return core_fail(Option_none()).traced(trace)
  3515. case "Some":
  3516. return succeed(option.value).traced(trace)
  3517. }
  3518. }),
  3519. core_interruptible = methodWithTrace(trace => self => {
  3520. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3521. effect.i0 = runtimeFlagsPatch_make((flag = 1), flag)
  3522. var flag
  3523. effect.i1 = () => self
  3524. return trace ? effect.traced(trace) : effect
  3525. }),
  3526. core_map = dualWithTrace(
  3527. 2,
  3528. (trace, restore) => (self, f) =>
  3529. core_flatMap(a => sync(() => restore(f)(a)))(self).traced(trace)
  3530. ),
  3531. onExit = dualWithTrace(
  3532. 2,
  3533. (trace, restoreTrace) => (self, cleanup) =>
  3534. uninterruptibleMask(restore =>
  3535. matchCauseEffect(
  3536. restore(self),
  3537. cause1 => {
  3538. const result = exitFailCause(cause1)
  3539. return matchCauseEffect(
  3540. cause2 => exitFailCause(sequential(cause1, cause2)),
  3541. () => result
  3542. )(restoreTrace(cleanup)(result))
  3543. },
  3544. success => {
  3545. const result = exitSucceed(success)
  3546. return zipRight(result)(restoreTrace(cleanup)(result))
  3547. }
  3548. )
  3549. ).traced(trace)
  3550. ),
  3551. onInterrupt = dualWithTrace(
  3552. 2,
  3553. (trace, restore) => (self, cleanup) =>
  3554. onExit(
  3555. self,
  3556. exitMatch(
  3557. cause =>
  3558. isInterruptedOnly(cause)
  3559. ? core_asUnit(
  3560. restore(cleanup)(
  3561. (self =>
  3562. cause_reduce(
  3563. self,
  3564. mjs_HashSet_empty(),
  3565. (set, cause) =>
  3566. "Interrupt" === cause._tag
  3567. ? Option_some(
  3568. mjs_HashSet_add(cause.fiberId)(set)
  3569. )
  3570. : Option_none()
  3571. ))(cause)
  3572. )
  3573. )
  3574. : core_unit(),
  3575. () => core_unit()
  3576. )
  3577. ).traced(trace)
  3578. ),
  3579. core_orElse = dualWithTrace(
  3580. 2,
  3581. (trace, restore) => (self, that) =>
  3582. attemptOrElse(restore(that), succeed)(self).traced(trace)
  3583. ),
  3584. provideContext = dualWithTrace(
  3585. 2,
  3586. trace => (self, context) =>
  3587. fiberRefLocally(currentContext, context)(self).traced(trace)
  3588. ),
  3589. contramapContext = dualWithTrace(
  3590. 2,
  3591. (trace, restore) => (self, f) =>
  3592. contextWithEffect(context =>
  3593. provideContext(restore(f)(context))(self)
  3594. ).traced(trace)
  3595. ),
  3596. succeed = methodWithTrace(trace => value => {
  3597. const effect = new EffectPrimitiveSuccess("Success")
  3598. effect.i0 = value
  3599. return trace ? effect.traced(trace) : effect
  3600. }),
  3601. suspend = methodWithTrace(
  3602. (trace, restore) => effect =>
  3603. core_flatMap(Function_identity)(sync(restore(effect))).traced(trace)
  3604. ),
  3605. sync = methodWithTrace((trace, restore) => evaluate => {
  3606. const effect = new EffectPrimitive("Sync")
  3607. effect.i0 = restore(evaluate)
  3608. return trace ? effect.traced(trace) : effect
  3609. }),
  3610. core_tap = dualWithTrace(
  3611. 2,
  3612. (trace, restore) => (self, f) =>
  3613. core_flatMap(a => core_as(a)(restore(f)(a)))(self).traced(trace)
  3614. ),
  3615. transplant = methodWithTrace(
  3616. (trace, restore) => f =>
  3617. withFiberRuntime(state => {
  3618. const scopeOverride = state.getFiberRef(forkScopeOverride),
  3619. scope = getOrElse(() => state.scope())(scopeOverride)
  3620. return restore(f)(
  3621. fiberRefLocally(forkScopeOverride, Option_some(scope))
  3622. )
  3623. }).traced(trace)
  3624. ),
  3625. attemptOrElse = dualWithTrace(
  3626. 3,
  3627. (trace, restore) => (self, that, onSuccess) =>
  3628. matchCauseEffect(
  3629. self,
  3630. cause =>
  3631. cause_defects(cause).length > 0
  3632. ? failCause(
  3633. getOrThrow(
  3634. (self =>
  3635. cause_match(
  3636. self,
  3637. Option_none(),
  3638. failure => Option_some(die(failure)),
  3639. defect => Option_some(die(defect)),
  3640. () => Option_none(),
  3641. (option, annotation) =>
  3642. Option_map(cause => annotated(cause, annotation))(
  3643. option
  3644. ),
  3645. (left, right) =>
  3646. Option_isSome(left) && Option_isSome(right)
  3647. ? Option_some(sequential(left.value, right.value))
  3648. : Option_isSome(left) && Option_isNone(right)
  3649. ? Option_some(left.value)
  3650. : Option_isNone(left) && Option_isSome(right)
  3651. ? Option_some(right.value)
  3652. : Option_none(),
  3653. (left, right) =>
  3654. Option_isSome(left) && Option_isSome(right)
  3655. ? Option_some(parallel(left.value, right.value))
  3656. : Option_isSome(left) && Option_isNone(right)
  3657. ? Option_some(left.value)
  3658. : Option_isNone(left) && Option_isSome(right)
  3659. ? Option_some(right.value)
  3660. : Option_none()
  3661. ))(cause)
  3662. )
  3663. )
  3664. : restore(that)(),
  3665. restore(onSuccess)
  3666. ).traced(trace)
  3667. ),
  3668. uninterruptible = methodWithTrace(trace => self => {
  3669. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3670. effect.i0 = Patch_disable(1)
  3671. effect.i1 = () => self
  3672. return trace ? effect.traced(trace) : effect
  3673. }),
  3674. uninterruptibleMask = methodWithTrace((trace, restore) => f => {
  3675. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3676. effect.i0 = Patch_disable(1)
  3677. effect.i1 = oldFlags =>
  3678. interruption(oldFlags)
  3679. ? restore(f)(core_interruptible)
  3680. : restore(f)(uninterruptible)
  3681. return trace ? effect.traced(trace) : effect
  3682. }),
  3683. core_unit = methodWithTrace(trace => _ => succeed(void 0).traced(trace)),
  3684. updateRuntimeFlags = methodWithTrace(trace => patch => {
  3685. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3686. effect.i0 = patch
  3687. effect.i1 = void 0
  3688. return trace ? effect.traced(trace) : effect
  3689. }),
  3690. whenEffect = dualWithTrace(
  3691. 2,
  3692. trace => (self, predicate) =>
  3693. core_flatMap(b =>
  3694. b ? core_map(Option_some)(self) : succeed(Option_none())
  3695. )(predicate).traced(trace)
  3696. ),
  3697. whileLoop = methodWithTrace(
  3698. (trace, restore) => (check, body, process) => {
  3699. const effect = new EffectPrimitive("While")
  3700. effect.i0 = restore(check)
  3701. effect.i1 = restore(body)
  3702. effect.i2 = restore(process)
  3703. return trace ? effect.traced(trace) : effect
  3704. }
  3705. ),
  3706. withFiberRuntime = methodWithTrace((trace, restore) => withRuntime => {
  3707. const effect = new EffectPrimitive("WithRuntime")
  3708. effect.i0 = restore(withRuntime)
  3709. return trace ? effect.traced(trace) : effect
  3710. }),
  3711. withParallelism = dualWithTrace(
  3712. 2,
  3713. trace => (self, parallelism) =>
  3714. suspend(() =>
  3715. fiberRefLocally(currentParallelism, Option_some(parallelism))(self)
  3716. ).traced(trace)
  3717. ),
  3718. yieldNow = methodWithTrace(trace => () => {
  3719. const effect = new EffectPrimitive("Yield")
  3720. return trace ? effect.traced(trace) : effect
  3721. }),
  3722. core_zip = dualWithTrace(
  3723. 2,
  3724. trace => (self, that) =>
  3725. core_flatMap(self, a => core_map(that, b => [a, b])).traced(trace)
  3726. ),
  3727. zipLeft = dualWithTrace(
  3728. 2,
  3729. trace => (self, that) =>
  3730. core_flatMap(self, a => core_as(that, a)).traced(trace)
  3731. ),
  3732. zipRight = dualWithTrace(
  3733. 2,
  3734. trace => (self, that) => core_flatMap(self, () => that).traced(trace)
  3735. ),
  3736. core_zipWith = dualWithTrace(
  3737. 3,
  3738. (trace, restore) => (self, that, f) =>
  3739. core_flatMap(self, a => core_map(that, b => restore(f)(a, b))).traced(
  3740. trace
  3741. )
  3742. ),
  3743. interruptFiber = methodWithTrace(
  3744. trace => self =>
  3745. core_flatMap(fiberId => interruptAsFiber(fiberId)(self))(
  3746. fiberId()
  3747. ).traced(trace)
  3748. ),
  3749. interruptAsFiber = dualWithTrace(
  3750. 2,
  3751. trace => (self, fiberId) =>
  3752. core_flatMap(() => self.await())(
  3753. self.interruptAsFork(fiberId)
  3754. ).traced(trace)
  3755. ),
  3756. logLevelAll = {
  3757. _tag: "All",
  3758. syslog: 0,
  3759. label: "ALL",
  3760. ordinal: Number.MIN_SAFE_INTEGER,
  3761. },
  3762. logLevelInfo = { _tag: "Info", syslog: 6, label: "INFO", ordinal: 2e4 },
  3763. logLevelDebug = {
  3764. _tag: "Debug",
  3765. syslog: 7,
  3766. label: "DEBUG",
  3767. ordinal: 1e4,
  3768. },
  3769. logLevelNone = {
  3770. _tag: "None",
  3771. syslog: 7,
  3772. label: "OFF",
  3773. ordinal: Number.MAX_SAFE_INTEGER,
  3774. },
  3775. FiberRefTypeId = Symbol.for("@effect/io/FiberRef"),
  3776. fiberRefVariance = { _A: _ => _ },
  3777. fiberRefGet = methodWithTrace(
  3778. trace => self => fiberRefModify(self, a => [a, a]).traced(trace)
  3779. ),
  3780. fiberRefGetWith = dualWithTrace(
  3781. 2,
  3782. (trace, restore) => (self, f) =>
  3783. core_flatMap(fiberRefGet(self), restore(f)).traced(trace)
  3784. ),
  3785. fiberRefSet = dualWithTrace(
  3786. 2,
  3787. trace => (self, value) =>
  3788. fiberRefModify(self, () => [void 0, value]).traced(trace)
  3789. ),
  3790. fiberRefModify = dualWithTrace(
  3791. 2,
  3792. (trace, restore) => (self, f) =>
  3793. withFiberRuntime(state => {
  3794. const [b, a] = restore(f)(state.getFiberRef(self))
  3795. state.setFiberRef(self, a)
  3796. return succeed(b)
  3797. }).traced(trace)
  3798. ),
  3799. fiberRefLocally = dualWithTrace(
  3800. 3,
  3801. trace => (use, self, value) =>
  3802. acquireUseRelease(
  3803. zipLeft(fiberRefGet(self), fiberRefSet(self, value)),
  3804. () => use,
  3805. oldValue => fiberRefSet(self, oldValue)
  3806. ).traced(trace)
  3807. ),
  3808. fiberRefUnsafeMake = (
  3809. initial,
  3810. fork = Function_identity,
  3811. join = (_, a) => a
  3812. ) => fiberRefUnsafeMakePatch(initial, Differ_update(), fork, join),
  3813. fiberRefUnsafeMakeHashSet = initial =>
  3814. fiberRefUnsafeMakePatch(
  3815. initial,
  3816. Differ_hashSet(),
  3817. Differ_HashSetPatch_empty()
  3818. ),
  3819. fiberRefUnsafeMakeContext = initial =>
  3820. fiberRefUnsafeMakePatch(
  3821. initial,
  3822. Differ_environment(),
  3823. Differ_ContextPatch_empty()
  3824. ),
  3825. fiberRefUnsafeMakePatch = (
  3826. initial,
  3827. differ,
  3828. fork,
  3829. join = (_, n) => n
  3830. ) => ({
  3831. [FiberRefTypeId]: fiberRefVariance,
  3832. initial,
  3833. diff: (oldValue, newValue) => Differ_diff(oldValue, newValue)(differ),
  3834. combine: (first, second) => Differ_combine(first, second)(differ),
  3835. patch: patch => oldValue => Differ_patch(patch, oldValue)(differ),
  3836. fork,
  3837. join,
  3838. }),
  3839. fiberRefUnsafeMakeRuntimeFlags = initial =>
  3840. fiberRefUnsafeMakePatch(
  3841. initial,
  3842. mjs_Differ_make({
  3843. empty: runtimeFlagsPatch_empty,
  3844. diff: (oldValue, newValue) => runtimeFlags_diff(oldValue, newValue),
  3845. combine: (first, second) =>
  3846. runtimeFlagsPatch_andThen(second)(first),
  3847. patch: (_patch, oldValue) => runtimeFlags_patch(oldValue, _patch),
  3848. }),
  3849. Patch_empty
  3850. ),
  3851. currentContext = fiberRefUnsafeMakeContext(mjs_Context_empty()),
  3852. currentLogAnnotations = fiberRefUnsafeMake(mjs_HashMap_empty()),
  3853. currentLogLevel = fiberRefUnsafeMake(logLevelInfo),
  3854. currentLogSpan = fiberRefUnsafeMake(Chunk_empty()),
  3855. currentScheduler = fiberRefUnsafeMake(defaultScheduler),
  3856. currentParallelism = fiberRefUnsafeMake(Option_none()),
  3857. unhandledErrorLogLevel = fiberRefUnsafeMake(
  3858. Option_some(logLevelDebug),
  3859. _ => _,
  3860. (_, x) => x
  3861. ),
  3862. currentTags = fiberRefUnsafeMakeHashSet(mjs_HashSet_empty()),
  3863. forkScopeOverride = fiberRefUnsafeMake(
  3864. Option_none(),
  3865. () => Option_none(),
  3866. (parent, _) => parent
  3867. ),
  3868. interruptedCause = fiberRefUnsafeMake(
  3869. cause_empty,
  3870. () => cause_empty,
  3871. (parent, _) => parent
  3872. ),
  3873. ScopeTypeId = Symbol.for("@effect/io/Scope"),
  3874. CloseableScopeTypeId = Symbol.for("@effect/io/CloseableScope"),
  3875. scopeAddFinalizerExit = methodWithTrace(
  3876. (trace, restore) => (self, finalizer) =>
  3877. self.addFinalizer(restore(finalizer)).traced(trace)
  3878. ),
  3879. scopeClose = methodWithTrace(
  3880. trace => (self, exit) => self.close(exit).traced(trace)
  3881. ),
  3882. releaseMapAdd = dualWithTrace(
  3883. 2,
  3884. (trace, restore) => (self, finalizer) =>
  3885. core_map(
  3886. match(
  3887. () => () => core_unit(),
  3888. key => exit => releaseMapRelease(key, exit)(self)
  3889. )
  3890. )(releaseMapAddIfOpen(restore(finalizer))(self)).traced(trace)
  3891. ),
  3892. releaseMapRelease = dualWithTrace(
  3893. 3,
  3894. trace => (self, key, exit) =>
  3895. suspend(() => {
  3896. switch (self.state._tag) {
  3897. case "Exited":
  3898. return core_unit()
  3899. case "Running": {
  3900. const finalizer = self.state.finalizers.get(key)
  3901. self.state.finalizers.delete(key)
  3902. return null != finalizer
  3903. ? self.state.update(finalizer)(exit)
  3904. : core_unit()
  3905. }
  3906. }
  3907. }).traced(trace)
  3908. ),
  3909. releaseMapAddIfOpen = dualWithTrace(
  3910. 2,
  3911. (trace, restore) => (self, finalizer) =>
  3912. suspend(() => {
  3913. switch (self.state._tag) {
  3914. case "Exited":
  3915. self.state.nextKey += 1
  3916. return core_as(Option_none())(
  3917. restore(finalizer)(self.state.exit)
  3918. )
  3919. case "Running": {
  3920. const key = self.state.nextKey
  3921. self.state.finalizers.set(key, finalizer)
  3922. self.state.nextKey += 1
  3923. return succeed(Option_some(key))
  3924. }
  3925. }
  3926. }).traced(trace)
  3927. ),
  3928. releaseMapMake = methodWithTrace(
  3929. trace => () =>
  3930. sync(() => ({
  3931. state: {
  3932. _tag: "Running",
  3933. nextKey: 0,
  3934. finalizers: new Map(),
  3935. update: Function_identity,
  3936. },
  3937. })).traced(trace)
  3938. ),
  3939. exitAs = Function_dual(2, (self, value) => {
  3940. switch (self._tag) {
  3941. case "Failure":
  3942. return self
  3943. case "Success":
  3944. return exitSucceed(value)
  3945. }
  3946. }),
  3947. exitAsUnit = self => exitAs(self, void 0),
  3948. exitCollectAllPar = exits => exitCollectAllInternal(exits, parallel),
  3949. exitFailCause = cause => {
  3950. const effect = new EffectPrimitiveFailure("Failure")
  3951. effect.i0 = cause
  3952. return effect
  3953. },
  3954. exitMap = Function_dual(2, (self, f) => {
  3955. switch (self._tag) {
  3956. case "Failure":
  3957. return self
  3958. case "Success":
  3959. return exitSucceed(f(self.i0))
  3960. }
  3961. }),
  3962. exitMatch = Function_dual(3, (self, onFailure, onSuccess) => {
  3963. switch (self._tag) {
  3964. case "Failure":
  3965. return onFailure(self.i0)
  3966. case "Success":
  3967. return onSuccess(self.i0)
  3968. }
  3969. }),
  3970. exitMatchEffect = Function_dual(3, (self, onFailure, onSuccess) => {
  3971. switch (self._tag) {
  3972. case "Failure":
  3973. return onFailure(self.i0)
  3974. case "Success":
  3975. return onSuccess(self.i0)
  3976. }
  3977. }),
  3978. exitSucceed = value => {
  3979. const effect = new EffectPrimitiveSuccess("Success")
  3980. effect.i0 = value
  3981. return effect
  3982. },
  3983. exitUnit = () => exitSucceed(void 0),
  3984. exitZipWith = Function_dual(4, (self, that, f, g) => {
  3985. switch (self._tag) {
  3986. case "Failure":
  3987. switch (that._tag) {
  3988. case "Success":
  3989. return self
  3990. case "Failure":
  3991. return exitFailCause(g(self.i0, that.i0))
  3992. }
  3993. case "Success":
  3994. switch (that._tag) {
  3995. case "Success":
  3996. return exitSucceed(f(self.i0, that.i0))
  3997. case "Failure":
  3998. return that
  3999. }
  4000. }
  4001. }),
  4002. exitCollectAllInternal = (exits, combineCauses) => {
  4003. const list = Chunk_fromIterable(exits)
  4004. return Chunk_isNonEmpty(list)
  4005. ? Option_some(
  4006. exitMap(Chunk_reverse)(
  4007. Chunk_reduce(
  4008. exitMap(Chunk_of)(Chunk_headNonEmpty(list)),
  4009. (accumulator, current) =>
  4010. exitZipWith(
  4011. current,
  4012. (list, value) => Chunk_prepend(value)(list),
  4013. combineCauses
  4014. )(accumulator)
  4015. )(Chunk_tailNonEmpty(list))
  4016. )
  4017. )
  4018. : Option_none()
  4019. },
  4020. deferredUnsafeMake = fiberId => ({
  4021. [DeferredTypeId]: deferredVariance,
  4022. state: MutableRef_make(pending([])),
  4023. blockingOn: fiberId,
  4024. }),
  4025. deferredMake = methodWithTrace(
  4026. trace => () =>
  4027. core_flatMap(id => deferredMakeAs(id))(fiberId()).traced(trace)
  4028. ),
  4029. deferredMakeAs = methodWithTrace(
  4030. trace => fiberId =>
  4031. sync(() => deferredUnsafeMake(fiberId)).traced(trace)
  4032. ),
  4033. deferredAwait = methodWithTrace(
  4034. trace => self =>
  4035. asyncInterruptEither(k => {
  4036. const state = MutableRef_get(self.state)
  4037. switch (state._tag) {
  4038. case "Done":
  4039. return Either_right(state.effect)
  4040. case "Pending":
  4041. MutableRef_set(pending([k, ...state.joiners]))(self.state)
  4042. return Either_left(deferredInterruptJoiner(self, k))
  4043. }
  4044. }, self.blockingOn).traced(trace)
  4045. ),
  4046. deferredCompleteWith = dualWithTrace(
  4047. 2,
  4048. trace => (self, effect) =>
  4049. sync(() => {
  4050. const state = MutableRef_get(self.state)
  4051. switch (state._tag) {
  4052. case "Done":
  4053. return !1
  4054. case "Pending":
  4055. MutableRef_set(done(effect))(self.state)
  4056. for (let i = 0; i < state.joiners.length; i++)
  4057. state.joiners[i](effect)
  4058. return !0
  4059. }
  4060. }).traced(trace)
  4061. ),
  4062. deferredFail = dualWithTrace(
  4063. 2,
  4064. trace => (self, error) =>
  4065. deferredCompleteWith(self, core_fail(error)).traced(trace)
  4066. ),
  4067. deferredFailCause = dualWithTrace(
  4068. 2,
  4069. trace => (self, cause) =>
  4070. deferredCompleteWith(self, failCause(cause)).traced(trace)
  4071. ),
  4072. deferredSucceed = dualWithTrace(
  4073. 2,
  4074. trace => (self, value) =>
  4075. deferredCompleteWith(self, succeed(value)).traced(trace)
  4076. ),
  4077. deferredUnsafeDone = (self, effect) => {
  4078. const state = MutableRef_get(self.state)
  4079. if ("Pending" === state._tag) {
  4080. MutableRef_set(done(effect))(self.state)
  4081. for (let i = state.joiners.length - 1; i >= 0; i--)
  4082. state.joiners[i](effect)
  4083. }
  4084. },
  4085. deferredInterruptJoiner = (self, joiner) =>
  4086. sync(() => {
  4087. const state = MutableRef_get(self.state)
  4088. "Pending" === state._tag &&
  4089. MutableRef_set(pending(state.joiners.filter(j => j !== joiner)))(
  4090. self.state
  4091. )
  4092. })
  4093. class ConsImpl {
  4094. constructor(head, tail) {
  4095. this.head = head
  4096. this.tail = tail
  4097. this._tag = "Cons"
  4098. this[List_a] = listVariance
  4099. }
  4100. toString() {
  4101. return `List.Cons(${List_toReadonlyArray(this).map(String).join(", ")})`
  4102. }
  4103. toJSON() {
  4104. return { _tag: "List.Cons", values: List_toReadonlyArray(this) }
  4105. }
  4106. [Symbol.for("nodejs.util.inspect.custom")]() {
  4107. return this.toJSON()
  4108. }
  4109. [Equal_symbol](that) {
  4110. return (
  4111. isList(that) &&
  4112. this._tag === that._tag &&
  4113. equalsWith(this, that, equals)
  4114. )
  4115. }
  4116. [symbol]() {
  4117. return string("@effect/data/List")
  4118. }
  4119. [Symbol.iterator]() {
  4120. let done = !1,
  4121. self = this
  4122. return {
  4123. next() {
  4124. if (done) return this.return()
  4125. if ("Nil" === self._tag) {
  4126. done = !0
  4127. return this.return()
  4128. }
  4129. const value = self.head
  4130. self = self.tail
  4131. return { done, value }
  4132. },
  4133. return(value) {
  4134. done || (done = !0)
  4135. return { done: !0, value }
  4136. },
  4137. }
  4138. }
  4139. }
  4140. class NilImpl {
  4141. constructor() {
  4142. this._tag = "Nil"
  4143. this[List_b] = listVariance
  4144. }
  4145. toString() {
  4146. return "List.Nil"
  4147. }
  4148. toJSON() {
  4149. return { _tag: "List.Nil" }
  4150. }
  4151. [Symbol.for("nodejs.util.inspect.custom")]() {
  4152. return this.toJSON()
  4153. }
  4154. [symbol]() {
  4155. return array(Array.from(this))
  4156. }
  4157. [Equal_symbol](that) {
  4158. return isList(that) && this._tag === that._tag
  4159. }
  4160. [Symbol.iterator]() {
  4161. return { next: () => ({ done: !0, value: void 0 }) }
  4162. }
  4163. }
  4164. const Duration_TypeId = Symbol.for("@effect/data/Duration")
  4165. class DurationImpl {
  4166. constructor(millis) {
  4167. this.millis = millis
  4168. this._id = Duration_TypeId
  4169. }
  4170. [symbol]() {
  4171. return Hash_hash(this.millis)
  4172. }
  4173. [Equal_symbol](that) {
  4174. return isDuration(that) && this.millis === that.millis
  4175. }
  4176. }
  4177. const isDuration = u =>
  4178. "object" == typeof u &&
  4179. null != u &&
  4180. "_id" in u &&
  4181. u._id === Duration_TypeId,
  4182. zero = new DurationImpl(0),
  4183. millis = millis => new DurationImpl(millis)
  4184. fromSemigroup(
  4185. Semigroup_make(
  4186. Function_dual(
  4187. 2,
  4188. (self, that) => new DurationImpl(self.millis + that.millis)
  4189. )
  4190. ),
  4191. zero
  4192. ).combineAll
  4193. var fiberRefs_a
  4194. const FiberRefsSym = Symbol.for("@effect/io/FiberRefs")
  4195. class FiberRefsImpl {
  4196. constructor(locals) {
  4197. this.locals = locals
  4198. this[fiberRefs_a] = FiberRefsSym
  4199. }
  4200. }
  4201. fiberRefs_a = FiberRefsSym
  4202. const findAncestor = (
  4203. _ref,
  4204. _parentStack,
  4205. _childStack,
  4206. _childModified = !1
  4207. ) => {
  4208. const ref = _ref
  4209. let ret,
  4210. parentStack = _parentStack,
  4211. childStack = _childStack,
  4212. childModified = _childModified
  4213. for (; void 0 === ret; )
  4214. if (
  4215. isNonEmptyReadonlyArray(parentStack) &&
  4216. isNonEmptyReadonlyArray(childStack)
  4217. ) {
  4218. const parentFiberId = headNonEmpty(parentStack)[0],
  4219. parentAncestors = tailNonEmpty(parentStack),
  4220. childFiberId = headNonEmpty(childStack)[0],
  4221. childRefValue = headNonEmpty(childStack)[1],
  4222. childAncestors = tailNonEmpty(childStack)
  4223. if (parentFiberId.startTimeMillis < childFiberId.startTimeMillis) {
  4224. childStack = childAncestors
  4225. childModified = !0
  4226. } else if (
  4227. parentFiberId.startTimeMillis > childFiberId.startTimeMillis
  4228. )
  4229. parentStack = parentAncestors
  4230. else if (parentFiberId.id < childFiberId.id) {
  4231. childStack = childAncestors
  4232. childModified = !0
  4233. } else
  4234. parentFiberId.id > childFiberId.id
  4235. ? (parentStack = parentAncestors)
  4236. : (ret = [childRefValue, childModified])
  4237. } else ret = [ref.initial, !0]
  4238. return ret
  4239. },
  4240. joinAs = Function_dual(3, (self, fiberId, that) => {
  4241. const parentFiberRefs = new Map(self.locals)
  4242. for (const [fiberRef, childStack] of that.locals) {
  4243. const childValue = headNonEmpty(childStack)[1]
  4244. if (!equals(headNonEmpty(childStack)[0], fiberId)) {
  4245. if (!parentFiberRefs.has(fiberRef)) {
  4246. if (equals(childValue, fiberRef.initial)) continue
  4247. parentFiberRefs.set(fiberRef, [
  4248. [fiberId, fiberRef.join(fiberRef.initial, childValue)],
  4249. ])
  4250. continue
  4251. }
  4252. const parentStack = parentFiberRefs.get(fiberRef),
  4253. [ancestor, wasModified] = findAncestor(
  4254. fiberRef,
  4255. parentStack,
  4256. childStack
  4257. )
  4258. if (wasModified) {
  4259. const patch = fiberRef.diff(ancestor, childValue),
  4260. oldValue = headNonEmpty(parentStack)[1],
  4261. newValue = fiberRef.join(
  4262. oldValue,
  4263. fiberRef.patch(patch)(oldValue)
  4264. )
  4265. if (!equals(oldValue, newValue)) {
  4266. let newStack
  4267. const parentFiberId = headNonEmpty(parentStack)[0]
  4268. newStack = equals(parentFiberId, fiberId)
  4269. ? prepend([parentFiberId, newValue])(
  4270. tailNonEmpty(parentStack)
  4271. )
  4272. : prepend([fiberId, newValue])(parentStack)
  4273. parentFiberRefs.set(fiberRef, newStack)
  4274. }
  4275. }
  4276. }
  4277. }
  4278. return new FiberRefsImpl(new Map(parentFiberRefs))
  4279. }),
  4280. forkAs = Function_dual(2, (self, childId) => {
  4281. const map = new Map()
  4282. for (const [fiberRef, stack] of self.locals.entries()) {
  4283. const oldValue = headNonEmpty(stack)[1],
  4284. newValue = fiberRef.patch(fiberRef.fork)(oldValue)
  4285. equals(oldValue, newValue)
  4286. ? map.set(fiberRef, stack)
  4287. : map.set(fiberRef, prepend([childId, newValue])(stack))
  4288. }
  4289. return new FiberRefsImpl(map)
  4290. }),
  4291. delete_ = Function_dual(2, (self, fiberRef) => {
  4292. const locals = new Map(self.locals)
  4293. locals.delete(fiberRef)
  4294. return new FiberRefsImpl(locals)
  4295. }),
  4296. fiberRefs_get = Function_dual(2, (self, fiberRef) =>
  4297. self.locals.has(fiberRef)
  4298. ? Option_some(headNonEmpty(self.locals.get(fiberRef))[1])
  4299. : Option_none()
  4300. ),
  4301. getOrDefault = Function_dual(2, (self, fiberRef) =>
  4302. getOrElse(() => fiberRef.initial)(fiberRefs_get(self, fiberRef))
  4303. ),
  4304. updatedAs = Function_dual(4, (self, fiberId, fiberRef, value) => {
  4305. const oldStack = self.locals.has(fiberRef)
  4306. ? self.locals.get(fiberRef)
  4307. : []
  4308. let newStack
  4309. if (isEmptyReadonlyArray(oldStack))
  4310. newStack = ReadonlyArray_of([fiberId, value])
  4311. else {
  4312. const [currentId, currentValue] = headNonEmpty(oldStack)
  4313. if (equals(currentId, fiberId)) {
  4314. if (equals(currentValue, value)) return self
  4315. newStack = prepend([fiberId, value])(tailNonEmpty(oldStack))
  4316. } else newStack = prepend([fiberId, value])(oldStack)
  4317. }
  4318. const locals = new Map(self.locals)
  4319. return new FiberRefsImpl(locals.set(fiberRef, newStack))
  4320. }),
  4321. FiberRefs_forkAs = forkAs,
  4322. FiberRefs_getOrDefault = getOrDefault,
  4323. FiberRefs_updatedAs = updatedAs,
  4324. FiberRefs_unsafeMake = function (fiberRefLocals) {
  4325. return new FiberRefsImpl(fiberRefLocals)
  4326. },
  4327. patch_diff = (oldValue, newValue) => {
  4328. const missingLocals = new Map(oldValue.locals)
  4329. let patch = { _tag: "Empty" }
  4330. for (const [fiberRef, pairs] of newValue.locals.entries()) {
  4331. const newValue = headNonEmpty(pairs)[1],
  4332. old = missingLocals.get(fiberRef)
  4333. if (void 0 !== old) {
  4334. const oldValue = headNonEmpty(old)[1]
  4335. equals(oldValue, newValue) ||
  4336. (patch = patch_combine({
  4337. _tag: "Update",
  4338. fiberRef,
  4339. patch: fiberRef.diff(oldValue, newValue),
  4340. })(patch))
  4341. } else
  4342. patch = patch_combine({ _tag: "Add", fiberRef, value: newValue })(
  4343. patch
  4344. )
  4345. missingLocals.delete(fiberRef)
  4346. }
  4347. for (const [fiberRef] of missingLocals.entries())
  4348. patch = patch_combine({ _tag: "Remove", fiberRef })(patch)
  4349. return patch
  4350. },
  4351. patch_combine = Function_dual(2, (self, that) => ({
  4352. _tag: "AndThen",
  4353. first: self,
  4354. second: that,
  4355. })),
  4356. patch_patch = Function_dual(3, (self, fiberId, oldValue) => {
  4357. let fiberRefs = oldValue,
  4358. patches = ReadonlyArray_of(self)
  4359. for (; isNonEmptyReadonlyArray(patches); ) {
  4360. const head = headNonEmpty(patches),
  4361. tail = tailNonEmpty(patches)
  4362. switch (head._tag) {
  4363. case "Empty":
  4364. patches = tail
  4365. break
  4366. case "Add":
  4367. fiberRefs = updatedAs(
  4368. fiberRefs,
  4369. fiberId,
  4370. head.fiberRef,
  4371. head.value
  4372. )
  4373. patches = tail
  4374. break
  4375. case "Remove":
  4376. fiberRefs = delete_(fiberRefs, head.fiberRef)
  4377. patches = tail
  4378. break
  4379. case "Update": {
  4380. const value = getOrDefault(fiberRefs, head.fiberRef)
  4381. fiberRefs = updatedAs(
  4382. fiberRefs,
  4383. fiberId,
  4384. head.fiberRef,
  4385. head.fiberRef.patch(head.patch)(value)
  4386. )
  4387. patches = tail
  4388. break
  4389. }
  4390. case "AndThen":
  4391. patches = prepend(head.first)(prepend(head.second)(tail))
  4392. }
  4393. }
  4394. return fiberRefs
  4395. })
  4396. class SingleShotGen {
  4397. constructor(self) {
  4398. this.self = self
  4399. this.called = !1
  4400. }
  4401. next(a) {
  4402. return this.called
  4403. ? { value: a, done: !0 }
  4404. : ((this.called = !0), { value: this.self, done: !1 })
  4405. }
  4406. return(a) {
  4407. return { value: a, done: !0 }
  4408. }
  4409. throw(e) {
  4410. throw e
  4411. }
  4412. [Symbol.iterator]() {
  4413. return new SingleShotGen(this.self)
  4414. }
  4415. }
  4416. const All = logLevelAll,
  4417. Fatal = { _tag: "Fatal", syslog: 2, label: "FATAL", ordinal: 5e4 },
  4418. Level_Error = { _tag: "Error", syslog: 3, label: "ERROR", ordinal: 4e4 },
  4419. Warning = { _tag: "Warning", syslog: 4, label: "WARN", ordinal: 3e4 },
  4420. Info = logLevelInfo,
  4421. Level_Debug = logLevelDebug,
  4422. Trace = { _tag: "Trace", syslog: 7, label: "TRACE", ordinal: 0 },
  4423. Level_None = logLevelNone,
  4424. locally = dualWithTrace(
  4425. 2,
  4426. trace => (use, self) =>
  4427. fiberRefLocally(use, currentLogLevel, self).traced(trace)
  4428. ),
  4429. greaterThanEqual = greaterThanOrEqualTo(
  4430. Order_contramap(level => level.ordinal)(Order)
  4431. ),
  4432. fromLiteral = _ => {
  4433. switch (_) {
  4434. case "All":
  4435. return All
  4436. case "Debug":
  4437. return Level_Debug
  4438. case "Error":
  4439. return Level_Error
  4440. case "Fatal":
  4441. return Fatal
  4442. case "Info":
  4443. return Info
  4444. case "Trace":
  4445. return Trace
  4446. case "None":
  4447. return Level_None
  4448. case "Warning":
  4449. return Warning
  4450. }
  4451. },
  4452. Span_render = now => self =>
  4453. `${self.label.replace(/[\s="]/g, "_")}=${now - self.startTime}ms`
  4454. var ref_a
  4455. const RefTypeId = Symbol.for("@effect/io/Ref"),
  4456. refVariance = { _A: _ => _ }
  4457. class RefImpl {
  4458. constructor(ref) {
  4459. this.ref = ref
  4460. this[ref_a] = refVariance
  4461. }
  4462. modify(f) {
  4463. return bodyWithTrace((trace, restore) =>
  4464. sync(() => {
  4465. const current = MutableRef_get(this.ref),
  4466. [b, a] = restore(f)(current)
  4467. current !== a && MutableRef_set(a)(this.ref)
  4468. return b
  4469. }).traced(trace)
  4470. )
  4471. }
  4472. }
  4473. ref_a = RefTypeId
  4474. const ref_unsafeMake = value => new RefImpl(MutableRef_make(value)),
  4475. ref_make = methodWithTrace(
  4476. trace => value => sync(() => ref_unsafeMake(value)).traced(trace)
  4477. ),
  4478. ref_get = methodWithTrace(
  4479. trace => self => self.modify(a => [a, a]).traced(trace)
  4480. ),
  4481. ref_set = dualWithTrace(
  4482. 2,
  4483. trace => (self, value) =>
  4484. self.modify(() => [void 0, value]).traced(trace)
  4485. ),
  4486. ref_modify = dualWithTrace(
  4487. 2,
  4488. (trace, restore) => (self, f) => self.modify(restore(f)).traced(trace)
  4489. ),
  4490. ref_update = dualWithTrace(
  4491. 2,
  4492. (trace, restore) => (self, f) =>
  4493. self.modify(a => [void 0, restore(f)(a)]).traced(trace)
  4494. ),
  4495. effect_collectAll = methodWithTrace(
  4496. trace => effects =>
  4497. core_forEach(effects, Function_identity).traced(trace)
  4498. ),
  4499. diffFiberRefs = methodWithTrace(
  4500. trace => self =>
  4501. summarized(getFiberRefs(), patch_diff)(self).traced(trace)
  4502. ),
  4503. effect_Do = methodWithTrace(trace => () => succeed({}).traced(trace)),
  4504. effect_bind = dualWithTrace(
  4505. 3,
  4506. (trace, restore) => (self, tag, f) =>
  4507. core_flatMap(self, k =>
  4508. core_map(restore(f)(k), a => ({ ...k, [tag]: a }))
  4509. ).traced(trace)
  4510. ),
  4511. bindValue = dualWithTrace(
  4512. 3,
  4513. (trace, restore) => (self, tag, f) =>
  4514. core_map(self, k => ({ ...k, [tag]: restore(f)(k) })).traced(trace)
  4515. ),
  4516. filterOrElse = dualWithTrace(
  4517. 3,
  4518. (trace, restore) => (self, f, orElse) =>
  4519. filterOrElseWith(self, restore(f), orElse).traced(trace)
  4520. ),
  4521. filterOrElseWith = dualWithTrace(
  4522. 3,
  4523. (trace, restore) => (self, f, orElse) =>
  4524. core_flatMap(self, a =>
  4525. restore(f)(a) ? succeed(a) : restore(orElse)(a)
  4526. ).traced(trace)
  4527. ),
  4528. filterOrFail = dualWithTrace(
  4529. 3,
  4530. (trace, restore) => (self, f, error) =>
  4531. filterOrElse(self, restore(f), () => failSync(restore(error))).traced(
  4532. trace
  4533. )
  4534. ),
  4535. effect_match = dualWithTrace(
  4536. 3,
  4537. (trace, restore) => (self, onFailure, onSuccess) =>
  4538. matchEffect(
  4539. self,
  4540. e => succeed(restore(onFailure)(e)),
  4541. a => succeed(restore(onSuccess)(a))
  4542. ).traced(trace)
  4543. )
  4544. class EffectGen {
  4545. constructor(value) {
  4546. this.value = value
  4547. }
  4548. [Symbol.iterator]() {
  4549. return new SingleShotGen(this)
  4550. }
  4551. }
  4552. const getFiberRefs = methodWithTrace(
  4553. trace => () =>
  4554. withFiberRuntime(state => succeed(state.unsafeGetFiberRefs())).traced(
  4555. trace
  4556. )
  4557. ),
  4558. ignore = methodWithTrace(
  4559. trace => self =>
  4560. effect_match(self, Function_constVoid, Function_constVoid).traced(
  4561. trace
  4562. )
  4563. ),
  4564. effect_isSuccess = methodWithTrace(
  4565. trace => self =>
  4566. effect_match(self, Function_constFalse, Function_constTrue).traced(
  4567. trace
  4568. )
  4569. ),
  4570. someInfo = Option_some(Info),
  4571. someDebug = Option_some(Level_Debug),
  4572. log = methodWithTrace(
  4573. trace => message =>
  4574. withFiberRuntime(fiberState => {
  4575. fiberState.log(message, cause_empty, Option_none())
  4576. return core_unit()
  4577. }).traced(trace)
  4578. ),
  4579. logDebug = methodWithTrace(
  4580. trace => message =>
  4581. withFiberRuntime(fiberState => {
  4582. fiberState.log(message, cause_empty, someDebug)
  4583. return core_unit()
  4584. }).traced(trace)
  4585. ),
  4586. logInfo = methodWithTrace(
  4587. trace => message =>
  4588. withFiberRuntime(fiberState => {
  4589. fiberState.log(message, cause_empty, someInfo)
  4590. return core_unit()
  4591. }).traced(trace)
  4592. ),
  4593. logAnnotate = dualWithTrace(
  4594. 3,
  4595. trace => (effect, key, value) =>
  4596. core_flatMap(fiberRefGet(currentLogAnnotations), annotations =>
  4597. suspend(() =>
  4598. fiberRefLocally(
  4599. currentLogAnnotations,
  4600. HashMap_set(key, value)(annotations)
  4601. )(effect)
  4602. )
  4603. ).traced(trace)
  4604. ),
  4605. orElseSucceed = dualWithTrace(
  4606. 2,
  4607. (trace, restore) => (self, evaluate) =>
  4608. core_orElse(self, () => sync(restore(evaluate))).traced(trace)
  4609. ),
  4610. patchFiberRefs = methodWithTrace(
  4611. trace => patch =>
  4612. updateFiberRefs((fiberId, fiberRefs) =>
  4613. patch_patch(fiberId, fiberRefs)(patch)
  4614. ).traced(trace)
  4615. ),
  4616. promise = methodWithTrace(
  4617. (trace, restore) => evaluate =>
  4618. core_async(resolve => {
  4619. restore(evaluate)()
  4620. .then(a => resolve(exitSucceed(a)))
  4621. .catch(e => resolve(exitFailCause(die(e))))
  4622. }).traced(trace)
  4623. ),
  4624. summarized = dualWithTrace(
  4625. 3,
  4626. (trace, restore) => (self, summary, f) =>
  4627. core_flatMap(summary, start =>
  4628. core_flatMap(self, value =>
  4629. core_map(summary, end => [restore(f)(start, end), value])
  4630. )
  4631. ).traced(trace)
  4632. ),
  4633. effect_all = methodWithTrace(
  4634. trace =>
  4635. function () {
  4636. return 1 === arguments.length
  4637. ? isEffect(arguments[0])
  4638. ? core_map(arguments[0], x => [x])
  4639. : Array.isArray(arguments[0])
  4640. ? core_map(
  4641. effect_collectAll(arguments[0]),
  4642. toReadonlyArray
  4643. ).traced(trace)
  4644. : core_map(values => {
  4645. const res = {}
  4646. for (const [k, v] of values) res[k] = v
  4647. return res
  4648. })(
  4649. core_forEach(Object.entries(arguments[0]), ([_, e]) =>
  4650. core_map(e, a => [_, a])
  4651. )
  4652. ).traced(trace)
  4653. : core_map(effect_collectAll(arguments), toReadonlyArray).traced(
  4654. trace
  4655. )
  4656. }
  4657. ),
  4658. updateFiberRefs = methodWithTrace(
  4659. (trace, restore) => f =>
  4660. withFiberRuntime(state => {
  4661. state.setFiberRefs(
  4662. restore(f)(state.id(), state.unsafeGetFiberRefs())
  4663. )
  4664. return core_unit()
  4665. }).traced(trace)
  4666. ),
  4667. MutableHashMap_TypeId = Symbol.for("@effect/data/MutableHashMap")
  4668. class MutableHashMapImpl {
  4669. constructor() {
  4670. this._id = MutableHashMap_TypeId
  4671. this.backingMap = MutableRef_make(mjs_HashMap_empty())
  4672. }
  4673. [Symbol.iterator]() {
  4674. return this.backingMap.current[Symbol.iterator]()
  4675. }
  4676. toString() {
  4677. return `MutableHashMap(${Array.from(this)
  4678. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  4679. .join(", ")})`
  4680. }
  4681. toJSON() {
  4682. return { _tag: "MutableHashMap", values: Array.from(this) }
  4683. }
  4684. [Symbol.for("nodejs.util.inspect.custom")]() {
  4685. return this.toJSON()
  4686. }
  4687. }
  4688. const MutableHashMap_get = Function_dual(2, (self, key) =>
  4689. mjs_HashMap_get(self.backingMap.current, key)
  4690. ),
  4691. MutableHashMap_has = Function_dual(2, (self, key) =>
  4692. Option_isSome(MutableHashMap_get(self, key))
  4693. ),
  4694. MutableHashMap_set = Function_dual(3, (self, key, value) => {
  4695. MutableRef_update(self.backingMap, HashMap_set(key, value))
  4696. return self
  4697. }),
  4698. ExecutionStrategy_sequential = { _tag: "Sequential" }
  4699. var fiberStatus_a, fiberStatus_b, fiberStatus_c
  4700. const FiberStatusTypeId = Symbol.for("@effect/io/Fiber/Status")
  4701. class Done {
  4702. constructor() {
  4703. this[fiberStatus_a] = FiberStatusTypeId
  4704. this._tag = "Done"
  4705. }
  4706. [((fiberStatus_a = FiberStatusTypeId), symbol)]() {
  4707. return combine(Hash_hash(this._tag))(
  4708. Hash_hash("@effect/io/Fiber/Status")
  4709. )
  4710. }
  4711. [Equal_symbol](that) {
  4712. return isFiberStatus(that) && "Done" === that._tag
  4713. }
  4714. }
  4715. class Running {
  4716. constructor(runtimeFlags) {
  4717. this.runtimeFlags = runtimeFlags
  4718. this[fiberStatus_b] = FiberStatusTypeId
  4719. this._tag = "Running"
  4720. }
  4721. [((fiberStatus_b = FiberStatusTypeId), symbol)]() {
  4722. return combine(Hash_hash(this.runtimeFlags))(
  4723. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  4724. )
  4725. }
  4726. [Equal_symbol](that) {
  4727. return (
  4728. isFiberStatus(that) &&
  4729. "Running" === that._tag &&
  4730. this.runtimeFlags === that.runtimeFlags
  4731. )
  4732. }
  4733. }
  4734. class Suspended {
  4735. constructor(runtimeFlags, blockingOn) {
  4736. this.runtimeFlags = runtimeFlags
  4737. this.blockingOn = blockingOn
  4738. this[fiberStatus_c] = FiberStatusTypeId
  4739. this._tag = "Suspended"
  4740. }
  4741. [((fiberStatus_c = FiberStatusTypeId), symbol)]() {
  4742. return combine(Hash_hash(this.blockingOn))(
  4743. combine(Hash_hash(this.runtimeFlags))(
  4744. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  4745. )
  4746. )
  4747. }
  4748. [Equal_symbol](that) {
  4749. return (
  4750. isFiberStatus(that) &&
  4751. "Suspended" === that._tag &&
  4752. this.runtimeFlags === that.runtimeFlags &&
  4753. equals(this.blockingOn, that.blockingOn)
  4754. )
  4755. }
  4756. }
  4757. const isFiberStatus = u =>
  4758. "object" == typeof u && null != u && FiberStatusTypeId in u,
  4759. Status_done = new Done(),
  4760. Status_running = runtimeFlags => new Running(runtimeFlags),
  4761. interruptSignal = cause => ({ _tag: "InterruptSignal", cause }),
  4762. stateful = onFiber => ({ _tag: "Stateful", onFiber }),
  4763. resume = effect => ({ _tag: "Resume", effect })
  4764. var fiberScope_a, fiberScope_b
  4765. const FiberScopeTypeId = Symbol.for("@effect/io/Fiber/Scope")
  4766. class Global {
  4767. constructor() {
  4768. this[fiberScope_a] = FiberScopeTypeId
  4769. this.fiberId = Id_none
  4770. this.roots = new Set()
  4771. }
  4772. add(_runtimeFlags, child) {
  4773. this.roots.add(child)
  4774. child.unsafeAddObserver(() => {
  4775. this.roots.delete(child)
  4776. })
  4777. }
  4778. }
  4779. fiberScope_a = FiberScopeTypeId
  4780. class Local {
  4781. constructor(fiberId, parent) {
  4782. this.fiberId = fiberId
  4783. this.parent = parent
  4784. this[fiberScope_b] = FiberScopeTypeId
  4785. }
  4786. add(_runtimeFlags, child) {
  4787. this.parent.tell(
  4788. stateful(parentFiber => {
  4789. parentFiber.addChild(child)
  4790. child.unsafeAddObserver(() => {
  4791. parentFiber.removeChild(child)
  4792. })
  4793. })
  4794. )
  4795. }
  4796. }
  4797. fiberScope_b = FiberScopeTypeId
  4798. const globalScope = globalValue(
  4799. Symbol.for("@effect/io/FiberScope/Global"),
  4800. () => new Global()
  4801. ),
  4802. FiberTypeId = Symbol.for("@effect/io/Fiber"),
  4803. fiberVariance = { _E: _ => _, _A: _ => _ },
  4804. RuntimeFiberTypeId = Symbol.for("@effect/io/Fiber"),
  4805. _await = methodWithTrace(trace => self => self.await().traced(trace)),
  4806. fiber_join = methodWithTrace(
  4807. trace => self =>
  4808. zipLeft(core_flatten(self.await()), self.inheritAll()).traced(trace)
  4809. ),
  4810. currentFiberURI = "@effect/io/Fiber/Current",
  4811. MutableList_TypeId = Symbol.for("@effect/data/MutableList")
  4812. class MutableListImpl {
  4813. constructor() {
  4814. this._id = MutableList_TypeId
  4815. this.head = void 0
  4816. this.tail = void 0
  4817. this._length = 0
  4818. }
  4819. [Symbol.iterator]() {
  4820. let done = !1,
  4821. head = this.head
  4822. return {
  4823. next() {
  4824. if (done) return this.return()
  4825. if (null == head) {
  4826. done = !0
  4827. return this.return()
  4828. }
  4829. const value = head.value
  4830. head = head.next
  4831. return { done, value }
  4832. },
  4833. return(value) {
  4834. done || (done = !0)
  4835. return { done: !0, value }
  4836. },
  4837. }
  4838. }
  4839. toString() {
  4840. return `MutableList(${Array.from(this).map(String).join(", ")})`
  4841. }
  4842. toJSON() {
  4843. return { _tag: "MutableList", values: Array.from(this) }
  4844. }
  4845. [Symbol.for("nodejs.util.inspect.custom")]() {
  4846. return this.toJSON()
  4847. }
  4848. }
  4849. class LinkedListNode {
  4850. constructor(value) {
  4851. this.value = value
  4852. this.removed = !1
  4853. this.prev = void 0
  4854. this.next = void 0
  4855. }
  4856. }
  4857. const MutableList_isEmpty = self => 0 === MutableList_length(self),
  4858. MutableList_length = self => self._length,
  4859. MutableList_append = Function_dual(2, (self, value) => {
  4860. const node = new LinkedListNode(value)
  4861. void 0 === self.head && (self.head = node)
  4862. if (void 0 === self.tail) self.tail = node
  4863. else {
  4864. self.tail.next = node
  4865. node.prev = self.tail
  4866. self.tail = node
  4867. }
  4868. self._length += 1
  4869. return self
  4870. }),
  4871. MutableQueue_TypeId = Symbol.for("@effect/data/MutableQueue")
  4872. class MutableQueueImpl {
  4873. constructor(capacity) {
  4874. this.capacity = capacity
  4875. this._tag = "Bounded"
  4876. this._id = MutableQueue_TypeId
  4877. this.queue = new MutableListImpl()
  4878. }
  4879. [Symbol.iterator]() {
  4880. return Array.from(this.queue)[Symbol.iterator]()
  4881. }
  4882. toString() {
  4883. return `MutableQueue(${Array.from(this).map(String).join(", ")})`
  4884. }
  4885. toJSON() {
  4886. return { _tag: "MutableQueue", values: Array.from(this) }
  4887. }
  4888. [Symbol.for("nodejs.util.inspect.custom")]() {
  4889. return this.toJSON()
  4890. }
  4891. }
  4892. const MutableQueue_isEmpty = self => MutableList_isEmpty(self.queue),
  4893. offer = Function_dual(2, (self, value) => {
  4894. const queueLength = MutableList_length(self.queue)
  4895. if (void 0 !== self.capacity && queueLength === self.capacity) return !1
  4896. MutableList_append(value)(self.queue)
  4897. return !0
  4898. }),
  4899. MutableQueue_poll = Function_dual(2, (self, def) =>
  4900. MutableList_isEmpty(self.queue)
  4901. ? def
  4902. : (self => {
  4903. const head = self.head
  4904. if (void 0 !== head) {
  4905. ;((self, node) => {
  4906. if (!node.removed) {
  4907. node.removed = !0
  4908. if (void 0 !== node.prev && void 0 !== node.next) {
  4909. node.prev.next = node.next
  4910. node.next.prev = node.prev
  4911. } else if (void 0 !== node.prev) {
  4912. self.tail = node.prev
  4913. node.prev.next = void 0
  4914. } else if (void 0 !== node.next) {
  4915. self.head = node.next
  4916. node.next.prev = void 0
  4917. } else {
  4918. self.tail = void 0
  4919. self.head = void 0
  4920. }
  4921. self._length > 0 && (self._length -= 1)
  4922. }
  4923. })(self, head)
  4924. return head.value
  4925. }
  4926. })(self.queue)
  4927. ),
  4928. renderToString = u => {
  4929. if (
  4930. "object" == typeof u &&
  4931. null != u &&
  4932. "toString" in u &&
  4933. "function" == typeof u.toString &&
  4934. u.toString !== Object.prototype.toString
  4935. )
  4936. return u.toString()
  4937. if ("string" == typeof u) return `Error: ${u}`
  4938. if (
  4939. "object" == typeof u &&
  4940. null !== u &&
  4941. "message" in u &&
  4942. "string" == typeof u.message
  4943. ) {
  4944. const raw = JSON.parse(JSON.stringify(u)),
  4945. keys = new Set(Object.keys(raw))
  4946. keys.delete("name")
  4947. keys.delete("message")
  4948. keys.delete("_tag")
  4949. if (0 === keys.size)
  4950. return `${
  4951. "name" in u && "string" == typeof u.name ? u.name : "Error"
  4952. }${
  4953. "_tag" in u && "string" == typeof u._tag ? `(${u._tag})` : ""
  4954. }: ${u.message}`
  4955. }
  4956. return `Error: ${JSON.stringify(u)}`
  4957. },
  4958. renderStack = span =>
  4959. Option_isNone(span)
  4960. ? []
  4961. : span.value.stack.length > 0
  4962. ? (chunk => {
  4963. const ret = []
  4964. for (const s of chunk) {
  4965. const r = s?.toFrame()
  4966. r &&
  4967. runtimeDebug.filterStackFrame(r) &&
  4968. ret.push(renderFrame(r))
  4969. }
  4970. return ret
  4971. })(span.value.stack)
  4972. : [],
  4973. defaultErrorToLines = error =>
  4974. error instanceof Error
  4975. ? (error => {
  4976. if (error.stack) {
  4977. const stack = runtimeDebug.parseStack(error),
  4978. traces = []
  4979. for (const frame of stack)
  4980. if (frame) {
  4981. if (!runtimeDebug.filterStackFrame(frame)) break
  4982. traces.push(renderFrame(frame))
  4983. }
  4984. return [renderToString(error), traces.join("\r\n")]
  4985. }
  4986. return [String(error), void 0]
  4987. })(error)
  4988. : [renderToString(error), void 0]
  4989. class RenderError {
  4990. constructor(seq, message, stack) {
  4991. this.seq = seq
  4992. this.message = message
  4993. this.stack = stack
  4994. }
  4995. }
  4996. const cause_pretty_pretty = cause => {
  4997. if (isInterruptedOnly(cause))
  4998. return "All fibers interrupted without errors."
  4999. const errors = prettyErrors(cause),
  5000. final = Array.from(errors)
  5001. .sort((a, b) => (a.seq === b.seq ? 0 : a.seq > b.seq ? 1 : -1))
  5002. .map(e => {
  5003. let message = e.message
  5004. e.stack && e.stack.length > 0 && (message += `\r\n${e.stack}`)
  5005. return message
  5006. })
  5007. .join("\r\n\r\n")
  5008. return final.includes("\r\n") ? `\r\n${final}\r\n` : final
  5009. },
  5010. prettyErrors = cause =>
  5011. reduceWithContext(cause, void 0, {
  5012. emptyCase: () => [],
  5013. dieCase: (_, err) => {
  5014. const rendered = defaultErrorToLines(err)
  5015. return [
  5016. {
  5017. message: rendered[0],
  5018. errorSack: rendered[1],
  5019. fiberStack: Option_none(),
  5020. },
  5021. ]
  5022. },
  5023. failCase: (_, err) => {
  5024. const rendered = defaultErrorToLines(err)
  5025. return [
  5026. {
  5027. message: rendered[0],
  5028. errorSack: rendered[1],
  5029. fiberStack: Option_none(),
  5030. },
  5031. ]
  5032. },
  5033. interruptCase: () => [],
  5034. parallelCase: (_, l, r) => [...l, ...r],
  5035. sequentialCase: (_, l, r) => [...l, ...r],
  5036. annotatedCase: (_, v, parent) =>
  5037. isStackAnnotation(parent)
  5038. ? v.map(r => ({
  5039. message: r.message,
  5040. errorSack: r.errorSack,
  5041. fiberStack: orElse(() => Option_some(parent))(
  5042. Option_map(
  5043. r.fiberStack,
  5044. annotation =>
  5045. new StackAnnotation(
  5046. annotation.stack.length <
  5047. runtimeDebug.traceStackLimit &&
  5048. parent.stack.length > 0 &&
  5049. ((annotation.stack.length > 0 &&
  5050. unsafeLast(parent.stack) !==
  5051. unsafeLast(annotation.stack)) ||
  5052. 0 === annotation.stack.length)
  5053. ? Chunk_take(runtimeDebug.traceStackLimit)(
  5054. dedupeAdjacent(
  5055. Chunk_concat(parent.stack)(annotation.stack)
  5056. )
  5057. )
  5058. : annotation.stack,
  5059. annotation.seq
  5060. )
  5061. )
  5062. ),
  5063. }))
  5064. : v,
  5065. }).flatMap(r =>
  5066. ((error, errorStack, stack) => [
  5067. new RenderError(
  5068. "Some" === stack._tag ? stack.value.seq : 0,
  5069. error,
  5070. errorStack
  5071. ? errorStack + "\r\n" + renderStack(stack).join("\r\n")
  5072. : renderStack(stack).join("\r\n")
  5073. ),
  5074. ])(r.message, r.errorSack, r.fiberStack)
  5075. )
  5076. function renderFrame(r) {
  5077. return r
  5078. ? r.name
  5079. ? ` at ${r.name} (${r.fileName}:${r.line}:${r.column})`
  5080. : ` at ${r.fileName}:${r.line}:${r.column}`
  5081. : " at <unknown>"
  5082. }
  5083. const LoggerTypeId = Symbol.for("@effect/io/Logger"),
  5084. loggerVariance = { _Message: _ => _, _Output: _ => _ },
  5085. makeLogger = log => ({ [LoggerTypeId]: loggerVariance, log }),
  5086. stringLogger = makeLogger(
  5087. (fiberId, logLevel, message, cause, _context, spans, annotations) => {
  5088. const now = new Date(),
  5089. nowMillis = now.getTime()
  5090. let output = [
  5091. `timestamp=${now.toISOString()}`,
  5092. `level=${logLevel.label}`,
  5093. `fiber=${threadName(fiberId)}`,
  5094. ].join(" ")
  5095. if (message.length > 0) {
  5096. output += " message="
  5097. output = appendQuoted(message, output)
  5098. }
  5099. if (null != cause && cause != cause_empty) {
  5100. output += " cause="
  5101. output = appendQuoted(cause_pretty_pretty(cause), output)
  5102. }
  5103. if (Chunk_isNonEmpty(spans)) {
  5104. output += " "
  5105. let first = !0
  5106. for (const span of spans) {
  5107. first ? (first = !1) : (output += " ")
  5108. output += Span_render(nowMillis)(span)
  5109. }
  5110. }
  5111. if (mjs_HashMap_size(annotations) > 0) {
  5112. output += " "
  5113. let first = !0
  5114. for (const [key, value] of annotations) {
  5115. first ? (first = !1) : (output += " ")
  5116. output += filterKeyName(key)
  5117. output += "="
  5118. output = appendQuoted(value, output)
  5119. }
  5120. }
  5121. return output
  5122. }
  5123. ),
  5124. textOnly = /^[^\s"=]+$/,
  5125. appendQuoted = (label, output) =>
  5126. output +
  5127. (label.match(textOnly)
  5128. ? label
  5129. : `"${label.replace(/\\([\s\S])|(")/g, "\\$1$2")}"`),
  5130. filterKeyName = key => key.replace(/[\s="]/g, "_"),
  5131. logger_zip = Function_dual(2, (self, that) =>
  5132. makeLogger(
  5133. (fiberId, logLevel, message, cause, context, spans, annotations) => [
  5134. self.log(
  5135. fiberId,
  5136. logLevel,
  5137. message,
  5138. cause,
  5139. context,
  5140. spans,
  5141. annotations
  5142. ),
  5143. that.log(
  5144. fiberId,
  5145. logLevel,
  5146. message,
  5147. cause,
  5148. context,
  5149. spans,
  5150. annotations
  5151. ),
  5152. ]
  5153. )
  5154. )
  5155. var keyType_a, keyType_b, _g, _h
  5156. const MetricKeyTypeTypeId = Symbol.for("@effect/io/Metric/KeyType"),
  5157. CounterKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Counter"),
  5158. FrequencyKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Frequency"),
  5159. GaugeKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Gauge"),
  5160. HistogramKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Histogram"),
  5161. SummaryKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Summary"),
  5162. metricKeyTypeVariance = { _In: _ => _, _Out: _ => _ }
  5163. class CounterKeyType {
  5164. constructor() {
  5165. this[keyType_a] = metricKeyTypeVariance
  5166. this[keyType_b] = CounterKeyTypeTypeId
  5167. }
  5168. [((keyType_a = MetricKeyTypeTypeId),
  5169. (keyType_b = CounterKeyTypeTypeId),
  5170. symbol)]() {
  5171. return Hash_hash("effect/io/Metric/KeyType/Counter")
  5172. }
  5173. [Equal_symbol](that) {
  5174. return isCounterKey(that)
  5175. }
  5176. }
  5177. class HistogramKeyType {
  5178. constructor(boundaries) {
  5179. this.boundaries = boundaries
  5180. this[_g] = metricKeyTypeVariance
  5181. this[_h] = HistogramKeyTypeTypeId
  5182. }
  5183. [((_g = MetricKeyTypeTypeId), (_h = HistogramKeyTypeTypeId), symbol)]() {
  5184. return combine(Hash_hash(this.boundaries))(
  5185. Hash_hash("effect/io/Metric/KeyType/Histogram")
  5186. )
  5187. }
  5188. [Equal_symbol](that) {
  5189. return isHistogramKey(that) && equals(this.boundaries, that.boundaries)
  5190. }
  5191. }
  5192. const counter = new CounterKeyType(),
  5193. isCounterKey = u =>
  5194. "object" == typeof u && null != u && CounterKeyTypeTypeId in u,
  5195. isFrequencyKey = u =>
  5196. "object" == typeof u && null != u && FrequencyKeyTypeTypeId in u,
  5197. isGaugeKey = u =>
  5198. "object" == typeof u && null != u && GaugeKeyTypeTypeId in u,
  5199. isHistogramKey = u =>
  5200. "object" == typeof u && null != u && HistogramKeyTypeTypeId in u,
  5201. isSummaryKey = u =>
  5202. "object" == typeof u && null != u && SummaryKeyTypeTypeId in u
  5203. var key_a
  5204. const MetricKeyTypeId = Symbol.for("@effect/io/Metric/Key"),
  5205. metricKeyVariance = { _Type: _ => _ }
  5206. class MetricKeyImpl {
  5207. constructor(name, keyType, tags = mjs_HashSet_empty()) {
  5208. this.name = name
  5209. this.keyType = keyType
  5210. this.tags = tags
  5211. this[key_a] = metricKeyVariance
  5212. }
  5213. [((key_a = MetricKeyTypeId), symbol)]() {
  5214. return combine(Hash_hash(this.tags))(
  5215. combine(Hash_hash(this.keyType))(Hash_hash(this.name))
  5216. )
  5217. }
  5218. [Equal_symbol](u) {
  5219. return (
  5220. isMetricKey(u) &&
  5221. this.name === u.name &&
  5222. equals(this.keyType, u.keyType) &&
  5223. equals(this.tags, u.tags)
  5224. )
  5225. }
  5226. }
  5227. const isMetricKey = u =>
  5228. "object" == typeof u && null != u && MetricKeyTypeId in u,
  5229. key_taggedWithLabelSet = Function_dual(2, (self, extraTags) =>
  5230. 0 === mjs_HashSet_size(extraTags)
  5231. ? self
  5232. : new MetricKeyImpl(
  5233. self.name,
  5234. self.keyType,
  5235. mjs_HashSet_union(extraTags)(self.tags)
  5236. )
  5237. )
  5238. var state_a,
  5239. state_b,
  5240. state_c,
  5241. state_d,
  5242. state_e,
  5243. state_f,
  5244. state_g,
  5245. state_h,
  5246. state_j,
  5247. state_k
  5248. const MetricStateTypeId = Symbol.for("@effect/io/Metric/State"),
  5249. CounterStateTypeId = Symbol.for("effect/io/Metric/State/Counter"),
  5250. FrequencyStateTypeId = Symbol.for("effect/io/Metric/State/Frequency"),
  5251. GaugeStateTypeId = Symbol.for("effect/io/Metric/State/Gauge"),
  5252. HistogramStateTypeId = Symbol.for("effect/io/Metric/State/Histogram"),
  5253. SummaryStateTypeId = Symbol.for("effect/io/Metric/State/Summary"),
  5254. metricStateVariance = { _A: _ => _ }
  5255. class CounterState {
  5256. constructor(count) {
  5257. this.count = count
  5258. this[state_a] = metricStateVariance
  5259. this[state_b] = CounterStateTypeId
  5260. }
  5261. [((state_a = MetricStateTypeId),
  5262. (state_b = CounterStateTypeId),
  5263. symbol)]() {
  5264. return combine(Hash_hash(this.count))(
  5265. Hash_hash("effect/io/Metric/State/Counter")
  5266. )
  5267. }
  5268. [Equal_symbol](that) {
  5269. return isCounterState(that) && this.count === that.count
  5270. }
  5271. }
  5272. class FrequencyState {
  5273. constructor(occurrences) {
  5274. this.occurrences = occurrences
  5275. this[state_c] = metricStateVariance
  5276. this[state_d] = FrequencyStateTypeId
  5277. }
  5278. [((state_c = MetricStateTypeId),
  5279. (state_d = FrequencyStateTypeId),
  5280. symbol)]() {
  5281. return combine(Hash_hash(this.occurrences))(
  5282. Hash_hash("effect/io/Metric/State/Frequency")
  5283. )
  5284. }
  5285. [Equal_symbol](that) {
  5286. return (
  5287. isFrequencyState(that) && equals(this.occurrences, that.occurrences)
  5288. )
  5289. }
  5290. }
  5291. class GaugeState {
  5292. constructor(value) {
  5293. this.value = value
  5294. this[state_e] = metricStateVariance
  5295. this[state_f] = GaugeStateTypeId
  5296. }
  5297. [((state_e = MetricStateTypeId),
  5298. (state_f = GaugeStateTypeId),
  5299. symbol)]() {
  5300. return combine(Hash_hash(this.value))(
  5301. Hash_hash("effect/io/Metric/State/Gauge")
  5302. )
  5303. }
  5304. [Equal_symbol](u) {
  5305. return isGaugeState(u) && this.value === u.value
  5306. }
  5307. }
  5308. class HistogramState {
  5309. constructor(buckets, count, min, max, sum) {
  5310. this.buckets = buckets
  5311. this.count = count
  5312. this.min = min
  5313. this.max = max
  5314. this.sum = sum
  5315. this[state_g] = metricStateVariance
  5316. this[state_h] = HistogramStateTypeId
  5317. }
  5318. [((state_g = MetricStateTypeId),
  5319. (state_h = HistogramStateTypeId),
  5320. symbol)]() {
  5321. return combine(Hash_hash(this.sum))(
  5322. combine(Hash_hash(this.max))(
  5323. combine(Hash_hash(this.min))(
  5324. combine(Hash_hash(this.count))(
  5325. combine(Hash_hash(this.buckets))(
  5326. Hash_hash("effect/io/Metric/State/Histogram")
  5327. )
  5328. )
  5329. )
  5330. )
  5331. )
  5332. }
  5333. [Equal_symbol](that) {
  5334. return (
  5335. isHistogramState(that) &&
  5336. equals(this.buckets, that.buckets) &&
  5337. this.count === that.count &&
  5338. this.min === that.min &&
  5339. this.max === that.max &&
  5340. this.sum === that.sum
  5341. )
  5342. }
  5343. }
  5344. class SummaryState {
  5345. constructor(error, quantiles, count, min, max, sum) {
  5346. this.error = error
  5347. this.quantiles = quantiles
  5348. this.count = count
  5349. this.min = min
  5350. this.max = max
  5351. this.sum = sum
  5352. this[state_j] = metricStateVariance
  5353. this[state_k] = SummaryStateTypeId
  5354. }
  5355. [((state_j = MetricStateTypeId),
  5356. (state_k = SummaryStateTypeId),
  5357. symbol)]() {
  5358. return combine(Hash_hash(this.sum))(
  5359. combine(Hash_hash(this.max))(
  5360. combine(Hash_hash(this.min))(
  5361. combine(Hash_hash(this.count))(
  5362. combine(Hash_hash(this.quantiles))(
  5363. combine(Hash_hash(this.error))(
  5364. Hash_hash("effect/io/Metric/State/Summary")
  5365. )
  5366. )
  5367. )
  5368. )
  5369. )
  5370. )
  5371. }
  5372. [Equal_symbol](that) {
  5373. return (
  5374. isSummaryState(that) &&
  5375. this.error === that.error &&
  5376. equals(this.quantiles, that.quantiles) &&
  5377. this.count === that.count &&
  5378. this.min === that.min &&
  5379. this.max === that.max &&
  5380. this.sum === that.sum
  5381. )
  5382. }
  5383. }
  5384. const isCounterState = u =>
  5385. "object" == typeof u && null != u && CounterStateTypeId in u,
  5386. isFrequencyState = u =>
  5387. "object" == typeof u && null != u && FrequencyStateTypeId in u,
  5388. isGaugeState = u =>
  5389. "object" == typeof u && null != u && GaugeStateTypeId in u,
  5390. isHistogramState = u =>
  5391. "object" == typeof u && null != u && HistogramStateTypeId in u,
  5392. isSummaryState = u =>
  5393. "object" == typeof u && null != u && SummaryStateTypeId in u,
  5394. MetricHookTypeId = Symbol.for("@effect/io/Metric/Hook"),
  5395. metricHookVariance = { _In: _ => _, _Out: _ => _ },
  5396. hook_make = (get, update) => ({
  5397. [MetricHookTypeId]: metricHookVariance,
  5398. update,
  5399. get,
  5400. }),
  5401. calculateQuantiles = (error, sortedQuantiles, sortedSamples) => {
  5402. const sampleCount = sortedSamples.length
  5403. if (Chunk_isEmpty(sortedQuantiles)) return Chunk_empty()
  5404. const head = unsafeHead(sortedQuantiles),
  5405. tail = Chunk_drop(1)(sortedQuantiles),
  5406. resolved = Chunk_reduce(
  5407. Chunk_of(
  5408. resolveQuantile(
  5409. error,
  5410. sampleCount,
  5411. Option_none(),
  5412. 0,
  5413. head,
  5414. sortedSamples
  5415. )
  5416. ),
  5417. (accumulator, quantile) => {
  5418. const h = unsafeHead(accumulator)
  5419. return Chunk_append(
  5420. resolveQuantile(
  5421. error,
  5422. sampleCount,
  5423. h.value,
  5424. h.consumed,
  5425. quantile,
  5426. h.rest
  5427. )
  5428. )(accumulator)
  5429. }
  5430. )(tail)
  5431. return Chunk_map(rq => [rq.quantile, rq.value])(resolved)
  5432. },
  5433. resolveQuantile = (
  5434. error,
  5435. sampleCount,
  5436. current,
  5437. consumed,
  5438. quantile,
  5439. rest
  5440. ) => {
  5441. let error_1 = error,
  5442. sampleCount_1 = sampleCount,
  5443. current_1 = current,
  5444. consumed_1 = consumed,
  5445. quantile_1 = quantile,
  5446. rest_1 = rest,
  5447. error_2 = error,
  5448. sampleCount_2 = sampleCount,
  5449. current_2 = current,
  5450. consumed_2 = consumed,
  5451. quantile_2 = quantile,
  5452. rest_2 = rest
  5453. for (;;) {
  5454. if (Chunk_isEmpty(rest_1))
  5455. return {
  5456. quantile: quantile_1,
  5457. value: Option_none(),
  5458. consumed: consumed_1,
  5459. rest: Chunk_empty(),
  5460. }
  5461. if (1 === quantile_1)
  5462. return {
  5463. quantile: quantile_1,
  5464. value: Option_some(unsafeLast(rest_1)),
  5465. consumed: consumed_1 + rest_1.length,
  5466. rest: Chunk_empty(),
  5467. }
  5468. const sameHead = splitWhere(n => n > unsafeHead(rest_1))(rest_1),
  5469. desired = quantile_1 * sampleCount_1,
  5470. allowedError = (error_1 / 2) * desired,
  5471. candConsumed = consumed_1 + sameHead[0].length,
  5472. candError = Math.abs(candConsumed - desired)
  5473. if (candConsumed < desired - allowedError) {
  5474. error_2 = error_1
  5475. sampleCount_2 = sampleCount_1
  5476. current_2 = Chunk_head(rest_1)
  5477. consumed_2 = candConsumed
  5478. quantile_2 = quantile_1
  5479. rest_2 = sameHead[1]
  5480. error_1 = error_2
  5481. sampleCount_1 = sampleCount_2
  5482. current_1 = current_2
  5483. consumed_1 = consumed_2
  5484. quantile_1 = quantile_2
  5485. rest_1 = rest_2
  5486. } else {
  5487. if (candConsumed > desired + allowedError)
  5488. return {
  5489. quantile: quantile_1,
  5490. value: current_1,
  5491. consumed: consumed_1,
  5492. rest: rest_1,
  5493. }
  5494. switch (current_1._tag) {
  5495. case "None":
  5496. error_2 = error_1
  5497. sampleCount_2 = sampleCount_1
  5498. current_2 = Chunk_head(rest_1)
  5499. consumed_2 = candConsumed
  5500. quantile_2 = quantile_1
  5501. rest_2 = sameHead[1]
  5502. error_1 = error_2
  5503. sampleCount_1 = sampleCount_2
  5504. current_1 = current_2
  5505. consumed_1 = consumed_2
  5506. quantile_1 = quantile_2
  5507. rest_1 = rest_2
  5508. continue
  5509. case "Some":
  5510. if (candError < Math.abs(desired - current_1.value)) {
  5511. error_2 = error_1
  5512. sampleCount_2 = sampleCount_1
  5513. current_2 = Chunk_head(rest_1)
  5514. consumed_2 = candConsumed
  5515. quantile_2 = quantile_1
  5516. rest_2 = sameHead[1]
  5517. error_1 = error_2
  5518. sampleCount_1 = sampleCount_2
  5519. current_1 = current_2
  5520. consumed_1 = consumed_2
  5521. quantile_1 = quantile_2
  5522. rest_1 = rest_2
  5523. continue
  5524. }
  5525. return {
  5526. quantile: quantile_1,
  5527. value: Option_some(current_1.value),
  5528. consumed: consumed_1,
  5529. rest: rest_1,
  5530. }
  5531. }
  5532. }
  5533. }
  5534. throw new Error(
  5535. "BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/io/issues"
  5536. )
  5537. },
  5538. MetricPairTypeId = Symbol.for("@effect/io/Metric/Pair"),
  5539. metricPairVariance = { _Type: _ => _ }
  5540. var registry_a
  5541. const MetricRegistryTypeId = Symbol.for("@effect/io/Metric/Registry")
  5542. class MetricRegistryImpl {
  5543. constructor() {
  5544. this[registry_a] = MetricRegistryTypeId
  5545. this.map = new MutableHashMapImpl()
  5546. }
  5547. snapshot() {
  5548. const result = []
  5549. for (const [key, hook] of this.map)
  5550. result.push(
  5551. ((metricKey = key),
  5552. (metricState = hook.get()),
  5553. { [MetricPairTypeId]: metricPairVariance, metricKey, metricState })
  5554. )
  5555. var metricKey, metricState
  5556. return (elements => {
  5557. const set = HashSet_beginMutation(HashSet_empty())
  5558. for (const value of elements) HashSet_add(set, value)
  5559. return HashSet_endMutation(set)
  5560. })(result)
  5561. }
  5562. get(key) {
  5563. const hook = getOrUndefined(MutableHashMap_get(key)(this.map))
  5564. if (null == hook) {
  5565. if (isCounterKey(key.keyType)) return this.getCounter(key)
  5566. if (isGaugeKey(key.keyType)) return this.getGauge(key)
  5567. if (isFrequencyKey(key.keyType)) return this.getFrequency(key)
  5568. if (isHistogramKey(key.keyType)) return this.getHistogram(key)
  5569. if (isSummaryKey(key.keyType)) return this.getSummary(key)
  5570. throw new Error(
  5571. "BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/io/issues"
  5572. )
  5573. }
  5574. return hook
  5575. }
  5576. getCounter(key) {
  5577. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5578. if (null == value) {
  5579. const counter = (_key => {
  5580. let sum = 0
  5581. return hook_make(
  5582. () => new CounterState(sum),
  5583. value => {
  5584. sum += value
  5585. }
  5586. )
  5587. })()
  5588. MutableHashMap_has(key)(this.map) ||
  5589. MutableHashMap_set(key, counter)(this.map)
  5590. value = counter
  5591. }
  5592. return value
  5593. }
  5594. getFrequency(key) {
  5595. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5596. if (null == value) {
  5597. const frequency = (_key => {
  5598. let count = 0
  5599. const values = new Map()
  5600. return hook_make(
  5601. () => {
  5602. return (
  5603. (occurrences = mjs_HashMap_fromIterable(
  5604. Array.from(values.entries()).map(([k, v]) => [k, v])
  5605. )),
  5606. new FrequencyState(occurrences)
  5607. )
  5608. var occurrences
  5609. },
  5610. word => {
  5611. count += 1
  5612. const slotCount = values.get(word) ?? 0
  5613. values.set(word, slotCount + 1)
  5614. }
  5615. )
  5616. })()
  5617. MutableHashMap_has(key)(this.map) ||
  5618. MutableHashMap_set(key, frequency)(this.map)
  5619. value = frequency
  5620. }
  5621. return value
  5622. }
  5623. getGauge(key) {
  5624. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5625. if (null == value) {
  5626. const gauge = ((_key, startAt) => {
  5627. let value = startAt
  5628. return hook_make(
  5629. () => (value => new GaugeState(value))(value),
  5630. v => {
  5631. value = v
  5632. }
  5633. )
  5634. })(0, 0)
  5635. MutableHashMap_has(key)(this.map) ||
  5636. MutableHashMap_set(key, gauge)(this.map)
  5637. value = gauge
  5638. }
  5639. return value
  5640. }
  5641. getHistogram(key) {
  5642. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5643. if (null == value) {
  5644. const histogram = (key => {
  5645. const bounds = key.keyType.boundaries.values,
  5646. size = bounds.length,
  5647. values = Array(size + 1),
  5648. boundaries = Array(size)
  5649. let count = 0,
  5650. sum = 0,
  5651. min = Number.MAX_VALUE,
  5652. max = Number.MIN_VALUE
  5653. mapWithIndex((i, n) => {
  5654. boundaries[i] = n
  5655. })(Chunk_sort(Order)(bounds))
  5656. return hook_make(
  5657. () =>
  5658. ((buckets, count, min, max, sum) =>
  5659. new HistogramState(buckets, count, min, max, sum))(
  5660. (() => {
  5661. const builder = []
  5662. let i = 0,
  5663. cumulated = 0
  5664. for (; i != size; ) {
  5665. const boundary = boundaries[i]
  5666. cumulated += values[i]
  5667. builder.push([boundary, cumulated])
  5668. i += 1
  5669. }
  5670. return Chunk_fromIterable(builder)
  5671. })(),
  5672. count,
  5673. min,
  5674. max,
  5675. sum
  5676. ),
  5677. value => {
  5678. let from = 0,
  5679. to = size
  5680. for (; from !== to; ) {
  5681. const mid = Math.floor(from + (to - from) / 2)
  5682. value <= boundaries[mid] ? (to = mid) : (from = mid)
  5683. to === from + 1 &&
  5684. (value <= boundaries[from] ? (to = from) : (from = to))
  5685. }
  5686. values[from] = values[from] + 1
  5687. count += 1
  5688. sum += value
  5689. value < min && (min = value)
  5690. value > max && (max = value)
  5691. }
  5692. )
  5693. })(key)
  5694. MutableHashMap_has(key)(this.map) ||
  5695. MutableHashMap_set(key, histogram)(this.map)
  5696. value = histogram
  5697. }
  5698. return value
  5699. }
  5700. getSummary(key) {
  5701. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5702. if (null == value) {
  5703. const summary = (key => {
  5704. const { error, maxAge, maxSize, quantiles } = key.keyType,
  5705. sortedQuantiles = Chunk_sort(Order)(quantiles),
  5706. values = Array(maxSize)
  5707. let head = 0,
  5708. count = 0,
  5709. sum = 0,
  5710. min = Number.MAX_VALUE,
  5711. max = Number.MIN_VALUE
  5712. return hook_make(
  5713. () =>
  5714. ((error, quantiles, count, min, max, sum) =>
  5715. new SummaryState(error, quantiles, count, min, max, sum))(
  5716. error,
  5717. (now => {
  5718. const builder = []
  5719. let i = 0
  5720. for (; i !== maxSize - 1; ) {
  5721. const item = values[i]
  5722. if (null != item) {
  5723. const [t, v] = item,
  5724. age = millis(now - t)
  5725. age.millis >= 0 && age <= maxAge && builder.push(v)
  5726. }
  5727. i += 1
  5728. }
  5729. return calculateQuantiles(
  5730. error,
  5731. sortedQuantiles,
  5732. Chunk_sort(Order)(Chunk_fromIterable(builder))
  5733. )
  5734. })(Date.now()),
  5735. count,
  5736. min,
  5737. max,
  5738. sum
  5739. ),
  5740. ([value, timestamp]) =>
  5741. ((value, timestamp) => {
  5742. if (maxSize > 0) {
  5743. head += 1
  5744. values[head % maxSize] = [timestamp, value]
  5745. }
  5746. count += 1
  5747. sum += value
  5748. value < min && (min = value)
  5749. value > max && (max = value)
  5750. })(value, timestamp)
  5751. )
  5752. })(key)
  5753. MutableHashMap_has(key)(this.map) ||
  5754. MutableHashMap_set(key, summary)(this.map)
  5755. value = summary
  5756. }
  5757. return value
  5758. }
  5759. }
  5760. registry_a = MetricRegistryTypeId
  5761. const MetricTypeId = Symbol.for("@effect/io/Metric"),
  5762. metricVariance = { _Type: _ => _, _In: _ => _, _Out: _ => _ },
  5763. globalMetricRegistry = globalValue(
  5764. Symbol.for("@effect/io/Metric/globalMetricRegistry"),
  5765. () => new MetricRegistryImpl()
  5766. ),
  5767. metric_counter = name =>
  5768. fromMetricKey((name => new MetricKeyImpl(name, counter))(name)),
  5769. fromMetricKey = key => {
  5770. const hook = extraTags => {
  5771. const fullKey = key_taggedWithLabelSet(extraTags)(key)
  5772. return globalMetricRegistry.get(fullKey)
  5773. }
  5774. return (function (keyType, unsafeUpdate, unsafeValue) {
  5775. const metric = Object.assign(
  5776. methodWithTrace(
  5777. (trace, restore) => effect =>
  5778. core_tap(effect, a =>
  5779. sync(() => restore(unsafeUpdate)(a, mjs_HashSet_empty()))
  5780. ).traced(trace)
  5781. ),
  5782. {
  5783. [MetricTypeId]: metricVariance,
  5784. keyType,
  5785. unsafeUpdate,
  5786. unsafeValue,
  5787. }
  5788. )
  5789. return metric
  5790. })(
  5791. key.keyType,
  5792. (input, extraTags) => hook(extraTags).update(input),
  5793. extraTags => hook(extraTags).get()
  5794. )
  5795. },
  5796. metric_histogram = (name, boundaries) =>
  5797. fromMetricKey(
  5798. ((name, boundaries) =>
  5799. new MetricKeyImpl(
  5800. name,
  5801. (boundaries => new HistogramKeyType(boundaries))(boundaries)
  5802. ))(name, boundaries)
  5803. )
  5804. var boundaries_a
  5805. const MetricBoundariesTypeId = Symbol.for("@effect/io/Metric/Boundaries")
  5806. class MetricBoundariesImpl {
  5807. constructor(values) {
  5808. this.values = values
  5809. this[boundaries_a] = MetricBoundariesTypeId
  5810. }
  5811. [((boundaries_a = MetricBoundariesTypeId), symbol)]() {
  5812. return combine(Hash_hash(this.values))(
  5813. Hash_hash("@effect/io/Metric/Boundaries")
  5814. )
  5815. }
  5816. [Equal_symbol](u) {
  5817. return isMetricBoundaries(u) && equals(this.values, u.values)
  5818. }
  5819. }
  5820. const isMetricBoundaries = u =>
  5821. "object" == typeof u && null != u && MetricBoundariesTypeId in u,
  5822. fromChunk = chunk => {
  5823. const values = (self =>
  5824. unsafeFromArray(
  5825. uniq(
  5826. (self, that) =>
  5827. Hash_hash(self) === Hash_hash(that) && equals(self, that)
  5828. )(toReadonlyArray(self))
  5829. ))(Chunk_concat(Chunk_of(Number.POSITIVE_INFINITY))(chunk))
  5830. return new MetricBoundariesImpl(values)
  5831. },
  5832. exponential = (start, factor, count) => {
  5833. return fromChunk(
  5834. Chunk_map(i => start * Math.pow(factor, i))(
  5835. 0 <= (end = count - 1)
  5836. ? Chunk_makeBy(end - 0 + 1, i => 0 + i)
  5837. : Chunk_of(0)
  5838. )
  5839. )
  5840. var end
  5841. }
  5842. var supervisor_a, supervisor_b, supervisor_d
  5843. const SupervisorTypeId = Symbol.for("@effect/io/Supervisor"),
  5844. supervisorVariance = { _T: _ => _ }
  5845. class ProxySupervisor {
  5846. constructor(underlying, value0) {
  5847. this.underlying = underlying
  5848. this.value0 = value0
  5849. this[supervisor_a] = supervisorVariance
  5850. }
  5851. value() {
  5852. return bodyWithTrace(trace => this.value0().traced(trace))
  5853. }
  5854. onStart(context, effect, parent, fiber) {
  5855. this.underlying.onStart(context, effect, parent, fiber)
  5856. }
  5857. onEnd(value, fiber) {
  5858. this.underlying.onEnd(value, fiber)
  5859. }
  5860. onEffect(fiber, effect) {
  5861. this.underlying.onEffect(fiber, effect)
  5862. }
  5863. onSuspend(fiber) {
  5864. this.underlying.onSuspend(fiber)
  5865. }
  5866. onResume(fiber) {
  5867. this.underlying.onResume(fiber)
  5868. }
  5869. map(f) {
  5870. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  5871. }
  5872. zip(right) {
  5873. return new Zip(this, right)
  5874. }
  5875. }
  5876. supervisor_a = SupervisorTypeId
  5877. class Zip {
  5878. constructor(left, right) {
  5879. this.left = left
  5880. this.right = right
  5881. this[supervisor_b] = supervisorVariance
  5882. }
  5883. value() {
  5884. return bodyWithTrace(trace =>
  5885. core_zip(this.left.value(), this.right.value()).traced(trace)
  5886. )
  5887. }
  5888. onStart(context, effect, parent, fiber) {
  5889. this.left.onStart(context, effect, parent, fiber)
  5890. this.right.onStart(context, effect, parent, fiber)
  5891. }
  5892. onEnd(value, fiber) {
  5893. this.left.onEnd(value, fiber)
  5894. this.right.onEnd(value, fiber)
  5895. }
  5896. onEffect(fiber, effect) {
  5897. this.left.onEffect(fiber, effect)
  5898. this.right.onEffect(fiber, effect)
  5899. }
  5900. onSuspend(fiber) {
  5901. this.left.onSuspend(fiber)
  5902. this.right.onSuspend(fiber)
  5903. }
  5904. onResume(fiber) {
  5905. this.left.onResume(fiber)
  5906. this.right.onResume(fiber)
  5907. }
  5908. map(f) {
  5909. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  5910. }
  5911. zip(right) {
  5912. return new Zip(this, right)
  5913. }
  5914. }
  5915. supervisor_b = SupervisorTypeId
  5916. class Const {
  5917. constructor(effect) {
  5918. this.effect = effect
  5919. this[supervisor_d] = supervisorVariance
  5920. }
  5921. value() {
  5922. return bodyWithTrace(trace => this.effect.traced(trace))
  5923. }
  5924. onStart(_context, _effect, _parent, _fiber) {}
  5925. onEnd(_value, _fiber) {}
  5926. onEffect(_fiber, _effect) {}
  5927. onSuspend(_fiber) {}
  5928. onResume(_fiber) {}
  5929. map(f) {
  5930. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  5931. }
  5932. zip(right) {
  5933. return new Zip(this, right)
  5934. }
  5935. }
  5936. supervisor_d = SupervisorTypeId
  5937. const supervisor_none = (effect => new Const(effect))(core_unit()),
  5938. supervisor_patch_empty = { _tag: "Empty" },
  5939. supervisor_patch_combine = (self, that) => ({
  5940. _tag: "AndThen",
  5941. first: self,
  5942. second: that,
  5943. }),
  5944. removeSupervisor = (self, that) =>
  5945. equals(self, that)
  5946. ? supervisor_none
  5947. : self instanceof Zip
  5948. ? removeSupervisor(self.left, that).zip(
  5949. removeSupervisor(self.right, that)
  5950. )
  5951. : self,
  5952. patch_toSet = self =>
  5953. equals(self, supervisor_none)
  5954. ? mjs_HashSet_empty()
  5955. : self instanceof Zip
  5956. ? mjs_HashSet_union(patch_toSet(self.right))(patch_toSet(self.left))
  5957. : mjs_HashSet_make(self),
  5958. patch_differ = mjs_Differ_make({
  5959. empty: supervisor_patch_empty,
  5960. patch: (self, supervisor) =>
  5961. ((_supervisor, _patches) => {
  5962. let supervisor = _supervisor,
  5963. patches = _patches
  5964. for (; Chunk_isNonEmpty(patches); ) {
  5965. const head = Chunk_headNonEmpty(patches)
  5966. switch (head._tag) {
  5967. case "Empty":
  5968. patches = Chunk_tailNonEmpty(patches)
  5969. break
  5970. case "AddSupervisor":
  5971. supervisor = supervisor.zip(head.supervisor)
  5972. patches = Chunk_tailNonEmpty(patches)
  5973. break
  5974. case "RemoveSupervisor":
  5975. supervisor = removeSupervisor(supervisor, head.supervisor)
  5976. patches = Chunk_tailNonEmpty(patches)
  5977. break
  5978. case "AndThen":
  5979. patches = Chunk_prepend(head.first)(
  5980. Chunk_prepend(head.second)(Chunk_tailNonEmpty(patches))
  5981. )
  5982. }
  5983. }
  5984. return supervisor
  5985. })(supervisor, Chunk_of(self)),
  5986. combine: supervisor_patch_combine,
  5987. diff: (oldValue, newValue) => {
  5988. if (equals(oldValue, newValue)) return supervisor_patch_empty
  5989. const oldSupervisors = patch_toSet(oldValue),
  5990. newSupervisors = patch_toSet(newValue),
  5991. added = mjs_HashSet_reduce(
  5992. supervisor_patch_empty,
  5993. (patch, supervisor) =>
  5994. supervisor_patch_combine(patch, {
  5995. _tag: "AddSupervisor",
  5996. supervisor,
  5997. })
  5998. )(mjs_HashSet_difference(oldSupervisors)(newSupervisors)),
  5999. removed = mjs_HashSet_reduce(
  6000. supervisor_patch_empty,
  6001. (patch, supervisor) =>
  6002. supervisor_patch_combine(patch, {
  6003. _tag: "RemoveSupervisor",
  6004. supervisor,
  6005. })
  6006. )(mjs_HashSet_difference(newSupervisors)(oldSupervisors))
  6007. return supervisor_patch_combine(added, removed)
  6008. },
  6009. })
  6010. var fiberRuntime_a, fiberRuntime_b
  6011. const fibersStarted = metric_counter("effect_fiber_started"),
  6012. fiberSuccesses = metric_counter("effect_fiber_successes"),
  6013. fiberFailures = metric_counter("effect_fiber_failures"),
  6014. fiberLifetimes = metric_histogram(
  6015. "effect_fiber_lifetimes",
  6016. exponential(1, 2, 100)
  6017. ),
  6018. runtimeFiberVariance = { _E: _ => _, _A: _ => _ },
  6019. fiberRuntime_absurd = _ => {
  6020. throw new Error(
  6021. `BUG: FiberRuntime - ${JSON.stringify(
  6022. _
  6023. )} - please report an issue at https://github.com/Effect-TS/io/issues`
  6024. )
  6025. },
  6026. contOpSuccess = {
  6027. OnSuccess: (_, cont, value) => cont.i1(value),
  6028. OnSuccessAndFailure: (_, cont, value) => cont.i2(value),
  6029. RevertFlags: (self, cont, value) => {
  6030. self.patchRuntimeFlags(self._runtimeFlags, cont.patch)
  6031. return interruptible(self._runtimeFlags) && self.isInterrupted()
  6032. ? exitFailCause(self.getInterruptedCause())
  6033. : exitSucceed(value)
  6034. },
  6035. While: (self, cont, value) => {
  6036. cont.i2(value)
  6037. if (cont.i0()) {
  6038. self.pushStack(cont)
  6039. return cont.i1()
  6040. }
  6041. return core_unit()
  6042. },
  6043. },
  6044. drainQueueWhileRunningTable = {
  6045. InterruptSignal: (self, runtimeFlags, cur, message) => {
  6046. self.processNewInterruptSignal(message.cause)
  6047. return interruptible(runtimeFlags)
  6048. ? exitFailCause(message.cause)
  6049. : cur
  6050. },
  6051. Resume: (_self, _runtimeFlags, _cur, _message) => {
  6052. throw new Error(
  6053. "It is illegal to have multiple concurrent run loops in a single fiber"
  6054. )
  6055. },
  6056. Stateful: (self, runtimeFlags, cur, message) => {
  6057. message.onFiber(self, Status_running(runtimeFlags))
  6058. return cur
  6059. },
  6060. YieldNow: (_self, _runtimeFlags, cur, _message) =>
  6061. core_flatMap(() => cur)(yieldNow()),
  6062. }
  6063. class FiberRuntime {
  6064. constructor(fiberId, fiberRefs0, runtimeFlags0) {
  6065. this[fiberRuntime_a] = fiberVariance
  6066. this[fiberRuntime_b] = runtimeFiberVariance
  6067. this._queue = new MutableQueueImpl()
  6068. this._children = null
  6069. this._observers = new Array()
  6070. this._running = !1
  6071. this._stack = []
  6072. this._asyncInterruptor = null
  6073. this._asyncBlockingOn = null
  6074. this._exitValue = null
  6075. this._traceStack = []
  6076. this.run = () => {
  6077. this.drainQueueOnCurrentThread()
  6078. }
  6079. this._runtimeFlags = runtimeFlags0
  6080. this._fiberId = fiberId
  6081. this._fiberRefs = fiberRefs0
  6082. if (runtimeMetrics(runtimeFlags0)) {
  6083. const tags = this.getFiberRef(currentTags)
  6084. fibersStarted.unsafeUpdate(1, tags)
  6085. }
  6086. }
  6087. id() {
  6088. return this._fiberId
  6089. }
  6090. resume(effect) {
  6091. this.tell(resume(effect))
  6092. }
  6093. status() {
  6094. return this.ask((_, status) => status)
  6095. }
  6096. runtimeFlags() {
  6097. return this.ask((state, status) =>
  6098. (self => "Done" === self._tag)(status)
  6099. ? state._runtimeFlags
  6100. : status.runtimeFlags
  6101. )
  6102. }
  6103. scope() {
  6104. return new Local((fiber = this).id(), fiber)
  6105. var fiber
  6106. }
  6107. children() {
  6108. return this.ask(fiber => Chunk_fromIterable(fiber.getChildren()))
  6109. }
  6110. getChildren() {
  6111. null === this._children && (this._children = new Set())
  6112. return this._children
  6113. }
  6114. getSupervisor() {
  6115. return this.getFiberRef(currentSupervisor)
  6116. }
  6117. getInterruptedCause() {
  6118. return this.getFiberRef(interruptedCause)
  6119. }
  6120. fiberRefs() {
  6121. return this.ask(fiber => fiber.unsafeGetFiberRefs())
  6122. }
  6123. ask(f) {
  6124. return untraced(() =>
  6125. suspend(() => {
  6126. const deferred = deferredUnsafeMake(this._fiberId)
  6127. this.tell(
  6128. stateful((fiber, status) => {
  6129. deferredUnsafeDone(
  6130. deferred,
  6131. sync(() => f(fiber, status))
  6132. )
  6133. })
  6134. )
  6135. return deferredAwait(deferred)
  6136. })
  6137. )
  6138. }
  6139. tell(message) {
  6140. offer(message)(this._queue)
  6141. if (!this._running) {
  6142. this._running = !0
  6143. this.drainQueueLaterOnExecutor()
  6144. }
  6145. }
  6146. await() {
  6147. return untraced(() =>
  6148. asyncInterrupt(resume => {
  6149. const cb = exit => resume(succeed(exit))
  6150. this.tell(
  6151. stateful((fiber, _) => {
  6152. null !== fiber._exitValue
  6153. ? cb(this._exitValue)
  6154. : fiber.unsafeAddObserver(cb)
  6155. })
  6156. )
  6157. return sync(() =>
  6158. this.tell(
  6159. stateful((fiber, _) => {
  6160. fiber.unsafeRemoveObserver(cb)
  6161. })
  6162. )
  6163. )
  6164. }, this.id())
  6165. )
  6166. }
  6167. inheritAll() {
  6168. return untraced(() =>
  6169. withFiberRuntime((parentFiber, parentStatus) => {
  6170. const parentFiberId = parentFiber.id(),
  6171. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  6172. parentRuntimeFlags = parentStatus.runtimeFlags,
  6173. childFiberRefs = this.unsafeGetFiberRefs(),
  6174. updatedFiberRefs = joinAs(
  6175. parentFiberRefs,
  6176. parentFiberId,
  6177. childFiberRefs
  6178. )
  6179. parentFiber.setFiberRefs(updatedFiberRefs)
  6180. const updatedRuntimeFlags =
  6181. parentFiber.getFiberRef(currentRuntimeFlags),
  6182. patch = Patch_exclude(16)(
  6183. Patch_exclude(1)(
  6184. runtimeFlags_diff(parentRuntimeFlags, updatedRuntimeFlags)
  6185. )
  6186. )
  6187. return updateRuntimeFlags(patch)
  6188. })
  6189. )
  6190. }
  6191. poll() {
  6192. return untraced(() => sync(() => fromNullable(this._exitValue)))
  6193. }
  6194. unsafePoll() {
  6195. return this._exitValue
  6196. }
  6197. interruptAsFork(fiberId) {
  6198. return untraced(() =>
  6199. sync(() => this.tell(interruptSignal(interrupt(fiberId))))
  6200. )
  6201. }
  6202. unsafeAddObserver(observer) {
  6203. null !== this._exitValue
  6204. ? observer(this._exitValue)
  6205. : this._observers.push(observer)
  6206. }
  6207. unsafeRemoveObserver(observer) {
  6208. this._observers = this._observers.filter(o => o !== observer)
  6209. }
  6210. unsafeGetFiberRefs() {
  6211. this.setFiberRef(currentRuntimeFlags, this._runtimeFlags)
  6212. return this._fiberRefs
  6213. }
  6214. unsafeDeleteFiberRef(fiberRef) {
  6215. this._fiberRefs = delete_(this._fiberRefs, fiberRef)
  6216. }
  6217. getFiberRef(fiberRef) {
  6218. return getOrDefault(this._fiberRefs, fiberRef)
  6219. }
  6220. setFiberRef(fiberRef, value) {
  6221. this._fiberRefs = updatedAs(
  6222. this._fiberRefs,
  6223. this._fiberId,
  6224. fiberRef,
  6225. value
  6226. )
  6227. }
  6228. setFiberRefs(fiberRefs) {
  6229. this._fiberRefs = fiberRefs
  6230. }
  6231. addChild(child) {
  6232. this.getChildren().add(child)
  6233. }
  6234. removeChild(child) {
  6235. this.getChildren().delete(child)
  6236. }
  6237. drainQueueOnCurrentThread() {
  6238. let recurse = !0
  6239. for (; recurse; ) {
  6240. let evaluationSignal = "Continue"
  6241. const prev = globalThis[currentFiberURI]
  6242. globalThis[currentFiberURI] = this
  6243. try {
  6244. for (; "Continue" === evaluationSignal; )
  6245. evaluationSignal = MutableQueue_isEmpty(this._queue)
  6246. ? "Done"
  6247. : this.evaluateMessageWhileSuspended(
  6248. MutableQueue_poll(null)(this._queue)
  6249. )
  6250. } finally {
  6251. this._running = !1
  6252. globalThis[currentFiberURI] = prev
  6253. }
  6254. if (MutableQueue_isEmpty(this._queue) || this._running) recurse = !1
  6255. else {
  6256. this._running = !0
  6257. if ("Yield" === evaluationSignal) {
  6258. this.drainQueueLaterOnExecutor()
  6259. recurse = !1
  6260. } else recurse = !0
  6261. }
  6262. }
  6263. }
  6264. drainQueueLaterOnExecutor() {
  6265. this.getFiberRef(currentScheduler).scheduleTask(this.run)
  6266. }
  6267. drainQueueWhileRunning(runtimeFlags, cur0) {
  6268. let cur = cur0
  6269. for (; !MutableQueue_isEmpty(this._queue); ) {
  6270. const message = MutableQueue_poll(void 0)(this._queue)
  6271. cur = drainQueueWhileRunningTable[message._tag](
  6272. this,
  6273. runtimeFlags,
  6274. cur,
  6275. message
  6276. )
  6277. }
  6278. return cur
  6279. }
  6280. isInterrupted() {
  6281. return !(self =>
  6282. "Empty" === self._tag ||
  6283. cause_reduce(self, !0, (acc, cause) => {
  6284. switch (cause._tag) {
  6285. case "Empty":
  6286. return Option_some(acc)
  6287. case "Die":
  6288. case "Fail":
  6289. case "Interrupt":
  6290. return Option_some(!1)
  6291. default:
  6292. return Option_none()
  6293. }
  6294. }))(this.getFiberRef(interruptedCause))
  6295. }
  6296. addInterruptedCause(cause) {
  6297. const oldSC = this.getFiberRef(interruptedCause)
  6298. this.setFiberRef(interruptedCause, sequential(oldSC, cause))
  6299. }
  6300. processNewInterruptSignal(cause) {
  6301. this.addInterruptedCause(cause)
  6302. this.sendInterruptSignalToAllChildren()
  6303. }
  6304. sendInterruptSignalToAllChildren() {
  6305. if (null === this._children || 0 === this._children.size) return !1
  6306. let told = !1
  6307. for (const child of this._children) {
  6308. child.tell(interruptSignal(interrupt(this.id())))
  6309. told = !0
  6310. }
  6311. return told
  6312. }
  6313. interruptAllChildren() {
  6314. if (this.sendInterruptSignalToAllChildren()) {
  6315. const it = this._children.values()
  6316. this._children = null
  6317. let isDone = !1
  6318. const body = () => {
  6319. const next = it.next()
  6320. return next.done
  6321. ? sync(() => {
  6322. isDone = !0
  6323. })
  6324. : core_asUnit(next.value.await())
  6325. }
  6326. return whileLoop(
  6327. () => !isDone,
  6328. () => body(),
  6329. () => {}
  6330. )
  6331. }
  6332. return null
  6333. }
  6334. reportExitValue(exit) {
  6335. if (runtimeMetrics(this._runtimeFlags)) {
  6336. const tags = this.getFiberRef(currentTags)
  6337. switch (exit._tag) {
  6338. case "Success":
  6339. fiberSuccesses.unsafeUpdate(1, tags)
  6340. break
  6341. case "Failure":
  6342. fiberFailures.unsafeUpdate(1, tags)
  6343. }
  6344. }
  6345. if ("Failure" === exit._tag) {
  6346. const level = this.getFiberRef(unhandledErrorLogLevel)
  6347. isInterruptedOnly(exit.cause) ||
  6348. "Some" !== level._tag ||
  6349. this.log(
  6350. "Fiber terminated with a non handled error",
  6351. exit.cause,
  6352. level
  6353. )
  6354. }
  6355. }
  6356. setExitValue(exit) {
  6357. this._exitValue = exit
  6358. if (runtimeMetrics(this._runtimeFlags)) {
  6359. const tags = this.getFiberRef(currentTags),
  6360. startTimeMillis = this.id().startTimeMillis,
  6361. endTimeMillis = new Date().getTime()
  6362. fiberLifetimes.unsafeUpdate(
  6363. (endTimeMillis - startTimeMillis) / 1e3,
  6364. tags
  6365. )
  6366. }
  6367. this.reportExitValue(exit)
  6368. for (let i = this._observers.length - 1; i >= 0; i--)
  6369. this._observers[i](exit)
  6370. }
  6371. getLoggers() {
  6372. return this.getFiberRef(currentLoggers)
  6373. }
  6374. log(message, cause, overrideLogLevel) {
  6375. const logLevel = Option_isSome(overrideLogLevel)
  6376. ? overrideLogLevel.value
  6377. : this.getFiberRef(currentLogLevel),
  6378. spans = this.getFiberRef(currentLogSpan),
  6379. annotations = this.getFiberRef(currentLogAnnotations),
  6380. loggers = this.getLoggers(),
  6381. contextMap = this.unsafeGetFiberRefs()
  6382. mjs_HashSet_forEach(logger => {
  6383. logger.log(
  6384. this.id(),
  6385. logLevel,
  6386. message,
  6387. cause,
  6388. contextMap,
  6389. spans,
  6390. annotations
  6391. )
  6392. })(loggers)
  6393. }
  6394. evaluateMessageWhileSuspended(message) {
  6395. switch (message._tag) {
  6396. case "YieldNow":
  6397. return "Yield"
  6398. case "InterruptSignal":
  6399. this.processNewInterruptSignal(message.cause)
  6400. if (null !== this._asyncInterruptor) {
  6401. this._asyncInterruptor(exitFailCause(message.cause))
  6402. this._asyncInterruptor = null
  6403. }
  6404. return "Continue"
  6405. case "Resume":
  6406. this._asyncInterruptor = null
  6407. this._asyncBlockingOn = null
  6408. this.evaluateEffect(message.effect)
  6409. return "Continue"
  6410. case "Stateful":
  6411. message.onFiber(
  6412. this,
  6413. null !== this._exitValue
  6414. ? Status_done
  6415. : ((runtimeFlags = this._runtimeFlags),
  6416. (blockingOn = this._asyncBlockingOn),
  6417. new Suspended(runtimeFlags, blockingOn))
  6418. )
  6419. return "Continue"
  6420. default:
  6421. return fiberRuntime_absurd(message)
  6422. }
  6423. var runtimeFlags, blockingOn
  6424. }
  6425. evaluateEffect(effect0) {
  6426. this.getSupervisor().onResume(this)
  6427. try {
  6428. let effect =
  6429. interruptible(this._runtimeFlags) && this.isInterrupted()
  6430. ? exitFailCause(this.getInterruptedCause())
  6431. : effect0
  6432. for (; null !== effect; )
  6433. try {
  6434. const exit = this.runLoop(effect)
  6435. this._runtimeFlags = runtimeFlags_enable(16)(this._runtimeFlags)
  6436. const interruption = this.interruptAllChildren()
  6437. if (null !== interruption)
  6438. effect = untraced(() => core_flatMap(interruption, () => exit))
  6439. else {
  6440. MutableQueue_isEmpty(this._queue)
  6441. ? this.setExitValue(exit)
  6442. : this.tell(resume(exit))
  6443. effect = null
  6444. }
  6445. } catch (e) {
  6446. if (!isEffect(e)) throw e
  6447. if ("Yield" === e._tag)
  6448. if (cooperativeYielding(this._runtimeFlags)) {
  6449. this.tell({ _tag: "YieldNow" })
  6450. this.tell(resume(exitUnit()))
  6451. effect = null
  6452. } else effect = exitUnit()
  6453. else "Async" === e._tag && (effect = null)
  6454. }
  6455. } finally {
  6456. this.getSupervisor().onSuspend(this)
  6457. }
  6458. }
  6459. start(effect) {
  6460. if (this._running) this.tell(resume(effect))
  6461. else {
  6462. this._running = !0
  6463. const prev = globalThis[currentFiberURI]
  6464. globalThis[currentFiberURI] = this
  6465. try {
  6466. this.evaluateEffect(effect)
  6467. } finally {
  6468. this._running = !1
  6469. globalThis[currentFiberURI] = prev
  6470. MutableQueue_isEmpty(this._queue) ||
  6471. this.drainQueueLaterOnExecutor()
  6472. }
  6473. }
  6474. }
  6475. startFork(effect) {
  6476. this.tell(resume(effect))
  6477. }
  6478. patchRuntimeFlags(oldRuntimeFlags, patch) {
  6479. const newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, patch)
  6480. globalThis[currentFiberURI] = this
  6481. this._runtimeFlags = newRuntimeFlags
  6482. return newRuntimeFlags
  6483. }
  6484. initiateAsync(runtimeFlags, asyncRegister) {
  6485. let alreadyCalled = !1
  6486. const callback = effect => {
  6487. if (!alreadyCalled) {
  6488. alreadyCalled = !0
  6489. this.tell(resume(effect))
  6490. }
  6491. }
  6492. interruptible(runtimeFlags) && (this._asyncInterruptor = callback)
  6493. try {
  6494. asyncRegister(callback)
  6495. } catch (e) {
  6496. callback(failCause(die(e)))
  6497. }
  6498. }
  6499. pushStack(cont) {
  6500. this._stack.push(cont)
  6501. "trace" in cont && cont.trace && this._traceStack.push(cont.trace)
  6502. }
  6503. popStack() {
  6504. const item = this._stack.pop()
  6505. if (item) {
  6506. "trace" in item && item.trace && this._traceStack.pop()
  6507. return item
  6508. }
  6509. }
  6510. getNextSuccessCont() {
  6511. let frame = this.popStack()
  6512. for (; frame; ) {
  6513. if ("OnFailure" !== frame._tag && "Traced" !== frame._tag)
  6514. return frame
  6515. frame = this.popStack()
  6516. }
  6517. }
  6518. getNextFailCont() {
  6519. let frame = this.popStack()
  6520. for (; frame; ) {
  6521. if (
  6522. "OnSuccess" !== frame._tag &&
  6523. "While" !== frame._tag &&
  6524. "Traced" !== frame._tag
  6525. )
  6526. return frame
  6527. frame = this.popStack()
  6528. }
  6529. }
  6530. [((fiberRuntime_a = FiberTypeId),
  6531. (fiberRuntime_b = RuntimeFiberTypeId),
  6532. "Tag")](op) {
  6533. return core_map(fiberRefGet(currentContext), context =>
  6534. mjs_Context_unsafeGet(context, op)
  6535. )
  6536. }
  6537. Sync(op) {
  6538. const value = op.i0(),
  6539. cont = this.getNextSuccessCont()
  6540. if (void 0 !== cont) {
  6541. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  6542. return contOpSuccess[cont._tag](this, cont, value)
  6543. }
  6544. throw exitSucceed(value)
  6545. }
  6546. Success(op) {
  6547. const oldCur = op,
  6548. cont = this.getNextSuccessCont()
  6549. if (void 0 !== cont) {
  6550. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  6551. return contOpSuccess[cont._tag](this, cont, oldCur.i0)
  6552. }
  6553. throw oldCur
  6554. }
  6555. Failure(op) {
  6556. let cause = op.i0
  6557. if (
  6558. (self => "Annotated" === self._tag)(cause) &&
  6559. isStackAnnotation(cause.annotation)
  6560. ) {
  6561. const stack = cause.annotation.stack,
  6562. currentStack = this.stackToLines()
  6563. cause = annotated(
  6564. cause.cause,
  6565. new StackAnnotation(
  6566. Chunk_take(runtimeDebug.traceStackLimit)(
  6567. dedupeAdjacent(
  6568. 0 === stack.length
  6569. ? currentStack
  6570. : 0 === currentStack.length ||
  6571. unsafeLast(stack) === unsafeLast(currentStack)
  6572. ? stack
  6573. : Chunk_concat(currentStack)(stack)
  6574. )
  6575. ),
  6576. cause.annotation.seq
  6577. )
  6578. )
  6579. } else
  6580. cause = annotated(
  6581. op.i0,
  6582. new StackAnnotation(
  6583. this.stackToLines(),
  6584. (self => getAndUpdate(self, n => n + 1))(globalErrorSeq)
  6585. )
  6586. )
  6587. const cont = this.getNextFailCont()
  6588. if (void 0 === cont) throw exitFailCause(cause)
  6589. switch (cont._tag) {
  6590. case "OnFailure":
  6591. case "OnSuccessAndFailure":
  6592. return interruptible(this._runtimeFlags) && this.isInterrupted()
  6593. ? exitFailCause(stripFailures(cause))
  6594. : cont.i1(cause)
  6595. case "RevertFlags":
  6596. this.patchRuntimeFlags(this._runtimeFlags, cont.patch)
  6597. return interruptible(this._runtimeFlags) && this.isInterrupted()
  6598. ? exitFailCause(sequential(cause, this.getInterruptedCause()))
  6599. : exitFailCause(cause)
  6600. default:
  6601. fiberRuntime_absurd(cont)
  6602. }
  6603. }
  6604. WithRuntime(op) {
  6605. return op.i0(this, Status_running(this._runtimeFlags))
  6606. }
  6607. UpdateRuntimeFlags(op) {
  6608. if (void 0 === op.i1) {
  6609. this.patchRuntimeFlags(this._runtimeFlags, op.i0)
  6610. return exitUnit()
  6611. }
  6612. {
  6613. const updateFlags = op.i0,
  6614. oldRuntimeFlags = this._runtimeFlags,
  6615. newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, updateFlags)
  6616. if (newRuntimeFlags === oldRuntimeFlags) return op.i1(oldRuntimeFlags)
  6617. if (interruptible(newRuntimeFlags) && this.isInterrupted())
  6618. return exitFailCause(this.getInterruptedCause())
  6619. {
  6620. this.patchRuntimeFlags(this._runtimeFlags, updateFlags)
  6621. const revertFlags = runtimeFlags_diff(
  6622. newRuntimeFlags,
  6623. oldRuntimeFlags
  6624. )
  6625. this.pushStack(new RevertFlags(revertFlags))
  6626. return op.i1(oldRuntimeFlags)
  6627. }
  6628. }
  6629. }
  6630. OnSuccess(op) {
  6631. this.pushStack(op)
  6632. return op.i0
  6633. }
  6634. Traced(op) {
  6635. this.pushStack(op)
  6636. return op.i0
  6637. }
  6638. OnFailure(op) {
  6639. this.pushStack(op)
  6640. return op.i0
  6641. }
  6642. OnSuccessAndFailure(op) {
  6643. this.pushStack(op)
  6644. return op.i0
  6645. }
  6646. Async(op) {
  6647. this._asyncBlockingOn = op.i1
  6648. this.initiateAsync(this._runtimeFlags, op.i0)
  6649. throw op
  6650. }
  6651. Yield(op) {
  6652. throw op
  6653. }
  6654. While(op) {
  6655. const check = op.i0,
  6656. body = op.i1
  6657. if (check()) {
  6658. this.pushStack(op)
  6659. return body()
  6660. }
  6661. return exitUnit()
  6662. }
  6663. Commit(op) {
  6664. return op.commit()
  6665. }
  6666. runLoop(effect0) {
  6667. let cur = effect0,
  6668. ops = 0
  6669. for (;;) {
  6670. opSupervision(this._runtimeFlags) &&
  6671. this.getSupervisor().onEffect(this, cur)
  6672. cur = this.drainQueueWhileRunning(this._runtimeFlags, cur)
  6673. ops += 1
  6674. if (ops >= 2048) {
  6675. ops = 0
  6676. const oldCur = cur
  6677. cur = core_flatMap(() => oldCur)(yieldNow())
  6678. }
  6679. try {
  6680. cur._tag in this || fiberRuntime_absurd(cur)
  6681. cur = this[cur._tag](cur)
  6682. } catch (e) {
  6683. if (isEffect(e)) {
  6684. if ("Yield" === e._tag || "Async" === e._tag) throw e
  6685. if ("Success" === e._tag || "Failure" === e._tag) return e
  6686. } else
  6687. cur = isEffectError(e)
  6688. ? exitFailCause(e.cause)
  6689. : isInterruptedException(e)
  6690. ? exitFailCause(sequential(die(e), interrupt(Id_none)))
  6691. : exitFailCause(die(e))
  6692. }
  6693. }
  6694. }
  6695. stackToLines() {
  6696. if (0 === this._traceStack.length) return Chunk_empty()
  6697. const lines = []
  6698. let current = this._traceStack.length - 1
  6699. for (; current >= 0 && lines.length < runtimeDebug.traceStackLimit; ) {
  6700. const value = this._traceStack[current]
  6701. lines.push(value)
  6702. current -= 1
  6703. }
  6704. return unsafeFromArray(lines)
  6705. }
  6706. }
  6707. const currentMinimumLogLevel = fiberRefUnsafeMake(
  6708. fromLiteral(runtimeDebug.minumumLogLevel)
  6709. ),
  6710. defaultLogger = makeLogger(
  6711. (fiberId, logLevel, message, cause, context, spans, annotations) => {
  6712. const formatted = stringLogger.log(
  6713. fiberId,
  6714. logLevel,
  6715. message,
  6716. cause,
  6717. context,
  6718. spans,
  6719. annotations
  6720. ),
  6721. filter = getOrDefault(context, currentMinimumLogLevel)
  6722. greaterThanEqual(filter)(logLevel) &&
  6723. globalThis.console.log(formatted)
  6724. }
  6725. ),
  6726. currentLoggers = fiberRefUnsafeMakeHashSet(
  6727. mjs_HashSet_make(defaultLogger)
  6728. ),
  6729. acquireRelease = dualWithTrace(
  6730. 2,
  6731. (trace, restore) => (acquire, release) =>
  6732. uninterruptible(
  6733. core_tap(acquire, a =>
  6734. addFinalizer(exit => restore(release)(a, exit))
  6735. )
  6736. ).traced(trace)
  6737. ),
  6738. addFinalizer = methodWithTrace(
  6739. (trace, restore) => finalizer =>
  6740. core_flatMap(context(), context =>
  6741. core_flatMap(scope(), scope =>
  6742. scopeAddFinalizerExit(scope, exit =>
  6743. core_asUnit(provideContext(context)(restore(finalizer)(exit)))
  6744. )
  6745. )
  6746. ).traced(trace)
  6747. ),
  6748. forEachPar = dualWithTrace(
  6749. 2,
  6750. (trace, restore) => (self, f) =>
  6751. fiberRefGetWith(currentParallelism, o =>
  6752. "None" === o._tag
  6753. ? forEachParUnbounded(self, restore(f))
  6754. : forEachParN(self, o.value, f)
  6755. ).traced(trace)
  6756. ),
  6757. forEachParUnbounded = (self, f) =>
  6758. suspend(() => {
  6759. const as = Array.from(self).map((v, i) => [v, i]),
  6760. array = new Array(as.length)
  6761. return zipRight(
  6762. forEachParUnboundedDiscard(as, ([a, i]) =>
  6763. core_flatMap(f(a), b => sync(() => (array[i] = b)))
  6764. ),
  6765. succeed(unsafeFromArray(array))
  6766. )
  6767. }),
  6768. forEachParUnboundedDiscard = (self, f) =>
  6769. suspend(() => {
  6770. const as = Array.from(self),
  6771. size = as.length
  6772. return 0 === size
  6773. ? core_unit()
  6774. : 1 === size
  6775. ? core_asUnit(f(as[0]))
  6776. : uninterruptibleMask(restore => {
  6777. const deferred = deferredUnsafeMake(Id_none)
  6778. let ref = 0
  6779. const process = transplant(graft =>
  6780. core_forEach(as, a =>
  6781. forkDaemon(
  6782. graft(
  6783. matchCauseEffect(
  6784. cause =>
  6785. zipRight(
  6786. deferredFail(deferred, void 0),
  6787. failCause(cause)
  6788. ),
  6789. () => {
  6790. ref + 1 === size
  6791. ? deferredUnsafeDone(deferred, core_unit())
  6792. : (ref += 1)
  6793. return core_unit()
  6794. }
  6795. )(restore(suspend(() => f(a))))
  6796. )
  6797. )
  6798. )
  6799. )
  6800. return core_flatMap(process, fibers =>
  6801. matchCauseEffect(
  6802. restore(deferredAwait(deferred)),
  6803. cause =>
  6804. core_flatMap(
  6805. forEachParUnbounded(fibers, interruptFiber),
  6806. exits => {
  6807. const exit = exitCollectAllPar(exits)
  6808. return "Some" === exit._tag &&
  6809. (self => "Failure" === self._tag)(exit.value)
  6810. ? failCause(
  6811. parallel(stripFailures(cause), exit.value.i0)
  6812. )
  6813. : failCause(stripFailures(cause))
  6814. }
  6815. ),
  6816. () => forEachDiscard(fibers, f => f.inheritAll())
  6817. )
  6818. )
  6819. })
  6820. }),
  6821. forEachParN = (self, n, f) =>
  6822. suspend(() => {
  6823. const as = Array.from(self).map((v, i) => [v, i]),
  6824. array = new Array(as.length)
  6825. return zipRight(
  6826. forEachParNDiscard(as, n, ([a, i]) =>
  6827. core_map(f(a), b => (array[i] = b))
  6828. ),
  6829. succeed(unsafeFromArray(array))
  6830. )
  6831. }),
  6832. forEachParNDiscard = (self, n, f) =>
  6833. suspend(() => {
  6834. const iterator = self[Symbol.iterator](),
  6835. worker = core_flatMap(
  6836. sync(() => iterator.next()),
  6837. next =>
  6838. next.done
  6839. ? core_unit()
  6840. : core_flatMap(core_asUnit(f(next.value)), () => worker)
  6841. ),
  6842. effects = []
  6843. for (let i = 0; i < n; i++) effects.push(worker)
  6844. return forEachParUnboundedDiscard(effects, Function_identity)
  6845. }),
  6846. forkDaemon = methodWithTrace(
  6847. trace => self => forkWithScopeOverride(self, globalScope).traced(trace)
  6848. ),
  6849. unsafeMakeChildFiber = (
  6850. effect,
  6851. parentFiber,
  6852. parentRuntimeFlags,
  6853. overrideScope = null
  6854. ) => {
  6855. const childId = Id_unsafeMake(),
  6856. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  6857. childFiberRefs = forkAs(parentFiberRefs, childId),
  6858. childFiber = new FiberRuntime(
  6859. childId,
  6860. childFiberRefs,
  6861. parentRuntimeFlags
  6862. ),
  6863. childContext = getOrDefault(childFiberRefs, currentContext),
  6864. supervisor = childFiber.getSupervisor()
  6865. supervisor.onStart(
  6866. childContext,
  6867. effect,
  6868. Option_some(parentFiber),
  6869. childFiber
  6870. )
  6871. childFiber.unsafeAddObserver(exit => supervisor.onEnd(exit, childFiber))
  6872. ;(null !== overrideScope
  6873. ? overrideScope
  6874. : getOrElse(() => parentFiber.scope())(
  6875. parentFiber.getFiberRef(forkScopeOverride)
  6876. )
  6877. ).add(parentRuntimeFlags, childFiber)
  6878. return childFiber
  6879. },
  6880. forkWithScopeOverride = (self, scopeOverride) =>
  6881. withFiberRuntime((parentFiber, parentStatus) =>
  6882. succeed(
  6883. ((
  6884. effect,
  6885. parentFiber,
  6886. parentRuntimeFlags,
  6887. overrideScope = null
  6888. ) => {
  6889. const childFiber = unsafeMakeChildFiber(
  6890. effect,
  6891. parentFiber,
  6892. parentRuntimeFlags,
  6893. overrideScope
  6894. )
  6895. childFiber.resume(effect)
  6896. return childFiber
  6897. })(self, parentFiber, parentStatus.runtimeFlags, scopeOverride)
  6898. )
  6899. ),
  6900. scope = methodWithTrace(trace => () => scopeTag.traced(trace)),
  6901. scopeWith = methodWithTrace(
  6902. (trace, restore) => f =>
  6903. core_flatMap(scopeTag, restore(f)).traced(trace)
  6904. ),
  6905. fiberRuntime_some = methodWithTrace(
  6906. trace => self =>
  6907. matchEffect(
  6908. self,
  6909. e => core_fail(Option_some(e)),
  6910. option => {
  6911. switch (option._tag) {
  6912. case "None":
  6913. return core_fail(Option_none())
  6914. case "Some":
  6915. return succeed(option.value)
  6916. }
  6917. }
  6918. ).traced(trace)
  6919. ),
  6920. unsome = methodWithTrace(
  6921. trace => self =>
  6922. matchEffect(
  6923. self,
  6924. option => {
  6925. switch (option._tag) {
  6926. case "None":
  6927. return succeed(Option_none())
  6928. case "Some":
  6929. return core_fail(option.value)
  6930. }
  6931. },
  6932. a => succeed(Option_some(a))
  6933. ).traced(trace)
  6934. ),
  6935. scopeTag = Tag(),
  6936. scopeMake = methodWithTrace(
  6937. trace =>
  6938. (strategy = ExecutionStrategy_sequential) =>
  6939. core_map(releaseMapMake(), rm => ({
  6940. [ScopeTypeId]: ScopeTypeId,
  6941. [CloseableScopeTypeId]: CloseableScopeTypeId,
  6942. fork: strategy =>
  6943. bodyWithTrace(trace =>
  6944. uninterruptible(
  6945. core_flatMap(scope =>
  6946. core_as(scope)(
  6947. core_tap(fin => scopeAddFinalizerExit(scope, fin))(
  6948. releaseMapAdd(exit => scopeClose(scope, exit))(rm)
  6949. )
  6950. )
  6951. )(scopeMake(strategy))
  6952. ).traced(trace)
  6953. ),
  6954. close: exit =>
  6955. bodyWithTrace(trace =>
  6956. core_asUnit(
  6957. (
  6958. (strategy, exit) => self =>
  6959. suspend(() => {
  6960. switch (self.state._tag) {
  6961. case "Exited":
  6962. return core_unit()
  6963. case "Running": {
  6964. const finalizersMap = self.state.finalizers,
  6965. update = self.state.update,
  6966. finalizers = Array.from(finalizersMap.keys())
  6967. .sort((a, b) => b - a)
  6968. .map(key => finalizersMap.get(key))
  6969. self.state = {
  6970. _tag: "Exited",
  6971. nextKey: self.state.nextKey,
  6972. exit,
  6973. update,
  6974. }
  6975. return (self => "Sequential" === self._tag)(
  6976. strategy
  6977. )
  6978. ? core_flatMap(results =>
  6979. getOrElse(() => exitUnit())(
  6980. Option_map(exitAsUnit)(
  6981. exitCollectAllInternal(
  6982. results,
  6983. sequential
  6984. )
  6985. )
  6986. )
  6987. )(
  6988. core_forEach(fin =>
  6989. core_exit(update(fin)(exit))
  6990. )(finalizers)
  6991. )
  6992. : (self => "Parallel" === self._tag)(strategy)
  6993. ? core_flatMap(results =>
  6994. getOrElse(() => exitUnit())(
  6995. Option_map(exitAsUnit)(
  6996. exitCollectAllPar(results)
  6997. )
  6998. )
  6999. )(
  7000. forEachPar(fin =>
  7001. core_exit(update(fin)(exit))
  7002. )(finalizers)
  7003. )
  7004. : withParallelism(strategy.parallelism)(
  7005. core_flatMap(results =>
  7006. getOrElse(() => exitUnit())(
  7007. Option_map(exitAsUnit)(
  7008. exitCollectAllPar(results)
  7009. )
  7010. )
  7011. )(
  7012. forEachPar(fin =>
  7013. core_exit(update(fin)(exit))
  7014. )(finalizers)
  7015. )
  7016. )
  7017. }
  7018. }
  7019. })
  7020. )(
  7021. strategy,
  7022. exit
  7023. )(rm)
  7024. ).traced(trace)
  7025. ),
  7026. addFinalizer: fin =>
  7027. bodyWithTrace(trace =>
  7028. core_asUnit(releaseMapAdd(fin)(rm)).traced(trace)
  7029. ),
  7030. })).traced(trace)
  7031. ),
  7032. scopeExtend = dualWithTrace(2, trace => (effect, scope) => {
  7033. return contramapContext(
  7034. effect,
  7035. mjs_Context_merge(
  7036. ((tag = scopeTag),
  7037. (service = scope),
  7038. new ContextImpl(new Map([[tag, service]])))
  7039. )
  7040. ).traced(trace)
  7041. var tag, service
  7042. }),
  7043. fiberRefUnsafeMakeSupervisor = initial =>
  7044. fiberRefUnsafeMakePatch(initial, patch_differ, supervisor_patch_empty),
  7045. fiberRefLocallyScoped = dualWithTrace(
  7046. 2,
  7047. trace => (self, value) =>
  7048. core_asUnit(
  7049. acquireRelease(
  7050. core_flatMap(oldValue =>
  7051. core_as(oldValue)(fiberRefSet(self, value))
  7052. )(fiberRefGet(self)),
  7053. oldValue => fiberRefSet(self, oldValue)
  7054. )
  7055. ).traced(trace)
  7056. ),
  7057. fiberRefLocallyScopedWith = dualWithTrace(
  7058. 2,
  7059. (trace, restore) => (self, f) =>
  7060. fiberRefGetWith(self, a =>
  7061. fiberRefLocallyScoped(self, restore(f)(a))
  7062. ).traced(trace)
  7063. ),
  7064. currentRuntimeFlags = fiberRefUnsafeMakeRuntimeFlags(runtimeFlags_none),
  7065. currentSupervisor = fiberRefUnsafeMakeSupervisor(supervisor_none),
  7066. fiberInterruptFork = methodWithTrace(
  7067. trace => self =>
  7068. core_asUnit(forkDaemon(interruptFiber(self))).traced(trace)
  7069. )
  7070. var circular_b, circular_c
  7071. class Semaphore {
  7072. constructor(permits) {
  7073. this.permits = permits
  7074. this.waiters = new Array()
  7075. this.taken = 0
  7076. this.take = n =>
  7077. bodyWithTrace(trace =>
  7078. asyncInterruptEither(resume => {
  7079. if (this.free < n) {
  7080. const observer = () => {
  7081. if (this.free >= n) {
  7082. const observerIndex = this.waiters.findIndex(
  7083. cb => cb === observer
  7084. )
  7085. ;-1 !== observerIndex &&
  7086. this.waiters.splice(observerIndex, 1)
  7087. this.taken += n
  7088. resume(succeed(n))
  7089. }
  7090. }
  7091. this.waiters.push(observer)
  7092. return Either_left(
  7093. sync(() => {
  7094. const observerIndex = this.waiters.findIndex(
  7095. cb => cb === observer
  7096. )
  7097. ;-1 !== observerIndex &&
  7098. this.waiters.splice(observerIndex, 1)
  7099. })
  7100. )
  7101. }
  7102. this.taken += n
  7103. return Either_right(succeed(n))
  7104. }).traced(trace)
  7105. )
  7106. this.release = n =>
  7107. bodyWithTrace(trace =>
  7108. withFiberRuntime(fiber => {
  7109. this.taken -= n
  7110. fiber.getFiberRef(currentScheduler).scheduleTask(() => {
  7111. this.waiters.forEach(wake => wake())
  7112. })
  7113. return core_unit()
  7114. }).traced(trace)
  7115. )
  7116. this.withPermits = n =>
  7117. bodyWithTrace(
  7118. trace => self =>
  7119. untraced(() =>
  7120. uninterruptibleMask(restore =>
  7121. core_flatMap(restore(this.take(n)), permits =>
  7122. circular_ensuring(restore(self), this.release(permits))
  7123. )
  7124. )
  7125. ).traced(trace)
  7126. )
  7127. }
  7128. get free() {
  7129. return this.permits - this.taken
  7130. }
  7131. }
  7132. const circular_ensuring = dualWithTrace(
  7133. 2,
  7134. trace => (self, finalizer) =>
  7135. uninterruptibleMask(restore =>
  7136. matchCauseEffect(
  7137. restore(self),
  7138. cause1 =>
  7139. matchCauseEffect(
  7140. finalizer,
  7141. cause2 => failCause(sequential(cause1, cause2)),
  7142. () => failCause(cause1)
  7143. ),
  7144. a => core_as(finalizer, a)
  7145. )
  7146. ).traced(trace)
  7147. )
  7148. const zipWithPar = dualWithTrace(
  7149. 3,
  7150. (trace, restoreTrace) => (self, that, f) =>
  7151. uninterruptibleMask(restore =>
  7152. transplant(graft => {
  7153. const deferred = deferredUnsafeMake(Id_none),
  7154. ref = MutableRef_make(!1)
  7155. return core_flatMap(([left, right]) =>
  7156. matchCauseEffect(
  7157. cause =>
  7158. zipRight(
  7159. core_flatMap(([left, right]) =>
  7160. exitMatch(
  7161. causes =>
  7162. failCause(parallel(stripFailures(cause), causes)),
  7163. () => failCause(stripFailures(cause))
  7164. )(exitZipWith(right, f, parallel)(left))
  7165. )(core_zip(_await(right))(_await(left)))
  7166. )(
  7167. zipRight(fiberInterruptFork(right))(
  7168. fiberInterruptFork(left)
  7169. )
  7170. ),
  7171. () =>
  7172. core_zipWith(
  7173. fiber_join(left),
  7174. fiber_join(right),
  7175. restoreTrace(f)
  7176. )
  7177. )(restore(deferredAwait(deferred)))
  7178. )(
  7179. core_zip(forkZipWithPar(that, graft, restore, deferred, ref))(
  7180. forkZipWithPar(self, graft, restore, deferred, ref)
  7181. )
  7182. )
  7183. })
  7184. ).traced(trace)
  7185. ),
  7186. forkZipWithPar = (self, graft, restore, deferred, ref) =>
  7187. forkDaemon(
  7188. matchCauseEffect(
  7189. graft(restore(self)),
  7190. cause => zipRight(deferredFail(deferred, void 0), failCause(cause)),
  7191. value => {
  7192. if (MutableRef_get(ref)) {
  7193. deferredUnsafeDone(deferred, core_unit())
  7194. return succeed(value)
  7195. }
  7196. MutableRef_set(!0)(ref)
  7197. return succeed(value)
  7198. }
  7199. )
  7200. ),
  7201. SynchronizedTypeId = Symbol.for("@effect/io/Ref/Synchronized"),
  7202. synchronizedVariance = { _A: _ => _ }
  7203. class SynchronizedImpl {
  7204. constructor(ref, withLock) {
  7205. this.ref = ref
  7206. this.withLock = withLock
  7207. this[circular_b] = synchronizedVariance
  7208. this[circular_c] = refVariance
  7209. }
  7210. modify(f) {
  7211. return bodyWithTrace((trace, restore) =>
  7212. this.modifyEffect(a => succeed(restore(f)(a))).traced(trace)
  7213. )
  7214. }
  7215. modifyEffect(f) {
  7216. return bodyWithTrace((trace, restore) =>
  7217. this.withLock(
  7218. core_flatMap(([b, a]) => core_as(ref_set(this.ref, a), b))(
  7219. core_flatMap(ref_get(this.ref), restore(f))
  7220. )
  7221. ).traced(trace)
  7222. )
  7223. }
  7224. }
  7225. ;(circular_b = SynchronizedTypeId), (circular_c = RefTypeId)
  7226. const makeSynchronized = methodWithTrace(
  7227. trace => value =>
  7228. sync(() => unsafeMakeSynchronized(value)).traced(trace)
  7229. ),
  7230. unsafeMakeSynchronized = value => {
  7231. const ref = ref_unsafeMake(value),
  7232. sem = new Semaphore(1)
  7233. return new SynchronizedImpl(ref, sem.withPermits(1))
  7234. },
  7235. Cause_fail = fail,
  7236. Cause_failureOrCause = self => {
  7237. const option = (self =>
  7238. find(self, cause =>
  7239. "Fail" === cause._tag ? Option_some(cause.error) : Option_none()
  7240. ))(self)
  7241. switch (option._tag) {
  7242. case "None":
  7243. return Either_right(self)
  7244. case "Some":
  7245. return Either_left(option.value)
  7246. }
  7247. },
  7248. modifyEffect = dualWithTrace(
  7249. 2,
  7250. (trace, restore) => (self, f) =>
  7251. self.modifyEffect(restore(f)).traced(trace)
  7252. ),
  7253. layer_proto = {
  7254. [Symbol.for("@effect/io/Layer")]: {
  7255. _RIn: _ => _,
  7256. _E: _ => _,
  7257. _ROut: _ => _,
  7258. },
  7259. },
  7260. isFresh = self => "Fresh" === self._tag
  7261. class MemoMap {
  7262. constructor(ref) {
  7263. this.ref = ref
  7264. }
  7265. getOrElseMemoize(layer, scope) {
  7266. return core_flatten(
  7267. modifyEffect(this.ref, map => {
  7268. const inMap = map.get(layer)
  7269. if (void 0 !== inMap) {
  7270. const [acquire, release] = inMap,
  7271. cached = onExit(
  7272. exitMatch(
  7273. () => core_unit(),
  7274. () => scopeAddFinalizerExit(scope, release)
  7275. )
  7276. )(
  7277. core_flatMap(([patch, b]) =>
  7278. core_as(b)(patchFiberRefs(patch))
  7279. )(acquire)
  7280. )
  7281. return succeed([cached, map])
  7282. }
  7283. return core_flatMap(observers =>
  7284. core_flatMap(deferred =>
  7285. core_map(finalizerRef => {
  7286. const resource = uninterruptibleMask(restore =>
  7287. core_flatMap(innerScope =>
  7288. core_flatMap(exit => {
  7289. switch (exit._tag) {
  7290. case "Failure":
  7291. return zipRight(failCause(exit.i0))(
  7292. zipRight(scopeClose(innerScope, exit))(
  7293. deferredFailCause(deferred, exit.i0)
  7294. )
  7295. )
  7296. case "Success":
  7297. return core_as(exit.i0[1])(
  7298. zipRight(deferredSucceed(deferred, exit.i0))(
  7299. zipRight(
  7300. scopeAddFinalizerExit(scope, exit =>
  7301. core_flatMap(finalizer =>
  7302. finalizer(exit)
  7303. )(ref_get(finalizerRef))
  7304. )
  7305. )(
  7306. zipRight(ref_update(observers, n => n + 1))(
  7307. ref_set(finalizerRef, exit =>
  7308. core_asUnit(
  7309. whenEffect(
  7310. ref_modify(observers, n => [
  7311. 1 === n,
  7312. n - 1,
  7313. ])
  7314. )(scopeClose(innerScope, exit))
  7315. )
  7316. )
  7317. )
  7318. )
  7319. )
  7320. )
  7321. }
  7322. })(
  7323. core_exit(
  7324. restore(
  7325. core_flatMap(withScope(layer, innerScope), f =>
  7326. diffFiberRefs(f(this))
  7327. )
  7328. )
  7329. )
  7330. )
  7331. )(scopeMake())
  7332. ),
  7333. memoized = [
  7334. onExit(
  7335. exitMatchEffect(
  7336. () => core_unit(),
  7337. () => ref_update(observers, n => n + 1)
  7338. )
  7339. )(deferredAwait(deferred)),
  7340. exit =>
  7341. core_flatMap(finalizer => finalizer(exit))(
  7342. ref_get(finalizerRef)
  7343. ),
  7344. ]
  7345. return [
  7346. resource,
  7347. isFresh(layer) ? map : map.set(layer, memoized),
  7348. ]
  7349. })(ref_make(() => core_unit()))
  7350. )(deferredMake())
  7351. )(ref_make(0))
  7352. })
  7353. )
  7354. }
  7355. }
  7356. const buildWithScope = dualWithTrace(
  7357. 2,
  7358. trace => (self, scope) =>
  7359. core_flatMap(
  7360. core_map(ref => new MemoMap(ref))(makeSynchronized(new Map())),
  7361. memoMap => core_flatMap(withScope(self, scope), run => run(memoMap))
  7362. ).traced(trace)
  7363. ),
  7364. withScope = (self, scope) => {
  7365. const op = self
  7366. switch (op._tag) {
  7367. case "ExtendScope":
  7368. return sync(
  7369. () => memoMap =>
  7370. scopeWith(scope => memoMap.getOrElseMemoize(op.layer, scope))
  7371. )
  7372. case "Fold":
  7373. return sync(
  7374. () => memoMap =>
  7375. matchCauseEffect(
  7376. cause => memoMap.getOrElseMemoize(op.failureK(cause), scope),
  7377. value => memoMap.getOrElseMemoize(op.successK(value), scope)
  7378. )(memoMap.getOrElseMemoize(op.layer, scope))
  7379. )
  7380. case "Fresh":
  7381. return sync(() => _ => buildWithScope(scope)(op.layer))
  7382. case "FromEffect":
  7383. return sync(() => _ => op.effect)
  7384. case "ProvideTo":
  7385. return sync(
  7386. () => memoMap =>
  7387. core_flatMap(env =>
  7388. provideContext(env)(
  7389. memoMap.getOrElseMemoize(op.second, scope)
  7390. )
  7391. )(memoMap.getOrElseMemoize(op.first, scope))
  7392. )
  7393. case "Scoped":
  7394. return sync(() => _ => scopeExtend(op.effect, scope))
  7395. case "Suspend":
  7396. return sync(
  7397. () => memoMap => memoMap.getOrElseMemoize(op.evaluate(), scope)
  7398. )
  7399. case "ZipWith":
  7400. return sync(
  7401. () => memoMap =>
  7402. core_zipWith(
  7403. memoMap.getOrElseMemoize(op.second, scope),
  7404. op.zipK
  7405. )(memoMap.getOrElseMemoize(op.first, scope))
  7406. )
  7407. case "ZipWithPar":
  7408. return sync(
  7409. () => memoMap =>
  7410. zipWithPar(
  7411. memoMap.getOrElseMemoize(op.second, scope),
  7412. op.zipK
  7413. )(memoMap.getOrElseMemoize(op.first, scope))
  7414. )
  7415. }
  7416. },
  7417. layer_fail = error => layer_failCause(Cause_fail(error)),
  7418. layer_failCause = cause => fromEffectContext(failCause(cause)),
  7419. layer_flatMap = untracedDual(
  7420. 2,
  7421. restore => (self, f) => matchLayer(self, layer_fail, restore(f))
  7422. )
  7423. function fromEffectContext(effect) {
  7424. const fromEffect = Object.create(layer_proto)
  7425. fromEffect._tag = "FromEffect"
  7426. fromEffect.effect = effect
  7427. return fromEffect
  7428. }
  7429. const matchCauseLayer = untracedDual(
  7430. 3,
  7431. restore => (self, onFailure, onSuccess) => {
  7432. const fold = Object.create(layer_proto)
  7433. fold._tag = "Fold"
  7434. fold.layer = self
  7435. fold.failureK = restore(onFailure)
  7436. fold.successK = restore(onSuccess)
  7437. return fold
  7438. }
  7439. ),
  7440. matchLayer = untracedDual(
  7441. 3,
  7442. restore => (self, onFailure, onSuccess) =>
  7443. matchCauseLayer(
  7444. self,
  7445. cause => {
  7446. const failureOrCause = Cause_failureOrCause(cause)
  7447. switch (failureOrCause._tag) {
  7448. case "Left":
  7449. return restore(onFailure)(failureOrCause.left)
  7450. case "Right":
  7451. return layer_failCause(failureOrCause.right)
  7452. }
  7453. },
  7454. restore(onSuccess)
  7455. )
  7456. ),
  7457. layer_merge = Function_dual(2, (self, that) =>
  7458. layer_zipWithPar(self, that, (a, b) => mjs_Context_merge(b)(a))
  7459. ),
  7460. scopedDiscard = effect =>
  7461. scopedContext(core_as(mjs_Context_empty())(effect)),
  7462. scopedContext = effect => {
  7463. const scoped = Object.create(layer_proto)
  7464. scoped._tag = "Scoped"
  7465. scoped.effect = effect
  7466. return scoped
  7467. },
  7468. layer_zipWithPar = untracedDual(
  7469. 3,
  7470. restore => (self, that, f) =>
  7471. (evaluate => {
  7472. const suspend = Object.create(layer_proto)
  7473. suspend._tag = "Suspend"
  7474. suspend.evaluate = evaluate
  7475. return suspend
  7476. })(() => {
  7477. const zipWithPar = Object.create(layer_proto)
  7478. zipWithPar._tag = "ZipWithPar"
  7479. zipWithPar.first = self
  7480. zipWithPar.second = that
  7481. zipWithPar.zipK = restore(f)
  7482. return zipWithPar
  7483. })
  7484. ),
  7485. provideLayer = dualWithTrace(
  7486. 2,
  7487. trace => (self, layer) =>
  7488. acquireUseRelease(
  7489. scopeMake(),
  7490. scope =>
  7491. core_flatMap(buildWithScope(layer, scope), context =>
  7492. provideContext(self, context)
  7493. ),
  7494. (scope, exit) => scopeClose(scope, exit)
  7495. ).traced(trace)
  7496. ),
  7497. provideSomeLayer = dualWithTrace(
  7498. 2,
  7499. trace => (self, layer) =>
  7500. provideLayer(
  7501. self,
  7502. layer_merge(layer)(fromEffectContext(context()))
  7503. ).traced(trace)
  7504. ),
  7505. withMinimumLogLevel = dualWithTrace(
  7506. 2,
  7507. trace => (self, level) =>
  7508. fiberRefLocally(currentMinimumLogLevel, level)(self).traced(trace)
  7509. ),
  7510. addLogger = methodWithTrace(
  7511. trace => logger =>
  7512. scopedDiscard(
  7513. fiberRefLocallyScopedWith(
  7514. currentLoggers,
  7515. mjs_HashSet_add(logger)
  7516. ).traced(trace)
  7517. )
  7518. ),
  7519. removeLogger = untracedMethod(
  7520. () => logger =>
  7521. scopedDiscard(
  7522. fiberRefLocallyScopedWith(
  7523. currentLoggers,
  7524. mjs_HashSet_remove(logger)
  7525. )
  7526. )
  7527. ),
  7528. replaceLogger = Function_dual(2, (self, that) =>
  7529. layer_flatMap(removeLogger(self), () => addLogger(that))
  7530. )
  7531. class AsyncFiber {
  7532. constructor(fiber) {
  7533. this.fiber = fiber
  7534. this._tag = "AsyncFiber"
  7535. }
  7536. toString() {
  7537. return `Fiber #${this.fiber.id().id} has suspended work asyncroniously`
  7538. }
  7539. [Symbol.for("nodejs.util.inspect.custom")]() {
  7540. return this.toString()
  7541. }
  7542. }
  7543. const FiberFailureId = Symbol.for("@effect/io/Runtime/FiberFailure"),
  7544. FiberFailureCauseId = Symbol.for("@effect/io/Runtime/FiberFailure/Cause"),
  7545. NodePrint = Symbol.for("nodejs.util.inspect.custom"),
  7546. unsafeRunPromise = runtime =>
  7547. methodWithTrace(
  7548. trace => effect =>
  7549. new Promise((resolve, reject) => {
  7550. ;(runtime =>
  7551. methodWithTrace(trace => (self, options) => {
  7552. const fiberId = Id_unsafeMake(),
  7553. effect = self.traced(trace)
  7554. let fiberRefs = FiberRefs_updatedAs(
  7555. runtime.fiberRefs,
  7556. fiberId,
  7557. currentContext,
  7558. runtime.context
  7559. )
  7560. options?.scheduler &&
  7561. (fiberRefs = FiberRefs_updatedAs(
  7562. fiberRefs,
  7563. fiberId,
  7564. currentScheduler,
  7565. options.scheduler
  7566. ))
  7567. options?.updateRefs &&
  7568. (fiberRefs = options.updateRefs(fiberRefs, fiberId))
  7569. const fiberRuntime = new FiberRuntime(
  7570. fiberId,
  7571. FiberRefs_forkAs(fiberRefs, fiberId),
  7572. runtime.runtimeFlags
  7573. ),
  7574. supervisor = fiberRuntime.getSupervisor()
  7575. if (supervisor !== supervisor_none) {
  7576. supervisor.onStart(
  7577. runtime.context,
  7578. effect,
  7579. Option_none(),
  7580. fiberRuntime
  7581. )
  7582. fiberRuntime.unsafeAddObserver(exit =>
  7583. supervisor.onEnd(exit, fiberRuntime)
  7584. )
  7585. }
  7586. globalScope.add(runtime.runtimeFlags, fiberRuntime)
  7587. fiberRuntime.start(effect)
  7588. return fiberRuntime
  7589. }))(runtime)(effect.traced(trace)).unsafeAddObserver(result => {
  7590. switch (result._tag) {
  7591. case "Success":
  7592. resolve(result.i0)
  7593. break
  7594. case "Failure":
  7595. reject(
  7596. (cause => {
  7597. const limit = Error.stackTraceLimit
  7598. Error.stackTraceLimit = 0
  7599. const error = new Error()
  7600. Error.stackTraceLimit = limit
  7601. const pretty = prettyErrors(cause)
  7602. if (pretty.length > 0) {
  7603. error.name = pretty[0].message.split(":")[0]
  7604. error.message = pretty[0].message.substring(
  7605. error.name.length + 2
  7606. )
  7607. error.stack = `${error.name}: ${error.message}\n${pretty[0].stack}`
  7608. }
  7609. error[FiberFailureId] = FiberFailureId
  7610. error[FiberFailureCauseId] = cause
  7611. error.toString = () => cause_pretty_pretty(cause)
  7612. error[NodePrint] = () => error.toString()
  7613. return error
  7614. })(result.i0)
  7615. )
  7616. }
  7617. })
  7618. })
  7619. )
  7620. class RuntimeImpl {
  7621. constructor(context, runtimeFlags, fiberRefs) {
  7622. this.context = context
  7623. this.runtimeFlags = runtimeFlags
  7624. this.fiberRefs = fiberRefs
  7625. }
  7626. }
  7627. const runtime_make = (context, runtimeFlags, fiberRefs) =>
  7628. new RuntimeImpl(context, runtimeFlags, fiberRefs),
  7629. defaultRuntimeFlags = runtimeFlags_make(1, 32),
  7630. Effect_asUnit = core_asUnit,
  7631. Effect_bind = effect_bind,
  7632. Effect_bindValue = bindValue,
  7633. Effect_Do = effect_Do,
  7634. Effect_fail = core_fail,
  7635. Effect_filterOrElse = filterOrElse,
  7636. Effect_filterOrFail = filterOrFail,
  7637. Effect_flatMap = core_flatMap,
  7638. Effect_forEach = core_forEach,
  7639. Effect_fromOption = core_fromOption,
  7640. Effect_ignore = ignore,
  7641. Effect_isSuccess = effect_isSuccess,
  7642. Effect_log = log,
  7643. Effect_logDebug = logDebug,
  7644. Effect_logInfo = logInfo,
  7645. Effect_logAnnotate = logAnnotate,
  7646. Effect_map = core_map,
  7647. Effect_orElseSucceed = orElseSucceed,
  7648. Effect_promise = promise,
  7649. Effect_provideSomeLayer = provideSomeLayer,
  7650. Effect_some = fiberRuntime_some,
  7651. Effect_succeed = succeed,
  7652. Effect_sync = sync,
  7653. Effect_tap = core_tap,
  7654. Effect_all = effect_all,
  7655. Effect_unit = core_unit,
  7656. runPromise = unsafeRunPromise(
  7657. runtime_make(
  7658. mjs_Context_empty(),
  7659. defaultRuntimeFlags,
  7660. FiberRefs_unsafeMake(new Map())
  7661. )
  7662. ),
  7663. Effect_unsome = unsome,
  7664. Effect_zipLeft = zipLeft,
  7665. Effect_zipRight = zipRight,
  7666. external_rxjs_namespaceObject = rxjs,
  7667. lib = observer => value => {
  7668. observer.next(value)
  7669. }
  7670. Promise.resolve(!1)
  7671. Promise.resolve(!0)
  7672. var PROMISE_RESOLVED_VOID = Promise.resolve()
  7673. function util_sleep(time, resolveWith) {
  7674. time || (time = 0)
  7675. return new Promise(function (res) {
  7676. return setTimeout(function () {
  7677. return res(resolveWith)
  7678. }, time)
  7679. })
  7680. }
  7681. function randomToken() {
  7682. return Math.random().toString(36).substring(2)
  7683. }
  7684. var lastMs = 0,
  7685. additional = 0
  7686. function microSeconds() {
  7687. var ms = new Date().getTime()
  7688. if (ms === lastMs) return 1e3 * ms + ++additional
  7689. lastMs = ms
  7690. additional = 0
  7691. return 1e3 * ms
  7692. }
  7693. var isNode =
  7694. "[object process]" ===
  7695. Object.prototype.toString.call(
  7696. "undefined" != typeof process ? process : 0
  7697. )
  7698. const methods_native = {
  7699. create: function (channelName) {
  7700. var state = {
  7701. messagesCallback: null,
  7702. bc: new BroadcastChannel(channelName),
  7703. subFns: [],
  7704. }
  7705. state.bc.onmessage = function (msg) {
  7706. state.messagesCallback && state.messagesCallback(msg.data)
  7707. }
  7708. return state
  7709. },
  7710. close: function (channelState) {
  7711. channelState.bc.close()
  7712. channelState.subFns = []
  7713. },
  7714. onMessage: function (channelState, fn) {
  7715. channelState.messagesCallback = fn
  7716. },
  7717. postMessage: function (channelState, messageJson) {
  7718. try {
  7719. channelState.bc.postMessage(messageJson, !1)
  7720. return PROMISE_RESOLVED_VOID
  7721. } catch (err) {
  7722. return Promise.reject(err)
  7723. }
  7724. },
  7725. canBeUsed: function () {
  7726. if (isNode && "undefined" == typeof window) return !1
  7727. if ("function" == typeof BroadcastChannel) {
  7728. if (BroadcastChannel._pubkey)
  7729. throw new Error(
  7730. "BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill"
  7731. )
  7732. return !0
  7733. }
  7734. return !1
  7735. },
  7736. type: "native",
  7737. averageResponseTime: function () {
  7738. return 150
  7739. },
  7740. microSeconds,
  7741. }
  7742. var ObliviousSet = (function () {
  7743. function ObliviousSet(ttl) {
  7744. this.ttl = ttl
  7745. this.map = new Map()
  7746. this._to = !1
  7747. }
  7748. ObliviousSet.prototype.has = function (value) {
  7749. return this.map.has(value)
  7750. }
  7751. ObliviousSet.prototype.add = function (value) {
  7752. var _this = this
  7753. this.map.set(value, now())
  7754. if (!this._to) {
  7755. this._to = !0
  7756. setTimeout(function () {
  7757. _this._to = !1
  7758. !(function (obliviousSet) {
  7759. for (
  7760. var olderThen = now() - obliviousSet.ttl,
  7761. iterator = obliviousSet.map[Symbol.iterator]();
  7762. ;
  7763.  
  7764. ) {
  7765. var next = iterator.next().value
  7766. if (!next) return
  7767. var value = next[0]
  7768. if (!(next[1] < olderThen)) return
  7769. obliviousSet.map.delete(value)
  7770. }
  7771. })(_this)
  7772. }, 0)
  7773. }
  7774. }
  7775. ObliviousSet.prototype.clear = function () {
  7776. this.map.clear()
  7777. }
  7778. return ObliviousSet
  7779. })()
  7780. function now() {
  7781. return new Date().getTime()
  7782. }
  7783. function options_fillOptionsWithDefaults() {
  7784. var originalOptions =
  7785. arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
  7786. options = JSON.parse(JSON.stringify(originalOptions))
  7787. void 0 === options.webWorkerSupport && (options.webWorkerSupport = !0)
  7788. options.idb || (options.idb = {})
  7789. options.idb.ttl || (options.idb.ttl = 45e3)
  7790. options.idb.fallbackInterval || (options.idb.fallbackInterval = 150)
  7791. originalOptions.idb &&
  7792. "function" == typeof originalOptions.idb.onclose &&
  7793. (options.idb.onclose = originalOptions.idb.onclose)
  7794. options.localstorage || (options.localstorage = {})
  7795. options.localstorage.removeTimeout ||
  7796. (options.localstorage.removeTimeout = 6e4)
  7797. originalOptions.methods && (options.methods = originalOptions.methods)
  7798. options.node || (options.node = {})
  7799. options.node.ttl || (options.node.ttl = 12e4)
  7800. options.node.maxParallelWrites || (options.node.maxParallelWrites = 2048)
  7801. void 0 === options.node.useFastPath && (options.node.useFastPath = !0)
  7802. return options
  7803. }
  7804. var TRANSACTION_SETTINGS = { durability: "relaxed" }
  7805. function getIdb() {
  7806. if ("undefined" != typeof indexedDB) return indexedDB
  7807. if ("undefined" != typeof window) {
  7808. if (void 0 !== window.mozIndexedDB) return window.mozIndexedDB
  7809. if (void 0 !== window.webkitIndexedDB) return window.webkitIndexedDB
  7810. if (void 0 !== window.msIndexedDB) return window.msIndexedDB
  7811. }
  7812. return !1
  7813. }
  7814. function commitIndexedDBTransaction(tx) {
  7815. tx.commit && tx.commit()
  7816. }
  7817. function _readLoop(state) {
  7818. state.closed ||
  7819. readNewMessages(state)
  7820. .then(function () {
  7821. return util_sleep(state.options.idb.fallbackInterval)
  7822. })
  7823. .then(function () {
  7824. return _readLoop(state)
  7825. })
  7826. }
  7827. function readNewMessages(state) {
  7828. return state.closed
  7829. ? PROMISE_RESOLVED_VOID
  7830. : state.messagesCallback
  7831. ? (function (db, lastCursorId) {
  7832. var tx = db.transaction(
  7833. "messages",
  7834. "readonly",
  7835. TRANSACTION_SETTINGS
  7836. ),
  7837. objectStore = tx.objectStore("messages"),
  7838. ret = [],
  7839. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  7840. if (objectStore.getAll) {
  7841. var getAllRequest = objectStore.getAll(keyRangeValue)
  7842. return new Promise(function (res, rej) {
  7843. getAllRequest.onerror = function (err) {
  7844. return rej(err)
  7845. }
  7846. getAllRequest.onsuccess = function (e) {
  7847. res(e.target.result)
  7848. }
  7849. })
  7850. }
  7851. return new Promise(function (res, rej) {
  7852. var openCursorRequest = (function () {
  7853. try {
  7854. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  7855. return objectStore.openCursor(keyRangeValue)
  7856. } catch (e) {
  7857. return objectStore.openCursor()
  7858. }
  7859. })()
  7860. openCursorRequest.onerror = function (err) {
  7861. return rej(err)
  7862. }
  7863. openCursorRequest.onsuccess = function (ev) {
  7864. var cursor = ev.target.result
  7865. if (cursor)
  7866. if (cursor.value.id < lastCursorId + 1)
  7867. cursor.continue(lastCursorId + 1)
  7868. else {
  7869. ret.push(cursor.value)
  7870. cursor.continue()
  7871. }
  7872. else {
  7873. commitIndexedDBTransaction(tx)
  7874. res(ret)
  7875. }
  7876. }
  7877. })
  7878. })(state.db, state.lastCursorId).then(function (newerMessages) {
  7879. var useMessages = newerMessages
  7880. .filter(function (msgObj) {
  7881. return !!msgObj
  7882. })
  7883. .map(function (msgObj) {
  7884. msgObj.id > state.lastCursorId &&
  7885. (state.lastCursorId = msgObj.id)
  7886. return msgObj
  7887. })
  7888. .filter(function (msgObj) {
  7889. return (function (msgObj, state) {
  7890. return !(
  7891. msgObj.uuid === state.uuid ||
  7892. state.eMIs.has(msgObj.id) ||
  7893. msgObj.data.time < state.messagesCallbackTime
  7894. )
  7895. })(msgObj, state)
  7896. })
  7897. .sort(function (msgObjA, msgObjB) {
  7898. return msgObjA.time - msgObjB.time
  7899. })
  7900. useMessages.forEach(function (msgObj) {
  7901. if (state.messagesCallback) {
  7902. state.eMIs.add(msgObj.id)
  7903. state.messagesCallback(msgObj.data)
  7904. }
  7905. })
  7906. return PROMISE_RESOLVED_VOID
  7907. })
  7908. : PROMISE_RESOLVED_VOID
  7909. }
  7910. const indexed_db = {
  7911. create: function (channelName, options) {
  7912. options = options_fillOptionsWithDefaults(options)
  7913. return (function (channelName) {
  7914. var dbName = "pubkey.broadcast-channel-0-" + channelName,
  7915. openRequest = getIdb().open(dbName)
  7916. openRequest.onupgradeneeded = function (ev) {
  7917. ev.target.result.createObjectStore("messages", {
  7918. keyPath: "id",
  7919. autoIncrement: !0,
  7920. })
  7921. }
  7922. return new Promise(function (res, rej) {
  7923. openRequest.onerror = function (ev) {
  7924. return rej(ev)
  7925. }
  7926. openRequest.onsuccess = function () {
  7927. res(openRequest.result)
  7928. }
  7929. })
  7930. })(channelName).then(function (db) {
  7931. var state = {
  7932. closed: !1,
  7933. lastCursorId: 0,
  7934. channelName,
  7935. options,
  7936. uuid: randomToken(),
  7937. eMIs: new ObliviousSet(2 * options.idb.ttl),
  7938. writeBlockPromise: PROMISE_RESOLVED_VOID,
  7939. messagesCallback: null,
  7940. readQueuePromises: [],
  7941. db,
  7942. }
  7943. db.onclose = function () {
  7944. state.closed = !0
  7945. options.idb.onclose && options.idb.onclose()
  7946. }
  7947. _readLoop(state)
  7948. return state
  7949. })
  7950. },
  7951. close: function (channelState) {
  7952. channelState.closed = !0
  7953. channelState.db.close()
  7954. },
  7955. onMessage: function (channelState, fn, time) {
  7956. channelState.messagesCallbackTime = time
  7957. channelState.messagesCallback = fn
  7958. readNewMessages(channelState)
  7959. },
  7960. postMessage: function (channelState, messageJson) {
  7961. channelState.writeBlockPromise = channelState.writeBlockPromise
  7962. .then(function () {
  7963. return (function (db, readerUuid, messageJson) {
  7964. var writeObject = {
  7965. uuid: readerUuid,
  7966. time: new Date().getTime(),
  7967. data: messageJson,
  7968. },
  7969. tx = db.transaction(
  7970. ["messages"],
  7971. "readwrite",
  7972. TRANSACTION_SETTINGS
  7973. )
  7974. return new Promise(function (res, rej) {
  7975. tx.oncomplete = function () {
  7976. return res()
  7977. }
  7978. tx.onerror = function (ev) {
  7979. return rej(ev)
  7980. }
  7981. tx.objectStore("messages").add(writeObject)
  7982. commitIndexedDBTransaction(tx)
  7983. })
  7984. })(channelState.db, channelState.uuid, messageJson)
  7985. })
  7986. .then(function () {
  7987. 0 === Math.floor(11 * Math.random() + 0) &&
  7988. ((db = channelState.db),
  7989. (ttl = channelState.options.idb.ttl),
  7990. (function (db, ttl) {
  7991. var olderThen = new Date().getTime() - ttl,
  7992. tx = db.transaction(
  7993. "messages",
  7994. "readonly",
  7995. TRANSACTION_SETTINGS
  7996. ),
  7997. objectStore = tx.objectStore("messages"),
  7998. ret = []
  7999. return new Promise(function (res) {
  8000. objectStore.openCursor().onsuccess = function (ev) {
  8001. var cursor = ev.target.result
  8002. if (cursor) {
  8003. var msgObk = cursor.value
  8004. if (!(msgObk.time < olderThen)) {
  8005. commitIndexedDBTransaction(tx)
  8006. res(ret)
  8007. return
  8008. }
  8009. ret.push(msgObk)
  8010. cursor.continue()
  8011. } else res(ret)
  8012. }
  8013. })
  8014. })(db, ttl).then(function (tooOld) {
  8015. return (function (db, ids) {
  8016. var objectStore = db
  8017. .transaction(
  8018. ["messages"],
  8019. "readwrite",
  8020. TRANSACTION_SETTINGS
  8021. )
  8022. .objectStore("messages")
  8023. return Promise.all(
  8024. ids.map(function (id) {
  8025. var deleteRequest = objectStore.delete(id)
  8026. return new Promise(function (res) {
  8027. deleteRequest.onsuccess = function () {
  8028. return res()
  8029. }
  8030. })
  8031. })
  8032. )
  8033. })(
  8034. db,
  8035. tooOld.map(function (msg) {
  8036. return msg.id
  8037. })
  8038. )
  8039. }))
  8040. var db, ttl
  8041. })
  8042. return channelState.writeBlockPromise
  8043. },
  8044. canBeUsed: function () {
  8045. return !isNode && !!getIdb()
  8046. },
  8047. type: "idb",
  8048. averageResponseTime: function (options) {
  8049. return 2 * options.idb.fallbackInterval
  8050. },
  8051. microSeconds,
  8052. }
  8053. function getLocalStorage() {
  8054. var localStorage
  8055. if ("undefined" == typeof window) return null
  8056. try {
  8057. localStorage = window.localStorage
  8058. localStorage =
  8059. window["ie8-eventlistener/storage"] || window.localStorage
  8060. } catch (e) {}
  8061. return localStorage
  8062. }
  8063. function storageKey(channelName) {
  8064. return "pubkey.broadcastChannel-" + channelName
  8065. }
  8066. function localstorage_canBeUsed() {
  8067. if (isNode) return !1
  8068. var ls = getLocalStorage()
  8069. if (!ls) return !1
  8070. try {
  8071. var key = "__broadcastchannel_check"
  8072. ls.setItem(key, "works")
  8073. ls.removeItem(key)
  8074. } catch (e) {
  8075. return !1
  8076. }
  8077. return !0
  8078. }
  8079. const localstorage = {
  8080. create: function (channelName, options) {
  8081. options = options_fillOptionsWithDefaults(options)
  8082. if (!localstorage_canBeUsed())
  8083. throw new Error("BroadcastChannel: localstorage cannot be used")
  8084. var uuid = randomToken(),
  8085. eMIs = new ObliviousSet(options.localstorage.removeTimeout),
  8086. state = { channelName, uuid, eMIs }
  8087. state.listener = (function (channelName, fn) {
  8088. var key = storageKey(channelName),
  8089. listener = function (ev) {
  8090. ev.key === key &&
  8091. (function (msgObj) {
  8092. if (
  8093. state.messagesCallback &&
  8094. msgObj.uuid !== uuid &&
  8095. msgObj.token &&
  8096. !eMIs.has(msgObj.token) &&
  8097. !(
  8098. msgObj.data.time &&
  8099. msgObj.data.time < state.messagesCallbackTime
  8100. )
  8101. ) {
  8102. eMIs.add(msgObj.token)
  8103. state.messagesCallback(msgObj.data)
  8104. }
  8105. })(JSON.parse(ev.newValue))
  8106. }
  8107. window.addEventListener("storage", listener)
  8108. return listener
  8109. })(channelName)
  8110. return state
  8111. },
  8112. close: function (channelState) {
  8113. ;(listener = channelState.listener),
  8114. window.removeEventListener("storage", listener)
  8115. var listener
  8116. },
  8117. onMessage: function (channelState, fn, time) {
  8118. channelState.messagesCallbackTime = time
  8119. channelState.messagesCallback = fn
  8120. },
  8121. postMessage: function (channelState, messageJson) {
  8122. return new Promise(function (res) {
  8123. util_sleep().then(function () {
  8124. var key = storageKey(channelState.channelName),
  8125. writeObj = {
  8126. token: randomToken(),
  8127. time: new Date().getTime(),
  8128. data: messageJson,
  8129. uuid: channelState.uuid,
  8130. },
  8131. value = JSON.stringify(writeObj)
  8132. getLocalStorage().setItem(key, value)
  8133. var ev = document.createEvent("Event")
  8134. ev.initEvent("storage", !0, !0)
  8135. ev.key = key
  8136. ev.newValue = value
  8137. window.dispatchEvent(ev)
  8138. res()
  8139. })
  8140. })
  8141. },
  8142. canBeUsed: localstorage_canBeUsed,
  8143. type: "localstorage",
  8144. averageResponseTime: function () {
  8145. var userAgent = navigator.userAgent.toLowerCase()
  8146. return userAgent.includes("safari") && !userAgent.includes("chrome")
  8147. ? 240
  8148. : 120
  8149. },
  8150. microSeconds,
  8151. }
  8152. var simulate_microSeconds = microSeconds,
  8153. SIMULATE_CHANNELS = new Set()
  8154. const simulate = {
  8155. create: function (channelName) {
  8156. var state = { name: channelName, messagesCallback: null }
  8157. SIMULATE_CHANNELS.add(state)
  8158. return state
  8159. },
  8160. close: function (channelState) {
  8161. SIMULATE_CHANNELS.delete(channelState)
  8162. },
  8163. onMessage: function (channelState, fn) {
  8164. channelState.messagesCallback = fn
  8165. },
  8166. postMessage: function (channelState, messageJson) {
  8167. return new Promise(function (res) {
  8168. return setTimeout(function () {
  8169. Array.from(SIMULATE_CHANNELS)
  8170. .filter(function (channel) {
  8171. return channel.name === channelState.name
  8172. })
  8173. .filter(function (channel) {
  8174. return channel !== channelState
  8175. })
  8176. .filter(function (channel) {
  8177. return !!channel.messagesCallback
  8178. })
  8179. .forEach(function (channel) {
  8180. return channel.messagesCallback(messageJson)
  8181. })
  8182. res()
  8183. }, 5)
  8184. })
  8185. },
  8186. canBeUsed: function () {
  8187. return !0
  8188. },
  8189. type: "simulate",
  8190. averageResponseTime: function () {
  8191. return 5
  8192. },
  8193. microSeconds: simulate_microSeconds,
  8194. }
  8195. var METHODS = [methods_native, indexed_db, localstorage],
  8196. OPEN_BROADCAST_CHANNELS = new Set(),
  8197. lastId = 0,
  8198. broadcast_channel_BroadcastChannel = function (name, options) {
  8199. this.id = lastId++
  8200. OPEN_BROADCAST_CHANNELS.add(this)
  8201. this.name = name
  8202. this.options = options_fillOptionsWithDefaults(options)
  8203. this.method = (function (options) {
  8204. var chooseMethods = []
  8205. .concat(options.methods, METHODS)
  8206. .filter(Boolean)
  8207. if (options.type) {
  8208. if ("simulate" === options.type) return simulate
  8209. var ret = chooseMethods.find(function (m) {
  8210. return m.type === options.type
  8211. })
  8212. if (ret) return ret
  8213. throw new Error("method-type " + options.type + " not found")
  8214. }
  8215. options.webWorkerSupport ||
  8216. isNode ||
  8217. (chooseMethods = chooseMethods.filter(function (m) {
  8218. return "idb" !== m.type
  8219. }))
  8220. var useMethod = chooseMethods.find(function (method) {
  8221. return method.canBeUsed()
  8222. })
  8223. if (useMethod) return useMethod
  8224. throw new Error(
  8225. "No useable method found in " +
  8226. JSON.stringify(
  8227. METHODS.map(function (m) {
  8228. return m.type
  8229. })
  8230. )
  8231. )
  8232. })(this.options)
  8233. this._iL = !1
  8234. this._onML = null
  8235. this._addEL = { message: [], internal: [] }
  8236. this._uMP = new Set()
  8237. this._befC = []
  8238. this._prepP = null
  8239. !(function (channel) {
  8240. var obj,
  8241. maybePromise = channel.method.create(channel.name, channel.options)
  8242. if ((obj = maybePromise) && "function" == typeof obj.then) {
  8243. channel._prepP = maybePromise
  8244. maybePromise.then(function (s) {
  8245. channel._state = s
  8246. })
  8247. } else channel._state = maybePromise
  8248. })(this)
  8249. }
  8250. broadcast_channel_BroadcastChannel._pubkey = !0
  8251. broadcast_channel_BroadcastChannel.prototype = {
  8252. postMessage: function (msg) {
  8253. if (this.closed)
  8254. throw new Error(
  8255. "BroadcastChannel.postMessage(): Cannot post message after channel has closed " +
  8256. JSON.stringify(msg)
  8257. )
  8258. return _post(this, "message", msg)
  8259. },
  8260. postInternal: function (msg) {
  8261. return _post(this, "internal", msg)
  8262. },
  8263. set onmessage(fn) {
  8264. var listenObj = { time: this.method.microSeconds(), fn }
  8265. _removeListenerObject(this, "message", this._onML)
  8266. if (fn && "function" == typeof fn) {
  8267. this._onML = listenObj
  8268. _addListenerObject(this, "message", listenObj)
  8269. } else this._onML = null
  8270. },
  8271. addEventListener: function (type, fn) {
  8272. _addListenerObject(this, type, { time: this.method.microSeconds(), fn })
  8273. },
  8274. removeEventListener: function (type, fn) {
  8275. _removeListenerObject(
  8276. this,
  8277. type,
  8278. this._addEL[type].find(function (obj) {
  8279. return obj.fn === fn
  8280. })
  8281. )
  8282. },
  8283. close: function () {
  8284. var _this = this
  8285. if (!this.closed) {
  8286. OPEN_BROADCAST_CHANNELS.delete(this)
  8287. this.closed = !0
  8288. var awaitPrepare = this._prepP ? this._prepP : PROMISE_RESOLVED_VOID
  8289. this._onML = null
  8290. this._addEL.message = []
  8291. return awaitPrepare
  8292. .then(function () {
  8293. return Promise.all(Array.from(_this._uMP))
  8294. })
  8295. .then(function () {
  8296. return Promise.all(
  8297. _this._befC.map(function (fn) {
  8298. return fn()
  8299. })
  8300. )
  8301. })
  8302. .then(function () {
  8303. return _this.method.close(_this._state)
  8304. })
  8305. }
  8306. },
  8307. get type() {
  8308. return this.method.type
  8309. },
  8310. get isClosed() {
  8311. return this.closed
  8312. },
  8313. }
  8314. function _post(broadcastChannel, type, msg) {
  8315. var msgObj = {
  8316. time: broadcastChannel.method.microSeconds(),
  8317. type,
  8318. data: msg,
  8319. }
  8320. return (
  8321. broadcastChannel._prepP
  8322. ? broadcastChannel._prepP
  8323. : PROMISE_RESOLVED_VOID
  8324. ).then(function () {
  8325. var sendPromise = broadcastChannel.method.postMessage(
  8326. broadcastChannel._state,
  8327. msgObj
  8328. )
  8329. broadcastChannel._uMP.add(sendPromise)
  8330. sendPromise.catch().then(function () {
  8331. return broadcastChannel._uMP.delete(sendPromise)
  8332. })
  8333. return sendPromise
  8334. })
  8335. }
  8336. function _hasMessageListeners(channel) {
  8337. return (
  8338. channel._addEL.message.length > 0 || channel._addEL.internal.length > 0
  8339. )
  8340. }
  8341. function _addListenerObject(channel, type, obj) {
  8342. channel._addEL[type].push(obj)
  8343. !(function (channel) {
  8344. if (!channel._iL && _hasMessageListeners(channel)) {
  8345. var listenerFn = function (msgObj) {
  8346. channel._addEL[msgObj.type].forEach(function (listenerObject) {
  8347. var minMessageTime = listenerObject.time - 1e5
  8348. msgObj.time >= minMessageTime && listenerObject.fn(msgObj.data)
  8349. })
  8350. },
  8351. time = channel.method.microSeconds()
  8352. if (channel._prepP)
  8353. channel._prepP.then(function () {
  8354. channel._iL = !0
  8355. channel.method.onMessage(channel._state, listenerFn, time)
  8356. })
  8357. else {
  8358. channel._iL = !0
  8359. channel.method.onMessage(channel._state, listenerFn, time)
  8360. }
  8361. }
  8362. })(channel)
  8363. }
  8364. function _removeListenerObject(channel, type, obj) {
  8365. channel._addEL[type] = channel._addEL[type].filter(function (o) {
  8366. return o !== obj
  8367. })
  8368. !(function (channel) {
  8369. if (channel._iL && !_hasMessageListeners(channel)) {
  8370. channel._iL = !1
  8371. var time = channel.method.microSeconds()
  8372. channel.method.onMessage(channel._state, null, time)
  8373. }
  8374. })(channel)
  8375. }
  8376. var browser = __webpack_require__(661),
  8377. browser_default = __webpack_require__.n(browser)
  8378. const es_browser = {
  8379. add: function (fn) {
  8380. if (
  8381. "function" == typeof WorkerGlobalScope &&
  8382. self instanceof WorkerGlobalScope
  8383. );
  8384. else {
  8385. if ("function" != typeof window.addEventListener) return
  8386. window.addEventListener(
  8387. "beforeunload",
  8388. function () {
  8389. fn()
  8390. },
  8391. !0
  8392. )
  8393. window.addEventListener(
  8394. "unload",
  8395. function () {
  8396. fn()
  8397. },
  8398. !0
  8399. )
  8400. }
  8401. },
  8402. }
  8403. var node_ignored_ = __webpack_require__(938),
  8404. node_ignored_default = __webpack_require__.n(node_ignored_)
  8405. browser_default() && node_ignored_default(), new Set()
  8406. const external_DeepDiff_namespaceObject = DeepDiff
  8407. var fast_deep_equal = __webpack_require__(204),
  8408. fast_deep_equal_default = __webpack_require__.n(fast_deep_equal)
  8409. const mapObject = f => o =>
  8410. pipe(Object.entries(o), ReadonlyArray_map(f), Object.fromEntries),
  8411. makePageState = mapObject(([k, v]) => [
  8412. k,
  8413. { ele: Option_none(), read: v },
  8414. ]),
  8415. removeOldChats = mainState => maxChatCount =>
  8416. pipe(
  8417. Effect_sync(() =>
  8418. mainState.flowChats.sort((a, b) =>
  8419. a.animationEnded === b.animationEnded
  8420. ? 0
  8421. : a.animationEnded
  8422. ? -1
  8423. : 1
  8424. )
  8425. ),
  8426. Effect_zipRight(
  8427. Effect_sync(() =>
  8428. mainState.flowChats.splice(
  8429. 0,
  8430. Math.max(0, mainState.flowChats.length - maxChatCount)
  8431. )
  8432. )
  8433. ),
  8434. Effect_flatMap(
  8435. Effect_forEach(x =>
  8436. pipe(
  8437. Effect_logDebug("RemoveChat"),
  8438. Effect_zipRight(
  8439. Effect_sync(() => {
  8440. x.element.remove()
  8441. })
  8442. )
  8443. )
  8444. )
  8445. )
  8446. ),
  8447. external_m_namespaceObject = m
  8448. var external_m_default = __webpack_require__.n(external_m_namespaceObject)
  8449. const getChatFontSize = mainState =>
  8450. Math.round(
  8451. ((Math.max(mainState.config.fontSize - 0.2, 0.01) *
  8452. mainState.playerRect.height) /
  8453. mainState.config.laneCount) *
  8454. (mainState.config.flowY2 - mainState.config.flowY1) *
  8455. 100
  8456. ) / 100,
  8457. textShadow = shadowColor =>
  8458. flow(
  8459. x => `${x}px`,
  8460. x => (a, b) => `${a}${x} ${b}${x} ${shadowColor}99`,
  8461. x => join(", ")([x("-", "-"), x("", "-"), x("-", ""), x("", "")])
  8462. ),
  8463. textStyle = { fontFamily: "inherit" },
  8464. renderChat = chat => mainState =>
  8465. Effect_sync(() =>
  8466. external_m_default().render(
  8467. chat.element,
  8468. ((chat, mainState) =>
  8469. pipe(
  8470. mainState.config,
  8471. config => ({ data: chat.getData(config), config }),
  8472. ({ data, config }) =>
  8473. external_m_default()(
  8474. "span",
  8475. {
  8476. style: {
  8477. fontSize: `${getChatFontSize(mainState)}px`,
  8478. visibility: config.displayChats ? "visible" : "hidden",
  8479. color:
  8480. "owner" === data.authorType
  8481. ? config.ownerColor
  8482. : "moderator" === data.authorType
  8483. ? config.moderatorColor
  8484. : "member" === data.authorType
  8485. ? config.memberColor
  8486. : config.color,
  8487. fontWeight: config.fontWeight.toString(),
  8488. fontFamily: config.font,
  8489. opacity: config.chatOpacity.toString(),
  8490. textShadow: textShadow(config.shadowColor)(
  8491. config.shadowFontWeight
  8492. ),
  8493. },
  8494. },
  8495. pipe(
  8496. [
  8497. pipe(
  8498. data.authorName,
  8499. Option_filter(x => x.visible),
  8500. Option_map(x =>
  8501. external_m_default()(
  8502. "span",
  8503. {
  8504. style: {
  8505. color: getOrUndefined(data.textColor),
  8506. fontSize: "0.84em",
  8507. ...textStyle,
  8508. },
  8509. },
  8510. `${x.content}: `
  8511. )
  8512. )
  8513. ),
  8514. pipe(
  8515. data.messageElement,
  8516. Option_map(x =>
  8517. ((message, config) => {
  8518. const eleWin =
  8519. message.ownerDocument.defaultView ?? window,
  8520. { maxChatLength } = config
  8521. return pipe(
  8522. Array.from(message.childNodes),
  8523. ReadonlyArray_reduce(
  8524. { vnodes: [], length: 0 },
  8525. ({ vnodes, length }, node) =>
  8526. length >= maxChatLength
  8527. ? { vnodes, length }
  8528. : !config.textOnly &&
  8529. node instanceof eleWin.HTMLImageElement
  8530. ? {
  8531. vnodes: [
  8532. ...vnodes,
  8533. external_m_default()("img", {
  8534. style: {
  8535. height: "1em",
  8536. width: "1em",
  8537. verticalAlign: "text-top",
  8538. },
  8539. src: node.src.replace(
  8540. /=w\d+-h\d+-c-k-nd$/,
  8541. ""
  8542. ),
  8543. alt: node.alt,
  8544. }),
  8545. ],
  8546. length: length + 1,
  8547. }
  8548. : pipe(
  8549. node.textContent ?? "",
  8550. slice(0, maxChatLength),
  8551. x =>
  8552. node instanceof
  8553. eleWin.HTMLAnchorElement
  8554. ? {
  8555. vnodes: [
  8556. ...vnodes,
  8557. external_m_default()(
  8558. "span",
  8559. {
  8560. style: {
  8561. fontSize: "0.84em",
  8562. textDecoration:
  8563. "underline",
  8564. ...textStyle,
  8565. },
  8566. },
  8567. x
  8568. ),
  8569. ],
  8570. length: length + x.length,
  8571. }
  8572. : {
  8573. vnodes: [
  8574. ...vnodes,
  8575. external_m_default().fragment(
  8576. {},
  8577. x
  8578. ),
  8579. ],
  8580. length: length + x.length,
  8581. }
  8582. )
  8583. )
  8584. )
  8585. })(x, config)
  8586. ),
  8587. Option_map(x =>
  8588. external_m_default()(
  8589. "span",
  8590. {
  8591. style: {
  8592. color: getOrUndefined(data.textColor),
  8593. ...textStyle,
  8594. },
  8595. },
  8596. x.vnodes
  8597. )
  8598. )
  8599. ),
  8600. pipe(
  8601. data.paymentInfo,
  8602. Option_filter(x => x.visible),
  8603. Option_map(x =>
  8604. external_m_default()(
  8605. "span",
  8606. {
  8607. style: {
  8608. color: getOrUndefined(data.paidColor),
  8609. fontSize: "0.84em",
  8610. ...textStyle,
  8611. },
  8612. },
  8613. external_m_default()(
  8614. "strong",
  8615. { style: textStyle },
  8616. x.content
  8617. )
  8618. )
  8619. )
  8620. ),
  8621. ],
  8622. ReadonlyArray_compact
  8623. )
  8624. )
  8625. ))(chat, mainState)
  8626. )
  8627. ),
  8628. Bicovariant_mapLeft = F =>
  8629. Function_dual(2, (self, f) => F.bimap(self, f, Function_identity)),
  8630. Bicovariant_map = F =>
  8631. Function_dual(2, (self, f) => F.bimap(self, Function_identity, f)),
  8632. getFirst = self => self[0],
  8633. getSecond = self => self[1],
  8634. Tuple_bimap = Function_dual(3, (self, f, g) => [f(self[0]), g(self[1])]),
  8635. Tuple_Bicovariant = { bimap: Tuple_bimap },
  8636. mapFirst = Bicovariant_mapLeft(Tuple_Bicovariant),
  8637. mapSecond = Bicovariant_map(Tuple_Bicovariant),
  8638. external_window_hash_it_namespaceObject = window["hash-it"]
  8639. var external_window_hash_it_default = __webpack_require__.n(
  8640. external_window_hash_it_namespaceObject
  8641. )
  8642. const external_window_micro_memoize_namespaceObject =
  8643. window["micro-memoize"]
  8644. var external_window_micro_memoize_default = __webpack_require__.n(
  8645. external_window_micro_memoize_namespaceObject
  8646. )
  8647. const getFlowChatProgress = chat =>
  8648. pipe(
  8649. chat.animation,
  8650. flatMapNullable(x => x.currentTime),
  8651. getOrElse(() => 0),
  8652. x => x / chat.animationDuration
  8653. ),
  8654. getFlowChatRect = (chat, mainState) =>
  8655. pipe(
  8656. mainState.config,
  8657. x =>
  8658. mainState.playerRect.width * x.flowX2 -
  8659. (chat.width + mainState.playerRect.width * (x.flowX2 - x.flowX1)) *
  8660. getFlowChatProgress(chat),
  8661. x => new DOMRect(x, chat.y, chat.width, chat.height)
  8662. ),
  8663. getChatLane = (flowChat, progress) => mainState => {
  8664. const flowWidth =
  8665. mainState.playerRect.width *
  8666. (mainState.config.flowX2 - mainState.config.flowX1),
  8667. chatRect = getFlowChatRect(flowChat, mainState),
  8668. chatWidth = chatRect.width,
  8669. chatHeight = chatRect.height,
  8670. chatX = chatRect.x,
  8671. { flowChats } = mainState,
  8672. chatIndex = flowChats.indexOf(flowChat),
  8673. movingChats = pipe(
  8674. flowChats,
  8675. take(chatIndex >= 0 ? chatIndex : flowChats.length),
  8676. ReadonlyArray_filter(
  8677. chat => !chat.animationEnded && chat.width > 0
  8678. ),
  8679. sort(Order_contramap(x => x.lane)(Order))
  8680. ),
  8681. tooCloseTo = external_window_micro_memoize_default()(
  8682. x => {
  8683. const otherRect = getFlowChatRect(x, mainState),
  8684. otherWidth = otherRect.width,
  8685. otherX = otherRect.x,
  8686. gap =
  8687. (chatHeight * otherWidth * chatWidth) ** 0.333 *
  8688. mainState.config.minSpacing
  8689. return (
  8690. (flowWidth - otherX) / (flowWidth + otherWidth) - progress <
  8691. (chatWidth + gap) / (flowWidth + chatWidth) ||
  8692. otherX + otherWidth + gap > chatX
  8693. )
  8694. },
  8695. { maxSize: 1e3 }
  8696. ),
  8697. occupyInfo = pipe(
  8698. movingChats,
  8699. ReadonlyArray_map(x => ({
  8700. tooClose: () => tooCloseTo(x),
  8701. lane: x.lane,
  8702. })),
  8703. append({ tooClose: () => !0, lane: mainState.config.laneCount })
  8704. ),
  8705. index = occupyInfo.findIndex(x => x.lane >= flowChat.lane),
  8706. bottomFreeLane = pipe(
  8707. occupyInfo.slice(index),
  8708. findFirst(x => x.tooClose()),
  8709. Option_map(x => x.lane),
  8710. getOrElse(() => mainState.config.laneCount)
  8711. ),
  8712. topFreeLane = pipe(
  8713. occupyInfo.slice(0, index),
  8714. findLast(x => x.tooClose()),
  8715. Option_map(x => x.lane),
  8716. getOrElse(() => -1)
  8717. ),
  8718. formerLaneInterval = Math.min(
  8719. flowChat.lane - topFreeLane,
  8720. bottomFreeLane - flowChat.lane,
  8721. 1
  8722. )
  8723. return pipe(
  8724. occupyInfo,
  8725. ReadonlyArray_reduce(
  8726. { maxInterval: 0, maxIntervalLane: 0, lastLane: -1 },
  8727. ({ maxInterval, maxIntervalLane, lastLane }, info) =>
  8728. maxInterval > 0.999 || !info.tooClose()
  8729. ? { maxInterval, maxIntervalLane, lastLane }
  8730. : (() => {
  8731. const nextLane = info.lane,
  8732. interLane = Math.min(
  8733. Math.max((lastLane + nextLane) / 2, 0),
  8734. mainState.config.laneCount - 1
  8735. ),
  8736. newInterval = Math.min(
  8737. interLane - lastLane,
  8738. nextLane - interLane,
  8739. 1
  8740. )
  8741. return newInterval - maxInterval > 0.001
  8742. ? {
  8743. maxInterval: newInterval,
  8744. maxIntervalLane: Math.max(lastLane + newInterval, 0),
  8745. lastLane: nextLane,
  8746. }
  8747. : { maxInterval, maxIntervalLane, lastLane: nextLane }
  8748. })()
  8749. ),
  8750. x => ({
  8751. lane:
  8752. Math.abs(formerLaneInterval - x.maxInterval) < 0.001
  8753. ? flowChat.lane
  8754. : x.maxIntervalLane,
  8755. interval: x.maxInterval,
  8756. })
  8757. )
  8758. },
  8759. getLaneY = (lane, mainState) =>
  8760. mainState.playerRect.height *
  8761. ((lane / mainState.config.laneCount + 0.005) *
  8762. (mainState.config.flowY2 - mainState.config.flowY1) +
  8763. mainState.config.flowY1),
  8764. intervalTooSmall = interval => config =>
  8765. config.noOverlap && interval < 0.999,
  8766. setChatPlayState = chat => mainState =>
  8767. pipe(
  8768. chat,
  8769. liftPredicate(x => !x.animationEnded),
  8770. Effect_fromOption,
  8771. Effect_map(x => x.animation),
  8772. Effect_flatMap(Effect_fromOption),
  8773. Effect_tap(x =>
  8774. Effect_sync(
  8775. mainState.chatPlaying ? () => x.play() : () => x.pause()
  8776. )
  8777. ),
  8778. Effect_flatMap(x =>
  8779. Effect_sync(() => {
  8780. x.playbackRate = mainState.config.flowSpeed / 15
  8781. })
  8782. ),
  8783. Effect_ignore
  8784. ),
  8785. getWidth = external_window_micro_memoize_default()(
  8786. ele => ele?.getBoundingClientRect().width ?? 0,
  8787. {
  8788. maxSize: 2e3,
  8789. transformKey: ReadonlyArray_map(external_window_hash_it_default()),
  8790. }
  8791. ),
  8792. setChatAnimation = chat => mainState =>
  8793. pipe(
  8794. { fontSize: getChatFontSize(mainState) },
  8795. Effect_succeed,
  8796. Effect_tap(x =>
  8797. Effect_sync(() => {
  8798. chat.element.style.transform = `translate(${
  8799. mainState.playerRect.width *
  8800. (mainState.config.flowX2 - mainState.config.flowX1)
  8801. }px, -${2 * x.fontSize}px)`
  8802. })
  8803. ),
  8804. Effect_filterOrFail(() => !chat.animationEnded, Option_none),
  8805. Effect_tap(x =>
  8806. Effect_sync(() => {
  8807. chat.animationDuration = 6400
  8808. chat.width = getWidth(chat.element.firstElementChild)
  8809. chat.height = x.fontSize
  8810. })
  8811. ),
  8812. Effect_map(() => getFlowChatProgress(chat)),
  8813. Effect_map(progress => ({
  8814. progress,
  8815. ...getChatLane(chat, progress)(mainState),
  8816. })),
  8817. Effect_filterOrElse(
  8818. x => !intervalTooSmall(x.interval)(mainState.config),
  8819. () =>
  8820. pipe(
  8821. chat.animation,
  8822. Effect_fromOption,
  8823. Effect_flatMap(x =>
  8824. Effect_sync(() => {
  8825. x.finish()
  8826. chat.animation = Option_none()
  8827. })
  8828. ),
  8829. Effect_zipRight(Effect_fail(Option_none()))
  8830. )
  8831. ),
  8832. Effect_tap(x =>
  8833. Effect_sync(() => {
  8834. chat.lane = x.lane
  8835. })
  8836. ),
  8837. Effect_map(x => ({ ...x, laneY: getLaneY(chat.lane, mainState) })),
  8838. Effect_tap(ctx =>
  8839. pipe(
  8840. [
  8841. pipe(
  8842. chat.animation,
  8843. Effect_fromOption,
  8844. Effect_flatMap(x => Effect_sync(() => x.cancel())),
  8845. Effect_ignore
  8846. ),
  8847. pipe(
  8848. [
  8849. [
  8850. mainState.playerRect.width *
  8851. (mainState.config.flowX2 - mainState.config.flowX1),
  8852. ctx.laneY,
  8853. ],
  8854. [-chat.width, ctx.laneY],
  8855. ],
  8856. ReadonlyArray_map(
  8857. pipe(
  8858. x => `${x}px`,
  8859. x => Tuple_bimap(x, x)
  8860. )
  8861. ),
  8862. ReadonlyArray_map(([x, y]) => `translate(${x}, ${y})`),
  8863. ReadonlyArray_bindTo("transform"),
  8864. x =>
  8865. Effect_sync(() =>
  8866. chat.element.animate(x, {
  8867. duration: 6400,
  8868. easing: mainState.config.timingFunction,
  8869. })
  8870. ),
  8871. Effect_tap(x =>
  8872. Effect_sync(() => {
  8873. x.onfinish = () => {
  8874. chat.animationEnded = !0
  8875. }
  8876. chat.y = ctx.laneY
  8877. const newTime = 6400 * ctx.progress
  8878. x.currentTime = newTime
  8879. })
  8880. ),
  8881. Effect_flatMap(x =>
  8882. Effect_sync(() => {
  8883. chat.animation = Option_some(x)
  8884. })
  8885. ),
  8886. Effect_zipRight(setChatPlayState(chat)(mainState))
  8887. ),
  8888. ],
  8889. x => Effect_all(x)
  8890. )
  8891. ),
  8892. Effect_isSuccess
  8893. ),
  8894. tapEffect = f =>
  8895. (0, external_rxjs_namespaceObject.concatMap)(x =>
  8896. (0, external_rxjs_namespaceObject.from)(runPromise(f(x))).pipe(
  8897. (0, external_rxjs_namespaceObject.map)(() => x)
  8898. )
  8899. ),
  8900. configStream = (provideLog, mainState, co, chatScreen, live) =>
  8901. (0, external_rxjs_namespaceObject.defer)(() =>
  8902. (0, external_rxjs_namespaceObject.merge)(
  8903. (0, external_rxjs_namespaceObject.merge)(
  8904. co.bannedWordRegexs,
  8905. co.bannedWords,
  8906. co.bannedUsers
  8907. ),
  8908. pipe(
  8909. co.fieldScale,
  8910. (0, external_rxjs_namespaceObject.startWith)(
  8911. mainState.config.fieldScale
  8912. ),
  8913. (0, external_rxjs_namespaceObject.map)(
  8914. (
  8915. live => scale =>
  8916. pipe(
  8917. live.chatField.ele,
  8918. Effect_fromOption,
  8919. Effect_flatMap(field =>
  8920. pipe(
  8921. [
  8922. pipe(
  8923. fromNullable(field.parentElement),
  8924. Option_map(x =>
  8925. Effect_sync(() =>
  8926. Object.assign(x.style, {
  8927. transformOrigin:
  8928. (scale >= 1 ? "top" : "bottom") + " left",
  8929. transform: `scale(${scale})`,
  8930. width: 100 / scale + "%",
  8931. height: 100 / scale + "%",
  8932. })
  8933. )
  8934. )
  8935. ),
  8936. pipe(
  8937. live.chatScroller.ele,
  8938. Option_map(scroller =>
  8939. Effect_sync(() => {
  8940. scroller.scrollTop = scroller.scrollHeight
  8941. })
  8942. )
  8943. ),
  8944. ],
  8945. ReadonlyArray_compact,
  8946. x => Effect_all(x)
  8947. )
  8948. ),
  8949. Effect_ignore
  8950. )
  8951. )(live)
  8952. ),
  8953. tapEffect(provideLog)
  8954. ),
  8955. pipe(
  8956. (0, external_rxjs_namespaceObject.merge)(
  8957. pipe(
  8958. (0, external_rxjs_namespaceObject.merge)(
  8959. co.font,
  8960. co.fontSize,
  8961. co.fontWeight,
  8962. co.laneCount,
  8963. co.minSpacing,
  8964. co.flowY1,
  8965. co.flowY2,
  8966. pipe(
  8967. co.flowX1,
  8968. (0, external_rxjs_namespaceObject.startWith)(
  8969. mainState.config.flowX1
  8970. ),
  8971. tapEffect(x =>
  8972. provideLog(
  8973. Effect_sync(() =>
  8974. Object.assign(chatScreen.style, {
  8975. left: 100 * x + "%",
  8976. width: 100 * (mainState.config.flowX2 - x) + "%",
  8977. })
  8978. )
  8979. )
  8980. )
  8981. ),
  8982. pipe(
  8983. co.flowX2,
  8984. tapEffect(x =>
  8985. provideLog(
  8986. Effect_sync(() =>
  8987. Object.assign(chatScreen.style, {
  8988. left: 100 * mainState.config.flowX1 + "%",
  8989. width: 100 * (x - mainState.config.flowX1) + "%",
  8990. })
  8991. )
  8992. )
  8993. )
  8994. ),
  8995. co.textOnly
  8996. ),
  8997. (0, external_rxjs_namespaceObject.map)(() => ({
  8998. render: !0,
  8999. setAnimation: !0,
  9000. }))
  9001. ),
  9002. pipe(
  9003. (0, external_rxjs_namespaceObject.merge)(
  9004. co.color,
  9005. co.ownerColor,
  9006. co.moderatorColor,
  9007. co.memberColor,
  9008. co.shadowColor,
  9009. co.chatOpacity,
  9010. co.shadowFontWeight,
  9011. co.displayChats
  9012. ),
  9013. (0, external_rxjs_namespaceObject.map)(() => ({ render: !0 }))
  9014. ),
  9015. pipe(
  9016. co.flowSpeed,
  9017. (0, external_rxjs_namespaceObject.map)(() => ({
  9018. setPlayState: !0,
  9019. }))
  9020. ),
  9021. pipe(
  9022. (0, external_rxjs_namespaceObject.merge)(
  9023. pipe(
  9024. co.maxChatCount,
  9025. (0, external_rxjs_namespaceObject.map)(
  9026. removeOldChats(mainState)
  9027. ),
  9028. tapEffect(provideLog)
  9029. ),
  9030. co.noOverlap,
  9031. co.timingFunction
  9032. ),
  9033. (0, external_rxjs_namespaceObject.map)(() => ({
  9034. setAnimation: !0,
  9035. }))
  9036. )
  9037. ),
  9038. (0, external_rxjs_namespaceObject.throttleTime)(180, void 0, {
  9039. leading: !0,
  9040. trailing: !0,
  9041. }),
  9042. (0, external_rxjs_namespaceObject.map)(x => ({
  9043. render: !1,
  9044. setAnimation: !1,
  9045. setPlayState: !1,
  9046. ...x,
  9047. })),
  9048. tapEffect(c =>
  9049. provideLog(
  9050. pipe(
  9051. mainState.flowChats,
  9052. ReadonlyArray_filter(x => !x.animationEnded),
  9053. ReadonlyArray_map(chat =>
  9054. pipe(
  9055. [
  9056. pipe(
  9057. renderChat(chat),
  9058. liftPredicate(() => c.render)
  9059. ),
  9060. c.setAnimation
  9061. ? Option_some(setChatAnimation(chat))
  9062. : c.setPlayState
  9063. ? Option_some(setChatPlayState(chat))
  9064. : Option_none(),
  9065. ],
  9066. ReadonlyArray_compact,
  9067. ReadonlyArray_map(apply(mainState)),
  9068. x => Effect_all(x)
  9069. )
  9070. ),
  9071. x => Effect_all(x),
  9072. Effect_asUnit
  9073. )
  9074. )
  9075. )
  9076. ),
  9077. co.lang,
  9078. co.maxChatLength,
  9079. co.simplifyChatField,
  9080. co.createBanButton,
  9081. co.createChats,
  9082. co.displayModName,
  9083. co.displaySuperChatAuthor,
  9084. co.fieldScale
  9085. )
  9086. ),
  9087. external_jsep_namespaceObject = jsep
  9088. var external_jsep_default = __webpack_require__.n(
  9089. external_jsep_namespaceObject
  9090. ),
  9091. u = {
  9092. "||": function (r, e) {
  9093. return r || e
  9094. },
  9095. "&&": function (r, e) {
  9096. return r && e
  9097. },
  9098. "|": function (r, e) {
  9099. return r | e
  9100. },
  9101. "^": function (r, e) {
  9102. return r ^ e
  9103. },
  9104. "&": function (r, e) {
  9105. return r & e
  9106. },
  9107. "==": function (r, e) {
  9108. return r == e
  9109. },
  9110. "!=": function (r, e) {
  9111. return r != e
  9112. },
  9113. "===": function (r, e) {
  9114. return r === e
  9115. },
  9116. "!==": function (r, e) {
  9117. return r !== e
  9118. },
  9119. "<": function (r, e) {
  9120. return r < e
  9121. },
  9122. ">": function (r, e) {
  9123. return r > e
  9124. },
  9125. "<=": function (r, e) {
  9126. return r <= e
  9127. },
  9128. ">=": function (r, e) {
  9129. return r >= e
  9130. },
  9131. "<<": function (r, e) {
  9132. return r << e
  9133. },
  9134. ">>": function (r, e) {
  9135. return r >> e
  9136. },
  9137. ">>>": function (r, e) {
  9138. return r >>> e
  9139. },
  9140. "+": function (r, e) {
  9141. return r + e
  9142. },
  9143. "-": function (r, e) {
  9144. return r - e
  9145. },
  9146. "*": function (r, e) {
  9147. return r * e
  9148. },
  9149. "/": function (r, e) {
  9150. return r / e
  9151. },
  9152. "%": function (r, e) {
  9153. return r % e
  9154. },
  9155. },
  9156. i = {
  9157. "-": function (r) {
  9158. return -r
  9159. },
  9160. "+": function (r) {
  9161. return +r
  9162. },
  9163. "~": function (r) {
  9164. return ~r
  9165. },
  9166. "!": function (r) {
  9167. return !r
  9168. },
  9169. }
  9170. function s(r, e) {
  9171. return r.map(function (r) {
  9172. return a(r, e)
  9173. })
  9174. }
  9175. function c(r, e) {
  9176. var n,
  9177. t = a(r.object, e)
  9178. if (
  9179. ((n = r.computed ? a(r.property, e) : r.property.name),
  9180. /^__proto__|prototype|constructor$/.test(n))
  9181. )
  9182. throw Error('Access to member "' + n + '" disallowed.')
  9183. return [t, t[n]]
  9184. }
  9185. function a(r, e) {
  9186. var n = r
  9187. switch (n.type) {
  9188. case "ArrayExpression":
  9189. return s(n.elements, e)
  9190. case "BinaryExpression":
  9191. return u[n.operator](a(n.left, e), a(n.right, e))
  9192. case "CallExpression":
  9193. var t, o, l
  9194. if (
  9195. ("MemberExpression" === n.callee.type
  9196. ? ((t = (l = c(n.callee, e))[0]), (o = l[1]))
  9197. : (o = a(n.callee, e)),
  9198. "function" != typeof o)
  9199. )
  9200. return
  9201. return o.apply(t, s(n.arguments, e))
  9202. case "ConditionalExpression":
  9203. return a(n.test, e) ? a(n.consequent, e) : a(n.alternate, e)
  9204. case "Identifier":
  9205. return e[n.name]
  9206. case "Literal":
  9207. return n.value
  9208. case "LogicalExpression":
  9209. return "||" === n.operator
  9210. ? a(n.left, e) || a(n.right, e)
  9211. : "&&" === n.operator
  9212. ? a(n.left, e) && a(n.right, e)
  9213. : u[n.operator](a(n.left, e), a(n.right, e))
  9214. case "MemberExpression":
  9215. return c(n, e)[1]
  9216. case "ThisExpression":
  9217. return e
  9218. case "UnaryExpression":
  9219. return i[n.operator](a(n.argument, e))
  9220. default:
  9221. return
  9222. }
  9223. }
  9224. const defaultFilter = config =>
  9225. external_jsep_default()(
  9226. `\nor([\nRA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  9227. config.bannedWords
  9228. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nRA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  9229. config.bannedWordRegexs
  9230. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nO.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  9231. config.bannedUsers
  9232. )})\n)(authorID)\n])\n`
  9233. ),
  9234. Chainable_bind = F =>
  9235. Function_dual(3, (self, name, f) =>
  9236. F.flatMap(self, a =>
  9237. F.map(f(a), b => Object.assign({}, a, { [name]: b }))
  9238. )
  9239. ),
  9240. Identity_map = Function_dual(2, (self, f) => f(self)),
  9241. Identity_imap = Covariant_imap(Identity_map),
  9242. Identity_Covariant = { imap: Identity_imap, map: Identity_map },
  9243. Identity_Invariant = { imap: Identity_imap },
  9244. Identity_Chainable = {
  9245. imap: Identity_imap,
  9246. map: Identity_map,
  9247. flatMap: Function_dual(2, (self, f) => f(self)),
  9248. },
  9249. Identity_SemiProduct = {
  9250. imap: Identity_imap,
  9251. product: (self, that) => [self, that],
  9252. productMany: (self, collection) => [self, ...collection],
  9253. },
  9254. Identity_bindTo = Invariant_bindTo(Identity_Invariant),
  9255. Identity_let_ = let_(Identity_Covariant),
  9256. Identity_bind = Chainable_bind(Identity_Chainable),
  9257. Identity_andThenBind = SemiProduct_andThenBind(Identity_SemiProduct),
  9258. external_astring_namespaceObject = astring,
  9259. fycKey = key => `FYC_${key}`,
  9260. languages = ["FYC_EN", "FYC_JA"],
  9261. stringsArgs = [
  9262. [],
  9263. flow(split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty))),
  9264. join("\n"),
  9265. ],
  9266. sc = (k, d) => {
  9267. return (
  9268. (key = fycKey(k)),
  9269. (defaultValue = d),
  9270. {
  9271. gmKey: key,
  9272. getValue: Effect_promise(
  9273. async () => (await GM.getValue(key)) ?? defaultValue
  9274. ),
  9275. defaultValue,
  9276. toGm: Function_identity,
  9277. }
  9278. )
  9279. var key, defaultValue
  9280. },
  9281. ic = (k, d, c, g) => {
  9282. return (
  9283. (key = fycKey(k)),
  9284. (toConfig = c),
  9285. pipe(
  9286. { gmKey: key, defaultValue: (defaultValue = d), toGm: g },
  9287. Identity_andThenBind(
  9288. "getValue",
  9289. pipe(
  9290. Effect_promise(() => GM.getValue(key)),
  9291. Effect_map(x => (void 0 !== x ? toConfig(x) : defaultValue))
  9292. )
  9293. )
  9294. )
  9295. )
  9296. var key, defaultValue, toConfig
  9297. },
  9298. src_defaultGMConfig = pipe(
  9299. {
  9300. lang: ic(
  9301. "LANG",
  9302. "FYC_EN",
  9303. x => (languages.includes(x) ? x : "FYC_EN"),
  9304. x => x
  9305. ),
  9306. font: sc("FONT", "MS PGothic"),
  9307. chatOpacity: sc("OPACITY", 0.8),
  9308. color: sc("COLOR", "#ffffff"),
  9309. ownerColor: sc("COLOR_OWNER", "#ffd600"),
  9310. moderatorColor: sc("COLOR_MODERATOR", "#c564ff"),
  9311. memberColor: sc("COLOR_MEMBER", "#9fffff"),
  9312. fontSize: sc("SIZE", 1),
  9313. fontWeight: sc("WEIGHT", 730),
  9314. shadowFontWeight: sc("WEIGHT_SHADOW", 1),
  9315. maxChatCount: sc("LIMIT", 40),
  9316. flowSpeed: sc("SPEED", 18),
  9317. maxChatLength: sc("MAX", 100),
  9318. laneCount: sc("LANE_DIV", 12),
  9319. bannedWords: ic("NG_WORDS", ...stringsArgs),
  9320. bannedWordRegexs: ic("NG_REG_WORDS", ...stringsArgs),
  9321. bannedUsers: ic("NG_USERS", ...stringsArgs),
  9322. createChats: sc("TOGGLE_CREATE_COMMENTS", !0),
  9323. noOverlap: sc("NO_OVERLAP", !0),
  9324. createBanButton: sc("NG_BUTTON", !0),
  9325. simplifyChatField: sc("SIMPLE_CHAT_FIELD", !1),
  9326. displayModName: sc("DISPLAY_MODERATOR_NAME", !0),
  9327. displaySuperChatAuthor: sc("DISPLAY_SUPER_CHAT_AUTHOR", !0),
  9328. textOnly: sc("TEXT_ONLY", !1),
  9329. timingFunction: sc("TIMING_FUNCTION", "linear"),
  9330. displayChats: sc("DISPLAY_COMMENTS", !0),
  9331. minSpacing: sc("MIN_SPACING", 0.5),
  9332. fieldScale: sc("FIELD_SCALE", 1),
  9333. flowY1: sc("flowY1", 0),
  9334. flowY2: sc("flowY2", 1),
  9335. flowX1: sc("flowX1", 0),
  9336. flowX2: sc("flowX2", 1),
  9337. shadowColor: sc("shadowColor", "#000000"),
  9338. },
  9339. Identity_bind("filterExp", x =>
  9340. ic(
  9341. "filterExp",
  9342. external_jsep_default()(
  9343. `\n or([\n RA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  9344. x.bannedWords.defaultValue
  9345. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n RA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  9346. x.bannedWordRegexs.defaultValue
  9347. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n O.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  9348. x.bannedUsers.defaultValue
  9349. )})\n )(authorID)\n ])\n `
  9350. ),
  9351. external_jsep_default(),
  9352. external_astring_namespaceObject.generate
  9353. )
  9354. )
  9355. ),
  9356. src_listeningBroadcastConfigKeys = [
  9357. "lang",
  9358. "bannedWords",
  9359. "bannedWordRegexs",
  9360. "bannedUsers",
  9361. "filterExp",
  9362. "simplifyChatField",
  9363. "createBanButton",
  9364. "fieldScale",
  9365. ],
  9366. src_flatMapOption = f => self =>
  9367. Effect_flatMap(flow(f, Effect_fromOption))(self),
  9368. chatApp = pipe(
  9369. Effect_sync(() => document.querySelector("#chatframe")),
  9370. Effect_map(
  9371. flow(
  9372. fromNullable,
  9373. Option_filter(
  9374. flow(
  9375. x => x.contentDocument?.readyState,
  9376. x => "loading" === x || "complete" === x
  9377. )
  9378. ),
  9379. flatMapNullable(x => x.contentDocument),
  9380. orElse(() => Option_some(document)),
  9381. flatMapNullable(x => x.querySelector("yt-live-chat-app"))
  9382. )
  9383. ),
  9384. Effect_some
  9385. ),
  9386. livePageYt = {
  9387. toggleChatBtnParent: pipe(
  9388. Effect_sync(() => document.querySelector(".ytp-right-controls")),
  9389. Effect_map(fromNullable),
  9390. Effect_some
  9391. ),
  9392. settingsToggleNextElement: pipe(
  9393. Effect_sync(() => document.querySelector("#menu-container")),
  9394. Effect_map(
  9395. flow(
  9396. fromNullable,
  9397. Option_filter(x => null !== x.offsetParent),
  9398. flatMapNullable(x =>
  9399. x.querySelector(".dropdown-trigger.ytd-menu-renderer")
  9400. ),
  9401. orElse(() =>
  9402. fromNullable(
  9403. document.querySelector(
  9404. "#top-row .dropdown-trigger.ytd-menu-renderer"
  9405. )
  9406. )
  9407. )
  9408. )
  9409. ),
  9410. Effect_some
  9411. ),
  9412. settingsContainer: pipe(
  9413. Effect_sync(() => document.body),
  9414. Effect_map(fromNullable),
  9415. Effect_some
  9416. ),
  9417. player: pipe(
  9418. Effect_sync(() => document.querySelector("#movie_player")),
  9419. Effect_map(fromNullable),
  9420. Effect_some
  9421. ),
  9422. video: pipe(
  9423. Effect_sync(() =>
  9424. document.querySelector("video.video-stream.html5-main-video")
  9425. ),
  9426. Effect_map(fromNullable),
  9427. Effect_some
  9428. ),
  9429. chatField: pipe(
  9430. chatApp,
  9431. src_flatMapOption(
  9432. flow(
  9433. x => x.querySelector("#items.yt-live-chat-item-list-renderer"),
  9434. fromNullable
  9435. )
  9436. )
  9437. ),
  9438. chatTicker: pipe(
  9439. chatApp,
  9440. src_flatMapOption(
  9441. flow(
  9442. x => x.querySelector("#items.yt-live-chat-ticker-renderer"),
  9443. fromNullable
  9444. )
  9445. )
  9446. ),
  9447. chatScroller: pipe(
  9448. chatApp,
  9449. src_flatMapOption(
  9450. flow(
  9451. x =>
  9452. x.querySelector(
  9453. "#item-scroller.yt-live-chat-item-list-renderer"
  9454. ),
  9455. fromNullable
  9456. )
  9457. )
  9458. ),
  9459. offlineSlate: pipe(
  9460. Effect_sync(() => document.querySelector(".ytp-offline-slate")),
  9461. Effect_map(fromNullable),
  9462. Effect_some
  9463. ),
  9464. },
  9465. FiberRef_locally = fiberRefLocally,
  9466. logMeta = fiberRefUnsafeMake(Option_none()),
  9467. logWithMeta = level => message => data =>
  9468. pipe(
  9469. Effect_log(message),
  9470. FiberRef_locally(logMeta, Option_some(data)),
  9471. x => locally(level)(x)
  9472. ),
  9473. mainCss = pipe(
  9474. Effect_sync(() => document.createElement("style")),
  9475. Effect_tap(x =>
  9476. Effect_sync(() => {
  9477. x.innerHTML =
  9478. ".fyc_chat {\n line-height: 1;\n z-index: 30;\n position: absolute;\n user-select: none;\n white-space: nowrap;\n will-change: transform;\n}\n.fyc_button {\n display: inline-block;\n border-style: none;\n z-index: 4;\n font-weight: 500;\n color: var(--yt-spec-text-secondary);\n}"
  9479. })
  9480. )
  9481. ),
  9482. makeChatScreen = pipe(
  9483. Effect_sync(() => document.createElement("div")),
  9484. Effect_tap(x =>
  9485. Effect_sync(() =>
  9486. Object.assign(x.style, {
  9487. pointerEvents: "none",
  9488. zIndex: "30",
  9489. position: "absolute",
  9490. overflow: "hidden",
  9491. height: "100%",
  9492. width: "100%",
  9493. })
  9494. )
  9495. )
  9496. ),
  9497. observePair = con =>
  9498. pipe(
  9499. Effect_Do(),
  9500. Effect_bind("subject", () =>
  9501. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  9502. ),
  9503. Effect_bind("observer", x =>
  9504. Effect_sync(() => new con(lib(x.subject)))
  9505. )
  9506. ),
  9507. emptyElement = document.createElement("span"),
  9508. appendChatMessage = flip(chat =>
  9509. Effect_flatMap(x =>
  9510. Effect_sync(() => chat.querySelector("#content #message")?.append(x))
  9511. )
  9512. ),
  9513. external_Swal_namespaceObject = Swal
  9514. var external_Swal_default = __webpack_require__.n(
  9515. external_Swal_namespaceObject
  9516. )
  9517. const defaultToast = external_Swal_default().mixin({
  9518. toast: !0,
  9519. position: "bottom-left",
  9520. timer: 2500,
  9521. timerProgressBar: !0,
  9522. showConfirmButton: !1,
  9523. didOpen: toast => {
  9524. toast.addEventListener(
  9525. "pointerenter",
  9526. external_Swal_default().stopTimer
  9527. )
  9528. toast.addEventListener(
  9529. "pointerleave",
  9530. external_Swal_default().resumeTimer
  9531. )
  9532. },
  9533. }),
  9534. template = runPromise(
  9535. pipe(
  9536. document.createElement("button"),
  9537. Effect_succeed,
  9538. Effect_tap(x =>
  9539. Effect_sync(() =>
  9540. x.classList.add("style-scope", "yt-icon-button", "fyc_button")
  9541. )
  9542. ),
  9543. Effect_tap(x =>
  9544. Effect_sync(() =>
  9545. Object.assign(x.style, {
  9546. padding: "0px",
  9547. width: "20px",
  9548. height: "20px",
  9549. fill: "#fff",
  9550. })
  9551. )
  9552. ),
  9553. Effect_tap(x =>
  9554. Effect_sync(() =>
  9555. x.setAttribute("aria-label", "NGに入れる(Ban this user)")
  9556. )
  9557. ),
  9558. Effect_tap(x =>
  9559. Effect_sync(() => {
  9560. x.innerHTML =
  9561. '<svg class="style-scope yt-icon" style="width: 100%; height: 75%; fill: var(--yt-spec-text-secondary);" viewBox="0 0 512 512"><path d="M440 78A256 256 0 1 0 73 435 256 256 0 0 0 440 78zm-99 35L113 341C37 179 212 44 341 113zM177 405l228-228c76 162-99 297-228 228z" fill-rule="evenodd"/></svg>'
  9562. })
  9563. )
  9564. )
  9565. ),
  9566. filter_filterOperators = {
  9567. flip,
  9568. flow: fns => flow(...fns),
  9569. and: Monoid_booleanEvery.combineAll,
  9570. or: Monoid_booleanSome.combineAll,
  9571. RA: { some: ReadonlyArray_some, compact: ReadonlyArray_compact },
  9572. O: { exists },
  9573. inText: text => x => includes(x)(text.content),
  9574. eqText: text => x => text.content === x,
  9575. matchedByText: text => x => Boolean(text.content.match(RegExp(x, "u"))),
  9576. isVisible: x => x.visible,
  9577. }
  9578. var typed_assert_build = __webpack_require__(52)
  9579. const tapNonNull = (x, message) => {
  9580. typed_assert_build.Xd(x, message)
  9581. return x
  9582. },
  9583. parseChat = chat => {
  9584. const chatType = chat.querySelector(
  9585. ".yt-live-chat-ticker-paid-message-item-renderer"
  9586. )
  9587. ? "ticker"
  9588. : chat.querySelector(".yt-live-chat-membership-item-renderer")
  9589. ? "membership"
  9590. : chat.querySelector(
  9591. ".yt-live-chat-viewer-engagement-message-renderer"
  9592. )
  9593. ? "engagement"
  9594. : "normal",
  9595. isPaid =
  9596. "ticker" === chatType || Boolean(chat.querySelector("#card")),
  9597. paymentInfo = pipe(
  9598. fromNullable(
  9599. isPaid
  9600. ? chat.querySelector(
  9601. join(", ")([
  9602. "#purchase-amount",
  9603. "#purchase-amount-chip",
  9604. "#content>#text",
  9605. ])
  9606. )?.textContent
  9607. : void 0
  9608. ),
  9609. Option_map(x => ({ visible: !0, content: x }))
  9610. ),
  9611. authorType = chat.querySelector(".owner")
  9612. ? "owner"
  9613. : chat.querySelector(".moderator")
  9614. ? "moderator"
  9615. : chat.querySelector(".member")
  9616. ? "member"
  9617. : "normal",
  9618. messageElement = fromNullable(chat.querySelector("#message")),
  9619. isPaidNormal =
  9620. !!Option_isSome(paymentInfo) &&
  9621. Boolean(chat.querySelector(".yt-live-chat-paid-message-renderer")),
  9622. isPaidSticker =
  9623. !(!Option_isSome(paymentInfo) || isPaidNormal) &&
  9624. Boolean(chat.querySelector(".yt-live-chat-paid-sticker-renderer")),
  9625. textColor = fromNullable(
  9626. isPaidNormal
  9627. ? window
  9628. .getComputedStyle(tapNonNull(chat.querySelector("#header")))
  9629. .getPropertyValue("background-color")
  9630. : isPaidSticker
  9631. ? window
  9632. .getComputedStyle(chat)
  9633. .getPropertyValue(
  9634. "--yt-live-chat-paid-sticker-chip-background-color"
  9635. )
  9636. : void 0
  9637. ),
  9638. paidColor = fromNullable(
  9639. isPaidNormal
  9640. ? window
  9641. .getComputedStyle(tapNonNull(chat.querySelector("#content")))
  9642. .getPropertyValue("background-color")
  9643. : isPaidSticker
  9644. ? window
  9645. .getComputedStyle(chat)
  9646. .getPropertyValue(
  9647. "--yt-live-chat-paid-sticker-background-color"
  9648. )
  9649. : void 0
  9650. ),
  9651. authorPhotoMatches = chat
  9652. .querySelector(join(" ")(["#author-photo", "img"]))
  9653. ?.src.match(/ggpht\.com\/(ytc\/)?(.*)=/),
  9654. authorID = fromNullable(authorPhotoMatches?.at(-1)),
  9655. authorName = fromNullable(
  9656. chat.querySelector("#author-name")?.textContent
  9657. ),
  9658. message = pipe(
  9659. messageElement,
  9660. Option_map(x => ({ visible: !0, content: x.innerHTML }))
  9661. ),
  9662. messageText = pipe(
  9663. messageElement,
  9664. Option_map(x => ({ visible: !0, content: x.textContent ?? "" }))
  9665. )
  9666. return config => ({
  9667. chatType,
  9668. authorType,
  9669. authorID,
  9670. authorName: pipe(
  9671. authorName,
  9672. Option_map(x => ({
  9673. visible:
  9674. ("moderator" === authorType && config.displayModName) ||
  9675. (Option_isSome(paymentInfo) && config.displaySuperChatAuthor),
  9676. content: x,
  9677. }))
  9678. ),
  9679. messageElement,
  9680. message,
  9681. messageText,
  9682. paymentInfo,
  9683. textColor,
  9684. paidColor,
  9685. })
  9686. },
  9687. onChatFieldMutate = (chatScrn, mainState, getConfig, setConfig) =>
  9688. flow(
  9689. ReadonlyArray_flatMap(e => Array.from(e.addedNodes)),
  9690. ReadonlyArray_filter(x => x.children.length > 0),
  9691. ReadonlyArray_reverse,
  9692. ReadonlyArray_map(chat =>
  9693. pipe(
  9694. { getData: parseChat(chat), config: mainState.config },
  9695. Identity_let_("data", x => x.getData(x.config)),
  9696. Effect_succeed,
  9697. Effect_bind("banned", x => {
  9698. return pipe(
  9699. ((data = x.data),
  9700. (config = x.config),
  9701. pipe(
  9702. data,
  9703. liftPredicate(() =>
  9704. pipe(config.filterExp, x =>
  9705. a(
  9706. x,
  9707. (data => ({
  9708. ...filter_filterOperators,
  9709. authorName: data.authorName,
  9710. message: data.message,
  9711. messageText: data.messageText,
  9712. paymentInfo: data.paymentInfo,
  9713. authorID: pipe(
  9714. data.authorID,
  9715. Option_map(x => ({ visible: !1, content: x }))
  9716. ),
  9717. }))(data)
  9718. )
  9719. )
  9720. ),
  9721. Option_map(x => [
  9722. pipe(
  9723. x.message,
  9724. Option_map(m => m.content)
  9725. ),
  9726. pipe(
  9727. x.paymentInfo,
  9728. Option_map(p => p.content)
  9729. ),
  9730. ]),
  9731. Option_map(ReadonlyArray_map(getOrElse(() => ""))),
  9732. Option_map(JSON.stringify),
  9733. Effect_fromOption,
  9734. Effect_flatMap(x => Effect_logDebug(`Filtered: ${x}`)),
  9735. Effect_isSuccess
  9736. ))
  9737. )
  9738. var data, config
  9739. }),
  9740. Effect_flatMap(ctx =>
  9741. ctx.banned
  9742. ? Effect_sync(() => {
  9743. chat.style.display = "none"
  9744. })
  9745. : Effect_all([
  9746. pipe(
  9747. ctx.config.createChats &&
  9748. "normal" === ctx.data.chatType,
  9749. liftPredicate(Function_identity),
  9750. Effect_fromOption,
  9751. Effect_flatMap(() =>
  9752. ((getData, chatScrn, mainState) =>
  9753. pipe(
  9754. {
  9755. getData,
  9756. element: emptyElement,
  9757. lane: -1,
  9758. animation: Option_none(),
  9759. animationDuration: 0,
  9760. animationEnded: !1,
  9761. width: 2,
  9762. height: getChatFontSize(mainState),
  9763. y: 0,
  9764. },
  9765. x => getChatLane(x, 0)(mainState).interval,
  9766. intervalTooSmall,
  9767. x => x(mainState.config)
  9768. )
  9769. ? Effect_unit()
  9770. : pipe(
  9771. mainState.flowChats,
  9772. findFirstIndex(
  9773. chat =>
  9774. chat.animationEnded ||
  9775. mainState.flowChats.length >=
  9776. mainState.config.maxChatCount
  9777. ),
  9778. offScreenIndex =>
  9779. pipe(
  9780. offScreenIndex,
  9781. Option_map(index =>
  9782. pipe(
  9783. mainState.flowChats,
  9784. unsafeGet(index),
  9785. x => x.element
  9786. )
  9787. ),
  9788. getOrElse(() =>
  9789. document.createElement("span")
  9790. ),
  9791. Effect_succeed,
  9792. Effect_tap(element =>
  9793. pipe(
  9794. offScreenIndex,
  9795. match(
  9796. () =>
  9797. Effect_sync(() =>
  9798. chatScrn.append(element)
  9799. ),
  9800. i =>
  9801. pipe(
  9802. Effect_sync(
  9803. () =>
  9804. mainState.flowChats.splice(
  9805. i,
  9806. 1
  9807. )?.[0]?.animation ??
  9808. Option_none()
  9809. ),
  9810. Effect_some,
  9811. Effect_flatMap(oldAnimation =>
  9812. Effect_sync(() =>
  9813. oldAnimation.cancel()
  9814. )
  9815. ),
  9816. Effect_ignore
  9817. )
  9818. )
  9819. )
  9820. )
  9821. ),
  9822. Effect_flatMap(element =>
  9823. pipe(
  9824. {
  9825. getData,
  9826. element,
  9827. lane: -1,
  9828. animation: Option_none(),
  9829. animationDuration: 0,
  9830. animationEnded: !1,
  9831. width: 2,
  9832. height: getChatFontSize(mainState),
  9833. y: 0,
  9834. },
  9835. Effect_succeed,
  9836. Effect_zipLeft(
  9837. Effect_sync(() =>
  9838. element.classList.add("fyc_chat")
  9839. )
  9840. )
  9841. )
  9842. ),
  9843. Effect_flatMap(flowChat =>
  9844. pipe(
  9845. mainState,
  9846. Effect_succeed,
  9847. Effect_tap(renderChat(flowChat)),
  9848. Effect_flatMap(
  9849. setChatAnimation(flowChat)
  9850. ),
  9851. Effect_flatMap(x =>
  9852. Effect_sync(
  9853. x
  9854. ? () =>
  9855. mainState.flowChats.push(
  9856. flowChat
  9857. )
  9858. : () => flowChat.element.remove()
  9859. )
  9860. )
  9861. )
  9862. )
  9863. ))(ctx.getData, chatScrn, mainState)
  9864. )
  9865. ),
  9866. pipe(
  9867. ctx.data.authorID,
  9868. Option_filter(() => ctx.config.createBanButton),
  9869. Option_filter(() => !chat.children.namedItem("card")),
  9870. Effect_fromOption,
  9871. Effect_flatMap(x => {
  9872. return appendChatMessage(
  9873. ((id = x),
  9874. getConfig => setConfig => chat =>
  9875. pipe(
  9876. getConfig.bannedUsers,
  9877. Effect_filterOrFail(
  9878. x => !x.includes(id),
  9879. Option_none
  9880. ),
  9881. Effect_map(
  9882. flow(uniq(String_Equivalence), append(id))
  9883. ),
  9884. Effect_flatMap(x =>
  9885. pipe(
  9886. setConfig.bannedUsers(x),
  9887. Effect_zipRight(
  9888. Effect_sync(() =>
  9889. defaultToast.fire({
  9890. title: `Added Banned User: ${id}`,
  9891. icon: "success",
  9892. })
  9893. )
  9894. )
  9895. )
  9896. ),
  9897. Effect_ignore,
  9898. Effect_zipRight(
  9899. Effect_sync(() => {
  9900. chat.style.display = "none"
  9901. })
  9902. ),
  9903. onclick =>
  9904. pipe(
  9905. Effect_promise(() => template),
  9906. Effect_map(x => x.cloneNode(!0)),
  9907. Effect_tap(x =>
  9908. Effect_sync(() => {
  9909. x.onclick = () => runPromise(onclick)
  9910. })
  9911. )
  9912. )
  9913. ))(getConfig)(setConfig)(chat)
  9914. )(chat)
  9915. var id
  9916. })
  9917. ),
  9918. pipe(
  9919. ctx.config.simplifyChatField,
  9920. liftPredicate(Function_identity),
  9921. Effect_fromOption,
  9922. Effect_flatMap(() =>
  9923. (chat =>
  9924. chat.querySelector(
  9925. ".style-scope.yt-live-chat-paid-message-renderer"
  9926. )
  9927. ? Effect_unit()
  9928. : pipe(
  9929. [
  9930. "#author-photo",
  9931. "yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer",
  9932. ],
  9933. ReadonlyArray_map(x =>
  9934. fromNullable(chat.querySelector(x))
  9935. ),
  9936. ReadonlyArray_compact,
  9937. ReadonlyArray_map(x =>
  9938. Effect_sync(() => {
  9939. x.style.display = "none"
  9940. })
  9941. ),
  9942. append(
  9943. Effect_sync(() => {
  9944. chat.style.borderBottom =
  9945. "1px solid var(--yt-spec-text-secondary)"
  9946. })
  9947. ),
  9948. x => Effect_all(x)
  9949. ))(chat)
  9950. )
  9951. ),
  9952. ])
  9953. ),
  9954. Effect_ignore
  9955. )
  9956. ),
  9957. x => Effect_all(x)
  9958. ),
  9959. exceptions = ["timingFunction", "lang"],
  9960. isEditable = k => v =>
  9961. ("number" == typeof v ||
  9962. "string" == typeof v ||
  9963. (Array.isArray(v) && ("string" == typeof v[0] || 0 === v.length))) &&
  9964. !ReadonlyArray_some(x => x === k)(exceptions),
  9965. Editable_of = x => [x, Option_none()],
  9966. fromValueText = v => t => [v, Option_some([t, Option_none()])],
  9967. Editable_value = getFirst,
  9968. Editable_text = flow(getSecond, Option_map(getFirst)),
  9969. error = flow(getSecond, flatMap(getSecond)),
  9970. setValue = flow(constant, x => mapFirst(x)),
  9971. setText = x =>
  9972. mapSecond(
  9973. flow(
  9974. Option_map(mapFirst(constant(x))),
  9975. orElse(constant(Option_some([x, Option_none()])))
  9976. )
  9977. ),
  9978. hasError = flow(error, Option_isSome),
  9979. RefinedConstructorsTypeId = Symbol.for("@effect/data/Brand/Refined"),
  9980. makeLog = Object.assign(args => args, {
  9981. [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
  9982. option: args => Option_some(args),
  9983. either: args => Either_right(args),
  9984. refine: _args => !0,
  9985. }),
  9986. settingStateInit = config =>
  9987. pipe(
  9988. config,
  9989. mapObject(([k, v]) => [
  9990. k,
  9991. isEditable(k)(v) ? Editable_of(v) : "filterExp" === k ? void 0 : v,
  9992. ]),
  9993. x => ({
  9994. ...x,
  9995. showPanel: !1,
  9996. mainTab: 0,
  9997. logTab: 0,
  9998. timingStepCount: Editable_of(
  9999. parseInt(
  10000. config.timingFunction.match(/^steps\((\d+),.+/)?.[1] ?? "150",
  10001. 10
  10002. )
  10003. ),
  10004. eventLog: makeLog({ nextId: 0, entries: [] }),
  10005. panelRect: new DOMRectReadOnly(0, 0, 660, 395),
  10006. })
  10007. )
  10008. var EMPTY_OBJ = {},
  10009. EMPTY_ARR = [],
  10010. hyperapp_id = a => a,
  10011. hyperapp_map = EMPTY_ARR.map,
  10012. isArray = Array.isArray,
  10013. enqueue =
  10014. "undefined" != typeof requestAnimationFrame
  10015. ? requestAnimationFrame
  10016. : setTimeout,
  10017. createClass = obj => {
  10018. var out = ""
  10019. if ("string" == typeof obj) return obj
  10020. if (isArray(obj))
  10021. for (var tmp, k = 0; k < obj.length; k++)
  10022. (tmp = createClass(obj[k])) && (out += (out && " ") + tmp)
  10023. else for (var k in obj) obj[k] && (out += (out && " ") + k)
  10024. return out
  10025. },
  10026. shouldRestart = (a, b) => {
  10027. for (var k in { ...a, ...b })
  10028. if ("function" == typeof (isArray(a[k]) ? a[k][0] : a[k])) b[k] = a[k]
  10029. else if (a[k] !== b[k]) return !0
  10030. },
  10031. getKey = vdom => (null == vdom ? vdom : vdom.key),
  10032. patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
  10033. if ("style" === key)
  10034. for (var k in { ...oldValue, ...newValue }) {
  10035. oldValue =
  10036. null == newValue || null == newValue[k] ? "" : newValue[k]
  10037. "-" === k[0]
  10038. ? node[key].setProperty(k, oldValue)
  10039. : (node[key][k] = oldValue)
  10040. }
  10041. else
  10042. "o" === key[0] && "n" === key[1]
  10043. ? ((node.events || (node.events = {}))[(key = key.slice(2))] =
  10044. newValue)
  10045. ? oldValue || node.addEventListener(key, listener)
  10046. : node.removeEventListener(key, listener)
  10047. : !isSvg && "list" !== key && "form" !== key && key in node
  10048. ? (node[key] = newValue ?? "")
  10049. : null == newValue || !1 === newValue
  10050. ? node.removeAttribute(key)
  10051. : node.setAttribute(key, newValue)
  10052. },
  10053. createNode = (vdom, listener, isSvg) => {
  10054. var props = vdom.props,
  10055. node =
  10056. 3 === vdom.type
  10057. ? document.createTextNode(vdom.tag)
  10058. : (isSvg = isSvg || "svg" === vdom.tag)
  10059. ? document.createElementNS(
  10060. "http://www.w3.org/2000/svg",
  10061. vdom.tag,
  10062. props.is && props
  10063. )
  10064. : document.createElement(vdom.tag, props.is && props)
  10065. for (var k in props)
  10066. patchProperty(node, k, null, props[k], listener, isSvg)
  10067. for (var i = 0; i < vdom.children.length; i++)
  10068. node.appendChild(
  10069. createNode(
  10070. (vdom.children[i] = maybeVNode(vdom.children[i])),
  10071. listener,
  10072. isSvg
  10073. )
  10074. )
  10075. return (vdom.node = node)
  10076. },
  10077. hyperapp_patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
  10078. if (oldVNode === newVNode);
  10079. else if (null != oldVNode && 3 === oldVNode.type && 3 === newVNode.type)
  10080. oldVNode.tag !== newVNode.tag && (node.nodeValue = newVNode.tag)
  10081. else if (null == oldVNode || oldVNode.tag !== newVNode.tag) {
  10082. node = parent.insertBefore(
  10083. createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
  10084. node
  10085. )
  10086. null != oldVNode && parent.removeChild(oldVNode.node)
  10087. } else {
  10088. var tmpVKid,
  10089. oldVKid,
  10090. oldKey,
  10091. newKey,
  10092. oldProps = oldVNode.props,
  10093. newProps = newVNode.props,
  10094. oldVKids = oldVNode.children,
  10095. newVKids = newVNode.children,
  10096. oldHead = 0,
  10097. newHead = 0,
  10098. oldTail = oldVKids.length - 1,
  10099. newTail = newVKids.length - 1
  10100. isSvg = isSvg || "svg" === newVNode.tag
  10101. for (var i in { ...oldProps, ...newProps })
  10102. ("value" === i || "selected" === i || "checked" === i
  10103. ? node[i]
  10104. : oldProps[i]) !== newProps[i] &&
  10105. patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
  10106. for (
  10107. ;
  10108. newHead <= newTail &&
  10109. oldHead <= oldTail &&
  10110. null != (oldKey = getKey(oldVKids[oldHead])) &&
  10111. oldKey === getKey(newVKids[newHead]);
  10112.  
  10113. )
  10114. hyperapp_patch(
  10115. node,
  10116. oldVKids[oldHead].node,
  10117. oldVKids[oldHead],
  10118. (newVKids[newHead] = maybeVNode(
  10119. newVKids[newHead++],
  10120. oldVKids[oldHead++]
  10121. )),
  10122. listener,
  10123. isSvg
  10124. )
  10125. for (
  10126. ;
  10127. newHead <= newTail &&
  10128. oldHead <= oldTail &&
  10129. null != (oldKey = getKey(oldVKids[oldTail])) &&
  10130. oldKey === getKey(newVKids[newTail]);
  10131.  
  10132. )
  10133. hyperapp_patch(
  10134. node,
  10135. oldVKids[oldTail].node,
  10136. oldVKids[oldTail],
  10137. (newVKids[newTail] = maybeVNode(
  10138. newVKids[newTail--],
  10139. oldVKids[oldTail--]
  10140. )),
  10141. listener,
  10142. isSvg
  10143. )
  10144. if (oldHead > oldTail)
  10145. for (; newHead <= newTail; )
  10146. node.insertBefore(
  10147. createNode(
  10148. (newVKids[newHead] = maybeVNode(newVKids[newHead++])),
  10149. listener,
  10150. isSvg
  10151. ),
  10152. (oldVKid = oldVKids[oldHead]) && oldVKid.node
  10153. )
  10154. else if (newHead > newTail)
  10155. for (; oldHead <= oldTail; )
  10156. node.removeChild(oldVKids[oldHead++].node)
  10157. else {
  10158. var keyed = {},
  10159. newKeyed = {}
  10160. for (i = oldHead; i <= oldTail; i++)
  10161. null != (oldKey = oldVKids[i].key) &&
  10162. (keyed[oldKey] = oldVKids[i])
  10163. for (; newHead <= newTail; ) {
  10164. oldKey = getKey((oldVKid = oldVKids[oldHead]))
  10165. newKey = getKey(
  10166. (newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid))
  10167. )
  10168. if (
  10169. newKeyed[oldKey] ||
  10170. (null != newKey && newKey === getKey(oldVKids[oldHead + 1]))
  10171. ) {
  10172. null == oldKey && node.removeChild(oldVKid.node)
  10173. oldHead++
  10174. } else if (null == newKey || 1 === oldVNode.type) {
  10175. if (null == oldKey) {
  10176. hyperapp_patch(
  10177. node,
  10178. oldVKid && oldVKid.node,
  10179. oldVKid,
  10180. newVKids[newHead],
  10181. listener,
  10182. isSvg
  10183. )
  10184. newHead++
  10185. }
  10186. oldHead++
  10187. } else {
  10188. if (oldKey === newKey) {
  10189. hyperapp_patch(
  10190. node,
  10191. oldVKid.node,
  10192. oldVKid,
  10193. newVKids[newHead],
  10194. listener,
  10195. isSvg
  10196. )
  10197. newKeyed[newKey] = !0
  10198. oldHead++
  10199. } else if (null != (tmpVKid = keyed[newKey])) {
  10200. hyperapp_patch(
  10201. node,
  10202. node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
  10203. tmpVKid,
  10204. newVKids[newHead],
  10205. listener,
  10206. isSvg
  10207. )
  10208. newKeyed[newKey] = !0
  10209. } else
  10210. hyperapp_patch(
  10211. node,
  10212. oldVKid && oldVKid.node,
  10213. null,
  10214. newVKids[newHead],
  10215. listener,
  10216. isSvg
  10217. )
  10218. newHead++
  10219. }
  10220. }
  10221. for (; oldHead <= oldTail; )
  10222. null == getKey((oldVKid = oldVKids[oldHead++])) &&
  10223. node.removeChild(oldVKid.node)
  10224. for (var i in keyed)
  10225. null == newKeyed[i] && node.removeChild(keyed[i].node)
  10226. }
  10227. }
  10228. return (newVNode.node = node)
  10229. },
  10230. maybeVNode = (newVNode, oldVNode) =>
  10231. !0 !== newVNode && !1 !== newVNode && newVNode
  10232. ? "function" == typeof newVNode.tag
  10233. ? ((!oldVNode ||
  10234. null == oldVNode.memo ||
  10235. ((a, b) => {
  10236. for (var k in a) if (a[k] !== b[k]) return !0
  10237. for (var k in b) if (a[k] !== b[k]) return !0
  10238. })(oldVNode.memo, newVNode.memo)) &&
  10239. ((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
  10240. oldVNode)
  10241. : newVNode
  10242. : hyperapp_text(""),
  10243. recycleNode = node =>
  10244. 3 === node.nodeType
  10245. ? hyperapp_text(node.nodeValue, node)
  10246. : createVNode(
  10247. node.nodeName.toLowerCase(),
  10248. EMPTY_OBJ,
  10249. hyperapp_map.call(node.childNodes, recycleNode),
  10250. 1,
  10251. node
  10252. ),
  10253. createVNode = (tag, { key, ...props }, children, type, node) => ({
  10254. tag,
  10255. props,
  10256. key,
  10257. children,
  10258. type,
  10259. node,
  10260. }),
  10261. hyperapp_text = (value, node) =>
  10262. createVNode(value, EMPTY_OBJ, EMPTY_ARR, 3, node),
  10263. h = (tag, { class: c, ...props }, children = EMPTY_ARR) =>
  10264. createVNode(
  10265. tag,
  10266. { ...props, ...(c ? { class: createClass(c) } : EMPTY_OBJ) },
  10267. isArray(children) ? children : [children]
  10268. ),
  10269. app = ({
  10270. node,
  10271. view,
  10272. subscriptions,
  10273. dispatch = hyperapp_id,
  10274. init = EMPTY_OBJ,
  10275. }) => {
  10276. var state,
  10277. busy,
  10278. vdom = node && recycleNode(node),
  10279. subs = [],
  10280. update = newState => {
  10281. if (state !== newState) {
  10282. null == (state = newState) &&
  10283. (dispatch = subscriptions = render = hyperapp_id)
  10284. subscriptions &&
  10285. (subs = ((oldSubs, newSubs = EMPTY_ARR, dispatch) => {
  10286. for (
  10287. var oldSub, newSub, subs = [], i = 0;
  10288. i < oldSubs.length || i < newSubs.length;
  10289. i++
  10290. ) {
  10291. oldSub = oldSubs[i]
  10292. newSub = newSubs[i]
  10293. subs.push(
  10294. newSub && !0 !== newSub
  10295. ? !oldSub ||
  10296. newSub[0] !== oldSub[0] ||
  10297. shouldRestart(newSub[1], oldSub[1])
  10298. ? [
  10299. newSub[0],
  10300. newSub[1],
  10301. (oldSub && oldSub[2](),
  10302. newSub[0](dispatch, newSub[1])),
  10303. ]
  10304. : oldSub
  10305. : oldSub && oldSub[2]()
  10306. )
  10307. }
  10308. return subs
  10309. })(subs, subscriptions(state), dispatch))
  10310. view && !busy && enqueue(render, (busy = !0))
  10311. }
  10312. },
  10313. render = () =>
  10314. (node = hyperapp_patch(
  10315. node.parentNode,
  10316. node,
  10317. vdom,
  10318. (vdom = view(state)),
  10319. listener,
  10320. (busy = !1)
  10321. )),
  10322. listener = function (event) {
  10323. dispatch(this.events[event.type], event)
  10324. }
  10325. return (
  10326. (dispatch = dispatch((action, props) =>
  10327. "function" == typeof action
  10328. ? dispatch(action(state, props))
  10329. : isArray(action)
  10330. ? "function" == typeof action[0]
  10331. ? dispatch(action[0], action[1])
  10332. : action
  10333. .slice(1)
  10334. .map(
  10335. fx => fx && !0 !== fx && (fx[0] || fx)(dispatch, fx[1]),
  10336. update(action[0])
  10337. )
  10338. : update(action)
  10339. ))(init),
  10340. dispatch
  10341. )
  10342. }
  10343. const makeComponent = x => tag => ({ tag, view: x(tag) }),
  10344. src_flip =
  10345. x =>
  10346. (...b) =>
  10347. (...a) =>
  10348. x(...a)(...b),
  10349. defaultText = {
  10350. setting: ["Settings", "設定"],
  10351. font: ["Font", "フォント"],
  10352. color: ["Color(Normal)", "色(通常)"],
  10353. ownerColor: ["Color(Owner)", "色(オーナー)"],
  10354. moderatorColor: ["Color(Moderator)", "色(モデレーター)"],
  10355. memberColor: ["Color(Member)", "色(メンバー)"],
  10356. feedback: ["Feedback", "バグ報告と要望"],
  10357. eventLog: ["Event log", "イベントログ"],
  10358. giveFeedback: [
  10359. "Give your feedbacks here(Please attach the event log if they're bug related)",
  10360. "バグ報告、要望はこちら(バグの場合は、イベントログを添付してください)",
  10361. ],
  10362. chatOpacity: ["Opacity", "不透明度"],
  10363. fontSize: ["Size", "サイズ"],
  10364. fontWeight: ["Weight", "太さ"],
  10365. shadowFontWeight: ["Weight(Shadow)", "太さ(影)"],
  10366. flowSpeed: ["Speed", "速度"],
  10367. maxChatCount: ["Max number of chats", "最大表示数"],
  10368. maxChatLength: ["Max number of characters", "最大文字数"],
  10369. laneCount: ["Number of rows", "行数"],
  10370. bannedWords: ["Banned Words", "NGワード"],
  10371. bannedWordRegexs: ["Banned Words(Regex)", "NGワード(正規表現)"],
  10372. bannedUsers: ["Banned Users", "NGユーザー"],
  10373. simplifyChatField: ["Simplify", "簡略化する"],
  10374. createBanButton: ["Show ban button", "NGボタンを表示する"],
  10375. displayModName: [
  10376. "Show moderator's name",
  10377. "モデレーターの名前を表示する",
  10378. ],
  10379. displaySuperChatAuthor: [
  10380. "Show super chat author",
  10381. "スパチャの作成者を表示する",
  10382. ],
  10383. createChats: ["Display flowing chats", "チャットを流す"],
  10384. textOnly: ["Text only(ignore emojis)", "文字のみ(絵文字を無視する)"],
  10385. error: ["Error", "エラー"],
  10386. video: ["Video", "画面"],
  10387. chatField: ["Chat Window", "チャット欄"],
  10388. useStepTiming: ["Move chat in steps", "チャットを段階的に動かす"],
  10389. timingStepCount: ["└Step Count", "└段階数"],
  10390. chatFilter: ["Chat Filter", "チャットフィルター"],
  10391. flowChat: ["Flow Chat", "チャット流れ"],
  10392. clearFlowChats: ["Clear Flowing Chats", "流れるチャットをクリアする"],
  10393. flowNewChatIf: [
  10394. "A new chat will appear if all of the followings are met:",
  10395. "新しいチャットは以下のすべてを満たす場合に流れます:",
  10396. ],
  10397. noOverlap: ["└Chats won't overlap", "└他のチャットと重ならない"],
  10398. minSpacing: ["Min spacing between chats", "チャットの最小間隔"],
  10399. fieldScale: ["Scale", "拡大率"],
  10400. copy: ["Copy", "コピーする"],
  10401. showChat: ["Show chats", "チャットを表示する"],
  10402. hideChat: ["Hide chats", "チャットを非表示にする"],
  10403. flowY1: ["Flow area top edge", "流れ範囲の上端"],
  10404. flowY2: ["Flow area bottom edge", "流れ範囲の下端"],
  10405. flowX1: ["Flow area left edge", "流れ範囲の左端"],
  10406. flowX2: ["Flow area right edge", "流れ範囲の右端"],
  10407. shadowColor: ["Color(Shadow)", "色(影)"],
  10408. invalidColor: ["Invalid color", "無効な色"],
  10409. inputNonNumberic: ["Input isn't a number", "入力値が数字でない"],
  10410. invalidSetting: ["Invalid setting", "無効な設定値"],
  10411. },
  10412. getText = key => language =>
  10413. defaultText[key]["FYC_EN" === language ? 0 : 1],
  10414. languageLabels = ["English", "日本語"],
  10415. computed = {
  10416. useStepTiming: s => Boolean(s.timingFunction.match(/^steps\(.+/)),
  10417. },
  10418. getState = k => (k in computed ? computed[k] : s => s[k]),
  10419. configEffect = (k, v) => setConfig => () => runPromise(setConfig[k](v)),
  10420. stepTiming = stepCount => `steps(${stepCount}, jump-end)`,
  10421. setComputed = {
  10422. useStepTiming: v => c => s =>
  10423. pipe(
  10424. v ? stepTiming(Editable_value(s.timingStepCount)) : "linear",
  10425. timingFunction => [
  10426. { ...s, timingFunction },
  10427. configEffect("timingFunction", timingFunction)(c.setConfig),
  10428. ]
  10429. ),
  10430. },
  10431. settingUI_setComputed = setComputed,
  10432. setRange = keyA => keyB => bFn => vA => c => s =>
  10433. pipe(
  10434. { a: Editable_value(vA) },
  10435. Identity_let_("b", ({ a }) => bFn(a)(Editable_value(s[keyB]))),
  10436. ({ a, b }) =>
  10437. pipe(
  10438. [configEffect(keyA, a), configEffect(keyB, b)],
  10439. xs => setter =>
  10440. pipe(
  10441. xs,
  10442. ReadonlyArray_map(x => x(setter)),
  10443. effects => [
  10444. { ...s, [keyA]: vA, [keyB]: setValue(b)(s[keyB]) },
  10445. ...effects,
  10446. ]
  10447. )
  10448. )(c.setConfig)
  10449. ),
  10450. setState = {
  10451. flowY1: setRange("flowY1")("flowY2")(a => b => Math.max(b, a + 0.05)),
  10452. flowY2: setRange("flowY2")("flowY1")(a => b => Math.min(b, a - 0.05)),
  10453. flowX1: setRange("flowX1")("flowX2")(a => b => Math.max(b, a + 0.05)),
  10454. flowX2: setRange("flowX2")("flowX1")(a => b => Math.min(b, a - 0.05)),
  10455. timingStepCount: v => c => s =>
  10456. pipe(stepTiming(Editable_value(v)), timingFunction => [
  10457. { ...s, timingStepCount: v, timingFunction },
  10458. configEffect("timingFunction", timingFunction)(c.setConfig),
  10459. ]),
  10460. },
  10461. settingUI_setState = setState,
  10462. updateAt = k => v =>
  10463. pipe(
  10464. k in settingUI_setComputed
  10465. ? settingUI_setComputed[k](v)
  10466. : k in settingUI_setState
  10467. ? settingUI_setState[k](v)
  10468. : c => s =>
  10469. [
  10470. { ...s, [k]: v },
  10471. ...(k in c.setConfig && "filterExp" !== k
  10472. ? [
  10473. configEffect(
  10474. k,
  10475. Array.isArray(v) &&
  10476. 2 === v.length &&
  10477. isEditable(k)(v[0])
  10478. ? Editable_value(v)
  10479. : v
  10480. )(c.setConfig),
  10481. ]
  10482. : []),
  10483. ]
  10484. )
  10485. var util, objectUtil
  10486. !(function (util) {
  10487. util.assertEqual = val => val
  10488. util.assertIs = function (_arg) {}
  10489. util.assertNever = function (_x) {
  10490. throw new Error()
  10491. }
  10492. util.arrayToEnum = items => {
  10493. const obj = {}
  10494. for (const item of items) obj[item] = item
  10495. return obj
  10496. }
  10497. util.getValidEnumValues = obj => {
  10498. const validKeys = util
  10499. .objectKeys(obj)
  10500. .filter(k => "number" != typeof obj[obj[k]]),
  10501. filtered = {}
  10502. for (const k of validKeys) filtered[k] = obj[k]
  10503. return util.objectValues(filtered)
  10504. }
  10505. util.objectValues = obj =>
  10506. util.objectKeys(obj).map(function (e) {
  10507. return obj[e]
  10508. })
  10509. util.objectKeys =
  10510. "function" == typeof Object.keys
  10511. ? obj => Object.keys(obj)
  10512. : object => {
  10513. const keys = []
  10514. for (const key in object)
  10515. Object.prototype.hasOwnProperty.call(object, key) &&
  10516. keys.push(key)
  10517. return keys
  10518. }
  10519. util.find = (arr, checker) => {
  10520. for (const item of arr) if (checker(item)) return item
  10521. }
  10522. util.isInteger =
  10523. "function" == typeof Number.isInteger
  10524. ? val => Number.isInteger(val)
  10525. : val =>
  10526. "number" == typeof val && isFinite(val) && Math.floor(val) === val
  10527. util.joinValues = function (array, separator = " | ") {
  10528. return array
  10529. .map(val => ("string" == typeof val ? `'${val}'` : val))
  10530. .join(separator)
  10531. }
  10532. util.jsonStringifyReplacer = (_, value) =>
  10533. "bigint" == typeof value ? value.toString() : value
  10534. })(util || (util = {}))
  10535. !(function (objectUtil) {
  10536. objectUtil.mergeShapes = (first, second) => ({ ...first, ...second })
  10537. })(objectUtil || (objectUtil = {}))
  10538. const ZodParsedType = util.arrayToEnum([
  10539. "string",
  10540. "nan",
  10541. "number",
  10542. "integer",
  10543. "float",
  10544. "boolean",
  10545. "date",
  10546. "bigint",
  10547. "symbol",
  10548. "function",
  10549. "undefined",
  10550. "null",
  10551. "array",
  10552. "object",
  10553. "unknown",
  10554. "promise",
  10555. "void",
  10556. "never",
  10557. "map",
  10558. "set",
  10559. ]),
  10560. getParsedType = data => {
  10561. switch (typeof data) {
  10562. case "undefined":
  10563. return ZodParsedType.undefined
  10564. case "string":
  10565. return ZodParsedType.string
  10566. case "number":
  10567. return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number
  10568. case "boolean":
  10569. return ZodParsedType.boolean
  10570. case "function":
  10571. return ZodParsedType.function
  10572. case "bigint":
  10573. return ZodParsedType.bigint
  10574. case "symbol":
  10575. return ZodParsedType.symbol
  10576. case "object":
  10577. return Array.isArray(data)
  10578. ? ZodParsedType.array
  10579. : null === data
  10580. ? ZodParsedType.null
  10581. : data.then &&
  10582. "function" == typeof data.then &&
  10583. data.catch &&
  10584. "function" == typeof data.catch
  10585. ? ZodParsedType.promise
  10586. : "undefined" != typeof Map && data instanceof Map
  10587. ? ZodParsedType.map
  10588. : "undefined" != typeof Set && data instanceof Set
  10589. ? ZodParsedType.set
  10590. : "undefined" != typeof Date && data instanceof Date
  10591. ? ZodParsedType.date
  10592. : ZodParsedType.object
  10593. default:
  10594. return ZodParsedType.unknown
  10595. }
  10596. },
  10597. ZodIssueCode = util.arrayToEnum([
  10598. "invalid_type",
  10599. "invalid_literal",
  10600. "custom",
  10601. "invalid_union",
  10602. "invalid_union_discriminator",
  10603. "invalid_enum_value",
  10604. "unrecognized_keys",
  10605. "invalid_arguments",
  10606. "invalid_return_type",
  10607. "invalid_date",
  10608. "invalid_string",
  10609. "too_small",
  10610. "too_big",
  10611. "invalid_intersection_types",
  10612. "not_multiple_of",
  10613. "not_finite",
  10614. ])
  10615. class ZodError extends Error {
  10616. constructor(issues) {
  10617. super()
  10618. this.issues = []
  10619. this.addIssue = sub => {
  10620. this.issues = [...this.issues, sub]
  10621. }
  10622. this.addIssues = (subs = []) => {
  10623. this.issues = [...this.issues, ...subs]
  10624. }
  10625. const actualProto = new.target.prototype
  10626. Object.setPrototypeOf
  10627. ? Object.setPrototypeOf(this, actualProto)
  10628. : (this.__proto__ = actualProto)
  10629. this.name = "ZodError"
  10630. this.issues = issues
  10631. }
  10632. get errors() {
  10633. return this.issues
  10634. }
  10635. format(_mapper) {
  10636. const mapper =
  10637. _mapper ||
  10638. function (issue) {
  10639. return issue.message
  10640. },
  10641. fieldErrors = { _errors: [] },
  10642. processError = error => {
  10643. for (const issue of error.issues)
  10644. if ("invalid_union" === issue.code)
  10645. issue.unionErrors.map(processError)
  10646. else if ("invalid_return_type" === issue.code)
  10647. processError(issue.returnTypeError)
  10648. else if ("invalid_arguments" === issue.code)
  10649. processError(issue.argumentsError)
  10650. else if (0 === issue.path.length)
  10651. fieldErrors._errors.push(mapper(issue))
  10652. else {
  10653. let curr = fieldErrors,
  10654. i = 0
  10655. for (; i < issue.path.length; ) {
  10656. const el = issue.path[i]
  10657. if (i === issue.path.length - 1) {
  10658. curr[el] = curr[el] || { _errors: [] }
  10659. curr[el]._errors.push(mapper(issue))
  10660. } else curr[el] = curr[el] || { _errors: [] }
  10661. curr = curr[el]
  10662. i++
  10663. }
  10664. }
  10665. }
  10666. processError(this)
  10667. return fieldErrors
  10668. }
  10669. toString() {
  10670. return this.message
  10671. }
  10672. get message() {
  10673. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2)
  10674. }
  10675. get isEmpty() {
  10676. return 0 === this.issues.length
  10677. }
  10678. flatten(mapper = issue => issue.message) {
  10679. const fieldErrors = {},
  10680. formErrors = []
  10681. for (const sub of this.issues)
  10682. if (sub.path.length > 0) {
  10683. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []
  10684. fieldErrors[sub.path[0]].push(mapper(sub))
  10685. } else formErrors.push(mapper(sub))
  10686. return { formErrors, fieldErrors }
  10687. }
  10688. get formErrors() {
  10689. return this.flatten()
  10690. }
  10691. }
  10692. ZodError.create = issues => new ZodError(issues)
  10693. const errorMap = (issue, _ctx) => {
  10694. let message
  10695. switch (issue.code) {
  10696. case ZodIssueCode.invalid_type:
  10697. message =
  10698. issue.received === ZodParsedType.undefined
  10699. ? "Required"
  10700. : `Expected ${issue.expected}, received ${issue.received}`
  10701. break
  10702. case ZodIssueCode.invalid_literal:
  10703. message = `Invalid literal value, expected ${JSON.stringify(
  10704. issue.expected,
  10705. util.jsonStringifyReplacer
  10706. )}`
  10707. break
  10708. case ZodIssueCode.unrecognized_keys:
  10709. message = `Unrecognized key(s) in object: ${util.joinValues(
  10710. issue.keys,
  10711. ", "
  10712. )}`
  10713. break
  10714. case ZodIssueCode.invalid_union:
  10715. message = "Invalid input"
  10716. break
  10717. case ZodIssueCode.invalid_union_discriminator:
  10718. message = `Invalid discriminator value. Expected ${util.joinValues(
  10719. issue.options
  10720. )}`
  10721. break
  10722. case ZodIssueCode.invalid_enum_value:
  10723. message = `Invalid enum value. Expected ${util.joinValues(
  10724. issue.options
  10725. )}, received '${issue.received}'`
  10726. break
  10727. case ZodIssueCode.invalid_arguments:
  10728. message = "Invalid function arguments"
  10729. break
  10730. case ZodIssueCode.invalid_return_type:
  10731. message = "Invalid function return type"
  10732. break
  10733. case ZodIssueCode.invalid_date:
  10734. message = "Invalid date"
  10735. break
  10736. case ZodIssueCode.invalid_string:
  10737. if ("object" == typeof issue.validation)
  10738. if ("includes" in issue.validation) {
  10739. message = `Invalid input: must include "${issue.validation.includes}"`
  10740. "number" == typeof issue.validation.position &&
  10741. (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)
  10742. } else
  10743. "startsWith" in issue.validation
  10744. ? (message = `Invalid input: must start with "${issue.validation.startsWith}"`)
  10745. : "endsWith" in issue.validation
  10746. ? (message = `Invalid input: must end with "${issue.validation.endsWith}"`)
  10747. : util.assertNever(issue.validation)
  10748. else
  10749. message =
  10750. "regex" !== issue.validation
  10751. ? `Invalid ${issue.validation}`
  10752. : "Invalid"
  10753. break
  10754. case ZodIssueCode.too_small:
  10755. message =
  10756. "array" === issue.type
  10757. ? `Array must contain ${
  10758. issue.exact
  10759. ? "exactly"
  10760. : issue.inclusive
  10761. ? "at least"
  10762. : "more than"
  10763. } ${issue.minimum} element(s)`
  10764. : "string" === issue.type
  10765. ? `String must contain ${
  10766. issue.exact
  10767. ? "exactly"
  10768. : issue.inclusive
  10769. ? "at least"
  10770. : "over"
  10771. } ${issue.minimum} character(s)`
  10772. : "number" === issue.type
  10773. ? `Number must be ${
  10774. issue.exact
  10775. ? "exactly equal to "
  10776. : issue.inclusive
  10777. ? "greater than or equal to "
  10778. : "greater than "
  10779. }${issue.minimum}`
  10780. : "date" === issue.type
  10781. ? `Date must be ${
  10782. issue.exact
  10783. ? "exactly equal to "
  10784. : issue.inclusive
  10785. ? "greater than or equal to "
  10786. : "greater than "
  10787. }${new Date(Number(issue.minimum))}`
  10788. : "Invalid input"
  10789. break
  10790. case ZodIssueCode.too_big:
  10791. message =
  10792. "array" === issue.type
  10793. ? `Array must contain ${
  10794. issue.exact
  10795. ? "exactly"
  10796. : issue.inclusive
  10797. ? "at most"
  10798. : "less than"
  10799. } ${issue.maximum} element(s)`
  10800. : "string" === issue.type
  10801. ? `String must contain ${
  10802. issue.exact
  10803. ? "exactly"
  10804. : issue.inclusive
  10805. ? "at most"
  10806. : "under"
  10807. } ${issue.maximum} character(s)`
  10808. : "number" === issue.type
  10809. ? `Number must be ${
  10810. issue.exact
  10811. ? "exactly"
  10812. : issue.inclusive
  10813. ? "less than or equal to"
  10814. : "less than"
  10815. } ${issue.maximum}`
  10816. : "bigint" === issue.type
  10817. ? `BigInt must be ${
  10818. issue.exact
  10819. ? "exactly"
  10820. : issue.inclusive
  10821. ? "less than or equal to"
  10822. : "less than"
  10823. } ${issue.maximum}`
  10824. : "date" === issue.type
  10825. ? `Date must be ${
  10826. issue.exact
  10827. ? "exactly"
  10828. : issue.inclusive
  10829. ? "smaller than or equal to"
  10830. : "smaller than"
  10831. } ${new Date(Number(issue.maximum))}`
  10832. : "Invalid input"
  10833. break
  10834. case ZodIssueCode.custom:
  10835. message = "Invalid input"
  10836. break
  10837. case ZodIssueCode.invalid_intersection_types:
  10838. message = "Intersection results could not be merged"
  10839. break
  10840. case ZodIssueCode.not_multiple_of:
  10841. message = `Number must be a multiple of ${issue.multipleOf}`
  10842. break
  10843. case ZodIssueCode.not_finite:
  10844. message = "Number must be finite"
  10845. break
  10846. default:
  10847. message = _ctx.defaultError
  10848. util.assertNever(issue)
  10849. }
  10850. return { message }
  10851. }
  10852. let overrideErrorMap = errorMap
  10853. function getErrorMap() {
  10854. return overrideErrorMap
  10855. }
  10856. const makeIssue = params => {
  10857. const { data, path, errorMaps, issueData } = params,
  10858. fullPath = [...path, ...(issueData.path || [])],
  10859. fullIssue = { ...issueData, path: fullPath }
  10860. let errorMessage = ""
  10861. const maps = errorMaps
  10862. .filter(m => !!m)
  10863. .slice()
  10864. .reverse()
  10865. for (const map of maps)
  10866. errorMessage = map(fullIssue, {
  10867. data,
  10868. defaultError: errorMessage,
  10869. }).message
  10870. return {
  10871. ...issueData,
  10872. path: fullPath,
  10873. message: issueData.message || errorMessage,
  10874. }
  10875. }
  10876. function addIssueToContext(ctx, issueData) {
  10877. const issue = makeIssue({
  10878. issueData,
  10879. data: ctx.data,
  10880. path: ctx.path,
  10881. errorMaps: [
  10882. ctx.common.contextualErrorMap,
  10883. ctx.schemaErrorMap,
  10884. getErrorMap(),
  10885. errorMap,
  10886. ].filter(x => !!x),
  10887. })
  10888. ctx.common.issues.push(issue)
  10889. }
  10890. class ParseStatus {
  10891. constructor() {
  10892. this.value = "valid"
  10893. }
  10894. dirty() {
  10895. "valid" === this.value && (this.value = "dirty")
  10896. }
  10897. abort() {
  10898. "aborted" !== this.value && (this.value = "aborted")
  10899. }
  10900. static mergeArray(status, results) {
  10901. const arrayValue = []
  10902. for (const s of results) {
  10903. if ("aborted" === s.status) return INVALID
  10904. "dirty" === s.status && status.dirty()
  10905. arrayValue.push(s.value)
  10906. }
  10907. return { status: status.value, value: arrayValue }
  10908. }
  10909. static async mergeObjectAsync(status, pairs) {
  10910. const syncPairs = []
  10911. for (const pair of pairs)
  10912. syncPairs.push({ key: await pair.key, value: await pair.value })
  10913. return ParseStatus.mergeObjectSync(status, syncPairs)
  10914. }
  10915. static mergeObjectSync(status, pairs) {
  10916. const finalObject = {}
  10917. for (const pair of pairs) {
  10918. const { key, value } = pair
  10919. if ("aborted" === key.status) return INVALID
  10920. if ("aborted" === value.status) return INVALID
  10921. "dirty" === key.status && status.dirty()
  10922. "dirty" === value.status && status.dirty()
  10923. ;(void 0 !== value.value || pair.alwaysSet) &&
  10924. (finalObject[key.value] = value.value)
  10925. }
  10926. return { status: status.value, value: finalObject }
  10927. }
  10928. }
  10929. const INVALID = Object.freeze({ status: "aborted" }),
  10930. DIRTY = value => ({ status: "dirty", value }),
  10931. OK = value => ({ status: "valid", value }),
  10932. isAborted = x => "aborted" === x.status,
  10933. isDirty = x => "dirty" === x.status,
  10934. isValid = x => "valid" === x.status,
  10935. isAsync = x => "undefined" != typeof Promise && x instanceof Promise
  10936. var errorUtil
  10937. !(function (errorUtil) {
  10938. errorUtil.errToObj = message =>
  10939. "string" == typeof message ? { message } : message || {}
  10940. errorUtil.toString = message =>
  10941. "string" == typeof message
  10942. ? message
  10943. : null == message
  10944. ? void 0
  10945. : message.message
  10946. })(errorUtil || (errorUtil = {}))
  10947. class ParseInputLazyPath {
  10948. constructor(parent, value, path, key) {
  10949. this._cachedPath = []
  10950. this.parent = parent
  10951. this.data = value
  10952. this._path = path
  10953. this._key = key
  10954. }
  10955. get path() {
  10956. this._cachedPath.length ||
  10957. (this._key instanceof Array
  10958. ? this._cachedPath.push(...this._path, ...this._key)
  10959. : this._cachedPath.push(...this._path, this._key))
  10960. return this._cachedPath
  10961. }
  10962. }
  10963. const handleResult = (ctx, result) => {
  10964. if (isValid(result)) return { success: !0, data: result.value }
  10965. if (!ctx.common.issues.length)
  10966. throw new Error("Validation failed but no issues detected.")
  10967. return {
  10968. success: !1,
  10969. get error() {
  10970. if (this._error) return this._error
  10971. const error = new ZodError(ctx.common.issues)
  10972. this._error = error
  10973. return this._error
  10974. },
  10975. }
  10976. }
  10977. function processCreateParams(params) {
  10978. if (!params) return {}
  10979. const { errorMap, invalid_type_error, required_error, description } =
  10980. params
  10981. if (errorMap && (invalid_type_error || required_error))
  10982. throw new Error(
  10983. 'Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.'
  10984. )
  10985. return errorMap
  10986. ? { errorMap, description }
  10987. : {
  10988. errorMap: (iss, ctx) =>
  10989. "invalid_type" !== iss.code
  10990. ? { message: ctx.defaultError }
  10991. : void 0 === ctx.data
  10992. ? {
  10993. message:
  10994. null != required_error
  10995. ? required_error
  10996. : ctx.defaultError,
  10997. }
  10998. : {
  10999. message:
  11000. null != invalid_type_error
  11001. ? invalid_type_error
  11002. : ctx.defaultError,
  11003. },
  11004. description,
  11005. }
  11006. }
  11007. class ZodType {
  11008. constructor(def) {
  11009. this.spa = this.safeParseAsync
  11010. this._def = def
  11011. this.parse = this.parse.bind(this)
  11012. this.safeParse = this.safeParse.bind(this)
  11013. this.parseAsync = this.parseAsync.bind(this)
  11014. this.safeParseAsync = this.safeParseAsync.bind(this)
  11015. this.spa = this.spa.bind(this)
  11016. this.refine = this.refine.bind(this)
  11017. this.refinement = this.refinement.bind(this)
  11018. this.superRefine = this.superRefine.bind(this)
  11019. this.optional = this.optional.bind(this)
  11020. this.nullable = this.nullable.bind(this)
  11021. this.nullish = this.nullish.bind(this)
  11022. this.array = this.array.bind(this)
  11023. this.promise = this.promise.bind(this)
  11024. this.or = this.or.bind(this)
  11025. this.and = this.and.bind(this)
  11026. this.transform = this.transform.bind(this)
  11027. this.brand = this.brand.bind(this)
  11028. this.default = this.default.bind(this)
  11029. this.catch = this.catch.bind(this)
  11030. this.describe = this.describe.bind(this)
  11031. this.pipe = this.pipe.bind(this)
  11032. this.isNullable = this.isNullable.bind(this)
  11033. this.isOptional = this.isOptional.bind(this)
  11034. }
  11035. get description() {
  11036. return this._def.description
  11037. }
  11038. _getType(input) {
  11039. return getParsedType(input.data)
  11040. }
  11041. _getOrReturnCtx(input, ctx) {
  11042. return (
  11043. ctx || {
  11044. common: input.parent.common,
  11045. data: input.data,
  11046. parsedType: getParsedType(input.data),
  11047. schemaErrorMap: this._def.errorMap,
  11048. path: input.path,
  11049. parent: input.parent,
  11050. }
  11051. )
  11052. }
  11053. _processInputParams(input) {
  11054. return {
  11055. status: new ParseStatus(),
  11056. ctx: {
  11057. common: input.parent.common,
  11058. data: input.data,
  11059. parsedType: getParsedType(input.data),
  11060. schemaErrorMap: this._def.errorMap,
  11061. path: input.path,
  11062. parent: input.parent,
  11063. },
  11064. }
  11065. }
  11066. _parseSync(input) {
  11067. const result = this._parse(input)
  11068. if (isAsync(result))
  11069. throw new Error("Synchronous parse encountered promise.")
  11070. return result
  11071. }
  11072. _parseAsync(input) {
  11073. const result = this._parse(input)
  11074. return Promise.resolve(result)
  11075. }
  11076. parse(data, params) {
  11077. const result = this.safeParse(data, params)
  11078. if (result.success) return result.data
  11079. throw result.error
  11080. }
  11081. safeParse(data, params) {
  11082. var _a
  11083. const ctx = {
  11084. common: {
  11085. issues: [],
  11086. async:
  11087. null !== (_a = null == params ? void 0 : params.async) &&
  11088. void 0 !== _a &&
  11089. _a,
  11090. contextualErrorMap: null == params ? void 0 : params.errorMap,
  11091. },
  11092. path: (null == params ? void 0 : params.path) || [],
  11093. schemaErrorMap: this._def.errorMap,
  11094. parent: null,
  11095. data,
  11096. parsedType: getParsedType(data),
  11097. },
  11098. result = this._parseSync({ data, path: ctx.path, parent: ctx })
  11099. return handleResult(ctx, result)
  11100. }
  11101. async parseAsync(data, params) {
  11102. const result = await this.safeParseAsync(data, params)
  11103. if (result.success) return result.data
  11104. throw result.error
  11105. }
  11106. async safeParseAsync(data, params) {
  11107. const ctx = {
  11108. common: {
  11109. issues: [],
  11110. contextualErrorMap: null == params ? void 0 : params.errorMap,
  11111. async: !0,
  11112. },
  11113. path: (null == params ? void 0 : params.path) || [],
  11114. schemaErrorMap: this._def.errorMap,
  11115. parent: null,
  11116. data,
  11117. parsedType: getParsedType(data),
  11118. },
  11119. maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }),
  11120. result = await (isAsync(maybeAsyncResult)
  11121. ? maybeAsyncResult
  11122. : Promise.resolve(maybeAsyncResult))
  11123. return handleResult(ctx, result)
  11124. }
  11125. refine(check, message) {
  11126. const getIssueProperties = val =>
  11127. "string" == typeof message || void 0 === message
  11128. ? { message }
  11129. : "function" == typeof message
  11130. ? message(val)
  11131. : message
  11132. return this._refinement((val, ctx) => {
  11133. const result = check(val),
  11134. setError = () =>
  11135. ctx.addIssue({
  11136. code: ZodIssueCode.custom,
  11137. ...getIssueProperties(val),
  11138. })
  11139. if ("undefined" != typeof Promise && result instanceof Promise)
  11140. return result.then(data => {
  11141. if (data) return !0
  11142. setError()
  11143. return !1
  11144. })
  11145. if (result) return !0
  11146. setError()
  11147. return !1
  11148. })
  11149. }
  11150. refinement(check, refinementData) {
  11151. return this._refinement((val, ctx) => {
  11152. if (check(val)) return !0
  11153. ctx.addIssue(
  11154. "function" == typeof refinementData
  11155. ? refinementData(val, ctx)
  11156. : refinementData
  11157. )
  11158. return !1
  11159. })
  11160. }
  11161. _refinement(refinement) {
  11162. return new ZodEffects({
  11163. schema: this,
  11164. typeName: ZodFirstPartyTypeKind.ZodEffects,
  11165. effect: { type: "refinement", refinement },
  11166. })
  11167. }
  11168. superRefine(refinement) {
  11169. return this._refinement(refinement)
  11170. }
  11171. optional() {
  11172. return ZodOptional.create(this, this._def)
  11173. }
  11174. nullable() {
  11175. return ZodNullable.create(this, this._def)
  11176. }
  11177. nullish() {
  11178. return this.nullable().optional()
  11179. }
  11180. array() {
  11181. return ZodArray.create(this, this._def)
  11182. }
  11183. promise() {
  11184. return ZodPromise.create(this, this._def)
  11185. }
  11186. or(option) {
  11187. return ZodUnion.create([this, option], this._def)
  11188. }
  11189. and(incoming) {
  11190. return ZodIntersection.create(this, incoming, this._def)
  11191. }
  11192. transform(transform) {
  11193. return new ZodEffects({
  11194. ...processCreateParams(this._def),
  11195. schema: this,
  11196. typeName: ZodFirstPartyTypeKind.ZodEffects,
  11197. effect: { type: "transform", transform },
  11198. })
  11199. }
  11200. default(def) {
  11201. const defaultValueFunc = "function" == typeof def ? def : () => def
  11202. return new ZodDefault({
  11203. ...processCreateParams(this._def),
  11204. innerType: this,
  11205. defaultValue: defaultValueFunc,
  11206. typeName: ZodFirstPartyTypeKind.ZodDefault,
  11207. })
  11208. }
  11209. brand() {
  11210. return new ZodBranded({
  11211. typeName: ZodFirstPartyTypeKind.ZodBranded,
  11212. type: this,
  11213. ...processCreateParams(this._def),
  11214. })
  11215. }
  11216. catch(def) {
  11217. const catchValueFunc = "function" == typeof def ? def : () => def
  11218. return new ZodCatch({
  11219. ...processCreateParams(this._def),
  11220. innerType: this,
  11221. catchValue: catchValueFunc,
  11222. typeName: ZodFirstPartyTypeKind.ZodCatch,
  11223. })
  11224. }
  11225. describe(description) {
  11226. return new (0, this.constructor)({ ...this._def, description })
  11227. }
  11228. pipe(target) {
  11229. return ZodPipeline.create(this, target)
  11230. }
  11231. isOptional() {
  11232. return this.safeParse(void 0).success
  11233. }
  11234. isNullable() {
  11235. return this.safeParse(null).success
  11236. }
  11237. }
  11238. const cuidRegex = /^c[^\s-]{8,}$/i,
  11239. cuid2Regex = /^[a-z][a-z0-9]*$/,
  11240. ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/,
  11241. uuidRegex =
  11242. /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,
  11243. emailRegex =
  11244. /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/,
  11245. emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,
  11246. ipv4Regex =
  11247. /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,
  11248. ipv6Regex =
  11249. /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/
  11250. class ZodString extends ZodType {
  11251. constructor() {
  11252. super(...arguments)
  11253. this._regex = (regex, validation, message) =>
  11254. this.refinement(data => regex.test(data), {
  11255. validation,
  11256. code: ZodIssueCode.invalid_string,
  11257. ...errorUtil.errToObj(message),
  11258. })
  11259. this.nonempty = message => this.min(1, errorUtil.errToObj(message))
  11260. this.trim = () =>
  11261. new ZodString({
  11262. ...this._def,
  11263. checks: [...this._def.checks, { kind: "trim" }],
  11264. })
  11265. this.toLowerCase = () =>
  11266. new ZodString({
  11267. ...this._def,
  11268. checks: [...this._def.checks, { kind: "toLowerCase" }],
  11269. })
  11270. this.toUpperCase = () =>
  11271. new ZodString({
  11272. ...this._def,
  11273. checks: [...this._def.checks, { kind: "toUpperCase" }],
  11274. })
  11275. }
  11276. _parse(input) {
  11277. this._def.coerce && (input.data = String(input.data))
  11278. if (this._getType(input) !== ZodParsedType.string) {
  11279. const ctx = this._getOrReturnCtx(input)
  11280. addIssueToContext(ctx, {
  11281. code: ZodIssueCode.invalid_type,
  11282. expected: ZodParsedType.string,
  11283. received: ctx.parsedType,
  11284. })
  11285. return INVALID
  11286. }
  11287. const status = new ParseStatus()
  11288. let ctx
  11289. for (const check of this._def.checks)
  11290. if ("min" === check.kind) {
  11291. if (input.data.length < check.value) {
  11292. ctx = this._getOrReturnCtx(input, ctx)
  11293. addIssueToContext(ctx, {
  11294. code: ZodIssueCode.too_small,
  11295. minimum: check.value,
  11296. type: "string",
  11297. inclusive: !0,
  11298. exact: !1,
  11299. message: check.message,
  11300. })
  11301. status.dirty()
  11302. }
  11303. } else if ("max" === check.kind) {
  11304. if (input.data.length > check.value) {
  11305. ctx = this._getOrReturnCtx(input, ctx)
  11306. addIssueToContext(ctx, {
  11307. code: ZodIssueCode.too_big,
  11308. maximum: check.value,
  11309. type: "string",
  11310. inclusive: !0,
  11311. exact: !1,
  11312. message: check.message,
  11313. })
  11314. status.dirty()
  11315. }
  11316. } else if ("length" === check.kind) {
  11317. const tooBig = input.data.length > check.value,
  11318. tooSmall = input.data.length < check.value
  11319. if (tooBig || tooSmall) {
  11320. ctx = this._getOrReturnCtx(input, ctx)
  11321. tooBig
  11322. ? addIssueToContext(ctx, {
  11323. code: ZodIssueCode.too_big,
  11324. maximum: check.value,
  11325. type: "string",
  11326. inclusive: !0,
  11327. exact: !0,
  11328. message: check.message,
  11329. })
  11330. : tooSmall &&
  11331. addIssueToContext(ctx, {
  11332. code: ZodIssueCode.too_small,
  11333. minimum: check.value,
  11334. type: "string",
  11335. inclusive: !0,
  11336. exact: !0,
  11337. message: check.message,
  11338. })
  11339. status.dirty()
  11340. }
  11341. } else if ("email" === check.kind) {
  11342. if (!emailRegex.test(input.data)) {
  11343. ctx = this._getOrReturnCtx(input, ctx)
  11344. addIssueToContext(ctx, {
  11345. validation: "email",
  11346. code: ZodIssueCode.invalid_string,
  11347. message: check.message,
  11348. })
  11349. status.dirty()
  11350. }
  11351. } else if ("emoji" === check.kind) {
  11352. if (!emojiRegex.test(input.data)) {
  11353. ctx = this._getOrReturnCtx(input, ctx)
  11354. addIssueToContext(ctx, {
  11355. validation: "emoji",
  11356. code: ZodIssueCode.invalid_string,
  11357. message: check.message,
  11358. })
  11359. status.dirty()
  11360. }
  11361. } else if ("uuid" === check.kind) {
  11362. if (!uuidRegex.test(input.data)) {
  11363. ctx = this._getOrReturnCtx(input, ctx)
  11364. addIssueToContext(ctx, {
  11365. validation: "uuid",
  11366. code: ZodIssueCode.invalid_string,
  11367. message: check.message,
  11368. })
  11369. status.dirty()
  11370. }
  11371. } else if ("cuid" === check.kind) {
  11372. if (!cuidRegex.test(input.data)) {
  11373. ctx = this._getOrReturnCtx(input, ctx)
  11374. addIssueToContext(ctx, {
  11375. validation: "cuid",
  11376. code: ZodIssueCode.invalid_string,
  11377. message: check.message,
  11378. })
  11379. status.dirty()
  11380. }
  11381. } else if ("cuid2" === check.kind) {
  11382. if (!cuid2Regex.test(input.data)) {
  11383. ctx = this._getOrReturnCtx(input, ctx)
  11384. addIssueToContext(ctx, {
  11385. validation: "cuid2",
  11386. code: ZodIssueCode.invalid_string,
  11387. message: check.message,
  11388. })
  11389. status.dirty()
  11390. }
  11391. } else if ("ulid" === check.kind) {
  11392. if (!ulidRegex.test(input.data)) {
  11393. ctx = this._getOrReturnCtx(input, ctx)
  11394. addIssueToContext(ctx, {
  11395. validation: "ulid",
  11396. code: ZodIssueCode.invalid_string,
  11397. message: check.message,
  11398. })
  11399. status.dirty()
  11400. }
  11401. } else if ("url" === check.kind)
  11402. try {
  11403. new URL(input.data)
  11404. } catch (_a) {
  11405. ctx = this._getOrReturnCtx(input, ctx)
  11406. addIssueToContext(ctx, {
  11407. validation: "url",
  11408. code: ZodIssueCode.invalid_string,
  11409. message: check.message,
  11410. })
  11411. status.dirty()
  11412. }
  11413. else if ("regex" === check.kind) {
  11414. check.regex.lastIndex = 0
  11415. if (!check.regex.test(input.data)) {
  11416. ctx = this._getOrReturnCtx(input, ctx)
  11417. addIssueToContext(ctx, {
  11418. validation: "regex",
  11419. code: ZodIssueCode.invalid_string,
  11420. message: check.message,
  11421. })
  11422. status.dirty()
  11423. }
  11424. } else if ("trim" === check.kind) input.data = input.data.trim()
  11425. else if ("includes" === check.kind) {
  11426. if (!input.data.includes(check.value, check.position)) {
  11427. ctx = this._getOrReturnCtx(input, ctx)
  11428. addIssueToContext(ctx, {
  11429. code: ZodIssueCode.invalid_string,
  11430. validation: { includes: check.value, position: check.position },
  11431. message: check.message,
  11432. })
  11433. status.dirty()
  11434. }
  11435. } else if ("toLowerCase" === check.kind)
  11436. input.data = input.data.toLowerCase()
  11437. else if ("toUpperCase" === check.kind)
  11438. input.data = input.data.toUpperCase()
  11439. else if ("startsWith" === check.kind) {
  11440. if (!input.data.startsWith(check.value)) {
  11441. ctx = this._getOrReturnCtx(input, ctx)
  11442. addIssueToContext(ctx, {
  11443. code: ZodIssueCode.invalid_string,
  11444. validation: { startsWith: check.value },
  11445. message: check.message,
  11446. })
  11447. status.dirty()
  11448. }
  11449. } else if ("endsWith" === check.kind) {
  11450. if (!input.data.endsWith(check.value)) {
  11451. ctx = this._getOrReturnCtx(input, ctx)
  11452. addIssueToContext(ctx, {
  11453. code: ZodIssueCode.invalid_string,
  11454. validation: { endsWith: check.value },
  11455. message: check.message,
  11456. })
  11457. status.dirty()
  11458. }
  11459. } else if ("datetime" === check.kind) {
  11460. if (
  11461. !(
  11462. (args = check).precision
  11463. ? args.offset
  11464. ? new RegExp(
  11465. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`
  11466. )
  11467. : new RegExp(
  11468. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`
  11469. )
  11470. : 0 === args.precision
  11471. ? args.offset
  11472. ? new RegExp(
  11473. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  11474. )
  11475. : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")
  11476. : args.offset
  11477. ? new RegExp(
  11478. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  11479. )
  11480. : new RegExp(
  11481. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"
  11482. )
  11483. ).test(input.data)
  11484. ) {
  11485. ctx = this._getOrReturnCtx(input, ctx)
  11486. addIssueToContext(ctx, {
  11487. code: ZodIssueCode.invalid_string,
  11488. validation: "datetime",
  11489. message: check.message,
  11490. })
  11491. status.dirty()
  11492. }
  11493. } else if ("ip" === check.kind) {
  11494. if (
  11495. !((ip = input.data),
  11496. (version = check.version),
  11497. (("v4" === version || !version) && ipv4Regex.test(ip)) ||
  11498. (("v6" === version || !version) && ipv6Regex.test(ip)))
  11499. ) {
  11500. ctx = this._getOrReturnCtx(input, ctx)
  11501. addIssueToContext(ctx, {
  11502. validation: "ip",
  11503. code: ZodIssueCode.invalid_string,
  11504. message: check.message,
  11505. })
  11506. status.dirty()
  11507. }
  11508. } else util.assertNever(check)
  11509. var ip, version, args
  11510. return { status: status.value, value: input.data }
  11511. }
  11512. _addCheck(check) {
  11513. return new ZodString({
  11514. ...this._def,
  11515. checks: [...this._def.checks, check],
  11516. })
  11517. }
  11518. email(message) {
  11519. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) })
  11520. }
  11521. url(message) {
  11522. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) })
  11523. }
  11524. emoji(message) {
  11525. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) })
  11526. }
  11527. uuid(message) {
  11528. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) })
  11529. }
  11530. cuid(message) {
  11531. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) })
  11532. }
  11533. cuid2(message) {
  11534. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) })
  11535. }
  11536. ulid(message) {
  11537. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) })
  11538. }
  11539. ip(options) {
  11540. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) })
  11541. }
  11542. datetime(options) {
  11543. var _a
  11544. return "string" == typeof options
  11545. ? this._addCheck({
  11546. kind: "datetime",
  11547. precision: null,
  11548. offset: !1,
  11549. message: options,
  11550. })
  11551. : this._addCheck({
  11552. kind: "datetime",
  11553. precision:
  11554. void 0 === (null == options ? void 0 : options.precision)
  11555. ? null
  11556. : null == options
  11557. ? void 0
  11558. : options.precision,
  11559. offset:
  11560. null !== (_a = null == options ? void 0 : options.offset) &&
  11561. void 0 !== _a &&
  11562. _a,
  11563. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  11564. })
  11565. }
  11566. regex(regex, message) {
  11567. return this._addCheck({
  11568. kind: "regex",
  11569. regex,
  11570. ...errorUtil.errToObj(message),
  11571. })
  11572. }
  11573. includes(value, options) {
  11574. return this._addCheck({
  11575. kind: "includes",
  11576. value,
  11577. position: null == options ? void 0 : options.position,
  11578. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  11579. })
  11580. }
  11581. startsWith(value, message) {
  11582. return this._addCheck({
  11583. kind: "startsWith",
  11584. value,
  11585. ...errorUtil.errToObj(message),
  11586. })
  11587. }
  11588. endsWith(value, message) {
  11589. return this._addCheck({
  11590. kind: "endsWith",
  11591. value,
  11592. ...errorUtil.errToObj(message),
  11593. })
  11594. }
  11595. min(minLength, message) {
  11596. return this._addCheck({
  11597. kind: "min",
  11598. value: minLength,
  11599. ...errorUtil.errToObj(message),
  11600. })
  11601. }
  11602. max(maxLength, message) {
  11603. return this._addCheck({
  11604. kind: "max",
  11605. value: maxLength,
  11606. ...errorUtil.errToObj(message),
  11607. })
  11608. }
  11609. length(len, message) {
  11610. return this._addCheck({
  11611. kind: "length",
  11612. value: len,
  11613. ...errorUtil.errToObj(message),
  11614. })
  11615. }
  11616. get isDatetime() {
  11617. return !!this._def.checks.find(ch => "datetime" === ch.kind)
  11618. }
  11619. get isEmail() {
  11620. return !!this._def.checks.find(ch => "email" === ch.kind)
  11621. }
  11622. get isURL() {
  11623. return !!this._def.checks.find(ch => "url" === ch.kind)
  11624. }
  11625. get isEmoji() {
  11626. return !!this._def.checks.find(ch => "emoji" === ch.kind)
  11627. }
  11628. get isUUID() {
  11629. return !!this._def.checks.find(ch => "uuid" === ch.kind)
  11630. }
  11631. get isCUID() {
  11632. return !!this._def.checks.find(ch => "cuid" === ch.kind)
  11633. }
  11634. get isCUID2() {
  11635. return !!this._def.checks.find(ch => "cuid2" === ch.kind)
  11636. }
  11637. get isULID() {
  11638. return !!this._def.checks.find(ch => "ulid" === ch.kind)
  11639. }
  11640. get isIP() {
  11641. return !!this._def.checks.find(ch => "ip" === ch.kind)
  11642. }
  11643. get minLength() {
  11644. let min = null
  11645. for (const ch of this._def.checks)
  11646. "min" === ch.kind &&
  11647. (null === min || ch.value > min) &&
  11648. (min = ch.value)
  11649. return min
  11650. }
  11651. get maxLength() {
  11652. let max = null
  11653. for (const ch of this._def.checks)
  11654. "max" === ch.kind &&
  11655. (null === max || ch.value < max) &&
  11656. (max = ch.value)
  11657. return max
  11658. }
  11659. }
  11660. ZodString.create = params => {
  11661. var _a
  11662. return new ZodString({
  11663. checks: [],
  11664. typeName: ZodFirstPartyTypeKind.ZodString,
  11665. coerce:
  11666. null !== (_a = null == params ? void 0 : params.coerce) &&
  11667. void 0 !== _a &&
  11668. _a,
  11669. ...processCreateParams(params),
  11670. })
  11671. }
  11672. function floatSafeRemainder(val, step) {
  11673. const valDecCount = (val.toString().split(".")[1] || "").length,
  11674. stepDecCount = (step.toString().split(".")[1] || "").length,
  11675. decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount
  11676. return (
  11677. (parseInt(val.toFixed(decCount).replace(".", "")) %
  11678. parseInt(step.toFixed(decCount).replace(".", ""))) /
  11679. Math.pow(10, decCount)
  11680. )
  11681. }
  11682. class ZodNumber extends ZodType {
  11683. constructor() {
  11684. super(...arguments)
  11685. this.min = this.gte
  11686. this.max = this.lte
  11687. this.step = this.multipleOf
  11688. }
  11689. _parse(input) {
  11690. this._def.coerce && (input.data = Number(input.data))
  11691. if (this._getType(input) !== ZodParsedType.number) {
  11692. const ctx = this._getOrReturnCtx(input)
  11693. addIssueToContext(ctx, {
  11694. code: ZodIssueCode.invalid_type,
  11695. expected: ZodParsedType.number,
  11696. received: ctx.parsedType,
  11697. })
  11698. return INVALID
  11699. }
  11700. let ctx
  11701. const status = new ParseStatus()
  11702. for (const check of this._def.checks)
  11703. if ("int" === check.kind) {
  11704. if (!util.isInteger(input.data)) {
  11705. ctx = this._getOrReturnCtx(input, ctx)
  11706. addIssueToContext(ctx, {
  11707. code: ZodIssueCode.invalid_type,
  11708. expected: "integer",
  11709. received: "float",
  11710. message: check.message,
  11711. })
  11712. status.dirty()
  11713. }
  11714. } else if ("min" === check.kind) {
  11715. if (
  11716. check.inclusive
  11717. ? input.data < check.value
  11718. : input.data <= check.value
  11719. ) {
  11720. ctx = this._getOrReturnCtx(input, ctx)
  11721. addIssueToContext(ctx, {
  11722. code: ZodIssueCode.too_small,
  11723. minimum: check.value,
  11724. type: "number",
  11725. inclusive: check.inclusive,
  11726. exact: !1,
  11727. message: check.message,
  11728. })
  11729. status.dirty()
  11730. }
  11731. } else if ("max" === check.kind) {
  11732. if (
  11733. check.inclusive
  11734. ? input.data > check.value
  11735. : input.data >= check.value
  11736. ) {
  11737. ctx = this._getOrReturnCtx(input, ctx)
  11738. addIssueToContext(ctx, {
  11739. code: ZodIssueCode.too_big,
  11740. maximum: check.value,
  11741. type: "number",
  11742. inclusive: check.inclusive,
  11743. exact: !1,
  11744. message: check.message,
  11745. })
  11746. status.dirty()
  11747. }
  11748. } else if ("multipleOf" === check.kind) {
  11749. if (0 !== floatSafeRemainder(input.data, check.value)) {
  11750. ctx = this._getOrReturnCtx(input, ctx)
  11751. addIssueToContext(ctx, {
  11752. code: ZodIssueCode.not_multiple_of,
  11753. multipleOf: check.value,
  11754. message: check.message,
  11755. })
  11756. status.dirty()
  11757. }
  11758. } else if ("finite" === check.kind) {
  11759. if (!Number.isFinite(input.data)) {
  11760. ctx = this._getOrReturnCtx(input, ctx)
  11761. addIssueToContext(ctx, {
  11762. code: ZodIssueCode.not_finite,
  11763. message: check.message,
  11764. })
  11765. status.dirty()
  11766. }
  11767. } else util.assertNever(check)
  11768. return { status: status.value, value: input.data }
  11769. }
  11770. gte(value, message) {
  11771. return this.setLimit("min", value, !0, errorUtil.toString(message))
  11772. }
  11773. gt(value, message) {
  11774. return this.setLimit("min", value, !1, errorUtil.toString(message))
  11775. }
  11776. lte(value, message) {
  11777. return this.setLimit("max", value, !0, errorUtil.toString(message))
  11778. }
  11779. lt(value, message) {
  11780. return this.setLimit("max", value, !1, errorUtil.toString(message))
  11781. }
  11782. setLimit(kind, value, inclusive, message) {
  11783. return new ZodNumber({
  11784. ...this._def,
  11785. checks: [
  11786. ...this._def.checks,
  11787. { kind, value, inclusive, message: errorUtil.toString(message) },
  11788. ],
  11789. })
  11790. }
  11791. _addCheck(check) {
  11792. return new ZodNumber({
  11793. ...this._def,
  11794. checks: [...this._def.checks, check],
  11795. })
  11796. }
  11797. int(message) {
  11798. return this._addCheck({
  11799. kind: "int",
  11800. message: errorUtil.toString(message),
  11801. })
  11802. }
  11803. positive(message) {
  11804. return this._addCheck({
  11805. kind: "min",
  11806. value: 0,
  11807. inclusive: !1,
  11808. message: errorUtil.toString(message),
  11809. })
  11810. }
  11811. negative(message) {
  11812. return this._addCheck({
  11813. kind: "max",
  11814. value: 0,
  11815. inclusive: !1,
  11816. message: errorUtil.toString(message),
  11817. })
  11818. }
  11819. nonpositive(message) {
  11820. return this._addCheck({
  11821. kind: "max",
  11822. value: 0,
  11823. inclusive: !0,
  11824. message: errorUtil.toString(message),
  11825. })
  11826. }
  11827. nonnegative(message) {
  11828. return this._addCheck({
  11829. kind: "min",
  11830. value: 0,
  11831. inclusive: !0,
  11832. message: errorUtil.toString(message),
  11833. })
  11834. }
  11835. multipleOf(value, message) {
  11836. return this._addCheck({
  11837. kind: "multipleOf",
  11838. value,
  11839. message: errorUtil.toString(message),
  11840. })
  11841. }
  11842. finite(message) {
  11843. return this._addCheck({
  11844. kind: "finite",
  11845. message: errorUtil.toString(message),
  11846. })
  11847. }
  11848. safe(message) {
  11849. return this._addCheck({
  11850. kind: "min",
  11851. inclusive: !0,
  11852. value: Number.MIN_SAFE_INTEGER,
  11853. message: errorUtil.toString(message),
  11854. })._addCheck({
  11855. kind: "max",
  11856. inclusive: !0,
  11857. value: Number.MAX_SAFE_INTEGER,
  11858. message: errorUtil.toString(message),
  11859. })
  11860. }
  11861. get minValue() {
  11862. let min = null
  11863. for (const ch of this._def.checks)
  11864. "min" === ch.kind &&
  11865. (null === min || ch.value > min) &&
  11866. (min = ch.value)
  11867. return min
  11868. }
  11869. get maxValue() {
  11870. let max = null
  11871. for (const ch of this._def.checks)
  11872. "max" === ch.kind &&
  11873. (null === max || ch.value < max) &&
  11874. (max = ch.value)
  11875. return max
  11876. }
  11877. get isInt() {
  11878. return !!this._def.checks.find(
  11879. ch =>
  11880. "int" === ch.kind ||
  11881. ("multipleOf" === ch.kind && util.isInteger(ch.value))
  11882. )
  11883. }
  11884. get isFinite() {
  11885. let max = null,
  11886. min = null
  11887. for (const ch of this._def.checks) {
  11888. if (
  11889. "finite" === ch.kind ||
  11890. "int" === ch.kind ||
  11891. "multipleOf" === ch.kind
  11892. )
  11893. return !0
  11894. "min" === ch.kind
  11895. ? (null === min || ch.value > min) && (min = ch.value)
  11896. : "max" === ch.kind &&
  11897. (null === max || ch.value < max) &&
  11898. (max = ch.value)
  11899. }
  11900. return Number.isFinite(min) && Number.isFinite(max)
  11901. }
  11902. }
  11903. ZodNumber.create = params =>
  11904. new ZodNumber({
  11905. checks: [],
  11906. typeName: ZodFirstPartyTypeKind.ZodNumber,
  11907. coerce: (null == params ? void 0 : params.coerce) || !1,
  11908. ...processCreateParams(params),
  11909. })
  11910. class ZodBigInt extends ZodType {
  11911. constructor() {
  11912. super(...arguments)
  11913. this.min = this.gte
  11914. this.max = this.lte
  11915. }
  11916. _parse(input) {
  11917. this._def.coerce && (input.data = BigInt(input.data))
  11918. if (this._getType(input) !== ZodParsedType.bigint) {
  11919. const ctx = this._getOrReturnCtx(input)
  11920. addIssueToContext(ctx, {
  11921. code: ZodIssueCode.invalid_type,
  11922. expected: ZodParsedType.bigint,
  11923. received: ctx.parsedType,
  11924. })
  11925. return INVALID
  11926. }
  11927. let ctx
  11928. const status = new ParseStatus()
  11929. for (const check of this._def.checks)
  11930. if ("min" === check.kind) {
  11931. if (
  11932. check.inclusive
  11933. ? input.data < check.value
  11934. : input.data <= check.value
  11935. ) {
  11936. ctx = this._getOrReturnCtx(input, ctx)
  11937. addIssueToContext(ctx, {
  11938. code: ZodIssueCode.too_small,
  11939. type: "bigint",
  11940. minimum: check.value,
  11941. inclusive: check.inclusive,
  11942. message: check.message,
  11943. })
  11944. status.dirty()
  11945. }
  11946. } else if ("max" === check.kind) {
  11947. if (
  11948. check.inclusive
  11949. ? input.data > check.value
  11950. : input.data >= check.value
  11951. ) {
  11952. ctx = this._getOrReturnCtx(input, ctx)
  11953. addIssueToContext(ctx, {
  11954. code: ZodIssueCode.too_big,
  11955. type: "bigint",
  11956. maximum: check.value,
  11957. inclusive: check.inclusive,
  11958. message: check.message,
  11959. })
  11960. status.dirty()
  11961. }
  11962. } else if ("multipleOf" === check.kind) {
  11963. if (input.data % check.value !== BigInt(0)) {
  11964. ctx = this._getOrReturnCtx(input, ctx)
  11965. addIssueToContext(ctx, {
  11966. code: ZodIssueCode.not_multiple_of,
  11967. multipleOf: check.value,
  11968. message: check.message,
  11969. })
  11970. status.dirty()
  11971. }
  11972. } else util.assertNever(check)
  11973. return { status: status.value, value: input.data }
  11974. }
  11975. gte(value, message) {
  11976. return this.setLimit("min", value, !0, errorUtil.toString(message))
  11977. }
  11978. gt(value, message) {
  11979. return this.setLimit("min", value, !1, errorUtil.toString(message))
  11980. }
  11981. lte(value, message) {
  11982. return this.setLimit("max", value, !0, errorUtil.toString(message))
  11983. }
  11984. lt(value, message) {
  11985. return this.setLimit("max", value, !1, errorUtil.toString(message))
  11986. }
  11987. setLimit(kind, value, inclusive, message) {
  11988. return new ZodBigInt({
  11989. ...this._def,
  11990. checks: [
  11991. ...this._def.checks,
  11992. { kind, value, inclusive, message: errorUtil.toString(message) },
  11993. ],
  11994. })
  11995. }
  11996. _addCheck(check) {
  11997. return new ZodBigInt({
  11998. ...this._def,
  11999. checks: [...this._def.checks, check],
  12000. })
  12001. }
  12002. positive(message) {
  12003. return this._addCheck({
  12004. kind: "min",
  12005. value: BigInt(0),
  12006. inclusive: !1,
  12007. message: errorUtil.toString(message),
  12008. })
  12009. }
  12010. negative(message) {
  12011. return this._addCheck({
  12012. kind: "max",
  12013. value: BigInt(0),
  12014. inclusive: !1,
  12015. message: errorUtil.toString(message),
  12016. })
  12017. }
  12018. nonpositive(message) {
  12019. return this._addCheck({
  12020. kind: "max",
  12021. value: BigInt(0),
  12022. inclusive: !0,
  12023. message: errorUtil.toString(message),
  12024. })
  12025. }
  12026. nonnegative(message) {
  12027. return this._addCheck({
  12028. kind: "min",
  12029. value: BigInt(0),
  12030. inclusive: !0,
  12031. message: errorUtil.toString(message),
  12032. })
  12033. }
  12034. multipleOf(value, message) {
  12035. return this._addCheck({
  12036. kind: "multipleOf",
  12037. value,
  12038. message: errorUtil.toString(message),
  12039. })
  12040. }
  12041. get minValue() {
  12042. let min = null
  12043. for (const ch of this._def.checks)
  12044. "min" === ch.kind &&
  12045. (null === min || ch.value > min) &&
  12046. (min = ch.value)
  12047. return min
  12048. }
  12049. get maxValue() {
  12050. let max = null
  12051. for (const ch of this._def.checks)
  12052. "max" === ch.kind &&
  12053. (null === max || ch.value < max) &&
  12054. (max = ch.value)
  12055. return max
  12056. }
  12057. }
  12058. ZodBigInt.create = params => {
  12059. var _a
  12060. return new ZodBigInt({
  12061. checks: [],
  12062. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  12063. coerce:
  12064. null !== (_a = null == params ? void 0 : params.coerce) &&
  12065. void 0 !== _a &&
  12066. _a,
  12067. ...processCreateParams(params),
  12068. })
  12069. }
  12070. class ZodBoolean extends ZodType {
  12071. _parse(input) {
  12072. this._def.coerce && (input.data = Boolean(input.data))
  12073. if (this._getType(input) !== ZodParsedType.boolean) {
  12074. const ctx = this._getOrReturnCtx(input)
  12075. addIssueToContext(ctx, {
  12076. code: ZodIssueCode.invalid_type,
  12077. expected: ZodParsedType.boolean,
  12078. received: ctx.parsedType,
  12079. })
  12080. return INVALID
  12081. }
  12082. return OK(input.data)
  12083. }
  12084. }
  12085. ZodBoolean.create = params =>
  12086. new ZodBoolean({
  12087. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  12088. coerce: (null == params ? void 0 : params.coerce) || !1,
  12089. ...processCreateParams(params),
  12090. })
  12091. class ZodDate extends ZodType {
  12092. _parse(input) {
  12093. this._def.coerce && (input.data = new Date(input.data))
  12094. if (this._getType(input) !== ZodParsedType.date) {
  12095. const ctx = this._getOrReturnCtx(input)
  12096. addIssueToContext(ctx, {
  12097. code: ZodIssueCode.invalid_type,
  12098. expected: ZodParsedType.date,
  12099. received: ctx.parsedType,
  12100. })
  12101. return INVALID
  12102. }
  12103. if (isNaN(input.data.getTime())) {
  12104. addIssueToContext(this._getOrReturnCtx(input), {
  12105. code: ZodIssueCode.invalid_date,
  12106. })
  12107. return INVALID
  12108. }
  12109. const status = new ParseStatus()
  12110. let ctx
  12111. for (const check of this._def.checks)
  12112. if ("min" === check.kind) {
  12113. if (input.data.getTime() < check.value) {
  12114. ctx = this._getOrReturnCtx(input, ctx)
  12115. addIssueToContext(ctx, {
  12116. code: ZodIssueCode.too_small,
  12117. message: check.message,
  12118. inclusive: !0,
  12119. exact: !1,
  12120. minimum: check.value,
  12121. type: "date",
  12122. })
  12123. status.dirty()
  12124. }
  12125. } else if ("max" === check.kind) {
  12126. if (input.data.getTime() > check.value) {
  12127. ctx = this._getOrReturnCtx(input, ctx)
  12128. addIssueToContext(ctx, {
  12129. code: ZodIssueCode.too_big,
  12130. message: check.message,
  12131. inclusive: !0,
  12132. exact: !1,
  12133. maximum: check.value,
  12134. type: "date",
  12135. })
  12136. status.dirty()
  12137. }
  12138. } else util.assertNever(check)
  12139. return { status: status.value, value: new Date(input.data.getTime()) }
  12140. }
  12141. _addCheck(check) {
  12142. return new ZodDate({
  12143. ...this._def,
  12144. checks: [...this._def.checks, check],
  12145. })
  12146. }
  12147. min(minDate, message) {
  12148. return this._addCheck({
  12149. kind: "min",
  12150. value: minDate.getTime(),
  12151. message: errorUtil.toString(message),
  12152. })
  12153. }
  12154. max(maxDate, message) {
  12155. return this._addCheck({
  12156. kind: "max",
  12157. value: maxDate.getTime(),
  12158. message: errorUtil.toString(message),
  12159. })
  12160. }
  12161. get minDate() {
  12162. let min = null
  12163. for (const ch of this._def.checks)
  12164. "min" === ch.kind &&
  12165. (null === min || ch.value > min) &&
  12166. (min = ch.value)
  12167. return null != min ? new Date(min) : null
  12168. }
  12169. get maxDate() {
  12170. let max = null
  12171. for (const ch of this._def.checks)
  12172. "max" === ch.kind &&
  12173. (null === max || ch.value < max) &&
  12174. (max = ch.value)
  12175. return null != max ? new Date(max) : null
  12176. }
  12177. }
  12178. ZodDate.create = params =>
  12179. new ZodDate({
  12180. checks: [],
  12181. coerce: (null == params ? void 0 : params.coerce) || !1,
  12182. typeName: ZodFirstPartyTypeKind.ZodDate,
  12183. ...processCreateParams(params),
  12184. })
  12185. class ZodSymbol extends ZodType {
  12186. _parse(input) {
  12187. if (this._getType(input) !== ZodParsedType.symbol) {
  12188. const ctx = this._getOrReturnCtx(input)
  12189. addIssueToContext(ctx, {
  12190. code: ZodIssueCode.invalid_type,
  12191. expected: ZodParsedType.symbol,
  12192. received: ctx.parsedType,
  12193. })
  12194. return INVALID
  12195. }
  12196. return OK(input.data)
  12197. }
  12198. }
  12199. ZodSymbol.create = params =>
  12200. new ZodSymbol({
  12201. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  12202. ...processCreateParams(params),
  12203. })
  12204. class ZodUndefined extends ZodType {
  12205. _parse(input) {
  12206. if (this._getType(input) !== ZodParsedType.undefined) {
  12207. const ctx = this._getOrReturnCtx(input)
  12208. addIssueToContext(ctx, {
  12209. code: ZodIssueCode.invalid_type,
  12210. expected: ZodParsedType.undefined,
  12211. received: ctx.parsedType,
  12212. })
  12213. return INVALID
  12214. }
  12215. return OK(input.data)
  12216. }
  12217. }
  12218. ZodUndefined.create = params =>
  12219. new ZodUndefined({
  12220. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  12221. ...processCreateParams(params),
  12222. })
  12223. class ZodNull extends ZodType {
  12224. _parse(input) {
  12225. if (this._getType(input) !== ZodParsedType.null) {
  12226. const ctx = this._getOrReturnCtx(input)
  12227. addIssueToContext(ctx, {
  12228. code: ZodIssueCode.invalid_type,
  12229. expected: ZodParsedType.null,
  12230. received: ctx.parsedType,
  12231. })
  12232. return INVALID
  12233. }
  12234. return OK(input.data)
  12235. }
  12236. }
  12237. ZodNull.create = params =>
  12238. new ZodNull({
  12239. typeName: ZodFirstPartyTypeKind.ZodNull,
  12240. ...processCreateParams(params),
  12241. })
  12242. class ZodAny extends ZodType {
  12243. constructor() {
  12244. super(...arguments)
  12245. this._any = !0
  12246. }
  12247. _parse(input) {
  12248. return OK(input.data)
  12249. }
  12250. }
  12251. ZodAny.create = params =>
  12252. new ZodAny({
  12253. typeName: ZodFirstPartyTypeKind.ZodAny,
  12254. ...processCreateParams(params),
  12255. })
  12256. class ZodUnknown extends ZodType {
  12257. constructor() {
  12258. super(...arguments)
  12259. this._unknown = !0
  12260. }
  12261. _parse(input) {
  12262. return OK(input.data)
  12263. }
  12264. }
  12265. ZodUnknown.create = params =>
  12266. new ZodUnknown({
  12267. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  12268. ...processCreateParams(params),
  12269. })
  12270. class ZodNever extends ZodType {
  12271. _parse(input) {
  12272. const ctx = this._getOrReturnCtx(input)
  12273. addIssueToContext(ctx, {
  12274. code: ZodIssueCode.invalid_type,
  12275. expected: ZodParsedType.never,
  12276. received: ctx.parsedType,
  12277. })
  12278. return INVALID
  12279. }
  12280. }
  12281. ZodNever.create = params =>
  12282. new ZodNever({
  12283. typeName: ZodFirstPartyTypeKind.ZodNever,
  12284. ...processCreateParams(params),
  12285. })
  12286. class ZodVoid extends ZodType {
  12287. _parse(input) {
  12288. if (this._getType(input) !== ZodParsedType.undefined) {
  12289. const ctx = this._getOrReturnCtx(input)
  12290. addIssueToContext(ctx, {
  12291. code: ZodIssueCode.invalid_type,
  12292. expected: ZodParsedType.void,
  12293. received: ctx.parsedType,
  12294. })
  12295. return INVALID
  12296. }
  12297. return OK(input.data)
  12298. }
  12299. }
  12300. ZodVoid.create = params =>
  12301. new ZodVoid({
  12302. typeName: ZodFirstPartyTypeKind.ZodVoid,
  12303. ...processCreateParams(params),
  12304. })
  12305. class ZodArray extends ZodType {
  12306. _parse(input) {
  12307. const { ctx, status } = this._processInputParams(input),
  12308. def = this._def
  12309. if (ctx.parsedType !== ZodParsedType.array) {
  12310. addIssueToContext(ctx, {
  12311. code: ZodIssueCode.invalid_type,
  12312. expected: ZodParsedType.array,
  12313. received: ctx.parsedType,
  12314. })
  12315. return INVALID
  12316. }
  12317. if (null !== def.exactLength) {
  12318. const tooBig = ctx.data.length > def.exactLength.value,
  12319. tooSmall = ctx.data.length < def.exactLength.value
  12320. if (tooBig || tooSmall) {
  12321. addIssueToContext(ctx, {
  12322. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  12323. minimum: tooSmall ? def.exactLength.value : void 0,
  12324. maximum: tooBig ? def.exactLength.value : void 0,
  12325. type: "array",
  12326. inclusive: !0,
  12327. exact: !0,
  12328. message: def.exactLength.message,
  12329. })
  12330. status.dirty()
  12331. }
  12332. }
  12333. if (null !== def.minLength && ctx.data.length < def.minLength.value) {
  12334. addIssueToContext(ctx, {
  12335. code: ZodIssueCode.too_small,
  12336. minimum: def.minLength.value,
  12337. type: "array",
  12338. inclusive: !0,
  12339. exact: !1,
  12340. message: def.minLength.message,
  12341. })
  12342. status.dirty()
  12343. }
  12344. if (null !== def.maxLength && ctx.data.length > def.maxLength.value) {
  12345. addIssueToContext(ctx, {
  12346. code: ZodIssueCode.too_big,
  12347. maximum: def.maxLength.value,
  12348. type: "array",
  12349. inclusive: !0,
  12350. exact: !1,
  12351. message: def.maxLength.message,
  12352. })
  12353. status.dirty()
  12354. }
  12355. if (ctx.common.async)
  12356. return Promise.all(
  12357. [...ctx.data].map((item, i) =>
  12358. def.type._parseAsync(
  12359. new ParseInputLazyPath(ctx, item, ctx.path, i)
  12360. )
  12361. )
  12362. ).then(result => ParseStatus.mergeArray(status, result))
  12363. const result = [...ctx.data].map((item, i) =>
  12364. def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))
  12365. )
  12366. return ParseStatus.mergeArray(status, result)
  12367. }
  12368. get element() {
  12369. return this._def.type
  12370. }
  12371. min(minLength, message) {
  12372. return new ZodArray({
  12373. ...this._def,
  12374. minLength: { value: minLength, message: errorUtil.toString(message) },
  12375. })
  12376. }
  12377. max(maxLength, message) {
  12378. return new ZodArray({
  12379. ...this._def,
  12380. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  12381. })
  12382. }
  12383. length(len, message) {
  12384. return new ZodArray({
  12385. ...this._def,
  12386. exactLength: { value: len, message: errorUtil.toString(message) },
  12387. })
  12388. }
  12389. nonempty(message) {
  12390. return this.min(1, message)
  12391. }
  12392. }
  12393. ZodArray.create = (schema, params) =>
  12394. new ZodArray({
  12395. type: schema,
  12396. minLength: null,
  12397. maxLength: null,
  12398. exactLength: null,
  12399. typeName: ZodFirstPartyTypeKind.ZodArray,
  12400. ...processCreateParams(params),
  12401. })
  12402. function deepPartialify(schema) {
  12403. if (schema instanceof ZodObject) {
  12404. const newShape = {}
  12405. for (const key in schema.shape) {
  12406. const fieldSchema = schema.shape[key]
  12407. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema))
  12408. }
  12409. return new ZodObject({ ...schema._def, shape: () => newShape })
  12410. }
  12411. return schema instanceof ZodArray
  12412. ? new ZodArray({ ...schema._def, type: deepPartialify(schema.element) })
  12413. : schema instanceof ZodOptional
  12414. ? ZodOptional.create(deepPartialify(schema.unwrap()))
  12415. : schema instanceof ZodNullable
  12416. ? ZodNullable.create(deepPartialify(schema.unwrap()))
  12417. : schema instanceof ZodTuple
  12418. ? ZodTuple.create(schema.items.map(item => deepPartialify(item)))
  12419. : schema
  12420. }
  12421. class ZodObject extends ZodType {
  12422. constructor() {
  12423. super(...arguments)
  12424. this._cached = null
  12425. this.nonstrict = this.passthrough
  12426. this.augment = this.extend
  12427. }
  12428. _getCached() {
  12429. if (null !== this._cached) return this._cached
  12430. const shape = this._def.shape(),
  12431. keys = util.objectKeys(shape)
  12432. return (this._cached = { shape, keys })
  12433. }
  12434. _parse(input) {
  12435. if (this._getType(input) !== ZodParsedType.object) {
  12436. const ctx = this._getOrReturnCtx(input)
  12437. addIssueToContext(ctx, {
  12438. code: ZodIssueCode.invalid_type,
  12439. expected: ZodParsedType.object,
  12440. received: ctx.parsedType,
  12441. })
  12442. return INVALID
  12443. }
  12444. const { status, ctx } = this._processInputParams(input),
  12445. { shape, keys: shapeKeys } = this._getCached(),
  12446. extraKeys = []
  12447. if (
  12448. !(
  12449. this._def.catchall instanceof ZodNever &&
  12450. "strip" === this._def.unknownKeys
  12451. )
  12452. )
  12453. for (const key in ctx.data)
  12454. shapeKeys.includes(key) || extraKeys.push(key)
  12455. const pairs = []
  12456. for (const key of shapeKeys) {
  12457. const keyValidator = shape[key],
  12458. value = ctx.data[key]
  12459. pairs.push({
  12460. key: { status: "valid", value: key },
  12461. value: keyValidator._parse(
  12462. new ParseInputLazyPath(ctx, value, ctx.path, key)
  12463. ),
  12464. alwaysSet: key in ctx.data,
  12465. })
  12466. }
  12467. if (this._def.catchall instanceof ZodNever) {
  12468. const unknownKeys = this._def.unknownKeys
  12469. if ("passthrough" === unknownKeys)
  12470. for (const key of extraKeys)
  12471. pairs.push({
  12472. key: { status: "valid", value: key },
  12473. value: { status: "valid", value: ctx.data[key] },
  12474. })
  12475. else if ("strict" === unknownKeys) {
  12476. if (extraKeys.length > 0) {
  12477. addIssueToContext(ctx, {
  12478. code: ZodIssueCode.unrecognized_keys,
  12479. keys: extraKeys,
  12480. })
  12481. status.dirty()
  12482. }
  12483. } else if ("strip" !== unknownKeys)
  12484. throw new Error(
  12485. "Internal ZodObject error: invalid unknownKeys value."
  12486. )
  12487. } else {
  12488. const catchall = this._def.catchall
  12489. for (const key of extraKeys) {
  12490. const value = ctx.data[key]
  12491. pairs.push({
  12492. key: { status: "valid", value: key },
  12493. value: catchall._parse(
  12494. new ParseInputLazyPath(ctx, value, ctx.path, key)
  12495. ),
  12496. alwaysSet: key in ctx.data,
  12497. })
  12498. }
  12499. }
  12500. return ctx.common.async
  12501. ? Promise.resolve()
  12502. .then(async () => {
  12503. const syncPairs = []
  12504. for (const pair of pairs) {
  12505. const key = await pair.key
  12506. syncPairs.push({
  12507. key,
  12508. value: await pair.value,
  12509. alwaysSet: pair.alwaysSet,
  12510. })
  12511. }
  12512. return syncPairs
  12513. })
  12514. .then(syncPairs => ParseStatus.mergeObjectSync(status, syncPairs))
  12515. : ParseStatus.mergeObjectSync(status, pairs)
  12516. }
  12517. get shape() {
  12518. return this._def.shape()
  12519. }
  12520. strict(message) {
  12521. errorUtil.errToObj
  12522. return new ZodObject({
  12523. ...this._def,
  12524. unknownKeys: "strict",
  12525. ...(void 0 !== message
  12526. ? {
  12527. errorMap: (issue, ctx) => {
  12528. var _a, _b, _c, _d
  12529. const defaultError =
  12530. null !==
  12531. (_c =
  12532. null === (_b = (_a = this._def).errorMap) ||
  12533. void 0 === _b
  12534. ? void 0
  12535. : _b.call(_a, issue, ctx).message) && void 0 !== _c
  12536. ? _c
  12537. : ctx.defaultError
  12538. return "unrecognized_keys" === issue.code
  12539. ? {
  12540. message:
  12541. null !== (_d = errorUtil.errToObj(message).message) &&
  12542. void 0 !== _d
  12543. ? _d
  12544. : defaultError,
  12545. }
  12546. : { message: defaultError }
  12547. },
  12548. }
  12549. : {}),
  12550. })
  12551. }
  12552. strip() {
  12553. return new ZodObject({ ...this._def, unknownKeys: "strip" })
  12554. }
  12555. passthrough() {
  12556. return new ZodObject({ ...this._def, unknownKeys: "passthrough" })
  12557. }
  12558. extend(augmentation) {
  12559. return new ZodObject({
  12560. ...this._def,
  12561. shape: () => ({ ...this._def.shape(), ...augmentation }),
  12562. })
  12563. }
  12564. merge(merging) {
  12565. return new ZodObject({
  12566. unknownKeys: merging._def.unknownKeys,
  12567. catchall: merging._def.catchall,
  12568. shape: () => ({ ...this._def.shape(), ...merging._def.shape() }),
  12569. typeName: ZodFirstPartyTypeKind.ZodObject,
  12570. })
  12571. }
  12572. setKey(key, schema) {
  12573. return this.augment({ [key]: schema })
  12574. }
  12575. catchall(index) {
  12576. return new ZodObject({ ...this._def, catchall: index })
  12577. }
  12578. pick(mask) {
  12579. const shape = {}
  12580. util.objectKeys(mask).forEach(key => {
  12581. mask[key] && this.shape[key] && (shape[key] = this.shape[key])
  12582. })
  12583. return new ZodObject({ ...this._def, shape: () => shape })
  12584. }
  12585. omit(mask) {
  12586. const shape = {}
  12587. util.objectKeys(this.shape).forEach(key => {
  12588. mask[key] || (shape[key] = this.shape[key])
  12589. })
  12590. return new ZodObject({ ...this._def, shape: () => shape })
  12591. }
  12592. deepPartial() {
  12593. return deepPartialify(this)
  12594. }
  12595. partial(mask) {
  12596. const newShape = {}
  12597. util.objectKeys(this.shape).forEach(key => {
  12598. const fieldSchema = this.shape[key]
  12599. mask && !mask[key]
  12600. ? (newShape[key] = fieldSchema)
  12601. : (newShape[key] = fieldSchema.optional())
  12602. })
  12603. return new ZodObject({ ...this._def, shape: () => newShape })
  12604. }
  12605. required(mask) {
  12606. const newShape = {}
  12607. util.objectKeys(this.shape).forEach(key => {
  12608. if (mask && !mask[key]) newShape[key] = this.shape[key]
  12609. else {
  12610. let newField = this.shape[key]
  12611. for (; newField instanceof ZodOptional; )
  12612. newField = newField._def.innerType
  12613. newShape[key] = newField
  12614. }
  12615. })
  12616. return new ZodObject({ ...this._def, shape: () => newShape })
  12617. }
  12618. keyof() {
  12619. return createZodEnum(util.objectKeys(this.shape))
  12620. }
  12621. }
  12622. ZodObject.create = (shape, params) =>
  12623. new ZodObject({
  12624. shape: () => shape,
  12625. unknownKeys: "strip",
  12626. catchall: ZodNever.create(),
  12627. typeName: ZodFirstPartyTypeKind.ZodObject,
  12628. ...processCreateParams(params),
  12629. })
  12630. ZodObject.strictCreate = (shape, params) =>
  12631. new ZodObject({
  12632. shape: () => shape,
  12633. unknownKeys: "strict",
  12634. catchall: ZodNever.create(),
  12635. typeName: ZodFirstPartyTypeKind.ZodObject,
  12636. ...processCreateParams(params),
  12637. })
  12638. ZodObject.lazycreate = (shape, params) =>
  12639. new ZodObject({
  12640. shape,
  12641. unknownKeys: "strip",
  12642. catchall: ZodNever.create(),
  12643. typeName: ZodFirstPartyTypeKind.ZodObject,
  12644. ...processCreateParams(params),
  12645. })
  12646. class ZodUnion extends ZodType {
  12647. _parse(input) {
  12648. const { ctx } = this._processInputParams(input),
  12649. options = this._def.options
  12650. if (ctx.common.async)
  12651. return Promise.all(
  12652. options.map(async option => {
  12653. const childCtx = {
  12654. ...ctx,
  12655. common: { ...ctx.common, issues: [] },
  12656. parent: null,
  12657. }
  12658. return {
  12659. result: await option._parseAsync({
  12660. data: ctx.data,
  12661. path: ctx.path,
  12662. parent: childCtx,
  12663. }),
  12664. ctx: childCtx,
  12665. }
  12666. })
  12667. ).then(function (results) {
  12668. for (const result of results)
  12669. if ("valid" === result.result.status) return result.result
  12670. for (const result of results)
  12671. if ("dirty" === result.result.status) {
  12672. ctx.common.issues.push(...result.ctx.common.issues)
  12673. return result.result
  12674. }
  12675. const unionErrors = results.map(
  12676. result => new ZodError(result.ctx.common.issues)
  12677. )
  12678. addIssueToContext(ctx, {
  12679. code: ZodIssueCode.invalid_union,
  12680. unionErrors,
  12681. })
  12682. return INVALID
  12683. })
  12684. {
  12685. let dirty
  12686. const issues = []
  12687. for (const option of options) {
  12688. const childCtx = {
  12689. ...ctx,
  12690. common: { ...ctx.common, issues: [] },
  12691. parent: null,
  12692. },
  12693. result = option._parseSync({
  12694. data: ctx.data,
  12695. path: ctx.path,
  12696. parent: childCtx,
  12697. })
  12698. if ("valid" === result.status) return result
  12699. "dirty" !== result.status ||
  12700. dirty ||
  12701. (dirty = { result, ctx: childCtx })
  12702. childCtx.common.issues.length && issues.push(childCtx.common.issues)
  12703. }
  12704. if (dirty) {
  12705. ctx.common.issues.push(...dirty.ctx.common.issues)
  12706. return dirty.result
  12707. }
  12708. const unionErrors = issues.map(issues => new ZodError(issues))
  12709. addIssueToContext(ctx, {
  12710. code: ZodIssueCode.invalid_union,
  12711. unionErrors,
  12712. })
  12713. return INVALID
  12714. }
  12715. }
  12716. get options() {
  12717. return this._def.options
  12718. }
  12719. }
  12720. ZodUnion.create = (types, params) =>
  12721. new ZodUnion({
  12722. options: types,
  12723. typeName: ZodFirstPartyTypeKind.ZodUnion,
  12724. ...processCreateParams(params),
  12725. })
  12726. const getDiscriminator = type =>
  12727. type instanceof ZodLazy
  12728. ? getDiscriminator(type.schema)
  12729. : type instanceof ZodEffects
  12730. ? getDiscriminator(type.innerType())
  12731. : type instanceof ZodLiteral
  12732. ? [type.value]
  12733. : type instanceof ZodEnum
  12734. ? type.options
  12735. : type instanceof ZodNativeEnum
  12736. ? Object.keys(type.enum)
  12737. : type instanceof ZodDefault
  12738. ? getDiscriminator(type._def.innerType)
  12739. : type instanceof ZodUndefined
  12740. ? [void 0]
  12741. : type instanceof ZodNull
  12742. ? [null]
  12743. : null
  12744. class ZodDiscriminatedUnion extends ZodType {
  12745. _parse(input) {
  12746. const { ctx } = this._processInputParams(input)
  12747. if (ctx.parsedType !== ZodParsedType.object) {
  12748. addIssueToContext(ctx, {
  12749. code: ZodIssueCode.invalid_type,
  12750. expected: ZodParsedType.object,
  12751. received: ctx.parsedType,
  12752. })
  12753. return INVALID
  12754. }
  12755. const discriminator = this.discriminator,
  12756. discriminatorValue = ctx.data[discriminator],
  12757. option = this.optionsMap.get(discriminatorValue)
  12758. if (!option) {
  12759. addIssueToContext(ctx, {
  12760. code: ZodIssueCode.invalid_union_discriminator,
  12761. options: Array.from(this.optionsMap.keys()),
  12762. path: [discriminator],
  12763. })
  12764. return INVALID
  12765. }
  12766. return ctx.common.async
  12767. ? option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  12768. : option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })
  12769. }
  12770. get discriminator() {
  12771. return this._def.discriminator
  12772. }
  12773. get options() {
  12774. return this._def.options
  12775. }
  12776. get optionsMap() {
  12777. return this._def.optionsMap
  12778. }
  12779. static create(discriminator, options, params) {
  12780. const optionsMap = new Map()
  12781. for (const type of options) {
  12782. const discriminatorValues = getDiscriminator(
  12783. type.shape[discriminator]
  12784. )
  12785. if (!discriminatorValues)
  12786. throw new Error(
  12787. `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`
  12788. )
  12789. for (const value of discriminatorValues) {
  12790. if (optionsMap.has(value))
  12791. throw new Error(
  12792. `Discriminator property ${String(
  12793. discriminator
  12794. )} has duplicate value ${String(value)}`
  12795. )
  12796. optionsMap.set(value, type)
  12797. }
  12798. }
  12799. return new ZodDiscriminatedUnion({
  12800. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  12801. discriminator,
  12802. options,
  12803. optionsMap,
  12804. ...processCreateParams(params),
  12805. })
  12806. }
  12807. }
  12808. function mergeValues(a, b) {
  12809. const aType = getParsedType(a),
  12810. bType = getParsedType(b)
  12811. if (a === b) return { valid: !0, data: a }
  12812. if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  12813. const bKeys = util.objectKeys(b),
  12814. sharedKeys = util
  12815. .objectKeys(a)
  12816. .filter(key => -1 !== bKeys.indexOf(key)),
  12817. newObj = { ...a, ...b }
  12818. for (const key of sharedKeys) {
  12819. const sharedValue = mergeValues(a[key], b[key])
  12820. if (!sharedValue.valid) return { valid: !1 }
  12821. newObj[key] = sharedValue.data
  12822. }
  12823. return { valid: !0, data: newObj }
  12824. }
  12825. if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  12826. if (a.length !== b.length) return { valid: !1 }
  12827. const newArray = []
  12828. for (let index = 0; index < a.length; index++) {
  12829. const sharedValue = mergeValues(a[index], b[index])
  12830. if (!sharedValue.valid) return { valid: !1 }
  12831. newArray.push(sharedValue.data)
  12832. }
  12833. return { valid: !0, data: newArray }
  12834. }
  12835. return aType === ZodParsedType.date &&
  12836. bType === ZodParsedType.date &&
  12837. +a == +b
  12838. ? { valid: !0, data: a }
  12839. : { valid: !1 }
  12840. }
  12841. class ZodIntersection extends ZodType {
  12842. _parse(input) {
  12843. const { status, ctx } = this._processInputParams(input),
  12844. handleParsed = (parsedLeft, parsedRight) => {
  12845. if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID
  12846. const merged = mergeValues(parsedLeft.value, parsedRight.value)
  12847. if (!merged.valid) {
  12848. addIssueToContext(ctx, {
  12849. code: ZodIssueCode.invalid_intersection_types,
  12850. })
  12851. return INVALID
  12852. }
  12853. ;(isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty()
  12854. return { status: status.value, value: merged.data }
  12855. }
  12856. return ctx.common.async
  12857. ? Promise.all([
  12858. this._def.left._parseAsync({
  12859. data: ctx.data,
  12860. path: ctx.path,
  12861. parent: ctx,
  12862. }),
  12863. this._def.right._parseAsync({
  12864. data: ctx.data,
  12865. path: ctx.path,
  12866. parent: ctx,
  12867. }),
  12868. ]).then(([left, right]) => handleParsed(left, right))
  12869. : handleParsed(
  12870. this._def.left._parseSync({
  12871. data: ctx.data,
  12872. path: ctx.path,
  12873. parent: ctx,
  12874. }),
  12875. this._def.right._parseSync({
  12876. data: ctx.data,
  12877. path: ctx.path,
  12878. parent: ctx,
  12879. })
  12880. )
  12881. }
  12882. }
  12883. ZodIntersection.create = (left, right, params) =>
  12884. new ZodIntersection({
  12885. left,
  12886. right,
  12887. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  12888. ...processCreateParams(params),
  12889. })
  12890. class ZodTuple extends ZodType {
  12891. _parse(input) {
  12892. const { status, ctx } = this._processInputParams(input)
  12893. if (ctx.parsedType !== ZodParsedType.array) {
  12894. addIssueToContext(ctx, {
  12895. code: ZodIssueCode.invalid_type,
  12896. expected: ZodParsedType.array,
  12897. received: ctx.parsedType,
  12898. })
  12899. return INVALID
  12900. }
  12901. if (ctx.data.length < this._def.items.length) {
  12902. addIssueToContext(ctx, {
  12903. code: ZodIssueCode.too_small,
  12904. minimum: this._def.items.length,
  12905. inclusive: !0,
  12906. exact: !1,
  12907. type: "array",
  12908. })
  12909. return INVALID
  12910. }
  12911. if (!this._def.rest && ctx.data.length > this._def.items.length) {
  12912. addIssueToContext(ctx, {
  12913. code: ZodIssueCode.too_big,
  12914. maximum: this._def.items.length,
  12915. inclusive: !0,
  12916. exact: !1,
  12917. type: "array",
  12918. })
  12919. status.dirty()
  12920. }
  12921. const items = [...ctx.data]
  12922. .map((item, itemIndex) => {
  12923. const schema = this._def.items[itemIndex] || this._def.rest
  12924. return schema
  12925. ? schema._parse(
  12926. new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)
  12927. )
  12928. : null
  12929. })
  12930. .filter(x => !!x)
  12931. return ctx.common.async
  12932. ? Promise.all(items).then(results =>
  12933. ParseStatus.mergeArray(status, results)
  12934. )
  12935. : ParseStatus.mergeArray(status, items)
  12936. }
  12937. get items() {
  12938. return this._def.items
  12939. }
  12940. rest(rest) {
  12941. return new ZodTuple({ ...this._def, rest })
  12942. }
  12943. }
  12944. ZodTuple.create = (schemas, params) => {
  12945. if (!Array.isArray(schemas))
  12946. throw new Error("You must pass an array of schemas to z.tuple([ ... ])")
  12947. return new ZodTuple({
  12948. items: schemas,
  12949. typeName: ZodFirstPartyTypeKind.ZodTuple,
  12950. rest: null,
  12951. ...processCreateParams(params),
  12952. })
  12953. }
  12954. class ZodRecord extends ZodType {
  12955. get keySchema() {
  12956. return this._def.keyType
  12957. }
  12958. get valueSchema() {
  12959. return this._def.valueType
  12960. }
  12961. _parse(input) {
  12962. const { status, ctx } = this._processInputParams(input)
  12963. if (ctx.parsedType !== ZodParsedType.object) {
  12964. addIssueToContext(ctx, {
  12965. code: ZodIssueCode.invalid_type,
  12966. expected: ZodParsedType.object,
  12967. received: ctx.parsedType,
  12968. })
  12969. return INVALID
  12970. }
  12971. const pairs = [],
  12972. keyType = this._def.keyType,
  12973. valueType = this._def.valueType
  12974. for (const key in ctx.data)
  12975. pairs.push({
  12976. key: keyType._parse(
  12977. new ParseInputLazyPath(ctx, key, ctx.path, key)
  12978. ),
  12979. value: valueType._parse(
  12980. new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
  12981. ),
  12982. })
  12983. return ctx.common.async
  12984. ? ParseStatus.mergeObjectAsync(status, pairs)
  12985. : ParseStatus.mergeObjectSync(status, pairs)
  12986. }
  12987. get element() {
  12988. return this._def.valueType
  12989. }
  12990. static create(first, second, third) {
  12991. return new ZodRecord(
  12992. second instanceof ZodType
  12993. ? {
  12994. keyType: first,
  12995. valueType: second,
  12996. typeName: ZodFirstPartyTypeKind.ZodRecord,
  12997. ...processCreateParams(third),
  12998. }
  12999. : {
  13000. keyType: ZodString.create(),
  13001. valueType: first,
  13002. typeName: ZodFirstPartyTypeKind.ZodRecord,
  13003. ...processCreateParams(second),
  13004. }
  13005. )
  13006. }
  13007. }
  13008. class ZodMap extends ZodType {
  13009. _parse(input) {
  13010. const { status, ctx } = this._processInputParams(input)
  13011. if (ctx.parsedType !== ZodParsedType.map) {
  13012. addIssueToContext(ctx, {
  13013. code: ZodIssueCode.invalid_type,
  13014. expected: ZodParsedType.map,
  13015. received: ctx.parsedType,
  13016. })
  13017. return INVALID
  13018. }
  13019. const keyType = this._def.keyType,
  13020. valueType = this._def.valueType,
  13021. pairs = [...ctx.data.entries()].map(([key, value], index) => ({
  13022. key: keyType._parse(
  13023. new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])
  13024. ),
  13025. value: valueType._parse(
  13026. new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])
  13027. ),
  13028. }))
  13029. if (ctx.common.async) {
  13030. const finalMap = new Map()
  13031. return Promise.resolve().then(async () => {
  13032. for (const pair of pairs) {
  13033. const key = await pair.key,
  13034. value = await pair.value
  13035. if ("aborted" === key.status || "aborted" === value.status)
  13036. return INVALID
  13037. ;("dirty" !== key.status && "dirty" !== value.status) ||
  13038. status.dirty()
  13039. finalMap.set(key.value, value.value)
  13040. }
  13041. return { status: status.value, value: finalMap }
  13042. })
  13043. }
  13044. {
  13045. const finalMap = new Map()
  13046. for (const pair of pairs) {
  13047. const key = pair.key,
  13048. value = pair.value
  13049. if ("aborted" === key.status || "aborted" === value.status)
  13050. return INVALID
  13051. ;("dirty" !== key.status && "dirty" !== value.status) ||
  13052. status.dirty()
  13053. finalMap.set(key.value, value.value)
  13054. }
  13055. return { status: status.value, value: finalMap }
  13056. }
  13057. }
  13058. }
  13059. ZodMap.create = (keyType, valueType, params) =>
  13060. new ZodMap({
  13061. valueType,
  13062. keyType,
  13063. typeName: ZodFirstPartyTypeKind.ZodMap,
  13064. ...processCreateParams(params),
  13065. })
  13066. class ZodSet extends ZodType {
  13067. _parse(input) {
  13068. const { status, ctx } = this._processInputParams(input)
  13069. if (ctx.parsedType !== ZodParsedType.set) {
  13070. addIssueToContext(ctx, {
  13071. code: ZodIssueCode.invalid_type,
  13072. expected: ZodParsedType.set,
  13073. received: ctx.parsedType,
  13074. })
  13075. return INVALID
  13076. }
  13077. const def = this._def
  13078. if (null !== def.minSize && ctx.data.size < def.minSize.value) {
  13079. addIssueToContext(ctx, {
  13080. code: ZodIssueCode.too_small,
  13081. minimum: def.minSize.value,
  13082. type: "set",
  13083. inclusive: !0,
  13084. exact: !1,
  13085. message: def.minSize.message,
  13086. })
  13087. status.dirty()
  13088. }
  13089. if (null !== def.maxSize && ctx.data.size > def.maxSize.value) {
  13090. addIssueToContext(ctx, {
  13091. code: ZodIssueCode.too_big,
  13092. maximum: def.maxSize.value,
  13093. type: "set",
  13094. inclusive: !0,
  13095. exact: !1,
  13096. message: def.maxSize.message,
  13097. })
  13098. status.dirty()
  13099. }
  13100. const valueType = this._def.valueType
  13101. function finalizeSet(elements) {
  13102. const parsedSet = new Set()
  13103. for (const element of elements) {
  13104. if ("aborted" === element.status) return INVALID
  13105. "dirty" === element.status && status.dirty()
  13106. parsedSet.add(element.value)
  13107. }
  13108. return { status: status.value, value: parsedSet }
  13109. }
  13110. const elements = [...ctx.data.values()].map((item, i) =>
  13111. valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))
  13112. )
  13113. return ctx.common.async
  13114. ? Promise.all(elements).then(elements => finalizeSet(elements))
  13115. : finalizeSet(elements)
  13116. }
  13117. min(minSize, message) {
  13118. return new ZodSet({
  13119. ...this._def,
  13120. minSize: { value: minSize, message: errorUtil.toString(message) },
  13121. })
  13122. }
  13123. max(maxSize, message) {
  13124. return new ZodSet({
  13125. ...this._def,
  13126. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  13127. })
  13128. }
  13129. size(size, message) {
  13130. return this.min(size, message).max(size, message)
  13131. }
  13132. nonempty(message) {
  13133. return this.min(1, message)
  13134. }
  13135. }
  13136. ZodSet.create = (valueType, params) =>
  13137. new ZodSet({
  13138. valueType,
  13139. minSize: null,
  13140. maxSize: null,
  13141. typeName: ZodFirstPartyTypeKind.ZodSet,
  13142. ...processCreateParams(params),
  13143. })
  13144. class ZodFunction extends ZodType {
  13145. constructor() {
  13146. super(...arguments)
  13147. this.validate = this.implement
  13148. }
  13149. _parse(input) {
  13150. const { ctx } = this._processInputParams(input)
  13151. if (ctx.parsedType !== ZodParsedType.function) {
  13152. addIssueToContext(ctx, {
  13153. code: ZodIssueCode.invalid_type,
  13154. expected: ZodParsedType.function,
  13155. received: ctx.parsedType,
  13156. })
  13157. return INVALID
  13158. }
  13159. function makeArgsIssue(args, error) {
  13160. return makeIssue({
  13161. data: args,
  13162. path: ctx.path,
  13163. errorMaps: [
  13164. ctx.common.contextualErrorMap,
  13165. ctx.schemaErrorMap,
  13166. getErrorMap(),
  13167. errorMap,
  13168. ].filter(x => !!x),
  13169. issueData: {
  13170. code: ZodIssueCode.invalid_arguments,
  13171. argumentsError: error,
  13172. },
  13173. })
  13174. }
  13175. function makeReturnsIssue(returns, error) {
  13176. return makeIssue({
  13177. data: returns,
  13178. path: ctx.path,
  13179. errorMaps: [
  13180. ctx.common.contextualErrorMap,
  13181. ctx.schemaErrorMap,
  13182. getErrorMap(),
  13183. errorMap,
  13184. ].filter(x => !!x),
  13185. issueData: {
  13186. code: ZodIssueCode.invalid_return_type,
  13187. returnTypeError: error,
  13188. },
  13189. })
  13190. }
  13191. const params = { errorMap: ctx.common.contextualErrorMap },
  13192. fn = ctx.data
  13193. return this._def.returns instanceof ZodPromise
  13194. ? OK(async (...args) => {
  13195. const error = new ZodError([]),
  13196. parsedArgs = await this._def.args
  13197. .parseAsync(args, params)
  13198. .catch(e => {
  13199. error.addIssue(makeArgsIssue(args, e))
  13200. throw error
  13201. }),
  13202. result = await fn(...parsedArgs)
  13203. return await this._def.returns._def.type
  13204. .parseAsync(result, params)
  13205. .catch(e => {
  13206. error.addIssue(makeReturnsIssue(result, e))
  13207. throw error
  13208. })
  13209. })
  13210. : OK((...args) => {
  13211. const parsedArgs = this._def.args.safeParse(args, params)
  13212. if (!parsedArgs.success)
  13213. throw new ZodError([makeArgsIssue(args, parsedArgs.error)])
  13214. const result = fn(...parsedArgs.data),
  13215. parsedReturns = this._def.returns.safeParse(result, params)
  13216. if (!parsedReturns.success)
  13217. throw new ZodError([
  13218. makeReturnsIssue(result, parsedReturns.error),
  13219. ])
  13220. return parsedReturns.data
  13221. })
  13222. }
  13223. parameters() {
  13224. return this._def.args
  13225. }
  13226. returnType() {
  13227. return this._def.returns
  13228. }
  13229. args(...items) {
  13230. return new ZodFunction({
  13231. ...this._def,
  13232. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  13233. })
  13234. }
  13235. returns(returnType) {
  13236. return new ZodFunction({ ...this._def, returns: returnType })
  13237. }
  13238. implement(func) {
  13239. return this.parse(func)
  13240. }
  13241. strictImplement(func) {
  13242. return this.parse(func)
  13243. }
  13244. static create(args, returns, params) {
  13245. return new ZodFunction({
  13246. args: args || ZodTuple.create([]).rest(ZodUnknown.create()),
  13247. returns: returns || ZodUnknown.create(),
  13248. typeName: ZodFirstPartyTypeKind.ZodFunction,
  13249. ...processCreateParams(params),
  13250. })
  13251. }
  13252. }
  13253. class ZodLazy extends ZodType {
  13254. get schema() {
  13255. return this._def.getter()
  13256. }
  13257. _parse(input) {
  13258. const { ctx } = this._processInputParams(input)
  13259. return this._def
  13260. .getter()
  13261. ._parse({ data: ctx.data, path: ctx.path, parent: ctx })
  13262. }
  13263. }
  13264. ZodLazy.create = (getter, params) =>
  13265. new ZodLazy({
  13266. getter,
  13267. typeName: ZodFirstPartyTypeKind.ZodLazy,
  13268. ...processCreateParams(params),
  13269. })
  13270. class ZodLiteral extends ZodType {
  13271. _parse(input) {
  13272. if (input.data !== this._def.value) {
  13273. const ctx = this._getOrReturnCtx(input)
  13274. addIssueToContext(ctx, {
  13275. received: ctx.data,
  13276. code: ZodIssueCode.invalid_literal,
  13277. expected: this._def.value,
  13278. })
  13279. return INVALID
  13280. }
  13281. return { status: "valid", value: input.data }
  13282. }
  13283. get value() {
  13284. return this._def.value
  13285. }
  13286. }
  13287. ZodLiteral.create = (value, params) =>
  13288. new ZodLiteral({
  13289. value,
  13290. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  13291. ...processCreateParams(params),
  13292. })
  13293. function createZodEnum(values, params) {
  13294. return new ZodEnum({
  13295. values,
  13296. typeName: ZodFirstPartyTypeKind.ZodEnum,
  13297. ...processCreateParams(params),
  13298. })
  13299. }
  13300. class ZodEnum extends ZodType {
  13301. _parse(input) {
  13302. if ("string" != typeof input.data) {
  13303. const ctx = this._getOrReturnCtx(input),
  13304. expectedValues = this._def.values
  13305. addIssueToContext(ctx, {
  13306. expected: util.joinValues(expectedValues),
  13307. received: ctx.parsedType,
  13308. code: ZodIssueCode.invalid_type,
  13309. })
  13310. return INVALID
  13311. }
  13312. if (-1 === this._def.values.indexOf(input.data)) {
  13313. const ctx = this._getOrReturnCtx(input),
  13314. expectedValues = this._def.values
  13315. addIssueToContext(ctx, {
  13316. received: ctx.data,
  13317. code: ZodIssueCode.invalid_enum_value,
  13318. options: expectedValues,
  13319. })
  13320. return INVALID
  13321. }
  13322. return OK(input.data)
  13323. }
  13324. get options() {
  13325. return this._def.values
  13326. }
  13327. get enum() {
  13328. const enumValues = {}
  13329. for (const val of this._def.values) enumValues[val] = val
  13330. return enumValues
  13331. }
  13332. get Values() {
  13333. const enumValues = {}
  13334. for (const val of this._def.values) enumValues[val] = val
  13335. return enumValues
  13336. }
  13337. get Enum() {
  13338. const enumValues = {}
  13339. for (const val of this._def.values) enumValues[val] = val
  13340. return enumValues
  13341. }
  13342. extract(values) {
  13343. return ZodEnum.create(values)
  13344. }
  13345. exclude(values) {
  13346. return ZodEnum.create(this.options.filter(opt => !values.includes(opt)))
  13347. }
  13348. }
  13349. ZodEnum.create = createZodEnum
  13350. class ZodNativeEnum extends ZodType {
  13351. _parse(input) {
  13352. const nativeEnumValues = util.getValidEnumValues(this._def.values),
  13353. ctx = this._getOrReturnCtx(input)
  13354. if (
  13355. ctx.parsedType !== ZodParsedType.string &&
  13356. ctx.parsedType !== ZodParsedType.number
  13357. ) {
  13358. const expectedValues = util.objectValues(nativeEnumValues)
  13359. addIssueToContext(ctx, {
  13360. expected: util.joinValues(expectedValues),
  13361. received: ctx.parsedType,
  13362. code: ZodIssueCode.invalid_type,
  13363. })
  13364. return INVALID
  13365. }
  13366. if (-1 === nativeEnumValues.indexOf(input.data)) {
  13367. const expectedValues = util.objectValues(nativeEnumValues)
  13368. addIssueToContext(ctx, {
  13369. received: ctx.data,
  13370. code: ZodIssueCode.invalid_enum_value,
  13371. options: expectedValues,
  13372. })
  13373. return INVALID
  13374. }
  13375. return OK(input.data)
  13376. }
  13377. get enum() {
  13378. return this._def.values
  13379. }
  13380. }
  13381. ZodNativeEnum.create = (values, params) =>
  13382. new ZodNativeEnum({
  13383. values,
  13384. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  13385. ...processCreateParams(params),
  13386. })
  13387. class ZodPromise extends ZodType {
  13388. unwrap() {
  13389. return this._def.type
  13390. }
  13391. _parse(input) {
  13392. const { ctx } = this._processInputParams(input)
  13393. if (
  13394. ctx.parsedType !== ZodParsedType.promise &&
  13395. !1 === ctx.common.async
  13396. ) {
  13397. addIssueToContext(ctx, {
  13398. code: ZodIssueCode.invalid_type,
  13399. expected: ZodParsedType.promise,
  13400. received: ctx.parsedType,
  13401. })
  13402. return INVALID
  13403. }
  13404. const promisified =
  13405. ctx.parsedType === ZodParsedType.promise
  13406. ? ctx.data
  13407. : Promise.resolve(ctx.data)
  13408. return OK(
  13409. promisified.then(data =>
  13410. this._def.type.parseAsync(data, {
  13411. path: ctx.path,
  13412. errorMap: ctx.common.contextualErrorMap,
  13413. })
  13414. )
  13415. )
  13416. }
  13417. }
  13418. ZodPromise.create = (schema, params) =>
  13419. new ZodPromise({
  13420. type: schema,
  13421. typeName: ZodFirstPartyTypeKind.ZodPromise,
  13422. ...processCreateParams(params),
  13423. })
  13424. class ZodEffects extends ZodType {
  13425. innerType() {
  13426. return this._def.schema
  13427. }
  13428. sourceType() {
  13429. return this._def.schema._def.typeName ===
  13430. ZodFirstPartyTypeKind.ZodEffects
  13431. ? this._def.schema.sourceType()
  13432. : this._def.schema
  13433. }
  13434. _parse(input) {
  13435. const { status, ctx } = this._processInputParams(input),
  13436. effect = this._def.effect || null
  13437. if ("preprocess" === effect.type) {
  13438. const processed = effect.transform(ctx.data)
  13439. return ctx.common.async
  13440. ? Promise.resolve(processed).then(processed =>
  13441. this._def.schema._parseAsync({
  13442. data: processed,
  13443. path: ctx.path,
  13444. parent: ctx,
  13445. })
  13446. )
  13447. : this._def.schema._parseSync({
  13448. data: processed,
  13449. path: ctx.path,
  13450. parent: ctx,
  13451. })
  13452. }
  13453. const checkCtx = {
  13454. addIssue: arg => {
  13455. addIssueToContext(ctx, arg)
  13456. arg.fatal ? status.abort() : status.dirty()
  13457. },
  13458. get path() {
  13459. return ctx.path
  13460. },
  13461. }
  13462. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx)
  13463. if ("refinement" === effect.type) {
  13464. const executeRefinement = acc => {
  13465. const result = effect.refinement(acc, checkCtx)
  13466. if (ctx.common.async) return Promise.resolve(result)
  13467. if (result instanceof Promise)
  13468. throw new Error(
  13469. "Async refinement encountered during synchronous parse operation. Use .parseAsync instead."
  13470. )
  13471. return acc
  13472. }
  13473. if (!1 === ctx.common.async) {
  13474. const inner = this._def.schema._parseSync({
  13475. data: ctx.data,
  13476. path: ctx.path,
  13477. parent: ctx,
  13478. })
  13479. if ("aborted" === inner.status) return INVALID
  13480. "dirty" === inner.status && status.dirty()
  13481. executeRefinement(inner.value)
  13482. return { status: status.value, value: inner.value }
  13483. }
  13484. return this._def.schema
  13485. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  13486. .then(inner => {
  13487. if ("aborted" === inner.status) return INVALID
  13488. "dirty" === inner.status && status.dirty()
  13489. return executeRefinement(inner.value).then(() => ({
  13490. status: status.value,
  13491. value: inner.value,
  13492. }))
  13493. })
  13494. }
  13495. if ("transform" === effect.type) {
  13496. if (!1 === ctx.common.async) {
  13497. const base = this._def.schema._parseSync({
  13498. data: ctx.data,
  13499. path: ctx.path,
  13500. parent: ctx,
  13501. })
  13502. if (!isValid(base)) return base
  13503. const result = effect.transform(base.value, checkCtx)
  13504. if (result instanceof Promise)
  13505. throw new Error(
  13506. "Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."
  13507. )
  13508. return { status: status.value, value: result }
  13509. }
  13510. return this._def.schema
  13511. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  13512. .then(base =>
  13513. isValid(base)
  13514. ? Promise.resolve(effect.transform(base.value, checkCtx)).then(
  13515. result => ({ status: status.value, value: result })
  13516. )
  13517. : base
  13518. )
  13519. }
  13520. util.assertNever(effect)
  13521. }
  13522. }
  13523. ZodEffects.create = (schema, effect, params) =>
  13524. new ZodEffects({
  13525. schema,
  13526. typeName: ZodFirstPartyTypeKind.ZodEffects,
  13527. effect,
  13528. ...processCreateParams(params),
  13529. })
  13530. ZodEffects.createWithPreprocess = (preprocess, schema, params) =>
  13531. new ZodEffects({
  13532. schema,
  13533. effect: { type: "preprocess", transform: preprocess },
  13534. typeName: ZodFirstPartyTypeKind.ZodEffects,
  13535. ...processCreateParams(params),
  13536. })
  13537. class ZodOptional extends ZodType {
  13538. _parse(input) {
  13539. return this._getType(input) === ZodParsedType.undefined
  13540. ? OK(void 0)
  13541. : this._def.innerType._parse(input)
  13542. }
  13543. unwrap() {
  13544. return this._def.innerType
  13545. }
  13546. }
  13547. ZodOptional.create = (type, params) =>
  13548. new ZodOptional({
  13549. innerType: type,
  13550. typeName: ZodFirstPartyTypeKind.ZodOptional,
  13551. ...processCreateParams(params),
  13552. })
  13553. class ZodNullable extends ZodType {
  13554. _parse(input) {
  13555. return this._getType(input) === ZodParsedType.null
  13556. ? OK(null)
  13557. : this._def.innerType._parse(input)
  13558. }
  13559. unwrap() {
  13560. return this._def.innerType
  13561. }
  13562. }
  13563. ZodNullable.create = (type, params) =>
  13564. new ZodNullable({
  13565. innerType: type,
  13566. typeName: ZodFirstPartyTypeKind.ZodNullable,
  13567. ...processCreateParams(params),
  13568. })
  13569. class ZodDefault extends ZodType {
  13570. _parse(input) {
  13571. const { ctx } = this._processInputParams(input)
  13572. let data = ctx.data
  13573. ctx.parsedType === ZodParsedType.undefined &&
  13574. (data = this._def.defaultValue())
  13575. return this._def.innerType._parse({ data, path: ctx.path, parent: ctx })
  13576. }
  13577. removeDefault() {
  13578. return this._def.innerType
  13579. }
  13580. }
  13581. ZodDefault.create = (type, params) =>
  13582. new ZodDefault({
  13583. innerType: type,
  13584. typeName: ZodFirstPartyTypeKind.ZodDefault,
  13585. defaultValue:
  13586. "function" == typeof params.default
  13587. ? params.default
  13588. : () => params.default,
  13589. ...processCreateParams(params),
  13590. })
  13591. class ZodCatch extends ZodType {
  13592. _parse(input) {
  13593. const { ctx } = this._processInputParams(input),
  13594. newCtx = { ...ctx, common: { ...ctx.common, issues: [] } },
  13595. result = this._def.innerType._parse({
  13596. data: newCtx.data,
  13597. path: newCtx.path,
  13598. parent: { ...newCtx },
  13599. })
  13600. return isAsync(result)
  13601. ? result.then(result => ({
  13602. status: "valid",
  13603. value:
  13604. "valid" === result.status
  13605. ? result.value
  13606. : this._def.catchValue({
  13607. get error() {
  13608. return new ZodError(newCtx.common.issues)
  13609. },
  13610. input: newCtx.data,
  13611. }),
  13612. }))
  13613. : {
  13614. status: "valid",
  13615. value:
  13616. "valid" === result.status
  13617. ? result.value
  13618. : this._def.catchValue({
  13619. get error() {
  13620. return new ZodError(newCtx.common.issues)
  13621. },
  13622. input: newCtx.data,
  13623. }),
  13624. }
  13625. }
  13626. removeCatch() {
  13627. return this._def.innerType
  13628. }
  13629. }
  13630. ZodCatch.create = (type, params) =>
  13631. new ZodCatch({
  13632. innerType: type,
  13633. typeName: ZodFirstPartyTypeKind.ZodCatch,
  13634. catchValue:
  13635. "function" == typeof params.catch ? params.catch : () => params.catch,
  13636. ...processCreateParams(params),
  13637. })
  13638. class ZodNaN extends ZodType {
  13639. _parse(input) {
  13640. if (this._getType(input) !== ZodParsedType.nan) {
  13641. const ctx = this._getOrReturnCtx(input)
  13642. addIssueToContext(ctx, {
  13643. code: ZodIssueCode.invalid_type,
  13644. expected: ZodParsedType.nan,
  13645. received: ctx.parsedType,
  13646. })
  13647. return INVALID
  13648. }
  13649. return { status: "valid", value: input.data }
  13650. }
  13651. }
  13652. ZodNaN.create = params =>
  13653. new ZodNaN({
  13654. typeName: ZodFirstPartyTypeKind.ZodNaN,
  13655. ...processCreateParams(params),
  13656. })
  13657. const BRAND = Symbol("zod_brand")
  13658. class ZodBranded extends ZodType {
  13659. _parse(input) {
  13660. const { ctx } = this._processInputParams(input),
  13661. data = ctx.data
  13662. return this._def.type._parse({ data, path: ctx.path, parent: ctx })
  13663. }
  13664. unwrap() {
  13665. return this._def.type
  13666. }
  13667. }
  13668. class ZodPipeline extends ZodType {
  13669. _parse(input) {
  13670. const { status, ctx } = this._processInputParams(input)
  13671. if (ctx.common.async)
  13672. return (async () => {
  13673. const inResult = await this._def.in._parseAsync({
  13674. data: ctx.data,
  13675. path: ctx.path,
  13676. parent: ctx,
  13677. })
  13678. if ("aborted" === inResult.status) return INVALID
  13679. if ("dirty" === inResult.status) {
  13680. status.dirty()
  13681. return DIRTY(inResult.value)
  13682. }
  13683. return this._def.out._parseAsync({
  13684. data: inResult.value,
  13685. path: ctx.path,
  13686. parent: ctx,
  13687. })
  13688. })()
  13689. {
  13690. const inResult = this._def.in._parseSync({
  13691. data: ctx.data,
  13692. path: ctx.path,
  13693. parent: ctx,
  13694. })
  13695. if ("aborted" === inResult.status) return INVALID
  13696. if ("dirty" === inResult.status) {
  13697. status.dirty()
  13698. return { status: "dirty", value: inResult.value }
  13699. }
  13700. return this._def.out._parseSync({
  13701. data: inResult.value,
  13702. path: ctx.path,
  13703. parent: ctx,
  13704. })
  13705. }
  13706. }
  13707. static create(a, b) {
  13708. return new ZodPipeline({
  13709. in: a,
  13710. out: b,
  13711. typeName: ZodFirstPartyTypeKind.ZodPipeline,
  13712. })
  13713. }
  13714. }
  13715. const custom = (check, params = {}, fatal) =>
  13716. check
  13717. ? ZodAny.create().superRefine((data, ctx) => {
  13718. var _a, _b
  13719. if (!check(data)) {
  13720. const p =
  13721. "function" == typeof params
  13722. ? params(data)
  13723. : "string" == typeof params
  13724. ? { message: params }
  13725. : params,
  13726. _fatal =
  13727. null ===
  13728. (_b =
  13729. null !== (_a = p.fatal) && void 0 !== _a
  13730. ? _a
  13731. : fatal) ||
  13732. void 0 === _b ||
  13733. _b,
  13734. p2 = "string" == typeof p ? { message: p } : p
  13735. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal })
  13736. }
  13737. })
  13738. : ZodAny.create(),
  13739. late = { object: ZodObject.lazycreate }
  13740. var ZodFirstPartyTypeKind
  13741. !(function (ZodFirstPartyTypeKind) {
  13742. ZodFirstPartyTypeKind.ZodString = "ZodString"
  13743. ZodFirstPartyTypeKind.ZodNumber = "ZodNumber"
  13744. ZodFirstPartyTypeKind.ZodNaN = "ZodNaN"
  13745. ZodFirstPartyTypeKind.ZodBigInt = "ZodBigInt"
  13746. ZodFirstPartyTypeKind.ZodBoolean = "ZodBoolean"
  13747. ZodFirstPartyTypeKind.ZodDate = "ZodDate"
  13748. ZodFirstPartyTypeKind.ZodSymbol = "ZodSymbol"
  13749. ZodFirstPartyTypeKind.ZodUndefined = "ZodUndefined"
  13750. ZodFirstPartyTypeKind.ZodNull = "ZodNull"
  13751. ZodFirstPartyTypeKind.ZodAny = "ZodAny"
  13752. ZodFirstPartyTypeKind.ZodUnknown = "ZodUnknown"
  13753. ZodFirstPartyTypeKind.ZodNever = "ZodNever"
  13754. ZodFirstPartyTypeKind.ZodVoid = "ZodVoid"
  13755. ZodFirstPartyTypeKind.ZodArray = "ZodArray"
  13756. ZodFirstPartyTypeKind.ZodObject = "ZodObject"
  13757. ZodFirstPartyTypeKind.ZodUnion = "ZodUnion"
  13758. ZodFirstPartyTypeKind.ZodDiscriminatedUnion = "ZodDiscriminatedUnion"
  13759. ZodFirstPartyTypeKind.ZodIntersection = "ZodIntersection"
  13760. ZodFirstPartyTypeKind.ZodTuple = "ZodTuple"
  13761. ZodFirstPartyTypeKind.ZodRecord = "ZodRecord"
  13762. ZodFirstPartyTypeKind.ZodMap = "ZodMap"
  13763. ZodFirstPartyTypeKind.ZodSet = "ZodSet"
  13764. ZodFirstPartyTypeKind.ZodFunction = "ZodFunction"
  13765. ZodFirstPartyTypeKind.ZodLazy = "ZodLazy"
  13766. ZodFirstPartyTypeKind.ZodLiteral = "ZodLiteral"
  13767. ZodFirstPartyTypeKind.ZodEnum = "ZodEnum"
  13768. ZodFirstPartyTypeKind.ZodEffects = "ZodEffects"
  13769. ZodFirstPartyTypeKind.ZodNativeEnum = "ZodNativeEnum"
  13770. ZodFirstPartyTypeKind.ZodOptional = "ZodOptional"
  13771. ZodFirstPartyTypeKind.ZodNullable = "ZodNullable"
  13772. ZodFirstPartyTypeKind.ZodDefault = "ZodDefault"
  13773. ZodFirstPartyTypeKind.ZodCatch = "ZodCatch"
  13774. ZodFirstPartyTypeKind.ZodPromise = "ZodPromise"
  13775. ZodFirstPartyTypeKind.ZodBranded = "ZodBranded"
  13776. ZodFirstPartyTypeKind.ZodPipeline = "ZodPipeline"
  13777. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}))
  13778. const stringType = ZodString.create,
  13779. numberType = ZodNumber.create,
  13780. nanType = ZodNaN.create,
  13781. bigIntType = ZodBigInt.create,
  13782. booleanType = ZodBoolean.create,
  13783. dateType = ZodDate.create,
  13784. symbolType = ZodSymbol.create,
  13785. undefinedType = ZodUndefined.create,
  13786. nullType = ZodNull.create,
  13787. anyType = ZodAny.create,
  13788. unknownType = ZodUnknown.create,
  13789. neverType = ZodNever.create,
  13790. voidType = ZodVoid.create,
  13791. arrayType = ZodArray.create,
  13792. objectType = ZodObject.create,
  13793. strictObjectType = ZodObject.strictCreate,
  13794. unionType = ZodUnion.create,
  13795. discriminatedUnionType = ZodDiscriminatedUnion.create,
  13796. intersectionType = ZodIntersection.create,
  13797. tupleType = ZodTuple.create,
  13798. recordType = ZodRecord.create,
  13799. lib_mapType = ZodMap.create,
  13800. setType = ZodSet.create,
  13801. functionType = ZodFunction.create,
  13802. lazyType = ZodLazy.create,
  13803. literalType = ZodLiteral.create,
  13804. enumType = ZodEnum.create,
  13805. nativeEnumType = ZodNativeEnum.create,
  13806. promiseType = ZodPromise.create,
  13807. effectsType = ZodEffects.create,
  13808. optionalType = ZodOptional.create,
  13809. nullableType = ZodNullable.create,
  13810. preprocessType = ZodEffects.createWithPreprocess,
  13811. pipelineType = ZodPipeline.create,
  13812. coerce = {
  13813. string: arg => ZodString.create({ ...arg, coerce: !0 }),
  13814. number: arg => ZodNumber.create({ ...arg, coerce: !0 }),
  13815. boolean: arg => ZodBoolean.create({ ...arg, coerce: !0 }),
  13816. bigint: arg => ZodBigInt.create({ ...arg, coerce: !0 }),
  13817. date: arg => ZodDate.create({ ...arg, coerce: !0 }),
  13818. },
  13819. NEVER = INVALID
  13820. var z = Object.freeze({
  13821. __proto__: null,
  13822. defaultErrorMap: errorMap,
  13823. setErrorMap: function (map) {
  13824. overrideErrorMap = map
  13825. },
  13826. getErrorMap,
  13827. makeIssue,
  13828. EMPTY_PATH: [],
  13829. addIssueToContext,
  13830. ParseStatus,
  13831. INVALID,
  13832. DIRTY,
  13833. OK,
  13834. isAborted,
  13835. isDirty,
  13836. isValid,
  13837. isAsync,
  13838. get util() {
  13839. return util
  13840. },
  13841. get objectUtil() {
  13842. return objectUtil
  13843. },
  13844. ZodParsedType,
  13845. getParsedType,
  13846. ZodType,
  13847. ZodString,
  13848. ZodNumber,
  13849. ZodBigInt,
  13850. ZodBoolean,
  13851. ZodDate,
  13852. ZodSymbol,
  13853. ZodUndefined,
  13854. ZodNull,
  13855. ZodAny,
  13856. ZodUnknown,
  13857. ZodNever,
  13858. ZodVoid,
  13859. ZodArray,
  13860. ZodObject,
  13861. ZodUnion,
  13862. ZodDiscriminatedUnion,
  13863. ZodIntersection,
  13864. ZodTuple,
  13865. ZodRecord,
  13866. ZodMap,
  13867. ZodSet,
  13868. ZodFunction,
  13869. ZodLazy,
  13870. ZodLiteral,
  13871. ZodEnum,
  13872. ZodNativeEnum,
  13873. ZodPromise,
  13874. ZodEffects,
  13875. ZodTransformer: ZodEffects,
  13876. ZodOptional,
  13877. ZodNullable,
  13878. ZodDefault,
  13879. ZodCatch,
  13880. ZodNaN,
  13881. BRAND,
  13882. ZodBranded,
  13883. ZodPipeline,
  13884. custom,
  13885. Schema: ZodType,
  13886. ZodSchema: ZodType,
  13887. late,
  13888. get ZodFirstPartyTypeKind() {
  13889. return ZodFirstPartyTypeKind
  13890. },
  13891. coerce,
  13892. any: anyType,
  13893. array: arrayType,
  13894. bigint: bigIntType,
  13895. boolean: booleanType,
  13896. date: dateType,
  13897. discriminatedUnion: discriminatedUnionType,
  13898. effect: effectsType,
  13899. enum: enumType,
  13900. function: functionType,
  13901. instanceof: (
  13902. cls,
  13903. params = { message: `Input not instance of ${cls.name}` }
  13904. ) => custom(data => data instanceof cls, params),
  13905. intersection: intersectionType,
  13906. lazy: lazyType,
  13907. literal: literalType,
  13908. map: lib_mapType,
  13909. nan: nanType,
  13910. nativeEnum: nativeEnumType,
  13911. never: neverType,
  13912. null: nullType,
  13913. nullable: nullableType,
  13914. number: numberType,
  13915. object: objectType,
  13916. oboolean: () => booleanType().optional(),
  13917. onumber: () => numberType().optional(),
  13918. optional: optionalType,
  13919. ostring: () => stringType().optional(),
  13920. pipeline: pipelineType,
  13921. preprocess: preprocessType,
  13922. promise: promiseType,
  13923. record: recordType,
  13924. set: setType,
  13925. strictObject: strictObjectType,
  13926. string: stringType,
  13927. symbol: symbolType,
  13928. transformer: effectsType,
  13929. tuple: tupleType,
  13930. undefined: undefinedType,
  13931. union: unionType,
  13932. unknown: unknownType,
  13933. void: voidType,
  13934. NEVER,
  13935. ZodIssueCode,
  13936. quotelessJson: obj =>
  13937. JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"),
  13938. ZodError,
  13939. })
  13940. const checkboxNode = label => c => s => {
  13941. return ((label, checked, onchange) =>
  13942. h(
  13943. "div",
  13944. {},
  13945. h("label", {}, [
  13946. hyperapp_text(label),
  13947. h("input", { type: "checkbox", checked, onchange }),
  13948. ])
  13949. ))(
  13950. getText(label)(s.lang),
  13951. getState(label)(s),
  13952. ((key = label),
  13953. src_flip((s, e) =>
  13954. pipe(
  13955. (e =>
  13956. z.instanceof(HTMLInputElement).parse(e.currentTarget).checked)(
  13957. e
  13958. ),
  13959. updateAt(key),
  13960. src_flip,
  13961. apply(s)
  13962. )
  13963. ))(c)
  13964. )
  13965. var key
  13966. },
  13967. mapSettingNodes = f => xs => c => s =>
  13968. pipe(
  13969. xs,
  13970. ReadonlyArray_map(x => x(c)(s)),
  13971. f
  13972. ),
  13973. updateInput = setter => key =>
  13974. src_flip((s, e) =>
  13975. pipe(
  13976. (e => {
  13977. const target = e.currentTarget ?? e.__target
  13978. if (
  13979. target instanceof HTMLSelectElement ||
  13980. target instanceof HTMLTextAreaElement ||
  13981. target instanceof HTMLInputElement
  13982. )
  13983. return target.value
  13984. throw Error("Event target type isn't acceptable.")
  13985. })(e),
  13986. setter,
  13987. apply(getState(key)(s)),
  13988. updateAt(key),
  13989. src_flip,
  13990. apply(s)
  13991. )
  13992. ),
  13993. editAction = (key, setter) => c => ({
  13994. oninput: (s, e) => updateInput(setter(!0))(key)(c)(s, e),
  13995. onchange: (s, e) => updateInput(setter(!1))(key)(c)(s, e),
  13996. }),
  13997. setEditNumber = editing => value => state =>
  13998. pipe(
  13999. value,
  14000. Number.parseFloat,
  14001. editing
  14002. ? x =>
  14003. Number.isNaN(x) || "." === value.at(-1)
  14004. ? pipe(state, setText(value))
  14005. : fromValueText(x)(value)
  14006. : x =>
  14007. Number.isNaN(x)
  14008. ? pipe(
  14009. state,
  14010. mapSecond(constant(Option_some([value, Option_some("")])))
  14011. )
  14012. : Editable_of(x)
  14013. ),
  14014. errorText = subject => edit =>
  14015. pipe(
  14016. edit,
  14017. error,
  14018. Option_map(x => `${subject}${"" === x ? "" : ": "}${x}`),
  14019. getOrElse(constant(""))
  14020. ),
  14021. rangeRow = (min, max, step, action) => value =>
  14022. h("div", {}, [
  14023. h("input", {
  14024. style: { width: "150px", verticalAlign: "middle" },
  14025. type: "range",
  14026. min,
  14027. max,
  14028. step,
  14029. value: Editable_value(value).toString(),
  14030. oninput: action.onchange,
  14031. }),
  14032. h("input", {
  14033. style: {
  14034. width: "30px",
  14035. backgroundColor: "transparent",
  14036. color: "inherit",
  14037. borderWidth: "1px",
  14038. verticalAlign: "middle",
  14039. borderColor: hasError(value) ? "#f55" : void 0,
  14040. },
  14041. inputmode: "decimal",
  14042. value: pipe(
  14043. value,
  14044. Editable_text,
  14045. getOrElse(
  14046. constant(
  14047. Editable_value(value)
  14048. .toFixed(4)
  14049. .replace(/\.?0+$/, "")
  14050. )
  14051. )
  14052. ),
  14053. ...action,
  14054. }),
  14055. ]),
  14056. settingRow = (label, error, content) =>
  14057. h("div", {}, [
  14058. h("span", {}, hyperapp_text(label)),
  14059. h(
  14060. "span",
  14061. {
  14062. style: {
  14063. color: "#f55",
  14064. marginLeft: "5px",
  14065. whiteSpace: "pre-wrap",
  14066. },
  14067. },
  14068. hyperapp_text(error)
  14069. ),
  14070. h("div", {}, content),
  14071. ]),
  14072. numberNode = (label, min, max, step) => c => s =>
  14073. settingRow(
  14074. getText(label)(s.lang),
  14075. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  14076. [
  14077. rangeRow(
  14078. min,
  14079. max,
  14080. step,
  14081. editAction(label, setEditNumber)(c)
  14082. )(getState(label)(s)),
  14083. ]
  14084. ),
  14085. panelBoxStyle = width => ({ flex: `0 0 ${width}px`, margin: "2px" }),
  14086. settingUI_chatFieldPanel = pipe(
  14087. [
  14088. pipe(
  14089. [
  14090. numberNode("fieldScale", 0.7, 1.5, 0.05),
  14091. checkboxNode("simplifyChatField"),
  14092. checkboxNode("createBanButton"),
  14093. ],
  14094. mapSettingNodes(x => h("div", { style: panelBoxStyle(644) }, x))
  14095. ),
  14096. ],
  14097. mapSettingNodes(Function_identity)
  14098. ),
  14099. action = {
  14100. copy: () => s =>
  14101. Effect_promise(async () => {
  14102. GM.setClipboard(
  14103. pipe(
  14104. s.eventLog.entries,
  14105. ReadonlyArray_map(x => `${x.id}: ${x.text}`),
  14106. join("\n")
  14107. )
  14108. )
  14109. }),
  14110. clearFlowChats: c => () => c.act.clearFlowChats,
  14111. },
  14112. buttonNode = label => c => state =>
  14113. h(
  14114. "button",
  14115. {
  14116. type: "button",
  14117. onclick: s => [s, () => runPromise(action[label](c)(s))],
  14118. },
  14119. hyperapp_text(getText(label)(state.lang))
  14120. ),
  14121. tabContainer = style => ontabSelect => labels => tabs => mainTab =>
  14122. h("div", {}, [
  14123. h(
  14124. "div",
  14125. {},
  14126. pipe(
  14127. labels,
  14128. ReadonlyArray_map((x, i) =>
  14129. h(
  14130. "span",
  14131. {
  14132. style: {
  14133. ...style.label,
  14134. ...(mainTab === i ? style.labelFocus : {}),
  14135. display: "inline-block",
  14136. },
  14137. onpointerdown: [ontabSelect, i],
  14138. },
  14139. hyperapp_text(x)
  14140. )
  14141. )
  14142. )
  14143. ),
  14144. h(
  14145. "div",
  14146. { style: { ...style.container, overflow: "auto" } },
  14147. h(
  14148. "div",
  14149. { style: { ...style.tab } },
  14150. tabs.find((_, i) => i === mainTab)?.()
  14151. )
  14152. ),
  14153. ]),
  14154. feedbackPanel = c => s =>
  14155. pipe(
  14156. Math.trunc(getState("eventLog")(s).entries.length / 100) + 1,
  14157. logPageLength => [
  14158. h("div", { style: panelBoxStyle(644) }, [
  14159. h(
  14160. "div",
  14161. { style: { float: "right" } },
  14162. h(
  14163. "a",
  14164. {
  14165. style: { color: "#f0f" },
  14166. href: "https://greasyfork.org/en/scripts/411442-flow-youtube-chat/feedback",
  14167. target: "_blank",
  14168. },
  14169. hyperapp_text(getText("giveFeedback")(s.lang))
  14170. )
  14171. ),
  14172. h("div", {}, [
  14173. h("span", {}, hyperapp_text(getText("eventLog")(s.lang))),
  14174. buttonNode("copy")(c)(s),
  14175. tabContainer({
  14176. container: { height: "276px" },
  14177. label: { padding: "4px", width: "2em", textAlign: "center" },
  14178. labelFocus: { background: "#666" },
  14179. tab: {
  14180. display: "flex",
  14181. flexDirection: "column",
  14182. padding: "6px",
  14183. },
  14184. })((_, n) => updateAt("logTab")(n)(c))(
  14185. pipe(makeBy(logPageLength, x => `${x}`))
  14186. )(
  14187. pipe(
  14188. makeBy(
  14189. logPageLength,
  14190. i => () =>
  14191. pipe(
  14192. getState("eventLog")(s).entries.slice(
  14193. 100 * i,
  14194. 100 * (i + 1)
  14195. ),
  14196. ReadonlyArray_map((x, j) =>
  14197. h("div", { style: { display: "flex" } }, [
  14198. h(
  14199. "div",
  14200. {
  14201. style: {
  14202. userSelect: "none",
  14203. flex: "0 0 2em",
  14204. },
  14205. },
  14206. hyperapp_text(x.id)
  14207. ),
  14208. h(
  14209. "div",
  14210. {
  14211. style: {
  14212. background: j % 2 == 0 ? "#fff" : "#ddd",
  14213. color: "#000",
  14214. flex: "auto",
  14215. wordBreak: "break-all",
  14216. whiteSpace: "pre-wrap",
  14217. padding: "0 2px",
  14218. },
  14219. },
  14220. hyperapp_text(x.text)
  14221. ),
  14222. ])
  14223. )
  14224. )
  14225. )
  14226. )
  14227. )(getState("logTab")(s)),
  14228. ]),
  14229. ]),
  14230. ]
  14231. ),
  14232. setEditRegexs = editing => value =>
  14233. pipe(
  14234. value,
  14235. split(/\r\n|\n/),
  14236. ReadonlyArray_filter(not(isEmpty)),
  14237. Identity_bindTo("regexs"),
  14238. Identity_let_("errors", ({ regexs }) =>
  14239. pipe(
  14240. regexs,
  14241. ReadonlyArray_map((x, i) => {
  14242. try {
  14243. RegExp(x, "u")
  14244. return Option_none()
  14245. } catch (e) {
  14246. return Option_some(`${e} in regex number ${i}`)
  14247. }
  14248. }),
  14249. (Semigroup =>
  14250. fromSemigroup(
  14251. Semigroup_make((self, that) =>
  14252. Option_isNone(self)
  14253. ? that
  14254. : Option_isNone(that)
  14255. ? self
  14256. : Option_some(Semigroup.combine(self.value, that.value))
  14257. ),
  14258. Option_none()
  14259. ))(intercalate("\n")(Semigroup)).combineAll
  14260. )
  14261. ),
  14262. ctx =>
  14263. editing
  14264. ? setText(value)
  14265. : pipe(
  14266. ctx.errors,
  14267. Option_map(x =>
  14268. mapSecond(() => Option_some([value, Option_some(x)]))
  14269. ),
  14270. getOrElse(constant(constant(Editable_of(ctx.regexs))))
  14271. )
  14272. ),
  14273. setEditStrings = editing => value =>
  14274. pipe(value, split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty)), x =>
  14275. constant(
  14276. editing ? [x, Option_some([value, Option_none()])] : Editable_of(x)
  14277. )
  14278. ),
  14279. textAreaRow = (rows, action) => value =>
  14280. h("textarea", {
  14281. rows,
  14282. style: {
  14283. resize: "horizontal",
  14284. boxSizing: "border-box",
  14285. width: "100%",
  14286. borderColor: hasError(value) ? "#f55" : void 0,
  14287. },
  14288. value: pipe(
  14289. value,
  14290. Editable_text,
  14291. getOrElse(pipe(Editable_value(value), join("\n"), constant))
  14292. ),
  14293. ...action,
  14294. }),
  14295. textAreaNode = (label, rows, setter) => c => s =>
  14296. settingRow(
  14297. getText(label)(s.lang),
  14298. errorText(getText("invalidSetting")(s.lang))(s[label]),
  14299. [textAreaRow(rows, editAction(label, setter)(c))(getState(label)(s))]
  14300. ),
  14301. filterPanelOld = c => s =>
  14302. [
  14303. h(
  14304. "div",
  14305. { style: panelBoxStyle(212) },
  14306. textAreaNode("bannedWords", 18, setEditStrings)(c)(s)
  14307. ),
  14308. h(
  14309. "div",
  14310. { style: panelBoxStyle(212) },
  14311. textAreaNode("bannedWordRegexs", 18, setEditRegexs)(c)(s)
  14312. ),
  14313. h(
  14314. "div",
  14315. { style: panelBoxStyle(212) },
  14316. textAreaNode("bannedUsers", 18, setEditStrings)(c)(s)
  14317. ),
  14318. ]
  14319. var validate_color_lib = __webpack_require__(694),
  14320. lib_default = __webpack_require__.n(validate_color_lib)
  14321. const validColor = x => lib_default()(x.replace(/grey/gi, "gray")),
  14322. setEditColor = editing => value =>
  14323. editing
  14324. ? validColor(value)
  14325. ? constant(fromValueText(value)(value))
  14326. : setText(value)
  14327. : validColor(value)
  14328. ? constant(Editable_of(value))
  14329. : mapSecond(constant(Option_some([value, Option_some("")]))),
  14330. colorPicker = action => color =>
  14331. h("input", {
  14332. style: { width: "36px", verticalAlign: "middle" },
  14333. type: "color",
  14334. value: color,
  14335. oninput: action.onchange,
  14336. }),
  14337. textInput = action => value =>
  14338. h("input", {
  14339. style: {
  14340. verticalAlign: "middle",
  14341. width: "5.5em",
  14342. borderColor: hasError(value) ? "#f55" : void 0,
  14343. },
  14344. maxlength: 20,
  14345. value: pipe(
  14346. value,
  14347. Editable_text,
  14348. getOrElse(constant(Editable_value(value)))
  14349. ),
  14350. ...action,
  14351. }),
  14352. setEditInt = editing => value => state =>
  14353. pipe(
  14354. value,
  14355. Number.parseInt,
  14356. editing
  14357. ? x =>
  14358. Number.isNaN(x) || "." === value.at(-1)
  14359. ? pipe(state, setText(value))
  14360. : fromValueText(x)(value)
  14361. : x =>
  14362. Number.isNaN(x)
  14363. ? pipe(
  14364. state,
  14365. mapSecond(constant(Option_some([value, Option_some("")])))
  14366. )
  14367. : Editable_of(x)
  14368. ),
  14369. intNode = (label, min, max, step) => c => s =>
  14370. settingRow(
  14371. getText(label)(s.lang),
  14372. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  14373. [
  14374. rangeRow(
  14375. min,
  14376. max,
  14377. step,
  14378. editAction(label, setEditInt)(c)
  14379. )(getState(label)(s)),
  14380. ]
  14381. ),
  14382. fonts = currentFont => [
  14383. ["", "Default", "デフォルト"],
  14384. ["arial", "Arial", "Arial"],
  14385. ["arial black", "Arial Black", "Arial Black"],
  14386. ["arial narrow", "Arial Narrow", "Arial Narrow"],
  14387. ["Century", "Century", "Century"],
  14388. ["Comic Sans MS", "Comic Sans MS", "Comic Sans MS"],
  14389. ["Courier", "Courier", "Courier"],
  14390. ["cursive", "cursive", "cursive"],
  14391. ["fantasy", "fantasy", "fantasy"],
  14392. ["Impact", "Impact", "Impact"],
  14393. ["Meiryo", "Meiryo", "メイリオ"],
  14394. ["Meiryo UI", "Meiryo UI", "メイリオ UI"],
  14395. ["monospace", "monospace", "monospace"],
  14396. ["Monotype Corsiva", "Monotype Corsiva", "Monotype Corsiva"],
  14397. ["MS PGothic", "MS PGothic", "MS Pゴシック"],
  14398. ["MS Gothic", "MS Gothic", "MS ゴシック"],
  14399. ["MS Sans Serif", "MS Sans Serif", "MS Sans Serif"],
  14400. ["MS Serif", "MS Serif", "MS Serif"],
  14401. ["MS UI Gothic", "MS UI Gothic", "MS UI Gothic"],
  14402. ["sans-serif", "Sans-serif", "Sans-serif"],
  14403. ["serif", "Serif", "Serif"],
  14404. ["Times New Roman", "Times New Roman", "Times New Roman"],
  14405. ["Yu Gothic", "Yu Gothic", "遊ゴシック"],
  14406. ["YuGothic", "YuGothic", "游ゴシック体"],
  14407. [currentFont, "Custom", "カスタム"],
  14408. ],
  14409. setEditString = editing =>
  14410. flow(x => constant(editing ? fromValueText(x)(x) : Editable_of(x))),
  14411. settingUI_textRowStyle = { width: "70%", boxSizing: "border-box" },
  14412. ui_option = (value, label, selected) =>
  14413. h("option", { value, selected }, hyperapp_text(label)),
  14414. exampleTextStyle = s => ({
  14415. fontFamily: Editable_value(s.font),
  14416. fontWeight: Editable_value(s.fontWeight).toString(),
  14417. textShadow: textShadow(Editable_value(s.shadowColor))(
  14418. Editable_value(s.shadowFontWeight)
  14419. ),
  14420. }),
  14421. colorTextOutput = textStyle => color =>
  14422. h(
  14423. "span",
  14424. { style: { ...textStyle, color } },
  14425. hyperapp_text("Aa1あア亜")
  14426. ),
  14427. textColorNode = label => c => s =>
  14428. settingRow(
  14429. getText(label)(s.lang),
  14430. errorText(getText("invalidColor")(s.lang))(s[label]),
  14431. pipe(
  14432. {
  14433. a: editAction(label, setEditColor)(c),
  14434. v: Editable_value(s[label]),
  14435. },
  14436. ({ a, v }) => [
  14437. colorPicker(a)(v),
  14438. textInput(a)(s[label]),
  14439. colorTextOutput(exampleTextStyle(s))(v),
  14440. ]
  14441. )
  14442. ),
  14443. flowChatPanel = pipe(
  14444. [
  14445. pipe(
  14446. [
  14447. c => s =>
  14448. pipe(Editable_value(s.font), font =>
  14449. settingRow(getText("font")(s.lang), "", [
  14450. h(
  14451. "select",
  14452. {
  14453. style: settingUI_textRowStyle,
  14454. onchange: updateInput(setEditString(!1))("font")(c),
  14455. },
  14456. pipe(
  14457. fonts(font),
  14458. findFirstIndex(x => x[0] === font),
  14459. getOrElse(() => 0),
  14460. index =>
  14461. pipe(
  14462. fonts(font),
  14463. ReadonlyArray_map((f, i) =>
  14464. ui_option(
  14465. f[0],
  14466. pipe(
  14467. languages,
  14468. findFirstIndex(x => x === s.lang),
  14469. Option_map(x => unsafeGet(x + 1)(f)),
  14470. getOrElse(() => "Error")
  14471. ),
  14472. i === index
  14473. )
  14474. )
  14475. )
  14476. )
  14477. ),
  14478. h("input", {
  14479. style: settingUI_textRowStyle,
  14480. maxlength: 20,
  14481. value: font,
  14482. ...editAction("font", setEditString),
  14483. }),
  14484. ])
  14485. ),
  14486. textColorNode("color"),
  14487. textColorNode("ownerColor"),
  14488. textColorNode("moderatorColor"),
  14489. textColorNode("memberColor"),
  14490. ((label = "shadowColor"),
  14491. c => s =>
  14492. settingRow(
  14493. getText(label)(s.lang),
  14494. errorText(getText("invalidColor")(s.lang))(s[label]),
  14495. pipe(editAction(label, setEditColor)(c), x => [
  14496. colorPicker(x)(Editable_value(s[label])),
  14497. textInput(x)(s[label]),
  14498. ])
  14499. )),
  14500. ],
  14501. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  14502. ),
  14503. pipe(
  14504. [
  14505. numberNode("chatOpacity", 0, 1, 0.05),
  14506. numberNode("fontSize", 0.3, 2, 0.05),
  14507. numberNode("fontWeight", 10, 1e3, 10),
  14508. numberNode("shadowFontWeight", 0, 3, 0.1),
  14509. numberNode("flowSpeed", 1, 50, 1),
  14510. intNode("maxChatCount", 5, 200, 5),
  14511. intNode("maxChatLength", 5, 200, 5),
  14512. intNode("laneCount", 1, 25, 1),
  14513. ],
  14514. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  14515. ),
  14516. pipe(
  14517. [
  14518. numberNode("flowY1", 0, 0.95, 0.01),
  14519. numberNode("flowY2", 0.05, 1, 0.01),
  14520. numberNode("flowX1", 0, 0.95, 0.01),
  14521. numberNode("flowX2", 0.05, 1, 0.01),
  14522. numberNode("minSpacing", 0, 2.5, 0.1),
  14523. c => s =>
  14524. h("div", {}, [
  14525. checkboxNode("useStepTiming")(c)(s),
  14526. h(
  14527. "div",
  14528. {
  14529. style: {
  14530. opacity: getState("useStepTiming")(s) ? void 0 : "0.5",
  14531. },
  14532. },
  14533. intNode("timingStepCount", 1, 400, 1)(c)(s)
  14534. ),
  14535. ]),
  14536. checkboxNode("createChats"),
  14537. checkboxNode("displayModName"),
  14538. checkboxNode("displaySuperChatAuthor"),
  14539. checkboxNode("textOnly"),
  14540. () => s => hyperapp_text(getText("flowNewChatIf")(s.lang)),
  14541. checkboxNode("noOverlap"),
  14542. buttonNode("clearFlowChats"),
  14543. ],
  14544. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  14545. ),
  14546. ],
  14547. mapSettingNodes(Function_identity)
  14548. )
  14549. var label
  14550. const settingUI_flowChatPanel = flowChatPanel,
  14551. setString = flow(Function_identity, constant),
  14552. simpleWrap = (comp, init) =>
  14553. pipe(
  14554. Effect_sync(() => document.createElement(comp.tag)),
  14555. Effect_flatMap(node =>
  14556. Effect_sync(() => ({
  14557. node,
  14558. dispatch: app({ init, view: comp.view, node }),
  14559. }))
  14560. )
  14561. ),
  14562. toggleSettingsPanelComponent = flow(
  14563. syncState => (x, e) =>
  14564. pipe({ ...x, showPanel: !x.showPanel }, newState => [
  14565. newState,
  14566. x.showPanel
  14567. ? () => z.instanceof(HTMLElement).parse(e.currentTarget).blur()
  14568. : () => {},
  14569. () =>
  14570. runPromise(syncState(oldState => ({ ...oldState, ...newState }))),
  14571. ]),
  14572. toggle => state =>
  14573. h(
  14574. "button",
  14575. {
  14576. class: "fyc_button",
  14577. style: {
  14578. background: "rgba(0,0,0,0)",
  14579. marginLeft: "10px",
  14580. whiteSpace: "nowrap",
  14581. },
  14582. onclick: toggle,
  14583. },
  14584. [
  14585. h(
  14586. "svg",
  14587. {
  14588. preserveAspectRatio: "xMidYMid meet",
  14589. viewBox: "0 0 640 640",
  14590. width: "15",
  14591. height: "15",
  14592. style: { position: "relative", top: "1px" },
  14593. },
  14594. [
  14595. h(
  14596. "defs",
  14597. {},
  14598. h("path", {
  14599. id: "d1TbzTC1zI",
  14600. d: "M135 58c25 14 67 30 82 35-7 49 16 109-15 149-50 71-19 184 64 213 74 31 165-18 183-95-3-38 23-62 58-36l120 55c-39 10-106 35-72 85 40 38 1 71-29 98-29 53-70-17-109-5-46 22-25 109-96 85h-55c-24-31-21-103-80-84-32 32-70 31-93-9l-35-36c4-40 57-96-6-120-45 5-58-32-52-68 2-19-4-41 3-59 35-15 100-22 77-79-48-43 1-84 35-115 5-6 12-12 20-14zM577 2c52 3 72 62 62 106-5 51 19 117-27 155-18 24 8 49 11 74-39-8-98-46-146-60-55-1-111 2-167-2-52-15-57-76-52-121S242 52 282 18c38-30 88-11 132-16h163z",
  14601. })
  14602. ),
  14603. h("use", {
  14604. href: "#d1TbzTC1zI",
  14605. opacity: "1",
  14606. fill: "var(--iron-icon-fill-color, currentcolor)",
  14607. "fill-opacity": "1",
  14608. }),
  14609. ]
  14610. ),
  14611. h(
  14612. "span",
  14613. {
  14614. style: {
  14615. position: "relative",
  14616. top: "-2px",
  14617. marginLeft: "8px,",
  14618. },
  14619. },
  14620. hyperapp_text(getText("setting")(state.lang))
  14621. ),
  14622. ]
  14623. ),
  14624. button =>
  14625. makeComponent(
  14626. tag => s => h(tag, { style: { display: "flex" } }, button(s))
  14627. )("span")
  14628. ),
  14629. videoToggleStream = video =>
  14630. pipe(
  14631. [["playing"], ["waiting", "pause"]],
  14632. ReadonlyArray_map((x, i) => [x, 0 === i]),
  14633. ReadonlyArray_flatMap(([xs, b]) =>
  14634. pipe(
  14635. xs,
  14636. ReadonlyArray_map(x => [x, b])
  14637. )
  14638. ),
  14639. ReadonlyArray_map(([x, b]) =>
  14640. pipe(
  14641. (0, external_rxjs_namespaceObject.fromEvent)(video, x),
  14642. (0, external_rxjs_namespaceObject.map)(() => b)
  14643. )
  14644. ),
  14645. x => (0, external_rxjs_namespaceObject.merge)(...x)
  14646. ),
  14647. Logger_make = makeLogger,
  14648. Logger_replace = replaceLogger,
  14649. Logger_withMinimumLogLevel = withMinimumLogLevel,
  14650. Logger_zip = logger_zip,
  14651. Logger_defaultLogger = defaultLogger
  14652. var LogAnnotationKeys
  14653. !(function (LogAnnotationKeys) {
  14654. LogAnnotationKeys.name = "name"
  14655. })(LogAnnotationKeys || (LogAnnotationKeys = {}))
  14656. const src_LogAnnotationKeys = LogAnnotationKeys,
  14657. getConsoleLog = x =>
  14658. (x === Trace
  14659. ? console.trace
  14660. : x === Level_Debug
  14661. ? console.debug
  14662. : x === Info
  14663. ? console.info
  14664. : x === Warning
  14665. ? console.warn
  14666. : x === Level_Error || x === Fatal
  14667. ? console.error
  14668. : console.log
  14669. ).bind(console),
  14670. metaLogger = Logger_make(
  14671. (fiberId, logLevel, message, cause, context, span, annotations) =>
  14672. runPromise(
  14673. pipe(
  14674. () =>
  14675. `${pipe(
  14676. annotations,
  14677. mjs_HashMap_get(src_LogAnnotationKeys.name),
  14678. match(
  14679. () => "",
  14680. x => `[${x}] `
  14681. )
  14682. )}${message}`,
  14683. getStr =>
  14684. pipe(
  14685. FiberRefs_getOrDefault(context, logMeta),
  14686. match(
  14687. () =>
  14688. greaterThanEqual(Info)(logLevel)
  14689. ? Effect_sync(() => getConsoleLog(logLevel)(getStr()))
  14690. : Effect_unit(),
  14691. meta =>
  14692. Effect_sync(() =>
  14693. getConsoleLog(logLevel)(`${getStr()}: `, meta)
  14694. )
  14695. )
  14696. )
  14697. )
  14698. )
  14699. )
  14700. runPromise(
  14701. pipe(
  14702. Effect_Do(),
  14703. Effect_bindValue(
  14704. "settingUpdateApps",
  14705. () => new external_rxjs_namespaceObject.BehaviorSubject([])
  14706. ),
  14707. Effect_bindValue("provideLog", x => {
  14708. return (
  14709. (settingUpdateApps = x.settingUpdateApps),
  14710. effect => {
  14711. return pipe(
  14712. Effect_succeed(
  14713. Logger_replace(
  14714. Logger_defaultLogger,
  14715. Logger_zip(metaLogger)(
  14716. ((settingApps = settingUpdateApps),
  14717. Logger_make((fiberId, logLevel, message) => {
  14718. return runPromise(
  14719. ((apps = settingApps.getValue()),
  14720. dispatchable =>
  14721. pipe(
  14722. apps,
  14723. ReadonlyArray_map(x =>
  14724. Effect_sync(() => x(dispatchable))
  14725. ),
  14726. x => Effect_all(x)
  14727. ))(s => {
  14728. return {
  14729. ...s,
  14730. eventLog: ((text = message),
  14731. flow(
  14732. (
  14733. text => log =>
  14734. makeLog({
  14735. nextId: log.nextId + 1,
  14736. entries: pipe(
  14737. log.entries,
  14738. append({ id: log.nextId, text })
  14739. ),
  14740. })
  14741. )(text),
  14742. x =>
  14743. x.entries.length > 1e3
  14744. ? (log =>
  14745. makeLog({
  14746. nextId: log.nextId,
  14747. entries: pipe(log.entries, take(100)),
  14748. }))(x)
  14749. : x
  14750. ))(s.eventLog),
  14751. }
  14752. var text
  14753. })
  14754. )
  14755. var apps
  14756. }))
  14757. )
  14758. )
  14759. ),
  14760. Effect_flatMap(x => pipe(effect, Effect_provideSomeLayer(x))),
  14761. Effect_logAnnotate(src_LogAnnotationKeys.name, "FYC"),
  14762. Logger_withMinimumLogLevel(Level_Debug)
  14763. )
  14764. var settingApps
  14765. }
  14766. )
  14767. var settingUpdateApps
  14768. }),
  14769. Effect_flatMap(({ settingUpdateApps, provideLog }) =>
  14770. provideLog(
  14771. pipe(
  14772. src_defaultGMConfig,
  14773. x => ({ gmConfig: x, configKeys: Object.keys(x) }),
  14774. Effect_succeed,
  14775. Effect_bindValue(
  14776. "updateSettingState",
  14777. () => dispatchable =>
  14778. provideLog(
  14779. pipe(
  14780. settingUpdateApps.getValue(),
  14781. ReadonlyArray_map(x =>
  14782. Effect_sync(() => x(dispatchable))
  14783. ),
  14784. x => Effect_all(x)
  14785. )
  14786. )
  14787. ),
  14788. Effect_bind("config", ctx => {
  14789. return (
  14790. (config = ctx.gmConfig),
  14791. pipe(
  14792. Object.entries(config),
  14793. ReadonlyArray_map(([k, c]) =>
  14794. pipe(
  14795. c.getValue,
  14796. Effect_map(x => [k, x])
  14797. )
  14798. ),
  14799. x => Effect_all(x),
  14800. Effect_map(Object.fromEntries)
  14801. )
  14802. )
  14803. var config
  14804. }),
  14805. Effect_bindValue("getConfig", ctx =>
  14806. (c =>
  14807. pipe(
  14808. c,
  14809. mapObject(([x]) => [x, () => c[x]])
  14810. ))(ctx.config)
  14811. ),
  14812. flow(
  14813. Effect_bindValue("mainState", x => ({
  14814. chatPlaying: !0,
  14815. playerRect: new DOMRectReadOnly(0, 0, 600, 400),
  14816. config: x.config,
  14817. flowChats: [],
  14818. })),
  14819. Effect_bindValue("configSubject", ctx =>
  14820. pipe(
  14821. ctx.configKeys,
  14822. ReadonlyArray_map(x => [
  14823. x,
  14824. new external_rxjs_namespaceObject.Subject(),
  14825. ]),
  14826. Object.fromEntries
  14827. )
  14828. ),
  14829. Effect_bindValue("setterFromKeysMap", ctx =>
  14830. (
  14831. keys => f =>
  14832. pipe(
  14833. keys,
  14834. ReadonlyArray_map(x => [x, f(x)]),
  14835. Object.fromEntries
  14836. )
  14837. )(ctx.configKeys)
  14838. ),
  14839. Effect_bindValue("setConfigPlain", ctx =>
  14840. ctx.setterFromKeysMap(
  14841. key => val =>
  14842. Effect_promise(async () => {
  14843. Object.assign(ctx.mainState.config, { [key]: val })
  14844. ctx.configSubject[key].next(val)
  14845. })
  14846. )
  14847. ),
  14848. Effect_bindValue(
  14849. "changedConfigMap",
  14850. ctx => key => val =>
  14851. pipe(
  14852. Effect_promise(async () => ctx.config[key]),
  14853. Effect_filterOrFail(
  14854. x => !fast_deep_equal_default()(x, val),
  14855. Option_none
  14856. ),
  14857. Effect_flatMap(() => ctx.setConfigPlain[key](val))
  14858. )
  14859. ),
  14860. Effect_bindValue("setChangedConfig", ctx =>
  14861. ctx.setterFromKeysMap(ctx.changedConfigMap)
  14862. ),
  14863. Effect_bindValue(
  14864. "channel",
  14865. () =>
  14866. new broadcast_channel_BroadcastChannel(
  14867. "fyc-0615654655528523"
  14868. )
  14869. )
  14870. ),
  14871. flow(
  14872. Effect_bindValue("setConfig", ctx =>
  14873. ctx.setterFromKeysMap(
  14874. key => val =>
  14875. pipe(
  14876. ctx.changedConfigMap(key)(val),
  14877. Effect_zipRight(
  14878. Effect_promise(() =>
  14879. ctx.channel.postMessage([key, val])
  14880. )
  14881. ),
  14882. Effect_zipRight(
  14883. Effect_promise(() =>
  14884. pipe(ctx.gmConfig[key], x =>
  14885. GM.setValue(x.gmKey, x.toGm(val))
  14886. )
  14887. )
  14888. )
  14889. )
  14890. )
  14891. ),
  14892. Effect_bind("reinitSubject", () =>
  14893. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  14894. ),
  14895. Effect_bindValue("reinitialize", ctx =>
  14896. provideLog(
  14897. Effect_sync(() => {
  14898. requestAnimationFrame(() => lib(ctx.reinitSubject)())
  14899. })
  14900. )
  14901. ),
  14902. Effect_tap(ctx =>
  14903. ctx.setConfigPlain.filterExp(defaultFilter(ctx.config))
  14904. ),
  14905. Effect_bindValue("toggleChatButtonInit", ctx => ({
  14906. lang: ctx.config.lang,
  14907. displayChats: ctx.config.displayChats,
  14908. })),
  14909. Effect_bind("wrappedToggleChat", ctx => {
  14910. return simpleWrap(
  14911. ((setConfig = ctx.setConfig),
  14912. pipe(
  14913. "button",
  14914. makeComponent(
  14915. tag => state =>
  14916. pipe(
  14917. getText(
  14918. state.displayChats ? "hideChat" : "showChat"
  14919. )(state.lang),
  14920. label =>
  14921. h(
  14922. tag,
  14923. {
  14924. class: "ytp-button",
  14925. style: {
  14926. background: "none",
  14927. border: "none",
  14928. cursor: "pointer",
  14929. float: "left",
  14930. fontSize: "1em",
  14931. height: "4em",
  14932. outline: "none",
  14933. overflow: "visible",
  14934. padding: "0 0 0em",
  14935. position: "relative",
  14936. width: "3em",
  14937. },
  14938. type: "button",
  14939. "aria-label": label,
  14940. title: label,
  14941. onclick: s =>
  14942. pipe(!s.displayChats, displayChats => [
  14943. { ...s, displayChats },
  14944. () =>
  14945. runPromise(
  14946. setConfig.displayChats(displayChats)
  14947. ),
  14948. ]),
  14949. },
  14950. [
  14951. h(
  14952. "svg",
  14953. {
  14954. style: { width: "100%" },
  14955. viewBox: "0 0 36 36",
  14956. },
  14957. [
  14958. h("path", {
  14959. class: "chat-button-path",
  14960. d: "m11 12h17q1 0 1 1v9q0 1-1 1h-1v2l-4-2h-12q-1 0-1-1v-9q0-1 1-1z",
  14961. fill: "#fff",
  14962. "fill-opacity": state.displayChats
  14963. ? "1"
  14964. : "0",
  14965. stroke: "#fff",
  14966. "stroke-width": "2",
  14967. }),
  14968. ]
  14969. ),
  14970. ]
  14971. )
  14972. )
  14973. )
  14974. )),
  14975. ctx.toggleChatButtonInit
  14976. )
  14977. var setConfig
  14978. }),
  14979. Effect_bind("wrappedSettings", ctx =>
  14980. simpleWrap(
  14981. pipe(
  14982. (
  14983. c => state =>
  14984. state.showPanel
  14985. ? h(
  14986. "div",
  14987. {
  14988. class: "fyc_panel",
  14989. style: {
  14990. backgroundColor: "rgba(30,30,30,0.9)",
  14991. position: "absolute",
  14992. zIndex: "10000",
  14993. color: "#fff",
  14994. fontSize: "14px",
  14995. overflow: "auto",
  14996. left: `${state.panelRect.x}px`,
  14997. top: `${state.panelRect.y}px`,
  14998. width: `${state.panelRect.width}px`,
  14999. height: `${state.panelRect.height}px`,
  15000. border: "solid 1px #666",
  15001. fontFamily: "MS PGothic",
  15002. lineHeight: "1.2",
  15003. colorScheme: "dark",
  15004. },
  15005. },
  15006. [
  15007. h(
  15008. "div",
  15009. {
  15010. style: {
  15011. position: "absolute",
  15012. inset: "3px 3px auto auto",
  15013. },
  15014. },
  15015. [
  15016. hyperapp_text("🌐"),
  15017. h(
  15018. "select",
  15019. {
  15020. onchange:
  15021. updateInput(setString)("lang")(c),
  15022. },
  15023. pipe(
  15024. languages,
  15025. zip(languageLabels),
  15026. ReadonlyArray_map(([lang, label]) =>
  15027. ui_option(
  15028. lang,
  15029. label,
  15030. lang === state.lang
  15031. )
  15032. )
  15033. )
  15034. ),
  15035. ]
  15036. ),
  15037. tabContainer({
  15038. container: { height: "364px" },
  15039. label: { padding: "6px" },
  15040. labelFocus: { background: "#666" },
  15041. tab: { display: "flex", padding: "6px" },
  15042. })((s, n) => updateAt("mainTab")(n)(c)(s))(
  15043. pipe(
  15044. [
  15045. "flowChat",
  15046. "chatFilter",
  15047. "chatField",
  15048. "feedback",
  15049. ],
  15050. ReadonlyArray_map(getText),
  15051. ReadonlyArray_map(apply(state.lang))
  15052. )
  15053. )(
  15054. pipe(
  15055. [
  15056. settingUI_flowChatPanel,
  15057. filterPanelOld,
  15058. settingUI_chatFieldPanel,
  15059. feedbackPanel,
  15060. ],
  15061. ReadonlyArray_map(apply(c)),
  15062. ReadonlyArray_map(constant),
  15063. ReadonlyArray_map(src_flip),
  15064. ReadonlyArray_map(apply(state))
  15065. )
  15066. )(getState("mainTab")(state)),
  15067. ]
  15068. )
  15069. : h("div", {})
  15070. )({
  15071. setConfig: ctx.setConfig,
  15072. act: {
  15073. clearFlowChats: removeOldChats(ctx.mainState)(0),
  15074. },
  15075. }),
  15076. panel =>
  15077. makeComponent(
  15078. tag => s =>
  15079. h(tag, { style: { display: "contents" } }, panel(s))
  15080. )("span")
  15081. ),
  15082. settingStateInit(ctx.config)
  15083. )
  15084. ),
  15085. Effect_bind("wrappedToggleSettings", ctx =>
  15086. simpleWrap(
  15087. toggleSettingsPanelComponent(ctx.updateSettingState),
  15088. settingStateInit(ctx.config)
  15089. )
  15090. )
  15091. ),
  15092. flow(
  15093. Effect_tap(ctx =>
  15094. Effect_sync(() =>
  15095. settingUpdateApps.next([
  15096. ...settingUpdateApps.getValue(),
  15097. ctx.wrappedSettings.dispatch,
  15098. ctx.wrappedToggleSettings.dispatch,
  15099. ])
  15100. )
  15101. )
  15102. ),
  15103. Effect_bindValue(
  15104. "settingsRectSubject",
  15105. () =>
  15106. new external_rxjs_namespaceObject.BehaviorSubject(
  15107. new DOMRectReadOnly(0, 0, 660, 395)
  15108. )
  15109. ),
  15110. Effect_tap(ctx =>
  15111. pipe(
  15112. [
  15113. "Version: 1.15.20",
  15114. `User Agent: ${window.navigator.userAgent}`,
  15115. `GMConfig: ${JSON.stringify(ctx.config, void 0, 2)}`,
  15116. ],
  15117. ReadonlyArray_map(Effect_logDebug),
  15118. x => Effect_all(x)
  15119. )
  15120. ),
  15121. Effect_bindValue("co", ctx =>
  15122. pipe(
  15123. ctx.configSubject,
  15124. mapObject(([k, value]) => [
  15125. k,
  15126. pipe(
  15127. value,
  15128. tapEffect(v => {
  15129. return provideLog(
  15130. pipe(
  15131. v,
  15132. x => s => ({ ...s, [k]: x }),
  15133. Effect_succeed,
  15134. Effect_tap(() => {
  15135. return ctx.updateSettingState(
  15136. ((key = k),
  15137. value => state => ({
  15138. ...state,
  15139. [key]: isEditable(key)(value)
  15140. ? setValue(value)(state[key])
  15141. : "filterExp" === key
  15142. ? void 0
  15143. : value,
  15144. }))(v)
  15145. )
  15146. var key
  15147. }),
  15148. Effect_zipLeft(
  15149. pipe(
  15150. [
  15151. "bannedWords",
  15152. "bannedUsers",
  15153. "bannedWordRegexs",
  15154. ],
  15155. ((isEquivalent = String_Equivalence),
  15156. Function_dual(2, (self, a) => {
  15157. for (const i of self)
  15158. if (isEquivalent(a, i)) return !0
  15159. return !1
  15160. }))(k),
  15161. x =>
  15162. x
  15163. ? ctx.setConfig.filterExp(
  15164. defaultFilter(ctx.config)
  15165. )
  15166. : Effect_unit()
  15167. )
  15168. ),
  15169. Effect_flatMap(x =>
  15170. k in ctx.toggleChatButtonInit
  15171. ? Effect_sync(() =>
  15172. ctx.wrappedToggleChat.dispatch(x)
  15173. )
  15174. : Effect_unit()
  15175. ),
  15176. x => () => runPromise(provideLog(x)),
  15177. x => Effect_sync(() => requestAnimationFrame(x))
  15178. )
  15179. )
  15180. var isEquivalent
  15181. }),
  15182. (0, external_rxjs_namespaceObject.share)()
  15183. ),
  15184. ])
  15185. )
  15186. ),
  15187. Effect_bindValue("livePage", () => livePageYt),
  15188. Effect_bindValue("live", ctx => makePageState(ctx.livePage)),
  15189. Effect_bind("chatScreen", () => makeChatScreen),
  15190. Effect_bind("all$", ctx => {
  15191. return pipe(
  15192. {
  15193. eq:
  15194. ((E = strict()),
  15195. Equivalence_make(
  15196. (x, y) =>
  15197. x === y ||
  15198. (Option_isNone(x)
  15199. ? Option_isNone(y)
  15200. : !Option_isNone(y) && E(x.value, y.value))
  15201. )),
  15202. initDelay: 100,
  15203. urlDelay: 1700,
  15204. changeDetectInterval: 700,
  15205. bodyResizeDetectInterval: 300,
  15206. errorRetryInterval: 5e3,
  15207. liveElementKeys: Object.keys(ctx.livePage),
  15208. tapUpdateSettingsRect: ob =>
  15209. (0, external_rxjs_namespaceObject.switchMap)(value => {
  15210. return pipe(
  15211. ctx.settingsRectSubject,
  15212. (0, external_rxjs_namespaceObject.first)(),
  15213. (0, external_rxjs_namespaceObject.map)(
  15214. ((toggleSettingsElement =
  15215. ctx.wrappedToggleSettings.node),
  15216. nextSettingsRect => last =>
  15217. pipe(
  15218. Effect_succeed(toggleSettingsElement),
  15219. Effect_filterOrFail(
  15220. x => null !== x.offsetParent,
  15221. Option_none
  15222. ),
  15223. Effect_map(x => x.getBoundingClientRect()),
  15224. Effect_map(
  15225. x =>
  15226. new DOMRectReadOnly(
  15227. Math.max(
  15228. 0,
  15229. x.right + window.scrollX - 660
  15230. ),
  15231. Math.max(0, x.y + window.scrollY - 395),
  15232. 660,
  15233. Math.min(x.y + window.scrollY, 395)
  15234. )
  15235. ),
  15236. Effect_orElseSucceed(
  15237. () =>
  15238. new DOMRectReadOnly(-660, -395, 660, 395)
  15239. ),
  15240. Effect_filterOrFail(
  15241. x =>
  15242. x.x !== last.x ||
  15243. x.y !== last.y ||
  15244. x.width !== last.width ||
  15245. x.height !== last.height,
  15246. Option_none
  15247. ),
  15248. Effect_tap(nextSettingsRect),
  15249. Effect_ignore
  15250. ))(rect =>
  15251. Effect_sync(() =>
  15252. ctx.settingsRectSubject.next(rect)
  15253. )
  15254. )
  15255. ),
  15256. tapEffect(provideLog),
  15257. (0, external_rxjs_namespaceObject.map)(() => value)
  15258. )
  15259. var toggleSettingsElement
  15260. })(ob),
  15261. config$: configStream(
  15262. provideLog,
  15263. ctx.mainState,
  15264. ctx.co,
  15265. ctx.chatScreen,
  15266. ctx.live
  15267. ),
  15268. },
  15269. Effect_succeed,
  15270. Effect_bind("css", () => mainCss),
  15271. Effect_bind("documentMutationPair", () =>
  15272. observePair(MutationObserver)
  15273. ),
  15274. Effect_bind("chatMutationPair", () =>
  15275. observePair(MutationObserver)
  15276. ),
  15277. Effect_bind("playerResizePair", () =>
  15278. observePair(ResizeObserver)
  15279. ),
  15280. Effect_bind("bodyResizePair", () =>
  15281. observePair(ResizeObserver)
  15282. ),
  15283. Effect_map(c =>
  15284. pipe(
  15285. ctx.reinitSubject,
  15286. (0, external_rxjs_namespaceObject.observeOn)(
  15287. external_rxjs_namespaceObject.asyncScheduler
  15288. ),
  15289. (0, external_rxjs_namespaceObject.delay)(c.initDelay),
  15290. tapEffect(() => provideLog(Effect_logInfo("Init"))),
  15291. (0, external_rxjs_namespaceObject.switchMap)(() =>
  15292. pipe(
  15293. (0, external_rxjs_namespaceObject.interval)(
  15294. c.changeDetectInterval
  15295. ),
  15296. c.tapUpdateSettingsRect,
  15297. (0, external_rxjs_namespaceObject.concatMap)(index =>
  15298. pipe(
  15299. (0, external_rxjs_namespaceObject.from)(
  15300. runPromise(
  15301. provideLog(
  15302. pipe(
  15303. c.liveElementKeys,
  15304. ReadonlyArray_map(key =>
  15305. pipe(
  15306. ctx.live[key],
  15307. x => x.read,
  15308. Effect_unsome,
  15309. Effect_map(
  15310. liftPredicate(
  15311. newEle =>
  15312. !c.eq(ctx.live[key].ele, newEle)
  15313. )
  15314. ),
  15315. Effect_map(
  15316. Option_map(
  15317. flow(
  15318. Effect_succeed,
  15319. Effect_tap(x =>
  15320. Effect_sync(() => {
  15321. ctx.live[key].ele = x
  15322. })
  15323. ),
  15324. Effect_map(Option_isSome),
  15325. Effect_map(
  15326. x =>
  15327. `${key} ${
  15328. x ? "found" : "lost"
  15329. }`
  15330. ),
  15331. Effect_flatMap(Effect_logInfo)
  15332. )
  15333. )
  15334. ),
  15335. Effect_flatMap(
  15336. match(
  15337. () => Effect_succeed(!1),
  15338. Effect_zipRight(
  15339. Effect_succeed(!0)
  15340. )
  15341. )
  15342. )
  15343. )
  15344. ),
  15345. x => Effect_all(x),
  15346. Effect_map(
  15347. ReadonlyArray_some(Function_identity)
  15348. )
  15349. )
  15350. )
  15351. )
  15352. ),
  15353. (0, external_rxjs_namespaceObject.filter)(
  15354. Function_identity
  15355. ),
  15356. (0, external_rxjs_namespaceObject.map)(
  15357. () => index
  15358. )
  15359. )
  15360. ),
  15361. (0, external_rxjs_namespaceObject.startWith)(0)
  15362. )
  15363. ),
  15364. tapEffect(() =>
  15365. provideLog(
  15366. pipe(
  15367. Effect_logInfo("Loading..."),
  15368. Effect_zipRight(removeOldChats(ctx.mainState)(0)),
  15369. Effect_zipRight(
  15370. Effect_sync(() => {
  15371. c.documentMutationPair.observer.disconnect()
  15372. c.documentMutationPair.observer.observe(
  15373. document,
  15374. { childList: !0, subtree: !0 }
  15375. )
  15376. c.chatMutationPair.observer.disconnect()
  15377. c.playerResizePair.observer.disconnect()
  15378. c.bodyResizePair.observer.disconnect()
  15379. document.head.append(c.css)
  15380. })
  15381. ),
  15382. Effect_zipRight(
  15383. pipe(
  15384. [
  15385. pipe(
  15386. ctx.live.chatField.ele,
  15387. Option_map(x =>
  15388. Effect_sync(() =>
  15389. c.chatMutationPair.observer.observe(x, {
  15390. childList: !0,
  15391. })
  15392. )
  15393. )
  15394. ),
  15395. pipe(
  15396. ctx.live.chatTicker.ele,
  15397. Option_map(x =>
  15398. Effect_sync(() =>
  15399. c.chatMutationPair.observer.observe(x, {
  15400. childList: !0,
  15401. })
  15402. )
  15403. )
  15404. ),
  15405. pipe(
  15406. ctx.live.player.ele,
  15407. Option_map(
  15408. flow(
  15409. Effect_succeed,
  15410. Effect_tap(x =>
  15411. Effect_sync(() =>
  15412. c.playerResizePair.observer.observe(
  15413. x
  15414. )
  15415. )
  15416. ),
  15417. Effect_flatMap(x =>
  15418. Effect_sync(() =>
  15419. x.prepend(ctx.chatScreen)
  15420. )
  15421. )
  15422. )
  15423. )
  15424. ),
  15425. pipe(
  15426. ctx.live.toggleChatBtnParent.ele,
  15427. Option_map(x =>
  15428. Effect_sync(() =>
  15429. x.prepend(ctx.wrappedToggleChat.node)
  15430. )
  15431. )
  15432. ),
  15433. pipe(
  15434. ctx.live.settingsToggleNextElement.ele,
  15435. Option_map(x =>
  15436. Effect_sync(() =>
  15437. x.before(ctx.wrappedToggleSettings.node)
  15438. )
  15439. )
  15440. ),
  15441. pipe(
  15442. ctx.live.settingsContainer.ele,
  15443. Option_map(x =>
  15444. Effect_sync(() =>
  15445. x.append(ctx.wrappedSettings.node)
  15446. )
  15447. )
  15448. ),
  15449. pipe(
  15450. document.body,
  15451. fromNullable,
  15452. Option_map(x =>
  15453. Effect_sync(() =>
  15454. c.bodyResizePair.observer.observe(x)
  15455. )
  15456. )
  15457. ),
  15458. ],
  15459. ReadonlyArray_compact,
  15460. append(
  15461. pipe(
  15462. ctx.live.video.ele,
  15463. Option_filter(x => !x.paused),
  15464. orElse(() => ctx.live.offlineSlate.ele),
  15465. Option_isSome,
  15466. x =>
  15467. Effect_sync(() => {
  15468. Object.assign(ctx.mainState, {
  15469. chatPlaying: x,
  15470. })
  15471. })
  15472. )
  15473. ),
  15474. x => Effect_all(x)
  15475. )
  15476. )
  15477. )
  15478. )
  15479. ),
  15480. (0, external_rxjs_namespaceObject.switchMap)(() =>
  15481. (0, external_rxjs_namespaceObject.merge)(
  15482. pipe(
  15483. (0, external_rxjs_namespaceObject.fromEvent)(
  15484. ctx.channel,
  15485. "message"
  15486. ),
  15487. (0, external_rxjs_namespaceObject.map)(
  15488. ([key, val]) =>
  15489. pipe(
  15490. src_listeningBroadcastConfigKeys.includes(
  15491. key
  15492. ),
  15493. x =>
  15494. x
  15495. ? ctx.setChangedConfig[key](val)
  15496. : Effect_sync(() => {})
  15497. )
  15498. ),
  15499. tapEffect(provideLog)
  15500. ),
  15501. ...pipe(
  15502. ctx.configKeys,
  15503. ReadonlyArray_map(key =>
  15504. pipe(
  15505. ctx.co[key],
  15506. (0, external_rxjs_namespaceObject.startWith)(
  15507. ctx.config[key]
  15508. ),
  15509. (0, external_rxjs_namespaceObject.bufferCount)(
  15510. 2,
  15511. 1
  15512. ),
  15513. (0, external_rxjs_namespaceObject.map)(
  15514. ([x, y]) =>
  15515. (0, external_DeepDiff_namespaceObject.diff)(
  15516. x,
  15517. y
  15518. )
  15519. ),
  15520. (0, external_rxjs_namespaceObject.map)(x =>
  15521. Effect_logDebug(
  15522. `Config ${key}: ${JSON.stringify(
  15523. x,
  15524. void 0,
  15525. 2
  15526. )}`
  15527. )
  15528. ),
  15529. tapEffect(provideLog)
  15530. )
  15531. )
  15532. ),
  15533. c.config$,
  15534. pipe(
  15535. ctx.live.video.ele,
  15536. match(
  15537. () => external_rxjs_namespaceObject.EMPTY,
  15538. flow(
  15539. videoToggleStream,
  15540. (0, external_rxjs_namespaceObject.map)(
  15541. playing =>
  15542. playing ||
  15543. Option_isSome(ctx.live.offlineSlate.ele)
  15544. ),
  15545. (0, external_rxjs_namespaceObject.map)(
  15546. chatPlaying =>
  15547. pipe(
  15548. Effect_sync(() => {
  15549. ctx.mainState.chatPlaying = chatPlaying
  15550. }),
  15551. Effect_zipRight(
  15552. pipe(
  15553. ctx.mainState.flowChats,
  15554. ReadonlyArray_map(setChatPlayState),
  15555. ReadonlyArray_map(
  15556. apply(ctx.mainState)
  15557. ),
  15558. x => Effect_all(x)
  15559. )
  15560. )
  15561. )
  15562. ),
  15563. tapEffect(provideLog)
  15564. )
  15565. )
  15566. ),
  15567. pipe(
  15568. c.chatMutationPair.subject,
  15569. (0, external_rxjs_namespaceObject.map)(
  15570. onChatFieldMutate(
  15571. ctx.chatScreen,
  15572. ctx.mainState,
  15573. ctx.getConfig,
  15574. ctx.setConfig
  15575. )
  15576. ),
  15577. tapEffect(provideLog)
  15578. ),
  15579. pipe(
  15580. c.documentMutationPair.subject,
  15581. (0, external_rxjs_namespaceObject.map)(
  15582. () => window.location.href
  15583. ),
  15584. (0,
  15585. external_rxjs_namespaceObject.distinctUntilChanged)(),
  15586. (0, external_rxjs_namespaceObject.skip)(1),
  15587. c.tapUpdateSettingsRect,
  15588. (0, external_rxjs_namespaceObject.map)(x =>
  15589. Effect_all([
  15590. Effect_logInfo(`URL Changed: ${x}`),
  15591. removeOldChats(ctx.mainState)(0),
  15592. Effect_logInfo(`Wait for ${c.urlDelay}ms...`),
  15593. ])
  15594. ),
  15595. tapEffect(provideLog),
  15596. (0, external_rxjs_namespaceObject.delay)(
  15597. c.urlDelay
  15598. ),
  15599. tapEffect(() => ctx.reinitialize)
  15600. ),
  15601. pipe(
  15602. c.playerResizePair.subject,
  15603. (0, external_rxjs_namespaceObject.throttleTime)(
  15604. 500,
  15605. void 0,
  15606. { leading: !0, trailing: !0 }
  15607. ),
  15608. (0, external_rxjs_namespaceObject.startWith)([]),
  15609. (0, external_rxjs_namespaceObject.map)(
  15610. () => ctx.live.player.ele
  15611. ),
  15612. (0, external_rxjs_namespaceObject.map)(
  15613. Option_map(x => x.getBoundingClientRect())
  15614. ),
  15615. tapEffect(x => {
  15616. return provideLog(
  15617. ((rect = x),
  15618. (mainState = ctx.mainState),
  15619. pipe(
  15620. rect,
  15621. Effect_fromOption,
  15622. Effect_flatMap(
  15623. flow(
  15624. x =>
  15625. Effect_sync(() =>
  15626. Object.assign(mainState, {
  15627. playerRect: x,
  15628. })
  15629. ),
  15630. Effect_map(() => mainState.flowChats),
  15631. Effect_map(
  15632. ReadonlyArray_flatMap(x => [
  15633. renderChat(x)(mainState),
  15634. setChatAnimation(x)(mainState),
  15635. ])
  15636. ),
  15637. Effect_flatMap(x => Effect_all(x)),
  15638. Effect_zipLeft(
  15639. Effect_logInfo("Resize detected")
  15640. )
  15641. )
  15642. ),
  15643. Effect_ignore
  15644. ))
  15645. )
  15646. var rect, mainState
  15647. })
  15648. ),
  15649. pipe(
  15650. c.bodyResizePair.subject,
  15651. (0, external_rxjs_namespaceObject.throttleTime)(
  15652. c.bodyResizeDetectInterval,
  15653. void 0,
  15654. { leading: !0, trailing: !0 }
  15655. ),
  15656. (0, external_rxjs_namespaceObject.startWith)([]),
  15657. c.tapUpdateSettingsRect
  15658. ),
  15659. pipe(
  15660. ctx.settingsRectSubject,
  15661. tapEffect(panelRect =>
  15662. ctx.updateSettingState(s => ({ ...s, panelRect }))
  15663. )
  15664. )
  15665. )
  15666. ),
  15667. (0, external_rxjs_namespaceObject.retry)({
  15668. delay: e =>
  15669. pipe(
  15670. e,
  15671. external_rxjs_namespaceObject.of,
  15672. tapEffect(() =>
  15673. provideLog(
  15674. logWithMeta(Level_Error)(`Errored: ${e}`)(e)
  15675. )
  15676. ),
  15677. (0, external_rxjs_namespaceObject.delay)(
  15678. c.errorRetryInterval
  15679. ),
  15680. tapEffect(() => ctx.reinitialize)
  15681. ),
  15682. })
  15683. )
  15684. )
  15685. )
  15686. var E
  15687. }),
  15688. Effect_tap(ctx =>
  15689. Effect_sync(() =>
  15690. ctx.all$.subscribe({
  15691. error: x =>
  15692. runPromise(
  15693. logWithMeta(Level_Error)(`Stream Errored: ${x}`)(x)
  15694. ),
  15695. complete: () =>
  15696. runPromise(Effect_logInfo("Stream complete")),
  15697. })
  15698. )
  15699. ),
  15700. Effect_tap(ctx => ctx.reinitialize)
  15701. )
  15702. )
  15703. )
  15704. )
  15705. )
  15706. })()
  15707. })()