Flow Youtube Chat

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

目前為 2023-03-29 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Flow Youtube Chat
  3. // @description Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.
  4. // @version 1.15.19
  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. catchAllCause = dualWithTrace(2, (trace, restore) => (self, f) => {
  3386. const effect = new EffectPrimitive("OnFailure")
  3387. effect.i0 = self
  3388. effect.i1 = restore(f)
  3389. return trace ? effect.traced(trace) : effect
  3390. }),
  3391. context = methodWithTrace(
  3392. trace => () => suspend(() => fiberRefGet(currentContext)).traced(trace)
  3393. ),
  3394. contextWithEffect = methodWithTrace(
  3395. (trace, restore) => f =>
  3396. core_flatMap(restore(f))(context()).traced(trace)
  3397. ),
  3398. core_exit = methodWithTrace(
  3399. trace => self => matchCause(failCause, succeed)(self).traced(trace)
  3400. ),
  3401. core_fail = methodWithTrace(
  3402. trace => error => failCause(fail(error)).traced(trace)
  3403. ),
  3404. failSync = methodWithTrace(
  3405. (trace, restore) => evaluate =>
  3406. failCauseSync(() => fail(restore(evaluate)())).traced(trace)
  3407. ),
  3408. failCause = methodWithTrace(trace => cause => {
  3409. const effect = new EffectPrimitiveFailure("Failure")
  3410. effect.i0 = cause
  3411. return trace ? effect.traced(trace) : effect
  3412. }),
  3413. failCauseSync = methodWithTrace(
  3414. (trace, restore) => evaluate =>
  3415. core_flatMap(sync(restore(evaluate)), failCause).traced(trace)
  3416. ),
  3417. fiberId = methodWithTrace(
  3418. trace => () =>
  3419. withFiberRuntime(state => succeed(state.id())).traced(trace)
  3420. ),
  3421. core_flatMap = dualWithTrace(2, (trace, restore) => (self, f) => {
  3422. const effect = new EffectPrimitive("OnSuccess")
  3423. effect.i0 = self
  3424. effect.i1 = restore(f)
  3425. return trace ? effect.traced(trace) : effect
  3426. }),
  3427. core_flatten = methodWithTrace(
  3428. trace => self => core_flatMap(self, Function_identity).traced(trace)
  3429. ),
  3430. matchCause = dualWithTrace(
  3431. 3,
  3432. (trace, restore) => (self, onFailure, onSuccess) =>
  3433. matchCauseEffect(
  3434. cause => succeed(restore(onFailure)(cause)),
  3435. a => succeed(restore(onSuccess)(a))
  3436. )(self).traced(trace)
  3437. ),
  3438. matchCauseEffect = dualWithTrace(
  3439. 3,
  3440. (trace, restore) => (self, onFailure, onSuccess) => {
  3441. const effect = new EffectPrimitive("OnSuccessAndFailure")
  3442. effect.i0 = self
  3443. effect.i1 = restore(onFailure)
  3444. effect.i2 = restore(onSuccess)
  3445. return trace ? effect.traced(trace) : effect
  3446. }
  3447. ),
  3448. matchEffect = dualWithTrace(
  3449. 3,
  3450. (trace, restore) => (self, onFailure, onSuccess) =>
  3451. matchCauseEffect(
  3452. self,
  3453. cause => {
  3454. const failures = (self =>
  3455. Chunk_reverse(
  3456. cause_reduce(self, Chunk_empty(), (list, cause) =>
  3457. "Fail" === cause._tag
  3458. ? Option_some(Chunk_prepend(cause.error)(list))
  3459. : Option_none()
  3460. )
  3461. ))(cause)
  3462. return cause_defects(cause).length > 0
  3463. ? failCause(
  3464. (self =>
  3465. cause_match(
  3466. self,
  3467. cause_empty,
  3468. failure => die(failure),
  3469. defect => die(defect),
  3470. fiberId => interrupt(fiberId),
  3471. (cause, annotation) =>
  3472. isEmptyType(cause)
  3473. ? cause
  3474. : annotated(cause, annotation),
  3475. (left, right) => sequential(left, right),
  3476. (left, right) => parallel(left, right)
  3477. ))(cause)
  3478. )
  3479. : failures.length > 0
  3480. ? restore(onFailure)(unsafeHead(failures))
  3481. : failCause(cause)
  3482. },
  3483. onSuccess
  3484. ).traced(trace)
  3485. ),
  3486. core_forEach = dualWithTrace(
  3487. 2,
  3488. (trace, restore) => (self, f) =>
  3489. suspend(() => {
  3490. const arr = Array.from(self),
  3491. ret = new Array(arr.length)
  3492. let i = 0
  3493. return core_as(unsafeFromArray(ret))(
  3494. whileLoop(
  3495. () => i < arr.length,
  3496. () => restore(f)(arr[i]),
  3497. b => {
  3498. ret[i++] = b
  3499. }
  3500. )
  3501. )
  3502. }).traced(trace)
  3503. ),
  3504. forEachDiscard = dualWithTrace(
  3505. 2,
  3506. (trace, restore) => (self, f) =>
  3507. suspend(() => {
  3508. const arr = Array.from(self)
  3509. let i = 0
  3510. return whileLoop(
  3511. () => i < arr.length,
  3512. () => restore(f)(arr[i++]),
  3513. () => {}
  3514. )
  3515. }).traced(trace)
  3516. ),
  3517. core_fromOption = methodWithTrace(trace => option => {
  3518. switch (option._tag) {
  3519. case "None":
  3520. return core_fail(Option_none()).traced(trace)
  3521. case "Some":
  3522. return succeed(option.value).traced(trace)
  3523. }
  3524. }),
  3525. core_interruptible = methodWithTrace(trace => self => {
  3526. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3527. effect.i0 = runtimeFlagsPatch_make((flag = 1), flag)
  3528. var flag
  3529. effect.i1 = () => self
  3530. return trace ? effect.traced(trace) : effect
  3531. }),
  3532. core_map = dualWithTrace(
  3533. 2,
  3534. (trace, restore) => (self, f) =>
  3535. core_flatMap(a => sync(() => restore(f)(a)))(self).traced(trace)
  3536. ),
  3537. onExit = dualWithTrace(
  3538. 2,
  3539. (trace, restoreTrace) => (self, cleanup) =>
  3540. uninterruptibleMask(restore =>
  3541. matchCauseEffect(
  3542. restore(self),
  3543. cause1 => {
  3544. const result = exitFailCause(cause1)
  3545. return matchCauseEffect(
  3546. cause2 => exitFailCause(sequential(cause1, cause2)),
  3547. () => result
  3548. )(restoreTrace(cleanup)(result))
  3549. },
  3550. success => {
  3551. const result = exitSucceed(success)
  3552. return zipRight(result)(restoreTrace(cleanup)(result))
  3553. }
  3554. )
  3555. ).traced(trace)
  3556. ),
  3557. onInterrupt = dualWithTrace(
  3558. 2,
  3559. (trace, restore) => (self, cleanup) =>
  3560. onExit(
  3561. self,
  3562. exitMatch(
  3563. cause =>
  3564. isInterruptedOnly(cause)
  3565. ? core_asUnit(
  3566. restore(cleanup)(
  3567. (self =>
  3568. cause_reduce(
  3569. self,
  3570. mjs_HashSet_empty(),
  3571. (set, cause) =>
  3572. "Interrupt" === cause._tag
  3573. ? Option_some(
  3574. mjs_HashSet_add(cause.fiberId)(set)
  3575. )
  3576. : Option_none()
  3577. ))(cause)
  3578. )
  3579. )
  3580. : core_unit(),
  3581. () => core_unit()
  3582. )
  3583. ).traced(trace)
  3584. ),
  3585. core_orElse = dualWithTrace(
  3586. 2,
  3587. (trace, restore) => (self, that) =>
  3588. attemptOrElse(restore(that), succeed)(self).traced(trace)
  3589. ),
  3590. provideContext = dualWithTrace(
  3591. 2,
  3592. trace => (self, context) =>
  3593. fiberRefLocally(currentContext, context)(self).traced(trace)
  3594. ),
  3595. contramapContext = dualWithTrace(
  3596. 2,
  3597. (trace, restore) => (self, f) =>
  3598. contextWithEffect(context =>
  3599. provideContext(restore(f)(context))(self)
  3600. ).traced(trace)
  3601. ),
  3602. succeed = methodWithTrace(trace => value => {
  3603. const effect = new EffectPrimitiveSuccess("Success")
  3604. effect.i0 = value
  3605. return trace ? effect.traced(trace) : effect
  3606. }),
  3607. suspend = methodWithTrace(
  3608. (trace, restore) => effect =>
  3609. core_flatMap(Function_identity)(sync(restore(effect))).traced(trace)
  3610. ),
  3611. sync = methodWithTrace((trace, restore) => evaluate => {
  3612. const effect = new EffectPrimitive("Sync")
  3613. effect.i0 = restore(evaluate)
  3614. return trace ? effect.traced(trace) : effect
  3615. }),
  3616. core_tap = dualWithTrace(
  3617. 2,
  3618. (trace, restore) => (self, f) =>
  3619. core_flatMap(a => core_as(a)(restore(f)(a)))(self).traced(trace)
  3620. ),
  3621. transplant = methodWithTrace(
  3622. (trace, restore) => f =>
  3623. withFiberRuntime(state => {
  3624. const scopeOverride = state.getFiberRef(forkScopeOverride),
  3625. scope = getOrElse(() => state.scope())(scopeOverride)
  3626. return restore(f)(
  3627. fiberRefLocally(forkScopeOverride, Option_some(scope))
  3628. )
  3629. }).traced(trace)
  3630. ),
  3631. attemptOrElse = dualWithTrace(
  3632. 3,
  3633. (trace, restore) => (self, that, onSuccess) =>
  3634. matchCauseEffect(
  3635. self,
  3636. cause =>
  3637. cause_defects(cause).length > 0
  3638. ? failCause(
  3639. getOrThrow(
  3640. (self =>
  3641. cause_match(
  3642. self,
  3643. Option_none(),
  3644. failure => Option_some(die(failure)),
  3645. defect => Option_some(die(defect)),
  3646. () => Option_none(),
  3647. (option, annotation) =>
  3648. Option_map(cause => annotated(cause, annotation))(
  3649. option
  3650. ),
  3651. (left, right) =>
  3652. Option_isSome(left) && Option_isSome(right)
  3653. ? Option_some(sequential(left.value, right.value))
  3654. : Option_isSome(left) && Option_isNone(right)
  3655. ? Option_some(left.value)
  3656. : Option_isNone(left) && Option_isSome(right)
  3657. ? Option_some(right.value)
  3658. : Option_none(),
  3659. (left, right) =>
  3660. Option_isSome(left) && Option_isSome(right)
  3661. ? Option_some(parallel(left.value, right.value))
  3662. : Option_isSome(left) && Option_isNone(right)
  3663. ? Option_some(left.value)
  3664. : Option_isNone(left) && Option_isSome(right)
  3665. ? Option_some(right.value)
  3666. : Option_none()
  3667. ))(cause)
  3668. )
  3669. )
  3670. : restore(that)(),
  3671. restore(onSuccess)
  3672. ).traced(trace)
  3673. ),
  3674. uninterruptible = methodWithTrace(trace => self => {
  3675. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3676. effect.i0 = Patch_disable(1)
  3677. effect.i1 = () => self
  3678. return trace ? effect.traced(trace) : effect
  3679. }),
  3680. uninterruptibleMask = methodWithTrace((trace, restore) => f => {
  3681. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3682. effect.i0 = Patch_disable(1)
  3683. effect.i1 = oldFlags =>
  3684. interruption(oldFlags)
  3685. ? restore(f)(core_interruptible)
  3686. : restore(f)(uninterruptible)
  3687. return trace ? effect.traced(trace) : effect
  3688. }),
  3689. core_unit = methodWithTrace(trace => _ => succeed(void 0).traced(trace)),
  3690. updateRuntimeFlags = methodWithTrace(trace => patch => {
  3691. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3692. effect.i0 = patch
  3693. effect.i1 = void 0
  3694. return trace ? effect.traced(trace) : effect
  3695. }),
  3696. whenEffect = dualWithTrace(
  3697. 2,
  3698. trace => (self, predicate) =>
  3699. core_flatMap(b =>
  3700. b ? core_map(Option_some)(self) : succeed(Option_none())
  3701. )(predicate).traced(trace)
  3702. ),
  3703. whileLoop = methodWithTrace(
  3704. (trace, restore) => (check, body, process) => {
  3705. const effect = new EffectPrimitive("While")
  3706. effect.i0 = restore(check)
  3707. effect.i1 = restore(body)
  3708. effect.i2 = restore(process)
  3709. return trace ? effect.traced(trace) : effect
  3710. }
  3711. ),
  3712. withFiberRuntime = methodWithTrace((trace, restore) => withRuntime => {
  3713. const effect = new EffectPrimitive("WithRuntime")
  3714. effect.i0 = restore(withRuntime)
  3715. return trace ? effect.traced(trace) : effect
  3716. }),
  3717. withParallelism = dualWithTrace(
  3718. 2,
  3719. trace => (self, parallelism) =>
  3720. suspend(() =>
  3721. fiberRefLocally(currentParallelism, Option_some(parallelism))(self)
  3722. ).traced(trace)
  3723. ),
  3724. yieldNow = methodWithTrace(trace => () => {
  3725. const effect = new EffectPrimitive("Yield")
  3726. return trace ? effect.traced(trace) : effect
  3727. }),
  3728. core_zip = dualWithTrace(
  3729. 2,
  3730. trace => (self, that) =>
  3731. core_flatMap(self, a => core_map(that, b => [a, b])).traced(trace)
  3732. ),
  3733. zipLeft = dualWithTrace(
  3734. 2,
  3735. trace => (self, that) =>
  3736. core_flatMap(self, a => core_as(that, a)).traced(trace)
  3737. ),
  3738. zipRight = dualWithTrace(
  3739. 2,
  3740. trace => (self, that) => core_flatMap(self, () => that).traced(trace)
  3741. ),
  3742. core_zipWith = dualWithTrace(
  3743. 3,
  3744. (trace, restore) => (self, that, f) =>
  3745. core_flatMap(self, a => core_map(that, b => restore(f)(a, b))).traced(
  3746. trace
  3747. )
  3748. ),
  3749. interruptFiber = methodWithTrace(
  3750. trace => self =>
  3751. core_flatMap(fiberId => interruptAsFiber(fiberId)(self))(
  3752. fiberId()
  3753. ).traced(trace)
  3754. ),
  3755. interruptAsFiber = dualWithTrace(
  3756. 2,
  3757. trace => (self, fiberId) =>
  3758. core_flatMap(() => self.await())(
  3759. self.interruptAsFork(fiberId)
  3760. ).traced(trace)
  3761. ),
  3762. logLevelAll = {
  3763. _tag: "All",
  3764. syslog: 0,
  3765. label: "ALL",
  3766. ordinal: Number.MIN_SAFE_INTEGER,
  3767. },
  3768. logLevelInfo = { _tag: "Info", syslog: 6, label: "INFO", ordinal: 2e4 },
  3769. logLevelDebug = {
  3770. _tag: "Debug",
  3771. syslog: 7,
  3772. label: "DEBUG",
  3773. ordinal: 1e4,
  3774. },
  3775. logLevelNone = {
  3776. _tag: "None",
  3777. syslog: 7,
  3778. label: "OFF",
  3779. ordinal: Number.MAX_SAFE_INTEGER,
  3780. },
  3781. FiberRefTypeId = Symbol.for("@effect/io/FiberRef"),
  3782. fiberRefVariance = { _A: _ => _ },
  3783. fiberRefGet = methodWithTrace(
  3784. trace => self => fiberRefModify(self, a => [a, a]).traced(trace)
  3785. ),
  3786. fiberRefGetWith = dualWithTrace(
  3787. 2,
  3788. (trace, restore) => (self, f) =>
  3789. core_flatMap(fiberRefGet(self), restore(f)).traced(trace)
  3790. ),
  3791. fiberRefSet = dualWithTrace(
  3792. 2,
  3793. trace => (self, value) =>
  3794. fiberRefModify(self, () => [void 0, value]).traced(trace)
  3795. ),
  3796. fiberRefModify = dualWithTrace(
  3797. 2,
  3798. (trace, restore) => (self, f) =>
  3799. withFiberRuntime(state => {
  3800. const [b, a] = restore(f)(state.getFiberRef(self))
  3801. state.setFiberRef(self, a)
  3802. return succeed(b)
  3803. }).traced(trace)
  3804. ),
  3805. fiberRefLocally = dualWithTrace(
  3806. 3,
  3807. trace => (use, self, value) =>
  3808. acquireUseRelease(
  3809. zipLeft(fiberRefGet(self), fiberRefSet(self, value)),
  3810. () => use,
  3811. oldValue => fiberRefSet(self, oldValue)
  3812. ).traced(trace)
  3813. ),
  3814. fiberRefUnsafeMake = (
  3815. initial,
  3816. fork = Function_identity,
  3817. join = (_, a) => a
  3818. ) => fiberRefUnsafeMakePatch(initial, Differ_update(), fork, join),
  3819. fiberRefUnsafeMakeHashSet = initial =>
  3820. fiberRefUnsafeMakePatch(
  3821. initial,
  3822. Differ_hashSet(),
  3823. Differ_HashSetPatch_empty()
  3824. ),
  3825. fiberRefUnsafeMakeContext = initial =>
  3826. fiberRefUnsafeMakePatch(
  3827. initial,
  3828. Differ_environment(),
  3829. Differ_ContextPatch_empty()
  3830. ),
  3831. fiberRefUnsafeMakePatch = (
  3832. initial,
  3833. differ,
  3834. fork,
  3835. join = (_, n) => n
  3836. ) => ({
  3837. [FiberRefTypeId]: fiberRefVariance,
  3838. initial,
  3839. diff: (oldValue, newValue) => Differ_diff(oldValue, newValue)(differ),
  3840. combine: (first, second) => Differ_combine(first, second)(differ),
  3841. patch: patch => oldValue => Differ_patch(patch, oldValue)(differ),
  3842. fork,
  3843. join,
  3844. }),
  3845. fiberRefUnsafeMakeRuntimeFlags = initial =>
  3846. fiberRefUnsafeMakePatch(
  3847. initial,
  3848. mjs_Differ_make({
  3849. empty: runtimeFlagsPatch_empty,
  3850. diff: (oldValue, newValue) => runtimeFlags_diff(oldValue, newValue),
  3851. combine: (first, second) =>
  3852. runtimeFlagsPatch_andThen(second)(first),
  3853. patch: (_patch, oldValue) => runtimeFlags_patch(oldValue, _patch),
  3854. }),
  3855. Patch_empty
  3856. ),
  3857. currentContext = fiberRefUnsafeMakeContext(mjs_Context_empty()),
  3858. currentLogAnnotations = fiberRefUnsafeMake(mjs_HashMap_empty()),
  3859. currentLogLevel = fiberRefUnsafeMake(logLevelInfo),
  3860. currentLogSpan = fiberRefUnsafeMake(Chunk_empty()),
  3861. currentScheduler = fiberRefUnsafeMake(defaultScheduler),
  3862. currentParallelism = fiberRefUnsafeMake(Option_none()),
  3863. unhandledErrorLogLevel = fiberRefUnsafeMake(
  3864. Option_some(logLevelDebug),
  3865. _ => _,
  3866. (_, x) => x
  3867. ),
  3868. currentTags = fiberRefUnsafeMakeHashSet(mjs_HashSet_empty()),
  3869. forkScopeOverride = fiberRefUnsafeMake(
  3870. Option_none(),
  3871. () => Option_none(),
  3872. (parent, _) => parent
  3873. ),
  3874. interruptedCause = fiberRefUnsafeMake(
  3875. cause_empty,
  3876. () => cause_empty,
  3877. (parent, _) => parent
  3878. ),
  3879. ScopeTypeId = Symbol.for("@effect/io/Scope"),
  3880. CloseableScopeTypeId = Symbol.for("@effect/io/CloseableScope"),
  3881. scopeAddFinalizerExit = methodWithTrace(
  3882. (trace, restore) => (self, finalizer) =>
  3883. self.addFinalizer(restore(finalizer)).traced(trace)
  3884. ),
  3885. scopeClose = methodWithTrace(
  3886. trace => (self, exit) => self.close(exit).traced(trace)
  3887. ),
  3888. releaseMapAdd = dualWithTrace(
  3889. 2,
  3890. (trace, restore) => (self, finalizer) =>
  3891. core_map(
  3892. match(
  3893. () => () => core_unit(),
  3894. key => exit => releaseMapRelease(key, exit)(self)
  3895. )
  3896. )(releaseMapAddIfOpen(restore(finalizer))(self)).traced(trace)
  3897. ),
  3898. releaseMapRelease = dualWithTrace(
  3899. 3,
  3900. trace => (self, key, exit) =>
  3901. suspend(() => {
  3902. switch (self.state._tag) {
  3903. case "Exited":
  3904. return core_unit()
  3905. case "Running": {
  3906. const finalizer = self.state.finalizers.get(key)
  3907. self.state.finalizers.delete(key)
  3908. return null != finalizer
  3909. ? self.state.update(finalizer)(exit)
  3910. : core_unit()
  3911. }
  3912. }
  3913. }).traced(trace)
  3914. ),
  3915. releaseMapAddIfOpen = dualWithTrace(
  3916. 2,
  3917. (trace, restore) => (self, finalizer) =>
  3918. suspend(() => {
  3919. switch (self.state._tag) {
  3920. case "Exited":
  3921. self.state.nextKey += 1
  3922. return core_as(Option_none())(
  3923. restore(finalizer)(self.state.exit)
  3924. )
  3925. case "Running": {
  3926. const key = self.state.nextKey
  3927. self.state.finalizers.set(key, finalizer)
  3928. self.state.nextKey += 1
  3929. return succeed(Option_some(key))
  3930. }
  3931. }
  3932. }).traced(trace)
  3933. ),
  3934. releaseMapMake = methodWithTrace(
  3935. trace => () =>
  3936. sync(() => ({
  3937. state: {
  3938. _tag: "Running",
  3939. nextKey: 0,
  3940. finalizers: new Map(),
  3941. update: Function_identity,
  3942. },
  3943. })).traced(trace)
  3944. ),
  3945. exitAs = Function_dual(2, (self, value) => {
  3946. switch (self._tag) {
  3947. case "Failure":
  3948. return self
  3949. case "Success":
  3950. return exitSucceed(value)
  3951. }
  3952. }),
  3953. exitAsUnit = self => exitAs(self, void 0),
  3954. exitCollectAllPar = exits => exitCollectAllInternal(exits, parallel),
  3955. exitFailCause = cause => {
  3956. const effect = new EffectPrimitiveFailure("Failure")
  3957. effect.i0 = cause
  3958. return effect
  3959. },
  3960. exitMap = Function_dual(2, (self, f) => {
  3961. switch (self._tag) {
  3962. case "Failure":
  3963. return self
  3964. case "Success":
  3965. return exitSucceed(f(self.i0))
  3966. }
  3967. }),
  3968. exitMatch = Function_dual(3, (self, onFailure, onSuccess) => {
  3969. switch (self._tag) {
  3970. case "Failure":
  3971. return onFailure(self.i0)
  3972. case "Success":
  3973. return onSuccess(self.i0)
  3974. }
  3975. }),
  3976. exitMatchEffect = Function_dual(3, (self, onFailure, onSuccess) => {
  3977. switch (self._tag) {
  3978. case "Failure":
  3979. return onFailure(self.i0)
  3980. case "Success":
  3981. return onSuccess(self.i0)
  3982. }
  3983. }),
  3984. exitSucceed = value => {
  3985. const effect = new EffectPrimitiveSuccess("Success")
  3986. effect.i0 = value
  3987. return effect
  3988. },
  3989. exitUnit = () => exitSucceed(void 0),
  3990. exitZipWith = Function_dual(4, (self, that, f, g) => {
  3991. switch (self._tag) {
  3992. case "Failure":
  3993. switch (that._tag) {
  3994. case "Success":
  3995. return self
  3996. case "Failure":
  3997. return exitFailCause(g(self.i0, that.i0))
  3998. }
  3999. case "Success":
  4000. switch (that._tag) {
  4001. case "Success":
  4002. return exitSucceed(f(self.i0, that.i0))
  4003. case "Failure":
  4004. return that
  4005. }
  4006. }
  4007. }),
  4008. exitCollectAllInternal = (exits, combineCauses) => {
  4009. const list = Chunk_fromIterable(exits)
  4010. return Chunk_isNonEmpty(list)
  4011. ? Option_some(
  4012. exitMap(Chunk_reverse)(
  4013. Chunk_reduce(
  4014. exitMap(Chunk_of)(Chunk_headNonEmpty(list)),
  4015. (accumulator, current) =>
  4016. exitZipWith(
  4017. current,
  4018. (list, value) => Chunk_prepend(value)(list),
  4019. combineCauses
  4020. )(accumulator)
  4021. )(Chunk_tailNonEmpty(list))
  4022. )
  4023. )
  4024. : Option_none()
  4025. },
  4026. deferredUnsafeMake = fiberId => ({
  4027. [DeferredTypeId]: deferredVariance,
  4028. state: MutableRef_make(pending([])),
  4029. blockingOn: fiberId,
  4030. }),
  4031. deferredMake = methodWithTrace(
  4032. trace => () =>
  4033. core_flatMap(id => deferredMakeAs(id))(fiberId()).traced(trace)
  4034. ),
  4035. deferredMakeAs = methodWithTrace(
  4036. trace => fiberId =>
  4037. sync(() => deferredUnsafeMake(fiberId)).traced(trace)
  4038. ),
  4039. deferredAwait = methodWithTrace(
  4040. trace => self =>
  4041. asyncInterruptEither(k => {
  4042. const state = MutableRef_get(self.state)
  4043. switch (state._tag) {
  4044. case "Done":
  4045. return Either_right(state.effect)
  4046. case "Pending":
  4047. MutableRef_set(pending([k, ...state.joiners]))(self.state)
  4048. return Either_left(deferredInterruptJoiner(self, k))
  4049. }
  4050. }, self.blockingOn).traced(trace)
  4051. ),
  4052. deferredCompleteWith = dualWithTrace(
  4053. 2,
  4054. trace => (self, effect) =>
  4055. sync(() => {
  4056. const state = MutableRef_get(self.state)
  4057. switch (state._tag) {
  4058. case "Done":
  4059. return !1
  4060. case "Pending":
  4061. MutableRef_set(done(effect))(self.state)
  4062. for (let i = 0; i < state.joiners.length; i++)
  4063. state.joiners[i](effect)
  4064. return !0
  4065. }
  4066. }).traced(trace)
  4067. ),
  4068. deferredFail = dualWithTrace(
  4069. 2,
  4070. trace => (self, error) =>
  4071. deferredCompleteWith(self, core_fail(error)).traced(trace)
  4072. ),
  4073. deferredFailCause = dualWithTrace(
  4074. 2,
  4075. trace => (self, cause) =>
  4076. deferredCompleteWith(self, failCause(cause)).traced(trace)
  4077. ),
  4078. deferredSucceed = dualWithTrace(
  4079. 2,
  4080. trace => (self, value) =>
  4081. deferredCompleteWith(self, succeed(value)).traced(trace)
  4082. ),
  4083. deferredUnsafeDone = (self, effect) => {
  4084. const state = MutableRef_get(self.state)
  4085. if ("Pending" === state._tag) {
  4086. MutableRef_set(done(effect))(self.state)
  4087. for (let i = state.joiners.length - 1; i >= 0; i--)
  4088. state.joiners[i](effect)
  4089. }
  4090. },
  4091. deferredInterruptJoiner = (self, joiner) =>
  4092. sync(() => {
  4093. const state = MutableRef_get(self.state)
  4094. "Pending" === state._tag &&
  4095. MutableRef_set(pending(state.joiners.filter(j => j !== joiner)))(
  4096. self.state
  4097. )
  4098. })
  4099. class ConsImpl {
  4100. constructor(head, tail) {
  4101. this.head = head
  4102. this.tail = tail
  4103. this._tag = "Cons"
  4104. this[List_a] = listVariance
  4105. }
  4106. toString() {
  4107. return `List.Cons(${List_toReadonlyArray(this).map(String).join(", ")})`
  4108. }
  4109. toJSON() {
  4110. return { _tag: "List.Cons", values: List_toReadonlyArray(this) }
  4111. }
  4112. [Symbol.for("nodejs.util.inspect.custom")]() {
  4113. return this.toJSON()
  4114. }
  4115. [Equal_symbol](that) {
  4116. return (
  4117. isList(that) &&
  4118. this._tag === that._tag &&
  4119. equalsWith(this, that, equals)
  4120. )
  4121. }
  4122. [symbol]() {
  4123. return string("@effect/data/List")
  4124. }
  4125. [Symbol.iterator]() {
  4126. let done = !1,
  4127. self = this
  4128. return {
  4129. next() {
  4130. if (done) return this.return()
  4131. if ("Nil" === self._tag) {
  4132. done = !0
  4133. return this.return()
  4134. }
  4135. const value = self.head
  4136. self = self.tail
  4137. return { done, value }
  4138. },
  4139. return(value) {
  4140. done || (done = !0)
  4141. return { done: !0, value }
  4142. },
  4143. }
  4144. }
  4145. }
  4146. class NilImpl {
  4147. constructor() {
  4148. this._tag = "Nil"
  4149. this[List_b] = listVariance
  4150. }
  4151. toString() {
  4152. return "List.Nil"
  4153. }
  4154. toJSON() {
  4155. return { _tag: "List.Nil" }
  4156. }
  4157. [Symbol.for("nodejs.util.inspect.custom")]() {
  4158. return this.toJSON()
  4159. }
  4160. [symbol]() {
  4161. return array(Array.from(this))
  4162. }
  4163. [Equal_symbol](that) {
  4164. return isList(that) && this._tag === that._tag
  4165. }
  4166. [Symbol.iterator]() {
  4167. return { next: () => ({ done: !0, value: void 0 }) }
  4168. }
  4169. }
  4170. const Duration_TypeId = Symbol.for("@effect/data/Duration")
  4171. class DurationImpl {
  4172. constructor(millis) {
  4173. this.millis = millis
  4174. this._id = Duration_TypeId
  4175. }
  4176. [symbol]() {
  4177. return Hash_hash(this.millis)
  4178. }
  4179. [Equal_symbol](that) {
  4180. return isDuration(that) && this.millis === that.millis
  4181. }
  4182. }
  4183. const isDuration = u =>
  4184. "object" == typeof u &&
  4185. null != u &&
  4186. "_id" in u &&
  4187. u._id === Duration_TypeId,
  4188. zero = new DurationImpl(0),
  4189. millis = millis => new DurationImpl(millis)
  4190. fromSemigroup(
  4191. Semigroup_make(
  4192. Function_dual(
  4193. 2,
  4194. (self, that) => new DurationImpl(self.millis + that.millis)
  4195. )
  4196. ),
  4197. zero
  4198. ).combineAll
  4199. var fiberRefs_a
  4200. const FiberRefsSym = Symbol.for("@effect/io/FiberRefs")
  4201. class FiberRefsImpl {
  4202. constructor(locals) {
  4203. this.locals = locals
  4204. this[fiberRefs_a] = FiberRefsSym
  4205. }
  4206. }
  4207. fiberRefs_a = FiberRefsSym
  4208. const findAncestor = (
  4209. _ref,
  4210. _parentStack,
  4211. _childStack,
  4212. _childModified = !1
  4213. ) => {
  4214. const ref = _ref
  4215. let ret,
  4216. parentStack = _parentStack,
  4217. childStack = _childStack,
  4218. childModified = _childModified
  4219. for (; void 0 === ret; )
  4220. if (
  4221. isNonEmptyReadonlyArray(parentStack) &&
  4222. isNonEmptyReadonlyArray(childStack)
  4223. ) {
  4224. const parentFiberId = headNonEmpty(parentStack)[0],
  4225. parentAncestors = tailNonEmpty(parentStack),
  4226. childFiberId = headNonEmpty(childStack)[0],
  4227. childRefValue = headNonEmpty(childStack)[1],
  4228. childAncestors = tailNonEmpty(childStack)
  4229. if (parentFiberId.startTimeMillis < childFiberId.startTimeMillis) {
  4230. childStack = childAncestors
  4231. childModified = !0
  4232. } else if (
  4233. parentFiberId.startTimeMillis > childFiberId.startTimeMillis
  4234. )
  4235. parentStack = parentAncestors
  4236. else if (parentFiberId.id < childFiberId.id) {
  4237. childStack = childAncestors
  4238. childModified = !0
  4239. } else
  4240. parentFiberId.id > childFiberId.id
  4241. ? (parentStack = parentAncestors)
  4242. : (ret = [childRefValue, childModified])
  4243. } else ret = [ref.initial, !0]
  4244. return ret
  4245. },
  4246. joinAs = Function_dual(3, (self, fiberId, that) => {
  4247. const parentFiberRefs = new Map(self.locals)
  4248. for (const [fiberRef, childStack] of that.locals) {
  4249. const childValue = headNonEmpty(childStack)[1]
  4250. if (!equals(headNonEmpty(childStack)[0], fiberId)) {
  4251. if (!parentFiberRefs.has(fiberRef)) {
  4252. if (equals(childValue, fiberRef.initial)) continue
  4253. parentFiberRefs.set(fiberRef, [
  4254. [fiberId, fiberRef.join(fiberRef.initial, childValue)],
  4255. ])
  4256. continue
  4257. }
  4258. const parentStack = parentFiberRefs.get(fiberRef),
  4259. [ancestor, wasModified] = findAncestor(
  4260. fiberRef,
  4261. parentStack,
  4262. childStack
  4263. )
  4264. if (wasModified) {
  4265. const patch = fiberRef.diff(ancestor, childValue),
  4266. oldValue = headNonEmpty(parentStack)[1],
  4267. newValue = fiberRef.join(
  4268. oldValue,
  4269. fiberRef.patch(patch)(oldValue)
  4270. )
  4271. if (!equals(oldValue, newValue)) {
  4272. let newStack
  4273. const parentFiberId = headNonEmpty(parentStack)[0]
  4274. newStack = equals(parentFiberId, fiberId)
  4275. ? prepend([parentFiberId, newValue])(
  4276. tailNonEmpty(parentStack)
  4277. )
  4278. : prepend([fiberId, newValue])(parentStack)
  4279. parentFiberRefs.set(fiberRef, newStack)
  4280. }
  4281. }
  4282. }
  4283. }
  4284. return new FiberRefsImpl(new Map(parentFiberRefs))
  4285. }),
  4286. forkAs = Function_dual(2, (self, childId) => {
  4287. const map = new Map()
  4288. for (const [fiberRef, stack] of self.locals.entries()) {
  4289. const oldValue = headNonEmpty(stack)[1],
  4290. newValue = fiberRef.patch(fiberRef.fork)(oldValue)
  4291. equals(oldValue, newValue)
  4292. ? map.set(fiberRef, stack)
  4293. : map.set(fiberRef, prepend([childId, newValue])(stack))
  4294. }
  4295. return new FiberRefsImpl(map)
  4296. }),
  4297. delete_ = Function_dual(2, (self, fiberRef) => {
  4298. const locals = new Map(self.locals)
  4299. locals.delete(fiberRef)
  4300. return new FiberRefsImpl(locals)
  4301. }),
  4302. fiberRefs_get = Function_dual(2, (self, fiberRef) =>
  4303. self.locals.has(fiberRef)
  4304. ? Option_some(headNonEmpty(self.locals.get(fiberRef))[1])
  4305. : Option_none()
  4306. ),
  4307. getOrDefault = Function_dual(2, (self, fiberRef) =>
  4308. getOrElse(() => fiberRef.initial)(fiberRefs_get(self, fiberRef))
  4309. ),
  4310. updatedAs = Function_dual(4, (self, fiberId, fiberRef, value) => {
  4311. const oldStack = self.locals.has(fiberRef)
  4312. ? self.locals.get(fiberRef)
  4313. : []
  4314. let newStack
  4315. if (isEmptyReadonlyArray(oldStack))
  4316. newStack = ReadonlyArray_of([fiberId, value])
  4317. else {
  4318. const [currentId, currentValue] = headNonEmpty(oldStack)
  4319. if (equals(currentId, fiberId)) {
  4320. if (equals(currentValue, value)) return self
  4321. newStack = prepend([fiberId, value])(tailNonEmpty(oldStack))
  4322. } else newStack = prepend([fiberId, value])(oldStack)
  4323. }
  4324. const locals = new Map(self.locals)
  4325. return new FiberRefsImpl(locals.set(fiberRef, newStack))
  4326. }),
  4327. FiberRefs_forkAs = forkAs,
  4328. FiberRefs_getOrDefault = getOrDefault,
  4329. FiberRefs_updatedAs = updatedAs,
  4330. FiberRefs_unsafeMake = function (fiberRefLocals) {
  4331. return new FiberRefsImpl(fiberRefLocals)
  4332. },
  4333. patch_diff = (oldValue, newValue) => {
  4334. const missingLocals = new Map(oldValue.locals)
  4335. let patch = { _tag: "Empty" }
  4336. for (const [fiberRef, pairs] of newValue.locals.entries()) {
  4337. const newValue = headNonEmpty(pairs)[1],
  4338. old = missingLocals.get(fiberRef)
  4339. if (void 0 !== old) {
  4340. const oldValue = headNonEmpty(old)[1]
  4341. equals(oldValue, newValue) ||
  4342. (patch = patch_combine({
  4343. _tag: "Update",
  4344. fiberRef,
  4345. patch: fiberRef.diff(oldValue, newValue),
  4346. })(patch))
  4347. } else
  4348. patch = patch_combine({ _tag: "Add", fiberRef, value: newValue })(
  4349. patch
  4350. )
  4351. missingLocals.delete(fiberRef)
  4352. }
  4353. for (const [fiberRef] of missingLocals.entries())
  4354. patch = patch_combine({ _tag: "Remove", fiberRef })(patch)
  4355. return patch
  4356. },
  4357. patch_combine = Function_dual(2, (self, that) => ({
  4358. _tag: "AndThen",
  4359. first: self,
  4360. second: that,
  4361. })),
  4362. patch_patch = Function_dual(3, (self, fiberId, oldValue) => {
  4363. let fiberRefs = oldValue,
  4364. patches = ReadonlyArray_of(self)
  4365. for (; isNonEmptyReadonlyArray(patches); ) {
  4366. const head = headNonEmpty(patches),
  4367. tail = tailNonEmpty(patches)
  4368. switch (head._tag) {
  4369. case "Empty":
  4370. patches = tail
  4371. break
  4372. case "Add":
  4373. fiberRefs = updatedAs(
  4374. fiberRefs,
  4375. fiberId,
  4376. head.fiberRef,
  4377. head.value
  4378. )
  4379. patches = tail
  4380. break
  4381. case "Remove":
  4382. fiberRefs = delete_(fiberRefs, head.fiberRef)
  4383. patches = tail
  4384. break
  4385. case "Update": {
  4386. const value = getOrDefault(fiberRefs, head.fiberRef)
  4387. fiberRefs = updatedAs(
  4388. fiberRefs,
  4389. fiberId,
  4390. head.fiberRef,
  4391. head.fiberRef.patch(head.patch)(value)
  4392. )
  4393. patches = tail
  4394. break
  4395. }
  4396. case "AndThen":
  4397. patches = prepend(head.first)(prepend(head.second)(tail))
  4398. }
  4399. }
  4400. return fiberRefs
  4401. })
  4402. class SingleShotGen {
  4403. constructor(self) {
  4404. this.self = self
  4405. this.called = !1
  4406. }
  4407. next(a) {
  4408. return this.called
  4409. ? { value: a, done: !0 }
  4410. : ((this.called = !0), { value: this.self, done: !1 })
  4411. }
  4412. return(a) {
  4413. return { value: a, done: !0 }
  4414. }
  4415. throw(e) {
  4416. throw e
  4417. }
  4418. [Symbol.iterator]() {
  4419. return new SingleShotGen(this.self)
  4420. }
  4421. }
  4422. const All = logLevelAll,
  4423. Fatal = { _tag: "Fatal", syslog: 2, label: "FATAL", ordinal: 5e4 },
  4424. Level_Error = { _tag: "Error", syslog: 3, label: "ERROR", ordinal: 4e4 },
  4425. Warning = { _tag: "Warning", syslog: 4, label: "WARN", ordinal: 3e4 },
  4426. Info = logLevelInfo,
  4427. Level_Debug = logLevelDebug,
  4428. Trace = { _tag: "Trace", syslog: 7, label: "TRACE", ordinal: 0 },
  4429. Level_None = logLevelNone,
  4430. locally = dualWithTrace(
  4431. 2,
  4432. trace => (use, self) =>
  4433. fiberRefLocally(use, currentLogLevel, self).traced(trace)
  4434. ),
  4435. greaterThanEqual = greaterThanOrEqualTo(
  4436. Order_contramap(level => level.ordinal)(Order)
  4437. ),
  4438. fromLiteral = _ => {
  4439. switch (_) {
  4440. case "All":
  4441. return All
  4442. case "Debug":
  4443. return Level_Debug
  4444. case "Error":
  4445. return Level_Error
  4446. case "Fatal":
  4447. return Fatal
  4448. case "Info":
  4449. return Info
  4450. case "Trace":
  4451. return Trace
  4452. case "None":
  4453. return Level_None
  4454. case "Warning":
  4455. return Warning
  4456. }
  4457. },
  4458. Span_render = now => self =>
  4459. `${self.label.replace(/[\s="]/g, "_")}=${now - self.startTime}ms`
  4460. var ref_a
  4461. const RefTypeId = Symbol.for("@effect/io/Ref"),
  4462. refVariance = { _A: _ => _ }
  4463. class RefImpl {
  4464. constructor(ref) {
  4465. this.ref = ref
  4466. this[ref_a] = refVariance
  4467. }
  4468. modify(f) {
  4469. return bodyWithTrace((trace, restore) =>
  4470. sync(() => {
  4471. const current = MutableRef_get(this.ref),
  4472. [b, a] = restore(f)(current)
  4473. current !== a && MutableRef_set(a)(this.ref)
  4474. return b
  4475. }).traced(trace)
  4476. )
  4477. }
  4478. }
  4479. ref_a = RefTypeId
  4480. const ref_unsafeMake = value => new RefImpl(MutableRef_make(value)),
  4481. ref_make = methodWithTrace(
  4482. trace => value => sync(() => ref_unsafeMake(value)).traced(trace)
  4483. ),
  4484. ref_get = methodWithTrace(
  4485. trace => self => self.modify(a => [a, a]).traced(trace)
  4486. ),
  4487. ref_set = dualWithTrace(
  4488. 2,
  4489. trace => (self, value) =>
  4490. self.modify(() => [void 0, value]).traced(trace)
  4491. ),
  4492. ref_modify = dualWithTrace(
  4493. 2,
  4494. (trace, restore) => (self, f) => self.modify(restore(f)).traced(trace)
  4495. ),
  4496. ref_update = dualWithTrace(
  4497. 2,
  4498. (trace, restore) => (self, f) =>
  4499. self.modify(a => [void 0, restore(f)(a)]).traced(trace)
  4500. ),
  4501. effect_collectAll = methodWithTrace(
  4502. trace => effects =>
  4503. core_forEach(effects, Function_identity).traced(trace)
  4504. ),
  4505. diffFiberRefs = methodWithTrace(
  4506. trace => self =>
  4507. summarized(getFiberRefs(), patch_diff)(self).traced(trace)
  4508. ),
  4509. effect_Do = methodWithTrace(trace => () => succeed({}).traced(trace)),
  4510. effect_bind = dualWithTrace(
  4511. 3,
  4512. (trace, restore) => (self, tag, f) =>
  4513. core_flatMap(self, k =>
  4514. core_map(restore(f)(k), a => ({ ...k, [tag]: a }))
  4515. ).traced(trace)
  4516. ),
  4517. bindValue = dualWithTrace(
  4518. 3,
  4519. (trace, restore) => (self, tag, f) =>
  4520. core_map(self, k => ({ ...k, [tag]: restore(f)(k) })).traced(trace)
  4521. ),
  4522. filterOrElse = dualWithTrace(
  4523. 3,
  4524. (trace, restore) => (self, f, orElse) =>
  4525. filterOrElseWith(self, restore(f), orElse).traced(trace)
  4526. ),
  4527. filterOrElseWith = dualWithTrace(
  4528. 3,
  4529. (trace, restore) => (self, f, orElse) =>
  4530. core_flatMap(self, a =>
  4531. restore(f)(a) ? succeed(a) : restore(orElse)(a)
  4532. ).traced(trace)
  4533. ),
  4534. filterOrFail = dualWithTrace(
  4535. 3,
  4536. (trace, restore) => (self, f, error) =>
  4537. filterOrElse(self, restore(f), () => failSync(restore(error))).traced(
  4538. trace
  4539. )
  4540. ),
  4541. effect_match = dualWithTrace(
  4542. 3,
  4543. (trace, restore) => (self, onFailure, onSuccess) =>
  4544. matchEffect(
  4545. self,
  4546. e => succeed(restore(onFailure)(e)),
  4547. a => succeed(restore(onSuccess)(a))
  4548. ).traced(trace)
  4549. )
  4550. class EffectGen {
  4551. constructor(value) {
  4552. this.value = value
  4553. }
  4554. [Symbol.iterator]() {
  4555. return new SingleShotGen(this)
  4556. }
  4557. }
  4558. const getFiberRefs = methodWithTrace(
  4559. trace => () =>
  4560. withFiberRuntime(state => succeed(state.unsafeGetFiberRefs())).traced(
  4561. trace
  4562. )
  4563. ),
  4564. ignore = methodWithTrace(
  4565. trace => self =>
  4566. effect_match(self, Function_constVoid, Function_constVoid).traced(
  4567. trace
  4568. )
  4569. ),
  4570. effect_isSuccess = methodWithTrace(
  4571. trace => self =>
  4572. effect_match(self, Function_constFalse, Function_constTrue).traced(
  4573. trace
  4574. )
  4575. ),
  4576. someInfo = Option_some(Info),
  4577. someDebug = Option_some(Level_Debug),
  4578. log = methodWithTrace(
  4579. trace => message =>
  4580. withFiberRuntime(fiberState => {
  4581. fiberState.log(message, cause_empty, Option_none())
  4582. return core_unit()
  4583. }).traced(trace)
  4584. ),
  4585. logDebug = methodWithTrace(
  4586. trace => message =>
  4587. withFiberRuntime(fiberState => {
  4588. fiberState.log(message, cause_empty, someDebug)
  4589. return core_unit()
  4590. }).traced(trace)
  4591. ),
  4592. logInfo = methodWithTrace(
  4593. trace => message =>
  4594. withFiberRuntime(fiberState => {
  4595. fiberState.log(message, cause_empty, someInfo)
  4596. return core_unit()
  4597. }).traced(trace)
  4598. ),
  4599. logInfoCauseMessage = methodWithTrace(
  4600. trace => (message, cause) =>
  4601. withFiberRuntime(fiberState => {
  4602. fiberState.log(message, cause, someInfo)
  4603. return core_unit()
  4604. }).traced(trace)
  4605. ),
  4606. logAnnotate = dualWithTrace(
  4607. 3,
  4608. trace => (effect, key, value) =>
  4609. core_flatMap(fiberRefGet(currentLogAnnotations), annotations =>
  4610. suspend(() =>
  4611. fiberRefLocally(
  4612. currentLogAnnotations,
  4613. HashMap_set(key, value)(annotations)
  4614. )(effect)
  4615. )
  4616. ).traced(trace)
  4617. ),
  4618. orElseSucceed = dualWithTrace(
  4619. 2,
  4620. (trace, restore) => (self, evaluate) =>
  4621. core_orElse(self, () => sync(restore(evaluate))).traced(trace)
  4622. ),
  4623. patchFiberRefs = methodWithTrace(
  4624. trace => patch =>
  4625. updateFiberRefs((fiberId, fiberRefs) =>
  4626. patch_patch(fiberId, fiberRefs)(patch)
  4627. ).traced(trace)
  4628. ),
  4629. promise = methodWithTrace(
  4630. (trace, restore) => evaluate =>
  4631. core_async(resolve => {
  4632. restore(evaluate)()
  4633. .then(a => resolve(exitSucceed(a)))
  4634. .catch(e => resolve(exitFailCause(die(e))))
  4635. }).traced(trace)
  4636. ),
  4637. summarized = dualWithTrace(
  4638. 3,
  4639. (trace, restore) => (self, summary, f) =>
  4640. core_flatMap(summary, start =>
  4641. core_flatMap(self, value =>
  4642. core_map(summary, end => [restore(f)(start, end), value])
  4643. )
  4644. ).traced(trace)
  4645. ),
  4646. effect_all = methodWithTrace(
  4647. trace =>
  4648. function () {
  4649. return 1 === arguments.length
  4650. ? isEffect(arguments[0])
  4651. ? core_map(arguments[0], x => [x])
  4652. : Array.isArray(arguments[0])
  4653. ? core_map(
  4654. effect_collectAll(arguments[0]),
  4655. toReadonlyArray
  4656. ).traced(trace)
  4657. : core_map(values => {
  4658. const res = {}
  4659. for (const [k, v] of values) res[k] = v
  4660. return res
  4661. })(
  4662. core_forEach(Object.entries(arguments[0]), ([_, e]) =>
  4663. core_map(e, a => [_, a])
  4664. )
  4665. ).traced(trace)
  4666. : core_map(effect_collectAll(arguments), toReadonlyArray).traced(
  4667. trace
  4668. )
  4669. }
  4670. ),
  4671. updateFiberRefs = methodWithTrace(
  4672. (trace, restore) => f =>
  4673. withFiberRuntime(state => {
  4674. state.setFiberRefs(
  4675. restore(f)(state.id(), state.unsafeGetFiberRefs())
  4676. )
  4677. return core_unit()
  4678. }).traced(trace)
  4679. ),
  4680. MutableHashMap_TypeId = Symbol.for("@effect/data/MutableHashMap")
  4681. class MutableHashMapImpl {
  4682. constructor() {
  4683. this._id = MutableHashMap_TypeId
  4684. this.backingMap = MutableRef_make(mjs_HashMap_empty())
  4685. }
  4686. [Symbol.iterator]() {
  4687. return this.backingMap.current[Symbol.iterator]()
  4688. }
  4689. toString() {
  4690. return `MutableHashMap(${Array.from(this)
  4691. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  4692. .join(", ")})`
  4693. }
  4694. toJSON() {
  4695. return { _tag: "MutableHashMap", values: Array.from(this) }
  4696. }
  4697. [Symbol.for("nodejs.util.inspect.custom")]() {
  4698. return this.toJSON()
  4699. }
  4700. }
  4701. const MutableHashMap_get = Function_dual(2, (self, key) =>
  4702. mjs_HashMap_get(self.backingMap.current, key)
  4703. ),
  4704. MutableHashMap_has = Function_dual(2, (self, key) =>
  4705. Option_isSome(MutableHashMap_get(self, key))
  4706. ),
  4707. MutableHashMap_set = Function_dual(3, (self, key, value) => {
  4708. MutableRef_update(self.backingMap, HashMap_set(key, value))
  4709. return self
  4710. }),
  4711. ExecutionStrategy_sequential = { _tag: "Sequential" }
  4712. var fiberStatus_a, fiberStatus_b, fiberStatus_c
  4713. const FiberStatusTypeId = Symbol.for("@effect/io/Fiber/Status")
  4714. class Done {
  4715. constructor() {
  4716. this[fiberStatus_a] = FiberStatusTypeId
  4717. this._tag = "Done"
  4718. }
  4719. [((fiberStatus_a = FiberStatusTypeId), symbol)]() {
  4720. return combine(Hash_hash(this._tag))(
  4721. Hash_hash("@effect/io/Fiber/Status")
  4722. )
  4723. }
  4724. [Equal_symbol](that) {
  4725. return isFiberStatus(that) && "Done" === that._tag
  4726. }
  4727. }
  4728. class Running {
  4729. constructor(runtimeFlags) {
  4730. this.runtimeFlags = runtimeFlags
  4731. this[fiberStatus_b] = FiberStatusTypeId
  4732. this._tag = "Running"
  4733. }
  4734. [((fiberStatus_b = FiberStatusTypeId), symbol)]() {
  4735. return combine(Hash_hash(this.runtimeFlags))(
  4736. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  4737. )
  4738. }
  4739. [Equal_symbol](that) {
  4740. return (
  4741. isFiberStatus(that) &&
  4742. "Running" === that._tag &&
  4743. this.runtimeFlags === that.runtimeFlags
  4744. )
  4745. }
  4746. }
  4747. class Suspended {
  4748. constructor(runtimeFlags, blockingOn) {
  4749. this.runtimeFlags = runtimeFlags
  4750. this.blockingOn = blockingOn
  4751. this[fiberStatus_c] = FiberStatusTypeId
  4752. this._tag = "Suspended"
  4753. }
  4754. [((fiberStatus_c = FiberStatusTypeId), symbol)]() {
  4755. return combine(Hash_hash(this.blockingOn))(
  4756. combine(Hash_hash(this.runtimeFlags))(
  4757. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  4758. )
  4759. )
  4760. }
  4761. [Equal_symbol](that) {
  4762. return (
  4763. isFiberStatus(that) &&
  4764. "Suspended" === that._tag &&
  4765. this.runtimeFlags === that.runtimeFlags &&
  4766. equals(this.blockingOn, that.blockingOn)
  4767. )
  4768. }
  4769. }
  4770. const isFiberStatus = u =>
  4771. "object" == typeof u && null != u && FiberStatusTypeId in u,
  4772. Status_done = new Done(),
  4773. Status_running = runtimeFlags => new Running(runtimeFlags),
  4774. interruptSignal = cause => ({ _tag: "InterruptSignal", cause }),
  4775. stateful = onFiber => ({ _tag: "Stateful", onFiber }),
  4776. resume = effect => ({ _tag: "Resume", effect })
  4777. var fiberScope_a, fiberScope_b
  4778. const FiberScopeTypeId = Symbol.for("@effect/io/Fiber/Scope")
  4779. class Global {
  4780. constructor() {
  4781. this[fiberScope_a] = FiberScopeTypeId
  4782. this.fiberId = Id_none
  4783. this.roots = new Set()
  4784. }
  4785. add(_runtimeFlags, child) {
  4786. this.roots.add(child)
  4787. child.unsafeAddObserver(() => {
  4788. this.roots.delete(child)
  4789. })
  4790. }
  4791. }
  4792. fiberScope_a = FiberScopeTypeId
  4793. class Local {
  4794. constructor(fiberId, parent) {
  4795. this.fiberId = fiberId
  4796. this.parent = parent
  4797. this[fiberScope_b] = FiberScopeTypeId
  4798. }
  4799. add(_runtimeFlags, child) {
  4800. this.parent.tell(
  4801. stateful(parentFiber => {
  4802. parentFiber.addChild(child)
  4803. child.unsafeAddObserver(() => {
  4804. parentFiber.removeChild(child)
  4805. })
  4806. })
  4807. )
  4808. }
  4809. }
  4810. fiberScope_b = FiberScopeTypeId
  4811. const globalScope = globalValue(
  4812. Symbol.for("@effect/io/FiberScope/Global"),
  4813. () => new Global()
  4814. ),
  4815. FiberTypeId = Symbol.for("@effect/io/Fiber"),
  4816. fiberVariance = { _E: _ => _, _A: _ => _ },
  4817. RuntimeFiberTypeId = Symbol.for("@effect/io/Fiber"),
  4818. _await = methodWithTrace(trace => self => self.await().traced(trace)),
  4819. fiber_join = methodWithTrace(
  4820. trace => self =>
  4821. zipLeft(core_flatten(self.await()), self.inheritAll()).traced(trace)
  4822. ),
  4823. currentFiberURI = "@effect/io/Fiber/Current",
  4824. MutableList_TypeId = Symbol.for("@effect/data/MutableList")
  4825. class MutableListImpl {
  4826. constructor() {
  4827. this._id = MutableList_TypeId
  4828. this.head = void 0
  4829. this.tail = void 0
  4830. this._length = 0
  4831. }
  4832. [Symbol.iterator]() {
  4833. let done = !1,
  4834. head = this.head
  4835. return {
  4836. next() {
  4837. if (done) return this.return()
  4838. if (null == head) {
  4839. done = !0
  4840. return this.return()
  4841. }
  4842. const value = head.value
  4843. head = head.next
  4844. return { done, value }
  4845. },
  4846. return(value) {
  4847. done || (done = !0)
  4848. return { done: !0, value }
  4849. },
  4850. }
  4851. }
  4852. toString() {
  4853. return `MutableList(${Array.from(this).map(String).join(", ")})`
  4854. }
  4855. toJSON() {
  4856. return { _tag: "MutableList", values: Array.from(this) }
  4857. }
  4858. [Symbol.for("nodejs.util.inspect.custom")]() {
  4859. return this.toJSON()
  4860. }
  4861. }
  4862. class LinkedListNode {
  4863. constructor(value) {
  4864. this.value = value
  4865. this.removed = !1
  4866. this.prev = void 0
  4867. this.next = void 0
  4868. }
  4869. }
  4870. const MutableList_isEmpty = self => 0 === MutableList_length(self),
  4871. MutableList_length = self => self._length,
  4872. MutableList_append = Function_dual(2, (self, value) => {
  4873. const node = new LinkedListNode(value)
  4874. void 0 === self.head && (self.head = node)
  4875. if (void 0 === self.tail) self.tail = node
  4876. else {
  4877. self.tail.next = node
  4878. node.prev = self.tail
  4879. self.tail = node
  4880. }
  4881. self._length += 1
  4882. return self
  4883. }),
  4884. MutableQueue_TypeId = Symbol.for("@effect/data/MutableQueue")
  4885. class MutableQueueImpl {
  4886. constructor(capacity) {
  4887. this.capacity = capacity
  4888. this._tag = "Bounded"
  4889. this._id = MutableQueue_TypeId
  4890. this.queue = new MutableListImpl()
  4891. }
  4892. [Symbol.iterator]() {
  4893. return Array.from(this.queue)[Symbol.iterator]()
  4894. }
  4895. toString() {
  4896. return `MutableQueue(${Array.from(this).map(String).join(", ")})`
  4897. }
  4898. toJSON() {
  4899. return { _tag: "MutableQueue", values: Array.from(this) }
  4900. }
  4901. [Symbol.for("nodejs.util.inspect.custom")]() {
  4902. return this.toJSON()
  4903. }
  4904. }
  4905. const MutableQueue_isEmpty = self => MutableList_isEmpty(self.queue),
  4906. offer = Function_dual(2, (self, value) => {
  4907. const queueLength = MutableList_length(self.queue)
  4908. if (void 0 !== self.capacity && queueLength === self.capacity) return !1
  4909. MutableList_append(value)(self.queue)
  4910. return !0
  4911. }),
  4912. MutableQueue_poll = Function_dual(2, (self, def) =>
  4913. MutableList_isEmpty(self.queue)
  4914. ? def
  4915. : (self => {
  4916. const head = self.head
  4917. if (void 0 !== head) {
  4918. ;((self, node) => {
  4919. if (!node.removed) {
  4920. node.removed = !0
  4921. if (void 0 !== node.prev && void 0 !== node.next) {
  4922. node.prev.next = node.next
  4923. node.next.prev = node.prev
  4924. } else if (void 0 !== node.prev) {
  4925. self.tail = node.prev
  4926. node.prev.next = void 0
  4927. } else if (void 0 !== node.next) {
  4928. self.head = node.next
  4929. node.next.prev = void 0
  4930. } else {
  4931. self.tail = void 0
  4932. self.head = void 0
  4933. }
  4934. self._length > 0 && (self._length -= 1)
  4935. }
  4936. })(self, head)
  4937. return head.value
  4938. }
  4939. })(self.queue)
  4940. ),
  4941. renderToString = u => {
  4942. if (
  4943. "object" == typeof u &&
  4944. null != u &&
  4945. "toString" in u &&
  4946. "function" == typeof u.toString &&
  4947. u.toString !== Object.prototype.toString
  4948. )
  4949. return u.toString()
  4950. if ("string" == typeof u) return `Error: ${u}`
  4951. if (
  4952. "object" == typeof u &&
  4953. null !== u &&
  4954. "message" in u &&
  4955. "string" == typeof u.message
  4956. ) {
  4957. const raw = JSON.parse(JSON.stringify(u)),
  4958. keys = new Set(Object.keys(raw))
  4959. keys.delete("name")
  4960. keys.delete("message")
  4961. keys.delete("_tag")
  4962. if (0 === keys.size)
  4963. return `${
  4964. "name" in u && "string" == typeof u.name ? u.name : "Error"
  4965. }${
  4966. "_tag" in u && "string" == typeof u._tag ? `(${u._tag})` : ""
  4967. }: ${u.message}`
  4968. }
  4969. return `Error: ${JSON.stringify(u)}`
  4970. },
  4971. renderStack = span =>
  4972. Option_isNone(span)
  4973. ? []
  4974. : span.value.stack.length > 0
  4975. ? (chunk => {
  4976. const ret = []
  4977. for (const s of chunk) {
  4978. const r = s?.toFrame()
  4979. r &&
  4980. runtimeDebug.filterStackFrame(r) &&
  4981. ret.push(renderFrame(r))
  4982. }
  4983. return ret
  4984. })(span.value.stack)
  4985. : [],
  4986. defaultErrorToLines = error =>
  4987. error instanceof Error
  4988. ? (error => {
  4989. if (error.stack) {
  4990. const stack = runtimeDebug.parseStack(error),
  4991. traces = []
  4992. for (const frame of stack)
  4993. if (frame) {
  4994. if (!runtimeDebug.filterStackFrame(frame)) break
  4995. traces.push(renderFrame(frame))
  4996. }
  4997. return [renderToString(error), traces.join("\r\n")]
  4998. }
  4999. return [String(error), void 0]
  5000. })(error)
  5001. : [renderToString(error), void 0]
  5002. class RenderError {
  5003. constructor(seq, message, stack) {
  5004. this.seq = seq
  5005. this.message = message
  5006. this.stack = stack
  5007. }
  5008. }
  5009. const cause_pretty_pretty = cause => {
  5010. if (isInterruptedOnly(cause))
  5011. return "All fibers interrupted without errors."
  5012. const errors = prettyErrors(cause),
  5013. final = Array.from(errors)
  5014. .sort((a, b) => (a.seq === b.seq ? 0 : a.seq > b.seq ? 1 : -1))
  5015. .map(e => {
  5016. let message = e.message
  5017. e.stack && e.stack.length > 0 && (message += `\r\n${e.stack}`)
  5018. return message
  5019. })
  5020. .join("\r\n\r\n")
  5021. return final.includes("\r\n") ? `\r\n${final}\r\n` : final
  5022. },
  5023. prettyErrors = cause =>
  5024. reduceWithContext(cause, void 0, {
  5025. emptyCase: () => [],
  5026. dieCase: (_, err) => {
  5027. const rendered = defaultErrorToLines(err)
  5028. return [
  5029. {
  5030. message: rendered[0],
  5031. errorSack: rendered[1],
  5032. fiberStack: Option_none(),
  5033. },
  5034. ]
  5035. },
  5036. failCase: (_, err) => {
  5037. const rendered = defaultErrorToLines(err)
  5038. return [
  5039. {
  5040. message: rendered[0],
  5041. errorSack: rendered[1],
  5042. fiberStack: Option_none(),
  5043. },
  5044. ]
  5045. },
  5046. interruptCase: () => [],
  5047. parallelCase: (_, l, r) => [...l, ...r],
  5048. sequentialCase: (_, l, r) => [...l, ...r],
  5049. annotatedCase: (_, v, parent) =>
  5050. isStackAnnotation(parent)
  5051. ? v.map(r => ({
  5052. message: r.message,
  5053. errorSack: r.errorSack,
  5054. fiberStack: orElse(() => Option_some(parent))(
  5055. Option_map(
  5056. r.fiberStack,
  5057. annotation =>
  5058. new StackAnnotation(
  5059. annotation.stack.length <
  5060. runtimeDebug.traceStackLimit &&
  5061. parent.stack.length > 0 &&
  5062. ((annotation.stack.length > 0 &&
  5063. unsafeLast(parent.stack) !==
  5064. unsafeLast(annotation.stack)) ||
  5065. 0 === annotation.stack.length)
  5066. ? Chunk_take(runtimeDebug.traceStackLimit)(
  5067. dedupeAdjacent(
  5068. Chunk_concat(parent.stack)(annotation.stack)
  5069. )
  5070. )
  5071. : annotation.stack,
  5072. annotation.seq
  5073. )
  5074. )
  5075. ),
  5076. }))
  5077. : v,
  5078. }).flatMap(r =>
  5079. ((error, errorStack, stack) => [
  5080. new RenderError(
  5081. "Some" === stack._tag ? stack.value.seq : 0,
  5082. error,
  5083. errorStack
  5084. ? errorStack + "\r\n" + renderStack(stack).join("\r\n")
  5085. : renderStack(stack).join("\r\n")
  5086. ),
  5087. ])(r.message, r.errorSack, r.fiberStack)
  5088. )
  5089. function renderFrame(r) {
  5090. return r
  5091. ? r.name
  5092. ? ` at ${r.name} (${r.fileName}:${r.line}:${r.column})`
  5093. : ` at ${r.fileName}:${r.line}:${r.column}`
  5094. : " at <unknown>"
  5095. }
  5096. const LoggerTypeId = Symbol.for("@effect/io/Logger"),
  5097. loggerVariance = { _Message: _ => _, _Output: _ => _ },
  5098. makeLogger = log => ({ [LoggerTypeId]: loggerVariance, log }),
  5099. stringLogger = makeLogger(
  5100. (fiberId, logLevel, message, cause, _context, spans, annotations) => {
  5101. const now = new Date(),
  5102. nowMillis = now.getTime()
  5103. let output = [
  5104. `timestamp=${now.toISOString()}`,
  5105. `level=${logLevel.label}`,
  5106. `fiber=${threadName(fiberId)}`,
  5107. ].join(" ")
  5108. if (message.length > 0) {
  5109. output += " message="
  5110. output = appendQuoted(message, output)
  5111. }
  5112. if (null != cause && cause != cause_empty) {
  5113. output += " cause="
  5114. output = appendQuoted(cause_pretty_pretty(cause), output)
  5115. }
  5116. if (Chunk_isNonEmpty(spans)) {
  5117. output += " "
  5118. let first = !0
  5119. for (const span of spans) {
  5120. first ? (first = !1) : (output += " ")
  5121. output += Span_render(nowMillis)(span)
  5122. }
  5123. }
  5124. if (mjs_HashMap_size(annotations) > 0) {
  5125. output += " "
  5126. let first = !0
  5127. for (const [key, value] of annotations) {
  5128. first ? (first = !1) : (output += " ")
  5129. output += filterKeyName(key)
  5130. output += "="
  5131. output = appendQuoted(value, output)
  5132. }
  5133. }
  5134. return output
  5135. }
  5136. ),
  5137. textOnly = /^[^\s"=]+$/,
  5138. appendQuoted = (label, output) =>
  5139. output +
  5140. (label.match(textOnly)
  5141. ? label
  5142. : `"${label.replace(/\\([\s\S])|(")/g, "\\$1$2")}"`),
  5143. filterKeyName = key => key.replace(/[\s="]/g, "_"),
  5144. logger_zip = Function_dual(2, (self, that) =>
  5145. makeLogger(
  5146. (fiberId, logLevel, message, cause, context, spans, annotations) => [
  5147. self.log(
  5148. fiberId,
  5149. logLevel,
  5150. message,
  5151. cause,
  5152. context,
  5153. spans,
  5154. annotations
  5155. ),
  5156. that.log(
  5157. fiberId,
  5158. logLevel,
  5159. message,
  5160. cause,
  5161. context,
  5162. spans,
  5163. annotations
  5164. ),
  5165. ]
  5166. )
  5167. )
  5168. var keyType_a, keyType_b, _g, _h
  5169. const MetricKeyTypeTypeId = Symbol.for("@effect/io/Metric/KeyType"),
  5170. CounterKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Counter"),
  5171. FrequencyKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Frequency"),
  5172. GaugeKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Gauge"),
  5173. HistogramKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Histogram"),
  5174. SummaryKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Summary"),
  5175. metricKeyTypeVariance = { _In: _ => _, _Out: _ => _ }
  5176. class CounterKeyType {
  5177. constructor() {
  5178. this[keyType_a] = metricKeyTypeVariance
  5179. this[keyType_b] = CounterKeyTypeTypeId
  5180. }
  5181. [((keyType_a = MetricKeyTypeTypeId),
  5182. (keyType_b = CounterKeyTypeTypeId),
  5183. symbol)]() {
  5184. return Hash_hash("effect/io/Metric/KeyType/Counter")
  5185. }
  5186. [Equal_symbol](that) {
  5187. return isCounterKey(that)
  5188. }
  5189. }
  5190. class HistogramKeyType {
  5191. constructor(boundaries) {
  5192. this.boundaries = boundaries
  5193. this[_g] = metricKeyTypeVariance
  5194. this[_h] = HistogramKeyTypeTypeId
  5195. }
  5196. [((_g = MetricKeyTypeTypeId), (_h = HistogramKeyTypeTypeId), symbol)]() {
  5197. return combine(Hash_hash(this.boundaries))(
  5198. Hash_hash("effect/io/Metric/KeyType/Histogram")
  5199. )
  5200. }
  5201. [Equal_symbol](that) {
  5202. return isHistogramKey(that) && equals(this.boundaries, that.boundaries)
  5203. }
  5204. }
  5205. const counter = new CounterKeyType(),
  5206. isCounterKey = u =>
  5207. "object" == typeof u && null != u && CounterKeyTypeTypeId in u,
  5208. isFrequencyKey = u =>
  5209. "object" == typeof u && null != u && FrequencyKeyTypeTypeId in u,
  5210. isGaugeKey = u =>
  5211. "object" == typeof u && null != u && GaugeKeyTypeTypeId in u,
  5212. isHistogramKey = u =>
  5213. "object" == typeof u && null != u && HistogramKeyTypeTypeId in u,
  5214. isSummaryKey = u =>
  5215. "object" == typeof u && null != u && SummaryKeyTypeTypeId in u
  5216. var key_a
  5217. const MetricKeyTypeId = Symbol.for("@effect/io/Metric/Key"),
  5218. metricKeyVariance = { _Type: _ => _ }
  5219. class MetricKeyImpl {
  5220. constructor(name, keyType, tags = mjs_HashSet_empty()) {
  5221. this.name = name
  5222. this.keyType = keyType
  5223. this.tags = tags
  5224. this[key_a] = metricKeyVariance
  5225. }
  5226. [((key_a = MetricKeyTypeId), symbol)]() {
  5227. return combine(Hash_hash(this.tags))(
  5228. combine(Hash_hash(this.keyType))(Hash_hash(this.name))
  5229. )
  5230. }
  5231. [Equal_symbol](u) {
  5232. return (
  5233. isMetricKey(u) &&
  5234. this.name === u.name &&
  5235. equals(this.keyType, u.keyType) &&
  5236. equals(this.tags, u.tags)
  5237. )
  5238. }
  5239. }
  5240. const isMetricKey = u =>
  5241. "object" == typeof u && null != u && MetricKeyTypeId in u,
  5242. key_taggedWithLabelSet = Function_dual(2, (self, extraTags) =>
  5243. 0 === mjs_HashSet_size(extraTags)
  5244. ? self
  5245. : new MetricKeyImpl(
  5246. self.name,
  5247. self.keyType,
  5248. mjs_HashSet_union(extraTags)(self.tags)
  5249. )
  5250. )
  5251. var state_a,
  5252. state_b,
  5253. state_c,
  5254. state_d,
  5255. state_e,
  5256. state_f,
  5257. state_g,
  5258. state_h,
  5259. state_j,
  5260. state_k
  5261. const MetricStateTypeId = Symbol.for("@effect/io/Metric/State"),
  5262. CounterStateTypeId = Symbol.for("effect/io/Metric/State/Counter"),
  5263. FrequencyStateTypeId = Symbol.for("effect/io/Metric/State/Frequency"),
  5264. GaugeStateTypeId = Symbol.for("effect/io/Metric/State/Gauge"),
  5265. HistogramStateTypeId = Symbol.for("effect/io/Metric/State/Histogram"),
  5266. SummaryStateTypeId = Symbol.for("effect/io/Metric/State/Summary"),
  5267. metricStateVariance = { _A: _ => _ }
  5268. class CounterState {
  5269. constructor(count) {
  5270. this.count = count
  5271. this[state_a] = metricStateVariance
  5272. this[state_b] = CounterStateTypeId
  5273. }
  5274. [((state_a = MetricStateTypeId),
  5275. (state_b = CounterStateTypeId),
  5276. symbol)]() {
  5277. return combine(Hash_hash(this.count))(
  5278. Hash_hash("effect/io/Metric/State/Counter")
  5279. )
  5280. }
  5281. [Equal_symbol](that) {
  5282. return isCounterState(that) && this.count === that.count
  5283. }
  5284. }
  5285. class FrequencyState {
  5286. constructor(occurrences) {
  5287. this.occurrences = occurrences
  5288. this[state_c] = metricStateVariance
  5289. this[state_d] = FrequencyStateTypeId
  5290. }
  5291. [((state_c = MetricStateTypeId),
  5292. (state_d = FrequencyStateTypeId),
  5293. symbol)]() {
  5294. return combine(Hash_hash(this.occurrences))(
  5295. Hash_hash("effect/io/Metric/State/Frequency")
  5296. )
  5297. }
  5298. [Equal_symbol](that) {
  5299. return (
  5300. isFrequencyState(that) && equals(this.occurrences, that.occurrences)
  5301. )
  5302. }
  5303. }
  5304. class GaugeState {
  5305. constructor(value) {
  5306. this.value = value
  5307. this[state_e] = metricStateVariance
  5308. this[state_f] = GaugeStateTypeId
  5309. }
  5310. [((state_e = MetricStateTypeId),
  5311. (state_f = GaugeStateTypeId),
  5312. symbol)]() {
  5313. return combine(Hash_hash(this.value))(
  5314. Hash_hash("effect/io/Metric/State/Gauge")
  5315. )
  5316. }
  5317. [Equal_symbol](u) {
  5318. return isGaugeState(u) && this.value === u.value
  5319. }
  5320. }
  5321. class HistogramState {
  5322. constructor(buckets, count, min, max, sum) {
  5323. this.buckets = buckets
  5324. this.count = count
  5325. this.min = min
  5326. this.max = max
  5327. this.sum = sum
  5328. this[state_g] = metricStateVariance
  5329. this[state_h] = HistogramStateTypeId
  5330. }
  5331. [((state_g = MetricStateTypeId),
  5332. (state_h = HistogramStateTypeId),
  5333. symbol)]() {
  5334. return combine(Hash_hash(this.sum))(
  5335. combine(Hash_hash(this.max))(
  5336. combine(Hash_hash(this.min))(
  5337. combine(Hash_hash(this.count))(
  5338. combine(Hash_hash(this.buckets))(
  5339. Hash_hash("effect/io/Metric/State/Histogram")
  5340. )
  5341. )
  5342. )
  5343. )
  5344. )
  5345. }
  5346. [Equal_symbol](that) {
  5347. return (
  5348. isHistogramState(that) &&
  5349. equals(this.buckets, that.buckets) &&
  5350. this.count === that.count &&
  5351. this.min === that.min &&
  5352. this.max === that.max &&
  5353. this.sum === that.sum
  5354. )
  5355. }
  5356. }
  5357. class SummaryState {
  5358. constructor(error, quantiles, count, min, max, sum) {
  5359. this.error = error
  5360. this.quantiles = quantiles
  5361. this.count = count
  5362. this.min = min
  5363. this.max = max
  5364. this.sum = sum
  5365. this[state_j] = metricStateVariance
  5366. this[state_k] = SummaryStateTypeId
  5367. }
  5368. [((state_j = MetricStateTypeId),
  5369. (state_k = SummaryStateTypeId),
  5370. symbol)]() {
  5371. return combine(Hash_hash(this.sum))(
  5372. combine(Hash_hash(this.max))(
  5373. combine(Hash_hash(this.min))(
  5374. combine(Hash_hash(this.count))(
  5375. combine(Hash_hash(this.quantiles))(
  5376. combine(Hash_hash(this.error))(
  5377. Hash_hash("effect/io/Metric/State/Summary")
  5378. )
  5379. )
  5380. )
  5381. )
  5382. )
  5383. )
  5384. }
  5385. [Equal_symbol](that) {
  5386. return (
  5387. isSummaryState(that) &&
  5388. this.error === that.error &&
  5389. equals(this.quantiles, that.quantiles) &&
  5390. this.count === that.count &&
  5391. this.min === that.min &&
  5392. this.max === that.max &&
  5393. this.sum === that.sum
  5394. )
  5395. }
  5396. }
  5397. const isCounterState = u =>
  5398. "object" == typeof u && null != u && CounterStateTypeId in u,
  5399. isFrequencyState = u =>
  5400. "object" == typeof u && null != u && FrequencyStateTypeId in u,
  5401. isGaugeState = u =>
  5402. "object" == typeof u && null != u && GaugeStateTypeId in u,
  5403. isHistogramState = u =>
  5404. "object" == typeof u && null != u && HistogramStateTypeId in u,
  5405. isSummaryState = u =>
  5406. "object" == typeof u && null != u && SummaryStateTypeId in u,
  5407. MetricHookTypeId = Symbol.for("@effect/io/Metric/Hook"),
  5408. metricHookVariance = { _In: _ => _, _Out: _ => _ },
  5409. hook_make = (get, update) => ({
  5410. [MetricHookTypeId]: metricHookVariance,
  5411. update,
  5412. get,
  5413. }),
  5414. calculateQuantiles = (error, sortedQuantiles, sortedSamples) => {
  5415. const sampleCount = sortedSamples.length
  5416. if (Chunk_isEmpty(sortedQuantiles)) return Chunk_empty()
  5417. const head = unsafeHead(sortedQuantiles),
  5418. tail = Chunk_drop(1)(sortedQuantiles),
  5419. resolved = Chunk_reduce(
  5420. Chunk_of(
  5421. resolveQuantile(
  5422. error,
  5423. sampleCount,
  5424. Option_none(),
  5425. 0,
  5426. head,
  5427. sortedSamples
  5428. )
  5429. ),
  5430. (accumulator, quantile) => {
  5431. const h = unsafeHead(accumulator)
  5432. return Chunk_append(
  5433. resolveQuantile(
  5434. error,
  5435. sampleCount,
  5436. h.value,
  5437. h.consumed,
  5438. quantile,
  5439. h.rest
  5440. )
  5441. )(accumulator)
  5442. }
  5443. )(tail)
  5444. return Chunk_map(rq => [rq.quantile, rq.value])(resolved)
  5445. },
  5446. resolveQuantile = (
  5447. error,
  5448. sampleCount,
  5449. current,
  5450. consumed,
  5451. quantile,
  5452. rest
  5453. ) => {
  5454. let error_1 = error,
  5455. sampleCount_1 = sampleCount,
  5456. current_1 = current,
  5457. consumed_1 = consumed,
  5458. quantile_1 = quantile,
  5459. rest_1 = rest,
  5460. error_2 = error,
  5461. sampleCount_2 = sampleCount,
  5462. current_2 = current,
  5463. consumed_2 = consumed,
  5464. quantile_2 = quantile,
  5465. rest_2 = rest
  5466. for (;;) {
  5467. if (Chunk_isEmpty(rest_1))
  5468. return {
  5469. quantile: quantile_1,
  5470. value: Option_none(),
  5471. consumed: consumed_1,
  5472. rest: Chunk_empty(),
  5473. }
  5474. if (1 === quantile_1)
  5475. return {
  5476. quantile: quantile_1,
  5477. value: Option_some(unsafeLast(rest_1)),
  5478. consumed: consumed_1 + rest_1.length,
  5479. rest: Chunk_empty(),
  5480. }
  5481. const sameHead = splitWhere(n => n > unsafeHead(rest_1))(rest_1),
  5482. desired = quantile_1 * sampleCount_1,
  5483. allowedError = (error_1 / 2) * desired,
  5484. candConsumed = consumed_1 + sameHead[0].length,
  5485. candError = Math.abs(candConsumed - desired)
  5486. if (candConsumed < desired - allowedError) {
  5487. error_2 = error_1
  5488. sampleCount_2 = sampleCount_1
  5489. current_2 = Chunk_head(rest_1)
  5490. consumed_2 = candConsumed
  5491. quantile_2 = quantile_1
  5492. rest_2 = sameHead[1]
  5493. error_1 = error_2
  5494. sampleCount_1 = sampleCount_2
  5495. current_1 = current_2
  5496. consumed_1 = consumed_2
  5497. quantile_1 = quantile_2
  5498. rest_1 = rest_2
  5499. } else {
  5500. if (candConsumed > desired + allowedError)
  5501. return {
  5502. quantile: quantile_1,
  5503. value: current_1,
  5504. consumed: consumed_1,
  5505. rest: rest_1,
  5506. }
  5507. switch (current_1._tag) {
  5508. case "None":
  5509. error_2 = error_1
  5510. sampleCount_2 = sampleCount_1
  5511. current_2 = Chunk_head(rest_1)
  5512. consumed_2 = candConsumed
  5513. quantile_2 = quantile_1
  5514. rest_2 = sameHead[1]
  5515. error_1 = error_2
  5516. sampleCount_1 = sampleCount_2
  5517. current_1 = current_2
  5518. consumed_1 = consumed_2
  5519. quantile_1 = quantile_2
  5520. rest_1 = rest_2
  5521. continue
  5522. case "Some":
  5523. if (candError < Math.abs(desired - current_1.value)) {
  5524. error_2 = error_1
  5525. sampleCount_2 = sampleCount_1
  5526. current_2 = Chunk_head(rest_1)
  5527. consumed_2 = candConsumed
  5528. quantile_2 = quantile_1
  5529. rest_2 = sameHead[1]
  5530. error_1 = error_2
  5531. sampleCount_1 = sampleCount_2
  5532. current_1 = current_2
  5533. consumed_1 = consumed_2
  5534. quantile_1 = quantile_2
  5535. rest_1 = rest_2
  5536. continue
  5537. }
  5538. return {
  5539. quantile: quantile_1,
  5540. value: Option_some(current_1.value),
  5541. consumed: consumed_1,
  5542. rest: rest_1,
  5543. }
  5544. }
  5545. }
  5546. }
  5547. throw new Error(
  5548. "BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/io/issues"
  5549. )
  5550. },
  5551. MetricPairTypeId = Symbol.for("@effect/io/Metric/Pair"),
  5552. metricPairVariance = { _Type: _ => _ }
  5553. var registry_a
  5554. const MetricRegistryTypeId = Symbol.for("@effect/io/Metric/Registry")
  5555. class MetricRegistryImpl {
  5556. constructor() {
  5557. this[registry_a] = MetricRegistryTypeId
  5558. this.map = new MutableHashMapImpl()
  5559. }
  5560. snapshot() {
  5561. const result = []
  5562. for (const [key, hook] of this.map)
  5563. result.push(
  5564. ((metricKey = key),
  5565. (metricState = hook.get()),
  5566. { [MetricPairTypeId]: metricPairVariance, metricKey, metricState })
  5567. )
  5568. var metricKey, metricState
  5569. return (elements => {
  5570. const set = HashSet_beginMutation(HashSet_empty())
  5571. for (const value of elements) HashSet_add(set, value)
  5572. return HashSet_endMutation(set)
  5573. })(result)
  5574. }
  5575. get(key) {
  5576. const hook = getOrUndefined(MutableHashMap_get(key)(this.map))
  5577. if (null == hook) {
  5578. if (isCounterKey(key.keyType)) return this.getCounter(key)
  5579. if (isGaugeKey(key.keyType)) return this.getGauge(key)
  5580. if (isFrequencyKey(key.keyType)) return this.getFrequency(key)
  5581. if (isHistogramKey(key.keyType)) return this.getHistogram(key)
  5582. if (isSummaryKey(key.keyType)) return this.getSummary(key)
  5583. throw new Error(
  5584. "BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/io/issues"
  5585. )
  5586. }
  5587. return hook
  5588. }
  5589. getCounter(key) {
  5590. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5591. if (null == value) {
  5592. const counter = (_key => {
  5593. let sum = 0
  5594. return hook_make(
  5595. () => new CounterState(sum),
  5596. value => {
  5597. sum += value
  5598. }
  5599. )
  5600. })()
  5601. MutableHashMap_has(key)(this.map) ||
  5602. MutableHashMap_set(key, counter)(this.map)
  5603. value = counter
  5604. }
  5605. return value
  5606. }
  5607. getFrequency(key) {
  5608. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5609. if (null == value) {
  5610. const frequency = (_key => {
  5611. let count = 0
  5612. const values = new Map()
  5613. return hook_make(
  5614. () => {
  5615. return (
  5616. (occurrences = mjs_HashMap_fromIterable(
  5617. Array.from(values.entries()).map(([k, v]) => [k, v])
  5618. )),
  5619. new FrequencyState(occurrences)
  5620. )
  5621. var occurrences
  5622. },
  5623. word => {
  5624. count += 1
  5625. const slotCount = values.get(word) ?? 0
  5626. values.set(word, slotCount + 1)
  5627. }
  5628. )
  5629. })()
  5630. MutableHashMap_has(key)(this.map) ||
  5631. MutableHashMap_set(key, frequency)(this.map)
  5632. value = frequency
  5633. }
  5634. return value
  5635. }
  5636. getGauge(key) {
  5637. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5638. if (null == value) {
  5639. const gauge = ((_key, startAt) => {
  5640. let value = startAt
  5641. return hook_make(
  5642. () => (value => new GaugeState(value))(value),
  5643. v => {
  5644. value = v
  5645. }
  5646. )
  5647. })(0, 0)
  5648. MutableHashMap_has(key)(this.map) ||
  5649. MutableHashMap_set(key, gauge)(this.map)
  5650. value = gauge
  5651. }
  5652. return value
  5653. }
  5654. getHistogram(key) {
  5655. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5656. if (null == value) {
  5657. const histogram = (key => {
  5658. const bounds = key.keyType.boundaries.values,
  5659. size = bounds.length,
  5660. values = Array(size + 1),
  5661. boundaries = Array(size)
  5662. let count = 0,
  5663. sum = 0,
  5664. min = Number.MAX_VALUE,
  5665. max = Number.MIN_VALUE
  5666. mapWithIndex((i, n) => {
  5667. boundaries[i] = n
  5668. })(Chunk_sort(Order)(bounds))
  5669. return hook_make(
  5670. () =>
  5671. ((buckets, count, min, max, sum) =>
  5672. new HistogramState(buckets, count, min, max, sum))(
  5673. (() => {
  5674. const builder = []
  5675. let i = 0,
  5676. cumulated = 0
  5677. for (; i != size; ) {
  5678. const boundary = boundaries[i]
  5679. cumulated += values[i]
  5680. builder.push([boundary, cumulated])
  5681. i += 1
  5682. }
  5683. return Chunk_fromIterable(builder)
  5684. })(),
  5685. count,
  5686. min,
  5687. max,
  5688. sum
  5689. ),
  5690. value => {
  5691. let from = 0,
  5692. to = size
  5693. for (; from !== to; ) {
  5694. const mid = Math.floor(from + (to - from) / 2)
  5695. value <= boundaries[mid] ? (to = mid) : (from = mid)
  5696. to === from + 1 &&
  5697. (value <= boundaries[from] ? (to = from) : (from = to))
  5698. }
  5699. values[from] = values[from] + 1
  5700. count += 1
  5701. sum += value
  5702. value < min && (min = value)
  5703. value > max && (max = value)
  5704. }
  5705. )
  5706. })(key)
  5707. MutableHashMap_has(key)(this.map) ||
  5708. MutableHashMap_set(key, histogram)(this.map)
  5709. value = histogram
  5710. }
  5711. return value
  5712. }
  5713. getSummary(key) {
  5714. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  5715. if (null == value) {
  5716. const summary = (key => {
  5717. const { error, maxAge, maxSize, quantiles } = key.keyType,
  5718. sortedQuantiles = Chunk_sort(Order)(quantiles),
  5719. values = Array(maxSize)
  5720. let head = 0,
  5721. count = 0,
  5722. sum = 0,
  5723. min = Number.MAX_VALUE,
  5724. max = Number.MIN_VALUE
  5725. return hook_make(
  5726. () =>
  5727. ((error, quantiles, count, min, max, sum) =>
  5728. new SummaryState(error, quantiles, count, min, max, sum))(
  5729. error,
  5730. (now => {
  5731. const builder = []
  5732. let i = 0
  5733. for (; i !== maxSize - 1; ) {
  5734. const item = values[i]
  5735. if (null != item) {
  5736. const [t, v] = item,
  5737. age = millis(now - t)
  5738. age.millis >= 0 && age <= maxAge && builder.push(v)
  5739. }
  5740. i += 1
  5741. }
  5742. return calculateQuantiles(
  5743. error,
  5744. sortedQuantiles,
  5745. Chunk_sort(Order)(Chunk_fromIterable(builder))
  5746. )
  5747. })(Date.now()),
  5748. count,
  5749. min,
  5750. max,
  5751. sum
  5752. ),
  5753. ([value, timestamp]) =>
  5754. ((value, timestamp) => {
  5755. if (maxSize > 0) {
  5756. head += 1
  5757. values[head % maxSize] = [timestamp, value]
  5758. }
  5759. count += 1
  5760. sum += value
  5761. value < min && (min = value)
  5762. value > max && (max = value)
  5763. })(value, timestamp)
  5764. )
  5765. })(key)
  5766. MutableHashMap_has(key)(this.map) ||
  5767. MutableHashMap_set(key, summary)(this.map)
  5768. value = summary
  5769. }
  5770. return value
  5771. }
  5772. }
  5773. registry_a = MetricRegistryTypeId
  5774. const MetricTypeId = Symbol.for("@effect/io/Metric"),
  5775. metricVariance = { _Type: _ => _, _In: _ => _, _Out: _ => _ },
  5776. globalMetricRegistry = globalValue(
  5777. Symbol.for("@effect/io/Metric/globalMetricRegistry"),
  5778. () => new MetricRegistryImpl()
  5779. ),
  5780. metric_counter = name =>
  5781. fromMetricKey((name => new MetricKeyImpl(name, counter))(name)),
  5782. fromMetricKey = key => {
  5783. const hook = extraTags => {
  5784. const fullKey = key_taggedWithLabelSet(extraTags)(key)
  5785. return globalMetricRegistry.get(fullKey)
  5786. }
  5787. return (function (keyType, unsafeUpdate, unsafeValue) {
  5788. const metric = Object.assign(
  5789. methodWithTrace(
  5790. (trace, restore) => effect =>
  5791. core_tap(effect, a =>
  5792. sync(() => restore(unsafeUpdate)(a, mjs_HashSet_empty()))
  5793. ).traced(trace)
  5794. ),
  5795. {
  5796. [MetricTypeId]: metricVariance,
  5797. keyType,
  5798. unsafeUpdate,
  5799. unsafeValue,
  5800. }
  5801. )
  5802. return metric
  5803. })(
  5804. key.keyType,
  5805. (input, extraTags) => hook(extraTags).update(input),
  5806. extraTags => hook(extraTags).get()
  5807. )
  5808. },
  5809. metric_histogram = (name, boundaries) =>
  5810. fromMetricKey(
  5811. ((name, boundaries) =>
  5812. new MetricKeyImpl(
  5813. name,
  5814. (boundaries => new HistogramKeyType(boundaries))(boundaries)
  5815. ))(name, boundaries)
  5816. )
  5817. var boundaries_a
  5818. const MetricBoundariesTypeId = Symbol.for("@effect/io/Metric/Boundaries")
  5819. class MetricBoundariesImpl {
  5820. constructor(values) {
  5821. this.values = values
  5822. this[boundaries_a] = MetricBoundariesTypeId
  5823. }
  5824. [((boundaries_a = MetricBoundariesTypeId), symbol)]() {
  5825. return combine(Hash_hash(this.values))(
  5826. Hash_hash("@effect/io/Metric/Boundaries")
  5827. )
  5828. }
  5829. [Equal_symbol](u) {
  5830. return isMetricBoundaries(u) && equals(this.values, u.values)
  5831. }
  5832. }
  5833. const isMetricBoundaries = u =>
  5834. "object" == typeof u && null != u && MetricBoundariesTypeId in u,
  5835. fromChunk = chunk => {
  5836. const values = (self =>
  5837. unsafeFromArray(
  5838. uniq(
  5839. (self, that) =>
  5840. Hash_hash(self) === Hash_hash(that) && equals(self, that)
  5841. )(toReadonlyArray(self))
  5842. ))(Chunk_concat(Chunk_of(Number.POSITIVE_INFINITY))(chunk))
  5843. return new MetricBoundariesImpl(values)
  5844. },
  5845. exponential = (start, factor, count) => {
  5846. return fromChunk(
  5847. Chunk_map(i => start * Math.pow(factor, i))(
  5848. 0 <= (end = count - 1)
  5849. ? Chunk_makeBy(end - 0 + 1, i => 0 + i)
  5850. : Chunk_of(0)
  5851. )
  5852. )
  5853. var end
  5854. }
  5855. var supervisor_a, supervisor_b, supervisor_d
  5856. const SupervisorTypeId = Symbol.for("@effect/io/Supervisor"),
  5857. supervisorVariance = { _T: _ => _ }
  5858. class ProxySupervisor {
  5859. constructor(underlying, value0) {
  5860. this.underlying = underlying
  5861. this.value0 = value0
  5862. this[supervisor_a] = supervisorVariance
  5863. }
  5864. value() {
  5865. return bodyWithTrace(trace => this.value0().traced(trace))
  5866. }
  5867. onStart(context, effect, parent, fiber) {
  5868. this.underlying.onStart(context, effect, parent, fiber)
  5869. }
  5870. onEnd(value, fiber) {
  5871. this.underlying.onEnd(value, fiber)
  5872. }
  5873. onEffect(fiber, effect) {
  5874. this.underlying.onEffect(fiber, effect)
  5875. }
  5876. onSuspend(fiber) {
  5877. this.underlying.onSuspend(fiber)
  5878. }
  5879. onResume(fiber) {
  5880. this.underlying.onResume(fiber)
  5881. }
  5882. map(f) {
  5883. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  5884. }
  5885. zip(right) {
  5886. return new Zip(this, right)
  5887. }
  5888. }
  5889. supervisor_a = SupervisorTypeId
  5890. class Zip {
  5891. constructor(left, right) {
  5892. this.left = left
  5893. this.right = right
  5894. this[supervisor_b] = supervisorVariance
  5895. }
  5896. value() {
  5897. return bodyWithTrace(trace =>
  5898. core_zip(this.left.value(), this.right.value()).traced(trace)
  5899. )
  5900. }
  5901. onStart(context, effect, parent, fiber) {
  5902. this.left.onStart(context, effect, parent, fiber)
  5903. this.right.onStart(context, effect, parent, fiber)
  5904. }
  5905. onEnd(value, fiber) {
  5906. this.left.onEnd(value, fiber)
  5907. this.right.onEnd(value, fiber)
  5908. }
  5909. onEffect(fiber, effect) {
  5910. this.left.onEffect(fiber, effect)
  5911. this.right.onEffect(fiber, effect)
  5912. }
  5913. onSuspend(fiber) {
  5914. this.left.onSuspend(fiber)
  5915. this.right.onSuspend(fiber)
  5916. }
  5917. onResume(fiber) {
  5918. this.left.onResume(fiber)
  5919. this.right.onResume(fiber)
  5920. }
  5921. map(f) {
  5922. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  5923. }
  5924. zip(right) {
  5925. return new Zip(this, right)
  5926. }
  5927. }
  5928. supervisor_b = SupervisorTypeId
  5929. class Const {
  5930. constructor(effect) {
  5931. this.effect = effect
  5932. this[supervisor_d] = supervisorVariance
  5933. }
  5934. value() {
  5935. return bodyWithTrace(trace => this.effect.traced(trace))
  5936. }
  5937. onStart(_context, _effect, _parent, _fiber) {}
  5938. onEnd(_value, _fiber) {}
  5939. onEffect(_fiber, _effect) {}
  5940. onSuspend(_fiber) {}
  5941. onResume(_fiber) {}
  5942. map(f) {
  5943. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  5944. }
  5945. zip(right) {
  5946. return new Zip(this, right)
  5947. }
  5948. }
  5949. supervisor_d = SupervisorTypeId
  5950. const supervisor_none = (effect => new Const(effect))(core_unit()),
  5951. supervisor_patch_empty = { _tag: "Empty" },
  5952. supervisor_patch_combine = (self, that) => ({
  5953. _tag: "AndThen",
  5954. first: self,
  5955. second: that,
  5956. }),
  5957. removeSupervisor = (self, that) =>
  5958. equals(self, that)
  5959. ? supervisor_none
  5960. : self instanceof Zip
  5961. ? removeSupervisor(self.left, that).zip(
  5962. removeSupervisor(self.right, that)
  5963. )
  5964. : self,
  5965. patch_toSet = self =>
  5966. equals(self, supervisor_none)
  5967. ? mjs_HashSet_empty()
  5968. : self instanceof Zip
  5969. ? mjs_HashSet_union(patch_toSet(self.right))(patch_toSet(self.left))
  5970. : mjs_HashSet_make(self),
  5971. patch_differ = mjs_Differ_make({
  5972. empty: supervisor_patch_empty,
  5973. patch: (self, supervisor) =>
  5974. ((_supervisor, _patches) => {
  5975. let supervisor = _supervisor,
  5976. patches = _patches
  5977. for (; Chunk_isNonEmpty(patches); ) {
  5978. const head = Chunk_headNonEmpty(patches)
  5979. switch (head._tag) {
  5980. case "Empty":
  5981. patches = Chunk_tailNonEmpty(patches)
  5982. break
  5983. case "AddSupervisor":
  5984. supervisor = supervisor.zip(head.supervisor)
  5985. patches = Chunk_tailNonEmpty(patches)
  5986. break
  5987. case "RemoveSupervisor":
  5988. supervisor = removeSupervisor(supervisor, head.supervisor)
  5989. patches = Chunk_tailNonEmpty(patches)
  5990. break
  5991. case "AndThen":
  5992. patches = Chunk_prepend(head.first)(
  5993. Chunk_prepend(head.second)(Chunk_tailNonEmpty(patches))
  5994. )
  5995. }
  5996. }
  5997. return supervisor
  5998. })(supervisor, Chunk_of(self)),
  5999. combine: supervisor_patch_combine,
  6000. diff: (oldValue, newValue) => {
  6001. if (equals(oldValue, newValue)) return supervisor_patch_empty
  6002. const oldSupervisors = patch_toSet(oldValue),
  6003. newSupervisors = patch_toSet(newValue),
  6004. added = mjs_HashSet_reduce(
  6005. supervisor_patch_empty,
  6006. (patch, supervisor) =>
  6007. supervisor_patch_combine(patch, {
  6008. _tag: "AddSupervisor",
  6009. supervisor,
  6010. })
  6011. )(mjs_HashSet_difference(oldSupervisors)(newSupervisors)),
  6012. removed = mjs_HashSet_reduce(
  6013. supervisor_patch_empty,
  6014. (patch, supervisor) =>
  6015. supervisor_patch_combine(patch, {
  6016. _tag: "RemoveSupervisor",
  6017. supervisor,
  6018. })
  6019. )(mjs_HashSet_difference(newSupervisors)(oldSupervisors))
  6020. return supervisor_patch_combine(added, removed)
  6021. },
  6022. })
  6023. var fiberRuntime_a, fiberRuntime_b
  6024. const fibersStarted = metric_counter("effect_fiber_started"),
  6025. fiberSuccesses = metric_counter("effect_fiber_successes"),
  6026. fiberFailures = metric_counter("effect_fiber_failures"),
  6027. fiberLifetimes = metric_histogram(
  6028. "effect_fiber_lifetimes",
  6029. exponential(1, 2, 100)
  6030. ),
  6031. runtimeFiberVariance = { _E: _ => _, _A: _ => _ },
  6032. fiberRuntime_absurd = _ => {
  6033. throw new Error(
  6034. `BUG: FiberRuntime - ${JSON.stringify(
  6035. _
  6036. )} - please report an issue at https://github.com/Effect-TS/io/issues`
  6037. )
  6038. },
  6039. contOpSuccess = {
  6040. OnSuccess: (_, cont, value) => cont.i1(value),
  6041. OnSuccessAndFailure: (_, cont, value) => cont.i2(value),
  6042. RevertFlags: (self, cont, value) => {
  6043. self.patchRuntimeFlags(self._runtimeFlags, cont.patch)
  6044. return interruptible(self._runtimeFlags) && self.isInterrupted()
  6045. ? exitFailCause(self.getInterruptedCause())
  6046. : exitSucceed(value)
  6047. },
  6048. While: (self, cont, value) => {
  6049. cont.i2(value)
  6050. if (cont.i0()) {
  6051. self.pushStack(cont)
  6052. return cont.i1()
  6053. }
  6054. return core_unit()
  6055. },
  6056. },
  6057. drainQueueWhileRunningTable = {
  6058. InterruptSignal: (self, runtimeFlags, cur, message) => {
  6059. self.processNewInterruptSignal(message.cause)
  6060. return interruptible(runtimeFlags)
  6061. ? exitFailCause(message.cause)
  6062. : cur
  6063. },
  6064. Resume: (_self, _runtimeFlags, _cur, _message) => {
  6065. throw new Error(
  6066. "It is illegal to have multiple concurrent run loops in a single fiber"
  6067. )
  6068. },
  6069. Stateful: (self, runtimeFlags, cur, message) => {
  6070. message.onFiber(self, Status_running(runtimeFlags))
  6071. return cur
  6072. },
  6073. YieldNow: (_self, _runtimeFlags, cur, _message) =>
  6074. core_flatMap(() => cur)(yieldNow()),
  6075. }
  6076. class FiberRuntime {
  6077. constructor(fiberId, fiberRefs0, runtimeFlags0) {
  6078. this[fiberRuntime_a] = fiberVariance
  6079. this[fiberRuntime_b] = runtimeFiberVariance
  6080. this._queue = new MutableQueueImpl()
  6081. this._children = null
  6082. this._observers = new Array()
  6083. this._running = !1
  6084. this._stack = []
  6085. this._asyncInterruptor = null
  6086. this._asyncBlockingOn = null
  6087. this._exitValue = null
  6088. this._traceStack = []
  6089. this.run = () => {
  6090. this.drainQueueOnCurrentThread()
  6091. }
  6092. this._runtimeFlags = runtimeFlags0
  6093. this._fiberId = fiberId
  6094. this._fiberRefs = fiberRefs0
  6095. if (runtimeMetrics(runtimeFlags0)) {
  6096. const tags = this.getFiberRef(currentTags)
  6097. fibersStarted.unsafeUpdate(1, tags)
  6098. }
  6099. }
  6100. id() {
  6101. return this._fiberId
  6102. }
  6103. resume(effect) {
  6104. this.tell(resume(effect))
  6105. }
  6106. status() {
  6107. return this.ask((_, status) => status)
  6108. }
  6109. runtimeFlags() {
  6110. return this.ask((state, status) =>
  6111. (self => "Done" === self._tag)(status)
  6112. ? state._runtimeFlags
  6113. : status.runtimeFlags
  6114. )
  6115. }
  6116. scope() {
  6117. return new Local((fiber = this).id(), fiber)
  6118. var fiber
  6119. }
  6120. children() {
  6121. return this.ask(fiber => Chunk_fromIterable(fiber.getChildren()))
  6122. }
  6123. getChildren() {
  6124. null === this._children && (this._children = new Set())
  6125. return this._children
  6126. }
  6127. getSupervisor() {
  6128. return this.getFiberRef(currentSupervisor)
  6129. }
  6130. getInterruptedCause() {
  6131. return this.getFiberRef(interruptedCause)
  6132. }
  6133. fiberRefs() {
  6134. return this.ask(fiber => fiber.unsafeGetFiberRefs())
  6135. }
  6136. ask(f) {
  6137. return untraced(() =>
  6138. suspend(() => {
  6139. const deferred = deferredUnsafeMake(this._fiberId)
  6140. this.tell(
  6141. stateful((fiber, status) => {
  6142. deferredUnsafeDone(
  6143. deferred,
  6144. sync(() => f(fiber, status))
  6145. )
  6146. })
  6147. )
  6148. return deferredAwait(deferred)
  6149. })
  6150. )
  6151. }
  6152. tell(message) {
  6153. offer(message)(this._queue)
  6154. if (!this._running) {
  6155. this._running = !0
  6156. this.drainQueueLaterOnExecutor()
  6157. }
  6158. }
  6159. await() {
  6160. return untraced(() =>
  6161. asyncInterrupt(resume => {
  6162. const cb = exit => resume(succeed(exit))
  6163. this.tell(
  6164. stateful((fiber, _) => {
  6165. null !== fiber._exitValue
  6166. ? cb(this._exitValue)
  6167. : fiber.unsafeAddObserver(cb)
  6168. })
  6169. )
  6170. return sync(() =>
  6171. this.tell(
  6172. stateful((fiber, _) => {
  6173. fiber.unsafeRemoveObserver(cb)
  6174. })
  6175. )
  6176. )
  6177. }, this.id())
  6178. )
  6179. }
  6180. inheritAll() {
  6181. return untraced(() =>
  6182. withFiberRuntime((parentFiber, parentStatus) => {
  6183. const parentFiberId = parentFiber.id(),
  6184. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  6185. parentRuntimeFlags = parentStatus.runtimeFlags,
  6186. childFiberRefs = this.unsafeGetFiberRefs(),
  6187. updatedFiberRefs = joinAs(
  6188. parentFiberRefs,
  6189. parentFiberId,
  6190. childFiberRefs
  6191. )
  6192. parentFiber.setFiberRefs(updatedFiberRefs)
  6193. const updatedRuntimeFlags =
  6194. parentFiber.getFiberRef(currentRuntimeFlags),
  6195. patch = Patch_exclude(16)(
  6196. Patch_exclude(1)(
  6197. runtimeFlags_diff(parentRuntimeFlags, updatedRuntimeFlags)
  6198. )
  6199. )
  6200. return updateRuntimeFlags(patch)
  6201. })
  6202. )
  6203. }
  6204. poll() {
  6205. return untraced(() => sync(() => fromNullable(this._exitValue)))
  6206. }
  6207. unsafePoll() {
  6208. return this._exitValue
  6209. }
  6210. interruptAsFork(fiberId) {
  6211. return untraced(() =>
  6212. sync(() => this.tell(interruptSignal(interrupt(fiberId))))
  6213. )
  6214. }
  6215. unsafeAddObserver(observer) {
  6216. null !== this._exitValue
  6217. ? observer(this._exitValue)
  6218. : this._observers.push(observer)
  6219. }
  6220. unsafeRemoveObserver(observer) {
  6221. this._observers = this._observers.filter(o => o !== observer)
  6222. }
  6223. unsafeGetFiberRefs() {
  6224. this.setFiberRef(currentRuntimeFlags, this._runtimeFlags)
  6225. return this._fiberRefs
  6226. }
  6227. unsafeDeleteFiberRef(fiberRef) {
  6228. this._fiberRefs = delete_(this._fiberRefs, fiberRef)
  6229. }
  6230. getFiberRef(fiberRef) {
  6231. return getOrDefault(this._fiberRefs, fiberRef)
  6232. }
  6233. setFiberRef(fiberRef, value) {
  6234. this._fiberRefs = updatedAs(
  6235. this._fiberRefs,
  6236. this._fiberId,
  6237. fiberRef,
  6238. value
  6239. )
  6240. }
  6241. setFiberRefs(fiberRefs) {
  6242. this._fiberRefs = fiberRefs
  6243. }
  6244. addChild(child) {
  6245. this.getChildren().add(child)
  6246. }
  6247. removeChild(child) {
  6248. this.getChildren().delete(child)
  6249. }
  6250. drainQueueOnCurrentThread() {
  6251. let recurse = !0
  6252. for (; recurse; ) {
  6253. let evaluationSignal = "Continue"
  6254. const prev = globalThis[currentFiberURI]
  6255. globalThis[currentFiberURI] = this
  6256. try {
  6257. for (; "Continue" === evaluationSignal; )
  6258. evaluationSignal = MutableQueue_isEmpty(this._queue)
  6259. ? "Done"
  6260. : this.evaluateMessageWhileSuspended(
  6261. MutableQueue_poll(null)(this._queue)
  6262. )
  6263. } finally {
  6264. this._running = !1
  6265. globalThis[currentFiberURI] = prev
  6266. }
  6267. if (MutableQueue_isEmpty(this._queue) || this._running) recurse = !1
  6268. else {
  6269. this._running = !0
  6270. if ("Yield" === evaluationSignal) {
  6271. this.drainQueueLaterOnExecutor()
  6272. recurse = !1
  6273. } else recurse = !0
  6274. }
  6275. }
  6276. }
  6277. drainQueueLaterOnExecutor() {
  6278. this.getFiberRef(currentScheduler).scheduleTask(this.run)
  6279. }
  6280. drainQueueWhileRunning(runtimeFlags, cur0) {
  6281. let cur = cur0
  6282. for (; !MutableQueue_isEmpty(this._queue); ) {
  6283. const message = MutableQueue_poll(void 0)(this._queue)
  6284. cur = drainQueueWhileRunningTable[message._tag](
  6285. this,
  6286. runtimeFlags,
  6287. cur,
  6288. message
  6289. )
  6290. }
  6291. return cur
  6292. }
  6293. isInterrupted() {
  6294. return !(self =>
  6295. "Empty" === self._tag ||
  6296. cause_reduce(self, !0, (acc, cause) => {
  6297. switch (cause._tag) {
  6298. case "Empty":
  6299. return Option_some(acc)
  6300. case "Die":
  6301. case "Fail":
  6302. case "Interrupt":
  6303. return Option_some(!1)
  6304. default:
  6305. return Option_none()
  6306. }
  6307. }))(this.getFiberRef(interruptedCause))
  6308. }
  6309. addInterruptedCause(cause) {
  6310. const oldSC = this.getFiberRef(interruptedCause)
  6311. this.setFiberRef(interruptedCause, sequential(oldSC, cause))
  6312. }
  6313. processNewInterruptSignal(cause) {
  6314. this.addInterruptedCause(cause)
  6315. this.sendInterruptSignalToAllChildren()
  6316. }
  6317. sendInterruptSignalToAllChildren() {
  6318. if (null === this._children || 0 === this._children.size) return !1
  6319. let told = !1
  6320. for (const child of this._children) {
  6321. child.tell(interruptSignal(interrupt(this.id())))
  6322. told = !0
  6323. }
  6324. return told
  6325. }
  6326. interruptAllChildren() {
  6327. if (this.sendInterruptSignalToAllChildren()) {
  6328. const it = this._children.values()
  6329. this._children = null
  6330. let isDone = !1
  6331. const body = () => {
  6332. const next = it.next()
  6333. return next.done
  6334. ? sync(() => {
  6335. isDone = !0
  6336. })
  6337. : core_asUnit(next.value.await())
  6338. }
  6339. return whileLoop(
  6340. () => !isDone,
  6341. () => body(),
  6342. () => {}
  6343. )
  6344. }
  6345. return null
  6346. }
  6347. reportExitValue(exit) {
  6348. if (runtimeMetrics(this._runtimeFlags)) {
  6349. const tags = this.getFiberRef(currentTags)
  6350. switch (exit._tag) {
  6351. case "Success":
  6352. fiberSuccesses.unsafeUpdate(1, tags)
  6353. break
  6354. case "Failure":
  6355. fiberFailures.unsafeUpdate(1, tags)
  6356. }
  6357. }
  6358. if ("Failure" === exit._tag) {
  6359. const level = this.getFiberRef(unhandledErrorLogLevel)
  6360. isInterruptedOnly(exit.cause) ||
  6361. "Some" !== level._tag ||
  6362. this.log(
  6363. "Fiber terminated with a non handled error",
  6364. exit.cause,
  6365. level
  6366. )
  6367. }
  6368. }
  6369. setExitValue(exit) {
  6370. this._exitValue = exit
  6371. if (runtimeMetrics(this._runtimeFlags)) {
  6372. const tags = this.getFiberRef(currentTags),
  6373. startTimeMillis = this.id().startTimeMillis,
  6374. endTimeMillis = new Date().getTime()
  6375. fiberLifetimes.unsafeUpdate(
  6376. (endTimeMillis - startTimeMillis) / 1e3,
  6377. tags
  6378. )
  6379. }
  6380. this.reportExitValue(exit)
  6381. for (let i = this._observers.length - 1; i >= 0; i--)
  6382. this._observers[i](exit)
  6383. }
  6384. getLoggers() {
  6385. return this.getFiberRef(currentLoggers)
  6386. }
  6387. log(message, cause, overrideLogLevel) {
  6388. const logLevel = Option_isSome(overrideLogLevel)
  6389. ? overrideLogLevel.value
  6390. : this.getFiberRef(currentLogLevel),
  6391. spans = this.getFiberRef(currentLogSpan),
  6392. annotations = this.getFiberRef(currentLogAnnotations),
  6393. loggers = this.getLoggers(),
  6394. contextMap = this.unsafeGetFiberRefs()
  6395. mjs_HashSet_forEach(logger => {
  6396. logger.log(
  6397. this.id(),
  6398. logLevel,
  6399. message,
  6400. cause,
  6401. contextMap,
  6402. spans,
  6403. annotations
  6404. )
  6405. })(loggers)
  6406. }
  6407. evaluateMessageWhileSuspended(message) {
  6408. switch (message._tag) {
  6409. case "YieldNow":
  6410. return "Yield"
  6411. case "InterruptSignal":
  6412. this.processNewInterruptSignal(message.cause)
  6413. if (null !== this._asyncInterruptor) {
  6414. this._asyncInterruptor(exitFailCause(message.cause))
  6415. this._asyncInterruptor = null
  6416. }
  6417. return "Continue"
  6418. case "Resume":
  6419. this._asyncInterruptor = null
  6420. this._asyncBlockingOn = null
  6421. this.evaluateEffect(message.effect)
  6422. return "Continue"
  6423. case "Stateful":
  6424. message.onFiber(
  6425. this,
  6426. null !== this._exitValue
  6427. ? Status_done
  6428. : ((runtimeFlags = this._runtimeFlags),
  6429. (blockingOn = this._asyncBlockingOn),
  6430. new Suspended(runtimeFlags, blockingOn))
  6431. )
  6432. return "Continue"
  6433. default:
  6434. return fiberRuntime_absurd(message)
  6435. }
  6436. var runtimeFlags, blockingOn
  6437. }
  6438. evaluateEffect(effect0) {
  6439. this.getSupervisor().onResume(this)
  6440. try {
  6441. let effect =
  6442. interruptible(this._runtimeFlags) && this.isInterrupted()
  6443. ? exitFailCause(this.getInterruptedCause())
  6444. : effect0
  6445. for (; null !== effect; )
  6446. try {
  6447. const exit = this.runLoop(effect)
  6448. this._runtimeFlags = runtimeFlags_enable(16)(this._runtimeFlags)
  6449. const interruption = this.interruptAllChildren()
  6450. if (null !== interruption)
  6451. effect = untraced(() => core_flatMap(interruption, () => exit))
  6452. else {
  6453. MutableQueue_isEmpty(this._queue)
  6454. ? this.setExitValue(exit)
  6455. : this.tell(resume(exit))
  6456. effect = null
  6457. }
  6458. } catch (e) {
  6459. if (!isEffect(e)) throw e
  6460. if ("Yield" === e._tag)
  6461. if (cooperativeYielding(this._runtimeFlags)) {
  6462. this.tell({ _tag: "YieldNow" })
  6463. this.tell(resume(exitUnit()))
  6464. effect = null
  6465. } else effect = exitUnit()
  6466. else "Async" === e._tag && (effect = null)
  6467. }
  6468. } finally {
  6469. this.getSupervisor().onSuspend(this)
  6470. }
  6471. }
  6472. start(effect) {
  6473. if (this._running) this.tell(resume(effect))
  6474. else {
  6475. this._running = !0
  6476. const prev = globalThis[currentFiberURI]
  6477. globalThis[currentFiberURI] = this
  6478. try {
  6479. this.evaluateEffect(effect)
  6480. } finally {
  6481. this._running = !1
  6482. globalThis[currentFiberURI] = prev
  6483. MutableQueue_isEmpty(this._queue) ||
  6484. this.drainQueueLaterOnExecutor()
  6485. }
  6486. }
  6487. }
  6488. startFork(effect) {
  6489. this.tell(resume(effect))
  6490. }
  6491. patchRuntimeFlags(oldRuntimeFlags, patch) {
  6492. const newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, patch)
  6493. globalThis[currentFiberURI] = this
  6494. this._runtimeFlags = newRuntimeFlags
  6495. return newRuntimeFlags
  6496. }
  6497. initiateAsync(runtimeFlags, asyncRegister) {
  6498. let alreadyCalled = !1
  6499. const callback = effect => {
  6500. if (!alreadyCalled) {
  6501. alreadyCalled = !0
  6502. this.tell(resume(effect))
  6503. }
  6504. }
  6505. interruptible(runtimeFlags) && (this._asyncInterruptor = callback)
  6506. try {
  6507. asyncRegister(callback)
  6508. } catch (e) {
  6509. callback(failCause(die(e)))
  6510. }
  6511. }
  6512. pushStack(cont) {
  6513. this._stack.push(cont)
  6514. "trace" in cont && cont.trace && this._traceStack.push(cont.trace)
  6515. }
  6516. popStack() {
  6517. const item = this._stack.pop()
  6518. if (item) {
  6519. "trace" in item && item.trace && this._traceStack.pop()
  6520. return item
  6521. }
  6522. }
  6523. getNextSuccessCont() {
  6524. let frame = this.popStack()
  6525. for (; frame; ) {
  6526. if ("OnFailure" !== frame._tag && "Traced" !== frame._tag)
  6527. return frame
  6528. frame = this.popStack()
  6529. }
  6530. }
  6531. getNextFailCont() {
  6532. let frame = this.popStack()
  6533. for (; frame; ) {
  6534. if (
  6535. "OnSuccess" !== frame._tag &&
  6536. "While" !== frame._tag &&
  6537. "Traced" !== frame._tag
  6538. )
  6539. return frame
  6540. frame = this.popStack()
  6541. }
  6542. }
  6543. [((fiberRuntime_a = FiberTypeId),
  6544. (fiberRuntime_b = RuntimeFiberTypeId),
  6545. "Tag")](op) {
  6546. return core_map(fiberRefGet(currentContext), context =>
  6547. mjs_Context_unsafeGet(context, op)
  6548. )
  6549. }
  6550. Sync(op) {
  6551. const value = op.i0(),
  6552. cont = this.getNextSuccessCont()
  6553. if (void 0 !== cont) {
  6554. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  6555. return contOpSuccess[cont._tag](this, cont, value)
  6556. }
  6557. throw exitSucceed(value)
  6558. }
  6559. Success(op) {
  6560. const oldCur = op,
  6561. cont = this.getNextSuccessCont()
  6562. if (void 0 !== cont) {
  6563. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  6564. return contOpSuccess[cont._tag](this, cont, oldCur.i0)
  6565. }
  6566. throw oldCur
  6567. }
  6568. Failure(op) {
  6569. let cause = op.i0
  6570. if (
  6571. (self => "Annotated" === self._tag)(cause) &&
  6572. isStackAnnotation(cause.annotation)
  6573. ) {
  6574. const stack = cause.annotation.stack,
  6575. currentStack = this.stackToLines()
  6576. cause = annotated(
  6577. cause.cause,
  6578. new StackAnnotation(
  6579. Chunk_take(runtimeDebug.traceStackLimit)(
  6580. dedupeAdjacent(
  6581. 0 === stack.length
  6582. ? currentStack
  6583. : 0 === currentStack.length ||
  6584. unsafeLast(stack) === unsafeLast(currentStack)
  6585. ? stack
  6586. : Chunk_concat(currentStack)(stack)
  6587. )
  6588. ),
  6589. cause.annotation.seq
  6590. )
  6591. )
  6592. } else
  6593. cause = annotated(
  6594. op.i0,
  6595. new StackAnnotation(
  6596. this.stackToLines(),
  6597. (self => getAndUpdate(self, n => n + 1))(globalErrorSeq)
  6598. )
  6599. )
  6600. const cont = this.getNextFailCont()
  6601. if (void 0 === cont) throw exitFailCause(cause)
  6602. switch (cont._tag) {
  6603. case "OnFailure":
  6604. case "OnSuccessAndFailure":
  6605. return interruptible(this._runtimeFlags) && this.isInterrupted()
  6606. ? exitFailCause(stripFailures(cause))
  6607. : cont.i1(cause)
  6608. case "RevertFlags":
  6609. this.patchRuntimeFlags(this._runtimeFlags, cont.patch)
  6610. return interruptible(this._runtimeFlags) && this.isInterrupted()
  6611. ? exitFailCause(sequential(cause, this.getInterruptedCause()))
  6612. : exitFailCause(cause)
  6613. default:
  6614. fiberRuntime_absurd(cont)
  6615. }
  6616. }
  6617. WithRuntime(op) {
  6618. return op.i0(this, Status_running(this._runtimeFlags))
  6619. }
  6620. UpdateRuntimeFlags(op) {
  6621. if (void 0 === op.i1) {
  6622. this.patchRuntimeFlags(this._runtimeFlags, op.i0)
  6623. return exitUnit()
  6624. }
  6625. {
  6626. const updateFlags = op.i0,
  6627. oldRuntimeFlags = this._runtimeFlags,
  6628. newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, updateFlags)
  6629. if (newRuntimeFlags === oldRuntimeFlags) return op.i1(oldRuntimeFlags)
  6630. if (interruptible(newRuntimeFlags) && this.isInterrupted())
  6631. return exitFailCause(this.getInterruptedCause())
  6632. {
  6633. this.patchRuntimeFlags(this._runtimeFlags, updateFlags)
  6634. const revertFlags = runtimeFlags_diff(
  6635. newRuntimeFlags,
  6636. oldRuntimeFlags
  6637. )
  6638. this.pushStack(new RevertFlags(revertFlags))
  6639. return op.i1(oldRuntimeFlags)
  6640. }
  6641. }
  6642. }
  6643. OnSuccess(op) {
  6644. this.pushStack(op)
  6645. return op.i0
  6646. }
  6647. Traced(op) {
  6648. this.pushStack(op)
  6649. return op.i0
  6650. }
  6651. OnFailure(op) {
  6652. this.pushStack(op)
  6653. return op.i0
  6654. }
  6655. OnSuccessAndFailure(op) {
  6656. this.pushStack(op)
  6657. return op.i0
  6658. }
  6659. Async(op) {
  6660. this._asyncBlockingOn = op.i1
  6661. this.initiateAsync(this._runtimeFlags, op.i0)
  6662. throw op
  6663. }
  6664. Yield(op) {
  6665. throw op
  6666. }
  6667. While(op) {
  6668. const check = op.i0,
  6669. body = op.i1
  6670. if (check()) {
  6671. this.pushStack(op)
  6672. return body()
  6673. }
  6674. return exitUnit()
  6675. }
  6676. Commit(op) {
  6677. return op.commit()
  6678. }
  6679. runLoop(effect0) {
  6680. let cur = effect0,
  6681. ops = 0
  6682. for (;;) {
  6683. opSupervision(this._runtimeFlags) &&
  6684. this.getSupervisor().onEffect(this, cur)
  6685. cur = this.drainQueueWhileRunning(this._runtimeFlags, cur)
  6686. ops += 1
  6687. if (ops >= 2048) {
  6688. ops = 0
  6689. const oldCur = cur
  6690. cur = core_flatMap(() => oldCur)(yieldNow())
  6691. }
  6692. try {
  6693. cur._tag in this || fiberRuntime_absurd(cur)
  6694. cur = this[cur._tag](cur)
  6695. } catch (e) {
  6696. if (isEffect(e)) {
  6697. if ("Yield" === e._tag || "Async" === e._tag) throw e
  6698. if ("Success" === e._tag || "Failure" === e._tag) return e
  6699. } else
  6700. cur = isEffectError(e)
  6701. ? exitFailCause(e.cause)
  6702. : isInterruptedException(e)
  6703. ? exitFailCause(sequential(die(e), interrupt(Id_none)))
  6704. : exitFailCause(die(e))
  6705. }
  6706. }
  6707. }
  6708. stackToLines() {
  6709. if (0 === this._traceStack.length) return Chunk_empty()
  6710. const lines = []
  6711. let current = this._traceStack.length - 1
  6712. for (; current >= 0 && lines.length < runtimeDebug.traceStackLimit; ) {
  6713. const value = this._traceStack[current]
  6714. lines.push(value)
  6715. current -= 1
  6716. }
  6717. return unsafeFromArray(lines)
  6718. }
  6719. }
  6720. const currentMinimumLogLevel = fiberRefUnsafeMake(
  6721. fromLiteral(runtimeDebug.minumumLogLevel)
  6722. ),
  6723. defaultLogger = makeLogger(
  6724. (fiberId, logLevel, message, cause, context, spans, annotations) => {
  6725. const formatted = stringLogger.log(
  6726. fiberId,
  6727. logLevel,
  6728. message,
  6729. cause,
  6730. context,
  6731. spans,
  6732. annotations
  6733. ),
  6734. filter = getOrDefault(context, currentMinimumLogLevel)
  6735. greaterThanEqual(filter)(logLevel) &&
  6736. globalThis.console.log(formatted)
  6737. }
  6738. ),
  6739. currentLoggers = fiberRefUnsafeMakeHashSet(
  6740. mjs_HashSet_make(defaultLogger)
  6741. ),
  6742. acquireRelease = dualWithTrace(
  6743. 2,
  6744. (trace, restore) => (acquire, release) =>
  6745. uninterruptible(
  6746. core_tap(acquire, a =>
  6747. addFinalizer(exit => restore(release)(a, exit))
  6748. )
  6749. ).traced(trace)
  6750. ),
  6751. addFinalizer = methodWithTrace(
  6752. (trace, restore) => finalizer =>
  6753. core_flatMap(context(), context =>
  6754. core_flatMap(scope(), scope =>
  6755. scopeAddFinalizerExit(scope, exit =>
  6756. core_asUnit(provideContext(context)(restore(finalizer)(exit)))
  6757. )
  6758. )
  6759. ).traced(trace)
  6760. ),
  6761. forEachPar = dualWithTrace(
  6762. 2,
  6763. (trace, restore) => (self, f) =>
  6764. fiberRefGetWith(currentParallelism, o =>
  6765. "None" === o._tag
  6766. ? forEachParUnbounded(self, restore(f))
  6767. : forEachParN(self, o.value, f)
  6768. ).traced(trace)
  6769. ),
  6770. forEachParUnbounded = (self, f) =>
  6771. suspend(() => {
  6772. const as = Array.from(self).map((v, i) => [v, i]),
  6773. array = new Array(as.length)
  6774. return zipRight(
  6775. forEachParUnboundedDiscard(as, ([a, i]) =>
  6776. core_flatMap(f(a), b => sync(() => (array[i] = b)))
  6777. ),
  6778. succeed(unsafeFromArray(array))
  6779. )
  6780. }),
  6781. forEachParUnboundedDiscard = (self, f) =>
  6782. suspend(() => {
  6783. const as = Array.from(self),
  6784. size = as.length
  6785. return 0 === size
  6786. ? core_unit()
  6787. : 1 === size
  6788. ? core_asUnit(f(as[0]))
  6789. : uninterruptibleMask(restore => {
  6790. const deferred = deferredUnsafeMake(Id_none)
  6791. let ref = 0
  6792. const process = transplant(graft =>
  6793. core_forEach(as, a =>
  6794. forkDaemon(
  6795. graft(
  6796. matchCauseEffect(
  6797. cause =>
  6798. zipRight(
  6799. deferredFail(deferred, void 0),
  6800. failCause(cause)
  6801. ),
  6802. () => {
  6803. ref + 1 === size
  6804. ? deferredUnsafeDone(deferred, core_unit())
  6805. : (ref += 1)
  6806. return core_unit()
  6807. }
  6808. )(restore(suspend(() => f(a))))
  6809. )
  6810. )
  6811. )
  6812. )
  6813. return core_flatMap(process, fibers =>
  6814. matchCauseEffect(
  6815. restore(deferredAwait(deferred)),
  6816. cause =>
  6817. core_flatMap(
  6818. forEachParUnbounded(fibers, interruptFiber),
  6819. exits => {
  6820. const exit = exitCollectAllPar(exits)
  6821. return "Some" === exit._tag &&
  6822. (self => "Failure" === self._tag)(exit.value)
  6823. ? failCause(
  6824. parallel(stripFailures(cause), exit.value.i0)
  6825. )
  6826. : failCause(stripFailures(cause))
  6827. }
  6828. ),
  6829. () => forEachDiscard(fibers, f => f.inheritAll())
  6830. )
  6831. )
  6832. })
  6833. }),
  6834. forEachParN = (self, n, f) =>
  6835. suspend(() => {
  6836. const as = Array.from(self).map((v, i) => [v, i]),
  6837. array = new Array(as.length)
  6838. return zipRight(
  6839. forEachParNDiscard(as, n, ([a, i]) =>
  6840. core_map(f(a), b => (array[i] = b))
  6841. ),
  6842. succeed(unsafeFromArray(array))
  6843. )
  6844. }),
  6845. forEachParNDiscard = (self, n, f) =>
  6846. suspend(() => {
  6847. const iterator = self[Symbol.iterator](),
  6848. worker = core_flatMap(
  6849. sync(() => iterator.next()),
  6850. next =>
  6851. next.done
  6852. ? core_unit()
  6853. : core_flatMap(core_asUnit(f(next.value)), () => worker)
  6854. ),
  6855. effects = []
  6856. for (let i = 0; i < n; i++) effects.push(worker)
  6857. return forEachParUnboundedDiscard(effects, Function_identity)
  6858. }),
  6859. forkDaemon = methodWithTrace(
  6860. trace => self => forkWithScopeOverride(self, globalScope).traced(trace)
  6861. ),
  6862. unsafeMakeChildFiber = (
  6863. effect,
  6864. parentFiber,
  6865. parentRuntimeFlags,
  6866. overrideScope = null
  6867. ) => {
  6868. const childId = Id_unsafeMake(),
  6869. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  6870. childFiberRefs = forkAs(parentFiberRefs, childId),
  6871. childFiber = new FiberRuntime(
  6872. childId,
  6873. childFiberRefs,
  6874. parentRuntimeFlags
  6875. ),
  6876. childContext = getOrDefault(childFiberRefs, currentContext),
  6877. supervisor = childFiber.getSupervisor()
  6878. supervisor.onStart(
  6879. childContext,
  6880. effect,
  6881. Option_some(parentFiber),
  6882. childFiber
  6883. )
  6884. childFiber.unsafeAddObserver(exit => supervisor.onEnd(exit, childFiber))
  6885. ;(null !== overrideScope
  6886. ? overrideScope
  6887. : getOrElse(() => parentFiber.scope())(
  6888. parentFiber.getFiberRef(forkScopeOverride)
  6889. )
  6890. ).add(parentRuntimeFlags, childFiber)
  6891. return childFiber
  6892. },
  6893. forkWithScopeOverride = (self, scopeOverride) =>
  6894. withFiberRuntime((parentFiber, parentStatus) =>
  6895. succeed(
  6896. ((
  6897. effect,
  6898. parentFiber,
  6899. parentRuntimeFlags,
  6900. overrideScope = null
  6901. ) => {
  6902. const childFiber = unsafeMakeChildFiber(
  6903. effect,
  6904. parentFiber,
  6905. parentRuntimeFlags,
  6906. overrideScope
  6907. )
  6908. childFiber.resume(effect)
  6909. return childFiber
  6910. })(self, parentFiber, parentStatus.runtimeFlags, scopeOverride)
  6911. )
  6912. ),
  6913. scope = methodWithTrace(trace => () => scopeTag.traced(trace)),
  6914. scopeWith = methodWithTrace(
  6915. (trace, restore) => f =>
  6916. core_flatMap(scopeTag, restore(f)).traced(trace)
  6917. ),
  6918. fiberRuntime_some = methodWithTrace(
  6919. trace => self =>
  6920. matchEffect(
  6921. self,
  6922. e => core_fail(Option_some(e)),
  6923. option => {
  6924. switch (option._tag) {
  6925. case "None":
  6926. return core_fail(Option_none())
  6927. case "Some":
  6928. return succeed(option.value)
  6929. }
  6930. }
  6931. ).traced(trace)
  6932. ),
  6933. unsome = methodWithTrace(
  6934. trace => self =>
  6935. matchEffect(
  6936. self,
  6937. option => {
  6938. switch (option._tag) {
  6939. case "None":
  6940. return succeed(Option_none())
  6941. case "Some":
  6942. return core_fail(option.value)
  6943. }
  6944. },
  6945. a => succeed(Option_some(a))
  6946. ).traced(trace)
  6947. ),
  6948. scopeTag = Tag(),
  6949. scopeMake = methodWithTrace(
  6950. trace =>
  6951. (strategy = ExecutionStrategy_sequential) =>
  6952. core_map(releaseMapMake(), rm => ({
  6953. [ScopeTypeId]: ScopeTypeId,
  6954. [CloseableScopeTypeId]: CloseableScopeTypeId,
  6955. fork: strategy =>
  6956. bodyWithTrace(trace =>
  6957. uninterruptible(
  6958. core_flatMap(scope =>
  6959. core_as(scope)(
  6960. core_tap(fin => scopeAddFinalizerExit(scope, fin))(
  6961. releaseMapAdd(exit => scopeClose(scope, exit))(rm)
  6962. )
  6963. )
  6964. )(scopeMake(strategy))
  6965. ).traced(trace)
  6966. ),
  6967. close: exit =>
  6968. bodyWithTrace(trace =>
  6969. core_asUnit(
  6970. (
  6971. (strategy, exit) => self =>
  6972. suspend(() => {
  6973. switch (self.state._tag) {
  6974. case "Exited":
  6975. return core_unit()
  6976. case "Running": {
  6977. const finalizersMap = self.state.finalizers,
  6978. update = self.state.update,
  6979. finalizers = Array.from(finalizersMap.keys())
  6980. .sort((a, b) => b - a)
  6981. .map(key => finalizersMap.get(key))
  6982. self.state = {
  6983. _tag: "Exited",
  6984. nextKey: self.state.nextKey,
  6985. exit,
  6986. update,
  6987. }
  6988. return (self => "Sequential" === self._tag)(
  6989. strategy
  6990. )
  6991. ? core_flatMap(results =>
  6992. getOrElse(() => exitUnit())(
  6993. Option_map(exitAsUnit)(
  6994. exitCollectAllInternal(
  6995. results,
  6996. sequential
  6997. )
  6998. )
  6999. )
  7000. )(
  7001. core_forEach(fin =>
  7002. core_exit(update(fin)(exit))
  7003. )(finalizers)
  7004. )
  7005. : (self => "Parallel" === self._tag)(strategy)
  7006. ? core_flatMap(results =>
  7007. getOrElse(() => exitUnit())(
  7008. Option_map(exitAsUnit)(
  7009. exitCollectAllPar(results)
  7010. )
  7011. )
  7012. )(
  7013. forEachPar(fin =>
  7014. core_exit(update(fin)(exit))
  7015. )(finalizers)
  7016. )
  7017. : withParallelism(strategy.parallelism)(
  7018. core_flatMap(results =>
  7019. getOrElse(() => exitUnit())(
  7020. Option_map(exitAsUnit)(
  7021. exitCollectAllPar(results)
  7022. )
  7023. )
  7024. )(
  7025. forEachPar(fin =>
  7026. core_exit(update(fin)(exit))
  7027. )(finalizers)
  7028. )
  7029. )
  7030. }
  7031. }
  7032. })
  7033. )(
  7034. strategy,
  7035. exit
  7036. )(rm)
  7037. ).traced(trace)
  7038. ),
  7039. addFinalizer: fin =>
  7040. bodyWithTrace(trace =>
  7041. core_asUnit(releaseMapAdd(fin)(rm)).traced(trace)
  7042. ),
  7043. })).traced(trace)
  7044. ),
  7045. scopeExtend = dualWithTrace(2, trace => (effect, scope) => {
  7046. return contramapContext(
  7047. effect,
  7048. mjs_Context_merge(
  7049. ((tag = scopeTag),
  7050. (service = scope),
  7051. new ContextImpl(new Map([[tag, service]])))
  7052. )
  7053. ).traced(trace)
  7054. var tag, service
  7055. }),
  7056. fiberRefUnsafeMakeSupervisor = initial =>
  7057. fiberRefUnsafeMakePatch(initial, patch_differ, supervisor_patch_empty),
  7058. fiberRefLocallyScoped = dualWithTrace(
  7059. 2,
  7060. trace => (self, value) =>
  7061. core_asUnit(
  7062. acquireRelease(
  7063. core_flatMap(oldValue =>
  7064. core_as(oldValue)(fiberRefSet(self, value))
  7065. )(fiberRefGet(self)),
  7066. oldValue => fiberRefSet(self, oldValue)
  7067. )
  7068. ).traced(trace)
  7069. ),
  7070. fiberRefLocallyScopedWith = dualWithTrace(
  7071. 2,
  7072. (trace, restore) => (self, f) =>
  7073. fiberRefGetWith(self, a =>
  7074. fiberRefLocallyScoped(self, restore(f)(a))
  7075. ).traced(trace)
  7076. ),
  7077. currentRuntimeFlags = fiberRefUnsafeMakeRuntimeFlags(runtimeFlags_none),
  7078. currentSupervisor = fiberRefUnsafeMakeSupervisor(supervisor_none),
  7079. fiberInterruptFork = methodWithTrace(
  7080. trace => self =>
  7081. core_asUnit(forkDaemon(interruptFiber(self))).traced(trace)
  7082. )
  7083. var circular_b, circular_c
  7084. class Semaphore {
  7085. constructor(permits) {
  7086. this.permits = permits
  7087. this.waiters = new Array()
  7088. this.taken = 0
  7089. this.take = n =>
  7090. bodyWithTrace(trace =>
  7091. asyncInterruptEither(resume => {
  7092. if (this.free < n) {
  7093. const observer = () => {
  7094. if (this.free >= n) {
  7095. const observerIndex = this.waiters.findIndex(
  7096. cb => cb === observer
  7097. )
  7098. ;-1 !== observerIndex &&
  7099. this.waiters.splice(observerIndex, 1)
  7100. this.taken += n
  7101. resume(succeed(n))
  7102. }
  7103. }
  7104. this.waiters.push(observer)
  7105. return Either_left(
  7106. sync(() => {
  7107. const observerIndex = this.waiters.findIndex(
  7108. cb => cb === observer
  7109. )
  7110. ;-1 !== observerIndex &&
  7111. this.waiters.splice(observerIndex, 1)
  7112. })
  7113. )
  7114. }
  7115. this.taken += n
  7116. return Either_right(succeed(n))
  7117. }).traced(trace)
  7118. )
  7119. this.release = n =>
  7120. bodyWithTrace(trace =>
  7121. withFiberRuntime(fiber => {
  7122. this.taken -= n
  7123. fiber.getFiberRef(currentScheduler).scheduleTask(() => {
  7124. this.waiters.forEach(wake => wake())
  7125. })
  7126. return core_unit()
  7127. }).traced(trace)
  7128. )
  7129. this.withPermits = n =>
  7130. bodyWithTrace(
  7131. trace => self =>
  7132. untraced(() =>
  7133. uninterruptibleMask(restore =>
  7134. core_flatMap(restore(this.take(n)), permits =>
  7135. circular_ensuring(restore(self), this.release(permits))
  7136. )
  7137. )
  7138. ).traced(trace)
  7139. )
  7140. }
  7141. get free() {
  7142. return this.permits - this.taken
  7143. }
  7144. }
  7145. const circular_ensuring = dualWithTrace(
  7146. 2,
  7147. trace => (self, finalizer) =>
  7148. uninterruptibleMask(restore =>
  7149. matchCauseEffect(
  7150. restore(self),
  7151. cause1 =>
  7152. matchCauseEffect(
  7153. finalizer,
  7154. cause2 => failCause(sequential(cause1, cause2)),
  7155. () => failCause(cause1)
  7156. ),
  7157. a => core_as(finalizer, a)
  7158. )
  7159. ).traced(trace)
  7160. )
  7161. const zipWithPar = dualWithTrace(
  7162. 3,
  7163. (trace, restoreTrace) => (self, that, f) =>
  7164. uninterruptibleMask(restore =>
  7165. transplant(graft => {
  7166. const deferred = deferredUnsafeMake(Id_none),
  7167. ref = MutableRef_make(!1)
  7168. return core_flatMap(([left, right]) =>
  7169. matchCauseEffect(
  7170. cause =>
  7171. zipRight(
  7172. core_flatMap(([left, right]) =>
  7173. exitMatch(
  7174. causes =>
  7175. failCause(parallel(stripFailures(cause), causes)),
  7176. () => failCause(stripFailures(cause))
  7177. )(exitZipWith(right, f, parallel)(left))
  7178. )(core_zip(_await(right))(_await(left)))
  7179. )(
  7180. zipRight(fiberInterruptFork(right))(
  7181. fiberInterruptFork(left)
  7182. )
  7183. ),
  7184. () =>
  7185. core_zipWith(
  7186. fiber_join(left),
  7187. fiber_join(right),
  7188. restoreTrace(f)
  7189. )
  7190. )(restore(deferredAwait(deferred)))
  7191. )(
  7192. core_zip(forkZipWithPar(that, graft, restore, deferred, ref))(
  7193. forkZipWithPar(self, graft, restore, deferred, ref)
  7194. )
  7195. )
  7196. })
  7197. ).traced(trace)
  7198. ),
  7199. forkZipWithPar = (self, graft, restore, deferred, ref) =>
  7200. forkDaemon(
  7201. matchCauseEffect(
  7202. graft(restore(self)),
  7203. cause => zipRight(deferredFail(deferred, void 0), failCause(cause)),
  7204. value => {
  7205. if (MutableRef_get(ref)) {
  7206. deferredUnsafeDone(deferred, core_unit())
  7207. return succeed(value)
  7208. }
  7209. MutableRef_set(!0)(ref)
  7210. return succeed(value)
  7211. }
  7212. )
  7213. ),
  7214. SynchronizedTypeId = Symbol.for("@effect/io/Ref/Synchronized"),
  7215. synchronizedVariance = { _A: _ => _ }
  7216. class SynchronizedImpl {
  7217. constructor(ref, withLock) {
  7218. this.ref = ref
  7219. this.withLock = withLock
  7220. this[circular_b] = synchronizedVariance
  7221. this[circular_c] = refVariance
  7222. }
  7223. modify(f) {
  7224. return bodyWithTrace((trace, restore) =>
  7225. this.modifyEffect(a => succeed(restore(f)(a))).traced(trace)
  7226. )
  7227. }
  7228. modifyEffect(f) {
  7229. return bodyWithTrace((trace, restore) =>
  7230. this.withLock(
  7231. core_flatMap(([b, a]) => core_as(ref_set(this.ref, a), b))(
  7232. core_flatMap(ref_get(this.ref), restore(f))
  7233. )
  7234. ).traced(trace)
  7235. )
  7236. }
  7237. }
  7238. ;(circular_b = SynchronizedTypeId), (circular_c = RefTypeId)
  7239. const makeSynchronized = methodWithTrace(
  7240. trace => value =>
  7241. sync(() => unsafeMakeSynchronized(value)).traced(trace)
  7242. ),
  7243. unsafeMakeSynchronized = value => {
  7244. const ref = ref_unsafeMake(value),
  7245. sem = new Semaphore(1)
  7246. return new SynchronizedImpl(ref, sem.withPermits(1))
  7247. },
  7248. Cause_fail = fail,
  7249. Cause_failureOrCause = self => {
  7250. const option = (self =>
  7251. find(self, cause =>
  7252. "Fail" === cause._tag ? Option_some(cause.error) : Option_none()
  7253. ))(self)
  7254. switch (option._tag) {
  7255. case "None":
  7256. return Either_right(self)
  7257. case "Some":
  7258. return Either_left(option.value)
  7259. }
  7260. },
  7261. modifyEffect = dualWithTrace(
  7262. 2,
  7263. (trace, restore) => (self, f) =>
  7264. self.modifyEffect(restore(f)).traced(trace)
  7265. ),
  7266. layer_proto = {
  7267. [Symbol.for("@effect/io/Layer")]: {
  7268. _RIn: _ => _,
  7269. _E: _ => _,
  7270. _ROut: _ => _,
  7271. },
  7272. },
  7273. isFresh = self => "Fresh" === self._tag
  7274. class MemoMap {
  7275. constructor(ref) {
  7276. this.ref = ref
  7277. }
  7278. getOrElseMemoize(layer, scope) {
  7279. return core_flatten(
  7280. modifyEffect(this.ref, map => {
  7281. const inMap = map.get(layer)
  7282. if (void 0 !== inMap) {
  7283. const [acquire, release] = inMap,
  7284. cached = onExit(
  7285. exitMatch(
  7286. () => core_unit(),
  7287. () => scopeAddFinalizerExit(scope, release)
  7288. )
  7289. )(
  7290. core_flatMap(([patch, b]) =>
  7291. core_as(b)(patchFiberRefs(patch))
  7292. )(acquire)
  7293. )
  7294. return succeed([cached, map])
  7295. }
  7296. return core_flatMap(observers =>
  7297. core_flatMap(deferred =>
  7298. core_map(finalizerRef => {
  7299. const resource = uninterruptibleMask(restore =>
  7300. core_flatMap(innerScope =>
  7301. core_flatMap(exit => {
  7302. switch (exit._tag) {
  7303. case "Failure":
  7304. return zipRight(failCause(exit.i0))(
  7305. zipRight(scopeClose(innerScope, exit))(
  7306. deferredFailCause(deferred, exit.i0)
  7307. )
  7308. )
  7309. case "Success":
  7310. return core_as(exit.i0[1])(
  7311. zipRight(deferredSucceed(deferred, exit.i0))(
  7312. zipRight(
  7313. scopeAddFinalizerExit(scope, exit =>
  7314. core_flatMap(finalizer =>
  7315. finalizer(exit)
  7316. )(ref_get(finalizerRef))
  7317. )
  7318. )(
  7319. zipRight(ref_update(observers, n => n + 1))(
  7320. ref_set(finalizerRef, exit =>
  7321. core_asUnit(
  7322. whenEffect(
  7323. ref_modify(observers, n => [
  7324. 1 === n,
  7325. n - 1,
  7326. ])
  7327. )(scopeClose(innerScope, exit))
  7328. )
  7329. )
  7330. )
  7331. )
  7332. )
  7333. )
  7334. }
  7335. })(
  7336. core_exit(
  7337. restore(
  7338. core_flatMap(withScope(layer, innerScope), f =>
  7339. diffFiberRefs(f(this))
  7340. )
  7341. )
  7342. )
  7343. )
  7344. )(scopeMake())
  7345. ),
  7346. memoized = [
  7347. onExit(
  7348. exitMatchEffect(
  7349. () => core_unit(),
  7350. () => ref_update(observers, n => n + 1)
  7351. )
  7352. )(deferredAwait(deferred)),
  7353. exit =>
  7354. core_flatMap(finalizer => finalizer(exit))(
  7355. ref_get(finalizerRef)
  7356. ),
  7357. ]
  7358. return [
  7359. resource,
  7360. isFresh(layer) ? map : map.set(layer, memoized),
  7361. ]
  7362. })(ref_make(() => core_unit()))
  7363. )(deferredMake())
  7364. )(ref_make(0))
  7365. })
  7366. )
  7367. }
  7368. }
  7369. const buildWithScope = dualWithTrace(
  7370. 2,
  7371. trace => (self, scope) =>
  7372. core_flatMap(
  7373. core_map(ref => new MemoMap(ref))(makeSynchronized(new Map())),
  7374. memoMap => core_flatMap(withScope(self, scope), run => run(memoMap))
  7375. ).traced(trace)
  7376. ),
  7377. withScope = (self, scope) => {
  7378. const op = self
  7379. switch (op._tag) {
  7380. case "ExtendScope":
  7381. return sync(
  7382. () => memoMap =>
  7383. scopeWith(scope => memoMap.getOrElseMemoize(op.layer, scope))
  7384. )
  7385. case "Fold":
  7386. return sync(
  7387. () => memoMap =>
  7388. matchCauseEffect(
  7389. cause => memoMap.getOrElseMemoize(op.failureK(cause), scope),
  7390. value => memoMap.getOrElseMemoize(op.successK(value), scope)
  7391. )(memoMap.getOrElseMemoize(op.layer, scope))
  7392. )
  7393. case "Fresh":
  7394. return sync(() => _ => buildWithScope(scope)(op.layer))
  7395. case "FromEffect":
  7396. return sync(() => _ => op.effect)
  7397. case "ProvideTo":
  7398. return sync(
  7399. () => memoMap =>
  7400. core_flatMap(env =>
  7401. provideContext(env)(
  7402. memoMap.getOrElseMemoize(op.second, scope)
  7403. )
  7404. )(memoMap.getOrElseMemoize(op.first, scope))
  7405. )
  7406. case "Scoped":
  7407. return sync(() => _ => scopeExtend(op.effect, scope))
  7408. case "Suspend":
  7409. return sync(
  7410. () => memoMap => memoMap.getOrElseMemoize(op.evaluate(), scope)
  7411. )
  7412. case "ZipWith":
  7413. return sync(
  7414. () => memoMap =>
  7415. core_zipWith(
  7416. memoMap.getOrElseMemoize(op.second, scope),
  7417. op.zipK
  7418. )(memoMap.getOrElseMemoize(op.first, scope))
  7419. )
  7420. case "ZipWithPar":
  7421. return sync(
  7422. () => memoMap =>
  7423. zipWithPar(
  7424. memoMap.getOrElseMemoize(op.second, scope),
  7425. op.zipK
  7426. )(memoMap.getOrElseMemoize(op.first, scope))
  7427. )
  7428. }
  7429. },
  7430. layer_fail = error => layer_failCause(Cause_fail(error)),
  7431. layer_failCause = cause => fromEffectContext(failCause(cause)),
  7432. layer_flatMap = untracedDual(
  7433. 2,
  7434. restore => (self, f) => matchLayer(self, layer_fail, restore(f))
  7435. )
  7436. function fromEffectContext(effect) {
  7437. const fromEffect = Object.create(layer_proto)
  7438. fromEffect._tag = "FromEffect"
  7439. fromEffect.effect = effect
  7440. return fromEffect
  7441. }
  7442. const matchCauseLayer = untracedDual(
  7443. 3,
  7444. restore => (self, onFailure, onSuccess) => {
  7445. const fold = Object.create(layer_proto)
  7446. fold._tag = "Fold"
  7447. fold.layer = self
  7448. fold.failureK = restore(onFailure)
  7449. fold.successK = restore(onSuccess)
  7450. return fold
  7451. }
  7452. ),
  7453. matchLayer = untracedDual(
  7454. 3,
  7455. restore => (self, onFailure, onSuccess) =>
  7456. matchCauseLayer(
  7457. self,
  7458. cause => {
  7459. const failureOrCause = Cause_failureOrCause(cause)
  7460. switch (failureOrCause._tag) {
  7461. case "Left":
  7462. return restore(onFailure)(failureOrCause.left)
  7463. case "Right":
  7464. return layer_failCause(failureOrCause.right)
  7465. }
  7466. },
  7467. restore(onSuccess)
  7468. )
  7469. ),
  7470. layer_merge = Function_dual(2, (self, that) =>
  7471. layer_zipWithPar(self, that, (a, b) => mjs_Context_merge(b)(a))
  7472. ),
  7473. scopedDiscard = effect =>
  7474. scopedContext(core_as(mjs_Context_empty())(effect)),
  7475. scopedContext = effect => {
  7476. const scoped = Object.create(layer_proto)
  7477. scoped._tag = "Scoped"
  7478. scoped.effect = effect
  7479. return scoped
  7480. },
  7481. layer_zipWithPar = untracedDual(
  7482. 3,
  7483. restore => (self, that, f) =>
  7484. (evaluate => {
  7485. const suspend = Object.create(layer_proto)
  7486. suspend._tag = "Suspend"
  7487. suspend.evaluate = evaluate
  7488. return suspend
  7489. })(() => {
  7490. const zipWithPar = Object.create(layer_proto)
  7491. zipWithPar._tag = "ZipWithPar"
  7492. zipWithPar.first = self
  7493. zipWithPar.second = that
  7494. zipWithPar.zipK = restore(f)
  7495. return zipWithPar
  7496. })
  7497. ),
  7498. provideLayer = dualWithTrace(
  7499. 2,
  7500. trace => (self, layer) =>
  7501. acquireUseRelease(
  7502. scopeMake(),
  7503. scope =>
  7504. core_flatMap(buildWithScope(layer, scope), context =>
  7505. provideContext(self, context)
  7506. ),
  7507. (scope, exit) => scopeClose(scope, exit)
  7508. ).traced(trace)
  7509. ),
  7510. provideSomeLayer = dualWithTrace(
  7511. 2,
  7512. trace => (self, layer) =>
  7513. provideLayer(
  7514. self,
  7515. layer_merge(layer)(fromEffectContext(context()))
  7516. ).traced(trace)
  7517. ),
  7518. withMinimumLogLevel = dualWithTrace(
  7519. 2,
  7520. trace => (self, level) =>
  7521. fiberRefLocally(currentMinimumLogLevel, level)(self).traced(trace)
  7522. ),
  7523. addLogger = methodWithTrace(
  7524. trace => logger =>
  7525. scopedDiscard(
  7526. fiberRefLocallyScopedWith(
  7527. currentLoggers,
  7528. mjs_HashSet_add(logger)
  7529. ).traced(trace)
  7530. )
  7531. ),
  7532. removeLogger = untracedMethod(
  7533. () => logger =>
  7534. scopedDiscard(
  7535. fiberRefLocallyScopedWith(
  7536. currentLoggers,
  7537. mjs_HashSet_remove(logger)
  7538. )
  7539. )
  7540. ),
  7541. replaceLogger = Function_dual(2, (self, that) =>
  7542. layer_flatMap(removeLogger(self), () => addLogger(that))
  7543. )
  7544. class AsyncFiber {
  7545. constructor(fiber) {
  7546. this.fiber = fiber
  7547. this._tag = "AsyncFiber"
  7548. }
  7549. toString() {
  7550. return `Fiber #${this.fiber.id().id} has suspended work asyncroniously`
  7551. }
  7552. [Symbol.for("nodejs.util.inspect.custom")]() {
  7553. return this.toString()
  7554. }
  7555. }
  7556. const FiberFailureId = Symbol.for("@effect/io/Runtime/FiberFailure"),
  7557. FiberFailureCauseId = Symbol.for("@effect/io/Runtime/FiberFailure/Cause"),
  7558. NodePrint = Symbol.for("nodejs.util.inspect.custom"),
  7559. unsafeRunPromise = runtime =>
  7560. methodWithTrace(
  7561. trace => effect =>
  7562. new Promise((resolve, reject) => {
  7563. ;(runtime =>
  7564. methodWithTrace(trace => (self, options) => {
  7565. const fiberId = Id_unsafeMake(),
  7566. effect = self.traced(trace)
  7567. let fiberRefs = FiberRefs_updatedAs(
  7568. runtime.fiberRefs,
  7569. fiberId,
  7570. currentContext,
  7571. runtime.context
  7572. )
  7573. options?.scheduler &&
  7574. (fiberRefs = FiberRefs_updatedAs(
  7575. fiberRefs,
  7576. fiberId,
  7577. currentScheduler,
  7578. options.scheduler
  7579. ))
  7580. options?.updateRefs &&
  7581. (fiberRefs = options.updateRefs(fiberRefs, fiberId))
  7582. const fiberRuntime = new FiberRuntime(
  7583. fiberId,
  7584. FiberRefs_forkAs(fiberRefs, fiberId),
  7585. runtime.runtimeFlags
  7586. ),
  7587. supervisor = fiberRuntime.getSupervisor()
  7588. if (supervisor !== supervisor_none) {
  7589. supervisor.onStart(
  7590. runtime.context,
  7591. effect,
  7592. Option_none(),
  7593. fiberRuntime
  7594. )
  7595. fiberRuntime.unsafeAddObserver(exit =>
  7596. supervisor.onEnd(exit, fiberRuntime)
  7597. )
  7598. }
  7599. globalScope.add(runtime.runtimeFlags, fiberRuntime)
  7600. fiberRuntime.start(effect)
  7601. return fiberRuntime
  7602. }))(runtime)(effect.traced(trace)).unsafeAddObserver(result => {
  7603. switch (result._tag) {
  7604. case "Success":
  7605. resolve(result.i0)
  7606. break
  7607. case "Failure":
  7608. reject(
  7609. (cause => {
  7610. const limit = Error.stackTraceLimit
  7611. Error.stackTraceLimit = 0
  7612. const error = new Error()
  7613. Error.stackTraceLimit = limit
  7614. const pretty = prettyErrors(cause)
  7615. if (pretty.length > 0) {
  7616. error.name = pretty[0].message.split(":")[0]
  7617. error.message = pretty[0].message.substring(
  7618. error.name.length + 2
  7619. )
  7620. error.stack = `${error.name}: ${error.message}\n${pretty[0].stack}`
  7621. }
  7622. error[FiberFailureId] = FiberFailureId
  7623. error[FiberFailureCauseId] = cause
  7624. error.toString = () => cause_pretty_pretty(cause)
  7625. error[NodePrint] = () => error.toString()
  7626. return error
  7627. })(result.i0)
  7628. )
  7629. }
  7630. })
  7631. })
  7632. )
  7633. class RuntimeImpl {
  7634. constructor(context, runtimeFlags, fiberRefs) {
  7635. this.context = context
  7636. this.runtimeFlags = runtimeFlags
  7637. this.fiberRefs = fiberRefs
  7638. }
  7639. }
  7640. const runtime_make = (context, runtimeFlags, fiberRefs) =>
  7641. new RuntimeImpl(context, runtimeFlags, fiberRefs),
  7642. defaultRuntimeFlags = runtimeFlags_make(1, 32),
  7643. Effect_asUnit = core_asUnit,
  7644. Effect_catchAllCause = catchAllCause,
  7645. Effect_bind = effect_bind,
  7646. Effect_bindValue = bindValue,
  7647. Effect_Do = effect_Do,
  7648. Effect_fail = core_fail,
  7649. Effect_filterOrElse = filterOrElse,
  7650. Effect_filterOrFail = filterOrFail,
  7651. Effect_flatMap = core_flatMap,
  7652. Effect_forEach = core_forEach,
  7653. Effect_fromOption = core_fromOption,
  7654. Effect_ignore = ignore,
  7655. Effect_isSuccess = effect_isSuccess,
  7656. Effect_log = log,
  7657. Effect_logDebug = logDebug,
  7658. Effect_logInfo = logInfo,
  7659. Effect_logInfoCauseMessage = logInfoCauseMessage,
  7660. Effect_logAnnotate = logAnnotate,
  7661. Effect_map = core_map,
  7662. Effect_orElseSucceed = orElseSucceed,
  7663. Effect_promise = promise,
  7664. Effect_provideSomeLayer = provideSomeLayer,
  7665. Effect_some = fiberRuntime_some,
  7666. Effect_succeed = succeed,
  7667. Effect_sync = sync,
  7668. Effect_tap = core_tap,
  7669. Effect_all = effect_all,
  7670. Effect_unit = core_unit,
  7671. runPromise = unsafeRunPromise(
  7672. runtime_make(
  7673. mjs_Context_empty(),
  7674. defaultRuntimeFlags,
  7675. FiberRefs_unsafeMake(new Map())
  7676. )
  7677. ),
  7678. Effect_unsome = unsome,
  7679. Effect_zipLeft = zipLeft,
  7680. Effect_zipRight = zipRight,
  7681. external_rxjs_namespaceObject = rxjs,
  7682. lib = observer => value => {
  7683. observer.next(value)
  7684. }
  7685. Promise.resolve(!1)
  7686. Promise.resolve(!0)
  7687. var PROMISE_RESOLVED_VOID = Promise.resolve()
  7688. function util_sleep(time, resolveWith) {
  7689. time || (time = 0)
  7690. return new Promise(function (res) {
  7691. return setTimeout(function () {
  7692. return res(resolveWith)
  7693. }, time)
  7694. })
  7695. }
  7696. function randomToken() {
  7697. return Math.random().toString(36).substring(2)
  7698. }
  7699. var lastMs = 0,
  7700. additional = 0
  7701. function microSeconds() {
  7702. var ms = new Date().getTime()
  7703. if (ms === lastMs) return 1e3 * ms + ++additional
  7704. lastMs = ms
  7705. additional = 0
  7706. return 1e3 * ms
  7707. }
  7708. var isNode =
  7709. "[object process]" ===
  7710. Object.prototype.toString.call(
  7711. "undefined" != typeof process ? process : 0
  7712. )
  7713. const methods_native = {
  7714. create: function (channelName) {
  7715. var state = {
  7716. messagesCallback: null,
  7717. bc: new BroadcastChannel(channelName),
  7718. subFns: [],
  7719. }
  7720. state.bc.onmessage = function (msg) {
  7721. state.messagesCallback && state.messagesCallback(msg.data)
  7722. }
  7723. return state
  7724. },
  7725. close: function (channelState) {
  7726. channelState.bc.close()
  7727. channelState.subFns = []
  7728. },
  7729. onMessage: function (channelState, fn) {
  7730. channelState.messagesCallback = fn
  7731. },
  7732. postMessage: function (channelState, messageJson) {
  7733. try {
  7734. channelState.bc.postMessage(messageJson, !1)
  7735. return PROMISE_RESOLVED_VOID
  7736. } catch (err) {
  7737. return Promise.reject(err)
  7738. }
  7739. },
  7740. canBeUsed: function () {
  7741. if (isNode && "undefined" == typeof window) return !1
  7742. if ("function" == typeof BroadcastChannel) {
  7743. if (BroadcastChannel._pubkey)
  7744. throw new Error(
  7745. "BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill"
  7746. )
  7747. return !0
  7748. }
  7749. return !1
  7750. },
  7751. type: "native",
  7752. averageResponseTime: function () {
  7753. return 150
  7754. },
  7755. microSeconds,
  7756. }
  7757. var ObliviousSet = (function () {
  7758. function ObliviousSet(ttl) {
  7759. this.ttl = ttl
  7760. this.map = new Map()
  7761. this._to = !1
  7762. }
  7763. ObliviousSet.prototype.has = function (value) {
  7764. return this.map.has(value)
  7765. }
  7766. ObliviousSet.prototype.add = function (value) {
  7767. var _this = this
  7768. this.map.set(value, now())
  7769. if (!this._to) {
  7770. this._to = !0
  7771. setTimeout(function () {
  7772. _this._to = !1
  7773. !(function (obliviousSet) {
  7774. for (
  7775. var olderThen = now() - obliviousSet.ttl,
  7776. iterator = obliviousSet.map[Symbol.iterator]();
  7777. ;
  7778.  
  7779. ) {
  7780. var next = iterator.next().value
  7781. if (!next) return
  7782. var value = next[0]
  7783. if (!(next[1] < olderThen)) return
  7784. obliviousSet.map.delete(value)
  7785. }
  7786. })(_this)
  7787. }, 0)
  7788. }
  7789. }
  7790. ObliviousSet.prototype.clear = function () {
  7791. this.map.clear()
  7792. }
  7793. return ObliviousSet
  7794. })()
  7795. function now() {
  7796. return new Date().getTime()
  7797. }
  7798. function options_fillOptionsWithDefaults() {
  7799. var originalOptions =
  7800. arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
  7801. options = JSON.parse(JSON.stringify(originalOptions))
  7802. void 0 === options.webWorkerSupport && (options.webWorkerSupport = !0)
  7803. options.idb || (options.idb = {})
  7804. options.idb.ttl || (options.idb.ttl = 45e3)
  7805. options.idb.fallbackInterval || (options.idb.fallbackInterval = 150)
  7806. originalOptions.idb &&
  7807. "function" == typeof originalOptions.idb.onclose &&
  7808. (options.idb.onclose = originalOptions.idb.onclose)
  7809. options.localstorage || (options.localstorage = {})
  7810. options.localstorage.removeTimeout ||
  7811. (options.localstorage.removeTimeout = 6e4)
  7812. originalOptions.methods && (options.methods = originalOptions.methods)
  7813. options.node || (options.node = {})
  7814. options.node.ttl || (options.node.ttl = 12e4)
  7815. options.node.maxParallelWrites || (options.node.maxParallelWrites = 2048)
  7816. void 0 === options.node.useFastPath && (options.node.useFastPath = !0)
  7817. return options
  7818. }
  7819. var TRANSACTION_SETTINGS = { durability: "relaxed" }
  7820. function getIdb() {
  7821. if ("undefined" != typeof indexedDB) return indexedDB
  7822. if ("undefined" != typeof window) {
  7823. if (void 0 !== window.mozIndexedDB) return window.mozIndexedDB
  7824. if (void 0 !== window.webkitIndexedDB) return window.webkitIndexedDB
  7825. if (void 0 !== window.msIndexedDB) return window.msIndexedDB
  7826. }
  7827. return !1
  7828. }
  7829. function commitIndexedDBTransaction(tx) {
  7830. tx.commit && tx.commit()
  7831. }
  7832. function _readLoop(state) {
  7833. state.closed ||
  7834. readNewMessages(state)
  7835. .then(function () {
  7836. return util_sleep(state.options.idb.fallbackInterval)
  7837. })
  7838. .then(function () {
  7839. return _readLoop(state)
  7840. })
  7841. }
  7842. function readNewMessages(state) {
  7843. return state.closed
  7844. ? PROMISE_RESOLVED_VOID
  7845. : state.messagesCallback
  7846. ? (function (db, lastCursorId) {
  7847. var tx = db.transaction(
  7848. "messages",
  7849. "readonly",
  7850. TRANSACTION_SETTINGS
  7851. ),
  7852. objectStore = tx.objectStore("messages"),
  7853. ret = [],
  7854. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  7855. if (objectStore.getAll) {
  7856. var getAllRequest = objectStore.getAll(keyRangeValue)
  7857. return new Promise(function (res, rej) {
  7858. getAllRequest.onerror = function (err) {
  7859. return rej(err)
  7860. }
  7861. getAllRequest.onsuccess = function (e) {
  7862. res(e.target.result)
  7863. }
  7864. })
  7865. }
  7866. return new Promise(function (res, rej) {
  7867. var openCursorRequest = (function () {
  7868. try {
  7869. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  7870. return objectStore.openCursor(keyRangeValue)
  7871. } catch (e) {
  7872. return objectStore.openCursor()
  7873. }
  7874. })()
  7875. openCursorRequest.onerror = function (err) {
  7876. return rej(err)
  7877. }
  7878. openCursorRequest.onsuccess = function (ev) {
  7879. var cursor = ev.target.result
  7880. if (cursor)
  7881. if (cursor.value.id < lastCursorId + 1)
  7882. cursor.continue(lastCursorId + 1)
  7883. else {
  7884. ret.push(cursor.value)
  7885. cursor.continue()
  7886. }
  7887. else {
  7888. commitIndexedDBTransaction(tx)
  7889. res(ret)
  7890. }
  7891. }
  7892. })
  7893. })(state.db, state.lastCursorId).then(function (newerMessages) {
  7894. var useMessages = newerMessages
  7895. .filter(function (msgObj) {
  7896. return !!msgObj
  7897. })
  7898. .map(function (msgObj) {
  7899. msgObj.id > state.lastCursorId &&
  7900. (state.lastCursorId = msgObj.id)
  7901. return msgObj
  7902. })
  7903. .filter(function (msgObj) {
  7904. return (function (msgObj, state) {
  7905. return !(
  7906. msgObj.uuid === state.uuid ||
  7907. state.eMIs.has(msgObj.id) ||
  7908. msgObj.data.time < state.messagesCallbackTime
  7909. )
  7910. })(msgObj, state)
  7911. })
  7912. .sort(function (msgObjA, msgObjB) {
  7913. return msgObjA.time - msgObjB.time
  7914. })
  7915. useMessages.forEach(function (msgObj) {
  7916. if (state.messagesCallback) {
  7917. state.eMIs.add(msgObj.id)
  7918. state.messagesCallback(msgObj.data)
  7919. }
  7920. })
  7921. return PROMISE_RESOLVED_VOID
  7922. })
  7923. : PROMISE_RESOLVED_VOID
  7924. }
  7925. const indexed_db = {
  7926. create: function (channelName, options) {
  7927. options = options_fillOptionsWithDefaults(options)
  7928. return (function (channelName) {
  7929. var dbName = "pubkey.broadcast-channel-0-" + channelName,
  7930. openRequest = getIdb().open(dbName)
  7931. openRequest.onupgradeneeded = function (ev) {
  7932. ev.target.result.createObjectStore("messages", {
  7933. keyPath: "id",
  7934. autoIncrement: !0,
  7935. })
  7936. }
  7937. return new Promise(function (res, rej) {
  7938. openRequest.onerror = function (ev) {
  7939. return rej(ev)
  7940. }
  7941. openRequest.onsuccess = function () {
  7942. res(openRequest.result)
  7943. }
  7944. })
  7945. })(channelName).then(function (db) {
  7946. var state = {
  7947. closed: !1,
  7948. lastCursorId: 0,
  7949. channelName,
  7950. options,
  7951. uuid: randomToken(),
  7952. eMIs: new ObliviousSet(2 * options.idb.ttl),
  7953. writeBlockPromise: PROMISE_RESOLVED_VOID,
  7954. messagesCallback: null,
  7955. readQueuePromises: [],
  7956. db,
  7957. }
  7958. db.onclose = function () {
  7959. state.closed = !0
  7960. options.idb.onclose && options.idb.onclose()
  7961. }
  7962. _readLoop(state)
  7963. return state
  7964. })
  7965. },
  7966. close: function (channelState) {
  7967. channelState.closed = !0
  7968. channelState.db.close()
  7969. },
  7970. onMessage: function (channelState, fn, time) {
  7971. channelState.messagesCallbackTime = time
  7972. channelState.messagesCallback = fn
  7973. readNewMessages(channelState)
  7974. },
  7975. postMessage: function (channelState, messageJson) {
  7976. channelState.writeBlockPromise = channelState.writeBlockPromise
  7977. .then(function () {
  7978. return (function (db, readerUuid, messageJson) {
  7979. var writeObject = {
  7980. uuid: readerUuid,
  7981. time: new Date().getTime(),
  7982. data: messageJson,
  7983. },
  7984. tx = db.transaction(
  7985. ["messages"],
  7986. "readwrite",
  7987. TRANSACTION_SETTINGS
  7988. )
  7989. return new Promise(function (res, rej) {
  7990. tx.oncomplete = function () {
  7991. return res()
  7992. }
  7993. tx.onerror = function (ev) {
  7994. return rej(ev)
  7995. }
  7996. tx.objectStore("messages").add(writeObject)
  7997. commitIndexedDBTransaction(tx)
  7998. })
  7999. })(channelState.db, channelState.uuid, messageJson)
  8000. })
  8001. .then(function () {
  8002. 0 === Math.floor(11 * Math.random() + 0) &&
  8003. ((db = channelState.db),
  8004. (ttl = channelState.options.idb.ttl),
  8005. (function (db, ttl) {
  8006. var olderThen = new Date().getTime() - ttl,
  8007. tx = db.transaction(
  8008. "messages",
  8009. "readonly",
  8010. TRANSACTION_SETTINGS
  8011. ),
  8012. objectStore = tx.objectStore("messages"),
  8013. ret = []
  8014. return new Promise(function (res) {
  8015. objectStore.openCursor().onsuccess = function (ev) {
  8016. var cursor = ev.target.result
  8017. if (cursor) {
  8018. var msgObk = cursor.value
  8019. if (!(msgObk.time < olderThen)) {
  8020. commitIndexedDBTransaction(tx)
  8021. res(ret)
  8022. return
  8023. }
  8024. ret.push(msgObk)
  8025. cursor.continue()
  8026. } else res(ret)
  8027. }
  8028. })
  8029. })(db, ttl).then(function (tooOld) {
  8030. return (function (db, ids) {
  8031. var objectStore = db
  8032. .transaction(
  8033. ["messages"],
  8034. "readwrite",
  8035. TRANSACTION_SETTINGS
  8036. )
  8037. .objectStore("messages")
  8038. return Promise.all(
  8039. ids.map(function (id) {
  8040. var deleteRequest = objectStore.delete(id)
  8041. return new Promise(function (res) {
  8042. deleteRequest.onsuccess = function () {
  8043. return res()
  8044. }
  8045. })
  8046. })
  8047. )
  8048. })(
  8049. db,
  8050. tooOld.map(function (msg) {
  8051. return msg.id
  8052. })
  8053. )
  8054. }))
  8055. var db, ttl
  8056. })
  8057. return channelState.writeBlockPromise
  8058. },
  8059. canBeUsed: function () {
  8060. return !isNode && !!getIdb()
  8061. },
  8062. type: "idb",
  8063. averageResponseTime: function (options) {
  8064. return 2 * options.idb.fallbackInterval
  8065. },
  8066. microSeconds,
  8067. }
  8068. function getLocalStorage() {
  8069. var localStorage
  8070. if ("undefined" == typeof window) return null
  8071. try {
  8072. localStorage = window.localStorage
  8073. localStorage =
  8074. window["ie8-eventlistener/storage"] || window.localStorage
  8075. } catch (e) {}
  8076. return localStorage
  8077. }
  8078. function storageKey(channelName) {
  8079. return "pubkey.broadcastChannel-" + channelName
  8080. }
  8081. function localstorage_canBeUsed() {
  8082. if (isNode) return !1
  8083. var ls = getLocalStorage()
  8084. if (!ls) return !1
  8085. try {
  8086. var key = "__broadcastchannel_check"
  8087. ls.setItem(key, "works")
  8088. ls.removeItem(key)
  8089. } catch (e) {
  8090. return !1
  8091. }
  8092. return !0
  8093. }
  8094. const localstorage = {
  8095. create: function (channelName, options) {
  8096. options = options_fillOptionsWithDefaults(options)
  8097. if (!localstorage_canBeUsed())
  8098. throw new Error("BroadcastChannel: localstorage cannot be used")
  8099. var uuid = randomToken(),
  8100. eMIs = new ObliviousSet(options.localstorage.removeTimeout),
  8101. state = { channelName, uuid, eMIs }
  8102. state.listener = (function (channelName, fn) {
  8103. var key = storageKey(channelName),
  8104. listener = function (ev) {
  8105. ev.key === key &&
  8106. (function (msgObj) {
  8107. if (
  8108. state.messagesCallback &&
  8109. msgObj.uuid !== uuid &&
  8110. msgObj.token &&
  8111. !eMIs.has(msgObj.token) &&
  8112. !(
  8113. msgObj.data.time &&
  8114. msgObj.data.time < state.messagesCallbackTime
  8115. )
  8116. ) {
  8117. eMIs.add(msgObj.token)
  8118. state.messagesCallback(msgObj.data)
  8119. }
  8120. })(JSON.parse(ev.newValue))
  8121. }
  8122. window.addEventListener("storage", listener)
  8123. return listener
  8124. })(channelName)
  8125. return state
  8126. },
  8127. close: function (channelState) {
  8128. ;(listener = channelState.listener),
  8129. window.removeEventListener("storage", listener)
  8130. var listener
  8131. },
  8132. onMessage: function (channelState, fn, time) {
  8133. channelState.messagesCallbackTime = time
  8134. channelState.messagesCallback = fn
  8135. },
  8136. postMessage: function (channelState, messageJson) {
  8137. return new Promise(function (res) {
  8138. util_sleep().then(function () {
  8139. var key = storageKey(channelState.channelName),
  8140. writeObj = {
  8141. token: randomToken(),
  8142. time: new Date().getTime(),
  8143. data: messageJson,
  8144. uuid: channelState.uuid,
  8145. },
  8146. value = JSON.stringify(writeObj)
  8147. getLocalStorage().setItem(key, value)
  8148. var ev = document.createEvent("Event")
  8149. ev.initEvent("storage", !0, !0)
  8150. ev.key = key
  8151. ev.newValue = value
  8152. window.dispatchEvent(ev)
  8153. res()
  8154. })
  8155. })
  8156. },
  8157. canBeUsed: localstorage_canBeUsed,
  8158. type: "localstorage",
  8159. averageResponseTime: function () {
  8160. var userAgent = navigator.userAgent.toLowerCase()
  8161. return userAgent.includes("safari") && !userAgent.includes("chrome")
  8162. ? 240
  8163. : 120
  8164. },
  8165. microSeconds,
  8166. }
  8167. var simulate_microSeconds = microSeconds,
  8168. SIMULATE_CHANNELS = new Set()
  8169. const simulate = {
  8170. create: function (channelName) {
  8171. var state = { name: channelName, messagesCallback: null }
  8172. SIMULATE_CHANNELS.add(state)
  8173. return state
  8174. },
  8175. close: function (channelState) {
  8176. SIMULATE_CHANNELS.delete(channelState)
  8177. },
  8178. onMessage: function (channelState, fn) {
  8179. channelState.messagesCallback = fn
  8180. },
  8181. postMessage: function (channelState, messageJson) {
  8182. return new Promise(function (res) {
  8183. return setTimeout(function () {
  8184. Array.from(SIMULATE_CHANNELS)
  8185. .filter(function (channel) {
  8186. return channel.name === channelState.name
  8187. })
  8188. .filter(function (channel) {
  8189. return channel !== channelState
  8190. })
  8191. .filter(function (channel) {
  8192. return !!channel.messagesCallback
  8193. })
  8194. .forEach(function (channel) {
  8195. return channel.messagesCallback(messageJson)
  8196. })
  8197. res()
  8198. }, 5)
  8199. })
  8200. },
  8201. canBeUsed: function () {
  8202. return !0
  8203. },
  8204. type: "simulate",
  8205. averageResponseTime: function () {
  8206. return 5
  8207. },
  8208. microSeconds: simulate_microSeconds,
  8209. }
  8210. var METHODS = [methods_native, indexed_db, localstorage],
  8211. OPEN_BROADCAST_CHANNELS = new Set(),
  8212. lastId = 0,
  8213. broadcast_channel_BroadcastChannel = function (name, options) {
  8214. this.id = lastId++
  8215. OPEN_BROADCAST_CHANNELS.add(this)
  8216. this.name = name
  8217. this.options = options_fillOptionsWithDefaults(options)
  8218. this.method = (function (options) {
  8219. var chooseMethods = []
  8220. .concat(options.methods, METHODS)
  8221. .filter(Boolean)
  8222. if (options.type) {
  8223. if ("simulate" === options.type) return simulate
  8224. var ret = chooseMethods.find(function (m) {
  8225. return m.type === options.type
  8226. })
  8227. if (ret) return ret
  8228. throw new Error("method-type " + options.type + " not found")
  8229. }
  8230. options.webWorkerSupport ||
  8231. isNode ||
  8232. (chooseMethods = chooseMethods.filter(function (m) {
  8233. return "idb" !== m.type
  8234. }))
  8235. var useMethod = chooseMethods.find(function (method) {
  8236. return method.canBeUsed()
  8237. })
  8238. if (useMethod) return useMethod
  8239. throw new Error(
  8240. "No useable method found in " +
  8241. JSON.stringify(
  8242. METHODS.map(function (m) {
  8243. return m.type
  8244. })
  8245. )
  8246. )
  8247. })(this.options)
  8248. this._iL = !1
  8249. this._onML = null
  8250. this._addEL = { message: [], internal: [] }
  8251. this._uMP = new Set()
  8252. this._befC = []
  8253. this._prepP = null
  8254. !(function (channel) {
  8255. var obj,
  8256. maybePromise = channel.method.create(channel.name, channel.options)
  8257. if ((obj = maybePromise) && "function" == typeof obj.then) {
  8258. channel._prepP = maybePromise
  8259. maybePromise.then(function (s) {
  8260. channel._state = s
  8261. })
  8262. } else channel._state = maybePromise
  8263. })(this)
  8264. }
  8265. broadcast_channel_BroadcastChannel._pubkey = !0
  8266. broadcast_channel_BroadcastChannel.prototype = {
  8267. postMessage: function (msg) {
  8268. if (this.closed)
  8269. throw new Error(
  8270. "BroadcastChannel.postMessage(): Cannot post message after channel has closed " +
  8271. JSON.stringify(msg)
  8272. )
  8273. return _post(this, "message", msg)
  8274. },
  8275. postInternal: function (msg) {
  8276. return _post(this, "internal", msg)
  8277. },
  8278. set onmessage(fn) {
  8279. var listenObj = { time: this.method.microSeconds(), fn }
  8280. _removeListenerObject(this, "message", this._onML)
  8281. if (fn && "function" == typeof fn) {
  8282. this._onML = listenObj
  8283. _addListenerObject(this, "message", listenObj)
  8284. } else this._onML = null
  8285. },
  8286. addEventListener: function (type, fn) {
  8287. _addListenerObject(this, type, { time: this.method.microSeconds(), fn })
  8288. },
  8289. removeEventListener: function (type, fn) {
  8290. _removeListenerObject(
  8291. this,
  8292. type,
  8293. this._addEL[type].find(function (obj) {
  8294. return obj.fn === fn
  8295. })
  8296. )
  8297. },
  8298. close: function () {
  8299. var _this = this
  8300. if (!this.closed) {
  8301. OPEN_BROADCAST_CHANNELS.delete(this)
  8302. this.closed = !0
  8303. var awaitPrepare = this._prepP ? this._prepP : PROMISE_RESOLVED_VOID
  8304. this._onML = null
  8305. this._addEL.message = []
  8306. return awaitPrepare
  8307. .then(function () {
  8308. return Promise.all(Array.from(_this._uMP))
  8309. })
  8310. .then(function () {
  8311. return Promise.all(
  8312. _this._befC.map(function (fn) {
  8313. return fn()
  8314. })
  8315. )
  8316. })
  8317. .then(function () {
  8318. return _this.method.close(_this._state)
  8319. })
  8320. }
  8321. },
  8322. get type() {
  8323. return this.method.type
  8324. },
  8325. get isClosed() {
  8326. return this.closed
  8327. },
  8328. }
  8329. function _post(broadcastChannel, type, msg) {
  8330. var msgObj = {
  8331. time: broadcastChannel.method.microSeconds(),
  8332. type,
  8333. data: msg,
  8334. }
  8335. return (
  8336. broadcastChannel._prepP
  8337. ? broadcastChannel._prepP
  8338. : PROMISE_RESOLVED_VOID
  8339. ).then(function () {
  8340. var sendPromise = broadcastChannel.method.postMessage(
  8341. broadcastChannel._state,
  8342. msgObj
  8343. )
  8344. broadcastChannel._uMP.add(sendPromise)
  8345. sendPromise.catch().then(function () {
  8346. return broadcastChannel._uMP.delete(sendPromise)
  8347. })
  8348. return sendPromise
  8349. })
  8350. }
  8351. function _hasMessageListeners(channel) {
  8352. return (
  8353. channel._addEL.message.length > 0 || channel._addEL.internal.length > 0
  8354. )
  8355. }
  8356. function _addListenerObject(channel, type, obj) {
  8357. channel._addEL[type].push(obj)
  8358. !(function (channel) {
  8359. if (!channel._iL && _hasMessageListeners(channel)) {
  8360. var listenerFn = function (msgObj) {
  8361. channel._addEL[msgObj.type].forEach(function (listenerObject) {
  8362. var minMessageTime = listenerObject.time - 1e5
  8363. msgObj.time >= minMessageTime && listenerObject.fn(msgObj.data)
  8364. })
  8365. },
  8366. time = channel.method.microSeconds()
  8367. if (channel._prepP)
  8368. channel._prepP.then(function () {
  8369. channel._iL = !0
  8370. channel.method.onMessage(channel._state, listenerFn, time)
  8371. })
  8372. else {
  8373. channel._iL = !0
  8374. channel.method.onMessage(channel._state, listenerFn, time)
  8375. }
  8376. }
  8377. })(channel)
  8378. }
  8379. function _removeListenerObject(channel, type, obj) {
  8380. channel._addEL[type] = channel._addEL[type].filter(function (o) {
  8381. return o !== obj
  8382. })
  8383. !(function (channel) {
  8384. if (channel._iL && !_hasMessageListeners(channel)) {
  8385. channel._iL = !1
  8386. var time = channel.method.microSeconds()
  8387. channel.method.onMessage(channel._state, null, time)
  8388. }
  8389. })(channel)
  8390. }
  8391. var browser = __webpack_require__(661),
  8392. browser_default = __webpack_require__.n(browser)
  8393. const es_browser = {
  8394. add: function (fn) {
  8395. if (
  8396. "function" == typeof WorkerGlobalScope &&
  8397. self instanceof WorkerGlobalScope
  8398. );
  8399. else {
  8400. if ("function" != typeof window.addEventListener) return
  8401. window.addEventListener(
  8402. "beforeunload",
  8403. function () {
  8404. fn()
  8405. },
  8406. !0
  8407. )
  8408. window.addEventListener(
  8409. "unload",
  8410. function () {
  8411. fn()
  8412. },
  8413. !0
  8414. )
  8415. }
  8416. },
  8417. }
  8418. var node_ignored_ = __webpack_require__(938),
  8419. node_ignored_default = __webpack_require__.n(node_ignored_)
  8420. browser_default() && node_ignored_default(), new Set()
  8421. const external_DeepDiff_namespaceObject = DeepDiff
  8422. var fast_deep_equal = __webpack_require__(204),
  8423. fast_deep_equal_default = __webpack_require__.n(fast_deep_equal)
  8424. const mapObject = f => o =>
  8425. pipe(Object.entries(o), ReadonlyArray_map(f), Object.fromEntries),
  8426. makePageState = mapObject(([k, v]) => [
  8427. k,
  8428. { ele: Option_none(), read: v },
  8429. ]),
  8430. external_jsep_namespaceObject = jsep
  8431. var external_jsep_default = __webpack_require__.n(
  8432. external_jsep_namespaceObject
  8433. ),
  8434. u = {
  8435. "||": function (r, e) {
  8436. return r || e
  8437. },
  8438. "&&": function (r, e) {
  8439. return r && e
  8440. },
  8441. "|": function (r, e) {
  8442. return r | e
  8443. },
  8444. "^": function (r, e) {
  8445. return r ^ e
  8446. },
  8447. "&": function (r, e) {
  8448. return r & e
  8449. },
  8450. "==": function (r, e) {
  8451. return r == e
  8452. },
  8453. "!=": function (r, e) {
  8454. return r != e
  8455. },
  8456. "===": function (r, e) {
  8457. return r === e
  8458. },
  8459. "!==": function (r, e) {
  8460. return r !== e
  8461. },
  8462. "<": function (r, e) {
  8463. return r < e
  8464. },
  8465. ">": function (r, e) {
  8466. return r > e
  8467. },
  8468. "<=": function (r, e) {
  8469. return r <= e
  8470. },
  8471. ">=": function (r, e) {
  8472. return r >= e
  8473. },
  8474. "<<": function (r, e) {
  8475. return r << e
  8476. },
  8477. ">>": function (r, e) {
  8478. return r >> e
  8479. },
  8480. ">>>": function (r, e) {
  8481. return r >>> e
  8482. },
  8483. "+": function (r, e) {
  8484. return r + e
  8485. },
  8486. "-": function (r, e) {
  8487. return r - e
  8488. },
  8489. "*": function (r, e) {
  8490. return r * e
  8491. },
  8492. "/": function (r, e) {
  8493. return r / e
  8494. },
  8495. "%": function (r, e) {
  8496. return r % e
  8497. },
  8498. },
  8499. i = {
  8500. "-": function (r) {
  8501. return -r
  8502. },
  8503. "+": function (r) {
  8504. return +r
  8505. },
  8506. "~": function (r) {
  8507. return ~r
  8508. },
  8509. "!": function (r) {
  8510. return !r
  8511. },
  8512. }
  8513. function s(r, e) {
  8514. return r.map(function (r) {
  8515. return a(r, e)
  8516. })
  8517. }
  8518. function c(r, e) {
  8519. var n,
  8520. t = a(r.object, e)
  8521. if (
  8522. ((n = r.computed ? a(r.property, e) : r.property.name),
  8523. /^__proto__|prototype|constructor$/.test(n))
  8524. )
  8525. throw Error('Access to member "' + n + '" disallowed.')
  8526. return [t, t[n]]
  8527. }
  8528. function a(r, e) {
  8529. var n = r
  8530. switch (n.type) {
  8531. case "ArrayExpression":
  8532. return s(n.elements, e)
  8533. case "BinaryExpression":
  8534. return u[n.operator](a(n.left, e), a(n.right, e))
  8535. case "CallExpression":
  8536. var t, o, l
  8537. if (
  8538. ("MemberExpression" === n.callee.type
  8539. ? ((t = (l = c(n.callee, e))[0]), (o = l[1]))
  8540. : (o = a(n.callee, e)),
  8541. "function" != typeof o)
  8542. )
  8543. return
  8544. return o.apply(t, s(n.arguments, e))
  8545. case "ConditionalExpression":
  8546. return a(n.test, e) ? a(n.consequent, e) : a(n.alternate, e)
  8547. case "Identifier":
  8548. return e[n.name]
  8549. case "Literal":
  8550. return n.value
  8551. case "LogicalExpression":
  8552. return "||" === n.operator
  8553. ? a(n.left, e) || a(n.right, e)
  8554. : "&&" === n.operator
  8555. ? a(n.left, e) && a(n.right, e)
  8556. : u[n.operator](a(n.left, e), a(n.right, e))
  8557. case "MemberExpression":
  8558. return c(n, e)[1]
  8559. case "ThisExpression":
  8560. return e
  8561. case "UnaryExpression":
  8562. return i[n.operator](a(n.argument, e))
  8563. default:
  8564. return
  8565. }
  8566. }
  8567. const defaultFilter = config =>
  8568. external_jsep_default()(
  8569. `\nor([\nRA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  8570. config.bannedWords
  8571. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nRA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  8572. config.bannedWordRegexs
  8573. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nO.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  8574. config.bannedUsers
  8575. )})\n)(authorID)\n])\n`
  8576. ),
  8577. Chainable_bind = F =>
  8578. Function_dual(3, (self, name, f) =>
  8579. F.flatMap(self, a =>
  8580. F.map(f(a), b => Object.assign({}, a, { [name]: b }))
  8581. )
  8582. ),
  8583. Identity_map = Function_dual(2, (self, f) => f(self)),
  8584. Identity_imap = Covariant_imap(Identity_map),
  8585. Identity_Covariant = { imap: Identity_imap, map: Identity_map },
  8586. Identity_Invariant = { imap: Identity_imap },
  8587. Identity_Chainable = {
  8588. imap: Identity_imap,
  8589. map: Identity_map,
  8590. flatMap: Function_dual(2, (self, f) => f(self)),
  8591. },
  8592. Identity_SemiProduct = {
  8593. imap: Identity_imap,
  8594. product: (self, that) => [self, that],
  8595. productMany: (self, collection) => [self, ...collection],
  8596. },
  8597. Identity_bindTo = Invariant_bindTo(Identity_Invariant),
  8598. Identity_let_ = let_(Identity_Covariant),
  8599. Identity_bind = Chainable_bind(Identity_Chainable),
  8600. Identity_andThenBind = SemiProduct_andThenBind(Identity_SemiProduct),
  8601. external_astring_namespaceObject = astring,
  8602. fycKey = key => `FYC_${key}`,
  8603. languages = ["FYC_EN", "FYC_JA"],
  8604. stringsArgs = [
  8605. [],
  8606. flow(split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty))),
  8607. join("\n"),
  8608. ],
  8609. sc = (k, d) => {
  8610. return (
  8611. (key = fycKey(k)),
  8612. (defaultValue = d),
  8613. {
  8614. gmKey: key,
  8615. getValue: Effect_promise(
  8616. async () => (await GM.getValue(key)) ?? defaultValue
  8617. ),
  8618. defaultValue,
  8619. toGm: Function_identity,
  8620. }
  8621. )
  8622. var key, defaultValue
  8623. },
  8624. ic = (k, d, c, g) => {
  8625. return (
  8626. (key = fycKey(k)),
  8627. (toConfig = c),
  8628. pipe(
  8629. { gmKey: key, defaultValue: (defaultValue = d), toGm: g },
  8630. Identity_andThenBind(
  8631. "getValue",
  8632. pipe(
  8633. Effect_promise(() => GM.getValue(key)),
  8634. Effect_map(x => (void 0 !== x ? toConfig(x) : defaultValue))
  8635. )
  8636. )
  8637. )
  8638. )
  8639. var key, defaultValue, toConfig
  8640. },
  8641. src_defaultGMConfig = pipe(
  8642. {
  8643. lang: ic(
  8644. "LANG",
  8645. "FYC_EN",
  8646. x => (languages.includes(x) ? x : "FYC_EN"),
  8647. x => x
  8648. ),
  8649. font: sc("FONT", "MS PGothic"),
  8650. chatOpacity: sc("OPACITY", 0.8),
  8651. color: sc("COLOR", "#ffffff"),
  8652. ownerColor: sc("COLOR_OWNER", "#ffd600"),
  8653. moderatorColor: sc("COLOR_MODERATOR", "#c564ff"),
  8654. memberColor: sc("COLOR_MEMBER", "#9fffff"),
  8655. fontSize: sc("SIZE", 1),
  8656. fontWeight: sc("WEIGHT", 730),
  8657. shadowFontWeight: sc("WEIGHT_SHADOW", 1),
  8658. maxChatCount: sc("LIMIT", 40),
  8659. flowSpeed: sc("SPEED", 18),
  8660. maxChatLength: sc("MAX", 100),
  8661. laneCount: sc("LANE_DIV", 12),
  8662. bannedWords: ic("NG_WORDS", ...stringsArgs),
  8663. bannedWordRegexs: ic("NG_REG_WORDS", ...stringsArgs),
  8664. bannedUsers: ic("NG_USERS", ...stringsArgs),
  8665. createChats: sc("TOGGLE_CREATE_COMMENTS", !0),
  8666. noOverlap: sc("NO_OVERLAP", !0),
  8667. createBanButton: sc("NG_BUTTON", !0),
  8668. simplifyChatField: sc("SIMPLE_CHAT_FIELD", !1),
  8669. displayModName: sc("DISPLAY_MODERATOR_NAME", !0),
  8670. displaySuperChatAuthor: sc("DISPLAY_SUPER_CHAT_AUTHOR", !0),
  8671. textOnly: sc("TEXT_ONLY", !1),
  8672. timingFunction: sc("TIMING_FUNCTION", "linear"),
  8673. displayChats: sc("DISPLAY_COMMENTS", !0),
  8674. minSpacing: sc("MIN_SPACING", 0.5),
  8675. fieldScale: sc("FIELD_SCALE", 1),
  8676. flowY1: sc("flowY1", 0),
  8677. flowY2: sc("flowY2", 1),
  8678. flowX1: sc("flowX1", 0),
  8679. flowX2: sc("flowX2", 1),
  8680. shadowColor: sc("shadowColor", "#000000"),
  8681. },
  8682. Identity_bind("filterExp", x =>
  8683. ic(
  8684. "filterExp",
  8685. external_jsep_default()(
  8686. `\n or([\n RA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  8687. x.bannedWords.defaultValue
  8688. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n RA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  8689. x.bannedWordRegexs.defaultValue
  8690. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n O.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  8691. x.bannedUsers.defaultValue
  8692. )})\n )(authorID)\n ])\n `
  8693. ),
  8694. external_jsep_default(),
  8695. external_astring_namespaceObject.generate
  8696. )
  8697. )
  8698. ),
  8699. src_listeningBroadcastConfigKeys = [
  8700. "lang",
  8701. "bannedWords",
  8702. "bannedWordRegexs",
  8703. "bannedUsers",
  8704. "filterExp",
  8705. "simplifyChatField",
  8706. "createBanButton",
  8707. "fieldScale",
  8708. ],
  8709. src_flatMapOption = f => self =>
  8710. Effect_flatMap(flow(f, Effect_fromOption))(self),
  8711. chatApp = pipe(
  8712. Effect_sync(() => document.querySelector("#chatframe")),
  8713. Effect_map(
  8714. flow(
  8715. fromNullable,
  8716. Option_filter(
  8717. flow(
  8718. x => x.contentDocument?.readyState,
  8719. x => "loading" === x || "complete" === x
  8720. )
  8721. ),
  8722. flatMapNullable(x => x.contentDocument),
  8723. orElse(() => Option_some(document)),
  8724. flatMapNullable(x => x.querySelector("yt-live-chat-app"))
  8725. )
  8726. ),
  8727. Effect_some
  8728. ),
  8729. livePageYt = {
  8730. toggleChatBtnParent: pipe(
  8731. Effect_sync(() => document.querySelector(".ytp-right-controls")),
  8732. Effect_map(fromNullable),
  8733. Effect_some
  8734. ),
  8735. settingsToggleNextElement: pipe(
  8736. Effect_sync(() => document.querySelector("#menu-container")),
  8737. Effect_map(
  8738. flow(
  8739. fromNullable,
  8740. Option_filter(x => null !== x.offsetParent),
  8741. flatMapNullable(x =>
  8742. x.querySelector(".dropdown-trigger.ytd-menu-renderer")
  8743. ),
  8744. orElse(() =>
  8745. fromNullable(
  8746. document.querySelector(
  8747. "#top-row .dropdown-trigger.ytd-menu-renderer"
  8748. )
  8749. )
  8750. )
  8751. )
  8752. ),
  8753. Effect_some
  8754. ),
  8755. settingsContainer: pipe(
  8756. Effect_sync(() => document.body),
  8757. Effect_map(fromNullable),
  8758. Effect_some
  8759. ),
  8760. player: pipe(
  8761. Effect_sync(() => document.querySelector("#movie_player")),
  8762. Effect_map(fromNullable),
  8763. Effect_some
  8764. ),
  8765. video: pipe(
  8766. Effect_sync(() =>
  8767. document.querySelector("video.video-stream.html5-main-video")
  8768. ),
  8769. Effect_map(fromNullable),
  8770. Effect_some
  8771. ),
  8772. chatField: pipe(
  8773. chatApp,
  8774. src_flatMapOption(
  8775. flow(
  8776. x => x.querySelector("#items.yt-live-chat-item-list-renderer"),
  8777. fromNullable
  8778. )
  8779. )
  8780. ),
  8781. chatTicker: pipe(
  8782. chatApp,
  8783. src_flatMapOption(
  8784. flow(
  8785. x => x.querySelector("#items.yt-live-chat-ticker-renderer"),
  8786. fromNullable
  8787. )
  8788. )
  8789. ),
  8790. chatScroller: pipe(
  8791. chatApp,
  8792. src_flatMapOption(
  8793. flow(
  8794. x =>
  8795. x.querySelector(
  8796. "#item-scroller.yt-live-chat-item-list-renderer"
  8797. ),
  8798. fromNullable
  8799. )
  8800. )
  8801. ),
  8802. offlineSlate: pipe(
  8803. Effect_sync(() => document.querySelector(".ytp-offline-slate")),
  8804. Effect_map(fromNullable),
  8805. Effect_some
  8806. ),
  8807. },
  8808. FiberRef_locally = fiberRefLocally,
  8809. logMeta = fiberRefUnsafeMake(Option_none()),
  8810. logWithMeta = level => message => data =>
  8811. pipe(
  8812. Effect_log(message),
  8813. FiberRef_locally(logMeta, Option_some(data)),
  8814. x => locally(level)(x)
  8815. ),
  8816. mainCss = pipe(
  8817. Effect_sync(() => document.createElement("style")),
  8818. Effect_tap(x =>
  8819. Effect_sync(() => {
  8820. x.innerHTML =
  8821. ".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}"
  8822. })
  8823. )
  8824. ),
  8825. makeChatScreen = pipe(
  8826. Effect_sync(() => document.createElement("div")),
  8827. Effect_tap(x =>
  8828. Effect_sync(() =>
  8829. Object.assign(x.style, {
  8830. pointerEvents: "none",
  8831. zIndex: "30",
  8832. position: "absolute",
  8833. overflow: "hidden",
  8834. height: "100%",
  8835. width: "100%",
  8836. })
  8837. )
  8838. )
  8839. ),
  8840. observePair = con =>
  8841. pipe(
  8842. Effect_Do(),
  8843. Effect_bind("subject", () =>
  8844. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  8845. ),
  8846. Effect_bind("observer", x =>
  8847. Effect_sync(() => new con(lib(x.subject)))
  8848. )
  8849. ),
  8850. getChatFontSize = mainState =>
  8851. Math.round(
  8852. ((Math.max(mainState.config.fontSize - 0.2, 0.01) *
  8853. mainState.playerRect.height) /
  8854. mainState.config.laneCount) *
  8855. (mainState.config.flowY2 - mainState.config.flowY1) *
  8856. 100
  8857. ) / 100,
  8858. external_window_micro_memoize_namespaceObject = window["micro-memoize"]
  8859. var external_window_micro_memoize_default = __webpack_require__.n(
  8860. external_window_micro_memoize_namespaceObject
  8861. )
  8862. const getFlowChatProgress = chat =>
  8863. pipe(
  8864. chat.animation,
  8865. flatMapNullable(x => x.currentTime),
  8866. getOrElse(() => 0),
  8867. x => x / chat.animationDuration
  8868. ),
  8869. getFlowChatRect = (chat, mainState) =>
  8870. pipe(
  8871. mainState.config,
  8872. x =>
  8873. mainState.playerRect.width * x.flowX2 -
  8874. (chat.width + mainState.playerRect.width * (x.flowX2 - x.flowX1)) *
  8875. getFlowChatProgress(chat),
  8876. x => new DOMRect(x, chat.y, chat.width, chat.height)
  8877. ),
  8878. getChatLane = (flowChat, progress, flowChats) => mainState => {
  8879. const flowWidth =
  8880. mainState.playerRect.width *
  8881. (mainState.config.flowX2 - mainState.config.flowX1),
  8882. chatRect = getFlowChatRect(flowChat, mainState),
  8883. chatWidth = chatRect.width,
  8884. chatHeight = chatRect.height,
  8885. chatX = chatRect.x,
  8886. chatIndex = flowChats.indexOf(flowChat),
  8887. movingChats = pipe(
  8888. flowChats,
  8889. take(chatIndex >= 0 ? chatIndex : flowChats.length),
  8890. ReadonlyArray_filter(
  8891. chat => !chat.animationEnded && chat.width > 0
  8892. ),
  8893. sort(Order_contramap(x => x.lane)(Order))
  8894. ),
  8895. tooCloseTo = external_window_micro_memoize_default()(
  8896. x => {
  8897. const otherRect = getFlowChatRect(x, mainState),
  8898. otherWidth = otherRect.width,
  8899. otherX = otherRect.x,
  8900. gap =
  8901. (chatHeight * otherWidth * chatWidth) ** 0.333 *
  8902. mainState.config.minSpacing
  8903. return (
  8904. (flowWidth - otherX) / (flowWidth + otherWidth) - progress <
  8905. (chatWidth + gap) / (flowWidth + chatWidth) ||
  8906. otherX + otherWidth + gap > chatX
  8907. )
  8908. },
  8909. { maxSize: 1e3 }
  8910. ),
  8911. occupyInfo = pipe(
  8912. movingChats,
  8913. ReadonlyArray_map(x => ({
  8914. tooClose: () => tooCloseTo(x),
  8915. lane: x.lane,
  8916. })),
  8917. append({ tooClose: () => !0, lane: mainState.config.laneCount })
  8918. ),
  8919. index = occupyInfo.findIndex(x => x.lane >= flowChat.lane),
  8920. bottomFreeLane = pipe(
  8921. occupyInfo.slice(index),
  8922. findFirst(x => x.tooClose()),
  8923. Option_map(x => x.lane),
  8924. getOrElse(() => mainState.config.laneCount)
  8925. ),
  8926. topFreeLane = pipe(
  8927. occupyInfo.slice(0, index),
  8928. findLast(x => x.tooClose()),
  8929. Option_map(x => x.lane),
  8930. getOrElse(() => -1)
  8931. ),
  8932. formerLaneInterval = Math.min(
  8933. flowChat.lane - topFreeLane,
  8934. bottomFreeLane - flowChat.lane,
  8935. 1
  8936. )
  8937. return pipe(
  8938. occupyInfo,
  8939. ReadonlyArray_reduce(
  8940. { maxInterval: 0, maxIntervalLane: 0, lastLane: -1 },
  8941. ({ maxInterval, maxIntervalLane, lastLane }, info) =>
  8942. maxInterval > 0.999 || !info.tooClose()
  8943. ? { maxInterval, maxIntervalLane, lastLane }
  8944. : (() => {
  8945. const nextLane = info.lane,
  8946. interLane = Math.min(
  8947. Math.max((lastLane + nextLane) / 2, 0),
  8948. mainState.config.laneCount - 1
  8949. ),
  8950. newInterval = Math.min(
  8951. interLane - lastLane,
  8952. nextLane - interLane,
  8953. 1
  8954. )
  8955. return newInterval - maxInterval > 0.001
  8956. ? {
  8957. maxInterval: newInterval,
  8958. maxIntervalLane: Math.max(lastLane + newInterval, 0),
  8959. lastLane: nextLane,
  8960. }
  8961. : { maxInterval, maxIntervalLane, lastLane: nextLane }
  8962. })()
  8963. ),
  8964. x => ({
  8965. lane:
  8966. Math.abs(formerLaneInterval - x.maxInterval) < 0.001
  8967. ? flowChat.lane
  8968. : x.maxIntervalLane,
  8969. interval: x.maxInterval,
  8970. })
  8971. )
  8972. },
  8973. intervalTooSmall = interval => config =>
  8974. config.noOverlap && interval < 0.999,
  8975. external_m_namespaceObject = m
  8976. var external_m_default = __webpack_require__.n(external_m_namespaceObject)
  8977. const textShadow = shadowColor =>
  8978. flow(
  8979. x => `${x}px`,
  8980. x => (a, b) => `${a}${x} ${b}${x} ${shadowColor}99`,
  8981. x => join(", ")([x("-", "-"), x("", "-"), x("-", ""), x("", "")])
  8982. ),
  8983. textStyle = { fontFamily: "inherit" },
  8984. renderChat = chat => mainState =>
  8985. Effect_sync(() =>
  8986. external_m_default().render(
  8987. chat.element,
  8988. ((chat, mainState) =>
  8989. pipe(
  8990. mainState.config,
  8991. config => ({ data: chat.getData(config), config }),
  8992. ({ data, config }) =>
  8993. external_m_default()(
  8994. "span",
  8995. {
  8996. style: {
  8997. fontSize: `${getChatFontSize(mainState)}px`,
  8998. visibility: config.displayChats ? "visible" : "hidden",
  8999. color:
  9000. "owner" === data.authorType
  9001. ? config.ownerColor
  9002. : "moderator" === data.authorType
  9003. ? config.moderatorColor
  9004. : "member" === data.authorType
  9005. ? config.memberColor
  9006. : config.color,
  9007. fontWeight: config.fontWeight.toString(),
  9008. fontFamily: config.font,
  9009. opacity: config.chatOpacity.toString(),
  9010. textShadow: textShadow(config.shadowColor)(
  9011. config.shadowFontWeight
  9012. ),
  9013. },
  9014. },
  9015. pipe(
  9016. [
  9017. pipe(
  9018. data.authorName,
  9019. Option_filter(x => x.visible),
  9020. Option_map(x =>
  9021. external_m_default()(
  9022. "span",
  9023. {
  9024. style: {
  9025. color: getOrUndefined(data.textColor),
  9026. fontSize: "0.84em",
  9027. ...textStyle,
  9028. },
  9029. },
  9030. `${x.content}: `
  9031. )
  9032. )
  9033. ),
  9034. pipe(
  9035. data.messageElement,
  9036. Option_map(x =>
  9037. ((message, config) => {
  9038. const eleWin =
  9039. message.ownerDocument.defaultView ?? window,
  9040. { maxChatLength } = config
  9041. return pipe(
  9042. Array.from(message.childNodes),
  9043. ReadonlyArray_reduce(
  9044. { vnodes: [], length: 0 },
  9045. ({ vnodes, length }, node) =>
  9046. length >= maxChatLength
  9047. ? { vnodes, length }
  9048. : !config.textOnly &&
  9049. node instanceof eleWin.HTMLImageElement
  9050. ? {
  9051. vnodes: [
  9052. ...vnodes,
  9053. external_m_default()("img", {
  9054. style: {
  9055. height: "1em",
  9056. width: "1em",
  9057. verticalAlign: "text-top",
  9058. },
  9059. src: node.src.replace(
  9060. /=w\d+-h\d+-c-k-nd$/,
  9061. ""
  9062. ),
  9063. alt: node.alt,
  9064. }),
  9065. ],
  9066. length: length + 1,
  9067. }
  9068. : pipe(
  9069. node.textContent ?? "",
  9070. slice(0, maxChatLength),
  9071. x =>
  9072. node instanceof
  9073. eleWin.HTMLAnchorElement
  9074. ? {
  9075. vnodes: [
  9076. ...vnodes,
  9077. external_m_default()(
  9078. "span",
  9079. {
  9080. style: {
  9081. fontSize: "0.84em",
  9082. textDecoration:
  9083. "underline",
  9084. ...textStyle,
  9085. },
  9086. },
  9087. x
  9088. ),
  9089. ],
  9090. length: length + x.length,
  9091. }
  9092. : {
  9093. vnodes: [
  9094. ...vnodes,
  9095. external_m_default().fragment(
  9096. {},
  9097. x
  9098. ),
  9099. ],
  9100. length: length + x.length,
  9101. }
  9102. )
  9103. )
  9104. )
  9105. })(x, config)
  9106. ),
  9107. Option_map(x =>
  9108. external_m_default()(
  9109. "span",
  9110. {
  9111. style: {
  9112. color: getOrUndefined(data.textColor),
  9113. ...textStyle,
  9114. },
  9115. },
  9116. x.vnodes
  9117. )
  9118. )
  9119. ),
  9120. pipe(
  9121. data.paymentInfo,
  9122. Option_filter(x => x.visible),
  9123. Option_map(x =>
  9124. external_m_default()(
  9125. "span",
  9126. {
  9127. style: {
  9128. color: getOrUndefined(data.paidColor),
  9129. fontSize: "0.84em",
  9130. ...textStyle,
  9131. },
  9132. },
  9133. external_m_default()(
  9134. "strong",
  9135. { style: textStyle },
  9136. x.content
  9137. )
  9138. )
  9139. )
  9140. ),
  9141. ],
  9142. ReadonlyArray_compact
  9143. )
  9144. )
  9145. ))(chat, mainState)
  9146. )
  9147. ),
  9148. Bicovariant_mapLeft = F =>
  9149. Function_dual(2, (self, f) => F.bimap(self, f, Function_identity)),
  9150. Bicovariant_map = F =>
  9151. Function_dual(2, (self, f) => F.bimap(self, Function_identity, f)),
  9152. getFirst = self => self[0],
  9153. getSecond = self => self[1],
  9154. Tuple_bimap = Function_dual(3, (self, f, g) => [f(self[0]), g(self[1])]),
  9155. Tuple_Bicovariant = { bimap: Tuple_bimap },
  9156. mapFirst = Bicovariant_mapLeft(Tuple_Bicovariant),
  9157. mapSecond = Bicovariant_map(Tuple_Bicovariant),
  9158. external_window_hash_it_namespaceObject = window["hash-it"]
  9159. var external_window_hash_it_default = __webpack_require__.n(
  9160. external_window_hash_it_namespaceObject
  9161. )
  9162. const getLaneY = (lane, mainState) =>
  9163. mainState.playerRect.height *
  9164. ((lane / mainState.config.laneCount + 0.005) *
  9165. (mainState.config.flowY2 - mainState.config.flowY1) +
  9166. mainState.config.flowY1),
  9167. setChatPlayState = chat => mainState =>
  9168. pipe(
  9169. chat,
  9170. liftPredicate(x => !x.animationEnded),
  9171. Effect_fromOption,
  9172. Effect_map(x => x.animation),
  9173. Effect_flatMap(Effect_fromOption),
  9174. Effect_tap(x =>
  9175. Effect_sync(
  9176. mainState.chatPlaying ? () => x.play() : () => x.pause()
  9177. )
  9178. ),
  9179. Effect_flatMap(x =>
  9180. Effect_sync(() => {
  9181. x.playbackRate = mainState.config.flowSpeed / 15
  9182. })
  9183. ),
  9184. Effect_ignore
  9185. ),
  9186. getWidth = external_window_micro_memoize_default()(
  9187. ele => ele?.getBoundingClientRect().width ?? 0,
  9188. {
  9189. maxSize: 2e3,
  9190. transformKey: ReadonlyArray_map(external_window_hash_it_default()),
  9191. }
  9192. ),
  9193. setChatAnimation = (chat, chats) => mainState =>
  9194. pipe(
  9195. { fontSize: getChatFontSize(mainState) },
  9196. Effect_succeed,
  9197. Effect_tap(x =>
  9198. Effect_sync(() => {
  9199. chat.element.style.transform = `translate(${
  9200. mainState.playerRect.width *
  9201. (mainState.config.flowX2 - mainState.config.flowX1)
  9202. }px, -${2 * x.fontSize}px)`
  9203. })
  9204. ),
  9205. Effect_filterOrFail(() => !chat.animationEnded, Option_none),
  9206. Effect_tap(x =>
  9207. Effect_sync(() => {
  9208. chat.animationDuration = 6400
  9209. chat.width = getWidth(chat.element.firstElementChild)
  9210. chat.height = x.fontSize
  9211. })
  9212. ),
  9213. Effect_map(() => getFlowChatProgress(chat)),
  9214. Effect_map(progress => ({
  9215. progress,
  9216. ...getChatLane(chat, progress, chats)(mainState),
  9217. })),
  9218. Effect_filterOrElse(
  9219. x => !intervalTooSmall(x.interval)(mainState.config),
  9220. () =>
  9221. pipe(
  9222. chat.animation,
  9223. Effect_fromOption,
  9224. Effect_flatMap(x =>
  9225. Effect_sync(() => {
  9226. x.finish()
  9227. chat.animation = Option_none()
  9228. })
  9229. ),
  9230. Effect_zipRight(Effect_fail(Option_none()))
  9231. )
  9232. ),
  9233. Effect_tap(x =>
  9234. Effect_sync(() => {
  9235. chat.lane = x.lane
  9236. })
  9237. ),
  9238. Effect_map(x => ({ ...x, laneY: getLaneY(chat.lane, mainState) })),
  9239. Effect_tap(ctx =>
  9240. pipe(
  9241. [
  9242. pipe(
  9243. chat.animation,
  9244. Effect_fromOption,
  9245. Effect_flatMap(x => Effect_sync(() => x.cancel())),
  9246. Effect_ignore
  9247. ),
  9248. pipe(
  9249. [
  9250. [
  9251. mainState.playerRect.width *
  9252. (mainState.config.flowX2 - mainState.config.flowX1),
  9253. ctx.laneY,
  9254. ],
  9255. [-chat.width, ctx.laneY],
  9256. ],
  9257. ReadonlyArray_map(
  9258. pipe(
  9259. x => `${x}px`,
  9260. x => Tuple_bimap(x, x)
  9261. )
  9262. ),
  9263. ReadonlyArray_map(([x, y]) => `translate(${x}, ${y})`),
  9264. ReadonlyArray_bindTo("transform"),
  9265. x =>
  9266. Effect_sync(() =>
  9267. chat.element.animate(x, {
  9268. duration: 6400,
  9269. easing: mainState.config.timingFunction,
  9270. })
  9271. ),
  9272. Effect_tap(x =>
  9273. Effect_sync(() => {
  9274. x.onfinish = () => {
  9275. chat.animationEnded = !0
  9276. }
  9277. chat.y = ctx.laneY
  9278. const newTime = 6400 * ctx.progress
  9279. x.currentTime = newTime
  9280. })
  9281. ),
  9282. Effect_flatMap(x =>
  9283. Effect_sync(() => {
  9284. chat.animation = Option_some(x)
  9285. })
  9286. ),
  9287. Effect_zipRight(setChatPlayState(chat)(mainState))
  9288. ),
  9289. ],
  9290. x => Effect_all(x)
  9291. )
  9292. ),
  9293. Effect_isSuccess
  9294. ),
  9295. emptyElement = document.createElement("span"),
  9296. appendChatMessage = flip(chat =>
  9297. Effect_flatMap(x =>
  9298. Effect_sync(() => chat.querySelector("#content #message")?.append(x))
  9299. )
  9300. ),
  9301. external_Swal_namespaceObject = Swal
  9302. var external_Swal_default = __webpack_require__.n(
  9303. external_Swal_namespaceObject
  9304. )
  9305. const defaultToast = external_Swal_default().mixin({
  9306. toast: !0,
  9307. position: "bottom-left",
  9308. timer: 2500,
  9309. timerProgressBar: !0,
  9310. showConfirmButton: !1,
  9311. didOpen: toast => {
  9312. toast.addEventListener(
  9313. "pointerenter",
  9314. external_Swal_default().stopTimer
  9315. )
  9316. toast.addEventListener(
  9317. "pointerleave",
  9318. external_Swal_default().resumeTimer
  9319. )
  9320. },
  9321. }),
  9322. template = runPromise(
  9323. pipe(
  9324. document.createElement("button"),
  9325. Effect_succeed,
  9326. Effect_tap(x =>
  9327. Effect_sync(() =>
  9328. x.classList.add("style-scope", "yt-icon-button", "fyc_button")
  9329. )
  9330. ),
  9331. Effect_tap(x =>
  9332. Effect_sync(() =>
  9333. Object.assign(x.style, {
  9334. padding: "0px",
  9335. width: "20px",
  9336. height: "20px",
  9337. fill: "#fff",
  9338. })
  9339. )
  9340. ),
  9341. Effect_tap(x =>
  9342. Effect_sync(() =>
  9343. x.setAttribute("aria-label", "NGに入れる(Ban this user)")
  9344. )
  9345. ),
  9346. Effect_tap(x =>
  9347. Effect_sync(() => {
  9348. x.innerHTML =
  9349. '<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>'
  9350. })
  9351. )
  9352. )
  9353. ),
  9354. filter_filterOperators = {
  9355. flip,
  9356. flow: fns => flow(...fns),
  9357. and: Monoid_booleanEvery.combineAll,
  9358. or: Monoid_booleanSome.combineAll,
  9359. RA: { some: ReadonlyArray_some, compact: ReadonlyArray_compact },
  9360. O: { exists },
  9361. inText: text => x => includes(x)(text.content),
  9362. eqText: text => x => text.content === x,
  9363. matchedByText: text => x => Boolean(text.content.match(RegExp(x, "u"))),
  9364. isVisible: x => x.visible,
  9365. }
  9366. var typed_assert_build = __webpack_require__(52)
  9367. const tapNonNull = (x, message) => {
  9368. typed_assert_build.Xd(x, message)
  9369. return x
  9370. },
  9371. parseChat = chat => {
  9372. const chatType = chat.querySelector(
  9373. ".yt-live-chat-ticker-paid-message-item-renderer"
  9374. )
  9375. ? "ticker"
  9376. : chat.querySelector(".yt-live-chat-membership-item-renderer")
  9377. ? "membership"
  9378. : chat.querySelector(
  9379. ".yt-live-chat-viewer-engagement-message-renderer"
  9380. )
  9381. ? "engagement"
  9382. : "normal",
  9383. isPaid =
  9384. "ticker" === chatType || Boolean(chat.querySelector("#card")),
  9385. paymentInfo = pipe(
  9386. fromNullable(
  9387. isPaid
  9388. ? chat.querySelector(
  9389. join(", ")([
  9390. "#purchase-amount",
  9391. "#purchase-amount-chip",
  9392. "#content>#text",
  9393. ])
  9394. )?.textContent
  9395. : void 0
  9396. ),
  9397. Option_map(x => ({ visible: !0, content: x }))
  9398. ),
  9399. authorType = chat.querySelector(".owner")
  9400. ? "owner"
  9401. : chat.querySelector(".moderator")
  9402. ? "moderator"
  9403. : chat.querySelector(".member")
  9404. ? "member"
  9405. : "normal",
  9406. messageElement = fromNullable(chat.querySelector("#message")),
  9407. isPaidNormal =
  9408. !!Option_isSome(paymentInfo) &&
  9409. Boolean(chat.querySelector(".yt-live-chat-paid-message-renderer")),
  9410. isPaidSticker =
  9411. !(!Option_isSome(paymentInfo) || isPaidNormal) &&
  9412. Boolean(chat.querySelector(".yt-live-chat-paid-sticker-renderer")),
  9413. textColor = fromNullable(
  9414. isPaidNormal
  9415. ? window
  9416. .getComputedStyle(tapNonNull(chat.querySelector("#header")))
  9417. .getPropertyValue("background-color")
  9418. : isPaidSticker
  9419. ? window
  9420. .getComputedStyle(chat)
  9421. .getPropertyValue(
  9422. "--yt-live-chat-paid-sticker-chip-background-color"
  9423. )
  9424. : void 0
  9425. ),
  9426. paidColor = fromNullable(
  9427. isPaidNormal
  9428. ? window
  9429. .getComputedStyle(tapNonNull(chat.querySelector("#content")))
  9430. .getPropertyValue("background-color")
  9431. : isPaidSticker
  9432. ? window
  9433. .getComputedStyle(chat)
  9434. .getPropertyValue(
  9435. "--yt-live-chat-paid-sticker-background-color"
  9436. )
  9437. : void 0
  9438. ),
  9439. authorPhotoMatches = chat
  9440. .querySelector(join(" ")(["#author-photo", "img"]))
  9441. ?.src.match(/ggpht\.com\/(ytc\/)?(.*)=/),
  9442. authorID = fromNullable(authorPhotoMatches?.at(-1)),
  9443. authorName = fromNullable(
  9444. chat.querySelector("#author-name")?.textContent
  9445. ),
  9446. message = pipe(
  9447. messageElement,
  9448. Option_map(x => ({ visible: !0, content: x.innerHTML }))
  9449. ),
  9450. messageText = pipe(
  9451. messageElement,
  9452. Option_map(x => ({ visible: !0, content: x.textContent ?? "" }))
  9453. )
  9454. return config => ({
  9455. chatType,
  9456. authorType,
  9457. authorID,
  9458. authorName: pipe(
  9459. authorName,
  9460. Option_map(x => ({
  9461. visible:
  9462. ("moderator" === authorType && config.displayModName) ||
  9463. (Option_isSome(paymentInfo) && config.displaySuperChatAuthor),
  9464. content: x,
  9465. }))
  9466. ),
  9467. messageElement,
  9468. message,
  9469. messageText,
  9470. paymentInfo,
  9471. textColor,
  9472. paidColor,
  9473. })
  9474. },
  9475. onChatFieldMutate = (
  9476. chatScrn,
  9477. flowChats,
  9478. mainState,
  9479. getConfig,
  9480. setConfig
  9481. ) =>
  9482. flow(
  9483. ReadonlyArray_flatMap(e => Array.from(e.addedNodes)),
  9484. ReadonlyArray_filter(x => x.children.length > 0),
  9485. ReadonlyArray_reverse,
  9486. ReadonlyArray_map(chat =>
  9487. pipe(
  9488. { getData: parseChat(chat), config: mainState.config },
  9489. Identity_let_("data", x => x.getData(x.config)),
  9490. Effect_succeed,
  9491. Effect_bind("banned", x => {
  9492. return pipe(
  9493. ((data = x.data),
  9494. (config = x.config),
  9495. pipe(
  9496. data,
  9497. liftPredicate(() =>
  9498. pipe(config.filterExp, x =>
  9499. a(
  9500. x,
  9501. (data => ({
  9502. ...filter_filterOperators,
  9503. authorName: data.authorName,
  9504. message: data.message,
  9505. messageText: data.messageText,
  9506. paymentInfo: data.paymentInfo,
  9507. authorID: pipe(
  9508. data.authorID,
  9509. Option_map(x => ({ visible: !1, content: x }))
  9510. ),
  9511. }))(data)
  9512. )
  9513. )
  9514. ),
  9515. Option_map(x => [
  9516. pipe(
  9517. x.message,
  9518. Option_map(m => m.content)
  9519. ),
  9520. pipe(
  9521. x.paymentInfo,
  9522. Option_map(p => p.content)
  9523. ),
  9524. ]),
  9525. Option_map(ReadonlyArray_map(getOrElse(() => ""))),
  9526. Option_map(JSON.stringify),
  9527. Effect_fromOption,
  9528. Effect_flatMap(x => Effect_logDebug(`Filtered: ${x}`)),
  9529. Effect_isSuccess
  9530. ))
  9531. )
  9532. var data, config
  9533. }),
  9534. Effect_flatMap(ctx =>
  9535. ctx.banned
  9536. ? Effect_sync(() => {
  9537. chat.style.display = "none"
  9538. })
  9539. : Effect_all([
  9540. pipe(
  9541. ctx.config.createChats &&
  9542. "normal" === ctx.data.chatType,
  9543. liftPredicate(Function_identity),
  9544. Effect_fromOption,
  9545. Effect_flatMap(() =>
  9546. ((getData, flowChats, chatScrn, mainState) =>
  9547. pipe(
  9548. {
  9549. getData,
  9550. element: emptyElement,
  9551. lane: -1,
  9552. animation: Option_none(),
  9553. animationDuration: 0,
  9554. animationEnded: !1,
  9555. width: 2,
  9556. height: getChatFontSize(mainState),
  9557. y: 0,
  9558. },
  9559. x =>
  9560. getChatLane(x, 0, flowChats)(mainState)
  9561. .interval,
  9562. intervalTooSmall,
  9563. x => x(mainState.config)
  9564. )
  9565. ? Effect_unit()
  9566. : pipe(
  9567. flowChats,
  9568. findFirstIndex(
  9569. chat =>
  9570. chat.animationEnded ||
  9571. flowChats.length >=
  9572. mainState.config.maxChatCount
  9573. ),
  9574. offScreenIndex =>
  9575. pipe(
  9576. offScreenIndex,
  9577. Option_map(index =>
  9578. pipe(
  9579. flowChats,
  9580. unsafeGet(index),
  9581. x => x.element
  9582. )
  9583. ),
  9584. getOrElse(() =>
  9585. document.createElement("span")
  9586. ),
  9587. Effect_succeed,
  9588. Effect_tap(element =>
  9589. pipe(
  9590. offScreenIndex,
  9591. match(
  9592. () =>
  9593. Effect_sync(() =>
  9594. chatScrn.append(element)
  9595. ),
  9596. i =>
  9597. pipe(
  9598. Effect_sync(
  9599. () =>
  9600. flowChats.splice(i, 1)?.[0]
  9601. ?.animation ??
  9602. Option_none()
  9603. ),
  9604. Effect_some,
  9605. Effect_flatMap(oldAnimation =>
  9606. Effect_sync(() =>
  9607. oldAnimation.cancel()
  9608. )
  9609. ),
  9610. Effect_ignore
  9611. )
  9612. )
  9613. )
  9614. )
  9615. ),
  9616. Effect_flatMap(element =>
  9617. pipe(
  9618. {
  9619. getData,
  9620. element,
  9621. lane: -1,
  9622. animation: Option_none(),
  9623. animationDuration: 0,
  9624. animationEnded: !1,
  9625. width: 2,
  9626. height: getChatFontSize(mainState),
  9627. y: 0,
  9628. },
  9629. Effect_succeed,
  9630. Effect_zipLeft(
  9631. Effect_sync(() =>
  9632. element.classList.add("fyc_chat")
  9633. )
  9634. )
  9635. )
  9636. ),
  9637. Effect_flatMap(flowChat =>
  9638. pipe(
  9639. mainState,
  9640. Effect_succeed,
  9641. Effect_tap(renderChat(flowChat)),
  9642. Effect_flatMap(
  9643. setChatAnimation(flowChat, flowChats)
  9644. ),
  9645. Effect_flatMap(x =>
  9646. Effect_sync(
  9647. x
  9648. ? () => flowChats.push(flowChat)
  9649. : () => flowChat.element.remove()
  9650. )
  9651. )
  9652. )
  9653. )
  9654. ))(ctx.getData, flowChats, chatScrn, mainState)
  9655. )
  9656. ),
  9657. pipe(
  9658. ctx.data.authorID,
  9659. Option_filter(() => ctx.config.createBanButton),
  9660. Option_filter(() => !chat.children.namedItem("card")),
  9661. Effect_fromOption,
  9662. Effect_flatMap(x => {
  9663. return appendChatMessage(
  9664. ((id = x),
  9665. getConfig => setConfig => chat =>
  9666. pipe(
  9667. getConfig.bannedUsers,
  9668. Effect_filterOrFail(
  9669. x => !x.includes(id),
  9670. Option_none
  9671. ),
  9672. Effect_map(
  9673. flow(uniq(String_Equivalence), append(id))
  9674. ),
  9675. Effect_flatMap(x =>
  9676. pipe(
  9677. setConfig.bannedUsers(x),
  9678. Effect_zipRight(
  9679. Effect_sync(() =>
  9680. defaultToast.fire({
  9681. title: `Added Banned User: ${id}`,
  9682. icon: "success",
  9683. })
  9684. )
  9685. )
  9686. )
  9687. ),
  9688. Effect_ignore,
  9689. Effect_zipRight(
  9690. Effect_sync(() => {
  9691. chat.style.display = "none"
  9692. })
  9693. ),
  9694. onclick =>
  9695. pipe(
  9696. Effect_promise(() => template),
  9697. Effect_map(x => x.cloneNode(!0)),
  9698. Effect_tap(x =>
  9699. Effect_sync(() => {
  9700. x.onclick = () => runPromise(onclick)
  9701. })
  9702. )
  9703. )
  9704. ))(getConfig)(setConfig)(chat)
  9705. )(chat)
  9706. var id
  9707. })
  9708. ),
  9709. pipe(
  9710. ctx.config.simplifyChatField,
  9711. liftPredicate(Function_identity),
  9712. Effect_fromOption,
  9713. Effect_flatMap(() =>
  9714. (chat =>
  9715. chat.querySelector(
  9716. ".style-scope.yt-live-chat-paid-message-renderer"
  9717. )
  9718. ? Effect_unit()
  9719. : pipe(
  9720. [
  9721. "#author-photo",
  9722. "yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer",
  9723. ],
  9724. ReadonlyArray_map(x =>
  9725. fromNullable(chat.querySelector(x))
  9726. ),
  9727. ReadonlyArray_compact,
  9728. ReadonlyArray_map(x =>
  9729. Effect_sync(() => {
  9730. x.style.display = "none"
  9731. })
  9732. ),
  9733. append(
  9734. Effect_sync(() => {
  9735. chat.style.borderBottom =
  9736. "1px solid var(--yt-spec-text-secondary)"
  9737. })
  9738. ),
  9739. x => Effect_all(x)
  9740. ))(chat)
  9741. )
  9742. ),
  9743. ])
  9744. ),
  9745. Effect_ignore
  9746. )
  9747. ),
  9748. x => Effect_all(x)
  9749. ),
  9750. removeOldChats = flowChats => maxChatCount =>
  9751. pipe(
  9752. Effect_sync(() =>
  9753. flowChats.sort((a, b) =>
  9754. a.animationEnded === b.animationEnded
  9755. ? 0
  9756. : a.animationEnded
  9757. ? -1
  9758. : 1
  9759. )
  9760. ),
  9761. Effect_zipRight(
  9762. Effect_sync(() =>
  9763. flowChats.splice(0, Math.max(0, flowChats.length - maxChatCount))
  9764. )
  9765. ),
  9766. Effect_flatMap(
  9767. Effect_forEach(x =>
  9768. pipe(
  9769. Effect_logDebug("RemoveChat"),
  9770. Effect_zipRight(
  9771. Effect_sync(() => {
  9772. x.element.remove()
  9773. })
  9774. )
  9775. )
  9776. )
  9777. )
  9778. ),
  9779. exceptions = ["timingFunction", "lang"],
  9780. isEditable = k => v =>
  9781. ("number" == typeof v ||
  9782. "string" == typeof v ||
  9783. (Array.isArray(v) && ("string" == typeof v[0] || 0 === v.length))) &&
  9784. !ReadonlyArray_some(x => x === k)(exceptions),
  9785. Editable_of = x => [x, Option_none()],
  9786. fromValueText = v => t => [v, Option_some([t, Option_none()])],
  9787. Editable_value = getFirst,
  9788. Editable_text = flow(getSecond, Option_map(getFirst)),
  9789. error = flow(getSecond, flatMap(getSecond)),
  9790. setValue = flow(constant, x => mapFirst(x)),
  9791. setText = x =>
  9792. mapSecond(
  9793. flow(
  9794. Option_map(mapFirst(constant(x))),
  9795. orElse(constant(Option_some([x, Option_none()])))
  9796. )
  9797. ),
  9798. hasError = flow(error, Option_isSome),
  9799. RefinedConstructorsTypeId = Symbol.for("@effect/data/Brand/Refined"),
  9800. makeLog = Object.assign(args => args, {
  9801. [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
  9802. option: args => Option_some(args),
  9803. either: args => Either_right(args),
  9804. refine: _args => !0,
  9805. }),
  9806. settingStateInit = config =>
  9807. pipe(
  9808. config,
  9809. mapObject(([k, v]) => [
  9810. k,
  9811. isEditable(k)(v) ? Editable_of(v) : "filterExp" === k ? void 0 : v,
  9812. ]),
  9813. x => ({
  9814. ...x,
  9815. showPanel: !1,
  9816. mainTab: 0,
  9817. logTab: 0,
  9818. timingStepCount: Editable_of(
  9819. parseInt(
  9820. config.timingFunction.match(/^steps\((\d+),.+/)?.[1] ?? "150",
  9821. 10
  9822. )
  9823. ),
  9824. eventLog: makeLog({ nextId: 0, entries: [] }),
  9825. panelRect: new DOMRectReadOnly(0, 0, 660, 395),
  9826. })
  9827. )
  9828. var EMPTY_OBJ = {},
  9829. EMPTY_ARR = [],
  9830. hyperapp_id = a => a,
  9831. hyperapp_map = EMPTY_ARR.map,
  9832. isArray = Array.isArray,
  9833. enqueue =
  9834. "undefined" != typeof requestAnimationFrame
  9835. ? requestAnimationFrame
  9836. : setTimeout,
  9837. createClass = obj => {
  9838. var out = ""
  9839. if ("string" == typeof obj) return obj
  9840. if (isArray(obj))
  9841. for (var tmp, k = 0; k < obj.length; k++)
  9842. (tmp = createClass(obj[k])) && (out += (out && " ") + tmp)
  9843. else for (var k in obj) obj[k] && (out += (out && " ") + k)
  9844. return out
  9845. },
  9846. shouldRestart = (a, b) => {
  9847. for (var k in { ...a, ...b })
  9848. if ("function" == typeof (isArray(a[k]) ? a[k][0] : a[k])) b[k] = a[k]
  9849. else if (a[k] !== b[k]) return !0
  9850. },
  9851. getKey = vdom => (null == vdom ? vdom : vdom.key),
  9852. patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
  9853. if ("style" === key)
  9854. for (var k in { ...oldValue, ...newValue }) {
  9855. oldValue =
  9856. null == newValue || null == newValue[k] ? "" : newValue[k]
  9857. "-" === k[0]
  9858. ? node[key].setProperty(k, oldValue)
  9859. : (node[key][k] = oldValue)
  9860. }
  9861. else
  9862. "o" === key[0] && "n" === key[1]
  9863. ? ((node.events || (node.events = {}))[(key = key.slice(2))] =
  9864. newValue)
  9865. ? oldValue || node.addEventListener(key, listener)
  9866. : node.removeEventListener(key, listener)
  9867. : !isSvg && "list" !== key && "form" !== key && key in node
  9868. ? (node[key] = newValue ?? "")
  9869. : null == newValue || !1 === newValue
  9870. ? node.removeAttribute(key)
  9871. : node.setAttribute(key, newValue)
  9872. },
  9873. createNode = (vdom, listener, isSvg) => {
  9874. var props = vdom.props,
  9875. node =
  9876. 3 === vdom.type
  9877. ? document.createTextNode(vdom.tag)
  9878. : (isSvg = isSvg || "svg" === vdom.tag)
  9879. ? document.createElementNS(
  9880. "http://www.w3.org/2000/svg",
  9881. vdom.tag,
  9882. props.is && props
  9883. )
  9884. : document.createElement(vdom.tag, props.is && props)
  9885. for (var k in props)
  9886. patchProperty(node, k, null, props[k], listener, isSvg)
  9887. for (var i = 0; i < vdom.children.length; i++)
  9888. node.appendChild(
  9889. createNode(
  9890. (vdom.children[i] = maybeVNode(vdom.children[i])),
  9891. listener,
  9892. isSvg
  9893. )
  9894. )
  9895. return (vdom.node = node)
  9896. },
  9897. hyperapp_patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
  9898. if (oldVNode === newVNode);
  9899. else if (null != oldVNode && 3 === oldVNode.type && 3 === newVNode.type)
  9900. oldVNode.tag !== newVNode.tag && (node.nodeValue = newVNode.tag)
  9901. else if (null == oldVNode || oldVNode.tag !== newVNode.tag) {
  9902. node = parent.insertBefore(
  9903. createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
  9904. node
  9905. )
  9906. null != oldVNode && parent.removeChild(oldVNode.node)
  9907. } else {
  9908. var tmpVKid,
  9909. oldVKid,
  9910. oldKey,
  9911. newKey,
  9912. oldProps = oldVNode.props,
  9913. newProps = newVNode.props,
  9914. oldVKids = oldVNode.children,
  9915. newVKids = newVNode.children,
  9916. oldHead = 0,
  9917. newHead = 0,
  9918. oldTail = oldVKids.length - 1,
  9919. newTail = newVKids.length - 1
  9920. isSvg = isSvg || "svg" === newVNode.tag
  9921. for (var i in { ...oldProps, ...newProps })
  9922. ("value" === i || "selected" === i || "checked" === i
  9923. ? node[i]
  9924. : oldProps[i]) !== newProps[i] &&
  9925. patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
  9926. for (
  9927. ;
  9928. newHead <= newTail &&
  9929. oldHead <= oldTail &&
  9930. null != (oldKey = getKey(oldVKids[oldHead])) &&
  9931. oldKey === getKey(newVKids[newHead]);
  9932.  
  9933. )
  9934. hyperapp_patch(
  9935. node,
  9936. oldVKids[oldHead].node,
  9937. oldVKids[oldHead],
  9938. (newVKids[newHead] = maybeVNode(
  9939. newVKids[newHead++],
  9940. oldVKids[oldHead++]
  9941. )),
  9942. listener,
  9943. isSvg
  9944. )
  9945. for (
  9946. ;
  9947. newHead <= newTail &&
  9948. oldHead <= oldTail &&
  9949. null != (oldKey = getKey(oldVKids[oldTail])) &&
  9950. oldKey === getKey(newVKids[newTail]);
  9951.  
  9952. )
  9953. hyperapp_patch(
  9954. node,
  9955. oldVKids[oldTail].node,
  9956. oldVKids[oldTail],
  9957. (newVKids[newTail] = maybeVNode(
  9958. newVKids[newTail--],
  9959. oldVKids[oldTail--]
  9960. )),
  9961. listener,
  9962. isSvg
  9963. )
  9964. if (oldHead > oldTail)
  9965. for (; newHead <= newTail; )
  9966. node.insertBefore(
  9967. createNode(
  9968. (newVKids[newHead] = maybeVNode(newVKids[newHead++])),
  9969. listener,
  9970. isSvg
  9971. ),
  9972. (oldVKid = oldVKids[oldHead]) && oldVKid.node
  9973. )
  9974. else if (newHead > newTail)
  9975. for (; oldHead <= oldTail; )
  9976. node.removeChild(oldVKids[oldHead++].node)
  9977. else {
  9978. var keyed = {},
  9979. newKeyed = {}
  9980. for (i = oldHead; i <= oldTail; i++)
  9981. null != (oldKey = oldVKids[i].key) &&
  9982. (keyed[oldKey] = oldVKids[i])
  9983. for (; newHead <= newTail; ) {
  9984. oldKey = getKey((oldVKid = oldVKids[oldHead]))
  9985. newKey = getKey(
  9986. (newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid))
  9987. )
  9988. if (
  9989. newKeyed[oldKey] ||
  9990. (null != newKey && newKey === getKey(oldVKids[oldHead + 1]))
  9991. ) {
  9992. null == oldKey && node.removeChild(oldVKid.node)
  9993. oldHead++
  9994. } else if (null == newKey || 1 === oldVNode.type) {
  9995. if (null == oldKey) {
  9996. hyperapp_patch(
  9997. node,
  9998. oldVKid && oldVKid.node,
  9999. oldVKid,
  10000. newVKids[newHead],
  10001. listener,
  10002. isSvg
  10003. )
  10004. newHead++
  10005. }
  10006. oldHead++
  10007. } else {
  10008. if (oldKey === newKey) {
  10009. hyperapp_patch(
  10010. node,
  10011. oldVKid.node,
  10012. oldVKid,
  10013. newVKids[newHead],
  10014. listener,
  10015. isSvg
  10016. )
  10017. newKeyed[newKey] = !0
  10018. oldHead++
  10019. } else if (null != (tmpVKid = keyed[newKey])) {
  10020. hyperapp_patch(
  10021. node,
  10022. node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
  10023. tmpVKid,
  10024. newVKids[newHead],
  10025. listener,
  10026. isSvg
  10027. )
  10028. newKeyed[newKey] = !0
  10029. } else
  10030. hyperapp_patch(
  10031. node,
  10032. oldVKid && oldVKid.node,
  10033. null,
  10034. newVKids[newHead],
  10035. listener,
  10036. isSvg
  10037. )
  10038. newHead++
  10039. }
  10040. }
  10041. for (; oldHead <= oldTail; )
  10042. null == getKey((oldVKid = oldVKids[oldHead++])) &&
  10043. node.removeChild(oldVKid.node)
  10044. for (var i in keyed)
  10045. null == newKeyed[i] && node.removeChild(keyed[i].node)
  10046. }
  10047. }
  10048. return (newVNode.node = node)
  10049. },
  10050. maybeVNode = (newVNode, oldVNode) =>
  10051. !0 !== newVNode && !1 !== newVNode && newVNode
  10052. ? "function" == typeof newVNode.tag
  10053. ? ((!oldVNode ||
  10054. null == oldVNode.memo ||
  10055. ((a, b) => {
  10056. for (var k in a) if (a[k] !== b[k]) return !0
  10057. for (var k in b) if (a[k] !== b[k]) return !0
  10058. })(oldVNode.memo, newVNode.memo)) &&
  10059. ((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
  10060. oldVNode)
  10061. : newVNode
  10062. : hyperapp_text(""),
  10063. recycleNode = node =>
  10064. 3 === node.nodeType
  10065. ? hyperapp_text(node.nodeValue, node)
  10066. : createVNode(
  10067. node.nodeName.toLowerCase(),
  10068. EMPTY_OBJ,
  10069. hyperapp_map.call(node.childNodes, recycleNode),
  10070. 1,
  10071. node
  10072. ),
  10073. createVNode = (tag, { key, ...props }, children, type, node) => ({
  10074. tag,
  10075. props,
  10076. key,
  10077. children,
  10078. type,
  10079. node,
  10080. }),
  10081. hyperapp_text = (value, node) =>
  10082. createVNode(value, EMPTY_OBJ, EMPTY_ARR, 3, node),
  10083. h = (tag, { class: c, ...props }, children = EMPTY_ARR) =>
  10084. createVNode(
  10085. tag,
  10086. { ...props, ...(c ? { class: createClass(c) } : EMPTY_OBJ) },
  10087. isArray(children) ? children : [children]
  10088. ),
  10089. app = ({
  10090. node,
  10091. view,
  10092. subscriptions,
  10093. dispatch = hyperapp_id,
  10094. init = EMPTY_OBJ,
  10095. }) => {
  10096. var state,
  10097. busy,
  10098. vdom = node && recycleNode(node),
  10099. subs = [],
  10100. update = newState => {
  10101. if (state !== newState) {
  10102. null == (state = newState) &&
  10103. (dispatch = subscriptions = render = hyperapp_id)
  10104. subscriptions &&
  10105. (subs = ((oldSubs, newSubs = EMPTY_ARR, dispatch) => {
  10106. for (
  10107. var oldSub, newSub, subs = [], i = 0;
  10108. i < oldSubs.length || i < newSubs.length;
  10109. i++
  10110. ) {
  10111. oldSub = oldSubs[i]
  10112. newSub = newSubs[i]
  10113. subs.push(
  10114. newSub && !0 !== newSub
  10115. ? !oldSub ||
  10116. newSub[0] !== oldSub[0] ||
  10117. shouldRestart(newSub[1], oldSub[1])
  10118. ? [
  10119. newSub[0],
  10120. newSub[1],
  10121. (oldSub && oldSub[2](),
  10122. newSub[0](dispatch, newSub[1])),
  10123. ]
  10124. : oldSub
  10125. : oldSub && oldSub[2]()
  10126. )
  10127. }
  10128. return subs
  10129. })(subs, subscriptions(state), dispatch))
  10130. view && !busy && enqueue(render, (busy = !0))
  10131. }
  10132. },
  10133. render = () =>
  10134. (node = hyperapp_patch(
  10135. node.parentNode,
  10136. node,
  10137. vdom,
  10138. (vdom = view(state)),
  10139. listener,
  10140. (busy = !1)
  10141. )),
  10142. listener = function (event) {
  10143. dispatch(this.events[event.type], event)
  10144. }
  10145. return (
  10146. (dispatch = dispatch((action, props) =>
  10147. "function" == typeof action
  10148. ? dispatch(action(state, props))
  10149. : isArray(action)
  10150. ? "function" == typeof action[0]
  10151. ? dispatch(action[0], action[1])
  10152. : action
  10153. .slice(1)
  10154. .map(
  10155. fx => fx && !0 !== fx && (fx[0] || fx)(dispatch, fx[1]),
  10156. update(action[0])
  10157. )
  10158. : update(action)
  10159. ))(init),
  10160. dispatch
  10161. )
  10162. }
  10163. const makeComponent = x => tag => ({ tag, view: x(tag) }),
  10164. src_flip =
  10165. x =>
  10166. (...b) =>
  10167. (...a) =>
  10168. x(...a)(...b),
  10169. defaultText = {
  10170. setting: ["Settings", "設定"],
  10171. font: ["Font", "フォント"],
  10172. color: ["Color(Normal)", "色(通常)"],
  10173. ownerColor: ["Color(Owner)", "色(オーナー)"],
  10174. moderatorColor: ["Color(Moderator)", "色(モデレーター)"],
  10175. memberColor: ["Color(Member)", "色(メンバー)"],
  10176. feedback: ["Feedback", "バグ報告と要望"],
  10177. eventLog: ["Event log", "イベントログ"],
  10178. giveFeedback: [
  10179. "Give your feedbacks here(Please attach the event log if they're bug related)",
  10180. "バグ報告、要望はこちら(バグの場合は、イベントログを添付してください)",
  10181. ],
  10182. chatOpacity: ["Opacity", "不透明度"],
  10183. fontSize: ["Size", "サイズ"],
  10184. fontWeight: ["Weight", "太さ"],
  10185. shadowFontWeight: ["Weight(Shadow)", "太さ(影)"],
  10186. flowSpeed: ["Speed", "速度"],
  10187. maxChatCount: ["Max number of chats", "最大表示数"],
  10188. maxChatLength: ["Max number of characters", "最大文字数"],
  10189. laneCount: ["Number of rows", "行数"],
  10190. bannedWords: ["Banned Words", "NGワード"],
  10191. bannedWordRegexs: ["Banned Words(Regex)", "NGワード(正規表現)"],
  10192. bannedUsers: ["Banned Users", "NGユーザー"],
  10193. simplifyChatField: ["Simplify", "簡略化する"],
  10194. createBanButton: ["Show ban button", "NGボタンを表示する"],
  10195. displayModName: [
  10196. "Show moderator's name",
  10197. "モデレーターの名前を表示する",
  10198. ],
  10199. displaySuperChatAuthor: [
  10200. "Show super chat author",
  10201. "スパチャの作成者を表示する",
  10202. ],
  10203. createChats: ["Display flowing chats", "チャットを流す"],
  10204. textOnly: ["Text only(ignore emojis)", "文字のみ(絵文字を無視する)"],
  10205. error: ["Error", "エラー"],
  10206. video: ["Video", "画面"],
  10207. chatField: ["Chat Window", "チャット欄"],
  10208. useStepTiming: ["Move chat in steps", "チャットを段階的に動かす"],
  10209. timingStepCount: ["└Step Count", "└段階数"],
  10210. chatFilter: ["Chat Filter", "チャットフィルター"],
  10211. flowChat: ["Flow Chat", "チャット流れ"],
  10212. clearFlowChats: ["Clear Flowing Chats", "流れるチャットをクリアする"],
  10213. flowNewChatIf: [
  10214. "A new chat will appear if all of the followings are met:",
  10215. "新しいチャットは以下のすべてを満たす場合に流れます:",
  10216. ],
  10217. noOverlap: ["└Chats won't overlap", "└他のチャットと重ならない"],
  10218. minSpacing: ["Min spacing between chats", "チャットの最小間隔"],
  10219. fieldScale: ["Scale", "拡大率"],
  10220. copy: ["Copy", "コピーする"],
  10221. showChat: ["Show chats", "チャットを表示する"],
  10222. hideChat: ["Hide chats", "チャットを非表示にする"],
  10223. flowY1: ["Flow area top edge", "流れ範囲の上端"],
  10224. flowY2: ["Flow area bottom edge", "流れ範囲の下端"],
  10225. flowX1: ["Flow area left edge", "流れ範囲の左端"],
  10226. flowX2: ["Flow area right edge", "流れ範囲の右端"],
  10227. shadowColor: ["Color(Shadow)", "色(影)"],
  10228. invalidColor: ["Invalid color", "無効な色"],
  10229. inputNonNumberic: ["Input isn't a number", "入力値が数字でない"],
  10230. invalidSetting: ["Invalid setting", "無効な設定値"],
  10231. },
  10232. getText = key => language =>
  10233. defaultText[key]["FYC_EN" === language ? 0 : 1],
  10234. languageLabels = ["English", "日本語"],
  10235. computed = {
  10236. useStepTiming: s => Boolean(s.timingFunction.match(/^steps\(.+/)),
  10237. },
  10238. getState = k => (k in computed ? computed[k] : s => s[k]),
  10239. configEffect = (k, v) => setConfig => () => runPromise(setConfig[k](v)),
  10240. stepTiming = stepCount => `steps(${stepCount}, jump-end)`,
  10241. setComputed = {
  10242. useStepTiming: v => c => s =>
  10243. pipe(
  10244. v ? stepTiming(Editable_value(s.timingStepCount)) : "linear",
  10245. timingFunction => [
  10246. { ...s, timingFunction },
  10247. configEffect("timingFunction", timingFunction)(c.setConfig),
  10248. ]
  10249. ),
  10250. },
  10251. settingUI_setComputed = setComputed,
  10252. setRange = keyA => keyB => bFn => vA => c => s =>
  10253. pipe(
  10254. { a: Editable_value(vA) },
  10255. Identity_let_("b", ({ a }) => bFn(a)(Editable_value(s[keyB]))),
  10256. ({ a, b }) =>
  10257. pipe(
  10258. [configEffect(keyA, a), configEffect(keyB, b)],
  10259. xs => setter =>
  10260. pipe(
  10261. xs,
  10262. ReadonlyArray_map(x => x(setter)),
  10263. effects => [
  10264. { ...s, [keyA]: vA, [keyB]: setValue(b)(s[keyB]) },
  10265. ...effects,
  10266. ]
  10267. )
  10268. )(c.setConfig)
  10269. ),
  10270. setState = {
  10271. flowY1: setRange("flowY1")("flowY2")(a => b => Math.max(b, a + 0.05)),
  10272. flowY2: setRange("flowY2")("flowY1")(a => b => Math.min(b, a - 0.05)),
  10273. flowX1: setRange("flowX1")("flowX2")(a => b => Math.max(b, a + 0.05)),
  10274. flowX2: setRange("flowX2")("flowX1")(a => b => Math.min(b, a - 0.05)),
  10275. timingStepCount: v => c => s =>
  10276. pipe(stepTiming(Editable_value(v)), timingFunction => [
  10277. { ...s, timingStepCount: v, timingFunction },
  10278. configEffect("timingFunction", timingFunction)(c.setConfig),
  10279. ]),
  10280. },
  10281. settingUI_setState = setState,
  10282. updateAt = k => v =>
  10283. pipe(
  10284. k in settingUI_setComputed
  10285. ? settingUI_setComputed[k](v)
  10286. : k in settingUI_setState
  10287. ? settingUI_setState[k](v)
  10288. : c => s =>
  10289. [
  10290. { ...s, [k]: v },
  10291. ...(k in c.setConfig && "filterExp" !== k
  10292. ? [
  10293. configEffect(
  10294. k,
  10295. Array.isArray(v) &&
  10296. 2 === v.length &&
  10297. isEditable(k)(v[0])
  10298. ? Editable_value(v)
  10299. : v
  10300. )(c.setConfig),
  10301. ]
  10302. : []),
  10303. ]
  10304. )
  10305. var util, objectUtil
  10306. !(function (util) {
  10307. util.assertEqual = val => val
  10308. util.assertIs = function (_arg) {}
  10309. util.assertNever = function (_x) {
  10310. throw new Error()
  10311. }
  10312. util.arrayToEnum = items => {
  10313. const obj = {}
  10314. for (const item of items) obj[item] = item
  10315. return obj
  10316. }
  10317. util.getValidEnumValues = obj => {
  10318. const validKeys = util
  10319. .objectKeys(obj)
  10320. .filter(k => "number" != typeof obj[obj[k]]),
  10321. filtered = {}
  10322. for (const k of validKeys) filtered[k] = obj[k]
  10323. return util.objectValues(filtered)
  10324. }
  10325. util.objectValues = obj =>
  10326. util.objectKeys(obj).map(function (e) {
  10327. return obj[e]
  10328. })
  10329. util.objectKeys =
  10330. "function" == typeof Object.keys
  10331. ? obj => Object.keys(obj)
  10332. : object => {
  10333. const keys = []
  10334. for (const key in object)
  10335. Object.prototype.hasOwnProperty.call(object, key) &&
  10336. keys.push(key)
  10337. return keys
  10338. }
  10339. util.find = (arr, checker) => {
  10340. for (const item of arr) if (checker(item)) return item
  10341. }
  10342. util.isInteger =
  10343. "function" == typeof Number.isInteger
  10344. ? val => Number.isInteger(val)
  10345. : val =>
  10346. "number" == typeof val && isFinite(val) && Math.floor(val) === val
  10347. util.joinValues = function (array, separator = " | ") {
  10348. return array
  10349. .map(val => ("string" == typeof val ? `'${val}'` : val))
  10350. .join(separator)
  10351. }
  10352. util.jsonStringifyReplacer = (_, value) =>
  10353. "bigint" == typeof value ? value.toString() : value
  10354. })(util || (util = {}))
  10355. !(function (objectUtil) {
  10356. objectUtil.mergeShapes = (first, second) => ({ ...first, ...second })
  10357. })(objectUtil || (objectUtil = {}))
  10358. const ZodParsedType = util.arrayToEnum([
  10359. "string",
  10360. "nan",
  10361. "number",
  10362. "integer",
  10363. "float",
  10364. "boolean",
  10365. "date",
  10366. "bigint",
  10367. "symbol",
  10368. "function",
  10369. "undefined",
  10370. "null",
  10371. "array",
  10372. "object",
  10373. "unknown",
  10374. "promise",
  10375. "void",
  10376. "never",
  10377. "map",
  10378. "set",
  10379. ]),
  10380. getParsedType = data => {
  10381. switch (typeof data) {
  10382. case "undefined":
  10383. return ZodParsedType.undefined
  10384. case "string":
  10385. return ZodParsedType.string
  10386. case "number":
  10387. return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number
  10388. case "boolean":
  10389. return ZodParsedType.boolean
  10390. case "function":
  10391. return ZodParsedType.function
  10392. case "bigint":
  10393. return ZodParsedType.bigint
  10394. case "symbol":
  10395. return ZodParsedType.symbol
  10396. case "object":
  10397. return Array.isArray(data)
  10398. ? ZodParsedType.array
  10399. : null === data
  10400. ? ZodParsedType.null
  10401. : data.then &&
  10402. "function" == typeof data.then &&
  10403. data.catch &&
  10404. "function" == typeof data.catch
  10405. ? ZodParsedType.promise
  10406. : "undefined" != typeof Map && data instanceof Map
  10407. ? ZodParsedType.map
  10408. : "undefined" != typeof Set && data instanceof Set
  10409. ? ZodParsedType.set
  10410. : "undefined" != typeof Date && data instanceof Date
  10411. ? ZodParsedType.date
  10412. : ZodParsedType.object
  10413. default:
  10414. return ZodParsedType.unknown
  10415. }
  10416. },
  10417. ZodIssueCode = util.arrayToEnum([
  10418. "invalid_type",
  10419. "invalid_literal",
  10420. "custom",
  10421. "invalid_union",
  10422. "invalid_union_discriminator",
  10423. "invalid_enum_value",
  10424. "unrecognized_keys",
  10425. "invalid_arguments",
  10426. "invalid_return_type",
  10427. "invalid_date",
  10428. "invalid_string",
  10429. "too_small",
  10430. "too_big",
  10431. "invalid_intersection_types",
  10432. "not_multiple_of",
  10433. "not_finite",
  10434. ])
  10435. class ZodError extends Error {
  10436. constructor(issues) {
  10437. super()
  10438. this.issues = []
  10439. this.addIssue = sub => {
  10440. this.issues = [...this.issues, sub]
  10441. }
  10442. this.addIssues = (subs = []) => {
  10443. this.issues = [...this.issues, ...subs]
  10444. }
  10445. const actualProto = new.target.prototype
  10446. Object.setPrototypeOf
  10447. ? Object.setPrototypeOf(this, actualProto)
  10448. : (this.__proto__ = actualProto)
  10449. this.name = "ZodError"
  10450. this.issues = issues
  10451. }
  10452. get errors() {
  10453. return this.issues
  10454. }
  10455. format(_mapper) {
  10456. const mapper =
  10457. _mapper ||
  10458. function (issue) {
  10459. return issue.message
  10460. },
  10461. fieldErrors = { _errors: [] },
  10462. processError = error => {
  10463. for (const issue of error.issues)
  10464. if ("invalid_union" === issue.code)
  10465. issue.unionErrors.map(processError)
  10466. else if ("invalid_return_type" === issue.code)
  10467. processError(issue.returnTypeError)
  10468. else if ("invalid_arguments" === issue.code)
  10469. processError(issue.argumentsError)
  10470. else if (0 === issue.path.length)
  10471. fieldErrors._errors.push(mapper(issue))
  10472. else {
  10473. let curr = fieldErrors,
  10474. i = 0
  10475. for (; i < issue.path.length; ) {
  10476. const el = issue.path[i]
  10477. if (i === issue.path.length - 1) {
  10478. curr[el] = curr[el] || { _errors: [] }
  10479. curr[el]._errors.push(mapper(issue))
  10480. } else curr[el] = curr[el] || { _errors: [] }
  10481. curr = curr[el]
  10482. i++
  10483. }
  10484. }
  10485. }
  10486. processError(this)
  10487. return fieldErrors
  10488. }
  10489. toString() {
  10490. return this.message
  10491. }
  10492. get message() {
  10493. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2)
  10494. }
  10495. get isEmpty() {
  10496. return 0 === this.issues.length
  10497. }
  10498. flatten(mapper = issue => issue.message) {
  10499. const fieldErrors = {},
  10500. formErrors = []
  10501. for (const sub of this.issues)
  10502. if (sub.path.length > 0) {
  10503. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []
  10504. fieldErrors[sub.path[0]].push(mapper(sub))
  10505. } else formErrors.push(mapper(sub))
  10506. return { formErrors, fieldErrors }
  10507. }
  10508. get formErrors() {
  10509. return this.flatten()
  10510. }
  10511. }
  10512. ZodError.create = issues => new ZodError(issues)
  10513. const errorMap = (issue, _ctx) => {
  10514. let message
  10515. switch (issue.code) {
  10516. case ZodIssueCode.invalid_type:
  10517. message =
  10518. issue.received === ZodParsedType.undefined
  10519. ? "Required"
  10520. : `Expected ${issue.expected}, received ${issue.received}`
  10521. break
  10522. case ZodIssueCode.invalid_literal:
  10523. message = `Invalid literal value, expected ${JSON.stringify(
  10524. issue.expected,
  10525. util.jsonStringifyReplacer
  10526. )}`
  10527. break
  10528. case ZodIssueCode.unrecognized_keys:
  10529. message = `Unrecognized key(s) in object: ${util.joinValues(
  10530. issue.keys,
  10531. ", "
  10532. )}`
  10533. break
  10534. case ZodIssueCode.invalid_union:
  10535. message = "Invalid input"
  10536. break
  10537. case ZodIssueCode.invalid_union_discriminator:
  10538. message = `Invalid discriminator value. Expected ${util.joinValues(
  10539. issue.options
  10540. )}`
  10541. break
  10542. case ZodIssueCode.invalid_enum_value:
  10543. message = `Invalid enum value. Expected ${util.joinValues(
  10544. issue.options
  10545. )}, received '${issue.received}'`
  10546. break
  10547. case ZodIssueCode.invalid_arguments:
  10548. message = "Invalid function arguments"
  10549. break
  10550. case ZodIssueCode.invalid_return_type:
  10551. message = "Invalid function return type"
  10552. break
  10553. case ZodIssueCode.invalid_date:
  10554. message = "Invalid date"
  10555. break
  10556. case ZodIssueCode.invalid_string:
  10557. if ("object" == typeof issue.validation)
  10558. if ("includes" in issue.validation) {
  10559. message = `Invalid input: must include "${issue.validation.includes}"`
  10560. "number" == typeof issue.validation.position &&
  10561. (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)
  10562. } else
  10563. "startsWith" in issue.validation
  10564. ? (message = `Invalid input: must start with "${issue.validation.startsWith}"`)
  10565. : "endsWith" in issue.validation
  10566. ? (message = `Invalid input: must end with "${issue.validation.endsWith}"`)
  10567. : util.assertNever(issue.validation)
  10568. else
  10569. message =
  10570. "regex" !== issue.validation
  10571. ? `Invalid ${issue.validation}`
  10572. : "Invalid"
  10573. break
  10574. case ZodIssueCode.too_small:
  10575. message =
  10576. "array" === issue.type
  10577. ? `Array must contain ${
  10578. issue.exact
  10579. ? "exactly"
  10580. : issue.inclusive
  10581. ? "at least"
  10582. : "more than"
  10583. } ${issue.minimum} element(s)`
  10584. : "string" === issue.type
  10585. ? `String must contain ${
  10586. issue.exact
  10587. ? "exactly"
  10588. : issue.inclusive
  10589. ? "at least"
  10590. : "over"
  10591. } ${issue.minimum} character(s)`
  10592. : "number" === issue.type
  10593. ? `Number must be ${
  10594. issue.exact
  10595. ? "exactly equal to "
  10596. : issue.inclusive
  10597. ? "greater than or equal to "
  10598. : "greater than "
  10599. }${issue.minimum}`
  10600. : "date" === issue.type
  10601. ? `Date must be ${
  10602. issue.exact
  10603. ? "exactly equal to "
  10604. : issue.inclusive
  10605. ? "greater than or equal to "
  10606. : "greater than "
  10607. }${new Date(Number(issue.minimum))}`
  10608. : "Invalid input"
  10609. break
  10610. case ZodIssueCode.too_big:
  10611. message =
  10612. "array" === issue.type
  10613. ? `Array must contain ${
  10614. issue.exact
  10615. ? "exactly"
  10616. : issue.inclusive
  10617. ? "at most"
  10618. : "less than"
  10619. } ${issue.maximum} element(s)`
  10620. : "string" === issue.type
  10621. ? `String must contain ${
  10622. issue.exact
  10623. ? "exactly"
  10624. : issue.inclusive
  10625. ? "at most"
  10626. : "under"
  10627. } ${issue.maximum} character(s)`
  10628. : "number" === issue.type
  10629. ? `Number must be ${
  10630. issue.exact
  10631. ? "exactly"
  10632. : issue.inclusive
  10633. ? "less than or equal to"
  10634. : "less than"
  10635. } ${issue.maximum}`
  10636. : "bigint" === issue.type
  10637. ? `BigInt must be ${
  10638. issue.exact
  10639. ? "exactly"
  10640. : issue.inclusive
  10641. ? "less than or equal to"
  10642. : "less than"
  10643. } ${issue.maximum}`
  10644. : "date" === issue.type
  10645. ? `Date must be ${
  10646. issue.exact
  10647. ? "exactly"
  10648. : issue.inclusive
  10649. ? "smaller than or equal to"
  10650. : "smaller than"
  10651. } ${new Date(Number(issue.maximum))}`
  10652. : "Invalid input"
  10653. break
  10654. case ZodIssueCode.custom:
  10655. message = "Invalid input"
  10656. break
  10657. case ZodIssueCode.invalid_intersection_types:
  10658. message = "Intersection results could not be merged"
  10659. break
  10660. case ZodIssueCode.not_multiple_of:
  10661. message = `Number must be a multiple of ${issue.multipleOf}`
  10662. break
  10663. case ZodIssueCode.not_finite:
  10664. message = "Number must be finite"
  10665. break
  10666. default:
  10667. message = _ctx.defaultError
  10668. util.assertNever(issue)
  10669. }
  10670. return { message }
  10671. }
  10672. let overrideErrorMap = errorMap
  10673. function getErrorMap() {
  10674. return overrideErrorMap
  10675. }
  10676. const makeIssue = params => {
  10677. const { data, path, errorMaps, issueData } = params,
  10678. fullPath = [...path, ...(issueData.path || [])],
  10679. fullIssue = { ...issueData, path: fullPath }
  10680. let errorMessage = ""
  10681. const maps = errorMaps
  10682. .filter(m => !!m)
  10683. .slice()
  10684. .reverse()
  10685. for (const map of maps)
  10686. errorMessage = map(fullIssue, {
  10687. data,
  10688. defaultError: errorMessage,
  10689. }).message
  10690. return {
  10691. ...issueData,
  10692. path: fullPath,
  10693. message: issueData.message || errorMessage,
  10694. }
  10695. }
  10696. function addIssueToContext(ctx, issueData) {
  10697. const issue = makeIssue({
  10698. issueData,
  10699. data: ctx.data,
  10700. path: ctx.path,
  10701. errorMaps: [
  10702. ctx.common.contextualErrorMap,
  10703. ctx.schemaErrorMap,
  10704. getErrorMap(),
  10705. errorMap,
  10706. ].filter(x => !!x),
  10707. })
  10708. ctx.common.issues.push(issue)
  10709. }
  10710. class ParseStatus {
  10711. constructor() {
  10712. this.value = "valid"
  10713. }
  10714. dirty() {
  10715. "valid" === this.value && (this.value = "dirty")
  10716. }
  10717. abort() {
  10718. "aborted" !== this.value && (this.value = "aborted")
  10719. }
  10720. static mergeArray(status, results) {
  10721. const arrayValue = []
  10722. for (const s of results) {
  10723. if ("aborted" === s.status) return INVALID
  10724. "dirty" === s.status && status.dirty()
  10725. arrayValue.push(s.value)
  10726. }
  10727. return { status: status.value, value: arrayValue }
  10728. }
  10729. static async mergeObjectAsync(status, pairs) {
  10730. const syncPairs = []
  10731. for (const pair of pairs)
  10732. syncPairs.push({ key: await pair.key, value: await pair.value })
  10733. return ParseStatus.mergeObjectSync(status, syncPairs)
  10734. }
  10735. static mergeObjectSync(status, pairs) {
  10736. const finalObject = {}
  10737. for (const pair of pairs) {
  10738. const { key, value } = pair
  10739. if ("aborted" === key.status) return INVALID
  10740. if ("aborted" === value.status) return INVALID
  10741. "dirty" === key.status && status.dirty()
  10742. "dirty" === value.status && status.dirty()
  10743. ;(void 0 !== value.value || pair.alwaysSet) &&
  10744. (finalObject[key.value] = value.value)
  10745. }
  10746. return { status: status.value, value: finalObject }
  10747. }
  10748. }
  10749. const INVALID = Object.freeze({ status: "aborted" }),
  10750. DIRTY = value => ({ status: "dirty", value }),
  10751. OK = value => ({ status: "valid", value }),
  10752. isAborted = x => "aborted" === x.status,
  10753. isDirty = x => "dirty" === x.status,
  10754. isValid = x => "valid" === x.status,
  10755. isAsync = x => "undefined" != typeof Promise && x instanceof Promise
  10756. var errorUtil
  10757. !(function (errorUtil) {
  10758. errorUtil.errToObj = message =>
  10759. "string" == typeof message ? { message } : message || {}
  10760. errorUtil.toString = message =>
  10761. "string" == typeof message
  10762. ? message
  10763. : null == message
  10764. ? void 0
  10765. : message.message
  10766. })(errorUtil || (errorUtil = {}))
  10767. class ParseInputLazyPath {
  10768. constructor(parent, value, path, key) {
  10769. this._cachedPath = []
  10770. this.parent = parent
  10771. this.data = value
  10772. this._path = path
  10773. this._key = key
  10774. }
  10775. get path() {
  10776. this._cachedPath.length ||
  10777. (this._key instanceof Array
  10778. ? this._cachedPath.push(...this._path, ...this._key)
  10779. : this._cachedPath.push(...this._path, this._key))
  10780. return this._cachedPath
  10781. }
  10782. }
  10783. const handleResult = (ctx, result) => {
  10784. if (isValid(result)) return { success: !0, data: result.value }
  10785. if (!ctx.common.issues.length)
  10786. throw new Error("Validation failed but no issues detected.")
  10787. return {
  10788. success: !1,
  10789. get error() {
  10790. if (this._error) return this._error
  10791. const error = new ZodError(ctx.common.issues)
  10792. this._error = error
  10793. return this._error
  10794. },
  10795. }
  10796. }
  10797. function processCreateParams(params) {
  10798. if (!params) return {}
  10799. const { errorMap, invalid_type_error, required_error, description } =
  10800. params
  10801. if (errorMap && (invalid_type_error || required_error))
  10802. throw new Error(
  10803. 'Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.'
  10804. )
  10805. return errorMap
  10806. ? { errorMap, description }
  10807. : {
  10808. errorMap: (iss, ctx) =>
  10809. "invalid_type" !== iss.code
  10810. ? { message: ctx.defaultError }
  10811. : void 0 === ctx.data
  10812. ? {
  10813. message:
  10814. null != required_error
  10815. ? required_error
  10816. : ctx.defaultError,
  10817. }
  10818. : {
  10819. message:
  10820. null != invalid_type_error
  10821. ? invalid_type_error
  10822. : ctx.defaultError,
  10823. },
  10824. description,
  10825. }
  10826. }
  10827. class ZodType {
  10828. constructor(def) {
  10829. this.spa = this.safeParseAsync
  10830. this._def = def
  10831. this.parse = this.parse.bind(this)
  10832. this.safeParse = this.safeParse.bind(this)
  10833. this.parseAsync = this.parseAsync.bind(this)
  10834. this.safeParseAsync = this.safeParseAsync.bind(this)
  10835. this.spa = this.spa.bind(this)
  10836. this.refine = this.refine.bind(this)
  10837. this.refinement = this.refinement.bind(this)
  10838. this.superRefine = this.superRefine.bind(this)
  10839. this.optional = this.optional.bind(this)
  10840. this.nullable = this.nullable.bind(this)
  10841. this.nullish = this.nullish.bind(this)
  10842. this.array = this.array.bind(this)
  10843. this.promise = this.promise.bind(this)
  10844. this.or = this.or.bind(this)
  10845. this.and = this.and.bind(this)
  10846. this.transform = this.transform.bind(this)
  10847. this.brand = this.brand.bind(this)
  10848. this.default = this.default.bind(this)
  10849. this.catch = this.catch.bind(this)
  10850. this.describe = this.describe.bind(this)
  10851. this.pipe = this.pipe.bind(this)
  10852. this.isNullable = this.isNullable.bind(this)
  10853. this.isOptional = this.isOptional.bind(this)
  10854. }
  10855. get description() {
  10856. return this._def.description
  10857. }
  10858. _getType(input) {
  10859. return getParsedType(input.data)
  10860. }
  10861. _getOrReturnCtx(input, ctx) {
  10862. return (
  10863. ctx || {
  10864. common: input.parent.common,
  10865. data: input.data,
  10866. parsedType: getParsedType(input.data),
  10867. schemaErrorMap: this._def.errorMap,
  10868. path: input.path,
  10869. parent: input.parent,
  10870. }
  10871. )
  10872. }
  10873. _processInputParams(input) {
  10874. return {
  10875. status: new ParseStatus(),
  10876. ctx: {
  10877. common: input.parent.common,
  10878. data: input.data,
  10879. parsedType: getParsedType(input.data),
  10880. schemaErrorMap: this._def.errorMap,
  10881. path: input.path,
  10882. parent: input.parent,
  10883. },
  10884. }
  10885. }
  10886. _parseSync(input) {
  10887. const result = this._parse(input)
  10888. if (isAsync(result))
  10889. throw new Error("Synchronous parse encountered promise.")
  10890. return result
  10891. }
  10892. _parseAsync(input) {
  10893. const result = this._parse(input)
  10894. return Promise.resolve(result)
  10895. }
  10896. parse(data, params) {
  10897. const result = this.safeParse(data, params)
  10898. if (result.success) return result.data
  10899. throw result.error
  10900. }
  10901. safeParse(data, params) {
  10902. var _a
  10903. const ctx = {
  10904. common: {
  10905. issues: [],
  10906. async:
  10907. null !== (_a = null == params ? void 0 : params.async) &&
  10908. void 0 !== _a &&
  10909. _a,
  10910. contextualErrorMap: null == params ? void 0 : params.errorMap,
  10911. },
  10912. path: (null == params ? void 0 : params.path) || [],
  10913. schemaErrorMap: this._def.errorMap,
  10914. parent: null,
  10915. data,
  10916. parsedType: getParsedType(data),
  10917. },
  10918. result = this._parseSync({ data, path: ctx.path, parent: ctx })
  10919. return handleResult(ctx, result)
  10920. }
  10921. async parseAsync(data, params) {
  10922. const result = await this.safeParseAsync(data, params)
  10923. if (result.success) return result.data
  10924. throw result.error
  10925. }
  10926. async safeParseAsync(data, params) {
  10927. const ctx = {
  10928. common: {
  10929. issues: [],
  10930. contextualErrorMap: null == params ? void 0 : params.errorMap,
  10931. async: !0,
  10932. },
  10933. path: (null == params ? void 0 : params.path) || [],
  10934. schemaErrorMap: this._def.errorMap,
  10935. parent: null,
  10936. data,
  10937. parsedType: getParsedType(data),
  10938. },
  10939. maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }),
  10940. result = await (isAsync(maybeAsyncResult)
  10941. ? maybeAsyncResult
  10942. : Promise.resolve(maybeAsyncResult))
  10943. return handleResult(ctx, result)
  10944. }
  10945. refine(check, message) {
  10946. const getIssueProperties = val =>
  10947. "string" == typeof message || void 0 === message
  10948. ? { message }
  10949. : "function" == typeof message
  10950. ? message(val)
  10951. : message
  10952. return this._refinement((val, ctx) => {
  10953. const result = check(val),
  10954. setError = () =>
  10955. ctx.addIssue({
  10956. code: ZodIssueCode.custom,
  10957. ...getIssueProperties(val),
  10958. })
  10959. if ("undefined" != typeof Promise && result instanceof Promise)
  10960. return result.then(data => {
  10961. if (data) return !0
  10962. setError()
  10963. return !1
  10964. })
  10965. if (result) return !0
  10966. setError()
  10967. return !1
  10968. })
  10969. }
  10970. refinement(check, refinementData) {
  10971. return this._refinement((val, ctx) => {
  10972. if (check(val)) return !0
  10973. ctx.addIssue(
  10974. "function" == typeof refinementData
  10975. ? refinementData(val, ctx)
  10976. : refinementData
  10977. )
  10978. return !1
  10979. })
  10980. }
  10981. _refinement(refinement) {
  10982. return new ZodEffects({
  10983. schema: this,
  10984. typeName: ZodFirstPartyTypeKind.ZodEffects,
  10985. effect: { type: "refinement", refinement },
  10986. })
  10987. }
  10988. superRefine(refinement) {
  10989. return this._refinement(refinement)
  10990. }
  10991. optional() {
  10992. return ZodOptional.create(this, this._def)
  10993. }
  10994. nullable() {
  10995. return ZodNullable.create(this, this._def)
  10996. }
  10997. nullish() {
  10998. return this.nullable().optional()
  10999. }
  11000. array() {
  11001. return ZodArray.create(this, this._def)
  11002. }
  11003. promise() {
  11004. return ZodPromise.create(this, this._def)
  11005. }
  11006. or(option) {
  11007. return ZodUnion.create([this, option], this._def)
  11008. }
  11009. and(incoming) {
  11010. return ZodIntersection.create(this, incoming, this._def)
  11011. }
  11012. transform(transform) {
  11013. return new ZodEffects({
  11014. ...processCreateParams(this._def),
  11015. schema: this,
  11016. typeName: ZodFirstPartyTypeKind.ZodEffects,
  11017. effect: { type: "transform", transform },
  11018. })
  11019. }
  11020. default(def) {
  11021. const defaultValueFunc = "function" == typeof def ? def : () => def
  11022. return new ZodDefault({
  11023. ...processCreateParams(this._def),
  11024. innerType: this,
  11025. defaultValue: defaultValueFunc,
  11026. typeName: ZodFirstPartyTypeKind.ZodDefault,
  11027. })
  11028. }
  11029. brand() {
  11030. return new ZodBranded({
  11031. typeName: ZodFirstPartyTypeKind.ZodBranded,
  11032. type: this,
  11033. ...processCreateParams(this._def),
  11034. })
  11035. }
  11036. catch(def) {
  11037. const catchValueFunc = "function" == typeof def ? def : () => def
  11038. return new ZodCatch({
  11039. ...processCreateParams(this._def),
  11040. innerType: this,
  11041. catchValue: catchValueFunc,
  11042. typeName: ZodFirstPartyTypeKind.ZodCatch,
  11043. })
  11044. }
  11045. describe(description) {
  11046. return new (0, this.constructor)({ ...this._def, description })
  11047. }
  11048. pipe(target) {
  11049. return ZodPipeline.create(this, target)
  11050. }
  11051. isOptional() {
  11052. return this.safeParse(void 0).success
  11053. }
  11054. isNullable() {
  11055. return this.safeParse(null).success
  11056. }
  11057. }
  11058. const cuidRegex = /^c[^\s-]{8,}$/i,
  11059. cuid2Regex = /^[a-z][a-z0-9]*$/,
  11060. ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/,
  11061. uuidRegex =
  11062. /^([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,
  11063. emailRegex =
  11064. /^(([^<>()[\]\\.,;:\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,})+))$/,
  11065. emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,
  11066. ipv4Regex =
  11067. /^(((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}))$/,
  11068. ipv6Regex =
  11069. /^(([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})))$/
  11070. class ZodString extends ZodType {
  11071. constructor() {
  11072. super(...arguments)
  11073. this._regex = (regex, validation, message) =>
  11074. this.refinement(data => regex.test(data), {
  11075. validation,
  11076. code: ZodIssueCode.invalid_string,
  11077. ...errorUtil.errToObj(message),
  11078. })
  11079. this.nonempty = message => this.min(1, errorUtil.errToObj(message))
  11080. this.trim = () =>
  11081. new ZodString({
  11082. ...this._def,
  11083. checks: [...this._def.checks, { kind: "trim" }],
  11084. })
  11085. this.toLowerCase = () =>
  11086. new ZodString({
  11087. ...this._def,
  11088. checks: [...this._def.checks, { kind: "toLowerCase" }],
  11089. })
  11090. this.toUpperCase = () =>
  11091. new ZodString({
  11092. ...this._def,
  11093. checks: [...this._def.checks, { kind: "toUpperCase" }],
  11094. })
  11095. }
  11096. _parse(input) {
  11097. this._def.coerce && (input.data = String(input.data))
  11098. if (this._getType(input) !== ZodParsedType.string) {
  11099. const ctx = this._getOrReturnCtx(input)
  11100. addIssueToContext(ctx, {
  11101. code: ZodIssueCode.invalid_type,
  11102. expected: ZodParsedType.string,
  11103. received: ctx.parsedType,
  11104. })
  11105. return INVALID
  11106. }
  11107. const status = new ParseStatus()
  11108. let ctx
  11109. for (const check of this._def.checks)
  11110. if ("min" === check.kind) {
  11111. if (input.data.length < check.value) {
  11112. ctx = this._getOrReturnCtx(input, ctx)
  11113. addIssueToContext(ctx, {
  11114. code: ZodIssueCode.too_small,
  11115. minimum: check.value,
  11116. type: "string",
  11117. inclusive: !0,
  11118. exact: !1,
  11119. message: check.message,
  11120. })
  11121. status.dirty()
  11122. }
  11123. } else if ("max" === check.kind) {
  11124. if (input.data.length > check.value) {
  11125. ctx = this._getOrReturnCtx(input, ctx)
  11126. addIssueToContext(ctx, {
  11127. code: ZodIssueCode.too_big,
  11128. maximum: check.value,
  11129. type: "string",
  11130. inclusive: !0,
  11131. exact: !1,
  11132. message: check.message,
  11133. })
  11134. status.dirty()
  11135. }
  11136. } else if ("length" === check.kind) {
  11137. const tooBig = input.data.length > check.value,
  11138. tooSmall = input.data.length < check.value
  11139. if (tooBig || tooSmall) {
  11140. ctx = this._getOrReturnCtx(input, ctx)
  11141. tooBig
  11142. ? addIssueToContext(ctx, {
  11143. code: ZodIssueCode.too_big,
  11144. maximum: check.value,
  11145. type: "string",
  11146. inclusive: !0,
  11147. exact: !0,
  11148. message: check.message,
  11149. })
  11150. : tooSmall &&
  11151. addIssueToContext(ctx, {
  11152. code: ZodIssueCode.too_small,
  11153. minimum: check.value,
  11154. type: "string",
  11155. inclusive: !0,
  11156. exact: !0,
  11157. message: check.message,
  11158. })
  11159. status.dirty()
  11160. }
  11161. } else if ("email" === check.kind) {
  11162. if (!emailRegex.test(input.data)) {
  11163. ctx = this._getOrReturnCtx(input, ctx)
  11164. addIssueToContext(ctx, {
  11165. validation: "email",
  11166. code: ZodIssueCode.invalid_string,
  11167. message: check.message,
  11168. })
  11169. status.dirty()
  11170. }
  11171. } else if ("emoji" === check.kind) {
  11172. if (!emojiRegex.test(input.data)) {
  11173. ctx = this._getOrReturnCtx(input, ctx)
  11174. addIssueToContext(ctx, {
  11175. validation: "emoji",
  11176. code: ZodIssueCode.invalid_string,
  11177. message: check.message,
  11178. })
  11179. status.dirty()
  11180. }
  11181. } else if ("uuid" === check.kind) {
  11182. if (!uuidRegex.test(input.data)) {
  11183. ctx = this._getOrReturnCtx(input, ctx)
  11184. addIssueToContext(ctx, {
  11185. validation: "uuid",
  11186. code: ZodIssueCode.invalid_string,
  11187. message: check.message,
  11188. })
  11189. status.dirty()
  11190. }
  11191. } else if ("cuid" === check.kind) {
  11192. if (!cuidRegex.test(input.data)) {
  11193. ctx = this._getOrReturnCtx(input, ctx)
  11194. addIssueToContext(ctx, {
  11195. validation: "cuid",
  11196. code: ZodIssueCode.invalid_string,
  11197. message: check.message,
  11198. })
  11199. status.dirty()
  11200. }
  11201. } else if ("cuid2" === check.kind) {
  11202. if (!cuid2Regex.test(input.data)) {
  11203. ctx = this._getOrReturnCtx(input, ctx)
  11204. addIssueToContext(ctx, {
  11205. validation: "cuid2",
  11206. code: ZodIssueCode.invalid_string,
  11207. message: check.message,
  11208. })
  11209. status.dirty()
  11210. }
  11211. } else if ("ulid" === check.kind) {
  11212. if (!ulidRegex.test(input.data)) {
  11213. ctx = this._getOrReturnCtx(input, ctx)
  11214. addIssueToContext(ctx, {
  11215. validation: "ulid",
  11216. code: ZodIssueCode.invalid_string,
  11217. message: check.message,
  11218. })
  11219. status.dirty()
  11220. }
  11221. } else if ("url" === check.kind)
  11222. try {
  11223. new URL(input.data)
  11224. } catch (_a) {
  11225. ctx = this._getOrReturnCtx(input, ctx)
  11226. addIssueToContext(ctx, {
  11227. validation: "url",
  11228. code: ZodIssueCode.invalid_string,
  11229. message: check.message,
  11230. })
  11231. status.dirty()
  11232. }
  11233. else if ("regex" === check.kind) {
  11234. check.regex.lastIndex = 0
  11235. if (!check.regex.test(input.data)) {
  11236. ctx = this._getOrReturnCtx(input, ctx)
  11237. addIssueToContext(ctx, {
  11238. validation: "regex",
  11239. code: ZodIssueCode.invalid_string,
  11240. message: check.message,
  11241. })
  11242. status.dirty()
  11243. }
  11244. } else if ("trim" === check.kind) input.data = input.data.trim()
  11245. else if ("includes" === check.kind) {
  11246. if (!input.data.includes(check.value, check.position)) {
  11247. ctx = this._getOrReturnCtx(input, ctx)
  11248. addIssueToContext(ctx, {
  11249. code: ZodIssueCode.invalid_string,
  11250. validation: { includes: check.value, position: check.position },
  11251. message: check.message,
  11252. })
  11253. status.dirty()
  11254. }
  11255. } else if ("toLowerCase" === check.kind)
  11256. input.data = input.data.toLowerCase()
  11257. else if ("toUpperCase" === check.kind)
  11258. input.data = input.data.toUpperCase()
  11259. else if ("startsWith" === check.kind) {
  11260. if (!input.data.startsWith(check.value)) {
  11261. ctx = this._getOrReturnCtx(input, ctx)
  11262. addIssueToContext(ctx, {
  11263. code: ZodIssueCode.invalid_string,
  11264. validation: { startsWith: check.value },
  11265. message: check.message,
  11266. })
  11267. status.dirty()
  11268. }
  11269. } else if ("endsWith" === check.kind) {
  11270. if (!input.data.endsWith(check.value)) {
  11271. ctx = this._getOrReturnCtx(input, ctx)
  11272. addIssueToContext(ctx, {
  11273. code: ZodIssueCode.invalid_string,
  11274. validation: { endsWith: check.value },
  11275. message: check.message,
  11276. })
  11277. status.dirty()
  11278. }
  11279. } else if ("datetime" === check.kind) {
  11280. if (
  11281. !(
  11282. (args = check).precision
  11283. ? args.offset
  11284. ? new RegExp(
  11285. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`
  11286. )
  11287. : new RegExp(
  11288. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`
  11289. )
  11290. : 0 === args.precision
  11291. ? args.offset
  11292. ? new RegExp(
  11293. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  11294. )
  11295. : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")
  11296. : args.offset
  11297. ? new RegExp(
  11298. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  11299. )
  11300. : new RegExp(
  11301. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"
  11302. )
  11303. ).test(input.data)
  11304. ) {
  11305. ctx = this._getOrReturnCtx(input, ctx)
  11306. addIssueToContext(ctx, {
  11307. code: ZodIssueCode.invalid_string,
  11308. validation: "datetime",
  11309. message: check.message,
  11310. })
  11311. status.dirty()
  11312. }
  11313. } else if ("ip" === check.kind) {
  11314. if (
  11315. !((ip = input.data),
  11316. (version = check.version),
  11317. (("v4" === version || !version) && ipv4Regex.test(ip)) ||
  11318. (("v6" === version || !version) && ipv6Regex.test(ip)))
  11319. ) {
  11320. ctx = this._getOrReturnCtx(input, ctx)
  11321. addIssueToContext(ctx, {
  11322. validation: "ip",
  11323. code: ZodIssueCode.invalid_string,
  11324. message: check.message,
  11325. })
  11326. status.dirty()
  11327. }
  11328. } else util.assertNever(check)
  11329. var ip, version, args
  11330. return { status: status.value, value: input.data }
  11331. }
  11332. _addCheck(check) {
  11333. return new ZodString({
  11334. ...this._def,
  11335. checks: [...this._def.checks, check],
  11336. })
  11337. }
  11338. email(message) {
  11339. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) })
  11340. }
  11341. url(message) {
  11342. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) })
  11343. }
  11344. emoji(message) {
  11345. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) })
  11346. }
  11347. uuid(message) {
  11348. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) })
  11349. }
  11350. cuid(message) {
  11351. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) })
  11352. }
  11353. cuid2(message) {
  11354. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) })
  11355. }
  11356. ulid(message) {
  11357. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) })
  11358. }
  11359. ip(options) {
  11360. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) })
  11361. }
  11362. datetime(options) {
  11363. var _a
  11364. return "string" == typeof options
  11365. ? this._addCheck({
  11366. kind: "datetime",
  11367. precision: null,
  11368. offset: !1,
  11369. message: options,
  11370. })
  11371. : this._addCheck({
  11372. kind: "datetime",
  11373. precision:
  11374. void 0 === (null == options ? void 0 : options.precision)
  11375. ? null
  11376. : null == options
  11377. ? void 0
  11378. : options.precision,
  11379. offset:
  11380. null !== (_a = null == options ? void 0 : options.offset) &&
  11381. void 0 !== _a &&
  11382. _a,
  11383. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  11384. })
  11385. }
  11386. regex(regex, message) {
  11387. return this._addCheck({
  11388. kind: "regex",
  11389. regex,
  11390. ...errorUtil.errToObj(message),
  11391. })
  11392. }
  11393. includes(value, options) {
  11394. return this._addCheck({
  11395. kind: "includes",
  11396. value,
  11397. position: null == options ? void 0 : options.position,
  11398. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  11399. })
  11400. }
  11401. startsWith(value, message) {
  11402. return this._addCheck({
  11403. kind: "startsWith",
  11404. value,
  11405. ...errorUtil.errToObj(message),
  11406. })
  11407. }
  11408. endsWith(value, message) {
  11409. return this._addCheck({
  11410. kind: "endsWith",
  11411. value,
  11412. ...errorUtil.errToObj(message),
  11413. })
  11414. }
  11415. min(minLength, message) {
  11416. return this._addCheck({
  11417. kind: "min",
  11418. value: minLength,
  11419. ...errorUtil.errToObj(message),
  11420. })
  11421. }
  11422. max(maxLength, message) {
  11423. return this._addCheck({
  11424. kind: "max",
  11425. value: maxLength,
  11426. ...errorUtil.errToObj(message),
  11427. })
  11428. }
  11429. length(len, message) {
  11430. return this._addCheck({
  11431. kind: "length",
  11432. value: len,
  11433. ...errorUtil.errToObj(message),
  11434. })
  11435. }
  11436. get isDatetime() {
  11437. return !!this._def.checks.find(ch => "datetime" === ch.kind)
  11438. }
  11439. get isEmail() {
  11440. return !!this._def.checks.find(ch => "email" === ch.kind)
  11441. }
  11442. get isURL() {
  11443. return !!this._def.checks.find(ch => "url" === ch.kind)
  11444. }
  11445. get isEmoji() {
  11446. return !!this._def.checks.find(ch => "emoji" === ch.kind)
  11447. }
  11448. get isUUID() {
  11449. return !!this._def.checks.find(ch => "uuid" === ch.kind)
  11450. }
  11451. get isCUID() {
  11452. return !!this._def.checks.find(ch => "cuid" === ch.kind)
  11453. }
  11454. get isCUID2() {
  11455. return !!this._def.checks.find(ch => "cuid2" === ch.kind)
  11456. }
  11457. get isULID() {
  11458. return !!this._def.checks.find(ch => "ulid" === ch.kind)
  11459. }
  11460. get isIP() {
  11461. return !!this._def.checks.find(ch => "ip" === ch.kind)
  11462. }
  11463. get minLength() {
  11464. let min = null
  11465. for (const ch of this._def.checks)
  11466. "min" === ch.kind &&
  11467. (null === min || ch.value > min) &&
  11468. (min = ch.value)
  11469. return min
  11470. }
  11471. get maxLength() {
  11472. let max = null
  11473. for (const ch of this._def.checks)
  11474. "max" === ch.kind &&
  11475. (null === max || ch.value < max) &&
  11476. (max = ch.value)
  11477. return max
  11478. }
  11479. }
  11480. ZodString.create = params => {
  11481. var _a
  11482. return new ZodString({
  11483. checks: [],
  11484. typeName: ZodFirstPartyTypeKind.ZodString,
  11485. coerce:
  11486. null !== (_a = null == params ? void 0 : params.coerce) &&
  11487. void 0 !== _a &&
  11488. _a,
  11489. ...processCreateParams(params),
  11490. })
  11491. }
  11492. function floatSafeRemainder(val, step) {
  11493. const valDecCount = (val.toString().split(".")[1] || "").length,
  11494. stepDecCount = (step.toString().split(".")[1] || "").length,
  11495. decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount
  11496. return (
  11497. (parseInt(val.toFixed(decCount).replace(".", "")) %
  11498. parseInt(step.toFixed(decCount).replace(".", ""))) /
  11499. Math.pow(10, decCount)
  11500. )
  11501. }
  11502. class ZodNumber extends ZodType {
  11503. constructor() {
  11504. super(...arguments)
  11505. this.min = this.gte
  11506. this.max = this.lte
  11507. this.step = this.multipleOf
  11508. }
  11509. _parse(input) {
  11510. this._def.coerce && (input.data = Number(input.data))
  11511. if (this._getType(input) !== ZodParsedType.number) {
  11512. const ctx = this._getOrReturnCtx(input)
  11513. addIssueToContext(ctx, {
  11514. code: ZodIssueCode.invalid_type,
  11515. expected: ZodParsedType.number,
  11516. received: ctx.parsedType,
  11517. })
  11518. return INVALID
  11519. }
  11520. let ctx
  11521. const status = new ParseStatus()
  11522. for (const check of this._def.checks)
  11523. if ("int" === check.kind) {
  11524. if (!util.isInteger(input.data)) {
  11525. ctx = this._getOrReturnCtx(input, ctx)
  11526. addIssueToContext(ctx, {
  11527. code: ZodIssueCode.invalid_type,
  11528. expected: "integer",
  11529. received: "float",
  11530. message: check.message,
  11531. })
  11532. status.dirty()
  11533. }
  11534. } else if ("min" === check.kind) {
  11535. if (
  11536. check.inclusive
  11537. ? input.data < check.value
  11538. : input.data <= check.value
  11539. ) {
  11540. ctx = this._getOrReturnCtx(input, ctx)
  11541. addIssueToContext(ctx, {
  11542. code: ZodIssueCode.too_small,
  11543. minimum: check.value,
  11544. type: "number",
  11545. inclusive: check.inclusive,
  11546. exact: !1,
  11547. message: check.message,
  11548. })
  11549. status.dirty()
  11550. }
  11551. } else if ("max" === check.kind) {
  11552. if (
  11553. check.inclusive
  11554. ? input.data > check.value
  11555. : input.data >= check.value
  11556. ) {
  11557. ctx = this._getOrReturnCtx(input, ctx)
  11558. addIssueToContext(ctx, {
  11559. code: ZodIssueCode.too_big,
  11560. maximum: check.value,
  11561. type: "number",
  11562. inclusive: check.inclusive,
  11563. exact: !1,
  11564. message: check.message,
  11565. })
  11566. status.dirty()
  11567. }
  11568. } else if ("multipleOf" === check.kind) {
  11569. if (0 !== floatSafeRemainder(input.data, check.value)) {
  11570. ctx = this._getOrReturnCtx(input, ctx)
  11571. addIssueToContext(ctx, {
  11572. code: ZodIssueCode.not_multiple_of,
  11573. multipleOf: check.value,
  11574. message: check.message,
  11575. })
  11576. status.dirty()
  11577. }
  11578. } else if ("finite" === check.kind) {
  11579. if (!Number.isFinite(input.data)) {
  11580. ctx = this._getOrReturnCtx(input, ctx)
  11581. addIssueToContext(ctx, {
  11582. code: ZodIssueCode.not_finite,
  11583. message: check.message,
  11584. })
  11585. status.dirty()
  11586. }
  11587. } else util.assertNever(check)
  11588. return { status: status.value, value: input.data }
  11589. }
  11590. gte(value, message) {
  11591. return this.setLimit("min", value, !0, errorUtil.toString(message))
  11592. }
  11593. gt(value, message) {
  11594. return this.setLimit("min", value, !1, errorUtil.toString(message))
  11595. }
  11596. lte(value, message) {
  11597. return this.setLimit("max", value, !0, errorUtil.toString(message))
  11598. }
  11599. lt(value, message) {
  11600. return this.setLimit("max", value, !1, errorUtil.toString(message))
  11601. }
  11602. setLimit(kind, value, inclusive, message) {
  11603. return new ZodNumber({
  11604. ...this._def,
  11605. checks: [
  11606. ...this._def.checks,
  11607. { kind, value, inclusive, message: errorUtil.toString(message) },
  11608. ],
  11609. })
  11610. }
  11611. _addCheck(check) {
  11612. return new ZodNumber({
  11613. ...this._def,
  11614. checks: [...this._def.checks, check],
  11615. })
  11616. }
  11617. int(message) {
  11618. return this._addCheck({
  11619. kind: "int",
  11620. message: errorUtil.toString(message),
  11621. })
  11622. }
  11623. positive(message) {
  11624. return this._addCheck({
  11625. kind: "min",
  11626. value: 0,
  11627. inclusive: !1,
  11628. message: errorUtil.toString(message),
  11629. })
  11630. }
  11631. negative(message) {
  11632. return this._addCheck({
  11633. kind: "max",
  11634. value: 0,
  11635. inclusive: !1,
  11636. message: errorUtil.toString(message),
  11637. })
  11638. }
  11639. nonpositive(message) {
  11640. return this._addCheck({
  11641. kind: "max",
  11642. value: 0,
  11643. inclusive: !0,
  11644. message: errorUtil.toString(message),
  11645. })
  11646. }
  11647. nonnegative(message) {
  11648. return this._addCheck({
  11649. kind: "min",
  11650. value: 0,
  11651. inclusive: !0,
  11652. message: errorUtil.toString(message),
  11653. })
  11654. }
  11655. multipleOf(value, message) {
  11656. return this._addCheck({
  11657. kind: "multipleOf",
  11658. value,
  11659. message: errorUtil.toString(message),
  11660. })
  11661. }
  11662. finite(message) {
  11663. return this._addCheck({
  11664. kind: "finite",
  11665. message: errorUtil.toString(message),
  11666. })
  11667. }
  11668. safe(message) {
  11669. return this._addCheck({
  11670. kind: "min",
  11671. inclusive: !0,
  11672. value: Number.MIN_SAFE_INTEGER,
  11673. message: errorUtil.toString(message),
  11674. })._addCheck({
  11675. kind: "max",
  11676. inclusive: !0,
  11677. value: Number.MAX_SAFE_INTEGER,
  11678. message: errorUtil.toString(message),
  11679. })
  11680. }
  11681. get minValue() {
  11682. let min = null
  11683. for (const ch of this._def.checks)
  11684. "min" === ch.kind &&
  11685. (null === min || ch.value > min) &&
  11686. (min = ch.value)
  11687. return min
  11688. }
  11689. get maxValue() {
  11690. let max = null
  11691. for (const ch of this._def.checks)
  11692. "max" === ch.kind &&
  11693. (null === max || ch.value < max) &&
  11694. (max = ch.value)
  11695. return max
  11696. }
  11697. get isInt() {
  11698. return !!this._def.checks.find(
  11699. ch =>
  11700. "int" === ch.kind ||
  11701. ("multipleOf" === ch.kind && util.isInteger(ch.value))
  11702. )
  11703. }
  11704. get isFinite() {
  11705. let max = null,
  11706. min = null
  11707. for (const ch of this._def.checks) {
  11708. if (
  11709. "finite" === ch.kind ||
  11710. "int" === ch.kind ||
  11711. "multipleOf" === ch.kind
  11712. )
  11713. return !0
  11714. "min" === ch.kind
  11715. ? (null === min || ch.value > min) && (min = ch.value)
  11716. : "max" === ch.kind &&
  11717. (null === max || ch.value < max) &&
  11718. (max = ch.value)
  11719. }
  11720. return Number.isFinite(min) && Number.isFinite(max)
  11721. }
  11722. }
  11723. ZodNumber.create = params =>
  11724. new ZodNumber({
  11725. checks: [],
  11726. typeName: ZodFirstPartyTypeKind.ZodNumber,
  11727. coerce: (null == params ? void 0 : params.coerce) || !1,
  11728. ...processCreateParams(params),
  11729. })
  11730. class ZodBigInt extends ZodType {
  11731. constructor() {
  11732. super(...arguments)
  11733. this.min = this.gte
  11734. this.max = this.lte
  11735. }
  11736. _parse(input) {
  11737. this._def.coerce && (input.data = BigInt(input.data))
  11738. if (this._getType(input) !== ZodParsedType.bigint) {
  11739. const ctx = this._getOrReturnCtx(input)
  11740. addIssueToContext(ctx, {
  11741. code: ZodIssueCode.invalid_type,
  11742. expected: ZodParsedType.bigint,
  11743. received: ctx.parsedType,
  11744. })
  11745. return INVALID
  11746. }
  11747. let ctx
  11748. const status = new ParseStatus()
  11749. for (const check of this._def.checks)
  11750. if ("min" === check.kind) {
  11751. if (
  11752. check.inclusive
  11753. ? input.data < check.value
  11754. : input.data <= check.value
  11755. ) {
  11756. ctx = this._getOrReturnCtx(input, ctx)
  11757. addIssueToContext(ctx, {
  11758. code: ZodIssueCode.too_small,
  11759. type: "bigint",
  11760. minimum: check.value,
  11761. inclusive: check.inclusive,
  11762. message: check.message,
  11763. })
  11764. status.dirty()
  11765. }
  11766. } else if ("max" === check.kind) {
  11767. if (
  11768. check.inclusive
  11769. ? input.data > check.value
  11770. : input.data >= check.value
  11771. ) {
  11772. ctx = this._getOrReturnCtx(input, ctx)
  11773. addIssueToContext(ctx, {
  11774. code: ZodIssueCode.too_big,
  11775. type: "bigint",
  11776. maximum: check.value,
  11777. inclusive: check.inclusive,
  11778. message: check.message,
  11779. })
  11780. status.dirty()
  11781. }
  11782. } else if ("multipleOf" === check.kind) {
  11783. if (input.data % check.value !== BigInt(0)) {
  11784. ctx = this._getOrReturnCtx(input, ctx)
  11785. addIssueToContext(ctx, {
  11786. code: ZodIssueCode.not_multiple_of,
  11787. multipleOf: check.value,
  11788. message: check.message,
  11789. })
  11790. status.dirty()
  11791. }
  11792. } else util.assertNever(check)
  11793. return { status: status.value, value: input.data }
  11794. }
  11795. gte(value, message) {
  11796. return this.setLimit("min", value, !0, errorUtil.toString(message))
  11797. }
  11798. gt(value, message) {
  11799. return this.setLimit("min", value, !1, errorUtil.toString(message))
  11800. }
  11801. lte(value, message) {
  11802. return this.setLimit("max", value, !0, errorUtil.toString(message))
  11803. }
  11804. lt(value, message) {
  11805. return this.setLimit("max", value, !1, errorUtil.toString(message))
  11806. }
  11807. setLimit(kind, value, inclusive, message) {
  11808. return new ZodBigInt({
  11809. ...this._def,
  11810. checks: [
  11811. ...this._def.checks,
  11812. { kind, value, inclusive, message: errorUtil.toString(message) },
  11813. ],
  11814. })
  11815. }
  11816. _addCheck(check) {
  11817. return new ZodBigInt({
  11818. ...this._def,
  11819. checks: [...this._def.checks, check],
  11820. })
  11821. }
  11822. positive(message) {
  11823. return this._addCheck({
  11824. kind: "min",
  11825. value: BigInt(0),
  11826. inclusive: !1,
  11827. message: errorUtil.toString(message),
  11828. })
  11829. }
  11830. negative(message) {
  11831. return this._addCheck({
  11832. kind: "max",
  11833. value: BigInt(0),
  11834. inclusive: !1,
  11835. message: errorUtil.toString(message),
  11836. })
  11837. }
  11838. nonpositive(message) {
  11839. return this._addCheck({
  11840. kind: "max",
  11841. value: BigInt(0),
  11842. inclusive: !0,
  11843. message: errorUtil.toString(message),
  11844. })
  11845. }
  11846. nonnegative(message) {
  11847. return this._addCheck({
  11848. kind: "min",
  11849. value: BigInt(0),
  11850. inclusive: !0,
  11851. message: errorUtil.toString(message),
  11852. })
  11853. }
  11854. multipleOf(value, message) {
  11855. return this._addCheck({
  11856. kind: "multipleOf",
  11857. value,
  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. }
  11878. ZodBigInt.create = params => {
  11879. var _a
  11880. return new ZodBigInt({
  11881. checks: [],
  11882. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  11883. coerce:
  11884. null !== (_a = null == params ? void 0 : params.coerce) &&
  11885. void 0 !== _a &&
  11886. _a,
  11887. ...processCreateParams(params),
  11888. })
  11889. }
  11890. class ZodBoolean extends ZodType {
  11891. _parse(input) {
  11892. this._def.coerce && (input.data = Boolean(input.data))
  11893. if (this._getType(input) !== ZodParsedType.boolean) {
  11894. const ctx = this._getOrReturnCtx(input)
  11895. addIssueToContext(ctx, {
  11896. code: ZodIssueCode.invalid_type,
  11897. expected: ZodParsedType.boolean,
  11898. received: ctx.parsedType,
  11899. })
  11900. return INVALID
  11901. }
  11902. return OK(input.data)
  11903. }
  11904. }
  11905. ZodBoolean.create = params =>
  11906. new ZodBoolean({
  11907. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  11908. coerce: (null == params ? void 0 : params.coerce) || !1,
  11909. ...processCreateParams(params),
  11910. })
  11911. class ZodDate extends ZodType {
  11912. _parse(input) {
  11913. this._def.coerce && (input.data = new Date(input.data))
  11914. if (this._getType(input) !== ZodParsedType.date) {
  11915. const ctx = this._getOrReturnCtx(input)
  11916. addIssueToContext(ctx, {
  11917. code: ZodIssueCode.invalid_type,
  11918. expected: ZodParsedType.date,
  11919. received: ctx.parsedType,
  11920. })
  11921. return INVALID
  11922. }
  11923. if (isNaN(input.data.getTime())) {
  11924. addIssueToContext(this._getOrReturnCtx(input), {
  11925. code: ZodIssueCode.invalid_date,
  11926. })
  11927. return INVALID
  11928. }
  11929. const status = new ParseStatus()
  11930. let ctx
  11931. for (const check of this._def.checks)
  11932. if ("min" === check.kind) {
  11933. if (input.data.getTime() < check.value) {
  11934. ctx = this._getOrReturnCtx(input, ctx)
  11935. addIssueToContext(ctx, {
  11936. code: ZodIssueCode.too_small,
  11937. message: check.message,
  11938. inclusive: !0,
  11939. exact: !1,
  11940. minimum: check.value,
  11941. type: "date",
  11942. })
  11943. status.dirty()
  11944. }
  11945. } else if ("max" === check.kind) {
  11946. if (input.data.getTime() > check.value) {
  11947. ctx = this._getOrReturnCtx(input, ctx)
  11948. addIssueToContext(ctx, {
  11949. code: ZodIssueCode.too_big,
  11950. message: check.message,
  11951. inclusive: !0,
  11952. exact: !1,
  11953. maximum: check.value,
  11954. type: "date",
  11955. })
  11956. status.dirty()
  11957. }
  11958. } else util.assertNever(check)
  11959. return { status: status.value, value: new Date(input.data.getTime()) }
  11960. }
  11961. _addCheck(check) {
  11962. return new ZodDate({
  11963. ...this._def,
  11964. checks: [...this._def.checks, check],
  11965. })
  11966. }
  11967. min(minDate, message) {
  11968. return this._addCheck({
  11969. kind: "min",
  11970. value: minDate.getTime(),
  11971. message: errorUtil.toString(message),
  11972. })
  11973. }
  11974. max(maxDate, message) {
  11975. return this._addCheck({
  11976. kind: "max",
  11977. value: maxDate.getTime(),
  11978. message: errorUtil.toString(message),
  11979. })
  11980. }
  11981. get minDate() {
  11982. let min = null
  11983. for (const ch of this._def.checks)
  11984. "min" === ch.kind &&
  11985. (null === min || ch.value > min) &&
  11986. (min = ch.value)
  11987. return null != min ? new Date(min) : null
  11988. }
  11989. get maxDate() {
  11990. let max = null
  11991. for (const ch of this._def.checks)
  11992. "max" === ch.kind &&
  11993. (null === max || ch.value < max) &&
  11994. (max = ch.value)
  11995. return null != max ? new Date(max) : null
  11996. }
  11997. }
  11998. ZodDate.create = params =>
  11999. new ZodDate({
  12000. checks: [],
  12001. coerce: (null == params ? void 0 : params.coerce) || !1,
  12002. typeName: ZodFirstPartyTypeKind.ZodDate,
  12003. ...processCreateParams(params),
  12004. })
  12005. class ZodSymbol extends ZodType {
  12006. _parse(input) {
  12007. if (this._getType(input) !== ZodParsedType.symbol) {
  12008. const ctx = this._getOrReturnCtx(input)
  12009. addIssueToContext(ctx, {
  12010. code: ZodIssueCode.invalid_type,
  12011. expected: ZodParsedType.symbol,
  12012. received: ctx.parsedType,
  12013. })
  12014. return INVALID
  12015. }
  12016. return OK(input.data)
  12017. }
  12018. }
  12019. ZodSymbol.create = params =>
  12020. new ZodSymbol({
  12021. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  12022. ...processCreateParams(params),
  12023. })
  12024. class ZodUndefined extends ZodType {
  12025. _parse(input) {
  12026. if (this._getType(input) !== ZodParsedType.undefined) {
  12027. const ctx = this._getOrReturnCtx(input)
  12028. addIssueToContext(ctx, {
  12029. code: ZodIssueCode.invalid_type,
  12030. expected: ZodParsedType.undefined,
  12031. received: ctx.parsedType,
  12032. })
  12033. return INVALID
  12034. }
  12035. return OK(input.data)
  12036. }
  12037. }
  12038. ZodUndefined.create = params =>
  12039. new ZodUndefined({
  12040. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  12041. ...processCreateParams(params),
  12042. })
  12043. class ZodNull extends ZodType {
  12044. _parse(input) {
  12045. if (this._getType(input) !== ZodParsedType.null) {
  12046. const ctx = this._getOrReturnCtx(input)
  12047. addIssueToContext(ctx, {
  12048. code: ZodIssueCode.invalid_type,
  12049. expected: ZodParsedType.null,
  12050. received: ctx.parsedType,
  12051. })
  12052. return INVALID
  12053. }
  12054. return OK(input.data)
  12055. }
  12056. }
  12057. ZodNull.create = params =>
  12058. new ZodNull({
  12059. typeName: ZodFirstPartyTypeKind.ZodNull,
  12060. ...processCreateParams(params),
  12061. })
  12062. class ZodAny extends ZodType {
  12063. constructor() {
  12064. super(...arguments)
  12065. this._any = !0
  12066. }
  12067. _parse(input) {
  12068. return OK(input.data)
  12069. }
  12070. }
  12071. ZodAny.create = params =>
  12072. new ZodAny({
  12073. typeName: ZodFirstPartyTypeKind.ZodAny,
  12074. ...processCreateParams(params),
  12075. })
  12076. class ZodUnknown extends ZodType {
  12077. constructor() {
  12078. super(...arguments)
  12079. this._unknown = !0
  12080. }
  12081. _parse(input) {
  12082. return OK(input.data)
  12083. }
  12084. }
  12085. ZodUnknown.create = params =>
  12086. new ZodUnknown({
  12087. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  12088. ...processCreateParams(params),
  12089. })
  12090. class ZodNever extends ZodType {
  12091. _parse(input) {
  12092. const ctx = this._getOrReturnCtx(input)
  12093. addIssueToContext(ctx, {
  12094. code: ZodIssueCode.invalid_type,
  12095. expected: ZodParsedType.never,
  12096. received: ctx.parsedType,
  12097. })
  12098. return INVALID
  12099. }
  12100. }
  12101. ZodNever.create = params =>
  12102. new ZodNever({
  12103. typeName: ZodFirstPartyTypeKind.ZodNever,
  12104. ...processCreateParams(params),
  12105. })
  12106. class ZodVoid extends ZodType {
  12107. _parse(input) {
  12108. if (this._getType(input) !== ZodParsedType.undefined) {
  12109. const ctx = this._getOrReturnCtx(input)
  12110. addIssueToContext(ctx, {
  12111. code: ZodIssueCode.invalid_type,
  12112. expected: ZodParsedType.void,
  12113. received: ctx.parsedType,
  12114. })
  12115. return INVALID
  12116. }
  12117. return OK(input.data)
  12118. }
  12119. }
  12120. ZodVoid.create = params =>
  12121. new ZodVoid({
  12122. typeName: ZodFirstPartyTypeKind.ZodVoid,
  12123. ...processCreateParams(params),
  12124. })
  12125. class ZodArray extends ZodType {
  12126. _parse(input) {
  12127. const { ctx, status } = this._processInputParams(input),
  12128. def = this._def
  12129. if (ctx.parsedType !== ZodParsedType.array) {
  12130. addIssueToContext(ctx, {
  12131. code: ZodIssueCode.invalid_type,
  12132. expected: ZodParsedType.array,
  12133. received: ctx.parsedType,
  12134. })
  12135. return INVALID
  12136. }
  12137. if (null !== def.exactLength) {
  12138. const tooBig = ctx.data.length > def.exactLength.value,
  12139. tooSmall = ctx.data.length < def.exactLength.value
  12140. if (tooBig || tooSmall) {
  12141. addIssueToContext(ctx, {
  12142. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  12143. minimum: tooSmall ? def.exactLength.value : void 0,
  12144. maximum: tooBig ? def.exactLength.value : void 0,
  12145. type: "array",
  12146. inclusive: !0,
  12147. exact: !0,
  12148. message: def.exactLength.message,
  12149. })
  12150. status.dirty()
  12151. }
  12152. }
  12153. if (null !== def.minLength && ctx.data.length < def.minLength.value) {
  12154. addIssueToContext(ctx, {
  12155. code: ZodIssueCode.too_small,
  12156. minimum: def.minLength.value,
  12157. type: "array",
  12158. inclusive: !0,
  12159. exact: !1,
  12160. message: def.minLength.message,
  12161. })
  12162. status.dirty()
  12163. }
  12164. if (null !== def.maxLength && ctx.data.length > def.maxLength.value) {
  12165. addIssueToContext(ctx, {
  12166. code: ZodIssueCode.too_big,
  12167. maximum: def.maxLength.value,
  12168. type: "array",
  12169. inclusive: !0,
  12170. exact: !1,
  12171. message: def.maxLength.message,
  12172. })
  12173. status.dirty()
  12174. }
  12175. if (ctx.common.async)
  12176. return Promise.all(
  12177. [...ctx.data].map((item, i) =>
  12178. def.type._parseAsync(
  12179. new ParseInputLazyPath(ctx, item, ctx.path, i)
  12180. )
  12181. )
  12182. ).then(result => ParseStatus.mergeArray(status, result))
  12183. const result = [...ctx.data].map((item, i) =>
  12184. def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))
  12185. )
  12186. return ParseStatus.mergeArray(status, result)
  12187. }
  12188. get element() {
  12189. return this._def.type
  12190. }
  12191. min(minLength, message) {
  12192. return new ZodArray({
  12193. ...this._def,
  12194. minLength: { value: minLength, message: errorUtil.toString(message) },
  12195. })
  12196. }
  12197. max(maxLength, message) {
  12198. return new ZodArray({
  12199. ...this._def,
  12200. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  12201. })
  12202. }
  12203. length(len, message) {
  12204. return new ZodArray({
  12205. ...this._def,
  12206. exactLength: { value: len, message: errorUtil.toString(message) },
  12207. })
  12208. }
  12209. nonempty(message) {
  12210. return this.min(1, message)
  12211. }
  12212. }
  12213. ZodArray.create = (schema, params) =>
  12214. new ZodArray({
  12215. type: schema,
  12216. minLength: null,
  12217. maxLength: null,
  12218. exactLength: null,
  12219. typeName: ZodFirstPartyTypeKind.ZodArray,
  12220. ...processCreateParams(params),
  12221. })
  12222. function deepPartialify(schema) {
  12223. if (schema instanceof ZodObject) {
  12224. const newShape = {}
  12225. for (const key in schema.shape) {
  12226. const fieldSchema = schema.shape[key]
  12227. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema))
  12228. }
  12229. return new ZodObject({ ...schema._def, shape: () => newShape })
  12230. }
  12231. return schema instanceof ZodArray
  12232. ? new ZodArray({ ...schema._def, type: deepPartialify(schema.element) })
  12233. : schema instanceof ZodOptional
  12234. ? ZodOptional.create(deepPartialify(schema.unwrap()))
  12235. : schema instanceof ZodNullable
  12236. ? ZodNullable.create(deepPartialify(schema.unwrap()))
  12237. : schema instanceof ZodTuple
  12238. ? ZodTuple.create(schema.items.map(item => deepPartialify(item)))
  12239. : schema
  12240. }
  12241. class ZodObject extends ZodType {
  12242. constructor() {
  12243. super(...arguments)
  12244. this._cached = null
  12245. this.nonstrict = this.passthrough
  12246. this.augment = this.extend
  12247. }
  12248. _getCached() {
  12249. if (null !== this._cached) return this._cached
  12250. const shape = this._def.shape(),
  12251. keys = util.objectKeys(shape)
  12252. return (this._cached = { shape, keys })
  12253. }
  12254. _parse(input) {
  12255. if (this._getType(input) !== ZodParsedType.object) {
  12256. const ctx = this._getOrReturnCtx(input)
  12257. addIssueToContext(ctx, {
  12258. code: ZodIssueCode.invalid_type,
  12259. expected: ZodParsedType.object,
  12260. received: ctx.parsedType,
  12261. })
  12262. return INVALID
  12263. }
  12264. const { status, ctx } = this._processInputParams(input),
  12265. { shape, keys: shapeKeys } = this._getCached(),
  12266. extraKeys = []
  12267. if (
  12268. !(
  12269. this._def.catchall instanceof ZodNever &&
  12270. "strip" === this._def.unknownKeys
  12271. )
  12272. )
  12273. for (const key in ctx.data)
  12274. shapeKeys.includes(key) || extraKeys.push(key)
  12275. const pairs = []
  12276. for (const key of shapeKeys) {
  12277. const keyValidator = shape[key],
  12278. value = ctx.data[key]
  12279. pairs.push({
  12280. key: { status: "valid", value: key },
  12281. value: keyValidator._parse(
  12282. new ParseInputLazyPath(ctx, value, ctx.path, key)
  12283. ),
  12284. alwaysSet: key in ctx.data,
  12285. })
  12286. }
  12287. if (this._def.catchall instanceof ZodNever) {
  12288. const unknownKeys = this._def.unknownKeys
  12289. if ("passthrough" === unknownKeys)
  12290. for (const key of extraKeys)
  12291. pairs.push({
  12292. key: { status: "valid", value: key },
  12293. value: { status: "valid", value: ctx.data[key] },
  12294. })
  12295. else if ("strict" === unknownKeys) {
  12296. if (extraKeys.length > 0) {
  12297. addIssueToContext(ctx, {
  12298. code: ZodIssueCode.unrecognized_keys,
  12299. keys: extraKeys,
  12300. })
  12301. status.dirty()
  12302. }
  12303. } else if ("strip" !== unknownKeys)
  12304. throw new Error(
  12305. "Internal ZodObject error: invalid unknownKeys value."
  12306. )
  12307. } else {
  12308. const catchall = this._def.catchall
  12309. for (const key of extraKeys) {
  12310. const value = ctx.data[key]
  12311. pairs.push({
  12312. key: { status: "valid", value: key },
  12313. value: catchall._parse(
  12314. new ParseInputLazyPath(ctx, value, ctx.path, key)
  12315. ),
  12316. alwaysSet: key in ctx.data,
  12317. })
  12318. }
  12319. }
  12320. return ctx.common.async
  12321. ? Promise.resolve()
  12322. .then(async () => {
  12323. const syncPairs = []
  12324. for (const pair of pairs) {
  12325. const key = await pair.key
  12326. syncPairs.push({
  12327. key,
  12328. value: await pair.value,
  12329. alwaysSet: pair.alwaysSet,
  12330. })
  12331. }
  12332. return syncPairs
  12333. })
  12334. .then(syncPairs => ParseStatus.mergeObjectSync(status, syncPairs))
  12335. : ParseStatus.mergeObjectSync(status, pairs)
  12336. }
  12337. get shape() {
  12338. return this._def.shape()
  12339. }
  12340. strict(message) {
  12341. errorUtil.errToObj
  12342. return new ZodObject({
  12343. ...this._def,
  12344. unknownKeys: "strict",
  12345. ...(void 0 !== message
  12346. ? {
  12347. errorMap: (issue, ctx) => {
  12348. var _a, _b, _c, _d
  12349. const defaultError =
  12350. null !==
  12351. (_c =
  12352. null === (_b = (_a = this._def).errorMap) ||
  12353. void 0 === _b
  12354. ? void 0
  12355. : _b.call(_a, issue, ctx).message) && void 0 !== _c
  12356. ? _c
  12357. : ctx.defaultError
  12358. return "unrecognized_keys" === issue.code
  12359. ? {
  12360. message:
  12361. null !== (_d = errorUtil.errToObj(message).message) &&
  12362. void 0 !== _d
  12363. ? _d
  12364. : defaultError,
  12365. }
  12366. : { message: defaultError }
  12367. },
  12368. }
  12369. : {}),
  12370. })
  12371. }
  12372. strip() {
  12373. return new ZodObject({ ...this._def, unknownKeys: "strip" })
  12374. }
  12375. passthrough() {
  12376. return new ZodObject({ ...this._def, unknownKeys: "passthrough" })
  12377. }
  12378. extend(augmentation) {
  12379. return new ZodObject({
  12380. ...this._def,
  12381. shape: () => ({ ...this._def.shape(), ...augmentation }),
  12382. })
  12383. }
  12384. merge(merging) {
  12385. return new ZodObject({
  12386. unknownKeys: merging._def.unknownKeys,
  12387. catchall: merging._def.catchall,
  12388. shape: () => ({ ...this._def.shape(), ...merging._def.shape() }),
  12389. typeName: ZodFirstPartyTypeKind.ZodObject,
  12390. })
  12391. }
  12392. setKey(key, schema) {
  12393. return this.augment({ [key]: schema })
  12394. }
  12395. catchall(index) {
  12396. return new ZodObject({ ...this._def, catchall: index })
  12397. }
  12398. pick(mask) {
  12399. const shape = {}
  12400. util.objectKeys(mask).forEach(key => {
  12401. mask[key] && this.shape[key] && (shape[key] = this.shape[key])
  12402. })
  12403. return new ZodObject({ ...this._def, shape: () => shape })
  12404. }
  12405. omit(mask) {
  12406. const shape = {}
  12407. util.objectKeys(this.shape).forEach(key => {
  12408. mask[key] || (shape[key] = this.shape[key])
  12409. })
  12410. return new ZodObject({ ...this._def, shape: () => shape })
  12411. }
  12412. deepPartial() {
  12413. return deepPartialify(this)
  12414. }
  12415. partial(mask) {
  12416. const newShape = {}
  12417. util.objectKeys(this.shape).forEach(key => {
  12418. const fieldSchema = this.shape[key]
  12419. mask && !mask[key]
  12420. ? (newShape[key] = fieldSchema)
  12421. : (newShape[key] = fieldSchema.optional())
  12422. })
  12423. return new ZodObject({ ...this._def, shape: () => newShape })
  12424. }
  12425. required(mask) {
  12426. const newShape = {}
  12427. util.objectKeys(this.shape).forEach(key => {
  12428. if (mask && !mask[key]) newShape[key] = this.shape[key]
  12429. else {
  12430. let newField = this.shape[key]
  12431. for (; newField instanceof ZodOptional; )
  12432. newField = newField._def.innerType
  12433. newShape[key] = newField
  12434. }
  12435. })
  12436. return new ZodObject({ ...this._def, shape: () => newShape })
  12437. }
  12438. keyof() {
  12439. return createZodEnum(util.objectKeys(this.shape))
  12440. }
  12441. }
  12442. ZodObject.create = (shape, params) =>
  12443. new ZodObject({
  12444. shape: () => shape,
  12445. unknownKeys: "strip",
  12446. catchall: ZodNever.create(),
  12447. typeName: ZodFirstPartyTypeKind.ZodObject,
  12448. ...processCreateParams(params),
  12449. })
  12450. ZodObject.strictCreate = (shape, params) =>
  12451. new ZodObject({
  12452. shape: () => shape,
  12453. unknownKeys: "strict",
  12454. catchall: ZodNever.create(),
  12455. typeName: ZodFirstPartyTypeKind.ZodObject,
  12456. ...processCreateParams(params),
  12457. })
  12458. ZodObject.lazycreate = (shape, params) =>
  12459. new ZodObject({
  12460. shape,
  12461. unknownKeys: "strip",
  12462. catchall: ZodNever.create(),
  12463. typeName: ZodFirstPartyTypeKind.ZodObject,
  12464. ...processCreateParams(params),
  12465. })
  12466. class ZodUnion extends ZodType {
  12467. _parse(input) {
  12468. const { ctx } = this._processInputParams(input),
  12469. options = this._def.options
  12470. if (ctx.common.async)
  12471. return Promise.all(
  12472. options.map(async option => {
  12473. const childCtx = {
  12474. ...ctx,
  12475. common: { ...ctx.common, issues: [] },
  12476. parent: null,
  12477. }
  12478. return {
  12479. result: await option._parseAsync({
  12480. data: ctx.data,
  12481. path: ctx.path,
  12482. parent: childCtx,
  12483. }),
  12484. ctx: childCtx,
  12485. }
  12486. })
  12487. ).then(function (results) {
  12488. for (const result of results)
  12489. if ("valid" === result.result.status) return result.result
  12490. for (const result of results)
  12491. if ("dirty" === result.result.status) {
  12492. ctx.common.issues.push(...result.ctx.common.issues)
  12493. return result.result
  12494. }
  12495. const unionErrors = results.map(
  12496. result => new ZodError(result.ctx.common.issues)
  12497. )
  12498. addIssueToContext(ctx, {
  12499. code: ZodIssueCode.invalid_union,
  12500. unionErrors,
  12501. })
  12502. return INVALID
  12503. })
  12504. {
  12505. let dirty
  12506. const issues = []
  12507. for (const option of options) {
  12508. const childCtx = {
  12509. ...ctx,
  12510. common: { ...ctx.common, issues: [] },
  12511. parent: null,
  12512. },
  12513. result = option._parseSync({
  12514. data: ctx.data,
  12515. path: ctx.path,
  12516. parent: childCtx,
  12517. })
  12518. if ("valid" === result.status) return result
  12519. "dirty" !== result.status ||
  12520. dirty ||
  12521. (dirty = { result, ctx: childCtx })
  12522. childCtx.common.issues.length && issues.push(childCtx.common.issues)
  12523. }
  12524. if (dirty) {
  12525. ctx.common.issues.push(...dirty.ctx.common.issues)
  12526. return dirty.result
  12527. }
  12528. const unionErrors = issues.map(issues => new ZodError(issues))
  12529. addIssueToContext(ctx, {
  12530. code: ZodIssueCode.invalid_union,
  12531. unionErrors,
  12532. })
  12533. return INVALID
  12534. }
  12535. }
  12536. get options() {
  12537. return this._def.options
  12538. }
  12539. }
  12540. ZodUnion.create = (types, params) =>
  12541. new ZodUnion({
  12542. options: types,
  12543. typeName: ZodFirstPartyTypeKind.ZodUnion,
  12544. ...processCreateParams(params),
  12545. })
  12546. const getDiscriminator = type =>
  12547. type instanceof ZodLazy
  12548. ? getDiscriminator(type.schema)
  12549. : type instanceof ZodEffects
  12550. ? getDiscriminator(type.innerType())
  12551. : type instanceof ZodLiteral
  12552. ? [type.value]
  12553. : type instanceof ZodEnum
  12554. ? type.options
  12555. : type instanceof ZodNativeEnum
  12556. ? Object.keys(type.enum)
  12557. : type instanceof ZodDefault
  12558. ? getDiscriminator(type._def.innerType)
  12559. : type instanceof ZodUndefined
  12560. ? [void 0]
  12561. : type instanceof ZodNull
  12562. ? [null]
  12563. : null
  12564. class ZodDiscriminatedUnion extends ZodType {
  12565. _parse(input) {
  12566. const { ctx } = this._processInputParams(input)
  12567. if (ctx.parsedType !== ZodParsedType.object) {
  12568. addIssueToContext(ctx, {
  12569. code: ZodIssueCode.invalid_type,
  12570. expected: ZodParsedType.object,
  12571. received: ctx.parsedType,
  12572. })
  12573. return INVALID
  12574. }
  12575. const discriminator = this.discriminator,
  12576. discriminatorValue = ctx.data[discriminator],
  12577. option = this.optionsMap.get(discriminatorValue)
  12578. if (!option) {
  12579. addIssueToContext(ctx, {
  12580. code: ZodIssueCode.invalid_union_discriminator,
  12581. options: Array.from(this.optionsMap.keys()),
  12582. path: [discriminator],
  12583. })
  12584. return INVALID
  12585. }
  12586. return ctx.common.async
  12587. ? option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  12588. : option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })
  12589. }
  12590. get discriminator() {
  12591. return this._def.discriminator
  12592. }
  12593. get options() {
  12594. return this._def.options
  12595. }
  12596. get optionsMap() {
  12597. return this._def.optionsMap
  12598. }
  12599. static create(discriminator, options, params) {
  12600. const optionsMap = new Map()
  12601. for (const type of options) {
  12602. const discriminatorValues = getDiscriminator(
  12603. type.shape[discriminator]
  12604. )
  12605. if (!discriminatorValues)
  12606. throw new Error(
  12607. `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`
  12608. )
  12609. for (const value of discriminatorValues) {
  12610. if (optionsMap.has(value))
  12611. throw new Error(
  12612. `Discriminator property ${String(
  12613. discriminator
  12614. )} has duplicate value ${String(value)}`
  12615. )
  12616. optionsMap.set(value, type)
  12617. }
  12618. }
  12619. return new ZodDiscriminatedUnion({
  12620. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  12621. discriminator,
  12622. options,
  12623. optionsMap,
  12624. ...processCreateParams(params),
  12625. })
  12626. }
  12627. }
  12628. function mergeValues(a, b) {
  12629. const aType = getParsedType(a),
  12630. bType = getParsedType(b)
  12631. if (a === b) return { valid: !0, data: a }
  12632. if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  12633. const bKeys = util.objectKeys(b),
  12634. sharedKeys = util
  12635. .objectKeys(a)
  12636. .filter(key => -1 !== bKeys.indexOf(key)),
  12637. newObj = { ...a, ...b }
  12638. for (const key of sharedKeys) {
  12639. const sharedValue = mergeValues(a[key], b[key])
  12640. if (!sharedValue.valid) return { valid: !1 }
  12641. newObj[key] = sharedValue.data
  12642. }
  12643. return { valid: !0, data: newObj }
  12644. }
  12645. if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  12646. if (a.length !== b.length) return { valid: !1 }
  12647. const newArray = []
  12648. for (let index = 0; index < a.length; index++) {
  12649. const sharedValue = mergeValues(a[index], b[index])
  12650. if (!sharedValue.valid) return { valid: !1 }
  12651. newArray.push(sharedValue.data)
  12652. }
  12653. return { valid: !0, data: newArray }
  12654. }
  12655. return aType === ZodParsedType.date &&
  12656. bType === ZodParsedType.date &&
  12657. +a == +b
  12658. ? { valid: !0, data: a }
  12659. : { valid: !1 }
  12660. }
  12661. class ZodIntersection extends ZodType {
  12662. _parse(input) {
  12663. const { status, ctx } = this._processInputParams(input),
  12664. handleParsed = (parsedLeft, parsedRight) => {
  12665. if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID
  12666. const merged = mergeValues(parsedLeft.value, parsedRight.value)
  12667. if (!merged.valid) {
  12668. addIssueToContext(ctx, {
  12669. code: ZodIssueCode.invalid_intersection_types,
  12670. })
  12671. return INVALID
  12672. }
  12673. ;(isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty()
  12674. return { status: status.value, value: merged.data }
  12675. }
  12676. return ctx.common.async
  12677. ? Promise.all([
  12678. this._def.left._parseAsync({
  12679. data: ctx.data,
  12680. path: ctx.path,
  12681. parent: ctx,
  12682. }),
  12683. this._def.right._parseAsync({
  12684. data: ctx.data,
  12685. path: ctx.path,
  12686. parent: ctx,
  12687. }),
  12688. ]).then(([left, right]) => handleParsed(left, right))
  12689. : handleParsed(
  12690. this._def.left._parseSync({
  12691. data: ctx.data,
  12692. path: ctx.path,
  12693. parent: ctx,
  12694. }),
  12695. this._def.right._parseSync({
  12696. data: ctx.data,
  12697. path: ctx.path,
  12698. parent: ctx,
  12699. })
  12700. )
  12701. }
  12702. }
  12703. ZodIntersection.create = (left, right, params) =>
  12704. new ZodIntersection({
  12705. left,
  12706. right,
  12707. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  12708. ...processCreateParams(params),
  12709. })
  12710. class ZodTuple extends ZodType {
  12711. _parse(input) {
  12712. const { status, ctx } = this._processInputParams(input)
  12713. if (ctx.parsedType !== ZodParsedType.array) {
  12714. addIssueToContext(ctx, {
  12715. code: ZodIssueCode.invalid_type,
  12716. expected: ZodParsedType.array,
  12717. received: ctx.parsedType,
  12718. })
  12719. return INVALID
  12720. }
  12721. if (ctx.data.length < this._def.items.length) {
  12722. addIssueToContext(ctx, {
  12723. code: ZodIssueCode.too_small,
  12724. minimum: this._def.items.length,
  12725. inclusive: !0,
  12726. exact: !1,
  12727. type: "array",
  12728. })
  12729. return INVALID
  12730. }
  12731. if (!this._def.rest && ctx.data.length > this._def.items.length) {
  12732. addIssueToContext(ctx, {
  12733. code: ZodIssueCode.too_big,
  12734. maximum: this._def.items.length,
  12735. inclusive: !0,
  12736. exact: !1,
  12737. type: "array",
  12738. })
  12739. status.dirty()
  12740. }
  12741. const items = [...ctx.data]
  12742. .map((item, itemIndex) => {
  12743. const schema = this._def.items[itemIndex] || this._def.rest
  12744. return schema
  12745. ? schema._parse(
  12746. new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)
  12747. )
  12748. : null
  12749. })
  12750. .filter(x => !!x)
  12751. return ctx.common.async
  12752. ? Promise.all(items).then(results =>
  12753. ParseStatus.mergeArray(status, results)
  12754. )
  12755. : ParseStatus.mergeArray(status, items)
  12756. }
  12757. get items() {
  12758. return this._def.items
  12759. }
  12760. rest(rest) {
  12761. return new ZodTuple({ ...this._def, rest })
  12762. }
  12763. }
  12764. ZodTuple.create = (schemas, params) => {
  12765. if (!Array.isArray(schemas))
  12766. throw new Error("You must pass an array of schemas to z.tuple([ ... ])")
  12767. return new ZodTuple({
  12768. items: schemas,
  12769. typeName: ZodFirstPartyTypeKind.ZodTuple,
  12770. rest: null,
  12771. ...processCreateParams(params),
  12772. })
  12773. }
  12774. class ZodRecord extends ZodType {
  12775. get keySchema() {
  12776. return this._def.keyType
  12777. }
  12778. get valueSchema() {
  12779. return this._def.valueType
  12780. }
  12781. _parse(input) {
  12782. const { status, ctx } = this._processInputParams(input)
  12783. if (ctx.parsedType !== ZodParsedType.object) {
  12784. addIssueToContext(ctx, {
  12785. code: ZodIssueCode.invalid_type,
  12786. expected: ZodParsedType.object,
  12787. received: ctx.parsedType,
  12788. })
  12789. return INVALID
  12790. }
  12791. const pairs = [],
  12792. keyType = this._def.keyType,
  12793. valueType = this._def.valueType
  12794. for (const key in ctx.data)
  12795. pairs.push({
  12796. key: keyType._parse(
  12797. new ParseInputLazyPath(ctx, key, ctx.path, key)
  12798. ),
  12799. value: valueType._parse(
  12800. new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
  12801. ),
  12802. })
  12803. return ctx.common.async
  12804. ? ParseStatus.mergeObjectAsync(status, pairs)
  12805. : ParseStatus.mergeObjectSync(status, pairs)
  12806. }
  12807. get element() {
  12808. return this._def.valueType
  12809. }
  12810. static create(first, second, third) {
  12811. return new ZodRecord(
  12812. second instanceof ZodType
  12813. ? {
  12814. keyType: first,
  12815. valueType: second,
  12816. typeName: ZodFirstPartyTypeKind.ZodRecord,
  12817. ...processCreateParams(third),
  12818. }
  12819. : {
  12820. keyType: ZodString.create(),
  12821. valueType: first,
  12822. typeName: ZodFirstPartyTypeKind.ZodRecord,
  12823. ...processCreateParams(second),
  12824. }
  12825. )
  12826. }
  12827. }
  12828. class ZodMap extends ZodType {
  12829. _parse(input) {
  12830. const { status, ctx } = this._processInputParams(input)
  12831. if (ctx.parsedType !== ZodParsedType.map) {
  12832. addIssueToContext(ctx, {
  12833. code: ZodIssueCode.invalid_type,
  12834. expected: ZodParsedType.map,
  12835. received: ctx.parsedType,
  12836. })
  12837. return INVALID
  12838. }
  12839. const keyType = this._def.keyType,
  12840. valueType = this._def.valueType,
  12841. pairs = [...ctx.data.entries()].map(([key, value], index) => ({
  12842. key: keyType._parse(
  12843. new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])
  12844. ),
  12845. value: valueType._parse(
  12846. new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])
  12847. ),
  12848. }))
  12849. if (ctx.common.async) {
  12850. const finalMap = new Map()
  12851. return Promise.resolve().then(async () => {
  12852. for (const pair of pairs) {
  12853. const key = await pair.key,
  12854. value = await pair.value
  12855. if ("aborted" === key.status || "aborted" === value.status)
  12856. return INVALID
  12857. ;("dirty" !== key.status && "dirty" !== value.status) ||
  12858. status.dirty()
  12859. finalMap.set(key.value, value.value)
  12860. }
  12861. return { status: status.value, value: finalMap }
  12862. })
  12863. }
  12864. {
  12865. const finalMap = new Map()
  12866. for (const pair of pairs) {
  12867. const key = pair.key,
  12868. value = pair.value
  12869. if ("aborted" === key.status || "aborted" === value.status)
  12870. return INVALID
  12871. ;("dirty" !== key.status && "dirty" !== value.status) ||
  12872. status.dirty()
  12873. finalMap.set(key.value, value.value)
  12874. }
  12875. return { status: status.value, value: finalMap }
  12876. }
  12877. }
  12878. }
  12879. ZodMap.create = (keyType, valueType, params) =>
  12880. new ZodMap({
  12881. valueType,
  12882. keyType,
  12883. typeName: ZodFirstPartyTypeKind.ZodMap,
  12884. ...processCreateParams(params),
  12885. })
  12886. class ZodSet extends ZodType {
  12887. _parse(input) {
  12888. const { status, ctx } = this._processInputParams(input)
  12889. if (ctx.parsedType !== ZodParsedType.set) {
  12890. addIssueToContext(ctx, {
  12891. code: ZodIssueCode.invalid_type,
  12892. expected: ZodParsedType.set,
  12893. received: ctx.parsedType,
  12894. })
  12895. return INVALID
  12896. }
  12897. const def = this._def
  12898. if (null !== def.minSize && ctx.data.size < def.minSize.value) {
  12899. addIssueToContext(ctx, {
  12900. code: ZodIssueCode.too_small,
  12901. minimum: def.minSize.value,
  12902. type: "set",
  12903. inclusive: !0,
  12904. exact: !1,
  12905. message: def.minSize.message,
  12906. })
  12907. status.dirty()
  12908. }
  12909. if (null !== def.maxSize && ctx.data.size > def.maxSize.value) {
  12910. addIssueToContext(ctx, {
  12911. code: ZodIssueCode.too_big,
  12912. maximum: def.maxSize.value,
  12913. type: "set",
  12914. inclusive: !0,
  12915. exact: !1,
  12916. message: def.maxSize.message,
  12917. })
  12918. status.dirty()
  12919. }
  12920. const valueType = this._def.valueType
  12921. function finalizeSet(elements) {
  12922. const parsedSet = new Set()
  12923. for (const element of elements) {
  12924. if ("aborted" === element.status) return INVALID
  12925. "dirty" === element.status && status.dirty()
  12926. parsedSet.add(element.value)
  12927. }
  12928. return { status: status.value, value: parsedSet }
  12929. }
  12930. const elements = [...ctx.data.values()].map((item, i) =>
  12931. valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))
  12932. )
  12933. return ctx.common.async
  12934. ? Promise.all(elements).then(elements => finalizeSet(elements))
  12935. : finalizeSet(elements)
  12936. }
  12937. min(minSize, message) {
  12938. return new ZodSet({
  12939. ...this._def,
  12940. minSize: { value: minSize, message: errorUtil.toString(message) },
  12941. })
  12942. }
  12943. max(maxSize, message) {
  12944. return new ZodSet({
  12945. ...this._def,
  12946. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  12947. })
  12948. }
  12949. size(size, message) {
  12950. return this.min(size, message).max(size, message)
  12951. }
  12952. nonempty(message) {
  12953. return this.min(1, message)
  12954. }
  12955. }
  12956. ZodSet.create = (valueType, params) =>
  12957. new ZodSet({
  12958. valueType,
  12959. minSize: null,
  12960. maxSize: null,
  12961. typeName: ZodFirstPartyTypeKind.ZodSet,
  12962. ...processCreateParams(params),
  12963. })
  12964. class ZodFunction extends ZodType {
  12965. constructor() {
  12966. super(...arguments)
  12967. this.validate = this.implement
  12968. }
  12969. _parse(input) {
  12970. const { ctx } = this._processInputParams(input)
  12971. if (ctx.parsedType !== ZodParsedType.function) {
  12972. addIssueToContext(ctx, {
  12973. code: ZodIssueCode.invalid_type,
  12974. expected: ZodParsedType.function,
  12975. received: ctx.parsedType,
  12976. })
  12977. return INVALID
  12978. }
  12979. function makeArgsIssue(args, error) {
  12980. return makeIssue({
  12981. data: args,
  12982. path: ctx.path,
  12983. errorMaps: [
  12984. ctx.common.contextualErrorMap,
  12985. ctx.schemaErrorMap,
  12986. getErrorMap(),
  12987. errorMap,
  12988. ].filter(x => !!x),
  12989. issueData: {
  12990. code: ZodIssueCode.invalid_arguments,
  12991. argumentsError: error,
  12992. },
  12993. })
  12994. }
  12995. function makeReturnsIssue(returns, error) {
  12996. return makeIssue({
  12997. data: returns,
  12998. path: ctx.path,
  12999. errorMaps: [
  13000. ctx.common.contextualErrorMap,
  13001. ctx.schemaErrorMap,
  13002. getErrorMap(),
  13003. errorMap,
  13004. ].filter(x => !!x),
  13005. issueData: {
  13006. code: ZodIssueCode.invalid_return_type,
  13007. returnTypeError: error,
  13008. },
  13009. })
  13010. }
  13011. const params = { errorMap: ctx.common.contextualErrorMap },
  13012. fn = ctx.data
  13013. return this._def.returns instanceof ZodPromise
  13014. ? OK(async (...args) => {
  13015. const error = new ZodError([]),
  13016. parsedArgs = await this._def.args
  13017. .parseAsync(args, params)
  13018. .catch(e => {
  13019. error.addIssue(makeArgsIssue(args, e))
  13020. throw error
  13021. }),
  13022. result = await fn(...parsedArgs)
  13023. return await this._def.returns._def.type
  13024. .parseAsync(result, params)
  13025. .catch(e => {
  13026. error.addIssue(makeReturnsIssue(result, e))
  13027. throw error
  13028. })
  13029. })
  13030. : OK((...args) => {
  13031. const parsedArgs = this._def.args.safeParse(args, params)
  13032. if (!parsedArgs.success)
  13033. throw new ZodError([makeArgsIssue(args, parsedArgs.error)])
  13034. const result = fn(...parsedArgs.data),
  13035. parsedReturns = this._def.returns.safeParse(result, params)
  13036. if (!parsedReturns.success)
  13037. throw new ZodError([
  13038. makeReturnsIssue(result, parsedReturns.error),
  13039. ])
  13040. return parsedReturns.data
  13041. })
  13042. }
  13043. parameters() {
  13044. return this._def.args
  13045. }
  13046. returnType() {
  13047. return this._def.returns
  13048. }
  13049. args(...items) {
  13050. return new ZodFunction({
  13051. ...this._def,
  13052. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  13053. })
  13054. }
  13055. returns(returnType) {
  13056. return new ZodFunction({ ...this._def, returns: returnType })
  13057. }
  13058. implement(func) {
  13059. return this.parse(func)
  13060. }
  13061. strictImplement(func) {
  13062. return this.parse(func)
  13063. }
  13064. static create(args, returns, params) {
  13065. return new ZodFunction({
  13066. args: args || ZodTuple.create([]).rest(ZodUnknown.create()),
  13067. returns: returns || ZodUnknown.create(),
  13068. typeName: ZodFirstPartyTypeKind.ZodFunction,
  13069. ...processCreateParams(params),
  13070. })
  13071. }
  13072. }
  13073. class ZodLazy extends ZodType {
  13074. get schema() {
  13075. return this._def.getter()
  13076. }
  13077. _parse(input) {
  13078. const { ctx } = this._processInputParams(input)
  13079. return this._def
  13080. .getter()
  13081. ._parse({ data: ctx.data, path: ctx.path, parent: ctx })
  13082. }
  13083. }
  13084. ZodLazy.create = (getter, params) =>
  13085. new ZodLazy({
  13086. getter,
  13087. typeName: ZodFirstPartyTypeKind.ZodLazy,
  13088. ...processCreateParams(params),
  13089. })
  13090. class ZodLiteral extends ZodType {
  13091. _parse(input) {
  13092. if (input.data !== this._def.value) {
  13093. const ctx = this._getOrReturnCtx(input)
  13094. addIssueToContext(ctx, {
  13095. received: ctx.data,
  13096. code: ZodIssueCode.invalid_literal,
  13097. expected: this._def.value,
  13098. })
  13099. return INVALID
  13100. }
  13101. return { status: "valid", value: input.data }
  13102. }
  13103. get value() {
  13104. return this._def.value
  13105. }
  13106. }
  13107. ZodLiteral.create = (value, params) =>
  13108. new ZodLiteral({
  13109. value,
  13110. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  13111. ...processCreateParams(params),
  13112. })
  13113. function createZodEnum(values, params) {
  13114. return new ZodEnum({
  13115. values,
  13116. typeName: ZodFirstPartyTypeKind.ZodEnum,
  13117. ...processCreateParams(params),
  13118. })
  13119. }
  13120. class ZodEnum extends ZodType {
  13121. _parse(input) {
  13122. if ("string" != typeof input.data) {
  13123. const ctx = this._getOrReturnCtx(input),
  13124. expectedValues = this._def.values
  13125. addIssueToContext(ctx, {
  13126. expected: util.joinValues(expectedValues),
  13127. received: ctx.parsedType,
  13128. code: ZodIssueCode.invalid_type,
  13129. })
  13130. return INVALID
  13131. }
  13132. if (-1 === this._def.values.indexOf(input.data)) {
  13133. const ctx = this._getOrReturnCtx(input),
  13134. expectedValues = this._def.values
  13135. addIssueToContext(ctx, {
  13136. received: ctx.data,
  13137. code: ZodIssueCode.invalid_enum_value,
  13138. options: expectedValues,
  13139. })
  13140. return INVALID
  13141. }
  13142. return OK(input.data)
  13143. }
  13144. get options() {
  13145. return this._def.values
  13146. }
  13147. get enum() {
  13148. const enumValues = {}
  13149. for (const val of this._def.values) enumValues[val] = val
  13150. return enumValues
  13151. }
  13152. get Values() {
  13153. const enumValues = {}
  13154. for (const val of this._def.values) enumValues[val] = val
  13155. return enumValues
  13156. }
  13157. get Enum() {
  13158. const enumValues = {}
  13159. for (const val of this._def.values) enumValues[val] = val
  13160. return enumValues
  13161. }
  13162. extract(values) {
  13163. return ZodEnum.create(values)
  13164. }
  13165. exclude(values) {
  13166. return ZodEnum.create(this.options.filter(opt => !values.includes(opt)))
  13167. }
  13168. }
  13169. ZodEnum.create = createZodEnum
  13170. class ZodNativeEnum extends ZodType {
  13171. _parse(input) {
  13172. const nativeEnumValues = util.getValidEnumValues(this._def.values),
  13173. ctx = this._getOrReturnCtx(input)
  13174. if (
  13175. ctx.parsedType !== ZodParsedType.string &&
  13176. ctx.parsedType !== ZodParsedType.number
  13177. ) {
  13178. const expectedValues = util.objectValues(nativeEnumValues)
  13179. addIssueToContext(ctx, {
  13180. expected: util.joinValues(expectedValues),
  13181. received: ctx.parsedType,
  13182. code: ZodIssueCode.invalid_type,
  13183. })
  13184. return INVALID
  13185. }
  13186. if (-1 === nativeEnumValues.indexOf(input.data)) {
  13187. const expectedValues = util.objectValues(nativeEnumValues)
  13188. addIssueToContext(ctx, {
  13189. received: ctx.data,
  13190. code: ZodIssueCode.invalid_enum_value,
  13191. options: expectedValues,
  13192. })
  13193. return INVALID
  13194. }
  13195. return OK(input.data)
  13196. }
  13197. get enum() {
  13198. return this._def.values
  13199. }
  13200. }
  13201. ZodNativeEnum.create = (values, params) =>
  13202. new ZodNativeEnum({
  13203. values,
  13204. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  13205. ...processCreateParams(params),
  13206. })
  13207. class ZodPromise extends ZodType {
  13208. unwrap() {
  13209. return this._def.type
  13210. }
  13211. _parse(input) {
  13212. const { ctx } = this._processInputParams(input)
  13213. if (
  13214. ctx.parsedType !== ZodParsedType.promise &&
  13215. !1 === ctx.common.async
  13216. ) {
  13217. addIssueToContext(ctx, {
  13218. code: ZodIssueCode.invalid_type,
  13219. expected: ZodParsedType.promise,
  13220. received: ctx.parsedType,
  13221. })
  13222. return INVALID
  13223. }
  13224. const promisified =
  13225. ctx.parsedType === ZodParsedType.promise
  13226. ? ctx.data
  13227. : Promise.resolve(ctx.data)
  13228. return OK(
  13229. promisified.then(data =>
  13230. this._def.type.parseAsync(data, {
  13231. path: ctx.path,
  13232. errorMap: ctx.common.contextualErrorMap,
  13233. })
  13234. )
  13235. )
  13236. }
  13237. }
  13238. ZodPromise.create = (schema, params) =>
  13239. new ZodPromise({
  13240. type: schema,
  13241. typeName: ZodFirstPartyTypeKind.ZodPromise,
  13242. ...processCreateParams(params),
  13243. })
  13244. class ZodEffects extends ZodType {
  13245. innerType() {
  13246. return this._def.schema
  13247. }
  13248. sourceType() {
  13249. return this._def.schema._def.typeName ===
  13250. ZodFirstPartyTypeKind.ZodEffects
  13251. ? this._def.schema.sourceType()
  13252. : this._def.schema
  13253. }
  13254. _parse(input) {
  13255. const { status, ctx } = this._processInputParams(input),
  13256. effect = this._def.effect || null
  13257. if ("preprocess" === effect.type) {
  13258. const processed = effect.transform(ctx.data)
  13259. return ctx.common.async
  13260. ? Promise.resolve(processed).then(processed =>
  13261. this._def.schema._parseAsync({
  13262. data: processed,
  13263. path: ctx.path,
  13264. parent: ctx,
  13265. })
  13266. )
  13267. : this._def.schema._parseSync({
  13268. data: processed,
  13269. path: ctx.path,
  13270. parent: ctx,
  13271. })
  13272. }
  13273. const checkCtx = {
  13274. addIssue: arg => {
  13275. addIssueToContext(ctx, arg)
  13276. arg.fatal ? status.abort() : status.dirty()
  13277. },
  13278. get path() {
  13279. return ctx.path
  13280. },
  13281. }
  13282. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx)
  13283. if ("refinement" === effect.type) {
  13284. const executeRefinement = acc => {
  13285. const result = effect.refinement(acc, checkCtx)
  13286. if (ctx.common.async) return Promise.resolve(result)
  13287. if (result instanceof Promise)
  13288. throw new Error(
  13289. "Async refinement encountered during synchronous parse operation. Use .parseAsync instead."
  13290. )
  13291. return acc
  13292. }
  13293. if (!1 === ctx.common.async) {
  13294. const inner = this._def.schema._parseSync({
  13295. data: ctx.data,
  13296. path: ctx.path,
  13297. parent: ctx,
  13298. })
  13299. if ("aborted" === inner.status) return INVALID
  13300. "dirty" === inner.status && status.dirty()
  13301. executeRefinement(inner.value)
  13302. return { status: status.value, value: inner.value }
  13303. }
  13304. return this._def.schema
  13305. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  13306. .then(inner => {
  13307. if ("aborted" === inner.status) return INVALID
  13308. "dirty" === inner.status && status.dirty()
  13309. return executeRefinement(inner.value).then(() => ({
  13310. status: status.value,
  13311. value: inner.value,
  13312. }))
  13313. })
  13314. }
  13315. if ("transform" === effect.type) {
  13316. if (!1 === ctx.common.async) {
  13317. const base = this._def.schema._parseSync({
  13318. data: ctx.data,
  13319. path: ctx.path,
  13320. parent: ctx,
  13321. })
  13322. if (!isValid(base)) return base
  13323. const result = effect.transform(base.value, checkCtx)
  13324. if (result instanceof Promise)
  13325. throw new Error(
  13326. "Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."
  13327. )
  13328. return { status: status.value, value: result }
  13329. }
  13330. return this._def.schema
  13331. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  13332. .then(base =>
  13333. isValid(base)
  13334. ? Promise.resolve(effect.transform(base.value, checkCtx)).then(
  13335. result => ({ status: status.value, value: result })
  13336. )
  13337. : base
  13338. )
  13339. }
  13340. util.assertNever(effect)
  13341. }
  13342. }
  13343. ZodEffects.create = (schema, effect, params) =>
  13344. new ZodEffects({
  13345. schema,
  13346. typeName: ZodFirstPartyTypeKind.ZodEffects,
  13347. effect,
  13348. ...processCreateParams(params),
  13349. })
  13350. ZodEffects.createWithPreprocess = (preprocess, schema, params) =>
  13351. new ZodEffects({
  13352. schema,
  13353. effect: { type: "preprocess", transform: preprocess },
  13354. typeName: ZodFirstPartyTypeKind.ZodEffects,
  13355. ...processCreateParams(params),
  13356. })
  13357. class ZodOptional extends ZodType {
  13358. _parse(input) {
  13359. return this._getType(input) === ZodParsedType.undefined
  13360. ? OK(void 0)
  13361. : this._def.innerType._parse(input)
  13362. }
  13363. unwrap() {
  13364. return this._def.innerType
  13365. }
  13366. }
  13367. ZodOptional.create = (type, params) =>
  13368. new ZodOptional({
  13369. innerType: type,
  13370. typeName: ZodFirstPartyTypeKind.ZodOptional,
  13371. ...processCreateParams(params),
  13372. })
  13373. class ZodNullable extends ZodType {
  13374. _parse(input) {
  13375. return this._getType(input) === ZodParsedType.null
  13376. ? OK(null)
  13377. : this._def.innerType._parse(input)
  13378. }
  13379. unwrap() {
  13380. return this._def.innerType
  13381. }
  13382. }
  13383. ZodNullable.create = (type, params) =>
  13384. new ZodNullable({
  13385. innerType: type,
  13386. typeName: ZodFirstPartyTypeKind.ZodNullable,
  13387. ...processCreateParams(params),
  13388. })
  13389. class ZodDefault extends ZodType {
  13390. _parse(input) {
  13391. const { ctx } = this._processInputParams(input)
  13392. let data = ctx.data
  13393. ctx.parsedType === ZodParsedType.undefined &&
  13394. (data = this._def.defaultValue())
  13395. return this._def.innerType._parse({ data, path: ctx.path, parent: ctx })
  13396. }
  13397. removeDefault() {
  13398. return this._def.innerType
  13399. }
  13400. }
  13401. ZodDefault.create = (type, params) =>
  13402. new ZodDefault({
  13403. innerType: type,
  13404. typeName: ZodFirstPartyTypeKind.ZodDefault,
  13405. defaultValue:
  13406. "function" == typeof params.default
  13407. ? params.default
  13408. : () => params.default,
  13409. ...processCreateParams(params),
  13410. })
  13411. class ZodCatch extends ZodType {
  13412. _parse(input) {
  13413. const { ctx } = this._processInputParams(input),
  13414. newCtx = { ...ctx, common: { ...ctx.common, issues: [] } },
  13415. result = this._def.innerType._parse({
  13416. data: newCtx.data,
  13417. path: newCtx.path,
  13418. parent: { ...newCtx },
  13419. })
  13420. return isAsync(result)
  13421. ? result.then(result => ({
  13422. status: "valid",
  13423. value:
  13424. "valid" === result.status
  13425. ? result.value
  13426. : this._def.catchValue({
  13427. get error() {
  13428. return new ZodError(newCtx.common.issues)
  13429. },
  13430. input: newCtx.data,
  13431. }),
  13432. }))
  13433. : {
  13434. status: "valid",
  13435. value:
  13436. "valid" === result.status
  13437. ? result.value
  13438. : this._def.catchValue({
  13439. get error() {
  13440. return new ZodError(newCtx.common.issues)
  13441. },
  13442. input: newCtx.data,
  13443. }),
  13444. }
  13445. }
  13446. removeCatch() {
  13447. return this._def.innerType
  13448. }
  13449. }
  13450. ZodCatch.create = (type, params) =>
  13451. new ZodCatch({
  13452. innerType: type,
  13453. typeName: ZodFirstPartyTypeKind.ZodCatch,
  13454. catchValue:
  13455. "function" == typeof params.catch ? params.catch : () => params.catch,
  13456. ...processCreateParams(params),
  13457. })
  13458. class ZodNaN extends ZodType {
  13459. _parse(input) {
  13460. if (this._getType(input) !== ZodParsedType.nan) {
  13461. const ctx = this._getOrReturnCtx(input)
  13462. addIssueToContext(ctx, {
  13463. code: ZodIssueCode.invalid_type,
  13464. expected: ZodParsedType.nan,
  13465. received: ctx.parsedType,
  13466. })
  13467. return INVALID
  13468. }
  13469. return { status: "valid", value: input.data }
  13470. }
  13471. }
  13472. ZodNaN.create = params =>
  13473. new ZodNaN({
  13474. typeName: ZodFirstPartyTypeKind.ZodNaN,
  13475. ...processCreateParams(params),
  13476. })
  13477. const BRAND = Symbol("zod_brand")
  13478. class ZodBranded extends ZodType {
  13479. _parse(input) {
  13480. const { ctx } = this._processInputParams(input),
  13481. data = ctx.data
  13482. return this._def.type._parse({ data, path: ctx.path, parent: ctx })
  13483. }
  13484. unwrap() {
  13485. return this._def.type
  13486. }
  13487. }
  13488. class ZodPipeline extends ZodType {
  13489. _parse(input) {
  13490. const { status, ctx } = this._processInputParams(input)
  13491. if (ctx.common.async)
  13492. return (async () => {
  13493. const inResult = await this._def.in._parseAsync({
  13494. data: ctx.data,
  13495. path: ctx.path,
  13496. parent: ctx,
  13497. })
  13498. if ("aborted" === inResult.status) return INVALID
  13499. if ("dirty" === inResult.status) {
  13500. status.dirty()
  13501. return DIRTY(inResult.value)
  13502. }
  13503. return this._def.out._parseAsync({
  13504. data: inResult.value,
  13505. path: ctx.path,
  13506. parent: ctx,
  13507. })
  13508. })()
  13509. {
  13510. const inResult = this._def.in._parseSync({
  13511. data: ctx.data,
  13512. path: ctx.path,
  13513. parent: ctx,
  13514. })
  13515. if ("aborted" === inResult.status) return INVALID
  13516. if ("dirty" === inResult.status) {
  13517. status.dirty()
  13518. return { status: "dirty", value: inResult.value }
  13519. }
  13520. return this._def.out._parseSync({
  13521. data: inResult.value,
  13522. path: ctx.path,
  13523. parent: ctx,
  13524. })
  13525. }
  13526. }
  13527. static create(a, b) {
  13528. return new ZodPipeline({
  13529. in: a,
  13530. out: b,
  13531. typeName: ZodFirstPartyTypeKind.ZodPipeline,
  13532. })
  13533. }
  13534. }
  13535. const custom = (check, params = {}, fatal) =>
  13536. check
  13537. ? ZodAny.create().superRefine((data, ctx) => {
  13538. var _a, _b
  13539. if (!check(data)) {
  13540. const p =
  13541. "function" == typeof params
  13542. ? params(data)
  13543. : "string" == typeof params
  13544. ? { message: params }
  13545. : params,
  13546. _fatal =
  13547. null ===
  13548. (_b =
  13549. null !== (_a = p.fatal) && void 0 !== _a
  13550. ? _a
  13551. : fatal) ||
  13552. void 0 === _b ||
  13553. _b,
  13554. p2 = "string" == typeof p ? { message: p } : p
  13555. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal })
  13556. }
  13557. })
  13558. : ZodAny.create(),
  13559. late = { object: ZodObject.lazycreate }
  13560. var ZodFirstPartyTypeKind
  13561. !(function (ZodFirstPartyTypeKind) {
  13562. ZodFirstPartyTypeKind.ZodString = "ZodString"
  13563. ZodFirstPartyTypeKind.ZodNumber = "ZodNumber"
  13564. ZodFirstPartyTypeKind.ZodNaN = "ZodNaN"
  13565. ZodFirstPartyTypeKind.ZodBigInt = "ZodBigInt"
  13566. ZodFirstPartyTypeKind.ZodBoolean = "ZodBoolean"
  13567. ZodFirstPartyTypeKind.ZodDate = "ZodDate"
  13568. ZodFirstPartyTypeKind.ZodSymbol = "ZodSymbol"
  13569. ZodFirstPartyTypeKind.ZodUndefined = "ZodUndefined"
  13570. ZodFirstPartyTypeKind.ZodNull = "ZodNull"
  13571. ZodFirstPartyTypeKind.ZodAny = "ZodAny"
  13572. ZodFirstPartyTypeKind.ZodUnknown = "ZodUnknown"
  13573. ZodFirstPartyTypeKind.ZodNever = "ZodNever"
  13574. ZodFirstPartyTypeKind.ZodVoid = "ZodVoid"
  13575. ZodFirstPartyTypeKind.ZodArray = "ZodArray"
  13576. ZodFirstPartyTypeKind.ZodObject = "ZodObject"
  13577. ZodFirstPartyTypeKind.ZodUnion = "ZodUnion"
  13578. ZodFirstPartyTypeKind.ZodDiscriminatedUnion = "ZodDiscriminatedUnion"
  13579. ZodFirstPartyTypeKind.ZodIntersection = "ZodIntersection"
  13580. ZodFirstPartyTypeKind.ZodTuple = "ZodTuple"
  13581. ZodFirstPartyTypeKind.ZodRecord = "ZodRecord"
  13582. ZodFirstPartyTypeKind.ZodMap = "ZodMap"
  13583. ZodFirstPartyTypeKind.ZodSet = "ZodSet"
  13584. ZodFirstPartyTypeKind.ZodFunction = "ZodFunction"
  13585. ZodFirstPartyTypeKind.ZodLazy = "ZodLazy"
  13586. ZodFirstPartyTypeKind.ZodLiteral = "ZodLiteral"
  13587. ZodFirstPartyTypeKind.ZodEnum = "ZodEnum"
  13588. ZodFirstPartyTypeKind.ZodEffects = "ZodEffects"
  13589. ZodFirstPartyTypeKind.ZodNativeEnum = "ZodNativeEnum"
  13590. ZodFirstPartyTypeKind.ZodOptional = "ZodOptional"
  13591. ZodFirstPartyTypeKind.ZodNullable = "ZodNullable"
  13592. ZodFirstPartyTypeKind.ZodDefault = "ZodDefault"
  13593. ZodFirstPartyTypeKind.ZodCatch = "ZodCatch"
  13594. ZodFirstPartyTypeKind.ZodPromise = "ZodPromise"
  13595. ZodFirstPartyTypeKind.ZodBranded = "ZodBranded"
  13596. ZodFirstPartyTypeKind.ZodPipeline = "ZodPipeline"
  13597. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}))
  13598. const stringType = ZodString.create,
  13599. numberType = ZodNumber.create,
  13600. nanType = ZodNaN.create,
  13601. bigIntType = ZodBigInt.create,
  13602. booleanType = ZodBoolean.create,
  13603. dateType = ZodDate.create,
  13604. symbolType = ZodSymbol.create,
  13605. undefinedType = ZodUndefined.create,
  13606. nullType = ZodNull.create,
  13607. anyType = ZodAny.create,
  13608. unknownType = ZodUnknown.create,
  13609. neverType = ZodNever.create,
  13610. voidType = ZodVoid.create,
  13611. arrayType = ZodArray.create,
  13612. objectType = ZodObject.create,
  13613. strictObjectType = ZodObject.strictCreate,
  13614. unionType = ZodUnion.create,
  13615. discriminatedUnionType = ZodDiscriminatedUnion.create,
  13616. intersectionType = ZodIntersection.create,
  13617. tupleType = ZodTuple.create,
  13618. recordType = ZodRecord.create,
  13619. lib_mapType = ZodMap.create,
  13620. setType = ZodSet.create,
  13621. functionType = ZodFunction.create,
  13622. lazyType = ZodLazy.create,
  13623. literalType = ZodLiteral.create,
  13624. enumType = ZodEnum.create,
  13625. nativeEnumType = ZodNativeEnum.create,
  13626. promiseType = ZodPromise.create,
  13627. effectsType = ZodEffects.create,
  13628. optionalType = ZodOptional.create,
  13629. nullableType = ZodNullable.create,
  13630. preprocessType = ZodEffects.createWithPreprocess,
  13631. pipelineType = ZodPipeline.create,
  13632. coerce = {
  13633. string: arg => ZodString.create({ ...arg, coerce: !0 }),
  13634. number: arg => ZodNumber.create({ ...arg, coerce: !0 }),
  13635. boolean: arg => ZodBoolean.create({ ...arg, coerce: !0 }),
  13636. bigint: arg => ZodBigInt.create({ ...arg, coerce: !0 }),
  13637. date: arg => ZodDate.create({ ...arg, coerce: !0 }),
  13638. },
  13639. NEVER = INVALID
  13640. var z = Object.freeze({
  13641. __proto__: null,
  13642. defaultErrorMap: errorMap,
  13643. setErrorMap: function (map) {
  13644. overrideErrorMap = map
  13645. },
  13646. getErrorMap,
  13647. makeIssue,
  13648. EMPTY_PATH: [],
  13649. addIssueToContext,
  13650. ParseStatus,
  13651. INVALID,
  13652. DIRTY,
  13653. OK,
  13654. isAborted,
  13655. isDirty,
  13656. isValid,
  13657. isAsync,
  13658. get util() {
  13659. return util
  13660. },
  13661. get objectUtil() {
  13662. return objectUtil
  13663. },
  13664. ZodParsedType,
  13665. getParsedType,
  13666. ZodType,
  13667. ZodString,
  13668. ZodNumber,
  13669. ZodBigInt,
  13670. ZodBoolean,
  13671. ZodDate,
  13672. ZodSymbol,
  13673. ZodUndefined,
  13674. ZodNull,
  13675. ZodAny,
  13676. ZodUnknown,
  13677. ZodNever,
  13678. ZodVoid,
  13679. ZodArray,
  13680. ZodObject,
  13681. ZodUnion,
  13682. ZodDiscriminatedUnion,
  13683. ZodIntersection,
  13684. ZodTuple,
  13685. ZodRecord,
  13686. ZodMap,
  13687. ZodSet,
  13688. ZodFunction,
  13689. ZodLazy,
  13690. ZodLiteral,
  13691. ZodEnum,
  13692. ZodNativeEnum,
  13693. ZodPromise,
  13694. ZodEffects,
  13695. ZodTransformer: ZodEffects,
  13696. ZodOptional,
  13697. ZodNullable,
  13698. ZodDefault,
  13699. ZodCatch,
  13700. ZodNaN,
  13701. BRAND,
  13702. ZodBranded,
  13703. ZodPipeline,
  13704. custom,
  13705. Schema: ZodType,
  13706. ZodSchema: ZodType,
  13707. late,
  13708. get ZodFirstPartyTypeKind() {
  13709. return ZodFirstPartyTypeKind
  13710. },
  13711. coerce,
  13712. any: anyType,
  13713. array: arrayType,
  13714. bigint: bigIntType,
  13715. boolean: booleanType,
  13716. date: dateType,
  13717. discriminatedUnion: discriminatedUnionType,
  13718. effect: effectsType,
  13719. enum: enumType,
  13720. function: functionType,
  13721. instanceof: (
  13722. cls,
  13723. params = { message: `Input not instance of ${cls.name}` }
  13724. ) => custom(data => data instanceof cls, params),
  13725. intersection: intersectionType,
  13726. lazy: lazyType,
  13727. literal: literalType,
  13728. map: lib_mapType,
  13729. nan: nanType,
  13730. nativeEnum: nativeEnumType,
  13731. never: neverType,
  13732. null: nullType,
  13733. nullable: nullableType,
  13734. number: numberType,
  13735. object: objectType,
  13736. oboolean: () => booleanType().optional(),
  13737. onumber: () => numberType().optional(),
  13738. optional: optionalType,
  13739. ostring: () => stringType().optional(),
  13740. pipeline: pipelineType,
  13741. preprocess: preprocessType,
  13742. promise: promiseType,
  13743. record: recordType,
  13744. set: setType,
  13745. strictObject: strictObjectType,
  13746. string: stringType,
  13747. symbol: symbolType,
  13748. transformer: effectsType,
  13749. tuple: tupleType,
  13750. undefined: undefinedType,
  13751. union: unionType,
  13752. unknown: unknownType,
  13753. void: voidType,
  13754. NEVER,
  13755. ZodIssueCode,
  13756. quotelessJson: obj =>
  13757. JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"),
  13758. ZodError,
  13759. })
  13760. const checkboxNode = label => c => s => {
  13761. return ((label, checked, onchange) =>
  13762. h(
  13763. "div",
  13764. {},
  13765. h("label", {}, [
  13766. hyperapp_text(label),
  13767. h("input", { type: "checkbox", checked, onchange }),
  13768. ])
  13769. ))(
  13770. getText(label)(s.lang),
  13771. getState(label)(s),
  13772. ((key = label),
  13773. src_flip((s, e) =>
  13774. pipe(
  13775. (e =>
  13776. z.instanceof(HTMLInputElement).parse(e.currentTarget).checked)(
  13777. e
  13778. ),
  13779. updateAt(key),
  13780. src_flip,
  13781. apply(s)
  13782. )
  13783. ))(c)
  13784. )
  13785. var key
  13786. },
  13787. mapSettingNodes = f => xs => c => s =>
  13788. pipe(
  13789. xs,
  13790. ReadonlyArray_map(x => x(c)(s)),
  13791. f
  13792. ),
  13793. updateInput = setter => key =>
  13794. src_flip((s, e) =>
  13795. pipe(
  13796. (e => {
  13797. const target = e.currentTarget ?? e.__target
  13798. if (
  13799. target instanceof HTMLSelectElement ||
  13800. target instanceof HTMLTextAreaElement ||
  13801. target instanceof HTMLInputElement
  13802. )
  13803. return target.value
  13804. throw Error("Event target type isn't acceptable.")
  13805. })(e),
  13806. setter,
  13807. apply(getState(key)(s)),
  13808. updateAt(key),
  13809. src_flip,
  13810. apply(s)
  13811. )
  13812. ),
  13813. editAction = (key, setter) => c => ({
  13814. oninput: (s, e) => updateInput(setter(!0))(key)(c)(s, e),
  13815. onchange: (s, e) => updateInput(setter(!1))(key)(c)(s, e),
  13816. }),
  13817. setEditNumber = editing => value => state =>
  13818. pipe(
  13819. value,
  13820. Number.parseFloat,
  13821. editing
  13822. ? x =>
  13823. Number.isNaN(x) || "." === value.at(-1)
  13824. ? pipe(state, setText(value))
  13825. : fromValueText(x)(value)
  13826. : x =>
  13827. Number.isNaN(x)
  13828. ? pipe(
  13829. state,
  13830. mapSecond(constant(Option_some([value, Option_some("")])))
  13831. )
  13832. : Editable_of(x)
  13833. ),
  13834. errorText = subject => edit =>
  13835. pipe(
  13836. edit,
  13837. error,
  13838. Option_map(x => `${subject}${"" === x ? "" : ": "}${x}`),
  13839. getOrElse(constant(""))
  13840. ),
  13841. rangeRow = (min, max, step, action) => value =>
  13842. h("div", {}, [
  13843. h("input", {
  13844. style: { width: "150px", verticalAlign: "middle" },
  13845. type: "range",
  13846. min,
  13847. max,
  13848. step,
  13849. value: Editable_value(value).toString(),
  13850. oninput: action.onchange,
  13851. }),
  13852. h("input", {
  13853. style: {
  13854. width: "30px",
  13855. backgroundColor: "transparent",
  13856. color: "inherit",
  13857. borderWidth: "1px",
  13858. verticalAlign: "middle",
  13859. borderColor: hasError(value) ? "#f55" : void 0,
  13860. },
  13861. inputmode: "decimal",
  13862. value: pipe(
  13863. value,
  13864. Editable_text,
  13865. getOrElse(
  13866. constant(
  13867. Editable_value(value)
  13868. .toFixed(4)
  13869. .replace(/\.?0+$/, "")
  13870. )
  13871. )
  13872. ),
  13873. ...action,
  13874. }),
  13875. ]),
  13876. settingRow = (label, error, content) =>
  13877. h("div", {}, [
  13878. h("span", {}, hyperapp_text(label)),
  13879. h(
  13880. "span",
  13881. {
  13882. style: {
  13883. color: "#f55",
  13884. marginLeft: "5px",
  13885. whiteSpace: "pre-wrap",
  13886. },
  13887. },
  13888. hyperapp_text(error)
  13889. ),
  13890. h("div", {}, content),
  13891. ]),
  13892. numberNode = (label, min, max, step) => c => s =>
  13893. settingRow(
  13894. getText(label)(s.lang),
  13895. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  13896. [
  13897. rangeRow(
  13898. min,
  13899. max,
  13900. step,
  13901. editAction(label, setEditNumber)(c)
  13902. )(getState(label)(s)),
  13903. ]
  13904. ),
  13905. panelBoxStyle = width => ({ flex: `0 0 ${width}px`, margin: "2px" }),
  13906. settingUI_chatFieldPanel = pipe(
  13907. [
  13908. pipe(
  13909. [
  13910. numberNode("fieldScale", 0.7, 1.5, 0.05),
  13911. checkboxNode("simplifyChatField"),
  13912. checkboxNode("createBanButton"),
  13913. ],
  13914. mapSettingNodes(x => h("div", { style: panelBoxStyle(644) }, x))
  13915. ),
  13916. ],
  13917. mapSettingNodes(Function_identity)
  13918. ),
  13919. action = {
  13920. copy: () => s =>
  13921. Effect_promise(async () => {
  13922. GM.setClipboard(
  13923. pipe(
  13924. s.eventLog.entries,
  13925. ReadonlyArray_map(x => `${x.id}: ${x.text}`),
  13926. join("\n")
  13927. )
  13928. )
  13929. }),
  13930. clearFlowChats: c => () => c.act.clearFlowChats,
  13931. },
  13932. buttonNode = label => c => state =>
  13933. h(
  13934. "button",
  13935. {
  13936. type: "button",
  13937. onclick: s => [s, () => runPromise(action[label](c)(s))],
  13938. },
  13939. hyperapp_text(getText(label)(state.lang))
  13940. ),
  13941. tabContainer = style => ontabSelect => labels => tabs => mainTab =>
  13942. h("div", {}, [
  13943. h(
  13944. "div",
  13945. {},
  13946. pipe(
  13947. labels,
  13948. ReadonlyArray_map((x, i) =>
  13949. h(
  13950. "span",
  13951. {
  13952. style: {
  13953. ...style.label,
  13954. ...(mainTab === i ? style.labelFocus : {}),
  13955. display: "inline-block",
  13956. },
  13957. onpointerdown: [ontabSelect, i],
  13958. },
  13959. hyperapp_text(x)
  13960. )
  13961. )
  13962. )
  13963. ),
  13964. h(
  13965. "div",
  13966. { style: { ...style.container, overflow: "auto" } },
  13967. h(
  13968. "div",
  13969. { style: { ...style.tab } },
  13970. tabs.find((_, i) => i === mainTab)?.()
  13971. )
  13972. ),
  13973. ]),
  13974. feedbackPanel = c => s =>
  13975. pipe(
  13976. Math.trunc(getState("eventLog")(s).entries.length / 100) + 1,
  13977. logPageLength => [
  13978. h("div", { style: panelBoxStyle(644) }, [
  13979. h(
  13980. "div",
  13981. { style: { float: "right" } },
  13982. h(
  13983. "a",
  13984. {
  13985. style: { color: "#f0f" },
  13986. href: "https://greasyfork.org/en/scripts/411442-flow-youtube-chat/feedback",
  13987. target: "_blank",
  13988. },
  13989. hyperapp_text(getText("giveFeedback")(s.lang))
  13990. )
  13991. ),
  13992. h("div", {}, [
  13993. h("span", {}, hyperapp_text(getText("eventLog")(s.lang))),
  13994. buttonNode("copy")(c)(s),
  13995. tabContainer({
  13996. container: { height: "276px" },
  13997. label: { padding: "4px", width: "2em", textAlign: "center" },
  13998. labelFocus: { background: "#666" },
  13999. tab: {
  14000. display: "flex",
  14001. flexDirection: "column",
  14002. padding: "6px",
  14003. },
  14004. })((_, n) => updateAt("logTab")(n)(c))(
  14005. pipe(makeBy(logPageLength, x => `${x}`))
  14006. )(
  14007. pipe(
  14008. makeBy(
  14009. logPageLength,
  14010. i => () =>
  14011. pipe(
  14012. getState("eventLog")(s).entries.slice(
  14013. 100 * i,
  14014. 100 * (i + 1)
  14015. ),
  14016. ReadonlyArray_map((x, j) =>
  14017. h("div", { style: { display: "flex" } }, [
  14018. h(
  14019. "div",
  14020. {
  14021. style: {
  14022. userSelect: "none",
  14023. flex: "0 0 2em",
  14024. },
  14025. },
  14026. hyperapp_text(x.id)
  14027. ),
  14028. h(
  14029. "div",
  14030. {
  14031. style: {
  14032. background: j % 2 == 0 ? "#fff" : "#ddd",
  14033. color: "#000",
  14034. flex: "auto",
  14035. wordBreak: "break-all",
  14036. whiteSpace: "pre-wrap",
  14037. padding: "0 2px",
  14038. },
  14039. },
  14040. hyperapp_text(x.text)
  14041. ),
  14042. ])
  14043. )
  14044. )
  14045. )
  14046. )
  14047. )(getState("logTab")(s)),
  14048. ]),
  14049. ]),
  14050. ]
  14051. ),
  14052. setEditRegexs = editing => value =>
  14053. pipe(
  14054. value,
  14055. split(/\r\n|\n/),
  14056. ReadonlyArray_filter(not(isEmpty)),
  14057. Identity_bindTo("regexs"),
  14058. Identity_let_("errors", ({ regexs }) =>
  14059. pipe(
  14060. regexs,
  14061. ReadonlyArray_map((x, i) => {
  14062. try {
  14063. RegExp(x, "u")
  14064. return Option_none()
  14065. } catch (e) {
  14066. return Option_some(`${e} in regex number ${i}`)
  14067. }
  14068. }),
  14069. (Semigroup =>
  14070. fromSemigroup(
  14071. Semigroup_make((self, that) =>
  14072. Option_isNone(self)
  14073. ? that
  14074. : Option_isNone(that)
  14075. ? self
  14076. : Option_some(Semigroup.combine(self.value, that.value))
  14077. ),
  14078. Option_none()
  14079. ))(intercalate("\n")(Semigroup)).combineAll
  14080. )
  14081. ),
  14082. ctx =>
  14083. editing
  14084. ? setText(value)
  14085. : pipe(
  14086. ctx.errors,
  14087. Option_map(x =>
  14088. mapSecond(() => Option_some([value, Option_some(x)]))
  14089. ),
  14090. getOrElse(constant(constant(Editable_of(ctx.regexs))))
  14091. )
  14092. ),
  14093. setEditStrings = editing => value =>
  14094. pipe(value, split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty)), x =>
  14095. constant(
  14096. editing ? [x, Option_some([value, Option_none()])] : Editable_of(x)
  14097. )
  14098. ),
  14099. textAreaRow = (rows, action) => value =>
  14100. h("textarea", {
  14101. rows,
  14102. style: {
  14103. resize: "horizontal",
  14104. boxSizing: "border-box",
  14105. width: "100%",
  14106. borderColor: hasError(value) ? "#f55" : void 0,
  14107. },
  14108. value: pipe(
  14109. value,
  14110. Editable_text,
  14111. getOrElse(pipe(Editable_value(value), join("\n"), constant))
  14112. ),
  14113. ...action,
  14114. }),
  14115. textAreaNode = (label, rows, setter) => c => s =>
  14116. settingRow(
  14117. getText(label)(s.lang),
  14118. errorText(getText("invalidSetting")(s.lang))(s[label]),
  14119. [textAreaRow(rows, editAction(label, setter)(c))(getState(label)(s))]
  14120. ),
  14121. filterPanelOld = c => s =>
  14122. [
  14123. h(
  14124. "div",
  14125. { style: panelBoxStyle(212) },
  14126. textAreaNode("bannedWords", 18, setEditStrings)(c)(s)
  14127. ),
  14128. h(
  14129. "div",
  14130. { style: panelBoxStyle(212) },
  14131. textAreaNode("bannedWordRegexs", 18, setEditRegexs)(c)(s)
  14132. ),
  14133. h(
  14134. "div",
  14135. { style: panelBoxStyle(212) },
  14136. textAreaNode("bannedUsers", 18, setEditStrings)(c)(s)
  14137. ),
  14138. ]
  14139. var validate_color_lib = __webpack_require__(694),
  14140. lib_default = __webpack_require__.n(validate_color_lib)
  14141. const validColor = x => lib_default()(x.replace(/grey/gi, "gray")),
  14142. setEditColor = editing => value =>
  14143. editing
  14144. ? validColor(value)
  14145. ? constant(fromValueText(value)(value))
  14146. : setText(value)
  14147. : validColor(value)
  14148. ? constant(Editable_of(value))
  14149. : mapSecond(constant(Option_some([value, Option_some("")]))),
  14150. colorPicker = action => color =>
  14151. h("input", {
  14152. style: { width: "36px", verticalAlign: "middle" },
  14153. type: "color",
  14154. value: color,
  14155. oninput: action.onchange,
  14156. }),
  14157. textInput = action => value =>
  14158. h("input", {
  14159. style: {
  14160. verticalAlign: "middle",
  14161. width: "5.5em",
  14162. borderColor: hasError(value) ? "#f55" : void 0,
  14163. },
  14164. maxlength: 20,
  14165. value: pipe(
  14166. value,
  14167. Editable_text,
  14168. getOrElse(constant(Editable_value(value)))
  14169. ),
  14170. ...action,
  14171. }),
  14172. setEditInt = editing => value => state =>
  14173. pipe(
  14174. value,
  14175. Number.parseInt,
  14176. editing
  14177. ? x =>
  14178. Number.isNaN(x) || "." === value.at(-1)
  14179. ? pipe(state, setText(value))
  14180. : fromValueText(x)(value)
  14181. : x =>
  14182. Number.isNaN(x)
  14183. ? pipe(
  14184. state,
  14185. mapSecond(constant(Option_some([value, Option_some("")])))
  14186. )
  14187. : Editable_of(x)
  14188. ),
  14189. intNode = (label, min, max, step) => c => s =>
  14190. settingRow(
  14191. getText(label)(s.lang),
  14192. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  14193. [
  14194. rangeRow(
  14195. min,
  14196. max,
  14197. step,
  14198. editAction(label, setEditInt)(c)
  14199. )(getState(label)(s)),
  14200. ]
  14201. ),
  14202. fonts = currentFont => [
  14203. ["", "Default", "デフォルト"],
  14204. ["arial", "Arial", "Arial"],
  14205. ["arial black", "Arial Black", "Arial Black"],
  14206. ["arial narrow", "Arial Narrow", "Arial Narrow"],
  14207. ["Century", "Century", "Century"],
  14208. ["Comic Sans MS", "Comic Sans MS", "Comic Sans MS"],
  14209. ["Courier", "Courier", "Courier"],
  14210. ["cursive", "cursive", "cursive"],
  14211. ["fantasy", "fantasy", "fantasy"],
  14212. ["Impact", "Impact", "Impact"],
  14213. ["Meiryo", "Meiryo", "メイリオ"],
  14214. ["Meiryo UI", "Meiryo UI", "メイリオ UI"],
  14215. ["monospace", "monospace", "monospace"],
  14216. ["Monotype Corsiva", "Monotype Corsiva", "Monotype Corsiva"],
  14217. ["MS PGothic", "MS PGothic", "MS Pゴシック"],
  14218. ["MS Gothic", "MS Gothic", "MS ゴシック"],
  14219. ["MS Sans Serif", "MS Sans Serif", "MS Sans Serif"],
  14220. ["MS Serif", "MS Serif", "MS Serif"],
  14221. ["MS UI Gothic", "MS UI Gothic", "MS UI Gothic"],
  14222. ["sans-serif", "Sans-serif", "Sans-serif"],
  14223. ["serif", "Serif", "Serif"],
  14224. ["Times New Roman", "Times New Roman", "Times New Roman"],
  14225. ["Yu Gothic", "Yu Gothic", "遊ゴシック"],
  14226. ["YuGothic", "YuGothic", "游ゴシック体"],
  14227. [currentFont, "Custom", "カスタム"],
  14228. ],
  14229. setEditString = editing =>
  14230. flow(x => constant(editing ? fromValueText(x)(x) : Editable_of(x))),
  14231. settingUI_textRowStyle = { width: "70%", boxSizing: "border-box" },
  14232. ui_option = (value, label, selected) =>
  14233. h("option", { value, selected }, hyperapp_text(label)),
  14234. exampleTextStyle = s => ({
  14235. fontFamily: Editable_value(s.font),
  14236. fontWeight: Editable_value(s.fontWeight).toString(),
  14237. textShadow: textShadow(Editable_value(s.shadowColor))(
  14238. Editable_value(s.shadowFontWeight)
  14239. ),
  14240. }),
  14241. colorTextOutput = textStyle => color =>
  14242. h(
  14243. "span",
  14244. { style: { ...textStyle, color } },
  14245. hyperapp_text("Aa1あア亜")
  14246. ),
  14247. textColorNode = label => c => s =>
  14248. settingRow(
  14249. getText(label)(s.lang),
  14250. errorText(getText("invalidColor")(s.lang))(s[label]),
  14251. pipe(
  14252. {
  14253. a: editAction(label, setEditColor)(c),
  14254. v: Editable_value(s[label]),
  14255. },
  14256. ({ a, v }) => [
  14257. colorPicker(a)(v),
  14258. textInput(a)(s[label]),
  14259. colorTextOutput(exampleTextStyle(s))(v),
  14260. ]
  14261. )
  14262. ),
  14263. flowChatPanel = pipe(
  14264. [
  14265. pipe(
  14266. [
  14267. c => s =>
  14268. pipe(Editable_value(s.font), font =>
  14269. settingRow(getText("font")(s.lang), "", [
  14270. h(
  14271. "select",
  14272. {
  14273. style: settingUI_textRowStyle,
  14274. onchange: updateInput(setEditString(!1))("font")(c),
  14275. },
  14276. pipe(
  14277. fonts(font),
  14278. findFirstIndex(x => x[0] === font),
  14279. getOrElse(() => 0),
  14280. index =>
  14281. pipe(
  14282. fonts(font),
  14283. ReadonlyArray_map((f, i) =>
  14284. ui_option(
  14285. f[0],
  14286. pipe(
  14287. languages,
  14288. findFirstIndex(x => x === s.lang),
  14289. Option_map(x => unsafeGet(x + 1)(f)),
  14290. getOrElse(() => "Error")
  14291. ),
  14292. i === index
  14293. )
  14294. )
  14295. )
  14296. )
  14297. ),
  14298. h("input", {
  14299. style: settingUI_textRowStyle,
  14300. maxlength: 20,
  14301. value: font,
  14302. ...editAction("font", setEditString),
  14303. }),
  14304. ])
  14305. ),
  14306. textColorNode("color"),
  14307. textColorNode("ownerColor"),
  14308. textColorNode("moderatorColor"),
  14309. textColorNode("memberColor"),
  14310. ((label = "shadowColor"),
  14311. c => s =>
  14312. settingRow(
  14313. getText(label)(s.lang),
  14314. errorText(getText("invalidColor")(s.lang))(s[label]),
  14315. pipe(editAction(label, setEditColor)(c), x => [
  14316. colorPicker(x)(Editable_value(s[label])),
  14317. textInput(x)(s[label]),
  14318. ])
  14319. )),
  14320. ],
  14321. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  14322. ),
  14323. pipe(
  14324. [
  14325. numberNode("chatOpacity", 0, 1, 0.05),
  14326. numberNode("fontSize", 0.3, 2, 0.05),
  14327. numberNode("fontWeight", 10, 1e3, 10),
  14328. numberNode("shadowFontWeight", 0, 3, 0.1),
  14329. numberNode("flowSpeed", 1, 50, 1),
  14330. intNode("maxChatCount", 5, 200, 5),
  14331. intNode("maxChatLength", 5, 200, 5),
  14332. intNode("laneCount", 1, 25, 1),
  14333. ],
  14334. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  14335. ),
  14336. pipe(
  14337. [
  14338. numberNode("flowY1", 0, 0.95, 0.01),
  14339. numberNode("flowY2", 0.05, 1, 0.01),
  14340. numberNode("flowX1", 0, 0.95, 0.01),
  14341. numberNode("flowX2", 0.05, 1, 0.01),
  14342. numberNode("minSpacing", 0, 2.5, 0.1),
  14343. c => s =>
  14344. h("div", {}, [
  14345. checkboxNode("useStepTiming")(c)(s),
  14346. h(
  14347. "div",
  14348. {
  14349. style: {
  14350. opacity: getState("useStepTiming")(s) ? void 0 : "0.5",
  14351. },
  14352. },
  14353. intNode("timingStepCount", 1, 400, 1)(c)(s)
  14354. ),
  14355. ]),
  14356. checkboxNode("createChats"),
  14357. checkboxNode("displayModName"),
  14358. checkboxNode("displaySuperChatAuthor"),
  14359. checkboxNode("textOnly"),
  14360. () => s => hyperapp_text(getText("flowNewChatIf")(s.lang)),
  14361. checkboxNode("noOverlap"),
  14362. buttonNode("clearFlowChats"),
  14363. ],
  14364. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  14365. ),
  14366. ],
  14367. mapSettingNodes(Function_identity)
  14368. )
  14369. var label
  14370. const settingUI_flowChatPanel = flowChatPanel,
  14371. setString = flow(Function_identity, constant),
  14372. simpleWrap = (comp, init) =>
  14373. pipe(
  14374. Effect_sync(() => document.createElement(comp.tag)),
  14375. Effect_flatMap(node =>
  14376. Effect_sync(() => ({
  14377. node,
  14378. dispatch: app({ init, view: comp.view, node }),
  14379. }))
  14380. )
  14381. ),
  14382. tapEffect = f =>
  14383. (0, external_rxjs_namespaceObject.concatMap)(x =>
  14384. (0, external_rxjs_namespaceObject.from)(runPromise(f(x))).pipe(
  14385. (0, external_rxjs_namespaceObject.map)(() => x)
  14386. )
  14387. ),
  14388. toggleSettingsPanelComponent = flow(
  14389. syncState => (x, e) =>
  14390. pipe({ ...x, showPanel: !x.showPanel }, newState => [
  14391. newState,
  14392. x.showPanel
  14393. ? () => z.instanceof(HTMLElement).parse(e.currentTarget).blur()
  14394. : () => {},
  14395. () =>
  14396. runPromise(syncState(oldState => ({ ...oldState, ...newState }))),
  14397. ]),
  14398. toggle => state =>
  14399. h(
  14400. "button",
  14401. {
  14402. class: "fyc_button",
  14403. style: {
  14404. background: "rgba(0,0,0,0)",
  14405. marginLeft: "10px",
  14406. whiteSpace: "nowrap",
  14407. },
  14408. onclick: toggle,
  14409. },
  14410. [
  14411. h(
  14412. "svg",
  14413. {
  14414. preserveAspectRatio: "xMidYMid meet",
  14415. viewBox: "0 0 640 640",
  14416. width: "15",
  14417. height: "15",
  14418. style: { position: "relative", top: "1px" },
  14419. },
  14420. [
  14421. h(
  14422. "defs",
  14423. {},
  14424. h("path", {
  14425. id: "d1TbzTC1zI",
  14426. 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",
  14427. })
  14428. ),
  14429. h("use", {
  14430. href: "#d1TbzTC1zI",
  14431. opacity: "1",
  14432. fill: "var(--iron-icon-fill-color, currentcolor)",
  14433. "fill-opacity": "1",
  14434. }),
  14435. ]
  14436. ),
  14437. h(
  14438. "span",
  14439. {
  14440. style: {
  14441. position: "relative",
  14442. top: "-2px",
  14443. marginLeft: "8px,",
  14444. },
  14445. },
  14446. hyperapp_text(getText("setting")(state.lang))
  14447. ),
  14448. ]
  14449. ),
  14450. button =>
  14451. makeComponent(
  14452. tag => s => h(tag, { style: { display: "flex" } }, button(s))
  14453. )("span")
  14454. ),
  14455. videoToggleStream = video =>
  14456. pipe(
  14457. [["playing"], ["waiting", "pause"]],
  14458. ReadonlyArray_map((x, i) => [x, 0 === i]),
  14459. ReadonlyArray_flatMap(([xs, b]) =>
  14460. pipe(
  14461. xs,
  14462. ReadonlyArray_map(x => [x, b])
  14463. )
  14464. ),
  14465. ReadonlyArray_map(([x, b]) =>
  14466. pipe(
  14467. (0, external_rxjs_namespaceObject.fromEvent)(video, x),
  14468. (0, external_rxjs_namespaceObject.map)(() => b)
  14469. )
  14470. ),
  14471. x => (0, external_rxjs_namespaceObject.merge)(...x)
  14472. ),
  14473. Logger_make = makeLogger,
  14474. Logger_replace = replaceLogger,
  14475. Logger_withMinimumLogLevel = withMinimumLogLevel,
  14476. Logger_zip = logger_zip,
  14477. Logger_defaultLogger = defaultLogger
  14478. var LogAnnotationKeys
  14479. !(function (LogAnnotationKeys) {
  14480. LogAnnotationKeys.name = "name"
  14481. })(LogAnnotationKeys || (LogAnnotationKeys = {}))
  14482. const src_LogAnnotationKeys = LogAnnotationKeys,
  14483. getConsoleLog = x =>
  14484. (x === Trace
  14485. ? console.trace
  14486. : x === Level_Debug
  14487. ? console.debug
  14488. : x === Info
  14489. ? console.info
  14490. : x === Warning
  14491. ? console.warn
  14492. : x === Level_Error || x === Fatal
  14493. ? console.error
  14494. : console.log
  14495. ).bind(console),
  14496. metaLogger = Logger_make(
  14497. (fiberId, logLevel, message, cause, context, span, annotations) =>
  14498. runPromise(
  14499. pipe(
  14500. () =>
  14501. `${pipe(
  14502. annotations,
  14503. mjs_HashMap_get(src_LogAnnotationKeys.name),
  14504. match(
  14505. () => "",
  14506. x => `[${x}] `
  14507. )
  14508. )}${message}`,
  14509. getStr =>
  14510. pipe(
  14511. FiberRefs_getOrDefault(context, logMeta),
  14512. match(
  14513. () =>
  14514. greaterThanEqual(Info)(logLevel)
  14515. ? Effect_sync(() => getConsoleLog(logLevel)(getStr()))
  14516. : Effect_unit(),
  14517. meta =>
  14518. Effect_sync(() =>
  14519. getConsoleLog(logLevel)(`${getStr()}: `, meta)
  14520. )
  14521. )
  14522. )
  14523. )
  14524. )
  14525. )
  14526. runPromise(
  14527. pipe(
  14528. Effect_Do(),
  14529. Effect_bindValue(
  14530. "settingUpdateApps",
  14531. () => new external_rxjs_namespaceObject.BehaviorSubject([])
  14532. ),
  14533. Effect_bindValue("provideLog", x => {
  14534. return (
  14535. (settingUpdateApps = x.settingUpdateApps),
  14536. effect => {
  14537. return pipe(
  14538. Effect_succeed(
  14539. Logger_replace(
  14540. Logger_defaultLogger,
  14541. Logger_zip(metaLogger)(
  14542. ((settingApps = settingUpdateApps),
  14543. Logger_make((fiberId, logLevel, message) => {
  14544. return runPromise(
  14545. ((apps = settingApps.getValue()),
  14546. dispatchable =>
  14547. pipe(
  14548. apps,
  14549. ReadonlyArray_map(x =>
  14550. Effect_sync(() => x(dispatchable))
  14551. ),
  14552. x => Effect_all(x)
  14553. ))(s => {
  14554. return {
  14555. ...s,
  14556. eventLog: ((text = message),
  14557. flow(
  14558. (
  14559. text => log =>
  14560. makeLog({
  14561. nextId: log.nextId + 1,
  14562. entries: pipe(
  14563. log.entries,
  14564. append({ id: log.nextId, text })
  14565. ),
  14566. })
  14567. )(text),
  14568. x =>
  14569. x.entries.length > 1e3
  14570. ? (log =>
  14571. makeLog({
  14572. nextId: log.nextId,
  14573. entries: pipe(log.entries, take(100)),
  14574. }))(x)
  14575. : x
  14576. ))(s.eventLog),
  14577. }
  14578. var text
  14579. })
  14580. )
  14581. var apps
  14582. }))
  14583. )
  14584. )
  14585. ),
  14586. Effect_tap(x => pipe(effect, Effect_provideSomeLayer(x))),
  14587. Effect_logAnnotate(src_LogAnnotationKeys.name, "FYC"),
  14588. Logger_withMinimumLogLevel(Level_Debug),
  14589. Effect_catchAllCause(x =>
  14590. Effect_logInfoCauseMessage("Defect", x)
  14591. )
  14592. )
  14593. var settingApps
  14594. }
  14595. )
  14596. var settingUpdateApps
  14597. }),
  14598. Effect_flatMap(({ settingUpdateApps, provideLog }) =>
  14599. provideLog(
  14600. pipe(
  14601. src_defaultGMConfig,
  14602. x => ({ gmConfig: x, configKeys: Object.keys(x) }),
  14603. Effect_succeed,
  14604. Effect_bindValue(
  14605. "updateSettingState",
  14606. () => dispatchable =>
  14607. provideLog(
  14608. pipe(
  14609. settingUpdateApps.getValue(),
  14610. ReadonlyArray_map(x =>
  14611. Effect_sync(() => x(dispatchable))
  14612. ),
  14613. x => Effect_all(x)
  14614. )
  14615. )
  14616. ),
  14617. Effect_bind("config", ctx => {
  14618. return (
  14619. (config = ctx.gmConfig),
  14620. pipe(
  14621. Object.entries(config),
  14622. ReadonlyArray_map(([k, c]) =>
  14623. pipe(
  14624. c.getValue,
  14625. Effect_map(x => [k, x])
  14626. )
  14627. ),
  14628. x => Effect_all(x),
  14629. Effect_map(Object.fromEntries)
  14630. )
  14631. )
  14632. var config
  14633. }),
  14634. Effect_bindValue("getConfig", ctx =>
  14635. (c =>
  14636. pipe(
  14637. c,
  14638. mapObject(([x]) => [x, () => c[x]])
  14639. ))(ctx.config)
  14640. ),
  14641. flow(
  14642. Effect_bindValue("mainState", x => ({
  14643. chatPlaying: !0,
  14644. playerRect: new DOMRectReadOnly(0, 0, 600, 400),
  14645. config: x.config,
  14646. })),
  14647. Effect_bindValue("configSubject", ctx =>
  14648. pipe(
  14649. ctx.configKeys,
  14650. ReadonlyArray_map(x => [
  14651. x,
  14652. new external_rxjs_namespaceObject.Subject(),
  14653. ]),
  14654. Object.fromEntries
  14655. )
  14656. ),
  14657. Effect_bindValue("setterFromKeysMap", ctx =>
  14658. (
  14659. keys => f =>
  14660. pipe(
  14661. keys,
  14662. ReadonlyArray_map(x => [x, f(x)]),
  14663. Object.fromEntries
  14664. )
  14665. )(ctx.configKeys)
  14666. ),
  14667. Effect_bindValue("setConfigPlain", ctx =>
  14668. ctx.setterFromKeysMap(
  14669. key => val =>
  14670. Effect_promise(async () => {
  14671. Object.assign(ctx.mainState.config, { [key]: val })
  14672. ctx.configSubject[key].next(val)
  14673. })
  14674. )
  14675. ),
  14676. Effect_bindValue(
  14677. "changedConfigMap",
  14678. ctx => key => val =>
  14679. pipe(
  14680. Effect_promise(async () => ctx.config[key]),
  14681. Effect_filterOrFail(
  14682. x => !fast_deep_equal_default()(x, val),
  14683. Option_none
  14684. ),
  14685. Effect_flatMap(() => ctx.setConfigPlain[key](val))
  14686. )
  14687. ),
  14688. Effect_bindValue("setChangedConfig", ctx =>
  14689. ctx.setterFromKeysMap(ctx.changedConfigMap)
  14690. ),
  14691. Effect_bindValue(
  14692. "channel",
  14693. () =>
  14694. new broadcast_channel_BroadcastChannel(
  14695. "fyc-0615654655528523"
  14696. )
  14697. )
  14698. ),
  14699. flow(
  14700. Effect_bindValue("setConfig", ctx =>
  14701. ctx.setterFromKeysMap(
  14702. key => val =>
  14703. pipe(
  14704. ctx.changedConfigMap(key)(val),
  14705. Effect_zipRight(
  14706. Effect_promise(() =>
  14707. ctx.channel.postMessage([key, val])
  14708. )
  14709. ),
  14710. Effect_zipRight(
  14711. Effect_promise(() =>
  14712. pipe(ctx.gmConfig[key], x =>
  14713. GM.setValue(x.gmKey, x.toGm(val))
  14714. )
  14715. )
  14716. )
  14717. )
  14718. )
  14719. ),
  14720. Effect_bind("reinitSubject", () =>
  14721. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  14722. ),
  14723. Effect_bindValue("reinitialize", ctx =>
  14724. provideLog(
  14725. Effect_sync(() => {
  14726. requestAnimationFrame(() => lib(ctx.reinitSubject)())
  14727. })
  14728. )
  14729. ),
  14730. Effect_tap(ctx =>
  14731. ctx.setConfigPlain.filterExp(defaultFilter(ctx.config))
  14732. ),
  14733. Effect_bindValue("toggleChatButtonInit", ctx => ({
  14734. lang: ctx.config.lang,
  14735. displayChats: ctx.config.displayChats,
  14736. })),
  14737. Effect_bind("wrappedToggleChat", ctx => {
  14738. return simpleWrap(
  14739. ((setConfig = ctx.setConfig),
  14740. pipe(
  14741. "button",
  14742. makeComponent(
  14743. tag => state =>
  14744. pipe(
  14745. getText(
  14746. state.displayChats ? "hideChat" : "showChat"
  14747. )(state.lang),
  14748. label =>
  14749. h(
  14750. tag,
  14751. {
  14752. class: "ytp-button",
  14753. style: {
  14754. background: "none",
  14755. border: "none",
  14756. cursor: "pointer",
  14757. float: "left",
  14758. fontSize: "1em",
  14759. height: "4em",
  14760. outline: "none",
  14761. overflow: "visible",
  14762. padding: "0 0 0em",
  14763. position: "relative",
  14764. width: "3em",
  14765. },
  14766. type: "button",
  14767. "aria-label": label,
  14768. title: label,
  14769. onclick: s =>
  14770. pipe(!s.displayChats, displayChats => [
  14771. { ...s, displayChats },
  14772. () =>
  14773. runPromise(
  14774. setConfig.displayChats(displayChats)
  14775. ),
  14776. ]),
  14777. },
  14778. [
  14779. h(
  14780. "svg",
  14781. {
  14782. style: { width: "100%" },
  14783. viewBox: "0 0 36 36",
  14784. },
  14785. [
  14786. h("path", {
  14787. class: "chat-button-path",
  14788. d: "m11 12h17q1 0 1 1v9q0 1-1 1h-1v2l-4-2h-12q-1 0-1-1v-9q0-1 1-1z",
  14789. fill: "#fff",
  14790. "fill-opacity": state.displayChats
  14791. ? "1"
  14792. : "0",
  14793. stroke: "#fff",
  14794. "stroke-width": "2",
  14795. }),
  14796. ]
  14797. ),
  14798. ]
  14799. )
  14800. )
  14801. )
  14802. )),
  14803. ctx.toggleChatButtonInit
  14804. )
  14805. var setConfig
  14806. }),
  14807. Effect_bindValue("flowChats", () => []),
  14808. Effect_bind("wrappedSettings", ctx =>
  14809. simpleWrap(
  14810. pipe(
  14811. (
  14812. c => state =>
  14813. state.showPanel
  14814. ? h(
  14815. "div",
  14816. {
  14817. class: "fyc_panel",
  14818. style: {
  14819. backgroundColor: "rgba(30,30,30,0.9)",
  14820. position: "absolute",
  14821. zIndex: "10000",
  14822. color: "#fff",
  14823. fontSize: "14px",
  14824. overflow: "auto",
  14825. left: `${state.panelRect.x}px`,
  14826. top: `${state.panelRect.y}px`,
  14827. width: `${state.panelRect.width}px`,
  14828. height: `${state.panelRect.height}px`,
  14829. border: "solid 1px #666",
  14830. fontFamily: "MS PGothic",
  14831. lineHeight: "1.2",
  14832. colorScheme: "dark",
  14833. },
  14834. },
  14835. [
  14836. h(
  14837. "div",
  14838. {
  14839. style: {
  14840. position: "absolute",
  14841. inset: "3px 3px auto auto",
  14842. },
  14843. },
  14844. [
  14845. hyperapp_text("🌐"),
  14846. h(
  14847. "select",
  14848. {
  14849. onchange:
  14850. updateInput(setString)("lang")(c),
  14851. },
  14852. pipe(
  14853. languages,
  14854. zip(languageLabels),
  14855. ReadonlyArray_map(([lang, label]) =>
  14856. ui_option(
  14857. lang,
  14858. label,
  14859. lang === state.lang
  14860. )
  14861. )
  14862. )
  14863. ),
  14864. ]
  14865. ),
  14866. tabContainer({
  14867. container: { height: "364px" },
  14868. label: { padding: "6px" },
  14869. labelFocus: { background: "#666" },
  14870. tab: { display: "flex", padding: "6px" },
  14871. })((s, n) => updateAt("mainTab")(n)(c)(s))(
  14872. pipe(
  14873. [
  14874. "flowChat",
  14875. "chatFilter",
  14876. "chatField",
  14877. "feedback",
  14878. ],
  14879. ReadonlyArray_map(getText),
  14880. ReadonlyArray_map(apply(state.lang))
  14881. )
  14882. )(
  14883. pipe(
  14884. [
  14885. settingUI_flowChatPanel,
  14886. filterPanelOld,
  14887. settingUI_chatFieldPanel,
  14888. feedbackPanel,
  14889. ],
  14890. ReadonlyArray_map(apply(c)),
  14891. ReadonlyArray_map(constant),
  14892. ReadonlyArray_map(src_flip),
  14893. ReadonlyArray_map(apply(state))
  14894. )
  14895. )(getState("mainTab")(state)),
  14896. ]
  14897. )
  14898. : h("div", {})
  14899. )({
  14900. setConfig: ctx.setConfig,
  14901. act: {
  14902. clearFlowChats: removeOldChats(ctx.flowChats)(0),
  14903. },
  14904. }),
  14905. panel =>
  14906. makeComponent(
  14907. tag => s =>
  14908. h(tag, { style: { display: "contents" } }, panel(s))
  14909. )("span")
  14910. ),
  14911. settingStateInit(ctx.config)
  14912. )
  14913. ),
  14914. Effect_bind("wrappedToggleSettings", ctx =>
  14915. simpleWrap(
  14916. toggleSettingsPanelComponent(ctx.updateSettingState),
  14917. settingStateInit(ctx.config)
  14918. )
  14919. )
  14920. ),
  14921. flow(
  14922. Effect_tap(ctx =>
  14923. Effect_sync(() =>
  14924. settingUpdateApps.next([
  14925. ...settingUpdateApps.getValue(),
  14926. ctx.wrappedSettings.dispatch,
  14927. ctx.wrappedToggleSettings.dispatch,
  14928. ])
  14929. )
  14930. )
  14931. ),
  14932. Effect_bindValue(
  14933. "settingsRectSubject",
  14934. () =>
  14935. new external_rxjs_namespaceObject.BehaviorSubject(
  14936. new DOMRectReadOnly(0, 0, 660, 395)
  14937. )
  14938. ),
  14939. Effect_tap(ctx =>
  14940. pipe(
  14941. [
  14942. "Version: 1.15.19",
  14943. `User Agent: ${window.navigator.userAgent}`,
  14944. `GMConfig: ${JSON.stringify(ctx.config, void 0, 2)}`,
  14945. ],
  14946. ReadonlyArray_map(Effect_logDebug),
  14947. x => Effect_all(x)
  14948. )
  14949. ),
  14950. Effect_bindValue("co", ctx =>
  14951. pipe(
  14952. ctx.configSubject,
  14953. mapObject(([k, value]) => [
  14954. k,
  14955. pipe(
  14956. value,
  14957. tapEffect(v =>
  14958. provideLog(
  14959. pipe(
  14960. v,
  14961. x => s => ({ ...s, [k]: x }),
  14962. Effect_succeed,
  14963. Effect_tap(() => {
  14964. return ctx.updateSettingState(
  14965. ((key = k),
  14966. value => state => ({
  14967. ...state,
  14968. [key]: isEditable(key)(value)
  14969. ? setValue(value)(state[key])
  14970. : "filterExp" === key
  14971. ? void 0
  14972. : value,
  14973. }))(v)
  14974. )
  14975. var key
  14976. }),
  14977. Effect_flatMap(x =>
  14978. k in ctx.toggleChatButtonInit
  14979. ? Effect_sync(() =>
  14980. ctx.wrappedToggleChat.dispatch(x)
  14981. )
  14982. : Effect_unit()
  14983. ),
  14984. x => () => runPromise(provideLog(x)),
  14985. x => Effect_sync(() => requestAnimationFrame(x))
  14986. )
  14987. )
  14988. )
  14989. ),
  14990. ])
  14991. )
  14992. ),
  14993. Effect_bindValue("livePage", () => livePageYt),
  14994. Effect_bindValue("live", ctx => makePageState(ctx.livePage)),
  14995. Effect_bind("chatScreen", () => makeChatScreen),
  14996. Effect_bind("all$", ctx => {
  14997. return pipe(
  14998. {
  14999. eq:
  15000. ((E = strict()),
  15001. Equivalence_make(
  15002. (x, y) =>
  15003. x === y ||
  15004. (Option_isNone(x)
  15005. ? Option_isNone(y)
  15006. : !Option_isNone(y) && E(x.value, y.value))
  15007. )),
  15008. initDelay: 100,
  15009. urlDelay: 1700,
  15010. changeDetectInterval: 700,
  15011. bodyResizeDetectInterval: 300,
  15012. errorRetryInterval: 5e3,
  15013. liveElementKeys: Object.keys(ctx.livePage),
  15014. tapUpdateSettingsRect: ob =>
  15015. (0, external_rxjs_namespaceObject.switchMap)(value => {
  15016. return pipe(
  15017. ctx.settingsRectSubject,
  15018. (0, external_rxjs_namespaceObject.first)(),
  15019. (0, external_rxjs_namespaceObject.map)(
  15020. ((toggleSettingsElement =
  15021. ctx.wrappedToggleSettings.node),
  15022. nextSettingsRect => last =>
  15023. pipe(
  15024. Effect_succeed(toggleSettingsElement),
  15025. Effect_filterOrFail(
  15026. x => null !== x.offsetParent,
  15027. Option_none
  15028. ),
  15029. Effect_map(x => x.getBoundingClientRect()),
  15030. Effect_map(
  15031. x =>
  15032. new DOMRectReadOnly(
  15033. Math.max(
  15034. 0,
  15035. x.right + window.scrollX - 660
  15036. ),
  15037. Math.max(0, x.y + window.scrollY - 395),
  15038. 660,
  15039. Math.min(x.y + window.scrollY, 395)
  15040. )
  15041. ),
  15042. Effect_orElseSucceed(
  15043. () =>
  15044. new DOMRectReadOnly(-660, -395, 660, 395)
  15045. ),
  15046. Effect_filterOrFail(
  15047. x =>
  15048. x.x !== last.x ||
  15049. x.y !== last.y ||
  15050. x.width !== last.width ||
  15051. x.height !== last.height,
  15052. Option_none
  15053. ),
  15054. Effect_tap(nextSettingsRect),
  15055. Effect_ignore
  15056. ))(rect =>
  15057. Effect_sync(() =>
  15058. ctx.settingsRectSubject.next(rect)
  15059. )
  15060. )
  15061. ),
  15062. tapEffect(provideLog),
  15063. (0, external_rxjs_namespaceObject.map)(() => value)
  15064. )
  15065. var toggleSettingsElement
  15066. })(ob),
  15067. config$: pipe(ctx.co, co =>
  15068. (0, external_rxjs_namespaceObject.defer)(() => {
  15069. return (0, external_rxjs_namespaceObject.merge)(
  15070. (0, external_rxjs_namespaceObject.merge)(
  15071. co.bannedWordRegexs,
  15072. co.bannedWords,
  15073. co.bannedUsers
  15074. ),
  15075. pipe(
  15076. co.fieldScale,
  15077. (0, external_rxjs_namespaceObject.startWith)(
  15078. ctx.config.fieldScale
  15079. ),
  15080. (0, external_rxjs_namespaceObject.map)(
  15081. ((live = ctx.live),
  15082. scale =>
  15083. pipe(
  15084. live.chatField.ele,
  15085. Effect_fromOption,
  15086. Effect_flatMap(field =>
  15087. pipe(
  15088. [
  15089. pipe(
  15090. fromNullable(field.parentElement),
  15091. Option_map(x =>
  15092. Effect_sync(() =>
  15093. Object.assign(x.style, {
  15094. transformOrigin:
  15095. (scale >= 1
  15096. ? "top"
  15097. : "bottom") + " left",
  15098. transform: `scale(${scale})`,
  15099. width: 100 / scale + "%",
  15100. height: 100 / scale + "%",
  15101. })
  15102. )
  15103. )
  15104. ),
  15105. pipe(
  15106. live.chatScroller.ele,
  15107. Option_map(scroller =>
  15108. Effect_sync(() => {
  15109. scroller.scrollTop =
  15110. scroller.scrollHeight
  15111. })
  15112. )
  15113. ),
  15114. ],
  15115. ReadonlyArray_compact,
  15116. x => Effect_all(x)
  15117. )
  15118. ),
  15119. Effect_ignore
  15120. ))
  15121. ),
  15122. tapEffect(provideLog)
  15123. ),
  15124. pipe(
  15125. (0, external_rxjs_namespaceObject.merge)(
  15126. pipe(
  15127. (0, external_rxjs_namespaceObject.merge)(
  15128. co.font,
  15129. co.fontSize,
  15130. co.fontWeight,
  15131. co.laneCount,
  15132. co.minSpacing,
  15133. co.flowY1,
  15134. co.flowY2,
  15135. pipe(
  15136. co.flowX1,
  15137. (0,
  15138. external_rxjs_namespaceObject.startWith)(
  15139. ctx.config.flowX1
  15140. ),
  15141. tapEffect(x =>
  15142. provideLog(
  15143. Effect_sync(() =>
  15144. Object.assign(ctx.chatScreen.style, {
  15145. left: 100 * x + "%",
  15146. width:
  15147. 100 * (ctx.config.flowX2 - x) +
  15148. "%",
  15149. })
  15150. )
  15151. )
  15152. )
  15153. ),
  15154. pipe(
  15155. co.flowX2,
  15156. tapEffect(x =>
  15157. provideLog(
  15158. Effect_sync(() =>
  15159. Object.assign(ctx.chatScreen.style, {
  15160. left: 100 * ctx.config.flowX1 + "%",
  15161. width:
  15162. 100 * (x - ctx.config.flowX1) +
  15163. "%",
  15164. })
  15165. )
  15166. )
  15167. )
  15168. ),
  15169. co.textOnly
  15170. ),
  15171. (0, external_rxjs_namespaceObject.map)(() => ({
  15172. render: !0,
  15173. setAnimation: !0,
  15174. }))
  15175. ),
  15176. pipe(
  15177. (0, external_rxjs_namespaceObject.merge)(
  15178. co.color,
  15179. co.ownerColor,
  15180. co.moderatorColor,
  15181. co.memberColor,
  15182. co.shadowColor,
  15183. co.chatOpacity,
  15184. co.shadowFontWeight,
  15185. co.displayChats
  15186. ),
  15187. (0, external_rxjs_namespaceObject.map)(() => ({
  15188. render: !0,
  15189. }))
  15190. ),
  15191. pipe(
  15192. co.flowSpeed,
  15193. (0, external_rxjs_namespaceObject.map)(() => ({
  15194. setPlayState: !0,
  15195. }))
  15196. ),
  15197. pipe(
  15198. (0, external_rxjs_namespaceObject.merge)(
  15199. pipe(
  15200. co.maxChatCount,
  15201. (0, external_rxjs_namespaceObject.map)(
  15202. removeOldChats(ctx.flowChats)
  15203. ),
  15204. tapEffect(provideLog)
  15205. ),
  15206. co.noOverlap,
  15207. co.timingFunction
  15208. ),
  15209. (0, external_rxjs_namespaceObject.map)(() => ({
  15210. setAnimation: !0,
  15211. }))
  15212. )
  15213. ),
  15214. (0, external_rxjs_namespaceObject.throttleTime)(
  15215. 180,
  15216. void 0,
  15217. { leading: !0, trailing: !0 }
  15218. ),
  15219. (0, external_rxjs_namespaceObject.map)(x => ({
  15220. render: !1,
  15221. setAnimation: !1,
  15222. setPlayState: !1,
  15223. ...x,
  15224. })),
  15225. tapEffect(config =>
  15226. provideLog(
  15227. pipe(
  15228. ctx.flowChats,
  15229. ReadonlyArray_filter(x => !x.animationEnded),
  15230. ReadonlyArray_map(chat =>
  15231. pipe(
  15232. [
  15233. pipe(
  15234. renderChat(chat),
  15235. liftPredicate(() => config.render)
  15236. ),
  15237. config.setAnimation
  15238. ? Option_some(
  15239. setChatAnimation(
  15240. chat,
  15241. ctx.flowChats
  15242. )
  15243. )
  15244. : config.setPlayState
  15245. ? Option_some(setChatPlayState(chat))
  15246. : Option_none(),
  15247. ],
  15248. ReadonlyArray_compact,
  15249. ReadonlyArray_map(apply(ctx.mainState)),
  15250. x => Effect_all(x)
  15251. )
  15252. ),
  15253. x => Effect_all(x),
  15254. Effect_asUnit
  15255. )
  15256. )
  15257. )
  15258. ),
  15259. pipe(
  15260. co.lang,
  15261. tapEffect(lang =>
  15262. ctx.updateSettingState(x => ({ ...x, lang }))
  15263. )
  15264. ),
  15265. co.maxChatLength,
  15266. co.simplifyChatField,
  15267. co.createBanButton,
  15268. co.createChats,
  15269. co.displayModName,
  15270. co.displaySuperChatAuthor,
  15271. co.fieldScale,
  15272. pipe(
  15273. (0, external_rxjs_namespaceObject.merge)(
  15274. co.bannedWords,
  15275. co.bannedWordRegexs,
  15276. co.bannedUsers
  15277. ),
  15278. tapEffect(() =>
  15279. ctx.setConfig.filterExp(defaultFilter(ctx.config))
  15280. )
  15281. )
  15282. )
  15283. var live
  15284. })
  15285. ),
  15286. },
  15287. Effect_succeed,
  15288. Effect_bind("css", () => mainCss),
  15289. Effect_bind("documentMutationPair", () =>
  15290. observePair(MutationObserver)
  15291. ),
  15292. Effect_bind("chatMutationPair", () =>
  15293. observePair(MutationObserver)
  15294. ),
  15295. Effect_bind("playerResizePair", () =>
  15296. observePair(ResizeObserver)
  15297. ),
  15298. Effect_bind("bodyResizePair", () =>
  15299. observePair(ResizeObserver)
  15300. ),
  15301. Effect_map(c =>
  15302. pipe(
  15303. ctx.reinitSubject,
  15304. (0, external_rxjs_namespaceObject.observeOn)(
  15305. external_rxjs_namespaceObject.asyncScheduler
  15306. ),
  15307. (0, external_rxjs_namespaceObject.delay)(c.initDelay),
  15308. tapEffect(() => provideLog(Effect_logInfo("Init"))),
  15309. (0, external_rxjs_namespaceObject.switchMap)(() =>
  15310. pipe(
  15311. (0, external_rxjs_namespaceObject.interval)(
  15312. c.changeDetectInterval
  15313. ),
  15314. c.tapUpdateSettingsRect,
  15315. (0, external_rxjs_namespaceObject.concatMap)(index =>
  15316. pipe(
  15317. (0, external_rxjs_namespaceObject.from)(
  15318. runPromise(
  15319. pipe(
  15320. c.liveElementKeys,
  15321. ReadonlyArray_map(key =>
  15322. pipe(
  15323. ctx.live[key],
  15324. x => x.read,
  15325. Effect_unsome,
  15326. Effect_map(
  15327. liftPredicate(
  15328. newEle =>
  15329. !c.eq(ctx.live[key].ele, newEle)
  15330. )
  15331. ),
  15332. Effect_map(
  15333. Option_map(
  15334. flow(
  15335. Effect_succeed,
  15336. Effect_tap(x =>
  15337. Effect_sync(() => {
  15338. ctx.live[key].ele = x
  15339. })
  15340. ),
  15341. Effect_map(Option_isSome),
  15342. Effect_map(
  15343. x =>
  15344. `${key} ${
  15345. x ? "found" : "lost"
  15346. }`
  15347. ),
  15348. Effect_flatMap(Effect_logInfo)
  15349. )
  15350. )
  15351. ),
  15352. Effect_flatMap(
  15353. match(
  15354. () => Effect_succeed(!1),
  15355. Effect_zipRight(Effect_succeed(!0))
  15356. )
  15357. )
  15358. )
  15359. ),
  15360. x => Effect_all(x),
  15361. Effect_map(
  15362. ReadonlyArray_some(Function_identity)
  15363. )
  15364. )
  15365. )
  15366. ),
  15367. (0, external_rxjs_namespaceObject.filter)(
  15368. Function_identity
  15369. ),
  15370. (0, external_rxjs_namespaceObject.map)(
  15371. () => index
  15372. )
  15373. )
  15374. ),
  15375. (0, external_rxjs_namespaceObject.startWith)(0)
  15376. )
  15377. ),
  15378. tapEffect(() =>
  15379. provideLog(
  15380. pipe(
  15381. Effect_logInfo("Loading..."),
  15382. Effect_zipRight(removeOldChats(ctx.flowChats)(0)),
  15383. Effect_zipRight(
  15384. Effect_sync(() => {
  15385. c.documentMutationPair.observer.disconnect()
  15386. c.documentMutationPair.observer.observe(
  15387. document,
  15388. { childList: !0, subtree: !0 }
  15389. )
  15390. c.chatMutationPair.observer.disconnect()
  15391. c.playerResizePair.observer.disconnect()
  15392. c.bodyResizePair.observer.disconnect()
  15393. document.head.append(c.css)
  15394. })
  15395. ),
  15396. Effect_zipRight(
  15397. pipe(
  15398. [
  15399. pipe(
  15400. ctx.live.chatField.ele,
  15401. Option_map(x =>
  15402. Effect_sync(() =>
  15403. c.chatMutationPair.observer.observe(x, {
  15404. childList: !0,
  15405. })
  15406. )
  15407. )
  15408. ),
  15409. pipe(
  15410. ctx.live.chatTicker.ele,
  15411. Option_map(x =>
  15412. Effect_sync(() =>
  15413. c.chatMutationPair.observer.observe(x, {
  15414. childList: !0,
  15415. })
  15416. )
  15417. )
  15418. ),
  15419. pipe(
  15420. ctx.live.player.ele,
  15421. Option_map(
  15422. flow(
  15423. Effect_succeed,
  15424. Effect_tap(x =>
  15425. Effect_sync(() =>
  15426. c.playerResizePair.observer.observe(
  15427. x
  15428. )
  15429. )
  15430. ),
  15431. Effect_flatMap(x =>
  15432. Effect_sync(() =>
  15433. x.prepend(ctx.chatScreen)
  15434. )
  15435. )
  15436. )
  15437. )
  15438. ),
  15439. pipe(
  15440. ctx.live.toggleChatBtnParent.ele,
  15441. Option_map(x =>
  15442. Effect_sync(() =>
  15443. x.prepend(ctx.wrappedToggleChat.node)
  15444. )
  15445. )
  15446. ),
  15447. pipe(
  15448. ctx.live.settingsToggleNextElement.ele,
  15449. Option_map(x =>
  15450. Effect_sync(() =>
  15451. x.before(ctx.wrappedToggleSettings.node)
  15452. )
  15453. )
  15454. ),
  15455. pipe(
  15456. ctx.live.settingsContainer.ele,
  15457. Option_map(x =>
  15458. Effect_sync(() =>
  15459. x.append(ctx.wrappedSettings.node)
  15460. )
  15461. )
  15462. ),
  15463. pipe(
  15464. document.body,
  15465. fromNullable,
  15466. Option_map(x =>
  15467. Effect_sync(() =>
  15468. c.bodyResizePair.observer.observe(x)
  15469. )
  15470. )
  15471. ),
  15472. ],
  15473. ReadonlyArray_compact,
  15474. append(
  15475. pipe(
  15476. ctx.live.video.ele,
  15477. Option_filter(x => !x.paused),
  15478. orElse(() => ctx.live.offlineSlate.ele),
  15479. Option_isSome,
  15480. x =>
  15481. Effect_sync(() => {
  15482. Object.assign(ctx.mainState, {
  15483. chatPlaying: x,
  15484. })
  15485. })
  15486. )
  15487. ),
  15488. x => Effect_all(x)
  15489. )
  15490. )
  15491. )
  15492. )
  15493. ),
  15494. (0, external_rxjs_namespaceObject.switchMap)(() =>
  15495. (0, external_rxjs_namespaceObject.merge)(
  15496. pipe(
  15497. (0, external_rxjs_namespaceObject.fromEvent)(
  15498. ctx.channel,
  15499. "message"
  15500. ),
  15501. (0, external_rxjs_namespaceObject.map)(
  15502. ([key, val]) =>
  15503. pipe(
  15504. src_listeningBroadcastConfigKeys.includes(
  15505. key
  15506. ),
  15507. x =>
  15508. x
  15509. ? ctx.setChangedConfig[key](val)
  15510. : Effect_sync(() => {})
  15511. )
  15512. ),
  15513. tapEffect(provideLog)
  15514. ),
  15515. ...pipe(
  15516. ctx.configKeys,
  15517. ReadonlyArray_map(key =>
  15518. pipe(
  15519. ctx.co[key],
  15520. (0, external_rxjs_namespaceObject.startWith)(
  15521. ctx.config[key]
  15522. ),
  15523. (0, external_rxjs_namespaceObject.bufferCount)(
  15524. 2,
  15525. 1
  15526. ),
  15527. (0, external_rxjs_namespaceObject.map)(
  15528. ([x, y]) =>
  15529. (0, external_DeepDiff_namespaceObject.diff)(
  15530. x,
  15531. y
  15532. )
  15533. ),
  15534. (0, external_rxjs_namespaceObject.map)(x =>
  15535. Effect_logDebug(
  15536. `Config ${key}: ${JSON.stringify(
  15537. x,
  15538. void 0,
  15539. 2
  15540. )}`
  15541. )
  15542. ),
  15543. tapEffect(provideLog)
  15544. )
  15545. )
  15546. ),
  15547. c.config$,
  15548. pipe(
  15549. ctx.live.video.ele,
  15550. match(
  15551. () => external_rxjs_namespaceObject.EMPTY,
  15552. flow(
  15553. videoToggleStream,
  15554. (0, external_rxjs_namespaceObject.map)(
  15555. playing =>
  15556. playing ||
  15557. Option_isSome(ctx.live.offlineSlate.ele)
  15558. ),
  15559. (0, external_rxjs_namespaceObject.map)(
  15560. chatPlaying =>
  15561. pipe(
  15562. Effect_sync(() => {
  15563. ctx.mainState.chatPlaying = chatPlaying
  15564. }),
  15565. Effect_zipRight(
  15566. pipe(
  15567. ctx.flowChats,
  15568. ReadonlyArray_map(setChatPlayState),
  15569. ReadonlyArray_map(
  15570. apply(ctx.mainState)
  15571. ),
  15572. x => Effect_all(x)
  15573. )
  15574. )
  15575. )
  15576. ),
  15577. tapEffect(provideLog)
  15578. )
  15579. )
  15580. ),
  15581. pipe(
  15582. c.chatMutationPair.subject,
  15583. (0, external_rxjs_namespaceObject.map)(
  15584. onChatFieldMutate(
  15585. ctx.chatScreen,
  15586. ctx.flowChats,
  15587. ctx.mainState,
  15588. ctx.getConfig,
  15589. ctx.setConfig
  15590. )
  15591. ),
  15592. tapEffect(provideLog)
  15593. ),
  15594. pipe(
  15595. c.documentMutationPair.subject,
  15596. (0, external_rxjs_namespaceObject.map)(
  15597. () => window.location.href
  15598. ),
  15599. (0,
  15600. external_rxjs_namespaceObject.distinctUntilChanged)(),
  15601. (0, external_rxjs_namespaceObject.skip)(1),
  15602. c.tapUpdateSettingsRect,
  15603. (0, external_rxjs_namespaceObject.map)(x =>
  15604. Effect_all([
  15605. Effect_logInfo(`URL Changed: ${x}`),
  15606. removeOldChats(ctx.flowChats)(0),
  15607. Effect_logInfo(`Wait for ${c.urlDelay}ms...`),
  15608. ])
  15609. ),
  15610. tapEffect(provideLog),
  15611. (0, external_rxjs_namespaceObject.delay)(
  15612. c.urlDelay
  15613. ),
  15614. tapEffect(() => ctx.reinitialize)
  15615. ),
  15616. pipe(
  15617. c.playerResizePair.subject,
  15618. (0, external_rxjs_namespaceObject.throttleTime)(
  15619. 500,
  15620. void 0,
  15621. { leading: !0, trailing: !0 }
  15622. ),
  15623. (0, external_rxjs_namespaceObject.startWith)([]),
  15624. (0, external_rxjs_namespaceObject.map)(
  15625. () => ctx.live.player.ele
  15626. ),
  15627. (0, external_rxjs_namespaceObject.map)(
  15628. Option_map(x => x.getBoundingClientRect())
  15629. ),
  15630. tapEffect(x => {
  15631. return provideLog(
  15632. ((rect = x),
  15633. (flowChats = ctx.flowChats),
  15634. (mainState = ctx.mainState),
  15635. pipe(
  15636. rect,
  15637. Effect_fromOption,
  15638. Effect_flatMap(
  15639. flow(
  15640. x =>
  15641. Effect_sync(() =>
  15642. Object.assign(mainState, {
  15643. playerRect: x,
  15644. })
  15645. ),
  15646. Effect_map(() => flowChats),
  15647. Effect_map(
  15648. ReadonlyArray_flatMap(x => [
  15649. renderChat(x)(mainState),
  15650. setChatAnimation(
  15651. x,
  15652. flowChats
  15653. )(mainState),
  15654. ])
  15655. ),
  15656. Effect_flatMap(x => Effect_all(x)),
  15657. Effect_zipLeft(
  15658. Effect_logInfo("Resize detected")
  15659. )
  15660. )
  15661. ),
  15662. Effect_ignore
  15663. ))
  15664. )
  15665. var rect, flowChats, mainState
  15666. })
  15667. ),
  15668. pipe(
  15669. c.bodyResizePair.subject,
  15670. (0, external_rxjs_namespaceObject.throttleTime)(
  15671. c.bodyResizeDetectInterval,
  15672. void 0,
  15673. { leading: !0, trailing: !0 }
  15674. ),
  15675. (0, external_rxjs_namespaceObject.startWith)([]),
  15676. c.tapUpdateSettingsRect
  15677. ),
  15678. pipe(
  15679. ctx.settingsRectSubject,
  15680. tapEffect(panelRect =>
  15681. ctx.updateSettingState(s => ({ ...s, panelRect }))
  15682. )
  15683. )
  15684. )
  15685. ),
  15686. (0, external_rxjs_namespaceObject.retry)({
  15687. delay: e =>
  15688. pipe(
  15689. e,
  15690. external_rxjs_namespaceObject.of,
  15691. tapEffect(() =>
  15692. provideLog(
  15693. logWithMeta(Level_Error)(`Errored: ${e}`)(e)
  15694. )
  15695. ),
  15696. (0, external_rxjs_namespaceObject.delay)(
  15697. c.errorRetryInterval
  15698. ),
  15699. tapEffect(() => ctx.reinitialize)
  15700. ),
  15701. })
  15702. )
  15703. )
  15704. )
  15705. var E
  15706. }),
  15707. Effect_tap(ctx =>
  15708. Effect_sync(() =>
  15709. ctx.all$.subscribe({
  15710. error: x =>
  15711. runPromise(
  15712. pipe(
  15713. logWithMeta(Level_Error)(`Stream Errored: ${x}`)(x)
  15714. )
  15715. ),
  15716. complete: () =>
  15717. runPromise(Effect_logInfo("Stream complete")),
  15718. })
  15719. )
  15720. ),
  15721. Effect_tap(ctx => ctx.reinitialize)
  15722. )
  15723. )
  15724. )
  15725. )
  15726. )
  15727. })()
  15728. })()