Flow Youtube Chat

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

当前为 2023-04-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Flow Youtube Chat
  3. // @description Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.
  4. // @version 1.16.1
  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.7.3/dist/sweetalert2.all.min.js#sha384-/Wx1NuqlgALfa1Do1U6Mer7quEDHOo8REf/0izoIrV8Y3Z/gtEHQc01STCEMM1LZ
  15. // @require https://unpkg.com/loglevel@1.8.1/dist/loglevel.min.js#sha384-Xv9RQU8lNizXGKl6BAyZjpzyUqh9/tgSO1XVnCQMy11vKJ/eBu6aCEf88WqGwElT
  16. // @require https://unpkg.com/rxjs@7.8.0/dist/bundles/rxjs.umd.min.js#sha384-jmg+DzMpc702jevWhETvz7gFleL89oF07xs35HZcjTuKhYi8znKw4fKQOi5EUQo9
  17. // @require https://unpkg.com/mithril@2.2.2/mithril.min.js#sha384-60kek02kUAH+DNSgj7HCtrpcirTroG3uWnDpsdvoAl2Z9Xe3GdpXDSy4ouNMHoBZ
  18. // @require https://cdn.jsdelivr.net/npm/deep-diff@1.0.2/index.min.js#sha384-Q/uiWfFlwn9XjOpL49VpFKn01EkScmaC3hh1prAn7S++WoZgXRrrjQvZ7cI7C7Zn
  19. // @require https://cdn.jsdelivr.net/npm/astring@1.8.4/dist/astring.min.js#sha384-WfNZenKd6kEjcIYQ2WtJNczMVjVwKo5RAxGNdUnNHQjqLKMcDl1pAZT5Jqsp9raN
  20. // @require https://cdn.jsdelivr.net/npm/jsep@1.3.8/dist/iife/jsep.iife.min.js#sha384-+qoPWZXQFfQjGhA9c2VU3zim4HqVm3e0uUJfnGXUp4sw3jolc2fsQ1bqEo1yOics
  21. // @require https://cdn.jsdelivr.net/npm/hash-it@6.0.0/dist/min/index.js#sha384-kqUFMXizyaodUGfm0UszFxndXukhSB/yEpOt+q9w/RgjyOK0wz9gXoEYb2FW1/ex
  22. // @require https://cdn.jsdelivr.net/npm/micro-memoize@4.0.14/dist/micro-memoize.min.js#sha384-W1hqD6GTNQ97ZqDR18GhfU1G9qcDLs4sL7BPYND2ncvGNNiLUmUp37Ph+hzm+OPt
  23. // @require https://cdn.jsdelivr.net/npm/lz-string@1.5.0/libs/lz-string.min.js#sha384-0d+Gr7vM4Drod8E3hXKgciWJSWbjD/opKLLygI9ktiWbuvlDwQLzU46wJ9s5gsp7
  24. // @run-at document-end
  25. // ==/UserScript==
  26.  
  27. /* jshint esversion: 6 */
  28.  
  29. ;(() => {
  30. var __webpack_modules__ = {
  31. 204: module => {
  32. "use strict"
  33. module.exports = function equal(a, b) {
  34. if (a === b) return !0
  35. if (a && b && "object" == typeof a && "object" == typeof b) {
  36. if (a.constructor !== b.constructor) return !1
  37. var length, i, keys
  38. if (Array.isArray(a)) {
  39. if ((length = a.length) != b.length) return !1
  40. for (i = length; 0 != i--; ) if (!equal(a[i], b[i])) return !1
  41. return !0
  42. }
  43. if (a.constructor === RegExp)
  44. return a.source === b.source && a.flags === b.flags
  45. if (a.valueOf !== Object.prototype.valueOf)
  46. return a.valueOf() === b.valueOf()
  47. if (a.toString !== Object.prototype.toString)
  48. return a.toString() === b.toString()
  49. if (
  50. (length = (keys = Object.keys(a)).length) !==
  51. Object.keys(b).length
  52. )
  53. return !1
  54. for (i = length; 0 != i--; )
  55. if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return !1
  56. for (i = length; 0 != i--; ) {
  57. var key = keys[i]
  58. if (!equal(a[key], b[key])) return !1
  59. }
  60. return !0
  61. }
  62. return a != a && b != b
  63. }
  64. },
  65. 52: (__unused_webpack_module, exports) => {
  66. "use strict"
  67. exports.Xd = exports.hu = exports.tE = void 0
  68. const expectedToBe = type => `expected to be ${type}`
  69. exports.tE = (condition, message) => {
  70. if (!condition) throw new TypeError(message)
  71. }
  72. let baseAssert = exports.tE
  73. exports.hu = (condition, message) => baseAssert(condition, message)
  74. exports.Xd = function (
  75. input,
  76. message = expectedToBe("neither null nor undefined")
  77. ) {
  78. ;(0, exports.hu)(null != input, message)
  79. }
  80. },
  81. 694: module => {
  82. module.exports = (function (e) {
  83. var r = {}
  84. function t(n) {
  85. if (r[n]) return r[n].exports
  86. var a = (r[n] = { i: n, l: !1, exports: {} })
  87. return e[n].call(a.exports, a, a.exports, t), (a.l = !0), a.exports
  88. }
  89. return (
  90. (t.m = e),
  91. (t.c = r),
  92. (t.d = function (e, r, n) {
  93. t.o(e, r) ||
  94. Object.defineProperty(e, r, { enumerable: !0, get: n })
  95. }),
  96. (t.r = function (e) {
  97. "undefined" != typeof Symbol &&
  98. Symbol.toStringTag &&
  99. Object.defineProperty(e, Symbol.toStringTag, {
  100. value: "Module",
  101. }),
  102. Object.defineProperty(e, "__esModule", { value: !0 })
  103. }),
  104. (t.t = function (e, r) {
  105. if ((1 & r && (e = t(e)), 8 & r)) return e
  106. if (4 & r && "object" == typeof e && e && e.__esModule) return e
  107. var n = Object.create(null)
  108. if (
  109. (t.r(n),
  110. Object.defineProperty(n, "default", {
  111. enumerable: !0,
  112. value: e,
  113. }),
  114. 2 & r && "string" != typeof e)
  115. )
  116. for (var a in e)
  117. t.d(
  118. n,
  119. a,
  120. function (r) {
  121. return e[r]
  122. }.bind(null, a)
  123. )
  124. return n
  125. }),
  126. (t.n = function (e) {
  127. var r =
  128. e && e.__esModule
  129. ? function () {
  130. return e.default
  131. }
  132. : function () {
  133. return e
  134. }
  135. return t.d(r, "a", r), r
  136. }),
  137. (t.o = function (e, r) {
  138. return Object.prototype.hasOwnProperty.call(e, r)
  139. }),
  140. (t.p = ""),
  141. t((t.s = 0))
  142. )
  143. })([
  144. function (e, r, t) {
  145. "use strict"
  146. t.r(r),
  147. t.d(r, "validateHTMLColorName", function () {
  148. return l
  149. }),
  150. t.d(r, "validateHTMLColorSpecialName", function () {
  151. return i
  152. }),
  153. t.d(r, "validateHTMLColorHex", function () {
  154. return u
  155. }),
  156. t.d(r, "validateHTMLColorRgb", function () {
  157. return g
  158. }),
  159. t.d(r, "validateHTMLColorHsl", function () {
  160. return y
  161. }),
  162. t.d(r, "validateHTMLColorHwb", function () {
  163. return L
  164. }),
  165. t.d(r, "validateHTMLColorLab", function () {
  166. return S
  167. }),
  168. t.d(r, "validateHTMLColorLch", function () {
  169. return m
  170. }),
  171. t.d(r, "validateHTMLColor", function () {
  172. return G
  173. })
  174. const n = e => e && "string" == typeof e,
  175. a = [
  176. "AliceBlue",
  177. "AntiqueWhite",
  178. "Aqua",
  179. "Aquamarine",
  180. "Azure",
  181. "Beige",
  182. "Bisque",
  183. "Black",
  184. "BlanchedAlmond",
  185. "Blue",
  186. "BlueViolet",
  187. "Brown",
  188. "BurlyWood",
  189. "CadetBlue",
  190. "Chartreuse",
  191. "Chocolate",
  192. "Coral",
  193. "CornflowerBlue",
  194. "Cornsilk",
  195. "Crimson",
  196. "Cyan",
  197. "DarkBlue",
  198. "DarkCyan",
  199. "DarkGoldenrod",
  200. "DarkGray",
  201. "DarkGrey",
  202. "DarkGreen",
  203. "DarkKhaki",
  204. "DarkMagenta",
  205. "DarkOliveGreen",
  206. "DarkOrange",
  207. "DarkOrchid",
  208. "DarkRed",
  209. "DarkSalmon",
  210. "DarkSeaGreen",
  211. "DarkSlateBlue",
  212. "DarkSlateGray",
  213. "DarkSlateGrey",
  214. "DarkTurquoise",
  215. "DarkViolet",
  216. "DeepPink",
  217. "DeepSkyBlue",
  218. "DimGray",
  219. "DimGrey",
  220. "DodgerBlue",
  221. "FireBrick",
  222. "FloralWhite",
  223. "ForestGreen",
  224. "Fuchsia",
  225. "Gainsboro",
  226. "GhostWhite",
  227. "Gold",
  228. "Goldenrod",
  229. "Gray",
  230. "Grey",
  231. "Green",
  232. "GreenYellow",
  233. "HoneyDew",
  234. "HotPink",
  235. "IndianRed",
  236. "Indigo",
  237. "Ivory",
  238. "Khaki",
  239. "Lavender",
  240. "LavenderBlush",
  241. "LawnGreen",
  242. "LemonChiffon",
  243. "LightBlue",
  244. "LightCoral",
  245. "LightCyan",
  246. "LightGoldenrodYellow",
  247. "LightGray",
  248. "LightGrey",
  249. "LightGreen",
  250. "LightPink",
  251. "LightSalmon",
  252. "LightSalmon",
  253. "LightSeaGreen",
  254. "LightSkyBlue",
  255. "LightSlateGray",
  256. "LightSlateGrey",
  257. "LightSteelBlue",
  258. "LightYellow",
  259. "Lime",
  260. "LimeGreen",
  261. "Linen",
  262. "Magenta",
  263. "Maroon",
  264. "MediumAquamarine",
  265. "MediumBlue",
  266. "MediumOrchid",
  267. "MediumPurple",
  268. "MediumSeaGreen",
  269. "MediumSlateBlue",
  270. "MediumSlateBlue",
  271. "MediumSpringGreen",
  272. "MediumTurquoise",
  273. "MediumVioletRed",
  274. "MidnightBlue",
  275. "MintCream",
  276. "MistyRose",
  277. "Moccasin",
  278. "NavajoWhite",
  279. "Navy",
  280. "OldLace",
  281. "Olive",
  282. "OliveDrab",
  283. "Orange",
  284. "OrangeRed",
  285. "Orchid",
  286. "PaleGoldenrod",
  287. "PaleGreen",
  288. "PaleTurquoise",
  289. "PaleVioletRed",
  290. "PapayaWhip",
  291. "PeachPuff",
  292. "Peru",
  293. "Pink",
  294. "Plum",
  295. "PowderBlue",
  296. "Purple",
  297. "RebeccaPurple",
  298. "Red",
  299. "RosyBrown",
  300. "RoyalBlue",
  301. "SaddleBrown",
  302. "Salmon",
  303. "SandyBrown",
  304. "SeaGreen",
  305. "SeaShell",
  306. "Sienna",
  307. "Silver",
  308. "SkyBlue",
  309. "SlateBlue",
  310. "SlateGray",
  311. "SlateGrey",
  312. "Snow",
  313. "SpringGreen",
  314. "SteelBlue",
  315. "Tan",
  316. "Teal",
  317. "Thistle",
  318. "Tomato",
  319. "Turquoise",
  320. "Violet",
  321. "Wheat",
  322. "White",
  323. "WhiteSmoke",
  324. "Yellow",
  325. "YellowGreen",
  326. ],
  327. o = ["currentColor", "inherit", "transparent"],
  328. l = e => {
  329. let r = !1
  330. return (
  331. n(e) &&
  332. a.map(
  333. t => (
  334. e.toLowerCase() === t.toLowerCase() && (r = !0), null
  335. )
  336. ),
  337. r
  338. )
  339. },
  340. i = e => {
  341. let r = !1
  342. return (
  343. n(e) &&
  344. o.map(
  345. t => (
  346. e.toLowerCase() === t.toLowerCase() && (r = !0), null
  347. )
  348. ),
  349. r
  350. )
  351. },
  352. u = e =>
  353. !!n(e) &&
  354. e &&
  355. /^#([\da-f]{3}){1,2}$|^#([\da-f]{4}){1,2}$/i.test(e),
  356. d = "(([\\d]{0,5})((\\.([\\d]{1,5}))?))",
  357. s = `(${d}%)`,
  358. c = "(([0-9]|[1-9][0-9]|100)%)",
  359. f = `(${c}|(0?((\\.([\\d]{1,5}))?))|1)`,
  360. h = `([\\s]{0,5})\\)?)(([\\s]{0,5})(\\/?)([\\s]{1,5})(((${c}))|(0?((\\.([\\d]{1,5}))?))|1))?([\\s]{0,5})\\)`,
  361. $ =
  362. "(-?(([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)?)",
  363. g = e => {
  364. if (n(e)) {
  365. const r = "([\\s]{0,5})([\\d]{1,5})%?([\\s]{0,5}),?",
  366. t = "((([\\s]{0,5}),?([\\s]{0,5}))|(([\\s]{1,5})))",
  367. n = new RegExp(
  368. `^(rgb)a?\\(${r}${t}${r}${t}${r}${t}((\\/?([\\s]{0,5})(0?\\.?([\\d]{1,5})%?([\\s]{0,5}))?|1|0))?\\)$`
  369. )
  370. return e && n.test(e)
  371. }
  372. return !1
  373. },
  374. y = e => {
  375. if (n(e)) {
  376. const r = new RegExp(
  377. `^(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))?\\)$`
  378. )
  379. return e && r.test(e)
  380. }
  381. return !1
  382. },
  383. L = e => {
  384. if (n(e)) {
  385. const r = new RegExp(
  386. `^(hwb\\(([\\s]{0,5})${$}([\\s]{1,5}))((0|${c})([\\s]{1,5}))((0|${c})${h}$`
  387. )
  388. return e && r.test(e)
  389. }
  390. return !1
  391. },
  392. S = e => {
  393. if (n(e)) {
  394. const r =
  395. "(-?(([0-9]|[1-9][0-9]|1[0-5][0-9])((\\.([\\d]{1,5}))?)?|160))",
  396. t = new RegExp(
  397. `^(lab\\(([\\s]{0,5})${s}([\\s]{1,5})${r}([\\s]{1,5})${r}${h}$`
  398. )
  399. return e && t.test(e)
  400. }
  401. return !1
  402. },
  403. m = e => {
  404. if (n(e)) {
  405. const o = new RegExp(
  406. `^lch\\((([\\s]{0,5})((([0-9]|[1-9][0-9])?((\\.([\\d]{1,5}))?)|100)(%)?)([\\s]{1,5})${
  407. "" + d
  408. }([\\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}))?)\\)$`
  409. )
  410. return e && o.test(e)
  411. }
  412. return !1
  413. },
  414. G = e => !!((e && u(e)) || g(e) || y(e) || L(e) || S(e) || m(e))
  415. r.default = e =>
  416. !!(
  417. (e && u(e)) ||
  418. l(e) ||
  419. i(e) ||
  420. g(e) ||
  421. y(e) ||
  422. L(e) ||
  423. S(e) ||
  424. m(e)
  425. )
  426. },
  427. ])
  428. },
  429. },
  430. __webpack_module_cache__ = {}
  431. function __webpack_require__(moduleId) {
  432. var cachedModule = __webpack_module_cache__[moduleId]
  433. if (void 0 !== cachedModule) return cachedModule.exports
  434. var module = (__webpack_module_cache__[moduleId] = { exports: {} })
  435. __webpack_modules__[moduleId](module, module.exports, __webpack_require__)
  436. return module.exports
  437. }
  438. __webpack_require__.n = module => {
  439. var getter =
  440. module && module.__esModule ? () => module.default : () => module
  441. __webpack_require__.d(getter, { a: getter })
  442. return getter
  443. }
  444. __webpack_require__.d = (exports, definition) => {
  445. for (var key in definition)
  446. __webpack_require__.o(definition, key) &&
  447. !__webpack_require__.o(exports, key) &&
  448. Object.defineProperty(exports, key, {
  449. enumerable: !0,
  450. get: definition[key],
  451. })
  452. }
  453. __webpack_require__.o = (obj, prop) =>
  454. Object.prototype.hasOwnProperty.call(obj, prop)
  455. ;(() => {
  456. "use strict"
  457. const Function_dual = (arity, body) => {
  458. const isDataFirst =
  459. "number" == typeof arity ? args => args.length >= arity : arity
  460. return function () {
  461. return isDataFirst(arguments)
  462. ? body.apply(this, arguments)
  463. : self => body(self, ...arguments)
  464. }
  465. },
  466. apply = a => self => self(a),
  467. Function_identity = a => a,
  468. constant = value => () => value,
  469. Function_constTrue = constant(!0),
  470. Function_constFalse = constant(!1),
  471. Function_constUndefined = constant(void 0),
  472. Function_constVoid = Function_constUndefined,
  473. flip =
  474. f =>
  475. (...b) =>
  476. (...a) =>
  477. f(...a)(...b)
  478. function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {
  479. switch (arguments.length) {
  480. case 1:
  481. return ab
  482. case 2:
  483. return function () {
  484. return bc(ab.apply(this, arguments))
  485. }
  486. case 3:
  487. return function () {
  488. return cd(bc(ab.apply(this, arguments)))
  489. }
  490. case 4:
  491. return function () {
  492. return de(cd(bc(ab.apply(this, arguments))))
  493. }
  494. case 5:
  495. return function () {
  496. return ef(de(cd(bc(ab.apply(this, arguments)))))
  497. }
  498. case 6:
  499. return function () {
  500. return fg(ef(de(cd(bc(ab.apply(this, arguments))))))
  501. }
  502. case 7:
  503. return function () {
  504. return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))
  505. }
  506. case 8:
  507. return function () {
  508. return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))))
  509. }
  510. case 9:
  511. return function () {
  512. return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))))
  513. }
  514. }
  515. }
  516. function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
  517. switch (arguments.length) {
  518. case 1:
  519. return a
  520. case 2:
  521. return ab(a)
  522. case 3:
  523. return bc(ab(a))
  524. case 4:
  525. return cd(bc(ab(a)))
  526. case 5:
  527. return de(cd(bc(ab(a))))
  528. case 6:
  529. return ef(de(cd(bc(ab(a)))))
  530. case 7:
  531. return fg(ef(de(cd(bc(ab(a))))))
  532. case 8:
  533. return gh(fg(ef(de(cd(bc(ab(a)))))))
  534. case 9:
  535. return hi(gh(fg(ef(de(cd(bc(ab(a))))))))
  536. default: {
  537. let ret = arguments[0]
  538. for (let i = 1; i < arguments.length; i++) ret = arguments[i](ret)
  539. return ret
  540. }
  541. }
  542. }
  543. const imap = map => Function_dual(3, (self, to, _) => map(self, to)),
  544. let_ = F =>
  545. Function_dual(3, (self, name, f) =>
  546. F.map(self, a => Object.assign({}, a, { [name]: f(a) }))
  547. ),
  548. letDiscard = F =>
  549. Function_dual(3, (self, name, b) =>
  550. F.map(self, a => Object.assign({}, a, { [name]: b }))
  551. ),
  552. globalStoreId = Symbol.for("@effect/data/Global/globalStoreId")
  553. globalStoreId in globalThis || (globalThis[globalStoreId] = new Map())
  554. const globalStore = globalThis[globalStoreId],
  555. globalValue = (id, compute) => {
  556. globalStore.has(id) || globalStore.set(id, compute())
  557. return globalStore.get(id)
  558. }
  559. function isNothing(value) {
  560. return null == value
  561. }
  562. class PCGRandom {
  563. constructor(seedHi, seedLo, incHi, incLo) {
  564. if (isNothing(seedLo) && isNothing(seedHi)) {
  565. seedLo = (4294967295 * Math.random()) >>> 0
  566. seedHi = 0
  567. } else if (isNothing(seedLo)) {
  568. seedLo = seedHi
  569. seedHi = 0
  570. }
  571. if (isNothing(incLo) && isNothing(incHi)) {
  572. incLo = this._state ? this._state[3] : 4150755663
  573. incHi = this._state ? this._state[2] : 335903614
  574. } else if (isNothing(incLo)) {
  575. incLo = incHi
  576. incHi = 0
  577. }
  578. this._state = new Int32Array([
  579. 0,
  580. 0,
  581. incHi >>> 0,
  582. (1 | (incLo || 0)) >>> 0,
  583. ])
  584. this._next()
  585. add64(
  586. this._state,
  587. this._state[0],
  588. this._state[1],
  589. seedHi >>> 0,
  590. seedLo >>> 0
  591. )
  592. this._next()
  593. return this
  594. }
  595. getState() {
  596. return [this._state[0], this._state[1], this._state[2], this._state[3]]
  597. }
  598. setState(state) {
  599. this._state[0] = state[0]
  600. this._state[1] = state[1]
  601. this._state[2] = state[2]
  602. this._state[3] = 1 | state[3]
  603. }
  604. integer(max) {
  605. if (!max) return this._next()
  606. if (0 == ((max >>>= 0) & (max - 1))) return this._next() & (max - 1)
  607. let num = 0
  608. const skew = (-max >>> 0) % max >>> 0
  609. for (num = this._next(); num < skew; num = this._next());
  610. return num % max
  611. }
  612. number() {
  613. return (
  614. (1 * (67108863 & this._next()) * 134217728 +
  615. 1 * (134217727 & this._next())) /
  616. 9007199254740992
  617. )
  618. }
  619. _next() {
  620. const oldHi = this._state[0] >>> 0,
  621. oldLo = this._state[1] >>> 0
  622. !(function (out, aHi, aLo, bHi, bLo) {
  623. let c1 = (32557 * (aLo >>> 16)) >>> 0,
  624. c0 = (19605 * (65535 & aLo)) >>> 0,
  625. lo = (32557 * (65535 & aLo)) >>> 0,
  626. hi = (19605 * (aLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16))) >>> 0
  627. c0 = (c0 << 16) >>> 0
  628. lo = (lo + c0) >>> 0
  629. lo >>> 0 < c0 >>> 0 && (hi = (hi + 1) >>> 0)
  630. c1 = (c1 << 16) >>> 0
  631. lo = (lo + c1) >>> 0
  632. lo >>> 0 < c1 >>> 0 && (hi = (hi + 1) >>> 0)
  633. hi = (hi + Math.imul(aLo, 1481765933)) >>> 0
  634. hi = (hi + Math.imul(aHi, bLo)) >>> 0
  635. out[0] = hi
  636. out[1] = lo
  637. })(this._state, oldHi, oldLo, 0, 1284865837)
  638. add64(
  639. this._state,
  640. this._state[0],
  641. this._state[1],
  642. this._state[2],
  643. this._state[3]
  644. )
  645. let xsHi = oldHi >>> 18,
  646. xsLo = ((oldLo >>> 18) | (oldHi << 14)) >>> 0
  647. xsHi = (xsHi ^ oldHi) >>> 0
  648. xsLo = (xsLo ^ oldLo) >>> 0
  649. const xorshifted = ((xsLo >>> 27) | (xsHi << 5)) >>> 0,
  650. rot = oldHi >>> 27
  651. return (
  652. ((xorshifted >>> rot) |
  653. (xorshifted << (((-rot >>> 0) & 31) >>> 0))) >>>
  654. 0
  655. )
  656. }
  657. }
  658. function add64(out, aHi, aLo, bHi, bLo) {
  659. let hi = (aHi + bHi) >>> 0
  660. const lo = (aLo + bLo) >>> 0
  661. lo >>> 0 < aLo >>> 0 && (hi = (hi + 1) | 0)
  662. out[0] = hi
  663. out[1] = lo
  664. }
  665. const randomHashCache = globalValue(
  666. Symbol.for("@effect/data/Hash/randomHashCache"),
  667. () => new WeakMap()
  668. ),
  669. pcgr = globalValue(
  670. Symbol.for("@effect/data/Hash/pcgr"),
  671. () => new PCGRandom()
  672. ),
  673. symbol = Symbol.for("@effect/data/Hash"),
  674. Hash_hash = self => {
  675. switch (typeof self) {
  676. case "number":
  677. return number(self)
  678. case "bigint":
  679. return string(self.toString(10))
  680. case "boolean":
  681. case "symbol":
  682. return string(String(self))
  683. case "string":
  684. return string(self)
  685. case "undefined":
  686. return string("undefined")
  687. case "function":
  688. case "object":
  689. return null === self
  690. ? string("null")
  691. : isHash(self)
  692. ? self[symbol]()
  693. : random(self)
  694. default:
  695. throw new Error("Bug in Equal.hashGeneric")
  696. }
  697. },
  698. random = self => {
  699. randomHashCache.has(self) ||
  700. randomHashCache.set(
  701. self,
  702. number(pcgr.integer(Number.MAX_SAFE_INTEGER))
  703. )
  704. return randomHashCache.get(self)
  705. },
  706. combine = b => self => (53 * self) ^ b,
  707. optimize = n => (3221225471 & n) | ((n >>> 1) & 1073741824),
  708. isHash = u => "object" == typeof u && null !== u && symbol in u,
  709. number = n => {
  710. if (n != n || n === 1 / 0) return 0
  711. let h = 0 | n
  712. h !== n && (h ^= 4294967295 * n)
  713. for (; n > 4294967295; ) h ^= n /= 4294967295
  714. return optimize(n)
  715. },
  716. string = str => {
  717. let h = 5381,
  718. i = str.length
  719. for (; i; ) h = (33 * h) ^ str.charCodeAt(--i)
  720. return optimize(h)
  721. },
  722. array = arr => {
  723. let h = 6151
  724. for (let i = 0; i < arr.length; i++) h = combine(Hash_hash(arr[i]))(h)
  725. return optimize(h)
  726. },
  727. Equal_symbol = Symbol.for("@effect/data/Equal")
  728. function equals() {
  729. return 1 === arguments.length
  730. ? self => compareBoth(self, arguments[0])
  731. : compareBoth(arguments[0], arguments[1])
  732. }
  733. function compareBoth(self, that) {
  734. if (self === that) return !0
  735. const selfType = typeof self
  736. return (
  737. selfType === typeof that &&
  738. !(
  739. ("object" !== selfType && "function" !== selfType) ||
  740. null === self ||
  741. null === that ||
  742. !isEqual(self) ||
  743. !isEqual(that)
  744. ) &&
  745. Hash_hash(self) === Hash_hash(that) &&
  746. self[Equal_symbol](that)
  747. )
  748. }
  749. const isEqual = u =>
  750. "object" == typeof u && null !== u && Equal_symbol in u,
  751. Equal_equivalence = () => (self, that) =>
  752. Hash_hash(self) === Hash_hash(that) && equals(self, that)
  753. var _a
  754. const runtimeDebug = globalValue(
  755. Symbol.for("@effect/data/Debug/runtimeDebug"),
  756. () => ({
  757. reportUnhandled: !0,
  758. minumumLogLevel: "Info",
  759. traceStackLimit: 5,
  760. tracingEnabled: !0,
  761. parseStack: error => {
  762. const stack = error.stack
  763. if (stack) {
  764. const lines = stack.split("\n")
  765. let starts = 0
  766. for (let i = 0; i < lines.length; i++)
  767. lines[i].startsWith("Error") && (starts = i)
  768. const frames = []
  769. for (let i = starts + 1; i < lines.length; i++)
  770. if (lines[i].includes("at")) {
  771. const blocks = lines[i]
  772. .split(" ")
  773. .filter(i => i.length > 0 && "at" !== i),
  774. name =
  775. 2 !== blocks.length || blocks[0].includes("<anonymous>")
  776. ? void 0
  777. : blocks[0],
  778. file = 2 === blocks.length ? blocks[1] : blocks[0],
  779. matchFrame = file?.match(/\(?(.*):(\d+):(\d+)/)
  780. matchFrame
  781. ? frames.push({
  782. name,
  783. fileName: matchFrame[1],
  784. line: Number.parseInt(matchFrame[2]),
  785. column: Number.parseInt(matchFrame[3]),
  786. })
  787. : frames.push(void 0)
  788. } else frames.push(void 0)
  789. return frames
  790. }
  791. return []
  792. },
  793. filterStackFrame: _ =>
  794. null != _ && !_.fileName.match(/\/internal_effect_untraced/),
  795. })
  796. ),
  797. sourceLocationProto = Object.setPrototypeOf(
  798. {
  799. toFrame() {
  800. if ("parsed" in this) return this.parsed
  801. const stack = runtimeDebug.parseStack(this)
  802. stack && stack.length >= 2 && stack[0] && stack[1]
  803. ? (this.parsed = {
  804. ...stack[this.depth - 1],
  805. name: stack[this.depth - 2]?.name,
  806. })
  807. : (this.parsed = void 0)
  808. return this.parsed
  809. },
  810. },
  811. Error.prototype
  812. ),
  813. sourceLocation = error => {
  814. error.depth = Error.stackTraceLimit
  815. Object.setPrototypeOf(error, sourceLocationProto)
  816. return error
  817. },
  818. bodyWithTrace = body => {
  819. if (!runtimeDebug.tracingEnabled) return body(void 0, restoreOff)
  820. runtimeDebug.tracingEnabled = !1
  821. try {
  822. const limit = Error.stackTraceLimit
  823. Error.stackTraceLimit = 3
  824. const source = sourceLocation(new Error())
  825. Error.stackTraceLimit = limit
  826. return body(source, restoreOn)
  827. } finally {
  828. runtimeDebug.tracingEnabled = !0
  829. }
  830. },
  831. methodWithTrace = body =>
  832. function () {
  833. if (!runtimeDebug.tracingEnabled)
  834. return body(void 0, restoreOff).apply(this, arguments)
  835. runtimeDebug.tracingEnabled = !1
  836. try {
  837. const limit = Error.stackTraceLimit
  838. Error.stackTraceLimit = 2
  839. const error = sourceLocation(new Error())
  840. Error.stackTraceLimit = limit
  841. return body(error, restoreOn).apply(this, arguments)
  842. } finally {
  843. runtimeDebug.tracingEnabled = !0
  844. }
  845. },
  846. dualWithTrace = (dfLen, body) => {
  847. const isDataFirst =
  848. "number" == typeof dfLen ? args => args.length === dfLen : dfLen
  849. return function () {
  850. if (!runtimeDebug.tracingEnabled) {
  851. const f = body(void 0, restoreOff)
  852. return isDataFirst(arguments)
  853. ? untraced(() => f.apply(this, arguments))
  854. : self => untraced(() => f(self, ...arguments))
  855. }
  856. runtimeDebug.tracingEnabled = !1
  857. try {
  858. const limit = Error.stackTraceLimit
  859. Error.stackTraceLimit = 2
  860. const source = sourceLocation(new Error())
  861. Error.stackTraceLimit = limit
  862. const f = body(source, restoreOn)
  863. return isDataFirst(arguments)
  864. ? untraced(() => f.apply(this, arguments))
  865. : self => untraced(() => f(self, ...arguments))
  866. } finally {
  867. runtimeDebug.tracingEnabled = !0
  868. }
  869. }
  870. },
  871. untraced = body => {
  872. if (!runtimeDebug.tracingEnabled) return body(restoreOff)
  873. runtimeDebug.tracingEnabled = !1
  874. try {
  875. return body(restoreOn)
  876. } finally {
  877. runtimeDebug.tracingEnabled = !0
  878. }
  879. },
  880. untracedDual = (dfLen, body) =>
  881. function () {
  882. if (!runtimeDebug.tracingEnabled) {
  883. const f = body(restoreOff)
  884. return arguments.length === dfLen
  885. ? untraced(() => f.apply(this, arguments))
  886. : self => untraced(() => f(self, ...arguments))
  887. }
  888. runtimeDebug.tracingEnabled = !1
  889. try {
  890. const f = body(restoreOn)
  891. return arguments.length === dfLen
  892. ? untraced(() => f.apply(this, arguments))
  893. : self => untraced(() => f(self, ...arguments))
  894. } finally {
  895. runtimeDebug.tracingEnabled = !0
  896. }
  897. },
  898. untracedMethod = body =>
  899. function () {
  900. if (!runtimeDebug.tracingEnabled)
  901. return untraced(() => body(restoreOff).apply(this, arguments))
  902. runtimeDebug.tracingEnabled = !1
  903. try {
  904. return untraced(() => body(restoreOn).apply(this, arguments))
  905. } finally {
  906. runtimeDebug.tracingEnabled = !0
  907. }
  908. },
  909. restoreOn = body =>
  910. function () {
  911. if (runtimeDebug.tracingEnabled) return body.apply(this, arguments)
  912. runtimeDebug.tracingEnabled = !0
  913. try {
  914. return body.apply(this, arguments)
  915. } finally {
  916. runtimeDebug.tracingEnabled = !1
  917. }
  918. },
  919. restoreOff = body =>
  920. function () {
  921. if (!runtimeDebug.tracingEnabled) return body.apply(this, arguments)
  922. runtimeDebug.tracingEnabled = !1
  923. try {
  924. return body.apply(this, arguments)
  925. } finally {
  926. runtimeDebug.tracingEnabled = !0
  927. }
  928. },
  929. EffectTypeId = Symbol.for("@effect/io/Effect")
  930. class TracedPrimitive {
  931. [((_a = EffectTypeId), Equal_symbol)](that) {
  932. return this === that
  933. }
  934. [symbol]() {
  935. return random(this)
  936. }
  937. constructor(i0, trace) {
  938. this.i0 = i0
  939. this.trace = trace
  940. this._tag = "Traced"
  941. this.i1 = void 0
  942. this.i2 = void 0
  943. this[_a] = effectVariance
  944. }
  945. traced(trace) {
  946. return trace ? new TracedPrimitive(this, trace) : this
  947. }
  948. }
  949. const effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  950. makeTraced = (self, source) => new TracedPrimitive(self, source)
  951. var Option_a, _b
  952. const Option_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  953. Option_EffectTypeId = Symbol.for("@effect/io/Effect"),
  954. OptionTypeId = Symbol.for("@effect/io/Option")
  955. class Some {
  956. [((Option_a = Option_EffectTypeId), Equal_symbol)](that) {
  957. return isOption(that) && isSome(that) && equals(that.i0, this.i0)
  958. }
  959. [symbol]() {
  960. return Hash_hash(this.i0)
  961. }
  962. toString() {
  963. return `some(${String(this.i0)})`
  964. }
  965. toJSON() {
  966. return { _tag: this._tag, value: this.i0 }
  967. }
  968. [Symbol.for("nodejs.util.inspect.custom")]() {
  969. return this.toJSON()
  970. }
  971. get [OptionTypeId]() {
  972. return { _A: _ => _ }
  973. }
  974. get value() {
  975. return this.i0
  976. }
  977. constructor(i0) {
  978. this.i0 = i0
  979. this._tag = "Some"
  980. this.i1 = void 0
  981. this.i2 = void 0
  982. this.trace = void 0
  983. this[Option_a] = Option_effectVariance
  984. }
  985. traced(trace) {
  986. return trace ? makeTraced(this, trace) : this
  987. }
  988. }
  989. class None {
  990. constructor() {
  991. this._tag = "None"
  992. this.i0 = void 0
  993. this.i1 = void 0
  994. this.i2 = void 0
  995. this.trace = void 0
  996. this[_b] = Option_effectVariance
  997. }
  998. [((_b = Option_EffectTypeId), Equal_symbol)](that) {
  999. return isOption(that) && isNone(that)
  1000. }
  1001. [symbol]() {
  1002. return Hash_hash(this._tag)
  1003. }
  1004. toString() {
  1005. return "none()"
  1006. }
  1007. toJSON() {
  1008. return { _tag: this._tag }
  1009. }
  1010. [Symbol.for("nodejs.util.inspect.custom")]() {
  1011. return this.toJSON()
  1012. }
  1013. get [OptionTypeId]() {
  1014. return { _A: _ => _ }
  1015. }
  1016. traced(trace) {
  1017. return trace ? makeTraced(this, trace) : this
  1018. }
  1019. }
  1020. const isOption = input =>
  1021. "object" == typeof input &&
  1022. null != input &&
  1023. "_tag" in input &&
  1024. ("None" === input._tag || "Some" === input._tag) &&
  1025. isEqual(input),
  1026. isNone = fa => "None" === fa._tag,
  1027. isSome = fa => "Some" === fa._tag,
  1028. none = new None(),
  1029. some = a => new Some(a)
  1030. var Either_a, Either_b
  1031. const Either_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  1032. Either_EffectTypeId = Symbol.for("@effect/io/Effect"),
  1033. EitherTypeId = Symbol.for("@effect/data/Either")
  1034. class Right {
  1035. [((Either_a = Either_EffectTypeId), Equal_symbol)](that) {
  1036. return isEither(that) && isRight(that) && equals(that.i0, this.i0)
  1037. }
  1038. [symbol]() {
  1039. return Hash_hash(this.i0)
  1040. }
  1041. get right() {
  1042. return this.i0
  1043. }
  1044. constructor(i0) {
  1045. this.i0 = i0
  1046. this._tag = "Right"
  1047. this.i1 = void 0
  1048. this.i2 = void 0
  1049. this.trace = void 0
  1050. this[Either_a] = Either_effectVariance
  1051. }
  1052. get [EitherTypeId]() {
  1053. return { _E: _ => _, _A: _ => _ }
  1054. }
  1055. toString() {
  1056. return `right(${String(this.i0)})`
  1057. }
  1058. toJSON() {
  1059. return { _tag: this._tag, right: this.i0 }
  1060. }
  1061. [Symbol.for("nodejs.util.inspect.custom")]() {
  1062. return this.toJSON()
  1063. }
  1064. traced(trace) {
  1065. return trace ? makeTraced(this, trace) : this
  1066. }
  1067. }
  1068. class Left {
  1069. [((Either_b = Either_EffectTypeId), Equal_symbol)](that) {
  1070. return isEither(that) && isLeft(that) && equals(that.i0, this.i0)
  1071. }
  1072. [symbol]() {
  1073. return Hash_hash(this.i0)
  1074. }
  1075. get [EitherTypeId]() {
  1076. return { _E: _ => _, _A: _ => _ }
  1077. }
  1078. get left() {
  1079. return this.i0
  1080. }
  1081. constructor(i0) {
  1082. this.i0 = i0
  1083. this._tag = "Left"
  1084. this.i1 = void 0
  1085. this.i2 = void 0
  1086. this.trace = void 0
  1087. this[Either_b] = Either_effectVariance
  1088. }
  1089. toString() {
  1090. return `left(${String(this.i0)})`
  1091. }
  1092. toJSON() {
  1093. return { _tag: this._tag, left: this.i0 }
  1094. }
  1095. [Symbol.for("nodejs.util.inspect.custom")]() {
  1096. return this.toJSON()
  1097. }
  1098. traced(trace) {
  1099. return trace ? makeTraced(this, trace) : this
  1100. }
  1101. }
  1102. const isEither = input =>
  1103. "object" == typeof input &&
  1104. null != input &&
  1105. "_tag" in input &&
  1106. ("Left" === input._tag || "Right" === input._tag) &&
  1107. isEqual(input),
  1108. isLeft = ma => "Left" === ma._tag,
  1109. isRight = ma => "Right" === ma._tag,
  1110. not = self => a => !self(a),
  1111. make = compare => ({
  1112. compare: (self, that) => (self === that ? 0 : compare(self, that)),
  1113. }),
  1114. Order_number = make((self, that) => (self < that ? -1 : 1)),
  1115. Order_contramap = Function_dual(2, (self, f) =>
  1116. make((b1, b2) => self.compare(f(b1), f(b2)))
  1117. ),
  1118. greaterThanOrEqualTo = O =>
  1119. Function_dual(2, (self, that) => -1 !== O.compare(self, that)),
  1120. Equivalence_make =
  1121. (Order_number.compare,
  1122. isEquivalent => (self, that) =>
  1123. self === that || isEquivalent(self, that)),
  1124. isStrictEquivalent = (x, y) => x === y,
  1125. strict = () => isStrictEquivalent,
  1126. Equivalence_string = strict(),
  1127. Semigroup_make = (
  1128. combine,
  1129. combineMany = (self, collection) => {
  1130. return ((b = self),
  1131. (f = combine),
  1132. function (iterable) {
  1133. if (Array.isArray(iterable)) return iterable.reduce(f, b)
  1134. let result = b
  1135. for (const n of iterable) result = f(result, n)
  1136. return result
  1137. })(collection)
  1138. var b, f
  1139. }
  1140. ) => ({ combine, combineMany }),
  1141. Semigroup_string = Semigroup_make((self, that) => self + that),
  1142. numberSum = Semigroup_make((self, that) => self + that),
  1143. numberMultiply = Semigroup_make(
  1144. (self, that) => self * that,
  1145. (self, collection) => {
  1146. if (0 === self) return 0
  1147. let out = self
  1148. for (const n of collection) {
  1149. if (0 === n) return 0
  1150. out *= n
  1151. }
  1152. return out
  1153. }
  1154. ),
  1155. booleanEvery = Semigroup_make(
  1156. (self, that) => self && that,
  1157. (self, collection) => {
  1158. if (!1 === self) return !1
  1159. for (const b of collection) if (!1 === b) return !1
  1160. return !0
  1161. }
  1162. ),
  1163. booleanSome = Semigroup_make(
  1164. (self, that) => self || that,
  1165. (self, collection) => {
  1166. if (!0 === self) return !0
  1167. for (const b of collection) if (!0 === b) return !0
  1168. return !1
  1169. }
  1170. ),
  1171. intercalate = Function_dual(2, (S, separator) =>
  1172. Semigroup_make((self, that) => S.combineMany(self, [separator, that]))
  1173. ),
  1174. fromSemigroup = (S, empty) => ({
  1175. combine: S.combine,
  1176. combineMany: S.combineMany,
  1177. empty,
  1178. combineAll: collection => S.combineMany(empty, collection),
  1179. }),
  1180. Monoid_string = fromSemigroup(Semigroup_string, ""),
  1181. Monoid_numberSum = fromSemigroup(numberSum, 0),
  1182. Monoid_numberMultiply = fromSemigroup(numberMultiply, 1),
  1183. Monoid_booleanEvery = fromSemigroup(booleanEvery, !0),
  1184. Monoid_booleanSome = fromSemigroup(booleanSome, !1),
  1185. Order = (numberSum.combine, numberMultiply.combine, Order_number),
  1186. MonoidMultiply = Monoid_numberMultiply,
  1187. filter =
  1188. (Monoid_numberSum.combineAll,
  1189. MonoidMultiply.combineAll,
  1190. Filterable =>
  1191. Function_dual(2, (self, predicate) =>
  1192. Filterable.filterMap(self, b => (predicate(b) ? some(b) : none))
  1193. )),
  1194. Option_none = () => none,
  1195. Option_some = some,
  1196. Option_isNone = isNone,
  1197. Option_isSome = isSome,
  1198. match = Function_dual(3, (self, onNone, onSome) =>
  1199. Option_isNone(self) ? onNone() : onSome(self.value)
  1200. ),
  1201. getOrElse = Function_dual(2, (self, onNone) =>
  1202. Option_isNone(self) ? onNone() : self.value
  1203. ),
  1204. orElse = Function_dual(2, (self, that) =>
  1205. Option_isNone(self) ? that() : self
  1206. ),
  1207. fromNullable = nullableValue =>
  1208. null == nullableValue ? Option_none() : Option_some(nullableValue),
  1209. getOrUndefined = getOrElse(Function_constUndefined),
  1210. getOrThrow = Function_dual(2, (self, onNone) => {
  1211. if (Option_isSome(self)) return self.value
  1212. throw onNone()
  1213. })(() => new Error("getOrThrow called on a None")),
  1214. Option_map = Function_dual(2, (self, f) =>
  1215. Option_isNone(self) ? Option_none() : Option_some(f(self.value))
  1216. ),
  1217. flatMap = Function_dual(2, (self, f) =>
  1218. Option_isNone(self) ? Option_none() : f(self.value)
  1219. ),
  1220. flatMapNullable = Function_dual(2, (self, f) =>
  1221. Option_isNone(self) ? Option_none() : fromNullable(f(self.value))
  1222. ),
  1223. Option_filter = filter({
  1224. partitionMap: Function_dual(2, (self, f) => {
  1225. if (Option_isNone(self)) return [Option_none(), Option_none()]
  1226. const e = f(self.value)
  1227. return isLeft(e)
  1228. ? [Option_some(e.left), Option_none()]
  1229. : [Option_none(), Option_some(e.right)]
  1230. }),
  1231. filterMap: Function_dual(2, (self, f) =>
  1232. Option_isNone(self) ? Option_none() : f(self.value)
  1233. ),
  1234. }),
  1235. liftPredicate = predicate => b =>
  1236. predicate(b) ? Option_some(b) : Option_none(),
  1237. contains = isEquivalent =>
  1238. Function_dual(
  1239. 2,
  1240. (self, a) => !Option_isNone(self) && isEquivalent(self.value, a)
  1241. ),
  1242. exists = Function_dual(
  1243. 2,
  1244. (self, predicate) => !Option_isNone(self) && predicate(self.value)
  1245. ),
  1246. Either_right = a => new Right(a),
  1247. Either_left = e => new Left(e),
  1248. Either_isLeft = isLeft,
  1249. Either_isRight = isRight,
  1250. merge = Function_dual(3, (self, onLeft, onRight) =>
  1251. Either_isLeft(self) ? onLeft(self.left) : onRight(self.right)
  1252. )(Function_identity, Function_identity),
  1253. isNonEmptyArray = self => self.length > 0,
  1254. String_Equivalence = Equivalence_string,
  1255. Semigroup = Semigroup_string,
  1256. Monoid = Monoid_string,
  1257. slice =
  1258. (Semigroup.combine,
  1259. Function_dual(3, (self, start, end) => self.slice(start, end))),
  1260. isEmpty = self => 0 === self.length,
  1261. split = Function_dual(2, (self, separator) => {
  1262. const out = self.split(separator)
  1263. return isNonEmptyArray(out) ? out : [self]
  1264. }),
  1265. includes = Function_dual(2, (self, searchString) =>
  1266. self.includes(searchString)
  1267. )
  1268. class LinesIterator {
  1269. constructor(s, stripped = !1) {
  1270. this.s = s
  1271. this.stripped = stripped
  1272. this.index = 0
  1273. this.length = s.length
  1274. }
  1275. next() {
  1276. if (this.done) return { done: !0, value: void 0 }
  1277. const start = this.index
  1278. for (; !this.done && !isLineBreak(this.s[this.index]); )
  1279. this.index = this.index + 1
  1280. let end = this.index
  1281. if (!this.done) {
  1282. const char = this.s[this.index]
  1283. this.index = this.index + 1
  1284. !this.done &&
  1285. isLineBreak2(char, this.s[this.index]) &&
  1286. (this.index = this.index + 1)
  1287. this.stripped || (end = this.index)
  1288. }
  1289. return { done: !1, value: this.s.substring(start, end) }
  1290. }
  1291. [Symbol.iterator]() {
  1292. return new LinesIterator(this.s, this.stripped)
  1293. }
  1294. get done() {
  1295. return this.index >= this.length
  1296. }
  1297. }
  1298. const isLineBreak = char => {
  1299. const code = char.charCodeAt(0)
  1300. return 13 === code || 10 === code
  1301. },
  1302. isLineBreak2 = (char0, char1) =>
  1303. 13 === char0.charCodeAt(0) && 10 === char1.charCodeAt(0),
  1304. Invariant_bindTo = F =>
  1305. Function_dual(2, (self, name) =>
  1306. F.imap(
  1307. self,
  1308. a => ({ [name]: a }),
  1309. ({ [name]: a }) => a
  1310. )
  1311. ),
  1312. makeBy = (n, f) => {
  1313. const max = Math.max(1, Math.floor(n)),
  1314. out = [f(0)]
  1315. for (let i = 1; i < max; i++) out.push(f(i))
  1316. return out
  1317. },
  1318. mjs_ReadonlyArray_fromIterable = collection =>
  1319. Array.isArray(collection) ? collection : Array.from(collection),
  1320. matchRight = Function_dual(3, (self, onEmpty, onNonEmpty) =>
  1321. isNonEmptyReadonlyArray(self)
  1322. ? onNonEmpty(initNonEmpty(self), lastNonEmpty(self))
  1323. : onEmpty()
  1324. ),
  1325. prepend = Function_dual(2, (self, head) => [head, ...self]),
  1326. append = Function_dual(2, (self, last) => [...self, last]),
  1327. isEmptyReadonlyArray = self => 0 === self.length,
  1328. isNonEmptyReadonlyArray = isNonEmptyArray,
  1329. isOutOfBound = (i, as) => i < 0 || i >= as.length,
  1330. ReadonlyArray_get = Function_dual(2, (self, index) => {
  1331. const i = Math.floor(index)
  1332. return isOutOfBound(i, self) ? Option_none() : Option_some(self[i])
  1333. }),
  1334. unsafeGet = Function_dual(2, (self, index) => {
  1335. const i = Math.floor(index)
  1336. if (isOutOfBound(i, self)) throw new Error(`Index ${i} out of bounds`)
  1337. return self[i]
  1338. }),
  1339. headNonEmpty = unsafeGet(0),
  1340. lastNonEmpty = self => self[self.length - 1],
  1341. tailNonEmpty = self => self.slice(1),
  1342. initNonEmpty = self => self.slice(0, -1),
  1343. take = Function_dual(2, (self, n) => {
  1344. const input = mjs_ReadonlyArray_fromIterable(self)
  1345. return input.slice(
  1346. 0,
  1347. ((i, as) => Math.floor(Math.min(Math.max(0, i), as.length)))(n, input)
  1348. )
  1349. }),
  1350. findFirstIndex = Function_dual(2, (self, predicate) => {
  1351. let i = 0
  1352. for (const a of self) {
  1353. if (predicate(a)) return Option_some(i)
  1354. i++
  1355. }
  1356. return Option_none()
  1357. }),
  1358. findFirst = Function_dual(2, (self, predicate) => {
  1359. const input = mjs_ReadonlyArray_fromIterable(self)
  1360. for (let i = 0; i < input.length; i++)
  1361. if (predicate(input[i])) return Option_some(input[i])
  1362. return Option_none()
  1363. }),
  1364. findLast = Function_dual(2, (self, predicate) => {
  1365. const input = mjs_ReadonlyArray_fromIterable(self)
  1366. for (let i = input.length - 1; i >= 0; i--)
  1367. if (predicate(input[i])) return Option_some(input[i])
  1368. return Option_none()
  1369. }),
  1370. ReadonlyArray_remove = Function_dual(2, (self, i) => {
  1371. const out = Array.from(self)
  1372. if (isOutOfBound(i, out)) return out
  1373. out.splice(i, 1)
  1374. return out
  1375. }),
  1376. ReadonlyArray_reverse = self => Array.from(self).reverse(),
  1377. sort = Function_dual(2, (self, O) => {
  1378. const out = Array.from(self)
  1379. out.sort(O.compare)
  1380. return out
  1381. }),
  1382. zip = Function_dual(2, (self, that) =>
  1383. ReadonlyArray_zipWith(self, that, (a, b) => [a, b])
  1384. ),
  1385. ReadonlyArray_zipWith = Function_dual(3, (self, that, f) => {
  1386. const as = mjs_ReadonlyArray_fromIterable(self),
  1387. bs = mjs_ReadonlyArray_fromIterable(that)
  1388. return isNonEmptyReadonlyArray(as) && isNonEmptyReadonlyArray(bs)
  1389. ? zipNonEmptyWith(bs, f)(as)
  1390. : []
  1391. }),
  1392. zipNonEmptyWith = Function_dual(3, (self, that, f) => {
  1393. const cs = [f(headNonEmpty(self), headNonEmpty(that))],
  1394. len = Math.min(self.length, that.length)
  1395. for (let i = 1; i < len; i++) cs[i] = f(self[i], that[i])
  1396. return cs
  1397. }),
  1398. ReadonlyArray_contains = isEquivalent =>
  1399. Function_dual(2, (self, a) => {
  1400. for (const i of self) if (isEquivalent(a, i)) return !0
  1401. return !1
  1402. }),
  1403. uniq = Function_dual(2, (self, isEquivalent) => {
  1404. const input = mjs_ReadonlyArray_fromIterable(self)
  1405. return isNonEmptyReadonlyArray(input)
  1406. ? uniqNonEmpty(isEquivalent)(input)
  1407. : []
  1408. }),
  1409. uniqNonEmpty = Function_dual(2, (self, isEquivalent) => {
  1410. const out = [headNonEmpty(self)],
  1411. rest = tailNonEmpty(self)
  1412. for (const a of rest) out.every(o => !isEquivalent(a, o)) && out.push(a)
  1413. return out
  1414. }),
  1415. ReadonlyArray_of = a => [a],
  1416. ReadonlyArray_map = Function_dual(2, (self, f) => self.map(f)),
  1417. mapNonEmpty = ReadonlyArray_map,
  1418. ReadonlyArray_Invariant = { imap: imap(ReadonlyArray_map) },
  1419. ReadonlyArray_flatMap = Function_dual(2, (self, f) => {
  1420. if (isEmptyReadonlyArray(self)) return []
  1421. const out = []
  1422. for (let i = 0; i < self.length; i++) out.push(...f(self[i], i))
  1423. return out
  1424. }),
  1425. ReadonlyArray_filterMap = Function_dual(2, (self, f) => {
  1426. const as = mjs_ReadonlyArray_fromIterable(self),
  1427. out = []
  1428. for (let i = 0; i < as.length; i++) {
  1429. const o = f(as[i], i)
  1430. Option_isSome(o) && out.push(o.value)
  1431. }
  1432. return out
  1433. }),
  1434. ReadonlyArray_compact = ReadonlyArray_filterMap(Function_identity),
  1435. ReadonlyArray_filter = Function_dual(2, (self, predicate) => {
  1436. const as = mjs_ReadonlyArray_fromIterable(self),
  1437. out = []
  1438. for (let i = 0; i < as.length; i++)
  1439. predicate(as[i], i) && out.push(as[i])
  1440. return out
  1441. }),
  1442. ReadonlyArray_reduce = Function_dual(3, (self, b, f) =>
  1443. mjs_ReadonlyArray_fromIterable(self).reduce((b, a, i) => f(b, a, i), b)
  1444. ),
  1445. ReadonlyArray_some = predicate => self => self.some(predicate),
  1446. ReadonlyArray_intercalate = M =>
  1447. Function_dual(2, (self, middle) => {
  1448. const as = mjs_ReadonlyArray_fromIterable(self)
  1449. return isNonEmptyReadonlyArray(as)
  1450. ? intercalateNonEmpty(M)(as, middle)
  1451. : M.empty
  1452. }),
  1453. intercalateNonEmpty = S =>
  1454. Function_dual(2, (self, middle) =>
  1455. intercalate(S, middle).combineMany(
  1456. headNonEmpty(self),
  1457. tailNonEmpty(self)
  1458. )
  1459. ),
  1460. join = ReadonlyArray_intercalate(Monoid),
  1461. ReadonlyArray_bindTo = Invariant_bindTo(ReadonlyArray_Invariant),
  1462. TypeId = Symbol.for("@effect/data/Chunk"),
  1463. emptyArray = []
  1464. class ChunkImpl {
  1465. constructor(backing) {
  1466. this.backing = backing
  1467. this._id = TypeId
  1468. switch (backing._tag) {
  1469. case "IEmpty":
  1470. this.length = 0
  1471. this.depth = 0
  1472. this.left = this
  1473. this.right = this
  1474. break
  1475. case "IConcat":
  1476. this.length = backing.left.length + backing.right.length
  1477. this.depth = 1 + Math.max(backing.left.depth, backing.right.depth)
  1478. this.left = backing.left
  1479. this.right = backing.right
  1480. break
  1481. case "IArray":
  1482. this.length = backing.array.length
  1483. this.depth = 0
  1484. this.left = _empty
  1485. this.right = _empty
  1486. break
  1487. case "ISingleton":
  1488. this.length = 1
  1489. this.depth = 0
  1490. this.left = _empty
  1491. this.right = _empty
  1492. break
  1493. case "ISlice":
  1494. this.length = backing.length
  1495. this.depth = backing.chunk.depth + 1
  1496. this.left = _empty
  1497. this.right = _empty
  1498. }
  1499. }
  1500. toString() {
  1501. return `Chunk(${toReadonlyArray(this).map(String).join(", ")})`
  1502. }
  1503. toJSON() {
  1504. return { _tag: "Chunk", values: toReadonlyArray(this) }
  1505. }
  1506. [Symbol.for("nodejs.util.inspect.custom")]() {
  1507. return this.toJSON()
  1508. }
  1509. [Equal_symbol](that) {
  1510. return (
  1511. !(!isChunk(that) || this.length !== that.length) &&
  1512. toReadonlyArray(this).every((value, i) =>
  1513. equals(value, Chunk_unsafeGet(that, i))
  1514. )
  1515. )
  1516. }
  1517. [symbol]() {
  1518. return array(toReadonlyArray(this))
  1519. }
  1520. [Symbol.iterator]() {
  1521. switch (this.backing._tag) {
  1522. case "IArray":
  1523. return this.backing.array[Symbol.iterator]()
  1524. case "IEmpty":
  1525. return emptyArray[Symbol.iterator]()
  1526. default:
  1527. return toReadonlyArray(this)[Symbol.iterator]()
  1528. }
  1529. }
  1530. }
  1531. const copyToArray = (self, array, initial) => {
  1532. switch (self.backing._tag) {
  1533. case "IArray":
  1534. !(function (src, srcPos, dest, destPos, len) {
  1535. for (let i = 0; i < Math.min(src.length, 0 + len); i++)
  1536. dest[destPos + i - 0] = src[i]
  1537. })(self.backing.array, 0, array, initial, self.length)
  1538. break
  1539. case "IConcat":
  1540. copyToArray(self.left, array, initial)
  1541. copyToArray(self.right, array, initial + self.left.length)
  1542. break
  1543. case "ISingleton":
  1544. array[initial] = self.backing.a
  1545. break
  1546. case "ISlice": {
  1547. let i = 0,
  1548. j = initial
  1549. for (; i < self.length; ) {
  1550. array[j] = Chunk_unsafeGet(self, i)
  1551. i += 1
  1552. j += 1
  1553. }
  1554. break
  1555. }
  1556. }
  1557. },
  1558. isChunk = u =>
  1559. "object" == typeof u && null != u && "_id" in u && u._id === TypeId,
  1560. _empty = new ChunkImpl({ _tag: "IEmpty" }),
  1561. Chunk_empty = () => _empty,
  1562. Chunk_fromIterable = self =>
  1563. isChunk(self)
  1564. ? self
  1565. : new ChunkImpl({ _tag: "IArray", array: Array.from(self) }),
  1566. toReadonlyArray = self => {
  1567. switch (self.backing._tag) {
  1568. case "IEmpty":
  1569. return emptyArray
  1570. case "IArray":
  1571. return self.backing.array
  1572. default: {
  1573. const arr = new Array(self.length)
  1574. copyToArray(self, arr, 0)
  1575. self.backing = { _tag: "IArray", array: arr }
  1576. self.left = _empty
  1577. self.right = _empty
  1578. self.depth = 0
  1579. return arr
  1580. }
  1581. }
  1582. },
  1583. Chunk_get = Function_dual(2, (self, index) =>
  1584. index < 0 || index >= self.length
  1585. ? Option_none()
  1586. : Option_some(Chunk_unsafeGet(self, index))
  1587. ),
  1588. unsafeFromArray = self => new ChunkImpl({ _tag: "IArray", array: self }),
  1589. Chunk_unsafeGet = Function_dual(2, (self, index) => {
  1590. switch (self.backing._tag) {
  1591. case "IEmpty":
  1592. throw new Error("Index out of bounds")
  1593. case "ISingleton":
  1594. if (0 !== index) throw new Error("Index out of bounds")
  1595. return self.backing.a
  1596. case "IArray":
  1597. if (index >= self.length || index < 0)
  1598. throw new Error("Index out of bounds")
  1599. return self.backing.array[index]
  1600. case "IConcat":
  1601. return index < self.left.length
  1602. ? Chunk_unsafeGet(self.left, index)
  1603. : Chunk_unsafeGet(self.right, index - self.left.length)
  1604. case "ISlice":
  1605. return Chunk_unsafeGet(
  1606. self.backing.chunk,
  1607. index + self.backing.offset
  1608. )
  1609. }
  1610. }),
  1611. Chunk_append = Function_dual(2, (self, a) =>
  1612. Chunk_concat(self, Chunk_of(a))
  1613. ),
  1614. Chunk_prepend = Function_dual(2, (self, a) =>
  1615. Chunk_concat(Chunk_of(a), self)
  1616. ),
  1617. Chunk_take = Function_dual(2, (self, n) => {
  1618. if (n <= 0) return _empty
  1619. if (n >= self.length) return self
  1620. switch (self.backing._tag) {
  1621. case "ISlice":
  1622. return new ChunkImpl({
  1623. _tag: "ISlice",
  1624. chunk: self.backing.chunk,
  1625. length: n,
  1626. offset: self.backing.offset,
  1627. })
  1628. case "IConcat":
  1629. return n > self.left.length
  1630. ? new ChunkImpl({
  1631. _tag: "IConcat",
  1632. left: self.left,
  1633. right: Chunk_take(self.right, n - self.left.length),
  1634. })
  1635. : Chunk_take(self.left, n)
  1636. default:
  1637. return new ChunkImpl({
  1638. _tag: "ISlice",
  1639. chunk: self,
  1640. offset: 0,
  1641. length: n,
  1642. })
  1643. }
  1644. }),
  1645. Chunk_drop = Function_dual(2, (self, n) => {
  1646. if (n <= 0) return self
  1647. if (n >= self.length) return _empty
  1648. switch (self.backing._tag) {
  1649. case "ISlice":
  1650. return new ChunkImpl({
  1651. _tag: "ISlice",
  1652. chunk: self.backing.chunk,
  1653. offset: self.backing.offset + n,
  1654. length: self.backing.length - n,
  1655. })
  1656. case "IConcat":
  1657. return n > self.left.length
  1658. ? Chunk_drop(self.right, n - self.left.length)
  1659. : new ChunkImpl({
  1660. _tag: "IConcat",
  1661. left: Chunk_drop(self.left, n),
  1662. right: self.right,
  1663. })
  1664. default:
  1665. return new ChunkImpl({
  1666. _tag: "ISlice",
  1667. chunk: self,
  1668. offset: n,
  1669. length: self.length - n,
  1670. })
  1671. }
  1672. }),
  1673. Chunk_concat = Function_dual(2, (self, that) => {
  1674. if ("IEmpty" === self.backing._tag) return that
  1675. if ("IEmpty" === that.backing._tag) return self
  1676. const diff = that.depth - self.depth
  1677. if (Math.abs(diff) <= 1)
  1678. return new ChunkImpl({ _tag: "IConcat", left: self, right: that })
  1679. if (diff < -1) {
  1680. if (self.left.depth >= self.right.depth) {
  1681. const nr = Chunk_concat(self.right, that)
  1682. return new ChunkImpl({
  1683. _tag: "IConcat",
  1684. left: self.left,
  1685. right: nr,
  1686. })
  1687. }
  1688. {
  1689. const nrr = Chunk_concat(self.right.right, that)
  1690. if (nrr.depth === self.depth - 3) {
  1691. const nr = new ChunkImpl({
  1692. _tag: "IConcat",
  1693. left: self.right.left,
  1694. right: nrr,
  1695. })
  1696. return new ChunkImpl({
  1697. _tag: "IConcat",
  1698. left: self.left,
  1699. right: nr,
  1700. })
  1701. }
  1702. {
  1703. const nl = new ChunkImpl({
  1704. _tag: "IConcat",
  1705. left: self.left,
  1706. right: self.right.left,
  1707. })
  1708. return new ChunkImpl({ _tag: "IConcat", left: nl, right: nrr })
  1709. }
  1710. }
  1711. }
  1712. if (that.right.depth >= that.left.depth) {
  1713. const nl = Chunk_concat(self, that.left)
  1714. return new ChunkImpl({ _tag: "IConcat", left: nl, right: that.right })
  1715. }
  1716. {
  1717. const nll = Chunk_concat(self, that.left.left)
  1718. if (nll.depth === that.depth - 3) {
  1719. const nl = new ChunkImpl({
  1720. _tag: "IConcat",
  1721. left: nll,
  1722. right: that.left.right,
  1723. })
  1724. return new ChunkImpl({
  1725. _tag: "IConcat",
  1726. left: nl,
  1727. right: that.right,
  1728. })
  1729. }
  1730. {
  1731. const nr = new ChunkImpl({
  1732. _tag: "IConcat",
  1733. left: that.left.right,
  1734. right: that.right,
  1735. })
  1736. return new ChunkImpl({ _tag: "IConcat", left: nll, right: nr })
  1737. }
  1738. }
  1739. }),
  1740. dedupeAdjacent = self => {
  1741. const builder = []
  1742. let lastA = Option_none()
  1743. for (const a of self)
  1744. if (Option_isNone(lastA) || !equals(a, lastA.value)) {
  1745. builder.push(a)
  1746. lastA = Option_some(a)
  1747. }
  1748. return unsafeFromArray(builder)
  1749. },
  1750. Chunk_flatten = Function_dual(2, (self, f) => {
  1751. if ("ISingleton" === self.backing._tag) return f(self.backing.a)
  1752. let r = _empty
  1753. for (const k of self) r = Chunk_concat(r, f(k))
  1754. return r
  1755. })(Function_identity),
  1756. Chunk_head = Chunk_get(0),
  1757. Chunk_isEmpty = self => 0 === self.length,
  1758. Chunk_isNonEmpty = self => self.length > 0,
  1759. Chunk_reduce = Function_dual(3, (self, b, f) =>
  1760. ReadonlyArray_reduce(b, f)(toReadonlyArray(self))
  1761. ),
  1762. Chunk_join = Function_dual(2, (self, sep) =>
  1763. Chunk_reduce(self, "", (s, a) => (s.length > 0 ? `${s}${sep}${a}` : a))
  1764. ),
  1765. Chunk_of = a => new ChunkImpl({ _tag: "ISingleton", a }),
  1766. Chunk_makeBy = Function_dual(2, (n, f) =>
  1767. ((...as) => unsafeFromArray(as))(...makeBy(n, f))
  1768. ),
  1769. Chunk_map = Function_dual(2, (self, f) =>
  1770. "ISingleton" === self.backing._tag
  1771. ? Chunk_of(f(self.backing.a))
  1772. : unsafeFromArray(ReadonlyArray_map(toReadonlyArray(self), f))
  1773. ),
  1774. mapWithIndex = Function_dual(2, (self, f) =>
  1775. "ISingleton" === self.backing._tag
  1776. ? Chunk_of(f(self.backing.a, 0))
  1777. : unsafeFromArray(ReadonlyArray_map(f)(toReadonlyArray(self)))
  1778. ),
  1779. Chunk_reverse = self =>
  1780. unsafeFromArray(ReadonlyArray_reverse(toReadonlyArray(self))),
  1781. Chunk_sort = Function_dual(2, (self, O) =>
  1782. unsafeFromArray(sort(O)(toReadonlyArray(self)))
  1783. ),
  1784. Chunk_splitAt = Function_dual(2, (self, n) => [
  1785. Chunk_take(self, n),
  1786. Chunk_drop(self, n),
  1787. ]),
  1788. splitWhere = Function_dual(2, (self, f) => {
  1789. let i = 0
  1790. for (const a of toReadonlyArray(self)) {
  1791. if (f(a)) break
  1792. i++
  1793. }
  1794. return Chunk_splitAt(self, i)
  1795. }),
  1796. Chunk_unfold = (s, f) => {
  1797. const builder = []
  1798. let cont = !0,
  1799. s1 = s
  1800. for (; cont; ) {
  1801. const x = f(s1)
  1802. if (Option_isSome(x)) {
  1803. s1 = x.value[1]
  1804. builder.push(x.value[0])
  1805. } else cont = !1
  1806. }
  1807. return unsafeFromArray(builder)
  1808. },
  1809. uniq_ = uniq(Equal_equivalence()),
  1810. unsafeHead = self => Chunk_unsafeGet(self, 0),
  1811. unsafeLast = self => Chunk_unsafeGet(self, self.length - 1),
  1812. Chunk_zip = Function_dual(2, (self, that) =>
  1813. Chunk_zipWith(self, that, (a, b) => [a, b])
  1814. ),
  1815. Chunk_zipWith = Function_dual(3, (self, that, f) => {
  1816. const selfA = toReadonlyArray(self),
  1817. thatA = toReadonlyArray(that)
  1818. return unsafeFromArray(ReadonlyArray_zipWith(thatA, f)(selfA))
  1819. }),
  1820. Chunk_headNonEmpty = unsafeHead,
  1821. Chunk_tailNonEmpty = self => Chunk_drop(self, 1)
  1822. var Context_a
  1823. const TagTypeId = Symbol.for("@effect/data/Context/Tag"),
  1824. Context_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  1825. Context_EffectTypeId = Symbol.for("@effect/io/Effect")
  1826. class TagImpl {
  1827. [((Context_a = Context_EffectTypeId), Equal_symbol)](that) {
  1828. return this === that
  1829. }
  1830. [symbol]() {
  1831. return random(this)
  1832. }
  1833. get [TagTypeId]() {
  1834. return { _S: _ => _, _I: _ => _ }
  1835. }
  1836. constructor(id) {
  1837. this._tag = "Tag"
  1838. this.i0 = void 0
  1839. this.i1 = void 0
  1840. this.i2 = void 0
  1841. this.trace = void 0
  1842. this[Context_a] = Context_effectVariance
  1843. if (void 0 !== id) return globalValue(id, () => this)
  1844. }
  1845. traced(trace) {
  1846. return trace ? makeTraced(this, trace) : this
  1847. }
  1848. of(self) {
  1849. return self
  1850. }
  1851. context(self) {
  1852. return Context_make(this, self)
  1853. }
  1854. }
  1855. const ContextTypeId = Symbol.for("@effect/data/Context")
  1856. class ContextImpl {
  1857. [Equal_symbol](that) {
  1858. if (isContext(that) && this.unsafeMap.size === that.unsafeMap.size) {
  1859. for (const k of this.unsafeMap.keys())
  1860. if (
  1861. !that.unsafeMap.has(k) ||
  1862. !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))
  1863. )
  1864. return !1
  1865. return !0
  1866. }
  1867. return !1
  1868. }
  1869. [symbol]() {
  1870. return number(this.unsafeMap.size)
  1871. }
  1872. constructor(unsafeMap) {
  1873. this.unsafeMap = unsafeMap
  1874. this._id = ContextTypeId
  1875. this._S = _ => _
  1876. }
  1877. }
  1878. const isContext = u =>
  1879. "object" == typeof u &&
  1880. null !== u &&
  1881. "_id" in u &&
  1882. u._id === ContextTypeId,
  1883. Context_make = (tag, service) =>
  1884. new ContextImpl(new Map([[tag, service]])),
  1885. add = Function_dual(3, (self, tag, service) => {
  1886. const map = new Map(self.unsafeMap)
  1887. map.set(tag, service)
  1888. return new ContextImpl(map)
  1889. }),
  1890. Context_get = Function_dual(2, (self, tag) => {
  1891. if (!self.unsafeMap.has(tag)) throw new Error("Service not found")
  1892. return self.unsafeMap.get(tag)
  1893. }),
  1894. Context_unsafeGet = Function_dual(2, (self, tag) => {
  1895. if (!self.unsafeMap.has(tag)) throw new Error("Service not found")
  1896. return self.unsafeMap.get(tag)
  1897. }),
  1898. Context_merge = Function_dual(2, (self, that) => {
  1899. const map = new Map(self.unsafeMap)
  1900. for (const [tag, s] of that.unsafeMap) map.set(tag, s)
  1901. return new ContextImpl(map)
  1902. }),
  1903. Tag = key => new TagImpl(key),
  1904. mjs_Context_empty = () => new ContextImpl(new Map()),
  1905. mjs_Context_make = Context_make,
  1906. Context_add = add,
  1907. mjs_Context_get = Context_get,
  1908. mjs_Context_unsafeGet = Context_unsafeGet,
  1909. mjs_Context_merge = Context_merge,
  1910. ContextPatchTypeId = Symbol.for("@effect/data/Differ/ContextPatch")
  1911. function ContextPatch_variance(a) {
  1912. return a
  1913. }
  1914. class ContextPatch_Empty {
  1915. constructor() {
  1916. this._tag = "Empty"
  1917. this._Input = ContextPatch_variance
  1918. this._Output = ContextPatch_variance
  1919. this._id = ContextPatchTypeId
  1920. }
  1921. [symbol]() {
  1922. return string("ContextPatch(Empty)")
  1923. }
  1924. [Equal_symbol](that) {
  1925. return (
  1926. "object" == typeof that &&
  1927. null !== that &&
  1928. "_id" in that &&
  1929. that._id === this._id &&
  1930. "_tag" in that &&
  1931. that._tag === this._id
  1932. )
  1933. }
  1934. }
  1935. class ContextPatch_AndThen {
  1936. constructor(first, second) {
  1937. this.first = first
  1938. this.second = second
  1939. this._tag = "AndThen"
  1940. this._id = ContextPatchTypeId
  1941. this._Input = ContextPatch_variance
  1942. this._Output = ContextPatch_variance
  1943. }
  1944. [symbol]() {
  1945. return string("ContextPatch(AndThen)")
  1946. }
  1947. [Equal_symbol](that) {
  1948. return (
  1949. "object" == typeof that &&
  1950. null !== that &&
  1951. "_id" in that &&
  1952. that._id === this._id &&
  1953. "_tag" in that &&
  1954. that._tag === this._id &&
  1955. equals(this.first, that.first) &&
  1956. equals(this.second, that.second)
  1957. )
  1958. }
  1959. }
  1960. class AddService {
  1961. constructor(tag, service) {
  1962. this.tag = tag
  1963. this.service = service
  1964. this._tag = "AddService"
  1965. this._id = ContextPatchTypeId
  1966. this._Input = ContextPatch_variance
  1967. this._Output = ContextPatch_variance
  1968. }
  1969. [symbol]() {
  1970. return string("ContextPatch(AddService)")
  1971. }
  1972. [Equal_symbol](that) {
  1973. return (
  1974. "object" == typeof that &&
  1975. null !== that &&
  1976. "_id" in that &&
  1977. that._id === this._id &&
  1978. "_tag" in that &&
  1979. that._tag === this._id &&
  1980. equals(this.tag, that.tag) &&
  1981. equals(this.service, that.service)
  1982. )
  1983. }
  1984. }
  1985. class RemoveService {
  1986. constructor(tag) {
  1987. this.tag = tag
  1988. this._tag = "RemoveService"
  1989. this._id = ContextPatchTypeId
  1990. this._Input = ContextPatch_variance
  1991. this._Output = ContextPatch_variance
  1992. }
  1993. [symbol]() {
  1994. return string("ContextPatch(RemoveService)")
  1995. }
  1996. [Equal_symbol](that) {
  1997. return (
  1998. "object" == typeof that &&
  1999. null !== that &&
  2000. "_id" in that &&
  2001. that._id === this._id &&
  2002. "_tag" in that &&
  2003. that._tag === this._id &&
  2004. equals(this.tag, that.tag)
  2005. )
  2006. }
  2007. }
  2008. class UpdateService {
  2009. constructor(tag, update) {
  2010. this.tag = tag
  2011. this.update = update
  2012. this._tag = "UpdateService"
  2013. this._id = ContextPatchTypeId
  2014. this._Input = ContextPatch_variance
  2015. this._Output = ContextPatch_variance
  2016. }
  2017. [symbol]() {
  2018. return string("ContextPatch(AndThen)")
  2019. }
  2020. [Equal_symbol](that) {
  2021. return (
  2022. "object" == typeof that &&
  2023. null !== that &&
  2024. "_id" in that &&
  2025. that._id === this._id &&
  2026. "_tag" in that &&
  2027. that._tag === this._id &&
  2028. equals(this.tag, that.tag) &&
  2029. equals(this.update, that.update)
  2030. )
  2031. }
  2032. }
  2033. const ContextPatch_empty = () => new ContextPatch_Empty(),
  2034. ContextPatch_combine = Function_dual(
  2035. 2,
  2036. (self, that) => new ContextPatch_AndThen(self, that)
  2037. ),
  2038. ContextPatch_patch = Function_dual(2, (self, context) => {
  2039. let wasServiceUpdated = !1,
  2040. patches = Chunk_of(self)
  2041. const updatedContext = new Map(context.unsafeMap)
  2042. for (; Chunk_isNonEmpty(patches); ) {
  2043. const head = Chunk_headNonEmpty(patches),
  2044. tail = Chunk_tailNonEmpty(patches)
  2045. switch (head._tag) {
  2046. case "Empty":
  2047. patches = tail
  2048. break
  2049. case "AddService":
  2050. updatedContext.set(head.tag, head.service)
  2051. patches = tail
  2052. break
  2053. case "AndThen":
  2054. patches = Chunk_prepend(
  2055. Chunk_prepend(tail, head.second),
  2056. head.first
  2057. )
  2058. break
  2059. case "RemoveService":
  2060. updatedContext.delete(head.tag)
  2061. patches = tail
  2062. break
  2063. case "UpdateService":
  2064. updatedContext.set(
  2065. head.tag,
  2066. head.update(updatedContext.get(head.tag))
  2067. )
  2068. wasServiceUpdated = !0
  2069. patches = tail
  2070. }
  2071. }
  2072. if (!wasServiceUpdated) return new ContextImpl(updatedContext)
  2073. const map = new Map()
  2074. for (const [tag] of context.unsafeMap)
  2075. if (updatedContext.has(tag)) {
  2076. map.set(tag, updatedContext.get(tag))
  2077. updatedContext.delete(tag)
  2078. }
  2079. for (const [tag, s] of updatedContext) map.set(tag, s)
  2080. return new ContextImpl(map)
  2081. }),
  2082. Differ_ContextPatch_empty = ContextPatch_empty,
  2083. Differ_ContextPatch_combine = ContextPatch_combine,
  2084. Differ_ContextPatch_patch = ContextPatch_patch,
  2085. SIZE = 5,
  2086. BUCKET_SIZE = Math.pow(2, SIZE),
  2087. MASK = BUCKET_SIZE - 1,
  2088. MAX_INDEX_NODE = BUCKET_SIZE / 2,
  2089. MIN_ARRAY_NODE = BUCKET_SIZE / 4
  2090. function hashFragment(shift, h) {
  2091. return (h >>> shift) & MASK
  2092. }
  2093. function toBitmap(x) {
  2094. return 1 << x
  2095. }
  2096. function fromBitmap(bitmap, bit) {
  2097. return (function (x) {
  2098. x =
  2099. ((x =
  2100. (858993459 & (x -= (x >> 1) & 1431655765)) +
  2101. ((x >> 2) & 858993459)) +
  2102. (x >> 4)) &
  2103. 252645135
  2104. return 127 & ((x += x >> 8) + (x >> 16))
  2105. })(bitmap & (bit - 1))
  2106. }
  2107. function arrayUpdate(mutate, at, v, arr) {
  2108. let out = arr
  2109. if (!mutate) {
  2110. const len = arr.length
  2111. out = new Array(len)
  2112. for (let i = 0; i < len; ++i) out[i] = arr[i]
  2113. }
  2114. out[at] = v
  2115. return out
  2116. }
  2117. function arraySpliceOut(mutate, at, arr) {
  2118. const newLen = arr.length - 1
  2119. let i = 0,
  2120. g = 0,
  2121. out = arr
  2122. if (mutate) i = g = at
  2123. else {
  2124. out = new Array(newLen)
  2125. for (; i < at; ) out[g++] = arr[i++]
  2126. }
  2127. ++i
  2128. for (; i <= newLen; ) out[g++] = arr[i++]
  2129. mutate && (out.length = newLen)
  2130. return out
  2131. }
  2132. class Stack {
  2133. constructor(value, previous) {
  2134. this.value = value
  2135. this.previous = previous
  2136. }
  2137. }
  2138. class EmptyNode {
  2139. constructor() {
  2140. this._tag = "EmptyNode"
  2141. }
  2142. modify(edit, _shift, f, hash, key, size) {
  2143. const v = f(Option_none())
  2144. if (Option_isNone(v)) return new EmptyNode()
  2145. ++size.value
  2146. return new LeafNode(edit, hash, key, v)
  2147. }
  2148. }
  2149. function isEmptyNode(a) {
  2150. return a instanceof EmptyNode
  2151. }
  2152. function canEditNode(node, edit) {
  2153. return !isEmptyNode(node) && edit === node.edit
  2154. }
  2155. class LeafNode {
  2156. constructor(edit, hash, key, value) {
  2157. this.edit = edit
  2158. this.hash = hash
  2159. this.key = key
  2160. this.value = value
  2161. this._tag = "LeafNode"
  2162. }
  2163. modify(edit, shift, f, hash, key, size) {
  2164. if (equals(key, this.key)) {
  2165. const v = f(this.value)
  2166. if (v === this.value) return this
  2167. if (Option_isNone(v)) {
  2168. --size.value
  2169. return new EmptyNode()
  2170. }
  2171. if (canEditNode(this, edit)) {
  2172. this.value = v
  2173. return this
  2174. }
  2175. return new LeafNode(edit, hash, key, v)
  2176. }
  2177. const v = f(Option_none())
  2178. if (Option_isNone(v)) return this
  2179. ++size.value
  2180. return mergeLeaves(
  2181. edit,
  2182. shift,
  2183. this.hash,
  2184. this,
  2185. hash,
  2186. new LeafNode(edit, hash, key, v)
  2187. )
  2188. }
  2189. }
  2190. class CollisionNode {
  2191. constructor(edit, hash, children) {
  2192. this.edit = edit
  2193. this.hash = hash
  2194. this.children = children
  2195. this._tag = "CollisionNode"
  2196. }
  2197. modify(edit, shift, f, hash, key, size) {
  2198. if (hash === this.hash) {
  2199. const canEdit = canEditNode(this, edit),
  2200. list = this.updateCollisionList(
  2201. canEdit,
  2202. edit,
  2203. this.hash,
  2204. this.children,
  2205. f,
  2206. key,
  2207. size
  2208. )
  2209. return list === this.children
  2210. ? this
  2211. : list.length > 1
  2212. ? new CollisionNode(edit, this.hash, list)
  2213. : list[0]
  2214. }
  2215. const v = f(Option_none())
  2216. if (Option_isNone(v)) return this
  2217. ++size.value
  2218. return mergeLeaves(
  2219. edit,
  2220. shift,
  2221. this.hash,
  2222. this,
  2223. hash,
  2224. new LeafNode(edit, hash, key, v)
  2225. )
  2226. }
  2227. updateCollisionList(mutate, edit, hash, list, f, key, size) {
  2228. const len = list.length
  2229. for (let i = 0; i < len; ++i) {
  2230. const child = list[i]
  2231. if ("key" in child && equals(key, child.key)) {
  2232. const value = child.value,
  2233. newValue = f(value)
  2234. if (newValue === value) return list
  2235. if (Option_isNone(newValue)) {
  2236. --size.value
  2237. return arraySpliceOut(mutate, i, list)
  2238. }
  2239. return arrayUpdate(
  2240. mutate,
  2241. i,
  2242. new LeafNode(edit, hash, key, newValue),
  2243. list
  2244. )
  2245. }
  2246. }
  2247. const newValue = f(Option_none())
  2248. if (Option_isNone(newValue)) return list
  2249. ++size.value
  2250. return arrayUpdate(
  2251. mutate,
  2252. len,
  2253. new LeafNode(edit, hash, key, newValue),
  2254. list
  2255. )
  2256. }
  2257. }
  2258. class IndexedNode {
  2259. constructor(edit, mask, children) {
  2260. this.edit = edit
  2261. this.mask = mask
  2262. this.children = children
  2263. this._tag = "IndexedNode"
  2264. }
  2265. modify(edit, shift, f, hash, key, size) {
  2266. const mask = this.mask,
  2267. children = this.children,
  2268. frag = hashFragment(shift, hash),
  2269. bit = toBitmap(frag),
  2270. indx = fromBitmap(mask, bit),
  2271. exists = mask & bit,
  2272. canEdit = canEditNode(this, edit)
  2273. if (!exists) {
  2274. const _newChild = new EmptyNode().modify(
  2275. edit,
  2276. shift + SIZE,
  2277. f,
  2278. hash,
  2279. key,
  2280. size
  2281. )
  2282. return _newChild
  2283. ? children.length >= MAX_INDEX_NODE
  2284. ? (function (edit, frag, child, bitmap, subNodes) {
  2285. const arr = []
  2286. let bit = bitmap,
  2287. count = 0
  2288. for (let i = 0; bit; ++i) {
  2289. 1 & bit && (arr[i] = subNodes[count++])
  2290. bit >>>= 1
  2291. }
  2292. arr[frag] = child
  2293. return new ArrayNode(edit, count + 1, arr)
  2294. })(edit, frag, _newChild, mask, children)
  2295. : new IndexedNode(
  2296. edit,
  2297. mask | bit,
  2298. (function (mutate, at, v, arr) {
  2299. const len = arr.length
  2300. if (mutate) {
  2301. let i = len
  2302. for (; i >= at; ) arr[i--] = arr[i]
  2303. arr[at] = v
  2304. return arr
  2305. }
  2306. let i = 0,
  2307. g = 0
  2308. const out = new Array(len + 1)
  2309. for (; i < at; ) out[g++] = arr[i++]
  2310. out[at] = v
  2311. for (; i < len; ) out[++g] = arr[i++]
  2312. return out
  2313. })(canEdit, indx, _newChild, children)
  2314. )
  2315. : this
  2316. }
  2317. const current = children[indx],
  2318. child = current.modify(edit, shift + SIZE, f, hash, key, size)
  2319. if (current === child) return this
  2320. let newChildren,
  2321. bitmap = mask
  2322. if (isEmptyNode(child)) {
  2323. bitmap &= ~bit
  2324. if (!bitmap) return new EmptyNode()
  2325. if (
  2326. children.length <= 2 &&
  2327. (isEmptyNode((node = children[1 ^ indx])) ||
  2328. "LeafNode" === node._tag ||
  2329. "CollisionNode" === node._tag)
  2330. )
  2331. return children[1 ^ indx]
  2332. newChildren = arraySpliceOut(canEdit, indx, children)
  2333. } else newChildren = arrayUpdate(canEdit, indx, child, children)
  2334. var node
  2335. if (canEdit) {
  2336. this.mask = bitmap
  2337. this.children = newChildren
  2338. return this
  2339. }
  2340. return new IndexedNode(edit, bitmap, newChildren)
  2341. }
  2342. }
  2343. class ArrayNode {
  2344. constructor(edit, size, children) {
  2345. this.edit = edit
  2346. this.size = size
  2347. this.children = children
  2348. this._tag = "ArrayNode"
  2349. }
  2350. modify(edit, shift, f, hash, key, size) {
  2351. let count = this.size
  2352. const children = this.children,
  2353. frag = hashFragment(shift, hash),
  2354. child = children[frag],
  2355. newChild = (child || new EmptyNode()).modify(
  2356. edit,
  2357. shift + SIZE,
  2358. f,
  2359. hash,
  2360. key,
  2361. size
  2362. )
  2363. if (child === newChild) return this
  2364. const canEdit = canEditNode(this, edit)
  2365. let newChildren
  2366. if (isEmptyNode(child) && !isEmptyNode(newChild)) {
  2367. ++count
  2368. newChildren = arrayUpdate(canEdit, frag, newChild, children)
  2369. } else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
  2370. --count
  2371. if (count <= MIN_ARRAY_NODE)
  2372. return (function (edit, count, removed, elements) {
  2373. const children = new Array(count - 1)
  2374. let g = 0,
  2375. bitmap = 0
  2376. for (let i = 0, len = elements.length; i < len; ++i)
  2377. if (i !== removed) {
  2378. const elem = elements[i]
  2379. if (elem && !isEmptyNode(elem)) {
  2380. children[g++] = elem
  2381. bitmap |= 1 << i
  2382. }
  2383. }
  2384. return new IndexedNode(edit, bitmap, children)
  2385. })(edit, count, frag, children)
  2386. newChildren = arrayUpdate(canEdit, frag, new EmptyNode(), children)
  2387. } else newChildren = arrayUpdate(canEdit, frag, newChild, children)
  2388. if (canEdit) {
  2389. this.size = count
  2390. this.children = newChildren
  2391. return this
  2392. }
  2393. return new ArrayNode(edit, count, newChildren)
  2394. }
  2395. }
  2396. function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
  2397. if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1])
  2398. const subH1 = hashFragment(shift, h1),
  2399. subH2 = hashFragment(shift, h2)
  2400. if (subH1 === subH2)
  2401. return child =>
  2402. new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child])
  2403. {
  2404. const children = subH1 < subH2 ? [n1, n2] : [n2, n1]
  2405. return new IndexedNode(
  2406. edit,
  2407. toBitmap(subH1) | toBitmap(subH2),
  2408. children
  2409. )
  2410. }
  2411. }
  2412. function mergeLeaves(edit, shift, h1, n1, h2, n2) {
  2413. let stack,
  2414. currentShift = shift
  2415. for (;;) {
  2416. const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2)
  2417. if ("function" != typeof res) {
  2418. let final = res
  2419. for (; null != stack; ) {
  2420. final = stack.value(final)
  2421. stack = stack.previous
  2422. }
  2423. return final
  2424. }
  2425. stack = new Stack(res, stack)
  2426. currentShift += SIZE
  2427. }
  2428. }
  2429. const HashMapTypeId = Symbol.for("@effect/data/HashMap")
  2430. class HashMapImpl {
  2431. constructor(_editable, _edit, _root, _size) {
  2432. this._editable = _editable
  2433. this._edit = _edit
  2434. this._root = _root
  2435. this._size = _size
  2436. this._id = HashMapTypeId
  2437. }
  2438. [Symbol.iterator]() {
  2439. return new HashMapIterator(this, (k, v) => [k, v])
  2440. }
  2441. [symbol]() {
  2442. let hash = Hash_hash("HashMap")
  2443. for (const item of this)
  2444. hash ^= combine(Hash_hash(item[0]))(Hash_hash(item[1]))
  2445. return hash
  2446. }
  2447. [Equal_symbol](that) {
  2448. if (isHashMap(that)) {
  2449. if (that._size !== this._size) return !1
  2450. for (const item of this) {
  2451. const elem = getHash(item[0], Hash_hash(item[0]))(that)
  2452. if (Option_isNone(elem)) return !1
  2453. if (!equals(item[1], elem.value)) return !1
  2454. }
  2455. return !0
  2456. }
  2457. return !1
  2458. }
  2459. toString() {
  2460. return `HashMap(${Array.from(this)
  2461. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  2462. .join(", ")})`
  2463. }
  2464. toJSON() {
  2465. return { _tag: "HashMap", values: Array.from(this) }
  2466. }
  2467. [Symbol.for("nodejs.util.inspect.custom")]() {
  2468. return this.toJSON()
  2469. }
  2470. }
  2471. class HashMapIterator {
  2472. constructor(map, f) {
  2473. this.map = map
  2474. this.f = f
  2475. this.v = visitLazy(this.map._root, this.f, void 0)
  2476. }
  2477. next() {
  2478. if (Option_isNone(this.v)) return { done: !0, value: void 0 }
  2479. const v0 = this.v.value
  2480. this.v = applyCont(v0.cont)
  2481. return { done: !1, value: v0.value }
  2482. }
  2483. [Symbol.iterator]() {
  2484. return new HashMapIterator(this.map, this.f)
  2485. }
  2486. }
  2487. const applyCont = cont =>
  2488. cont
  2489. ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4])
  2490. : Option_none(),
  2491. visitLazy = (node, f, cont = undefined) => {
  2492. switch (node._tag) {
  2493. case "LeafNode":
  2494. return Option_isSome(node.value)
  2495. ? Option_some({ value: f(node.key, node.value.value), cont })
  2496. : applyCont(cont)
  2497. case "CollisionNode":
  2498. case "ArrayNode":
  2499. case "IndexedNode": {
  2500. const children = node.children
  2501. return visitLazyChildren(children.length, children, 0, f, cont)
  2502. }
  2503. default:
  2504. return applyCont(cont)
  2505. }
  2506. },
  2507. visitLazyChildren = (len, children, i, f, cont) => {
  2508. for (; i < len; ) {
  2509. const child = children[i++]
  2510. if (child && !isEmptyNode(child))
  2511. return visitLazy(child, f, [len, children, i, f, cont])
  2512. }
  2513. return applyCont(cont)
  2514. },
  2515. HashMap_empty = () => new HashMapImpl(!1, 0, new EmptyNode(), 0),
  2516. isHashMap = u =>
  2517. "object" == typeof u &&
  2518. null != u &&
  2519. "_id" in u &&
  2520. u._id === HashMapTypeId,
  2521. HashMap_get = Function_dual(2, (self, key) =>
  2522. getHash(self, key, Hash_hash(key))
  2523. ),
  2524. getHash = Function_dual(3, (self, key, hash) => {
  2525. let node = self._root,
  2526. shift = 0
  2527. for (;;)
  2528. switch (node._tag) {
  2529. case "LeafNode":
  2530. return equals(key, node.key) ? node.value : Option_none()
  2531. case "CollisionNode":
  2532. if (hash === node.hash) {
  2533. const children = node.children
  2534. for (let i = 0, len = children.length; i < len; ++i) {
  2535. const child = children[i]
  2536. if ("key" in child && equals(key, child.key))
  2537. return child.value
  2538. }
  2539. }
  2540. return Option_none()
  2541. case "IndexedNode": {
  2542. const bit = toBitmap(hashFragment(shift, hash))
  2543. if (node.mask & bit) {
  2544. node = node.children[fromBitmap(node.mask, bit)]
  2545. shift += SIZE
  2546. break
  2547. }
  2548. return Option_none()
  2549. }
  2550. case "ArrayNode":
  2551. node = node.children[hashFragment(shift, hash)]
  2552. if (node) {
  2553. shift += SIZE
  2554. break
  2555. }
  2556. return Option_none()
  2557. default:
  2558. return Option_none()
  2559. }
  2560. }),
  2561. HashMap_has = Function_dual(2, (self, key) =>
  2562. Option_isSome(getHash(self, key, Hash_hash(key)))
  2563. ),
  2564. set = Function_dual(3, (self, key, value) =>
  2565. modifyAt(self, key, () => Option_some(value))
  2566. ),
  2567. setTree = Function_dual(3, (self, newRoot, newSize) => {
  2568. if (self._editable) {
  2569. self._root = newRoot
  2570. self._size = newSize
  2571. return self
  2572. }
  2573. return newRoot === self._root
  2574. ? self
  2575. : new HashMapImpl(self._editable, self._edit, newRoot, newSize)
  2576. }),
  2577. HashMap_size = self => self._size,
  2578. beginMutation = self =>
  2579. new HashMapImpl(!0, self._edit + 1, self._root, self._size),
  2580. endMutation = self => {
  2581. self._editable = !1
  2582. return self
  2583. },
  2584. modifyAt = Function_dual(3, (self, key, f) =>
  2585. modifyHash(self, key, Hash_hash(key), f)
  2586. ),
  2587. modifyHash = Function_dual(4, (self, key, hash, f) => {
  2588. const size = { value: self._size },
  2589. newRoot = self._root.modify(
  2590. self._editable ? self._edit : NaN,
  2591. 0,
  2592. f,
  2593. hash,
  2594. key,
  2595. size
  2596. )
  2597. return setTree(newRoot, size.value)(self)
  2598. }),
  2599. HashMap_remove = Function_dual(2, (self, key) =>
  2600. modifyAt(self, key, Option_none)
  2601. ),
  2602. forEachWithIndex = Function_dual(2, (self, f) =>
  2603. HashMap_reduceWithIndex(self, void 0, (_, value, key) => f(value, key))
  2604. ),
  2605. HashMap_reduceWithIndex = Function_dual(3, (self, zero, f) => {
  2606. const root = self._root
  2607. if ("LeafNode" === root._tag)
  2608. return Option_isSome(root.value)
  2609. ? f(zero, root.value.value, root.key)
  2610. : zero
  2611. if ("EmptyNode" === root._tag) return zero
  2612. const toVisit = [root.children]
  2613. let children
  2614. for (; (children = toVisit.pop()); )
  2615. for (let i = 0, len = children.length; i < len; ) {
  2616. const child = children[i++]
  2617. child &&
  2618. !isEmptyNode(child) &&
  2619. ("LeafNode" === child._tag
  2620. ? Option_isSome(child.value) &&
  2621. (zero = f(zero, child.value.value, child.key))
  2622. : toVisit.push(child.children))
  2623. }
  2624. return zero
  2625. }),
  2626. HashSetTypeId = Symbol.for("@effect/data/HashSet")
  2627. class HashSetImpl {
  2628. constructor(_keyMap) {
  2629. this._keyMap = _keyMap
  2630. this._id = HashSetTypeId
  2631. }
  2632. [Symbol.iterator]() {
  2633. return (self => new HashMapIterator(self, key => key))(this._keyMap)
  2634. }
  2635. [symbol]() {
  2636. return combine(Hash_hash(this._keyMap))(Hash_hash("HashSet"))
  2637. }
  2638. [Equal_symbol](that) {
  2639. return (
  2640. !!isHashSet(that) &&
  2641. HashMap_size(this._keyMap) === HashMap_size(that._keyMap) &&
  2642. equals(this._keyMap, that._keyMap)
  2643. )
  2644. }
  2645. toString() {
  2646. return `HashSet(${Array.from(this).map(String).join(", ")})`
  2647. }
  2648. toJSON() {
  2649. return { _tag: "HashSet", values: Array.from(this) }
  2650. }
  2651. [Symbol.for("nodejs.util.inspect.custom")]() {
  2652. return this.toJSON()
  2653. }
  2654. }
  2655. const isHashSet = u =>
  2656. "object" == typeof u &&
  2657. null != u &&
  2658. "_id" in u &&
  2659. u._id === HashSetTypeId,
  2660. HashSet_empty = () => new HashSetImpl(HashMap_empty()),
  2661. HashSet_has = Function_dual(2, (self, value) =>
  2662. HashMap_has(self._keyMap, value)
  2663. ),
  2664. HashSet_beginMutation = self =>
  2665. new HashSetImpl(beginMutation(self._keyMap)),
  2666. HashSet_endMutation = self => {
  2667. self._keyMap._editable = !1
  2668. return self
  2669. },
  2670. HashSet_mutate = Function_dual(2, (self, f) => {
  2671. const transient = HashSet_beginMutation(self)
  2672. f(transient)
  2673. return HashSet_endMutation(transient)
  2674. }),
  2675. HashSet_add = Function_dual(2, (self, value) =>
  2676. self._keyMap._editable
  2677. ? (set(value, !0)(self._keyMap), self)
  2678. : new HashSetImpl(set(value, !0)(self._keyMap))
  2679. ),
  2680. HashSet_remove = Function_dual(2, (self, value) =>
  2681. self._keyMap._editable
  2682. ? (HashMap_remove(value)(self._keyMap), self)
  2683. : new HashSetImpl(HashMap_remove(value)(self._keyMap))
  2684. ),
  2685. HashSet_difference = Function_dual(2, (self, that) =>
  2686. HashSet_mutate(self, set => {
  2687. for (const value of that) HashSet_remove(set, value)
  2688. })
  2689. ),
  2690. HashSet_union = Function_dual(2, (self, that) =>
  2691. HashSet_mutate(HashSet_empty(), set => {
  2692. HashSet_forEach(self, value => HashSet_add(set, value))
  2693. for (const value of that) HashSet_add(set, value)
  2694. })
  2695. ),
  2696. HashSet_forEach = Function_dual(2, (self, f) =>
  2697. forEachWithIndex(self._keyMap, (_, k) => f(k))
  2698. ),
  2699. HashSet_reduce = Function_dual(3, (self, zero, f) =>
  2700. HashMap_reduceWithIndex(self._keyMap, zero, (z, _, a) => f(z, a))
  2701. ),
  2702. mjs_HashMap_empty = HashMap_empty,
  2703. mjs_HashMap_fromIterable = entries => {
  2704. const map = beginMutation(HashMap_empty())
  2705. for (const entry of entries) set(entry[0], entry[1])(map)
  2706. return endMutation(map)
  2707. },
  2708. mjs_HashMap_get = HashMap_get,
  2709. HashMap_set = set,
  2710. mjs_HashMap_size = HashMap_size,
  2711. mjs_HashSet_empty = HashSet_empty,
  2712. mjs_HashSet_fromIterable = elements => {
  2713. const set = HashSet_beginMutation(HashSet_empty())
  2714. for (const value of elements) HashSet_add(set, value)
  2715. return HashSet_endMutation(set)
  2716. },
  2717. mjs_HashSet_make = (...elements) => {
  2718. const set = HashSet_beginMutation(HashSet_empty())
  2719. for (const value of elements) HashSet_add(set, value)
  2720. return HashSet_endMutation(set)
  2721. },
  2722. mjs_HashSet_has = HashSet_has,
  2723. mjs_HashSet_size = self => HashMap_size(self._keyMap),
  2724. mjs_HashSet_add = HashSet_add,
  2725. mjs_HashSet_remove = HashSet_remove,
  2726. mjs_HashSet_difference = HashSet_difference,
  2727. mjs_HashSet_union = HashSet_union,
  2728. mjs_HashSet_forEach = HashSet_forEach,
  2729. mjs_HashSet_reduce = HashSet_reduce,
  2730. HashSetPatchTypeId = Symbol.for("@effect/data/Differ/HashSetPatch")
  2731. function HashSetPatch_variance(a) {
  2732. return a
  2733. }
  2734. class HashSetPatch_Empty {
  2735. constructor() {
  2736. this._tag = "Empty"
  2737. this._Value = HashSetPatch_variance
  2738. this._id = HashSetPatchTypeId
  2739. }
  2740. [symbol]() {
  2741. return string("HashSetPatch(Empty)")
  2742. }
  2743. [Equal_symbol](that) {
  2744. return (
  2745. "object" == typeof that &&
  2746. null !== that &&
  2747. "_id" in that &&
  2748. that._id === this._id &&
  2749. "_tag" in that &&
  2750. that._tag === this._id
  2751. )
  2752. }
  2753. }
  2754. class HashSetPatch_AndThen {
  2755. constructor(first, second) {
  2756. this.first = first
  2757. this.second = second
  2758. this._tag = "AndThen"
  2759. this._Value = HashSetPatch_variance
  2760. this._id = HashSetPatchTypeId
  2761. }
  2762. [symbol]() {
  2763. return string("HashSetPatch(AndThen)")
  2764. }
  2765. [Equal_symbol](that) {
  2766. return (
  2767. "object" == typeof that &&
  2768. null !== that &&
  2769. "_id" in that &&
  2770. that._id === this._id &&
  2771. "_tag" in that &&
  2772. that._tag === this._id &&
  2773. equals(this.first, that.first) &&
  2774. equals(this.second, that.second)
  2775. )
  2776. }
  2777. }
  2778. class HashSetPatch_Add {
  2779. constructor(value) {
  2780. this.value = value
  2781. this._tag = "Add"
  2782. this._Value = HashSetPatch_variance
  2783. this._id = HashSetPatchTypeId
  2784. }
  2785. [symbol]() {
  2786. return string("HashSetPatch(Add)")
  2787. }
  2788. [Equal_symbol](that) {
  2789. return (
  2790. "object" == typeof that &&
  2791. null !== that &&
  2792. "_id" in that &&
  2793. that._id === this._id &&
  2794. "_tag" in that &&
  2795. that._tag === this._id &&
  2796. equals(this.value, that.value)
  2797. )
  2798. }
  2799. }
  2800. class HashSetPatch_Remove {
  2801. constructor(value) {
  2802. this.value = value
  2803. this._tag = "Remove"
  2804. this._Value = HashSetPatch_variance
  2805. this._id = HashSetPatchTypeId
  2806. }
  2807. [symbol]() {
  2808. return string("HashSetPatch(Remove)")
  2809. }
  2810. [Equal_symbol](that) {
  2811. return (
  2812. "object" == typeof that &&
  2813. null !== that &&
  2814. "_id" in that &&
  2815. that._id === this._id &&
  2816. "_tag" in that &&
  2817. that._tag === this._id &&
  2818. equals(this.value, that.value)
  2819. )
  2820. }
  2821. }
  2822. const HashSetPatch_empty = () => new HashSetPatch_Empty(),
  2823. HashSetPatch_combine = Function_dual(
  2824. 2,
  2825. (self, that) => new HashSetPatch_AndThen(self, that)
  2826. ),
  2827. HashSetPatch_patch = Function_dual(2, (self, oldValue) => {
  2828. let set = oldValue,
  2829. patches = Chunk_of(self)
  2830. for (; Chunk_isNonEmpty(patches); ) {
  2831. const head = Chunk_headNonEmpty(patches),
  2832. tail = Chunk_tailNonEmpty(patches)
  2833. switch (head._tag) {
  2834. case "Empty":
  2835. patches = tail
  2836. break
  2837. case "AndThen":
  2838. patches = Chunk_prepend(head.first)(
  2839. Chunk_prepend(head.second)(tail)
  2840. )
  2841. break
  2842. case "Add":
  2843. set = mjs_HashSet_add(head.value)(set)
  2844. patches = tail
  2845. break
  2846. case "Remove":
  2847. set = mjs_HashSet_remove(head.value)(set)
  2848. patches = tail
  2849. }
  2850. }
  2851. return set
  2852. }),
  2853. Differ_HashSetPatch_empty = HashSetPatch_empty,
  2854. Differ_HashSetPatch_combine = HashSetPatch_combine,
  2855. Differ_HashSetPatch_patch = HashSetPatch_patch,
  2856. DifferTypeId = Symbol.for("@effect/data/Differ")
  2857. class DifferImpl {
  2858. constructor(params) {
  2859. this._id = DifferTypeId
  2860. this._P = Function_identity
  2861. this._V = Function_identity
  2862. this.empty = params.empty
  2863. this.diff = params.diff
  2864. this.combine = params.combine
  2865. this.patch = params.patch
  2866. }
  2867. }
  2868. const Differ_make = params => new DifferImpl(params),
  2869. Differ_diff = Function_dual(3, (self, oldValue, newValue) =>
  2870. self.diff(oldValue, newValue)
  2871. ),
  2872. Differ_combine = Function_dual(3, (self, first, second) =>
  2873. self.combine(first, second)
  2874. ),
  2875. Differ_patch = Function_dual(3, (self, patch, oldValue) =>
  2876. self.patch(patch, oldValue)
  2877. ),
  2878. mjs_Differ_make = Differ_make,
  2879. Differ_environment = () =>
  2880. Differ_make({
  2881. empty: Differ_ContextPatch_empty(),
  2882. combine: (first, second) =>
  2883. Differ_ContextPatch_combine(second)(first),
  2884. diff: (oldValue, newValue) =>
  2885. ((oldValue, newValue) => {
  2886. const missingServices = new Map(oldValue.unsafeMap)
  2887. let patch = ContextPatch_empty()
  2888. for (const [tag, newService] of newValue.unsafeMap.entries())
  2889. if (missingServices.has(tag)) {
  2890. const old = missingServices.get(tag)
  2891. missingServices.delete(tag)
  2892. equals(old, newService) ||
  2893. (patch = ContextPatch_combine(
  2894. new UpdateService(tag, () => newService)
  2895. )(patch))
  2896. } else {
  2897. missingServices.delete(tag)
  2898. patch = ContextPatch_combine(new AddService(tag, newService))(
  2899. patch
  2900. )
  2901. }
  2902. for (const [tag] of missingServices.entries())
  2903. patch = ContextPatch_combine(new RemoveService(tag))(patch)
  2904. return patch
  2905. })(oldValue, newValue),
  2906. patch: (patch, oldValue) =>
  2907. Differ_ContextPatch_patch(oldValue)(patch),
  2908. }),
  2909. Differ_hashSet = () =>
  2910. Differ_make({
  2911. empty: Differ_HashSetPatch_empty(),
  2912. combine: (first, second) =>
  2913. Differ_HashSetPatch_combine(second)(first),
  2914. diff: (oldValue, newValue) =>
  2915. ((oldValue, newValue) => {
  2916. const [removed, patch] = mjs_HashSet_reduce(
  2917. [oldValue, HashSetPatch_empty()],
  2918. ([set, patch], value) =>
  2919. mjs_HashSet_has(value)(set)
  2920. ? [mjs_HashSet_remove(value)(set), patch]
  2921. : [
  2922. set,
  2923. HashSetPatch_combine(new HashSetPatch_Add(value))(
  2924. patch
  2925. ),
  2926. ]
  2927. )(newValue)
  2928. return mjs_HashSet_reduce(patch, (patch, value) =>
  2929. HashSetPatch_combine(new HashSetPatch_Remove(value))(patch)
  2930. )(removed)
  2931. })(oldValue, newValue),
  2932. patch: (patch, oldValue) =>
  2933. Differ_HashSetPatch_patch(oldValue)(patch),
  2934. }),
  2935. Differ_update = () => {
  2936. return (
  2937. (f = (_, a) => a),
  2938. Differ_make({
  2939. empty: Function_identity,
  2940. combine: (first, second) =>
  2941. first === Function_identity
  2942. ? second
  2943. : second === Function_identity
  2944. ? first
  2945. : a => second(first(a)),
  2946. diff: (oldValue, newValue) =>
  2947. equals(oldValue, newValue)
  2948. ? Function_identity
  2949. : constant(newValue),
  2950. patch: (patch, oldValue) => f(oldValue, patch(oldValue)),
  2951. })
  2952. )
  2953. var f
  2954. },
  2955. MutableRef_TypeId = Symbol.for("@effect/data/MutableRef")
  2956. class MutableRefImpl {
  2957. constructor(current) {
  2958. this.current = current
  2959. this._T = _ => _
  2960. this._id = MutableRef_TypeId
  2961. }
  2962. toString() {
  2963. return `MutableRef(${String(this.current)})`
  2964. }
  2965. toJSON() {
  2966. return { _tag: "MutableRef", current: this.current }
  2967. }
  2968. [Symbol.for("nodejs.util.inspect.custom")]() {
  2969. return this.toJSON()
  2970. }
  2971. }
  2972. const MutableRef_make = value => new MutableRefImpl(value),
  2973. MutableRef_get = self => self.current,
  2974. getAndSet = Function_dual(2, (self, value) => {
  2975. const ret = self.current
  2976. self.current = value
  2977. return ret
  2978. }),
  2979. getAndUpdate = Function_dual(2, (self, f) =>
  2980. getAndSet(self, f(MutableRef_get(self)))
  2981. ),
  2982. MutableRef_set = Function_dual(2, (self, value) => {
  2983. self.current = value
  2984. return self
  2985. }),
  2986. MutableRef_update = Function_dual(2, (self, f) =>
  2987. MutableRef_set(self, f(MutableRef_get(self)))
  2988. )
  2989. var fiberId_a, fiberId_b
  2990. const FiberIdTypeId = Symbol.for("@effect/io/Fiber/Id")
  2991. class fiberId_None {
  2992. constructor() {
  2993. this[fiberId_a] = FiberIdTypeId
  2994. this._tag = "None"
  2995. }
  2996. [((fiberId_a = FiberIdTypeId), symbol)]() {
  2997. return combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Id"))
  2998. }
  2999. [Equal_symbol](that) {
  3000. return isFiberId(that) && "None" === that._tag
  3001. }
  3002. }
  3003. class Runtime {
  3004. constructor(id, startTimeMillis) {
  3005. this.id = id
  3006. this.startTimeMillis = startTimeMillis
  3007. this[fiberId_b] = FiberIdTypeId
  3008. this._tag = "Runtime"
  3009. }
  3010. [((fiberId_b = FiberIdTypeId), symbol)]() {
  3011. return combine(Hash_hash(this.startTimeMillis))(
  3012. combine(Hash_hash(this.id))(
  3013. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Id"))
  3014. )
  3015. )
  3016. }
  3017. [Equal_symbol](that) {
  3018. return (
  3019. isFiberId(that) &&
  3020. "Runtime" === that._tag &&
  3021. this.id === that.id &&
  3022. this.startTimeMillis === that.startTimeMillis
  3023. )
  3024. }
  3025. }
  3026. const fiberId_none = new fiberId_None(),
  3027. isFiberId = self =>
  3028. "object" == typeof self && null != self && FiberIdTypeId in self,
  3029. ids = self => {
  3030. switch (self._tag) {
  3031. case "None":
  3032. return mjs_HashSet_empty()
  3033. case "Runtime":
  3034. return mjs_HashSet_make(self.id)
  3035. case "Composite":
  3036. return mjs_HashSet_union(ids(self.right))(ids(self.left))
  3037. }
  3038. },
  3039. _fiberCounter = globalValue(
  3040. Symbol.for("@effect/io/Fiber/Id/_fiberCounter"),
  3041. () => MutableRef_make(0)
  3042. ),
  3043. threadName = self =>
  3044. Array.from(ids(self))
  3045. .map(n => `#${n}`)
  3046. .join(","),
  3047. Id_none = fiberId_none,
  3048. Id_unsafeMake = () => {
  3049. const id = MutableRef_get(_fiberCounter)
  3050. MutableRef_set(id + 1)(_fiberCounter)
  3051. return new Runtime(id, new Date().getTime())
  3052. },
  3053. active = patch => 255 & patch,
  3054. enabled = patch => (patch >> 8) & 255,
  3055. runtimeFlagsPatch_make = (active, enabled) =>
  3056. (255 & active) + ((enabled & active & 255) << 8),
  3057. runtimeFlagsPatch_empty = runtimeFlagsPatch_make(0, 0),
  3058. exclude = Function_dual(2, (self, flag) =>
  3059. runtimeFlagsPatch_make(active(self) & ~flag, enabled(self))
  3060. ),
  3061. andThen = Function_dual(2, (self, that) => self | that),
  3062. cooperativeYielding = self => runtimeFlags_isEnabled(self, 32),
  3063. runtimeFlags_enable = Function_dual(2, (self, flag) => self | flag),
  3064. interruptible = self => interruption(self) && !windDown(self),
  3065. interruption = self => runtimeFlags_isEnabled(self, 1),
  3066. runtimeFlags_isEnabled = Function_dual(
  3067. 2,
  3068. (self, flag) => 0 != (self & flag)
  3069. ),
  3070. runtimeFlags_make = (...flags) => flags.reduce((a, b) => a | b, 0),
  3071. runtimeFlags_none = runtimeFlags_make(0),
  3072. opSupervision = self => runtimeFlags_isEnabled(self, 2),
  3073. runtimeMetrics = self => runtimeFlags_isEnabled(self, 4),
  3074. windDown = self => runtimeFlags_isEnabled(self, 16),
  3075. runtimeFlags_diff = Function_dual(2, (self, that) =>
  3076. runtimeFlagsPatch_make(self ^ that, that)
  3077. ),
  3078. runtimeFlags_patch = Function_dual(
  3079. 2,
  3080. (self, patch) =>
  3081. (self & (((~active(patch) >>> 0) & 255) | enabled(patch))) |
  3082. (active(patch) & enabled(patch))
  3083. ),
  3084. Patch_empty = runtimeFlagsPatch_empty,
  3085. Patch_disable = flag => runtimeFlagsPatch_make(flag, 0),
  3086. Patch_exclude = exclude
  3087. var cause_a
  3088. const CauseTypeId = Symbol.for("@effect/io/Cause"),
  3089. proto = {
  3090. [CauseTypeId]: { _E: _ => _ },
  3091. [symbol]() {
  3092. return combine(Hash_hash(flattenCause(this)))(
  3093. Hash_hash("@effect/io/Cause")
  3094. )
  3095. },
  3096. [Equal_symbol](that) {
  3097. return isCause(that) && causeEquals(this, that)
  3098. },
  3099. },
  3100. cause_empty = (() => {
  3101. const o = Object.create(proto)
  3102. o._tag = "Empty"
  3103. return o
  3104. })(),
  3105. fail = error => {
  3106. const o = Object.create(proto)
  3107. o._tag = "Fail"
  3108. o.error = error
  3109. return o
  3110. },
  3111. die = defect => {
  3112. const o = Object.create(proto)
  3113. o._tag = "Die"
  3114. o.defect = defect
  3115. return o
  3116. },
  3117. interrupt = fiberId => {
  3118. const o = Object.create(proto)
  3119. o._tag = "Interrupt"
  3120. o.fiberId = fiberId
  3121. return o
  3122. },
  3123. annotated = (cause, annotation) => {
  3124. const o = Object.create(proto)
  3125. o._tag = "Annotated"
  3126. o.cause = cause
  3127. o.annotation = annotation
  3128. return o
  3129. },
  3130. parallel = (left, right) => {
  3131. const o = Object.create(proto)
  3132. o._tag = "Parallel"
  3133. o.left = left
  3134. o.right = right
  3135. return o
  3136. },
  3137. sequential = (left, right) => {
  3138. const o = Object.create(proto)
  3139. o._tag = "Sequential"
  3140. o.left = left
  3141. o.right = right
  3142. return o
  3143. },
  3144. isCause = u => "object" == typeof u && null != u && CauseTypeId in u,
  3145. isEmptyType = self => "Empty" === self._tag,
  3146. isInterruptedOnly = self =>
  3147. reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self),
  3148. cause_defects = self =>
  3149. Chunk_reverse(
  3150. cause_reduce(self, Chunk_empty(), (list, cause) =>
  3151. "Die" === cause._tag
  3152. ? Option_some(Chunk_prepend(cause.defect)(list))
  3153. : Option_none()
  3154. )
  3155. ),
  3156. failureOrCause = self => {
  3157. const option = (self =>
  3158. find(self, cause =>
  3159. "Fail" === cause._tag ? Option_some(cause.error) : Option_none()
  3160. ))(self)
  3161. switch (option._tag) {
  3162. case "None":
  3163. return Either_right(self)
  3164. case "Some":
  3165. return Either_left(option.value)
  3166. }
  3167. },
  3168. stripFailures = self =>
  3169. cause_match(
  3170. self,
  3171. cause_empty,
  3172. () => cause_empty,
  3173. defect => die(defect),
  3174. fiberId => interrupt(fiberId),
  3175. (cause, annotation) =>
  3176. isEmptyType(cause) ? cause : annotated(cause, annotation),
  3177. (left, right) => sequential(left, right),
  3178. (left, right) => parallel(left, right)
  3179. ),
  3180. causeEquals = (left, right) => {
  3181. let leftStack = Chunk_of(left),
  3182. rightStack = Chunk_of(right)
  3183. for (; Chunk_isNonEmpty(leftStack) && Chunk_isNonEmpty(rightStack); ) {
  3184. const [leftParallel, leftSequential] = cause_reduce(
  3185. [mjs_HashSet_empty(), Chunk_empty()],
  3186. ([parallel, sequential], cause) => {
  3187. const [par, seq] = evaluateCause(cause)
  3188. return Option_some([
  3189. mjs_HashSet_union(par)(parallel),
  3190. Chunk_concat(seq)(sequential),
  3191. ])
  3192. }
  3193. )(Chunk_headNonEmpty(leftStack)),
  3194. [rightParallel, rightSequential] = cause_reduce(
  3195. [mjs_HashSet_empty(), Chunk_empty()],
  3196. ([parallel, sequential], cause) => {
  3197. const [par, seq] = evaluateCause(cause)
  3198. return Option_some([
  3199. mjs_HashSet_union(par)(parallel),
  3200. Chunk_concat(seq)(sequential),
  3201. ])
  3202. }
  3203. )(Chunk_headNonEmpty(rightStack))
  3204. if (!equals(leftParallel, rightParallel)) return !1
  3205. leftStack = leftSequential
  3206. rightStack = rightSequential
  3207. }
  3208. return !0
  3209. },
  3210. flattenCause = cause => flattenCauseLoop(Chunk_of(cause), Chunk_empty()),
  3211. flattenCauseLoop = (causes, flattened) => {
  3212. for (;;) {
  3213. const [parallel, sequential] = Chunk_reduce(
  3214. [mjs_HashSet_empty(), Chunk_empty()],
  3215. ([parallel, sequential], cause) => {
  3216. const [par, seq] = evaluateCause(cause)
  3217. return [
  3218. mjs_HashSet_union(par)(parallel),
  3219. Chunk_concat(seq)(sequential),
  3220. ]
  3221. }
  3222. )(causes),
  3223. updated =
  3224. mjs_HashSet_size(parallel) > 0
  3225. ? Chunk_prepend(parallel)(flattened)
  3226. : flattened
  3227. if (Chunk_isEmpty(sequential)) return Chunk_reverse(updated)
  3228. causes = sequential
  3229. flattened = updated
  3230. }
  3231. throw new Error(
  3232. "BUG: Cause.flattenCauseLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  3233. )
  3234. },
  3235. find = Function_dual(2, (self, pf) => {
  3236. const stack = [self]
  3237. for (; stack.length > 0; ) {
  3238. const item = stack.pop(),
  3239. option = pf(item)
  3240. switch (option._tag) {
  3241. case "None":
  3242. switch (item._tag) {
  3243. case "Sequential":
  3244. case "Parallel":
  3245. stack.push(item.right)
  3246. stack.push(item.left)
  3247. break
  3248. case "Annotated":
  3249. stack.push(item.cause)
  3250. }
  3251. break
  3252. case "Some":
  3253. return option
  3254. }
  3255. }
  3256. return Option_none()
  3257. }),
  3258. evaluateCause = self => {
  3259. let cause = self
  3260. const stack = []
  3261. let _parallel = mjs_HashSet_empty(),
  3262. _sequential = Chunk_empty()
  3263. for (; void 0 !== cause; )
  3264. switch (cause._tag) {
  3265. case "Empty":
  3266. if (0 === stack.length) return [_parallel, _sequential]
  3267. cause = stack.pop()
  3268. break
  3269. case "Fail":
  3270. if (0 === stack.length)
  3271. return [mjs_HashSet_add(cause.error)(_parallel), _sequential]
  3272. _parallel = mjs_HashSet_add(cause.error)(_parallel)
  3273. cause = stack.pop()
  3274. break
  3275. case "Die":
  3276. if (0 === stack.length)
  3277. return [mjs_HashSet_add(cause.defect)(_parallel), _sequential]
  3278. _parallel = mjs_HashSet_add(cause.defect)(_parallel)
  3279. cause = stack.pop()
  3280. break
  3281. case "Interrupt":
  3282. if (0 === stack.length)
  3283. return [mjs_HashSet_add(cause.fiberId)(_parallel), _sequential]
  3284. _parallel = mjs_HashSet_add(cause.fiberId)(_parallel)
  3285. cause = stack.pop()
  3286. break
  3287. case "Annotated":
  3288. cause = cause.cause
  3289. break
  3290. case "Sequential":
  3291. switch (cause.left._tag) {
  3292. case "Empty":
  3293. cause = cause.right
  3294. break
  3295. case "Sequential":
  3296. cause = sequential(
  3297. cause.left.left,
  3298. sequential(cause.left.right, cause.right)
  3299. )
  3300. break
  3301. case "Parallel":
  3302. cause = parallel(
  3303. sequential(cause.left.left, cause.right),
  3304. sequential(cause.left.right, cause.right)
  3305. )
  3306. break
  3307. case "Annotated":
  3308. cause = sequential(cause.left.cause, cause.right)
  3309. break
  3310. default:
  3311. _sequential = Chunk_prepend(cause.right)(_sequential)
  3312. cause = cause.left
  3313. }
  3314. break
  3315. case "Parallel":
  3316. stack.push(cause.right)
  3317. cause = cause.left
  3318. }
  3319. throw new Error(
  3320. "BUG: Cause.evaluateCauseLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  3321. )
  3322. },
  3323. IsInterruptedOnlyCauseReducer = {
  3324. emptyCase: Function_constTrue,
  3325. failCase: Function_constFalse,
  3326. dieCase: Function_constFalse,
  3327. interruptCase: Function_constTrue,
  3328. annotatedCase: (_, value) => value,
  3329. sequentialCase: (_, left, right) => left && right,
  3330. parallelCase: (_, left, right) => left && right,
  3331. },
  3332. cause_match = Function_dual(
  3333. 8,
  3334. (
  3335. self,
  3336. emptyCase,
  3337. failCase,
  3338. dieCase,
  3339. interruptCase,
  3340. annotatedCase,
  3341. sequentialCase,
  3342. parallelCase
  3343. ) =>
  3344. reduceWithContext(self, void 0, {
  3345. emptyCase: () => emptyCase,
  3346. failCase: (_, error) => failCase(error),
  3347. dieCase: (_, defect) => dieCase(defect),
  3348. interruptCase: (_, fiberId) => interruptCase(fiberId),
  3349. annotatedCase: (_, value, annotation) =>
  3350. annotatedCase(value, annotation),
  3351. sequentialCase: (_, left, right) => sequentialCase(left, right),
  3352. parallelCase: (_, left, right) => parallelCase(left, right),
  3353. })
  3354. ),
  3355. cause_reduce = Function_dual(3, (self, zero, pf) => {
  3356. let accumulator = zero,
  3357. cause = self
  3358. const causes = []
  3359. for (; void 0 !== cause; ) {
  3360. const option = pf(accumulator, cause)
  3361. accumulator = Option_isSome(option) ? option.value : accumulator
  3362. switch (cause._tag) {
  3363. case "Sequential":
  3364. case "Parallel":
  3365. causes.push(cause.right)
  3366. cause = cause.left
  3367. break
  3368. case "Annotated":
  3369. cause = cause.cause
  3370. break
  3371. default:
  3372. cause = void 0
  3373. }
  3374. void 0 === cause && causes.length > 0 && (cause = causes.pop())
  3375. }
  3376. return accumulator
  3377. }),
  3378. reduceWithContext = Function_dual(3, (self, context, reducer) => {
  3379. const input = [self],
  3380. output = []
  3381. for (; input.length > 0; ) {
  3382. const cause = input.pop()
  3383. switch (cause._tag) {
  3384. case "Empty":
  3385. output.push(Either_right(reducer.emptyCase(context)))
  3386. break
  3387. case "Fail":
  3388. output.push(Either_right(reducer.failCase(context, cause.error)))
  3389. break
  3390. case "Die":
  3391. output.push(Either_right(reducer.dieCase(context, cause.defect)))
  3392. break
  3393. case "Interrupt":
  3394. output.push(
  3395. Either_right(reducer.interruptCase(context, cause.fiberId))
  3396. )
  3397. break
  3398. case "Annotated":
  3399. input.push(cause.cause)
  3400. output.push(
  3401. Either_left({
  3402. _tag: "AnnotatedCase",
  3403. annotation: cause.annotation,
  3404. })
  3405. )
  3406. break
  3407. case "Sequential":
  3408. input.push(cause.right)
  3409. input.push(cause.left)
  3410. output.push(Either_left({ _tag: "SequentialCase" }))
  3411. break
  3412. case "Parallel":
  3413. input.push(cause.right)
  3414. input.push(cause.left)
  3415. output.push(Either_left({ _tag: "ParallelCase" }))
  3416. }
  3417. }
  3418. const accumulator = []
  3419. for (; output.length > 0; ) {
  3420. const either = output.pop()
  3421. switch (either._tag) {
  3422. case "Left":
  3423. switch (either.left._tag) {
  3424. case "SequentialCase": {
  3425. const left = accumulator.pop(),
  3426. right = accumulator.pop(),
  3427. value = reducer.sequentialCase(context, left, right)
  3428. accumulator.push(value)
  3429. break
  3430. }
  3431. case "ParallelCase": {
  3432. const left = accumulator.pop(),
  3433. right = accumulator.pop(),
  3434. value = reducer.parallelCase(context, left, right)
  3435. accumulator.push(value)
  3436. break
  3437. }
  3438. case "AnnotatedCase": {
  3439. const cause = accumulator.pop(),
  3440. value = reducer.annotatedCase(
  3441. context,
  3442. cause,
  3443. either.left.annotation
  3444. )
  3445. accumulator.push(value)
  3446. break
  3447. }
  3448. }
  3449. break
  3450. case "Right":
  3451. accumulator.push(either.right)
  3452. }
  3453. }
  3454. if (0 === accumulator.length)
  3455. throw new Error(
  3456. "BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/io/issues"
  3457. )
  3458. return accumulator.pop()
  3459. }),
  3460. makeException = (proto, tag) => {
  3461. const _tag = { value: tag, enumerable: !0 },
  3462. protoWithToString = {
  3463. ...proto,
  3464. toString() {
  3465. return `${this._tag}: ${this.message}`
  3466. },
  3467. }
  3468. return message =>
  3469. Object.create(protoWithToString, {
  3470. _tag,
  3471. message: { value: message, enumerable: !0 },
  3472. })
  3473. },
  3474. InterruptedExceptionTypeId = Symbol.for(
  3475. "@effect/io/Cause/errors/InterruptedException"
  3476. ),
  3477. isInterruptedException = u =>
  3478. "object" == typeof u && null != u && InterruptedExceptionTypeId in u,
  3479. NoSuchElementExceptionTypeId = Symbol.for(
  3480. "@effect/io/Cause/errors/NoSuchElement"
  3481. ),
  3482. NoSuchElementException = makeException(
  3483. { [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId },
  3484. "NoSuchElementException"
  3485. ),
  3486. StackAnnotationTypeId = Symbol.for("@effect/io/Cause/StackAnnotation")
  3487. class StackAnnotation {
  3488. constructor(stack, seq) {
  3489. this.stack = stack
  3490. this.seq = seq
  3491. this[cause_a] = StackAnnotationTypeId
  3492. }
  3493. }
  3494. cause_a = StackAnnotationTypeId
  3495. const globalErrorSeq = MutableRef_make(0),
  3496. isStackAnnotation = u =>
  3497. "object" == typeof u && null != u && StackAnnotationTypeId in u,
  3498. DeferredTypeId = Symbol.for("@effect/io/Deferred"),
  3499. deferredVariance = { _E: _ => _, _A: _ => _ },
  3500. pending = joiners => ({ _tag: "Pending", joiners }),
  3501. done = effect => ({ _tag: "Done", effect })
  3502. class DefaultScheduler {
  3503. constructor() {
  3504. this.running = !1
  3505. this.tasks = []
  3506. }
  3507. starveInternal(depth) {
  3508. const toRun = this.tasks
  3509. this.tasks = []
  3510. for (let i = 0; i < toRun.length; i++) toRun[i]()
  3511. 0 === this.tasks.length ? (this.running = !1) : this.starve(depth)
  3512. }
  3513. starve(depth = 0) {
  3514. depth >= 2048
  3515. ? setTimeout(() => this.starveInternal(0), 0)
  3516. : Promise.resolve(void 0).then(() => this.starveInternal(depth + 1))
  3517. }
  3518. scheduleTask(task) {
  3519. this.tasks.push(task)
  3520. if (!this.running) {
  3521. this.running = !0
  3522. this.starve()
  3523. }
  3524. }
  3525. }
  3526. const defaultScheduler = globalValue(
  3527. Symbol.for("@effect/io/Scheduler/defaultScheduler"),
  3528. () => new DefaultScheduler()
  3529. )
  3530. var core_a, core_b, core_c
  3531. const EffectErrorTypeId = Symbol.for("@effect/io/Effect/Error"),
  3532. isEffectError = u =>
  3533. "object" == typeof u && null != u && EffectErrorTypeId in u,
  3534. core_EffectTypeId = Symbol.for("@effect/io/Effect")
  3535. class RevertFlags {
  3536. constructor(patch) {
  3537. this.patch = patch
  3538. this._tag = "RevertFlags"
  3539. }
  3540. }
  3541. class EffectPrimitive {
  3542. constructor(_tag) {
  3543. this._tag = _tag
  3544. this.i0 = void 0
  3545. this.i1 = void 0
  3546. this.i2 = void 0
  3547. this.trace = void 0
  3548. this[core_a] = core_effectVariance
  3549. }
  3550. [((core_a = core_EffectTypeId), Equal_symbol)](that) {
  3551. return this === that
  3552. }
  3553. [symbol]() {
  3554. return random(this)
  3555. }
  3556. traced(trace) {
  3557. if (trace) {
  3558. const effect = new EffectPrimitive("Traced")
  3559. effect.i0 = this
  3560. effect.trace = trace
  3561. return effect
  3562. }
  3563. return this
  3564. }
  3565. }
  3566. class EffectPrimitiveFailure {
  3567. constructor(_tag) {
  3568. this._tag = _tag
  3569. this.i0 = void 0
  3570. this.i1 = void 0
  3571. this.i2 = void 0
  3572. this.trace = void 0
  3573. this[core_b] = core_effectVariance
  3574. }
  3575. [((core_b = core_EffectTypeId), Equal_symbol)](that) {
  3576. return this === that
  3577. }
  3578. [symbol]() {
  3579. return random(this)
  3580. }
  3581. get cause() {
  3582. return this.i0
  3583. }
  3584. traced(trace) {
  3585. if (trace) {
  3586. const effect = new EffectPrimitive("Traced")
  3587. effect.i0 = this
  3588. effect.trace = trace
  3589. return effect
  3590. }
  3591. return this
  3592. }
  3593. }
  3594. class EffectPrimitiveSuccess {
  3595. constructor(_tag) {
  3596. this._tag = _tag
  3597. this.i0 = void 0
  3598. this.i1 = void 0
  3599. this.i2 = void 0
  3600. this.trace = void 0
  3601. this[core_c] = core_effectVariance
  3602. }
  3603. [((core_c = core_EffectTypeId), Equal_symbol)](that) {
  3604. return this === that
  3605. }
  3606. [symbol]() {
  3607. return random(this)
  3608. }
  3609. get value() {
  3610. return this.i0
  3611. }
  3612. traced(trace) {
  3613. if (trace) {
  3614. const effect = new EffectPrimitive("Traced")
  3615. effect.i0 = this
  3616. effect.trace = trace
  3617. return effect
  3618. }
  3619. return this
  3620. }
  3621. }
  3622. const core_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  3623. isEffect = u =>
  3624. "object" == typeof u && null != u && core_EffectTypeId in u,
  3625. acquireUseRelease = dualWithTrace(
  3626. 3,
  3627. (trace, restoreTracing) => (acquire, use, release) =>
  3628. uninterruptibleMask(restore =>
  3629. core_flatMap(a =>
  3630. core_flatMap(exit =>
  3631. matchCauseEffect(
  3632. cause => {
  3633. switch (exit._tag) {
  3634. case "Failure":
  3635. return failCause(parallel(exit.i0, cause))
  3636. case "Success":
  3637. return failCause(cause)
  3638. }
  3639. },
  3640. () => exit
  3641. )(suspend(() => restoreTracing(release)(a, exit)))
  3642. )(core_exit(suspend(() => restore(restoreTracing(use)(a)))))
  3643. )(acquire)
  3644. ).traced(trace)
  3645. ),
  3646. core_as = dualWithTrace(
  3647. 2,
  3648. trace => (self, value) =>
  3649. core_flatMap(() => succeed(value))(self).traced(trace)
  3650. ),
  3651. core_asUnit = methodWithTrace(
  3652. trace => self => core_as(void 0)(self).traced(trace)
  3653. ),
  3654. core_async = methodWithTrace(
  3655. trace =>
  3656. (register, blockingOn = Id_none) => {
  3657. const effect = new EffectPrimitive("Async")
  3658. effect.i0 = register
  3659. effect.i1 = blockingOn
  3660. return trace ? effect.traced(trace) : effect
  3661. }
  3662. ),
  3663. asyncInterruptEither = methodWithTrace(
  3664. (trace, restore) =>
  3665. (register, blockingOn = Id_none) =>
  3666. suspend(() => {
  3667. let cancelerRef = core_unit()
  3668. return onInterrupt(() => cancelerRef)(
  3669. core_async(resume => {
  3670. const result = restore(register)(resume)
  3671. Either_isRight(result)
  3672. ? resume(result.right)
  3673. : (cancelerRef = result.left)
  3674. }, blockingOn)
  3675. )
  3676. }).traced(trace)
  3677. ),
  3678. asyncInterrupt = methodWithTrace(
  3679. (trace, restore) =>
  3680. (register, blockingOn = Id_none) =>
  3681. suspend(() => {
  3682. let cancelerRef = core_unit()
  3683. return onInterrupt(() => cancelerRef)(
  3684. core_async(resume => {
  3685. cancelerRef = restore(register)(resume)
  3686. }, blockingOn)
  3687. )
  3688. }).traced(trace)
  3689. ),
  3690. catchAll = dualWithTrace(
  3691. 2,
  3692. (trace, restore) => (self, f) =>
  3693. matchEffect(restore(f), succeed)(self).traced(trace)
  3694. ),
  3695. core_die = methodWithTrace(
  3696. trace => defect => failCause(die(defect)).traced(trace)
  3697. ),
  3698. core_either = methodWithTrace(
  3699. trace => self =>
  3700. matchEffect(
  3701. e => succeed(Either_left(e)),
  3702. a => succeed(Either_right(a))
  3703. )(self).traced(trace)
  3704. ),
  3705. context = methodWithTrace(
  3706. trace => () => suspend(() => fiberRefGet(currentContext)).traced(trace)
  3707. ),
  3708. contextWithEffect = methodWithTrace(
  3709. (trace, restore) => f =>
  3710. core_flatMap(restore(f))(context()).traced(trace)
  3711. ),
  3712. core_exit = methodWithTrace(
  3713. trace => self =>
  3714. matchCause(
  3715. cause => exitFailCause(cause),
  3716. a => exitSucceed(a)
  3717. )(self).traced(trace)
  3718. ),
  3719. core_fail = methodWithTrace(
  3720. trace => error => failCause(fail(error)).traced(trace)
  3721. ),
  3722. failSync = methodWithTrace(
  3723. (trace, restore) => evaluate =>
  3724. failCauseSync(() => fail(restore(evaluate)())).traced(trace)
  3725. ),
  3726. failCause = methodWithTrace(trace => cause => {
  3727. const effect = new EffectPrimitiveFailure("Failure")
  3728. effect.i0 = cause
  3729. return trace ? effect.traced(trace) : effect
  3730. }),
  3731. failCauseSync = methodWithTrace(
  3732. (trace, restore) => evaluate =>
  3733. core_flatMap(sync(restore(evaluate)), failCause).traced(trace)
  3734. ),
  3735. fiberId = methodWithTrace(
  3736. trace => () =>
  3737. withFiberRuntime(state => succeed(state.id())).traced(trace)
  3738. ),
  3739. core_flatMap = dualWithTrace(2, (trace, restore) => (self, f) => {
  3740. const effect = new EffectPrimitive("OnSuccess")
  3741. effect.i0 = self
  3742. effect.i1 = restore(f)
  3743. return trace ? effect.traced(trace) : effect
  3744. }),
  3745. core_flatten = methodWithTrace(
  3746. trace => self => core_flatMap(self, Function_identity).traced(trace)
  3747. ),
  3748. matchCause = dualWithTrace(
  3749. 3,
  3750. (trace, restore) => (self, onFailure, onSuccess) =>
  3751. matchCauseEffect(
  3752. cause => succeed(restore(onFailure)(cause)),
  3753. a => succeed(restore(onSuccess)(a))
  3754. )(self).traced(trace)
  3755. ),
  3756. matchCauseEffect = dualWithTrace(
  3757. 3,
  3758. (trace, restore) => (self, onFailure, onSuccess) => {
  3759. const effect = new EffectPrimitive("OnSuccessAndFailure")
  3760. effect.i0 = self
  3761. effect.i1 = restore(onFailure)
  3762. effect.i2 = restore(onSuccess)
  3763. return trace ? effect.traced(trace) : effect
  3764. }
  3765. ),
  3766. matchEffect = dualWithTrace(
  3767. 3,
  3768. (trace, restore) => (self, onFailure, onSuccess) =>
  3769. matchCauseEffect(
  3770. self,
  3771. cause => {
  3772. const failures = (self =>
  3773. Chunk_reverse(
  3774. cause_reduce(self, Chunk_empty(), (list, cause) =>
  3775. "Fail" === cause._tag
  3776. ? Option_some(Chunk_prepend(cause.error)(list))
  3777. : Option_none()
  3778. )
  3779. ))(cause)
  3780. return cause_defects(cause).length > 0
  3781. ? failCause(
  3782. (self =>
  3783. cause_match(
  3784. self,
  3785. cause_empty,
  3786. failure => die(failure),
  3787. defect => die(defect),
  3788. fiberId => interrupt(fiberId),
  3789. (cause, annotation) =>
  3790. isEmptyType(cause)
  3791. ? cause
  3792. : annotated(cause, annotation),
  3793. (left, right) => sequential(left, right),
  3794. (left, right) => parallel(left, right)
  3795. ))(cause)
  3796. )
  3797. : failures.length > 0
  3798. ? restore(onFailure)(unsafeHead(failures))
  3799. : failCause(cause)
  3800. },
  3801. onSuccess
  3802. ).traced(trace)
  3803. ),
  3804. core_forEach = dualWithTrace(
  3805. 2,
  3806. (trace, restore) => (self, f) =>
  3807. suspend(() => {
  3808. const arr = Array.from(self),
  3809. ret = new Array(arr.length)
  3810. let i = 0
  3811. return core_as(unsafeFromArray(ret))(
  3812. whileLoop(
  3813. () => i < arr.length,
  3814. () => restore(f)(arr[i]),
  3815. b => {
  3816. ret[i++] = b
  3817. }
  3818. )
  3819. )
  3820. }).traced(trace)
  3821. ),
  3822. forEachDiscard = dualWithTrace(
  3823. 2,
  3824. (trace, restore) => (self, f) =>
  3825. suspend(() => {
  3826. const arr = Array.from(self)
  3827. let i = 0
  3828. return whileLoop(
  3829. () => i < arr.length,
  3830. () => restore(f)(arr[i++]),
  3831. () => {}
  3832. )
  3833. }).traced(trace)
  3834. ),
  3835. core_fromOption = methodWithTrace(trace => option => {
  3836. switch (option._tag) {
  3837. case "None":
  3838. return core_fail(Option_none()).traced(trace)
  3839. case "Some":
  3840. return succeed(option.value).traced(trace)
  3841. }
  3842. }),
  3843. core_fromEither = methodWithTrace(trace => either => {
  3844. switch (either._tag) {
  3845. case "Left":
  3846. return core_fail(either.left).traced(trace)
  3847. case "Right":
  3848. return succeed(either.right).traced(trace)
  3849. }
  3850. }),
  3851. core_interruptible = methodWithTrace(trace => self => {
  3852. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3853. effect.i0 = runtimeFlagsPatch_make((flag = 1), flag)
  3854. var flag
  3855. effect.i1 = () => self
  3856. return trace ? effect.traced(trace) : effect
  3857. }),
  3858. core_map = dualWithTrace(
  3859. 2,
  3860. (trace, restore) => (self, f) =>
  3861. core_flatMap(a => sync(() => restore(f)(a)))(self).traced(trace)
  3862. ),
  3863. mapBoth = dualWithTrace(
  3864. 3,
  3865. (trace, restore) => (self, f, g) =>
  3866. matchEffect(
  3867. self,
  3868. e => failSync(() => restore(f)(e)),
  3869. a => sync(() => restore(g)(a))
  3870. ).traced(trace)
  3871. ),
  3872. mapError = dualWithTrace(
  3873. 2,
  3874. (trace, restore) => (self, f) =>
  3875. matchCauseEffect(
  3876. self,
  3877. cause => {
  3878. const either = failureOrCause(cause)
  3879. switch (either._tag) {
  3880. case "Left":
  3881. return failSync(() => restore(f)(either.left))
  3882. case "Right":
  3883. return failCause(either.right)
  3884. }
  3885. },
  3886. succeed
  3887. ).traced(trace)
  3888. ),
  3889. onExit = dualWithTrace(
  3890. 2,
  3891. (trace, restoreTrace) => (self, cleanup) =>
  3892. uninterruptibleMask(restore =>
  3893. matchCauseEffect(
  3894. restore(self),
  3895. cause1 => {
  3896. const result = exitFailCause(cause1)
  3897. return matchCauseEffect(
  3898. cause2 => exitFailCause(sequential(cause1, cause2)),
  3899. () => result
  3900. )(restoreTrace(cleanup)(result))
  3901. },
  3902. success => {
  3903. const result = exitSucceed(success)
  3904. return core_zipRight(result)(restoreTrace(cleanup)(result))
  3905. }
  3906. )
  3907. ).traced(trace)
  3908. ),
  3909. onInterrupt = dualWithTrace(
  3910. 2,
  3911. (trace, restore) => (self, cleanup) =>
  3912. onExit(
  3913. self,
  3914. exitMatch(
  3915. cause =>
  3916. isInterruptedOnly(cause)
  3917. ? core_asUnit(
  3918. restore(cleanup)(
  3919. (self =>
  3920. cause_reduce(
  3921. self,
  3922. mjs_HashSet_empty(),
  3923. (set, cause) =>
  3924. "Interrupt" === cause._tag
  3925. ? Option_some(
  3926. mjs_HashSet_add(cause.fiberId)(set)
  3927. )
  3928. : Option_none()
  3929. ))(cause)
  3930. )
  3931. )
  3932. : core_unit(),
  3933. () => core_unit()
  3934. )
  3935. ).traced(trace)
  3936. ),
  3937. core_orElse = dualWithTrace(
  3938. 2,
  3939. (trace, restore) => (self, that) =>
  3940. attemptOrElse(restore(that), succeed)(self).traced(trace)
  3941. ),
  3942. orDie = methodWithTrace(
  3943. trace => self => orDieWith(self, Function_identity).traced(trace)
  3944. ),
  3945. orDieWith = dualWithTrace(
  3946. 2,
  3947. (trace, restore) => (self, f) =>
  3948. matchEffect(e => core_die(restore(f)(e)), succeed)(self).traced(trace)
  3949. ),
  3950. provideContext = dualWithTrace(
  3951. 2,
  3952. trace => (self, context) =>
  3953. fiberRefLocally(currentContext, context)(self).traced(trace)
  3954. ),
  3955. contramapContext = dualWithTrace(
  3956. 2,
  3957. (trace, restore) => (self, f) =>
  3958. contextWithEffect(context =>
  3959. provideContext(restore(f)(context))(self)
  3960. ).traced(trace)
  3961. ),
  3962. succeed = methodWithTrace(trace => value => {
  3963. const effect = new EffectPrimitiveSuccess("Success")
  3964. effect.i0 = value
  3965. return trace ? effect.traced(trace) : effect
  3966. }),
  3967. suspend = methodWithTrace(
  3968. (trace, restore) => effect =>
  3969. core_flatMap(Function_identity)(sync(restore(effect))).traced(trace)
  3970. ),
  3971. sync = methodWithTrace((trace, restore) => evaluate => {
  3972. const effect = new EffectPrimitive("Sync")
  3973. effect.i0 = restore(evaluate)
  3974. return trace ? effect.traced(trace) : effect
  3975. }),
  3976. core_tap = dualWithTrace(
  3977. 2,
  3978. (trace, restore) => (self, f) =>
  3979. core_flatMap(a => core_as(a)(restore(f)(a)))(self).traced(trace)
  3980. ),
  3981. transplant = methodWithTrace(
  3982. (trace, restore) => f =>
  3983. withFiberRuntime(state => {
  3984. const scopeOverride = state.getFiberRef(forkScopeOverride),
  3985. scope = getOrElse(() => state.scope())(scopeOverride)
  3986. return restore(f)(
  3987. fiberRefLocally(forkScopeOverride, Option_some(scope))
  3988. )
  3989. }).traced(trace)
  3990. ),
  3991. attemptOrElse = dualWithTrace(
  3992. 3,
  3993. (trace, restore) => (self, that, onSuccess) =>
  3994. matchCauseEffect(
  3995. self,
  3996. cause =>
  3997. cause_defects(cause).length > 0
  3998. ? failCause(
  3999. getOrThrow(
  4000. (self =>
  4001. cause_match(
  4002. self,
  4003. Option_none(),
  4004. failure => Option_some(die(failure)),
  4005. defect => Option_some(die(defect)),
  4006. () => Option_none(),
  4007. (option, annotation) =>
  4008. Option_map(cause => annotated(cause, annotation))(
  4009. option
  4010. ),
  4011. (left, right) =>
  4012. Option_isSome(left) && Option_isSome(right)
  4013. ? Option_some(sequential(left.value, right.value))
  4014. : Option_isSome(left) && Option_isNone(right)
  4015. ? Option_some(left.value)
  4016. : Option_isNone(left) && Option_isSome(right)
  4017. ? Option_some(right.value)
  4018. : Option_none(),
  4019. (left, right) =>
  4020. Option_isSome(left) && Option_isSome(right)
  4021. ? Option_some(parallel(left.value, right.value))
  4022. : Option_isSome(left) && Option_isNone(right)
  4023. ? Option_some(left.value)
  4024. : Option_isNone(left) && Option_isSome(right)
  4025. ? Option_some(right.value)
  4026. : Option_none()
  4027. ))(cause)
  4028. )
  4029. )
  4030. : restore(that)(),
  4031. restore(onSuccess)
  4032. ).traced(trace)
  4033. ),
  4034. uninterruptible = methodWithTrace(trace => self => {
  4035. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  4036. effect.i0 = Patch_disable(1)
  4037. effect.i1 = () => self
  4038. return trace ? effect.traced(trace) : effect
  4039. }),
  4040. uninterruptibleMask = methodWithTrace((trace, restore) => f => {
  4041. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  4042. effect.i0 = Patch_disable(1)
  4043. effect.i1 = oldFlags =>
  4044. interruption(oldFlags)
  4045. ? restore(f)(core_interruptible)
  4046. : restore(f)(uninterruptible)
  4047. return trace ? effect.traced(trace) : effect
  4048. }),
  4049. core_unit = methodWithTrace(trace => _ => succeed(void 0).traced(trace)),
  4050. updateRuntimeFlags = methodWithTrace(trace => patch => {
  4051. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  4052. effect.i0 = patch
  4053. effect.i1 = void 0
  4054. return trace ? effect.traced(trace) : effect
  4055. }),
  4056. whenEffect = dualWithTrace(
  4057. 2,
  4058. trace => (self, predicate) =>
  4059. core_flatMap(b =>
  4060. b ? core_map(Option_some)(self) : succeed(Option_none())
  4061. )(predicate).traced(trace)
  4062. ),
  4063. whileLoop = methodWithTrace(
  4064. (trace, restore) => (check, body, process) => {
  4065. const effect = new EffectPrimitive("While")
  4066. effect.i0 = restore(check)
  4067. effect.i1 = restore(body)
  4068. effect.i2 = restore(process)
  4069. return trace ? effect.traced(trace) : effect
  4070. }
  4071. ),
  4072. withFiberRuntime = methodWithTrace((trace, restore) => withRuntime => {
  4073. const effect = new EffectPrimitive("WithRuntime")
  4074. effect.i0 = restore(withRuntime)
  4075. return trace ? effect.traced(trace) : effect
  4076. }),
  4077. withParallelism = dualWithTrace(
  4078. 2,
  4079. trace => (self, parallelism) =>
  4080. suspend(() =>
  4081. fiberRefLocally(currentParallelism, Option_some(parallelism))(self)
  4082. ).traced(trace)
  4083. ),
  4084. withParallelismUnbounded = methodWithTrace(
  4085. trace => self =>
  4086. suspend(() =>
  4087. fiberRefLocally(currentParallelism, Option_none())(self)
  4088. ).traced(trace)
  4089. ),
  4090. yieldNow = methodWithTrace(trace => () => {
  4091. const effect = new EffectPrimitive("Yield")
  4092. return trace ? effect.traced(trace) : effect
  4093. }),
  4094. core_zip = dualWithTrace(
  4095. 2,
  4096. trace => (self, that) =>
  4097. core_flatMap(self, a => core_map(that, b => [a, b])).traced(trace)
  4098. ),
  4099. core_zipLeft = dualWithTrace(
  4100. 2,
  4101. trace => (self, that) =>
  4102. core_flatMap(self, a => core_as(that, a)).traced(trace)
  4103. ),
  4104. core_zipRight = dualWithTrace(
  4105. 2,
  4106. trace => (self, that) => core_flatMap(self, () => that).traced(trace)
  4107. ),
  4108. core_zipWith = dualWithTrace(
  4109. 3,
  4110. (trace, restore) => (self, that, f) =>
  4111. core_flatMap(self, a => core_map(that, b => restore(f)(a, b))).traced(
  4112. trace
  4113. )
  4114. ),
  4115. interruptFiber = methodWithTrace(
  4116. trace => self =>
  4117. core_flatMap(fiberId => interruptAsFiber(fiberId)(self))(
  4118. fiberId()
  4119. ).traced(trace)
  4120. ),
  4121. interruptAsFiber = dualWithTrace(
  4122. 2,
  4123. trace => (self, fiberId) =>
  4124. core_flatMap(() => self.await())(
  4125. self.interruptAsFork(fiberId)
  4126. ).traced(trace)
  4127. ),
  4128. logLevelAll = {
  4129. _tag: "All",
  4130. syslog: 0,
  4131. label: "ALL",
  4132. ordinal: Number.MIN_SAFE_INTEGER,
  4133. },
  4134. logLevelInfo = { _tag: "Info", syslog: 6, label: "INFO", ordinal: 2e4 },
  4135. logLevelDebug = {
  4136. _tag: "Debug",
  4137. syslog: 7,
  4138. label: "DEBUG",
  4139. ordinal: 1e4,
  4140. },
  4141. logLevelNone = {
  4142. _tag: "None",
  4143. syslog: 7,
  4144. label: "OFF",
  4145. ordinal: Number.MAX_SAFE_INTEGER,
  4146. },
  4147. FiberRefTypeId = Symbol.for("@effect/io/FiberRef"),
  4148. fiberRefVariance = { _A: _ => _ },
  4149. fiberRefGet = methodWithTrace(
  4150. trace => self => fiberRefModify(self, a => [a, a]).traced(trace)
  4151. ),
  4152. fiberRefGetWith = dualWithTrace(
  4153. 2,
  4154. (trace, restore) => (self, f) =>
  4155. core_flatMap(fiberRefGet(self), restore(f)).traced(trace)
  4156. ),
  4157. fiberRefSet = dualWithTrace(
  4158. 2,
  4159. trace => (self, value) =>
  4160. fiberRefModify(self, () => [void 0, value]).traced(trace)
  4161. ),
  4162. fiberRefModify = dualWithTrace(
  4163. 2,
  4164. (trace, restore) => (self, f) =>
  4165. withFiberRuntime(state => {
  4166. const [b, a] = restore(f)(state.getFiberRef(self))
  4167. state.setFiberRef(self, a)
  4168. return succeed(b)
  4169. }).traced(trace)
  4170. ),
  4171. fiberRefLocally = dualWithTrace(
  4172. 3,
  4173. trace => (use, self, value) =>
  4174. acquireUseRelease(
  4175. core_zipLeft(fiberRefGet(self), fiberRefSet(self, value)),
  4176. () => use,
  4177. oldValue => fiberRefSet(self, oldValue)
  4178. ).traced(trace)
  4179. ),
  4180. fiberRefUnsafeMake = (
  4181. initial,
  4182. fork = Function_identity,
  4183. join = (_, a) => a
  4184. ) => fiberRefUnsafeMakePatch(initial, Differ_update(), fork, join),
  4185. fiberRefUnsafeMakeHashSet = initial =>
  4186. fiberRefUnsafeMakePatch(
  4187. initial,
  4188. Differ_hashSet(),
  4189. Differ_HashSetPatch_empty()
  4190. ),
  4191. fiberRefUnsafeMakeContext = initial =>
  4192. fiberRefUnsafeMakePatch(
  4193. initial,
  4194. Differ_environment(),
  4195. Differ_ContextPatch_empty()
  4196. ),
  4197. fiberRefUnsafeMakePatch = (
  4198. initial,
  4199. differ,
  4200. fork,
  4201. join = (_, n) => n
  4202. ) => ({
  4203. [FiberRefTypeId]: fiberRefVariance,
  4204. initial,
  4205. diff: (oldValue, newValue) => Differ_diff(oldValue, newValue)(differ),
  4206. combine: (first, second) => Differ_combine(first, second)(differ),
  4207. patch: patch => oldValue => Differ_patch(patch, oldValue)(differ),
  4208. fork,
  4209. join,
  4210. }),
  4211. fiberRefUnsafeMakeRuntimeFlags = initial =>
  4212. fiberRefUnsafeMakePatch(
  4213. initial,
  4214. mjs_Differ_make({
  4215. empty: runtimeFlagsPatch_empty,
  4216. diff: (oldValue, newValue) => runtimeFlags_diff(oldValue, newValue),
  4217. combine: (first, second) => andThen(second)(first),
  4218. patch: (_patch, oldValue) => runtimeFlags_patch(oldValue, _patch),
  4219. }),
  4220. Patch_empty
  4221. ),
  4222. currentContext = fiberRefUnsafeMakeContext(mjs_Context_empty()),
  4223. currentLogAnnotations = fiberRefUnsafeMake(mjs_HashMap_empty()),
  4224. currentLogLevel = fiberRefUnsafeMake(logLevelInfo),
  4225. currentLogSpan = fiberRefUnsafeMake(Chunk_empty()),
  4226. currentScheduler = fiberRefUnsafeMake(defaultScheduler),
  4227. currentParallelism = fiberRefUnsafeMake(Option_none()),
  4228. unhandledErrorLogLevel = fiberRefUnsafeMake(
  4229. Option_some(logLevelDebug),
  4230. _ => _,
  4231. (_, x) => x
  4232. ),
  4233. currentTags = fiberRefUnsafeMakeHashSet(mjs_HashSet_empty()),
  4234. forkScopeOverride = fiberRefUnsafeMake(
  4235. Option_none(),
  4236. () => Option_none(),
  4237. (parent, _) => parent
  4238. ),
  4239. interruptedCause = fiberRefUnsafeMake(
  4240. cause_empty,
  4241. () => cause_empty,
  4242. (parent, _) => parent
  4243. ),
  4244. ScopeTypeId = Symbol.for("@effect/io/Scope"),
  4245. CloseableScopeTypeId = Symbol.for("@effect/io/CloseableScope"),
  4246. scopeAddFinalizerExit = methodWithTrace(
  4247. (trace, restore) => (self, finalizer) =>
  4248. self.addFinalizer(restore(finalizer)).traced(trace)
  4249. ),
  4250. scopeClose = methodWithTrace(
  4251. trace => (self, exit) => self.close(exit).traced(trace)
  4252. ),
  4253. releaseMapAdd = dualWithTrace(
  4254. 2,
  4255. (trace, restore) => (self, finalizer) =>
  4256. core_map(
  4257. match(
  4258. () => () => core_unit(),
  4259. key => exit => releaseMapRelease(key, exit)(self)
  4260. )
  4261. )(releaseMapAddIfOpen(restore(finalizer))(self)).traced(trace)
  4262. ),
  4263. releaseMapRelease = dualWithTrace(
  4264. 3,
  4265. trace => (self, key, exit) =>
  4266. suspend(() => {
  4267. switch (self.state._tag) {
  4268. case "Exited":
  4269. return core_unit()
  4270. case "Running": {
  4271. const finalizer = self.state.finalizers.get(key)
  4272. self.state.finalizers.delete(key)
  4273. return null != finalizer
  4274. ? self.state.update(finalizer)(exit)
  4275. : core_unit()
  4276. }
  4277. }
  4278. }).traced(trace)
  4279. ),
  4280. releaseMapAddIfOpen = dualWithTrace(
  4281. 2,
  4282. (trace, restore) => (self, finalizer) =>
  4283. suspend(() => {
  4284. switch (self.state._tag) {
  4285. case "Exited":
  4286. self.state.nextKey += 1
  4287. return core_as(Option_none())(
  4288. restore(finalizer)(self.state.exit)
  4289. )
  4290. case "Running": {
  4291. const key = self.state.nextKey
  4292. self.state.finalizers.set(key, finalizer)
  4293. self.state.nextKey += 1
  4294. return succeed(Option_some(key))
  4295. }
  4296. }
  4297. }).traced(trace)
  4298. ),
  4299. releaseMapMake = methodWithTrace(
  4300. trace => () =>
  4301. sync(() => ({
  4302. state: {
  4303. _tag: "Running",
  4304. nextKey: 0,
  4305. finalizers: new Map(),
  4306. update: Function_identity,
  4307. },
  4308. })).traced(trace)
  4309. ),
  4310. exitAs = Function_dual(2, (self, value) => {
  4311. switch (self._tag) {
  4312. case "Failure":
  4313. return exitFailCause(self.i0)
  4314. case "Success":
  4315. return exitSucceed(value)
  4316. }
  4317. }),
  4318. exitAsUnit = self => exitAs(self, void 0),
  4319. exitCollectAllPar = exits => exitCollectAllInternal(exits, parallel),
  4320. exitFail = error => exitFailCause(fail(error)),
  4321. exitFailCause = cause => {
  4322. const effect = new EffectPrimitiveFailure("Failure")
  4323. effect.i0 = cause
  4324. return effect
  4325. },
  4326. exitMap = Function_dual(2, (self, f) => {
  4327. switch (self._tag) {
  4328. case "Failure":
  4329. return exitFailCause(self.i0)
  4330. case "Success":
  4331. return exitSucceed(f(self.i0))
  4332. }
  4333. }),
  4334. exitMatch = Function_dual(3, (self, onFailure, onSuccess) => {
  4335. switch (self._tag) {
  4336. case "Failure":
  4337. return onFailure(self.i0)
  4338. case "Success":
  4339. return onSuccess(self.i0)
  4340. }
  4341. }),
  4342. exitMatchEffect = Function_dual(3, (self, onFailure, onSuccess) => {
  4343. switch (self._tag) {
  4344. case "Failure":
  4345. return onFailure(self.i0)
  4346. case "Success":
  4347. return onSuccess(self.i0)
  4348. }
  4349. }),
  4350. exitSucceed = value => {
  4351. const effect = new EffectPrimitiveSuccess("Success")
  4352. effect.i0 = value
  4353. return effect
  4354. },
  4355. exitUnit = () => exitSucceed(void 0),
  4356. exitZipWith = Function_dual(4, (self, that, f, g) => {
  4357. switch (self._tag) {
  4358. case "Failure":
  4359. switch (that._tag) {
  4360. case "Success":
  4361. return exitFailCause(self.i0)
  4362. case "Failure":
  4363. return exitFailCause(g(self.i0, that.i0))
  4364. }
  4365. case "Success":
  4366. switch (that._tag) {
  4367. case "Success":
  4368. return exitSucceed(f(self.i0, that.i0))
  4369. case "Failure":
  4370. return exitFailCause(that.i0)
  4371. }
  4372. }
  4373. }),
  4374. exitCollectAllInternal = (exits, combineCauses) => {
  4375. const list = Chunk_fromIterable(exits)
  4376. return Chunk_isNonEmpty(list)
  4377. ? Option_some(
  4378. exitMap(Chunk_reverse)(
  4379. Chunk_reduce(
  4380. exitMap(Chunk_of)(Chunk_headNonEmpty(list)),
  4381. (accumulator, current) =>
  4382. exitZipWith(
  4383. current,
  4384. (list, value) => Chunk_prepend(value)(list),
  4385. combineCauses
  4386. )(accumulator)
  4387. )(Chunk_tailNonEmpty(list))
  4388. )
  4389. )
  4390. : Option_none()
  4391. },
  4392. deferredUnsafeMake = fiberId => ({
  4393. [DeferredTypeId]: deferredVariance,
  4394. state: MutableRef_make(pending([])),
  4395. blockingOn: fiberId,
  4396. }),
  4397. deferredMake = methodWithTrace(
  4398. trace => () =>
  4399. core_flatMap(id => deferredMakeAs(id))(fiberId()).traced(trace)
  4400. ),
  4401. deferredMakeAs = methodWithTrace(
  4402. trace => fiberId =>
  4403. sync(() => deferredUnsafeMake(fiberId)).traced(trace)
  4404. ),
  4405. deferredAwait = methodWithTrace(
  4406. trace => self =>
  4407. asyncInterruptEither(k => {
  4408. const state = MutableRef_get(self.state)
  4409. switch (state._tag) {
  4410. case "Done":
  4411. return Either_right(state.effect)
  4412. case "Pending":
  4413. MutableRef_set(pending([k, ...state.joiners]))(self.state)
  4414. return Either_left(deferredInterruptJoiner(self, k))
  4415. }
  4416. }, self.blockingOn).traced(trace)
  4417. ),
  4418. deferredCompleteWith = dualWithTrace(
  4419. 2,
  4420. trace => (self, effect) =>
  4421. sync(() => {
  4422. const state = MutableRef_get(self.state)
  4423. switch (state._tag) {
  4424. case "Done":
  4425. return !1
  4426. case "Pending":
  4427. MutableRef_set(done(effect))(self.state)
  4428. for (let i = 0; i < state.joiners.length; i++)
  4429. state.joiners[i](effect)
  4430. return !0
  4431. }
  4432. }).traced(trace)
  4433. ),
  4434. deferredFail = dualWithTrace(
  4435. 2,
  4436. trace => (self, error) =>
  4437. deferredCompleteWith(self, core_fail(error)).traced(trace)
  4438. ),
  4439. deferredFailCause = dualWithTrace(
  4440. 2,
  4441. trace => (self, cause) =>
  4442. deferredCompleteWith(self, failCause(cause)).traced(trace)
  4443. ),
  4444. deferredSucceed = dualWithTrace(
  4445. 2,
  4446. trace => (self, value) =>
  4447. deferredCompleteWith(self, succeed(value)).traced(trace)
  4448. ),
  4449. deferredUnsafeDone = (self, effect) => {
  4450. const state = MutableRef_get(self.state)
  4451. if ("Pending" === state._tag) {
  4452. MutableRef_set(done(effect))(self.state)
  4453. for (let i = state.joiners.length - 1; i >= 0; i--)
  4454. state.joiners[i](effect)
  4455. }
  4456. },
  4457. deferredInterruptJoiner = (self, joiner) =>
  4458. sync(() => {
  4459. const state = MutableRef_get(self.state)
  4460. "Pending" === state._tag &&
  4461. MutableRef_set(pending(state.joiners.filter(j => j !== joiner)))(
  4462. self.state
  4463. )
  4464. })
  4465. var clock_a
  4466. const ClockTypeId = Symbol.for("@effect/io/Clock"),
  4467. clockTag = Tag(ClockTypeId),
  4468. globalClockScheduler = {
  4469. unsafeSchedule(task, duration) {
  4470. if (duration.millis > 2147483647) return Function_constFalse
  4471. let completed = !1
  4472. const handle = setTimeout(() => {
  4473. completed = !0
  4474. task()
  4475. }, duration.millis)
  4476. return () => {
  4477. clearTimeout(handle)
  4478. return !completed
  4479. }
  4480. },
  4481. }
  4482. class ClockImpl {
  4483. constructor() {
  4484. this[clock_a] = ClockTypeId
  4485. }
  4486. unsafeCurrentTimeMillis() {
  4487. return new Date().getTime()
  4488. }
  4489. currentTimeMillis() {
  4490. return bodyWithTrace(trace =>
  4491. sync(() => this.unsafeCurrentTimeMillis()).traced(trace)
  4492. )
  4493. }
  4494. scheduler() {
  4495. return bodyWithTrace(trace =>
  4496. succeed(globalClockScheduler).traced(trace)
  4497. )
  4498. }
  4499. sleep(duration) {
  4500. return bodyWithTrace(trace =>
  4501. asyncInterruptEither(cb => {
  4502. const canceler = globalClockScheduler.unsafeSchedule(
  4503. () => cb(core_unit()),
  4504. duration
  4505. )
  4506. return Either_left(core_asUnit(sync(canceler)))
  4507. }).traced(trace)
  4508. )
  4509. }
  4510. }
  4511. clock_a = ClockTypeId
  4512. const ConfigErrorTypeId = Symbol.for("@effect/io/Config/Error"),
  4513. configError_proto = { [ConfigErrorTypeId]: ConfigErrorTypeId },
  4514. And = (self, that) => {
  4515. const error = Object.create(configError_proto)
  4516. error._tag = "And"
  4517. error.left = self
  4518. error.right = that
  4519. Object.defineProperty(error, "toString", {
  4520. enumerable: !1,
  4521. value() {
  4522. return `${this.left} and ${this.right}`
  4523. },
  4524. })
  4525. return error
  4526. },
  4527. Or = (self, that) => {
  4528. const error = Object.create(configError_proto)
  4529. error._tag = "Or"
  4530. error.left = self
  4531. error.right = that
  4532. Object.defineProperty(error, "toString", {
  4533. enumerable: !1,
  4534. value() {
  4535. return `${this.left} or ${this.right}`
  4536. },
  4537. })
  4538. return error
  4539. },
  4540. InvalidData = (path, message) => {
  4541. const error = Object.create(configError_proto)
  4542. error._tag = "InvalidData"
  4543. error.path = path
  4544. error.message = message
  4545. Object.defineProperty(error, "toString", {
  4546. enumerable: !1,
  4547. value() {
  4548. return `(Invalid data at ${Chunk_join(".")(this.path)}: "${
  4549. this.message
  4550. }")`
  4551. },
  4552. })
  4553. return error
  4554. },
  4555. MissingData = (path, message) => {
  4556. const error = Object.create(configError_proto)
  4557. error._tag = "MissingData"
  4558. error.path = path
  4559. error.message = message
  4560. Object.defineProperty(error, "toString", {
  4561. enumerable: !1,
  4562. value() {
  4563. return `(Missing data at ${Chunk_join(".")(this.path)}: "${
  4564. this.message
  4565. }")`
  4566. },
  4567. })
  4568. return error
  4569. },
  4570. SourceUnavailable = (path, message, cause) => {
  4571. const error = Object.create(configError_proto)
  4572. error._tag = "SourceUnavailable"
  4573. error.path = path
  4574. error.message = message
  4575. error.cause = cause
  4576. Object.defineProperty(error, "toString", {
  4577. enumerable: !1,
  4578. value() {
  4579. return `(Source unavailable at ${Chunk_join(".")(this.path)}: "${
  4580. this.message
  4581. }")`
  4582. },
  4583. })
  4584. return error
  4585. },
  4586. Unsupported = (path, message) => {
  4587. const error = Object.create(configError_proto)
  4588. error._tag = "Unsupported"
  4589. error.path = path
  4590. error.message = message
  4591. Object.defineProperty(error, "toString", {
  4592. enumerable: !1,
  4593. value() {
  4594. return `(Unsupported operation at ${Chunk_join(".")(this.path)}: "${
  4595. this.message
  4596. }")`
  4597. },
  4598. })
  4599. return error
  4600. },
  4601. prefixed = Function_dual(2, (self, prefix) => {
  4602. switch (self._tag) {
  4603. case "And":
  4604. return And(
  4605. prefixed(prefix)(self.left),
  4606. prefixed(prefix)(self.right)
  4607. )
  4608. case "Or":
  4609. return Or(prefixed(prefix)(self.left), prefixed(prefix)(self.right))
  4610. case "InvalidData":
  4611. return InvalidData(Chunk_concat(self.path)(prefix), self.message)
  4612. case "MissingData":
  4613. return MissingData(Chunk_concat(self.path)(prefix), self.message)
  4614. case "SourceUnavailable":
  4615. return SourceUnavailable(
  4616. Chunk_concat(self.path)(prefix),
  4617. self.message,
  4618. self.cause
  4619. )
  4620. case "Unsupported":
  4621. return Unsupported(Chunk_concat(self.path)(prefix), self.message)
  4622. }
  4623. })
  4624. var List_a, List_b
  4625. const ListTypeId = Symbol.for("@effect/data/List"),
  4626. listVariance = { _A: _ => _ }
  4627. class ConsImpl {
  4628. constructor(head, tail) {
  4629. this.head = head
  4630. this.tail = tail
  4631. this._tag = "Cons"
  4632. this[List_a] = listVariance
  4633. }
  4634. toString() {
  4635. return `List.Cons(${List_toReadonlyArray(this).map(String).join(", ")})`
  4636. }
  4637. toJSON() {
  4638. return { _tag: "List.Cons", values: List_toReadonlyArray(this) }
  4639. }
  4640. [((List_a = ListTypeId), Symbol.for("nodejs.util.inspect.custom"))]() {
  4641. return this.toJSON()
  4642. }
  4643. [Equal_symbol](that) {
  4644. return (
  4645. isList(that) &&
  4646. this._tag === that._tag &&
  4647. equalsWith(this, that, equals)
  4648. )
  4649. }
  4650. [symbol]() {
  4651. return string("@effect/data/List")
  4652. }
  4653. [Symbol.iterator]() {
  4654. let done = !1,
  4655. self = this
  4656. return {
  4657. next() {
  4658. if (done) return this.return()
  4659. if ("Nil" === self._tag) {
  4660. done = !0
  4661. return this.return()
  4662. }
  4663. const value = self.head
  4664. self = self.tail
  4665. return { done, value }
  4666. },
  4667. return(value) {
  4668. done || (done = !0)
  4669. return { done: !0, value }
  4670. },
  4671. }
  4672. }
  4673. }
  4674. class NilImpl {
  4675. constructor() {
  4676. this._tag = "Nil"
  4677. this[List_b] = listVariance
  4678. }
  4679. toString() {
  4680. return "List.Nil"
  4681. }
  4682. toJSON() {
  4683. return { _tag: "List.Nil" }
  4684. }
  4685. [((List_b = ListTypeId), Symbol.for("nodejs.util.inspect.custom"))]() {
  4686. return this.toJSON()
  4687. }
  4688. [symbol]() {
  4689. return array(Array.from(this))
  4690. }
  4691. [Equal_symbol](that) {
  4692. return isList(that) && this._tag === that._tag
  4693. }
  4694. [Symbol.iterator]() {
  4695. return { next: () => ({ done: !0, value: void 0 }) }
  4696. }
  4697. }
  4698. const isList = u => "object" == typeof u && null != u && ListTypeId in u,
  4699. isNil = self => "Nil" === self._tag,
  4700. isCons = self => "Cons" === self._tag,
  4701. List_length = self => {
  4702. let these = self,
  4703. len = 0
  4704. for (; !isNil(these); ) {
  4705. len += 1
  4706. these = these.tail
  4707. }
  4708. return len
  4709. },
  4710. equalsWith = Function_dual(3, (self, that, f) => {
  4711. if (self === that) return !0
  4712. if (List_length(self) !== List_length(that)) return !1
  4713. const selfIterator = self[Symbol.iterator](),
  4714. thatIterator = that[Symbol.iterator]()
  4715. let nextSelf, nextThat
  4716. for (
  4717. ;
  4718. !(nextSelf = selfIterator.next()).done &&
  4719. !(nextThat = thatIterator.next()).done;
  4720.  
  4721. )
  4722. if (!f(nextSelf.value, nextThat.value)) return !1
  4723. return !0
  4724. }),
  4725. _Nil = new NilImpl(),
  4726. cons = (head, tail) => new ConsImpl(head, tail),
  4727. List_toReadonlyArray = self => Array.from(self),
  4728. pathPatch_empty = { _tag: "Empty" },
  4729. pathPatch_patch = Function_dual(2, (path, patch) => {
  4730. let input = new ConsImpl(patch, _Nil),
  4731. output = path
  4732. for (; isCons(input); ) {
  4733. const patch = input.head
  4734. switch (patch._tag) {
  4735. case "Empty":
  4736. input = input.tail
  4737. break
  4738. case "AndThen":
  4739. input = cons(patch.first, cons(patch.second, input.tail))
  4740. break
  4741. case "MapName":
  4742. output = Chunk_map(output, patch.f)
  4743. input = input.tail
  4744. break
  4745. case "Nested":
  4746. output = Chunk_prepend(output, patch.name)
  4747. input = input.tail
  4748. break
  4749. case "Unnested":
  4750. if (!contains(String_Equivalence)(patch.name)(Chunk_head(output)))
  4751. return Either_left(
  4752. MissingData(
  4753. output,
  4754. `Expected ${patch.name} to be in path in ConfigProvider#unnested`
  4755. )
  4756. )
  4757. output = Chunk_tailNonEmpty(output)
  4758. input = input.tail
  4759. }
  4760. }
  4761. return Either_right(output)
  4762. }),
  4763. ConfigProviderTypeId = Symbol.for("@effect/io/Config/Provider"),
  4764. configProviderTag = Tag(ConfigProviderTypeId),
  4765. FlatConfigProviderTypeId = Symbol.for("@effect/io/Config/Provider/Flat"),
  4766. configProvider_make = untracedMethod(restore => (load, flattened) => ({
  4767. [ConfigProviderTypeId]: ConfigProviderTypeId,
  4768. load: methodWithTrace(
  4769. trace => config => restore(load)(config).traced(trace)
  4770. ),
  4771. flattened,
  4772. })),
  4773. makeFlat = untracedMethod(
  4774. restore => (load, enumerateChildren, patch) => ({
  4775. [FlatConfigProviderTypeId]: FlatConfigProviderTypeId,
  4776. patch,
  4777. load: methodWithTrace(
  4778. trace =>
  4779. (path, config, split = !0) =>
  4780. restore(load)(path, config, split).traced(trace)
  4781. ),
  4782. enumerateChildren: methodWithTrace(
  4783. trace => path => restore(enumerateChildren)(path).traced(trace)
  4784. ),
  4785. })
  4786. ),
  4787. fromFlat = untracedMethod(
  4788. () => flat =>
  4789. configProvider_make(
  4790. config =>
  4791. core_flatMap(
  4792. fromFlatLoop(flat, Chunk_empty(), config, !1),
  4793. chunk =>
  4794. match(
  4795. () =>
  4796. core_fail(
  4797. MissingData(
  4798. Chunk_empty(),
  4799. `Expected a single value having structure: ${config}`
  4800. )
  4801. ),
  4802. succeed
  4803. )(Chunk_head(chunk))
  4804. ),
  4805. flat
  4806. )
  4807. ),
  4808. fromEnv = untracedMethod(() => (config = {}) => {
  4809. const { pathDelim, seqDelim } = Object.assign(
  4810. {},
  4811. { pathDelim: "_", seqDelim: "," },
  4812. config
  4813. ),
  4814. getEnv = () =>
  4815. "undefined" != typeof process &&
  4816. "env" in process &&
  4817. "object" == typeof process.env
  4818. ? process.env
  4819. : {}
  4820. return fromFlat(
  4821. makeFlat(
  4822. (path, primitive, split = !0) => {
  4823. const pathString = (path => Chunk_join(pathDelim)(path))(path),
  4824. current = getEnv(),
  4825. valueOpt =
  4826. pathString in current
  4827. ? Option_some(current[pathString])
  4828. : Option_none()
  4829. return core_flatMap(value =>
  4830. parsePrimitive(value, path, primitive, seqDelim, split)
  4831. )(
  4832. mapError(() =>
  4833. MissingData(
  4834. path,
  4835. `Expected ${pathString} to exist in the process context`
  4836. )
  4837. )(core_fromOption(valueOpt))
  4838. )
  4839. },
  4840. path =>
  4841. sync(() => {
  4842. const current = getEnv(),
  4843. keys = Object.keys(current),
  4844. filteredKeyPaths = Array.from(keys)
  4845. .map(value => value.toUpperCase().split(pathDelim))
  4846. .filter(keyPath => {
  4847. for (let i = 0; i < path.length; i++) {
  4848. const pathComponent = Chunk_unsafeGet(i)(path),
  4849. currentElement = keyPath[i]
  4850. if (
  4851. void 0 === currentElement ||
  4852. pathComponent !== currentElement
  4853. )
  4854. return !1
  4855. }
  4856. return !0
  4857. })
  4858. .flatMap(keyPath =>
  4859. keyPath.slice(path.length, path.length + 1)
  4860. )
  4861. return mjs_HashSet_fromIterable(filteredKeyPaths)
  4862. }),
  4863. pathPatch_empty
  4864. )
  4865. )
  4866. }),
  4867. fromFlatLoop = (flat, prefix, config, split) => {
  4868. const op = config
  4869. switch (op._tag) {
  4870. case "Constant":
  4871. return succeed(Chunk_of(op.value))
  4872. case "Described":
  4873. return suspend(() => fromFlatLoop(flat, prefix, op.config, split))
  4874. case "Fail":
  4875. return core_fail(MissingData(prefix, op.message))
  4876. case "Fallback":
  4877. return catchAll(error1 =>
  4878. op.condition(error1)
  4879. ? catchAll(error2 => core_fail(Or(error1, error2)))(
  4880. fromFlatLoop(flat, prefix, op.second, split)
  4881. )
  4882. : core_fail(error1)
  4883. )(suspend(() => fromFlatLoop(flat, prefix, op.first, split)))
  4884. case "Lazy":
  4885. return suspend(() => fromFlatLoop(flat, prefix, op.config(), split))
  4886. case "MapOrFail":
  4887. return suspend(() =>
  4888. core_flatMap(
  4889. core_forEach(a =>
  4890. mapError(prefixed(prefix))(core_fromEither(op.mapOrFail(a)))
  4891. )
  4892. )(fromFlatLoop(flat, prefix, op.original, split))
  4893. )
  4894. case "Nested":
  4895. return suspend(() =>
  4896. fromFlatLoop(
  4897. flat,
  4898. Chunk_concat(prefix, Chunk_of(op.name)),
  4899. op.config,
  4900. split
  4901. )
  4902. )
  4903. case "Primitive":
  4904. return core_flatMap(prefix =>
  4905. core_flatMap(values => {
  4906. if (Chunk_isEmpty(values)) {
  4907. const name = getOrElse(() => "<n/a>")(
  4908. (self => Chunk_get(self, self.length - 1))(prefix)
  4909. )
  4910. return core_fail(
  4911. (
  4912. name => self =>
  4913. MissingData(
  4914. Chunk_empty(),
  4915. `Expected ${self.description} with name ${name}`
  4916. )
  4917. )(name)
  4918. )
  4919. }
  4920. return succeed(values)
  4921. })(flat.load(prefix, op, split))
  4922. )(core_fromEither(pathPatch_patch(prefix, flat.patch)))
  4923. case "Sequence":
  4924. return core_flatMap(patchedPrefix =>
  4925. core_flatMap(indices =>
  4926. Chunk_isEmpty(indices)
  4927. ? suspend(() =>
  4928. core_map(
  4929. fromFlatLoop(flat, patchedPrefix, op.config, !0),
  4930. Chunk_of
  4931. )
  4932. )
  4933. : core_map(chunkChunk => {
  4934. const flattened = Chunk_flatten(chunkChunk)
  4935. return Chunk_isEmpty(flattened)
  4936. ? Chunk_of(Chunk_empty())
  4937. : Chunk_of(flattened)
  4938. })(
  4939. core_forEach(indices, index =>
  4940. fromFlatLoop(
  4941. flat,
  4942. Chunk_append(prefix, `[${index}]`),
  4943. op.config,
  4944. !0
  4945. )
  4946. )
  4947. )
  4948. )(
  4949. core_flatMap(indicesFrom)(flat.enumerateChildren(patchedPrefix))
  4950. )
  4951. )(pathPatch_patch(prefix, flat.patch))
  4952. case "Table":
  4953. return suspend(() =>
  4954. core_flatMap(prefix =>
  4955. core_flatMap(keys =>
  4956. core_map(values => {
  4957. if (0 === values.length)
  4958. return Chunk_of(mjs_HashMap_empty())
  4959. const matrix = toReadonlyArray(values).map(toReadonlyArray)
  4960. return Chunk_map(values =>
  4961. mjs_HashMap_fromIterable(
  4962. Chunk_zip(Chunk_fromIterable(keys), values)
  4963. )
  4964. )(unsafeFromArray(transpose(matrix).map(unsafeFromArray)))
  4965. })(
  4966. core_forEach(key =>
  4967. fromFlatLoop(
  4968. flat,
  4969. Chunk_concat(Chunk_of(key))(prefix),
  4970. op.valueConfig,
  4971. split
  4972. )
  4973. )(keys)
  4974. )
  4975. )(flat.enumerateChildren(prefix))
  4976. )(core_fromEither(pathPatch_patch(prefix, flat.patch)))
  4977. )
  4978. case "ZipWith":
  4979. return suspend(() =>
  4980. core_flatMap(left =>
  4981. core_flatMap(right => {
  4982. if (Either_isLeft(left) && Either_isLeft(right))
  4983. return core_fail(And(left.left, right.left))
  4984. if (Either_isLeft(left) && Either_isRight(right))
  4985. return core_fail(left.left)
  4986. if (Either_isRight(left) && Either_isLeft(right))
  4987. return core_fail(right.left)
  4988. if (Either_isRight(left) && Either_isRight(right)) {
  4989. const path = Chunk_join(".")(prefix),
  4990. fail = fromFlatLoopFail(prefix, path),
  4991. [lefts, rights] = ((leftDef, rightDef, left, right) => {
  4992. const leftPad = Chunk_unfold(left.length, index =>
  4993. index >= right.length
  4994. ? Option_none()
  4995. : Option_some([leftDef(index), index + 1])
  4996. ),
  4997. rightPad = Chunk_unfold(right.length, index =>
  4998. index >= left.length
  4999. ? Option_none()
  5000. : Option_some([rightDef(index), index + 1])
  5001. )
  5002. return [
  5003. Chunk_concat(leftPad)(left),
  5004. Chunk_concat(rightPad)(right),
  5005. ]
  5006. })(
  5007. fail,
  5008. fail,
  5009. Chunk_map(Either_right)(left.right),
  5010. Chunk_map(Either_right)(right.right)
  5011. )
  5012. return core_forEach(([left, right]) =>
  5013. core_map(([left, right]) => op.zip(left, right))(
  5014. core_zip(core_fromEither(right))(core_fromEither(left))
  5015. )
  5016. )(Chunk_zip(rights)(lefts))
  5017. }
  5018. throw new Error(
  5019. "BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  5020. )
  5021. })(core_either(fromFlatLoop(flat, prefix, op.right, split)))
  5022. )(core_either(fromFlatLoop(flat, prefix, op.left, split)))
  5023. )
  5024. }
  5025. },
  5026. fromFlatLoopFail = (prefix, path) => index =>
  5027. Either_left(
  5028. MissingData(
  5029. prefix,
  5030. `The element at index ${index} in a sequence at path "${path}" was missing`
  5031. )
  5032. ),
  5033. parsePrimitive = (text, path, primitive, delimiter, split) =>
  5034. split
  5035. ? mapError(prefixed(path))(
  5036. core_forEach(char =>
  5037. core_fromEither(primitive.parse(char.trim()))
  5038. )(
  5039. ((text, delim) => {
  5040. const split = text.split(
  5041. new RegExp(`\\s*${escapeRegex(delim)}\\s*`)
  5042. )
  5043. return unsafeFromArray(split)
  5044. })(text, delimiter)
  5045. )
  5046. )
  5047. : mapError(prefixed(path))(
  5048. core_map(Chunk_of)(core_fromEither(primitive.parse(text)))
  5049. ),
  5050. transpose = array =>
  5051. Object.keys(array[0]).map(column => array.map(row => row[column])),
  5052. escapeRegex = string => string.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&"),
  5053. indicesFrom = quotedIndices =>
  5054. core_map(merge)(
  5055. core_either(
  5056. mapBoth(
  5057. () => Chunk_empty(),
  5058. Chunk_sort(Order)
  5059. )(core_forEach(quotedIndices, parseQuotedIndex))
  5060. )
  5061. ),
  5062. QUOTED_INDEX_REGEX = /^(\[(\d+)\])$/,
  5063. parseQuotedIndex = str => {
  5064. const match = str.match(QUOTED_INDEX_REGEX)
  5065. if (null !== match) {
  5066. const matchedIndex = match[2]
  5067. return flatMap(parseInteger)(
  5068. void 0 !== matchedIndex && matchedIndex.length > 0
  5069. ? Option_some(matchedIndex)
  5070. : Option_none()
  5071. )
  5072. }
  5073. return Option_none()
  5074. },
  5075. parseInteger = str => {
  5076. const parsedIndex = Number.parseInt(str)
  5077. return Number.isNaN(parsedIndex)
  5078. ? Option_none()
  5079. : Option_some(parsedIndex)
  5080. }
  5081. var random_a
  5082. const RandomTypeId = Symbol.for("@effect/io/Random"),
  5083. randomTag = Tag(RandomTypeId)
  5084. random_a = RandomTypeId
  5085. const shuffleWith = (elements, nextIntBounded) =>
  5086. suspend(() =>
  5087. core_flatMap(buffer => {
  5088. const numbers = []
  5089. for (let i = buffer.length; i >= 2; i -= 1) numbers.push(i)
  5090. return core_as(Chunk_fromIterable(buffer))(
  5091. forEachDiscard(n =>
  5092. core_map(k => swap(buffer, n - 1, k))(nextIntBounded(n))
  5093. )(numbers)
  5094. )
  5095. })(sync(() => Array.from(elements)))
  5096. ),
  5097. swap = (buffer, index1, index2) => {
  5098. const tmp = buffer[index1]
  5099. buffer[index1] = buffer[index2]
  5100. buffer[index2] = tmp
  5101. return buffer
  5102. }
  5103. var seed
  5104. const currentServices = fiberRefUnsafeMakeContext(
  5105. Context_add(
  5106. configProviderTag,
  5107. fromEnv()
  5108. )(
  5109. Context_add(
  5110. randomTag,
  5111. ((seed = (4294967296 * Math.random()) >>> 0),
  5112. new (class {
  5113. constructor(seed) {
  5114. this.seed = seed
  5115. this[random_a] = RandomTypeId
  5116. this.PRNG = new PCGRandom(seed)
  5117. }
  5118. next() {
  5119. return bodyWithTrace(trace =>
  5120. sync(() => this.PRNG.number()).traced(trace)
  5121. )
  5122. }
  5123. nextBoolean() {
  5124. return bodyWithTrace(trace =>
  5125. core_map(this.next(), n => n > 0.5).traced(trace)
  5126. )
  5127. }
  5128. nextInt() {
  5129. return bodyWithTrace(trace =>
  5130. sync(() => this.PRNG.integer(Number.MAX_SAFE_INTEGER)).traced(
  5131. trace
  5132. )
  5133. )
  5134. }
  5135. nextRange(min, max) {
  5136. return bodyWithTrace(trace =>
  5137. core_map(this.next(), n => (max - min) * n + min).traced(
  5138. trace
  5139. )
  5140. )
  5141. }
  5142. nextIntBetween(min, max) {
  5143. return bodyWithTrace(trace =>
  5144. sync(() => this.PRNG.integer(1 + max - min) + min).traced(
  5145. trace
  5146. )
  5147. )
  5148. }
  5149. shuffle(elements) {
  5150. return bodyWithTrace(trace =>
  5151. shuffleWith(elements, n => this.nextIntBetween(0, n)).traced(
  5152. trace
  5153. )
  5154. )
  5155. }
  5156. })(seed))
  5157. )(Context_add(clockTag, new ClockImpl())(mjs_Context_empty()))
  5158. )
  5159. ),
  5160. currentTimeMillis = methodWithTrace(
  5161. trace => () =>
  5162. clockWith(clock => clock.currentTimeMillis()).traced(trace)
  5163. ),
  5164. sleep = methodWithTrace(
  5165. trace => duration =>
  5166. clockWith(clock => clock.sleep(duration)).traced(trace)
  5167. ),
  5168. clockWith = methodWithTrace(
  5169. (trace, restore) => f =>
  5170. fiberRefGetWith(currentServices, services =>
  5171. restore(f)(mjs_Context_get(clockTag)(services))
  5172. ).traced(trace)
  5173. ),
  5174. Duration_TypeId = Symbol.for("@effect/data/Duration")
  5175. class DurationImpl {
  5176. constructor(millis) {
  5177. this.millis = millis
  5178. this._id = Duration_TypeId
  5179. }
  5180. [symbol]() {
  5181. return Hash_hash(this.millis)
  5182. }
  5183. [Equal_symbol](that) {
  5184. return isDuration(that) && this.millis === that.millis
  5185. }
  5186. }
  5187. const isDuration = u =>
  5188. "object" == typeof u &&
  5189. null != u &&
  5190. "_id" in u &&
  5191. u._id === Duration_TypeId,
  5192. zero = new DurationImpl(0),
  5193. millis = millis => new DurationImpl(millis),
  5194. seconds = seconds => new DurationImpl(1e3 * seconds),
  5195. Clock_sleep =
  5196. (fromSemigroup(
  5197. Semigroup_make(
  5198. Function_dual(
  5199. 2,
  5200. (self, that) => new DurationImpl(self.millis + that.millis)
  5201. )
  5202. ),
  5203. zero
  5204. ).combineAll,
  5205. sleep),
  5206. Clock_currentTimeMillis = currentTimeMillis
  5207. var fiberRefs_a
  5208. const FiberRefsSym = Symbol.for("@effect/io/FiberRefs")
  5209. class FiberRefsImpl {
  5210. constructor(locals) {
  5211. this.locals = locals
  5212. this[fiberRefs_a] = FiberRefsSym
  5213. }
  5214. }
  5215. fiberRefs_a = FiberRefsSym
  5216. const findAncestor = (
  5217. _ref,
  5218. _parentStack,
  5219. _childStack,
  5220. _childModified = !1
  5221. ) => {
  5222. const ref = _ref
  5223. let ret,
  5224. parentStack = _parentStack,
  5225. childStack = _childStack,
  5226. childModified = _childModified
  5227. for (; void 0 === ret; )
  5228. if (
  5229. isNonEmptyReadonlyArray(parentStack) &&
  5230. isNonEmptyReadonlyArray(childStack)
  5231. ) {
  5232. const parentFiberId = headNonEmpty(parentStack)[0],
  5233. parentAncestors = tailNonEmpty(parentStack),
  5234. childFiberId = headNonEmpty(childStack)[0],
  5235. childRefValue = headNonEmpty(childStack)[1],
  5236. childAncestors = tailNonEmpty(childStack)
  5237. if (parentFiberId.startTimeMillis < childFiberId.startTimeMillis) {
  5238. childStack = childAncestors
  5239. childModified = !0
  5240. } else if (
  5241. parentFiberId.startTimeMillis > childFiberId.startTimeMillis
  5242. )
  5243. parentStack = parentAncestors
  5244. else if (parentFiberId.id < childFiberId.id) {
  5245. childStack = childAncestors
  5246. childModified = !0
  5247. } else
  5248. parentFiberId.id > childFiberId.id
  5249. ? (parentStack = parentAncestors)
  5250. : (ret = [childRefValue, childModified])
  5251. } else ret = [ref.initial, !0]
  5252. return ret
  5253. },
  5254. joinAs = Function_dual(3, (self, fiberId, that) => {
  5255. const parentFiberRefs = new Map(self.locals)
  5256. for (const [fiberRef, childStack] of that.locals) {
  5257. const childValue = headNonEmpty(childStack)[1]
  5258. if (!equals(headNonEmpty(childStack)[0], fiberId)) {
  5259. if (!parentFiberRefs.has(fiberRef)) {
  5260. if (equals(childValue, fiberRef.initial)) continue
  5261. parentFiberRefs.set(fiberRef, [
  5262. [fiberId, fiberRef.join(fiberRef.initial, childValue)],
  5263. ])
  5264. continue
  5265. }
  5266. const parentStack = parentFiberRefs.get(fiberRef),
  5267. [ancestor, wasModified] = findAncestor(
  5268. fiberRef,
  5269. parentStack,
  5270. childStack
  5271. )
  5272. if (wasModified) {
  5273. const patch = fiberRef.diff(ancestor, childValue),
  5274. oldValue = headNonEmpty(parentStack)[1],
  5275. newValue = fiberRef.join(
  5276. oldValue,
  5277. fiberRef.patch(patch)(oldValue)
  5278. )
  5279. if (!equals(oldValue, newValue)) {
  5280. let newStack
  5281. const parentFiberId = headNonEmpty(parentStack)[0]
  5282. newStack = equals(parentFiberId, fiberId)
  5283. ? prepend([parentFiberId, newValue])(
  5284. tailNonEmpty(parentStack)
  5285. )
  5286. : prepend([fiberId, newValue])(parentStack)
  5287. parentFiberRefs.set(fiberRef, newStack)
  5288. }
  5289. }
  5290. }
  5291. }
  5292. return new FiberRefsImpl(new Map(parentFiberRefs))
  5293. }),
  5294. forkAs = Function_dual(2, (self, childId) => {
  5295. const map = new Map()
  5296. for (const [fiberRef, stack] of self.locals.entries()) {
  5297. const oldValue = headNonEmpty(stack)[1],
  5298. newValue = fiberRef.patch(fiberRef.fork)(oldValue)
  5299. equals(oldValue, newValue)
  5300. ? map.set(fiberRef, stack)
  5301. : map.set(fiberRef, prepend([childId, newValue])(stack))
  5302. }
  5303. return new FiberRefsImpl(map)
  5304. }),
  5305. delete_ = Function_dual(2, (self, fiberRef) => {
  5306. const locals = new Map(self.locals)
  5307. locals.delete(fiberRef)
  5308. return new FiberRefsImpl(locals)
  5309. }),
  5310. fiberRefs_get = Function_dual(2, (self, fiberRef) =>
  5311. self.locals.has(fiberRef)
  5312. ? Option_some(headNonEmpty(self.locals.get(fiberRef))[1])
  5313. : Option_none()
  5314. ),
  5315. getOrDefault = Function_dual(2, (self, fiberRef) =>
  5316. getOrElse(() => fiberRef.initial)(fiberRefs_get(self, fiberRef))
  5317. ),
  5318. updatedAs = Function_dual(4, (self, fiberId, fiberRef, value) => {
  5319. const oldStack = self.locals.has(fiberRef)
  5320. ? self.locals.get(fiberRef)
  5321. : []
  5322. let newStack
  5323. if (isEmptyReadonlyArray(oldStack))
  5324. newStack = ReadonlyArray_of([fiberId, value])
  5325. else {
  5326. const [currentId, currentValue] = headNonEmpty(oldStack)
  5327. if (equals(currentId, fiberId)) {
  5328. if (equals(currentValue, value)) return self
  5329. newStack = prepend([fiberId, value])(tailNonEmpty(oldStack))
  5330. } else newStack = prepend([fiberId, value])(oldStack)
  5331. }
  5332. const locals = new Map(self.locals)
  5333. return new FiberRefsImpl(locals.set(fiberRef, newStack))
  5334. }),
  5335. FiberRefs_forkAs = forkAs,
  5336. FiberRefs_getOrDefault = getOrDefault,
  5337. FiberRefs_updatedAs = updatedAs,
  5338. FiberRefs_unsafeMake = function (fiberRefLocals) {
  5339. return new FiberRefsImpl(fiberRefLocals)
  5340. },
  5341. patch_diff = (oldValue, newValue) => {
  5342. const missingLocals = new Map(oldValue.locals)
  5343. let patch = { _tag: "Empty" }
  5344. for (const [fiberRef, pairs] of newValue.locals.entries()) {
  5345. const newValue = headNonEmpty(pairs)[1],
  5346. old = missingLocals.get(fiberRef)
  5347. if (void 0 !== old) {
  5348. const oldValue = headNonEmpty(old)[1]
  5349. equals(oldValue, newValue) ||
  5350. (patch = patch_combine({
  5351. _tag: "Update",
  5352. fiberRef,
  5353. patch: fiberRef.diff(oldValue, newValue),
  5354. })(patch))
  5355. } else
  5356. patch = patch_combine({ _tag: "Add", fiberRef, value: newValue })(
  5357. patch
  5358. )
  5359. missingLocals.delete(fiberRef)
  5360. }
  5361. for (const [fiberRef] of missingLocals.entries())
  5362. patch = patch_combine({ _tag: "Remove", fiberRef })(patch)
  5363. return patch
  5364. },
  5365. patch_combine = Function_dual(2, (self, that) => ({
  5366. _tag: "AndThen",
  5367. first: self,
  5368. second: that,
  5369. })),
  5370. patch_patch = Function_dual(3, (self, fiberId, oldValue) => {
  5371. let fiberRefs = oldValue,
  5372. patches = ReadonlyArray_of(self)
  5373. for (; isNonEmptyReadonlyArray(patches); ) {
  5374. const head = headNonEmpty(patches),
  5375. tail = tailNonEmpty(patches)
  5376. switch (head._tag) {
  5377. case "Empty":
  5378. patches = tail
  5379. break
  5380. case "Add":
  5381. fiberRefs = updatedAs(
  5382. fiberRefs,
  5383. fiberId,
  5384. head.fiberRef,
  5385. head.value
  5386. )
  5387. patches = tail
  5388. break
  5389. case "Remove":
  5390. fiberRefs = delete_(fiberRefs, head.fiberRef)
  5391. patches = tail
  5392. break
  5393. case "Update": {
  5394. const value = getOrDefault(fiberRefs, head.fiberRef)
  5395. fiberRefs = updatedAs(
  5396. fiberRefs,
  5397. fiberId,
  5398. head.fiberRef,
  5399. head.fiberRef.patch(head.patch)(value)
  5400. )
  5401. patches = tail
  5402. break
  5403. }
  5404. case "AndThen":
  5405. patches = prepend(head.first)(prepend(head.second)(tail))
  5406. }
  5407. }
  5408. return fiberRefs
  5409. })
  5410. class SingleShotGen {
  5411. constructor(self) {
  5412. this.self = self
  5413. this.called = !1
  5414. }
  5415. next(a) {
  5416. return this.called
  5417. ? { value: a, done: !0 }
  5418. : ((this.called = !0), { value: this.self, done: !1 })
  5419. }
  5420. return(a) {
  5421. return { value: a, done: !0 }
  5422. }
  5423. throw(e) {
  5424. throw e
  5425. }
  5426. [Symbol.iterator]() {
  5427. return new SingleShotGen(this.self)
  5428. }
  5429. }
  5430. const All = logLevelAll,
  5431. Fatal = { _tag: "Fatal", syslog: 2, label: "FATAL", ordinal: 5e4 },
  5432. Level_Error = { _tag: "Error", syslog: 3, label: "ERROR", ordinal: 4e4 },
  5433. Warning = { _tag: "Warning", syslog: 4, label: "WARN", ordinal: 3e4 },
  5434. Info = logLevelInfo,
  5435. Level_Debug = logLevelDebug,
  5436. Trace = { _tag: "Trace", syslog: 7, label: "TRACE", ordinal: 0 },
  5437. Level_None = logLevelNone,
  5438. locally = dualWithTrace(
  5439. 2,
  5440. trace => (use, self) =>
  5441. fiberRefLocally(use, currentLogLevel, self).traced(trace)
  5442. ),
  5443. greaterThanEqual = greaterThanOrEqualTo(
  5444. Order_contramap(level => level.ordinal)(Order)
  5445. ),
  5446. fromLiteral = _ => {
  5447. switch (_) {
  5448. case "All":
  5449. return All
  5450. case "Debug":
  5451. return Level_Debug
  5452. case "Error":
  5453. return Level_Error
  5454. case "Fatal":
  5455. return Fatal
  5456. case "Info":
  5457. return Info
  5458. case "Trace":
  5459. return Trace
  5460. case "None":
  5461. return Level_None
  5462. case "Warning":
  5463. return Warning
  5464. }
  5465. },
  5466. Span_render = now => self =>
  5467. `${self.label.replace(/[\s="]/g, "_")}=${now - self.startTime}ms`
  5468. var ref_a
  5469. const RefTypeId = Symbol.for("@effect/io/Ref"),
  5470. refVariance = { _A: _ => _ }
  5471. class RefImpl {
  5472. constructor(ref) {
  5473. this.ref = ref
  5474. this[ref_a] = refVariance
  5475. }
  5476. modify(f) {
  5477. return bodyWithTrace((trace, restore) =>
  5478. sync(() => {
  5479. const current = MutableRef_get(this.ref),
  5480. [b, a] = restore(f)(current)
  5481. current !== a && MutableRef_set(a)(this.ref)
  5482. return b
  5483. }).traced(trace)
  5484. )
  5485. }
  5486. }
  5487. ref_a = RefTypeId
  5488. const ref_unsafeMake = value => new RefImpl(MutableRef_make(value)),
  5489. ref_make = methodWithTrace(
  5490. trace => value => sync(() => ref_unsafeMake(value)).traced(trace)
  5491. ),
  5492. ref_get = methodWithTrace(
  5493. trace => self => self.modify(a => [a, a]).traced(trace)
  5494. ),
  5495. ref_set = dualWithTrace(
  5496. 2,
  5497. trace => (self, value) =>
  5498. self.modify(() => [void 0, value]).traced(trace)
  5499. ),
  5500. ref_modify = dualWithTrace(
  5501. 2,
  5502. (trace, restore) => (self, f) => self.modify(restore(f)).traced(trace)
  5503. ),
  5504. ref_update = dualWithTrace(
  5505. 2,
  5506. (trace, restore) => (self, f) =>
  5507. self.modify(a => [void 0, restore(f)(a)]).traced(trace)
  5508. ),
  5509. Ref_make = ref_make,
  5510. Ref_get = ref_get,
  5511. Ref_set = ref_set,
  5512. effect_collectAll = methodWithTrace(
  5513. trace => effects =>
  5514. core_forEach(effects, Function_identity).traced(trace)
  5515. ),
  5516. delay = dualWithTrace(
  5517. 2,
  5518. trace => (self, duration) =>
  5519. core_zipRight(Clock_sleep(duration), self).traced(trace)
  5520. ),
  5521. diffFiberRefs = methodWithTrace(
  5522. trace => self =>
  5523. summarized(getFiberRefs(), patch_diff)(self).traced(trace)
  5524. ),
  5525. effect_Do = methodWithTrace(trace => () => succeed({}).traced(trace)),
  5526. effect_bind = dualWithTrace(
  5527. 3,
  5528. (trace, restore) => (self, tag, f) =>
  5529. core_flatMap(self, k =>
  5530. core_map(restore(f)(k), a => ({ ...k, [tag]: a }))
  5531. ).traced(trace)
  5532. ),
  5533. effect_bindDiscard = dualWithTrace(
  5534. 3,
  5535. trace => (self, tag, f) =>
  5536. core_flatMap(self, k =>
  5537. core_map(f, a => ({ ...k, [tag]: a }))
  5538. ).traced(trace)
  5539. ),
  5540. bindValue = dualWithTrace(
  5541. 3,
  5542. (trace, restore) => (self, tag, f) =>
  5543. core_map(self, k => ({ ...k, [tag]: restore(f)(k) })).traced(trace)
  5544. ),
  5545. bindValueDiscard = dualWithTrace(
  5546. 3,
  5547. trace => (self, tag, f) =>
  5548. core_map(self, k => ({ ...k, [tag]: f })).traced(trace)
  5549. ),
  5550. filterOrElse = dualWithTrace(
  5551. 3,
  5552. (trace, restore) => (self, f, orElse) =>
  5553. filterOrElseWith(self, restore(f), orElse).traced(trace)
  5554. ),
  5555. filterOrElseWith = dualWithTrace(
  5556. 3,
  5557. (trace, restore) => (self, f, orElse) =>
  5558. core_flatMap(self, a =>
  5559. restore(f)(a) ? succeed(a) : restore(orElse)(a)
  5560. ).traced(trace)
  5561. ),
  5562. filterOrFail = dualWithTrace(
  5563. 3,
  5564. (trace, restore) => (self, f, error) =>
  5565. filterOrElse(self, restore(f), () => failSync(restore(error))).traced(
  5566. trace
  5567. )
  5568. ),
  5569. effect_match = dualWithTrace(
  5570. 3,
  5571. (trace, restore) => (self, onFailure, onSuccess) =>
  5572. matchEffect(
  5573. self,
  5574. e => succeed(restore(onFailure)(e)),
  5575. a => succeed(restore(onSuccess)(a))
  5576. ).traced(trace)
  5577. )
  5578. class EffectGen {
  5579. constructor(value) {
  5580. this.value = value
  5581. }
  5582. [Symbol.iterator]() {
  5583. return new SingleShotGen(this)
  5584. }
  5585. }
  5586. const getFiberRefs = methodWithTrace(
  5587. trace => () =>
  5588. withFiberRuntime(state => succeed(state.unsafeGetFiberRefs())).traced(
  5589. trace
  5590. )
  5591. ),
  5592. ignore = methodWithTrace(
  5593. trace => self =>
  5594. effect_match(self, Function_constVoid, Function_constVoid).traced(
  5595. trace
  5596. )
  5597. ),
  5598. effect_isSuccess = methodWithTrace(
  5599. trace => self =>
  5600. effect_match(self, Function_constFalse, Function_constTrue).traced(
  5601. trace
  5602. )
  5603. ),
  5604. someError = Option_some(Level_Error),
  5605. someWarning = Option_some(Warning),
  5606. someInfo = Option_some(Info),
  5607. someDebug = Option_some(Level_Debug),
  5608. log = methodWithTrace(
  5609. trace => message =>
  5610. withFiberRuntime(fiberState => {
  5611. fiberState.log(message, cause_empty, Option_none())
  5612. return core_unit()
  5613. }).traced(trace)
  5614. ),
  5615. logDebug = methodWithTrace(
  5616. trace => message =>
  5617. withFiberRuntime(fiberState => {
  5618. fiberState.log(message, cause_empty, someDebug)
  5619. return core_unit()
  5620. }).traced(trace)
  5621. ),
  5622. logError = methodWithTrace(
  5623. trace => message =>
  5624. withFiberRuntime(fiberState => {
  5625. fiberState.log(message, cause_empty, someError)
  5626. return core_unit()
  5627. }).traced(trace)
  5628. ),
  5629. logInfo = methodWithTrace(
  5630. trace => message =>
  5631. withFiberRuntime(fiberState => {
  5632. fiberState.log(message, cause_empty, someInfo)
  5633. return core_unit()
  5634. }).traced(trace)
  5635. ),
  5636. logWarning = methodWithTrace(
  5637. trace => message =>
  5638. withFiberRuntime(fiberState => {
  5639. fiberState.log(message, cause_empty, someWarning)
  5640. return core_unit()
  5641. }).traced(trace)
  5642. ),
  5643. logAnnotate = dualWithTrace(
  5644. 3,
  5645. trace => (effect, key, value) =>
  5646. core_flatMap(fiberRefGet(currentLogAnnotations), annotations =>
  5647. suspend(() =>
  5648. fiberRefLocally(
  5649. currentLogAnnotations,
  5650. HashMap_set(key, value)(annotations)
  5651. )(effect)
  5652. )
  5653. ).traced(trace)
  5654. ),
  5655. orElseSucceed = dualWithTrace(
  5656. 2,
  5657. (trace, restore) => (self, evaluate) =>
  5658. core_orElse(self, () => sync(restore(evaluate))).traced(trace)
  5659. ),
  5660. patchFiberRefs = methodWithTrace(
  5661. trace => patch =>
  5662. updateFiberRefs((fiberId, fiberRefs) =>
  5663. patch_patch(fiberId, fiberRefs)(patch)
  5664. ).traced(trace)
  5665. ),
  5666. promise = methodWithTrace(
  5667. (trace, restore) => evaluate =>
  5668. core_async(resolve => {
  5669. restore(evaluate)()
  5670. .then(a => resolve(exitSucceed(a)))
  5671. .catch(e => resolve(exitFailCause(die(e))))
  5672. }).traced(trace)
  5673. ),
  5674. effect_sleep = Clock_sleep,
  5675. summarized = dualWithTrace(
  5676. 3,
  5677. (trace, restore) => (self, summary, f) =>
  5678. core_flatMap(summary, start =>
  5679. core_flatMap(self, value =>
  5680. core_map(summary, end =>
  5681. ((...args) => args)(restore(f)(start, end), value)
  5682. )
  5683. )
  5684. ).traced(trace)
  5685. ),
  5686. tapErrorCause = dualWithTrace(
  5687. 2,
  5688. (trace, restore) => (self, f) =>
  5689. matchCauseEffect(
  5690. self,
  5691. cause => core_zipRight(restore(f)(cause), failCause(cause)),
  5692. succeed
  5693. ).traced(trace)
  5694. ),
  5695. effect_all = methodWithTrace(
  5696. trace =>
  5697. function () {
  5698. return 1 === arguments.length
  5699. ? isEffect(arguments[0])
  5700. ? core_map(arguments[0], x => [x])
  5701. : Array.isArray(arguments[0])
  5702. ? core_map(
  5703. effect_collectAll(arguments[0]),
  5704. toReadonlyArray
  5705. ).traced(trace)
  5706. : core_map(values => {
  5707. const res = {}
  5708. for (const [k, v] of values) res[k] = v
  5709. return res
  5710. })(
  5711. core_forEach(Object.entries(arguments[0]), ([_, e]) =>
  5712. core_map(e, a => [_, a])
  5713. )
  5714. ).traced(trace)
  5715. : core_map(effect_collectAll(arguments), toReadonlyArray).traced(
  5716. trace
  5717. )
  5718. }
  5719. ),
  5720. updateFiberRefs = methodWithTrace(
  5721. (trace, restore) => f =>
  5722. withFiberRuntime(state => {
  5723. state.setFiberRefs(
  5724. restore(f)(state.id(), state.unsafeGetFiberRefs())
  5725. )
  5726. return core_unit()
  5727. }).traced(trace)
  5728. ),
  5729. MutableHashMap_TypeId = Symbol.for("@effect/data/MutableHashMap")
  5730. class MutableHashMapImpl {
  5731. constructor() {
  5732. this._id = MutableHashMap_TypeId
  5733. this.backingMap = MutableRef_make(mjs_HashMap_empty())
  5734. }
  5735. [Symbol.iterator]() {
  5736. return this.backingMap.current[Symbol.iterator]()
  5737. }
  5738. toString() {
  5739. return `MutableHashMap(${Array.from(this)
  5740. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  5741. .join(", ")})`
  5742. }
  5743. toJSON() {
  5744. return { _tag: "MutableHashMap", values: Array.from(this) }
  5745. }
  5746. [Symbol.for("nodejs.util.inspect.custom")]() {
  5747. return this.toJSON()
  5748. }
  5749. }
  5750. const MutableHashMap_get = Function_dual(2, (self, key) =>
  5751. mjs_HashMap_get(self.backingMap.current, key)
  5752. ),
  5753. MutableHashMap_has = Function_dual(2, (self, key) =>
  5754. Option_isSome(MutableHashMap_get(self, key))
  5755. ),
  5756. MutableHashMap_set = Function_dual(3, (self, key, value) => {
  5757. MutableRef_update(self.backingMap, HashMap_set(key, value))
  5758. return self
  5759. }),
  5760. ExecutionStrategy_sequential = { _tag: "Sequential" }
  5761. var fiberStatus_a, fiberStatus_b, fiberStatus_c
  5762. const FiberStatusTypeId = Symbol.for("@effect/io/Fiber/Status")
  5763. class Done {
  5764. constructor() {
  5765. this[fiberStatus_a] = FiberStatusTypeId
  5766. this._tag = "Done"
  5767. }
  5768. [((fiberStatus_a = FiberStatusTypeId), symbol)]() {
  5769. return combine(Hash_hash(this._tag))(
  5770. Hash_hash("@effect/io/Fiber/Status")
  5771. )
  5772. }
  5773. [Equal_symbol](that) {
  5774. return isFiberStatus(that) && "Done" === that._tag
  5775. }
  5776. }
  5777. class Running {
  5778. constructor(runtimeFlags) {
  5779. this.runtimeFlags = runtimeFlags
  5780. this[fiberStatus_b] = FiberStatusTypeId
  5781. this._tag = "Running"
  5782. }
  5783. [((fiberStatus_b = FiberStatusTypeId), symbol)]() {
  5784. return combine(Hash_hash(this.runtimeFlags))(
  5785. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  5786. )
  5787. }
  5788. [Equal_symbol](that) {
  5789. return (
  5790. isFiberStatus(that) &&
  5791. "Running" === that._tag &&
  5792. this.runtimeFlags === that.runtimeFlags
  5793. )
  5794. }
  5795. }
  5796. class Suspended {
  5797. constructor(runtimeFlags, blockingOn) {
  5798. this.runtimeFlags = runtimeFlags
  5799. this.blockingOn = blockingOn
  5800. this[fiberStatus_c] = FiberStatusTypeId
  5801. this._tag = "Suspended"
  5802. }
  5803. [((fiberStatus_c = FiberStatusTypeId), symbol)]() {
  5804. return combine(Hash_hash(this.blockingOn))(
  5805. combine(Hash_hash(this.runtimeFlags))(
  5806. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  5807. )
  5808. )
  5809. }
  5810. [Equal_symbol](that) {
  5811. return (
  5812. isFiberStatus(that) &&
  5813. "Suspended" === that._tag &&
  5814. this.runtimeFlags === that.runtimeFlags &&
  5815. equals(this.blockingOn, that.blockingOn)
  5816. )
  5817. }
  5818. }
  5819. const isFiberStatus = u =>
  5820. "object" == typeof u && null != u && FiberStatusTypeId in u,
  5821. Status_done = new Done(),
  5822. Status_running = runtimeFlags => new Running(runtimeFlags),
  5823. interruptSignal = cause => ({ _tag: "InterruptSignal", cause }),
  5824. stateful = onFiber => ({ _tag: "Stateful", onFiber }),
  5825. resume = effect => ({ _tag: "Resume", effect })
  5826. var fiberScope_a, fiberScope_b
  5827. const FiberScopeTypeId = Symbol.for("@effect/io/Fiber/Scope")
  5828. class Global {
  5829. constructor() {
  5830. this[fiberScope_a] = FiberScopeTypeId
  5831. this.fiberId = Id_none
  5832. this.roots = new Set()
  5833. }
  5834. add(_runtimeFlags, child) {
  5835. this.roots.add(child)
  5836. child.unsafeAddObserver(() => {
  5837. this.roots.delete(child)
  5838. })
  5839. }
  5840. }
  5841. fiberScope_a = FiberScopeTypeId
  5842. class Local {
  5843. constructor(fiberId, parent) {
  5844. this.fiberId = fiberId
  5845. this.parent = parent
  5846. this[fiberScope_b] = FiberScopeTypeId
  5847. }
  5848. add(_runtimeFlags, child) {
  5849. this.parent.tell(
  5850. stateful(parentFiber => {
  5851. parentFiber.addChild(child)
  5852. child.unsafeAddObserver(() => {
  5853. parentFiber.removeChild(child)
  5854. })
  5855. })
  5856. )
  5857. }
  5858. }
  5859. fiberScope_b = FiberScopeTypeId
  5860. const globalScope = globalValue(
  5861. Symbol.for("@effect/io/FiberScope/Global"),
  5862. () => new Global()
  5863. ),
  5864. FiberTypeId = Symbol.for("@effect/io/Fiber"),
  5865. fiberVariance = { _E: _ => _, _A: _ => _ },
  5866. RuntimeFiberTypeId = Symbol.for("@effect/io/Fiber"),
  5867. _await = methodWithTrace(trace => self => self.await().traced(trace)),
  5868. fiber_join = methodWithTrace(
  5869. trace => self =>
  5870. core_zipLeft(core_flatten(self.await()), self.inheritAll()).traced(
  5871. trace
  5872. )
  5873. ),
  5874. currentFiberURI = "@effect/io/Fiber/Current",
  5875. MutableList_TypeId = Symbol.for("@effect/data/MutableList")
  5876. class MutableListImpl {
  5877. constructor() {
  5878. this._id = MutableList_TypeId
  5879. this.head = void 0
  5880. this.tail = void 0
  5881. this._length = 0
  5882. }
  5883. [Symbol.iterator]() {
  5884. let done = !1,
  5885. head = this.head
  5886. return {
  5887. next() {
  5888. if (done) return this.return()
  5889. if (null == head) {
  5890. done = !0
  5891. return this.return()
  5892. }
  5893. const value = head.value
  5894. head = head.next
  5895. return { done, value }
  5896. },
  5897. return(value) {
  5898. done || (done = !0)
  5899. return { done: !0, value }
  5900. },
  5901. }
  5902. }
  5903. toString() {
  5904. return `MutableList(${Array.from(this).map(String).join(", ")})`
  5905. }
  5906. toJSON() {
  5907. return { _tag: "MutableList", values: Array.from(this) }
  5908. }
  5909. [Symbol.for("nodejs.util.inspect.custom")]() {
  5910. return this.toJSON()
  5911. }
  5912. }
  5913. class LinkedListNode {
  5914. constructor(value) {
  5915. this.value = value
  5916. this.removed = !1
  5917. this.prev = void 0
  5918. this.next = void 0
  5919. }
  5920. }
  5921. const MutableList_isEmpty = self => 0 === MutableList_length(self),
  5922. MutableList_length = self => self._length,
  5923. MutableList_append = Function_dual(2, (self, value) => {
  5924. const node = new LinkedListNode(value)
  5925. void 0 === self.head && (self.head = node)
  5926. if (void 0 === self.tail) self.tail = node
  5927. else {
  5928. self.tail.next = node
  5929. node.prev = self.tail
  5930. self.tail = node
  5931. }
  5932. self._length += 1
  5933. return self
  5934. }),
  5935. MutableQueue_TypeId = Symbol.for("@effect/data/MutableQueue")
  5936. class MutableQueueImpl {
  5937. constructor(capacity = undefined) {
  5938. this.capacity = capacity
  5939. this._tag = "Bounded"
  5940. this._id = MutableQueue_TypeId
  5941. this.queue = new MutableListImpl()
  5942. }
  5943. [Symbol.iterator]() {
  5944. return Array.from(this.queue)[Symbol.iterator]()
  5945. }
  5946. toString() {
  5947. return `MutableQueue(${Array.from(this).map(String).join(", ")})`
  5948. }
  5949. toJSON() {
  5950. return { _tag: "MutableQueue", values: Array.from(this) }
  5951. }
  5952. [Symbol.for("nodejs.util.inspect.custom")]() {
  5953. return this.toJSON()
  5954. }
  5955. }
  5956. const MutableQueue_isEmpty = self => MutableList_isEmpty(self.queue),
  5957. offer = Function_dual(2, (self, value) => {
  5958. const queueLength = MutableList_length(self.queue)
  5959. if (void 0 !== self.capacity && queueLength === self.capacity) return !1
  5960. MutableList_append(value)(self.queue)
  5961. return !0
  5962. }),
  5963. MutableQueue_poll = Function_dual(2, (self, def) =>
  5964. MutableList_isEmpty(self.queue)
  5965. ? def
  5966. : (self => {
  5967. const head = self.head
  5968. if (void 0 !== head) {
  5969. ;((self, node) => {
  5970. if (!node.removed) {
  5971. node.removed = !0
  5972. if (void 0 !== node.prev && void 0 !== node.next) {
  5973. node.prev.next = node.next
  5974. node.next.prev = node.prev
  5975. } else if (void 0 !== node.prev) {
  5976. self.tail = node.prev
  5977. node.prev.next = void 0
  5978. } else if (void 0 !== node.next) {
  5979. self.head = node.next
  5980. node.next.prev = void 0
  5981. } else {
  5982. self.tail = void 0
  5983. self.head = void 0
  5984. }
  5985. self._length > 0 && (self._length -= 1)
  5986. }
  5987. })(self, head)
  5988. return head.value
  5989. }
  5990. })(self.queue)
  5991. ),
  5992. renderToString = u => {
  5993. if (
  5994. "object" == typeof u &&
  5995. null != u &&
  5996. "toString" in u &&
  5997. "function" == typeof u.toString &&
  5998. u.toString !== Object.prototype.toString
  5999. )
  6000. return u.toString()
  6001. if ("string" == typeof u) return `Error: ${u}`
  6002. if (
  6003. "object" == typeof u &&
  6004. null !== u &&
  6005. "message" in u &&
  6006. "string" == typeof u.message
  6007. ) {
  6008. const raw = JSON.parse(JSON.stringify(u)),
  6009. keys = new Set(Object.keys(raw))
  6010. keys.delete("name")
  6011. keys.delete("message")
  6012. keys.delete("_tag")
  6013. if (0 === keys.size)
  6014. return `${
  6015. "name" in u && "string" == typeof u.name ? u.name : "Error"
  6016. }${
  6017. "_tag" in u && "string" == typeof u._tag ? `(${u._tag})` : ""
  6018. }: ${u.message}`
  6019. }
  6020. return `Error: ${JSON.stringify(u)}`
  6021. },
  6022. renderStack = span =>
  6023. Option_isNone(span)
  6024. ? []
  6025. : span.value.stack.length > 0
  6026. ? (chunk => {
  6027. const ret = []
  6028. for (const s of chunk) {
  6029. const r = s?.toFrame()
  6030. r &&
  6031. runtimeDebug.filterStackFrame(r) &&
  6032. ret.push(renderFrame(r))
  6033. }
  6034. return ret
  6035. })(span.value.stack)
  6036. : [],
  6037. defaultErrorToLines = error =>
  6038. error instanceof Error
  6039. ? (error => {
  6040. if (error.stack) {
  6041. const stack = runtimeDebug.parseStack(error),
  6042. traces = []
  6043. for (const frame of stack)
  6044. if (frame) {
  6045. if (!runtimeDebug.filterStackFrame(frame)) break
  6046. traces.push(renderFrame(frame))
  6047. }
  6048. return [renderToString(error), traces.join("\r\n")]
  6049. }
  6050. return [String(error), void 0]
  6051. })(error)
  6052. : [renderToString(error), void 0]
  6053. class RenderError {
  6054. constructor(seq, message, stack) {
  6055. this.seq = seq
  6056. this.message = message
  6057. this.stack = stack
  6058. }
  6059. }
  6060. const cause_pretty_pretty = cause => {
  6061. if (isInterruptedOnly(cause))
  6062. return "All fibers interrupted without errors."
  6063. const errors = prettyErrors(cause),
  6064. final = Array.from(errors)
  6065. .sort((a, b) => (a.seq === b.seq ? 0 : a.seq > b.seq ? 1 : -1))
  6066. .map(e => {
  6067. let message = e.message
  6068. e.stack && e.stack.length > 0 && (message += `\r\n${e.stack}`)
  6069. return message
  6070. })
  6071. .join("\r\n\r\n")
  6072. return final.includes("\r\n") ? `\r\n${final}\r\n` : final
  6073. },
  6074. prettyErrors = cause =>
  6075. reduceWithContext(cause, void 0, {
  6076. emptyCase: () => [],
  6077. dieCase: (_, err) => {
  6078. const rendered = defaultErrorToLines(err)
  6079. return [
  6080. {
  6081. message: rendered[0],
  6082. errorSack: rendered[1],
  6083. fiberStack: Option_none(),
  6084. },
  6085. ]
  6086. },
  6087. failCase: (_, err) => {
  6088. const rendered = defaultErrorToLines(err)
  6089. return [
  6090. {
  6091. message: rendered[0],
  6092. errorSack: rendered[1],
  6093. fiberStack: Option_none(),
  6094. },
  6095. ]
  6096. },
  6097. interruptCase: () => [],
  6098. parallelCase: (_, l, r) => [...l, ...r],
  6099. sequentialCase: (_, l, r) => [...l, ...r],
  6100. annotatedCase: (_, v, parent) =>
  6101. isStackAnnotation(parent)
  6102. ? v.map(r => ({
  6103. message: r.message,
  6104. errorSack: r.errorSack,
  6105. fiberStack: orElse(() => Option_some(parent))(
  6106. Option_map(
  6107. r.fiberStack,
  6108. annotation =>
  6109. new StackAnnotation(
  6110. annotation.stack.length <
  6111. runtimeDebug.traceStackLimit &&
  6112. parent.stack.length > 0 &&
  6113. ((annotation.stack.length > 0 &&
  6114. unsafeLast(parent.stack) !==
  6115. unsafeLast(annotation.stack)) ||
  6116. 0 === annotation.stack.length)
  6117. ? Chunk_take(runtimeDebug.traceStackLimit)(
  6118. dedupeAdjacent(
  6119. Chunk_concat(parent.stack)(annotation.stack)
  6120. )
  6121. )
  6122. : annotation.stack,
  6123. annotation.seq
  6124. )
  6125. )
  6126. ),
  6127. }))
  6128. : v,
  6129. }).flatMap(r =>
  6130. ((error, errorStack, stack) => [
  6131. new RenderError(
  6132. "Some" === stack._tag ? stack.value.seq : 0,
  6133. error,
  6134. errorStack
  6135. ? errorStack + "\r\n" + renderStack(stack).join("\r\n")
  6136. : renderStack(stack).join("\r\n")
  6137. ),
  6138. ])(r.message, r.errorSack, r.fiberStack)
  6139. )
  6140. function renderFrame(r) {
  6141. return r
  6142. ? r.name
  6143. ? ` at ${r.name} (${r.fileName}:${r.line}:${r.column})`
  6144. : ` at ${r.fileName}:${r.line}:${r.column}`
  6145. : " at <unknown>"
  6146. }
  6147. const LoggerTypeId = Symbol.for("@effect/io/Logger"),
  6148. loggerVariance = { _Message: _ => _, _Output: _ => _ },
  6149. makeLogger = log => ({ [LoggerTypeId]: loggerVariance, log }),
  6150. stringLogger = makeLogger(
  6151. (fiberId, logLevel, message, cause, _context, spans, annotations) => {
  6152. const now = new Date(),
  6153. nowMillis = now.getTime()
  6154. let output = [
  6155. `timestamp=${now.toISOString()}`,
  6156. `level=${logLevel.label}`,
  6157. `fiber=${threadName(fiberId)}`,
  6158. ].join(" ")
  6159. if (message.length > 0) {
  6160. output += " message="
  6161. output = appendQuoted(message, output)
  6162. }
  6163. if (null != cause && cause != cause_empty) {
  6164. output += " cause="
  6165. output = appendQuoted(cause_pretty_pretty(cause), output)
  6166. }
  6167. if (Chunk_isNonEmpty(spans)) {
  6168. output += " "
  6169. let first = !0
  6170. for (const span of spans) {
  6171. first ? (first = !1) : (output += " ")
  6172. output += Span_render(nowMillis)(span)
  6173. }
  6174. }
  6175. if (mjs_HashMap_size(annotations) > 0) {
  6176. output += " "
  6177. let first = !0
  6178. for (const [key, value] of annotations) {
  6179. first ? (first = !1) : (output += " ")
  6180. output += filterKeyName(key)
  6181. output += "="
  6182. output = appendQuoted(value, output)
  6183. }
  6184. }
  6185. return output
  6186. }
  6187. ),
  6188. textOnly = /^[^\s"=]+$/,
  6189. appendQuoted = (label, output) =>
  6190. output +
  6191. (label.match(textOnly)
  6192. ? label
  6193. : `"${label.replace(/\\([\s\S])|(")/g, "\\$1$2")}"`),
  6194. filterKeyName = key => key.replace(/[\s="]/g, "_"),
  6195. logger_zip = Function_dual(2, (self, that) =>
  6196. makeLogger(
  6197. (fiberId, logLevel, message, cause, context, spans, annotations) => [
  6198. self.log(
  6199. fiberId,
  6200. logLevel,
  6201. message,
  6202. cause,
  6203. context,
  6204. spans,
  6205. annotations
  6206. ),
  6207. that.log(
  6208. fiberId,
  6209. logLevel,
  6210. message,
  6211. cause,
  6212. context,
  6213. spans,
  6214. annotations
  6215. ),
  6216. ]
  6217. )
  6218. )
  6219. var keyType_a, keyType_b, _g, _h
  6220. const MetricKeyTypeTypeId = Symbol.for("@effect/io/Metric/KeyType"),
  6221. CounterKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Counter"),
  6222. FrequencyKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Frequency"),
  6223. GaugeKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Gauge"),
  6224. HistogramKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Histogram"),
  6225. SummaryKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Summary"),
  6226. metricKeyTypeVariance = { _In: _ => _, _Out: _ => _ }
  6227. class CounterKeyType {
  6228. constructor() {
  6229. this[keyType_a] = metricKeyTypeVariance
  6230. this[keyType_b] = CounterKeyTypeTypeId
  6231. }
  6232. [((keyType_a = MetricKeyTypeTypeId),
  6233. (keyType_b = CounterKeyTypeTypeId),
  6234. symbol)]() {
  6235. return Hash_hash("effect/io/Metric/KeyType/Counter")
  6236. }
  6237. [Equal_symbol](that) {
  6238. return isCounterKey(that)
  6239. }
  6240. }
  6241. class HistogramKeyType {
  6242. constructor(boundaries) {
  6243. this.boundaries = boundaries
  6244. this[_g] = metricKeyTypeVariance
  6245. this[_h] = HistogramKeyTypeTypeId
  6246. }
  6247. [((_g = MetricKeyTypeTypeId), (_h = HistogramKeyTypeTypeId), symbol)]() {
  6248. return combine(Hash_hash(this.boundaries))(
  6249. Hash_hash("effect/io/Metric/KeyType/Histogram")
  6250. )
  6251. }
  6252. [Equal_symbol](that) {
  6253. return isHistogramKey(that) && equals(this.boundaries, that.boundaries)
  6254. }
  6255. }
  6256. const counter = new CounterKeyType(),
  6257. isCounterKey = u =>
  6258. "object" == typeof u && null != u && CounterKeyTypeTypeId in u,
  6259. isFrequencyKey = u =>
  6260. "object" == typeof u && null != u && FrequencyKeyTypeTypeId in u,
  6261. isGaugeKey = u =>
  6262. "object" == typeof u && null != u && GaugeKeyTypeTypeId in u,
  6263. isHistogramKey = u =>
  6264. "object" == typeof u && null != u && HistogramKeyTypeTypeId in u,
  6265. isSummaryKey = u =>
  6266. "object" == typeof u && null != u && SummaryKeyTypeTypeId in u
  6267. var key_a
  6268. const MetricKeyTypeId = Symbol.for("@effect/io/Metric/Key"),
  6269. metricKeyVariance = { _Type: _ => _ }
  6270. class MetricKeyImpl {
  6271. constructor(name, keyType, tags = mjs_HashSet_empty()) {
  6272. this.name = name
  6273. this.keyType = keyType
  6274. this.tags = tags
  6275. this[key_a] = metricKeyVariance
  6276. }
  6277. [((key_a = MetricKeyTypeId), symbol)]() {
  6278. return combine(Hash_hash(this.tags))(
  6279. combine(Hash_hash(this.keyType))(Hash_hash(this.name))
  6280. )
  6281. }
  6282. [Equal_symbol](u) {
  6283. return (
  6284. isMetricKey(u) &&
  6285. this.name === u.name &&
  6286. equals(this.keyType, u.keyType) &&
  6287. equals(this.tags, u.tags)
  6288. )
  6289. }
  6290. }
  6291. const isMetricKey = u =>
  6292. "object" == typeof u && null != u && MetricKeyTypeId in u,
  6293. key_taggedWithLabelSet = Function_dual(2, (self, extraTags) =>
  6294. 0 === mjs_HashSet_size(extraTags)
  6295. ? self
  6296. : new MetricKeyImpl(
  6297. self.name,
  6298. self.keyType,
  6299. mjs_HashSet_union(extraTags)(self.tags)
  6300. )
  6301. )
  6302. var state_a,
  6303. state_b,
  6304. state_c,
  6305. state_d,
  6306. state_e,
  6307. state_f,
  6308. state_g,
  6309. state_h,
  6310. state_j,
  6311. state_k
  6312. const MetricStateTypeId = Symbol.for("@effect/io/Metric/State"),
  6313. CounterStateTypeId = Symbol.for("effect/io/Metric/State/Counter"),
  6314. FrequencyStateTypeId = Symbol.for("effect/io/Metric/State/Frequency"),
  6315. GaugeStateTypeId = Symbol.for("effect/io/Metric/State/Gauge"),
  6316. HistogramStateTypeId = Symbol.for("effect/io/Metric/State/Histogram"),
  6317. SummaryStateTypeId = Symbol.for("effect/io/Metric/State/Summary"),
  6318. metricStateVariance = { _A: _ => _ }
  6319. class CounterState {
  6320. constructor(count) {
  6321. this.count = count
  6322. this[state_a] = metricStateVariance
  6323. this[state_b] = CounterStateTypeId
  6324. }
  6325. [((state_a = MetricStateTypeId),
  6326. (state_b = CounterStateTypeId),
  6327. symbol)]() {
  6328. return combine(Hash_hash(this.count))(
  6329. Hash_hash("effect/io/Metric/State/Counter")
  6330. )
  6331. }
  6332. [Equal_symbol](that) {
  6333. return isCounterState(that) && this.count === that.count
  6334. }
  6335. }
  6336. class FrequencyState {
  6337. constructor(occurrences) {
  6338. this.occurrences = occurrences
  6339. this[state_c] = metricStateVariance
  6340. this[state_d] = FrequencyStateTypeId
  6341. }
  6342. [((state_c = MetricStateTypeId),
  6343. (state_d = FrequencyStateTypeId),
  6344. symbol)]() {
  6345. return combine(Hash_hash(this.occurrences))(
  6346. Hash_hash("effect/io/Metric/State/Frequency")
  6347. )
  6348. }
  6349. [Equal_symbol](that) {
  6350. return (
  6351. isFrequencyState(that) && equals(this.occurrences, that.occurrences)
  6352. )
  6353. }
  6354. }
  6355. class GaugeState {
  6356. constructor(value) {
  6357. this.value = value
  6358. this[state_e] = metricStateVariance
  6359. this[state_f] = GaugeStateTypeId
  6360. }
  6361. [((state_e = MetricStateTypeId),
  6362. (state_f = GaugeStateTypeId),
  6363. symbol)]() {
  6364. return combine(Hash_hash(this.value))(
  6365. Hash_hash("effect/io/Metric/State/Gauge")
  6366. )
  6367. }
  6368. [Equal_symbol](u) {
  6369. return isGaugeState(u) && this.value === u.value
  6370. }
  6371. }
  6372. class HistogramState {
  6373. constructor(buckets, count, min, max, sum) {
  6374. this.buckets = buckets
  6375. this.count = count
  6376. this.min = min
  6377. this.max = max
  6378. this.sum = sum
  6379. this[state_g] = metricStateVariance
  6380. this[state_h] = HistogramStateTypeId
  6381. }
  6382. [((state_g = MetricStateTypeId),
  6383. (state_h = HistogramStateTypeId),
  6384. symbol)]() {
  6385. return combine(Hash_hash(this.sum))(
  6386. combine(Hash_hash(this.max))(
  6387. combine(Hash_hash(this.min))(
  6388. combine(Hash_hash(this.count))(
  6389. combine(Hash_hash(this.buckets))(
  6390. Hash_hash("effect/io/Metric/State/Histogram")
  6391. )
  6392. )
  6393. )
  6394. )
  6395. )
  6396. }
  6397. [Equal_symbol](that) {
  6398. return (
  6399. isHistogramState(that) &&
  6400. equals(this.buckets, that.buckets) &&
  6401. this.count === that.count &&
  6402. this.min === that.min &&
  6403. this.max === that.max &&
  6404. this.sum === that.sum
  6405. )
  6406. }
  6407. }
  6408. class SummaryState {
  6409. constructor(error, quantiles, count, min, max, sum) {
  6410. this.error = error
  6411. this.quantiles = quantiles
  6412. this.count = count
  6413. this.min = min
  6414. this.max = max
  6415. this.sum = sum
  6416. this[state_j] = metricStateVariance
  6417. this[state_k] = SummaryStateTypeId
  6418. }
  6419. [((state_j = MetricStateTypeId),
  6420. (state_k = SummaryStateTypeId),
  6421. symbol)]() {
  6422. return combine(Hash_hash(this.sum))(
  6423. combine(Hash_hash(this.max))(
  6424. combine(Hash_hash(this.min))(
  6425. combine(Hash_hash(this.count))(
  6426. combine(Hash_hash(this.quantiles))(
  6427. combine(Hash_hash(this.error))(
  6428. Hash_hash("effect/io/Metric/State/Summary")
  6429. )
  6430. )
  6431. )
  6432. )
  6433. )
  6434. )
  6435. }
  6436. [Equal_symbol](that) {
  6437. return (
  6438. isSummaryState(that) &&
  6439. this.error === that.error &&
  6440. equals(this.quantiles, that.quantiles) &&
  6441. this.count === that.count &&
  6442. this.min === that.min &&
  6443. this.max === that.max &&
  6444. this.sum === that.sum
  6445. )
  6446. }
  6447. }
  6448. const isCounterState = u =>
  6449. "object" == typeof u && null != u && CounterStateTypeId in u,
  6450. isFrequencyState = u =>
  6451. "object" == typeof u && null != u && FrequencyStateTypeId in u,
  6452. isGaugeState = u =>
  6453. "object" == typeof u && null != u && GaugeStateTypeId in u,
  6454. isHistogramState = u =>
  6455. "object" == typeof u && null != u && HistogramStateTypeId in u,
  6456. isSummaryState = u =>
  6457. "object" == typeof u && null != u && SummaryStateTypeId in u,
  6458. MetricHookTypeId = Symbol.for("@effect/io/Metric/Hook"),
  6459. metricHookVariance = { _In: _ => _, _Out: _ => _ },
  6460. hook_make = (get, update) => ({
  6461. [MetricHookTypeId]: metricHookVariance,
  6462. update,
  6463. get,
  6464. }),
  6465. calculateQuantiles = (error, sortedQuantiles, sortedSamples) => {
  6466. const sampleCount = sortedSamples.length
  6467. if (Chunk_isEmpty(sortedQuantiles)) return Chunk_empty()
  6468. const head = unsafeHead(sortedQuantiles),
  6469. tail = Chunk_drop(1)(sortedQuantiles),
  6470. resolved = Chunk_reduce(
  6471. Chunk_of(
  6472. resolveQuantile(
  6473. error,
  6474. sampleCount,
  6475. Option_none(),
  6476. 0,
  6477. head,
  6478. sortedSamples
  6479. )
  6480. ),
  6481. (accumulator, quantile) => {
  6482. const h = unsafeHead(accumulator)
  6483. return Chunk_append(
  6484. resolveQuantile(
  6485. error,
  6486. sampleCount,
  6487. h.value,
  6488. h.consumed,
  6489. quantile,
  6490. h.rest
  6491. )
  6492. )(accumulator)
  6493. }
  6494. )(tail)
  6495. return Chunk_map(rq => [rq.quantile, rq.value])(resolved)
  6496. },
  6497. resolveQuantile = (
  6498. error,
  6499. sampleCount,
  6500. current,
  6501. consumed,
  6502. quantile,
  6503. rest
  6504. ) => {
  6505. let error_1 = error,
  6506. sampleCount_1 = sampleCount,
  6507. current_1 = current,
  6508. consumed_1 = consumed,
  6509. quantile_1 = quantile,
  6510. rest_1 = rest,
  6511. error_2 = error,
  6512. sampleCount_2 = sampleCount,
  6513. current_2 = current,
  6514. consumed_2 = consumed,
  6515. quantile_2 = quantile,
  6516. rest_2 = rest
  6517. for (;;) {
  6518. if (Chunk_isEmpty(rest_1))
  6519. return {
  6520. quantile: quantile_1,
  6521. value: Option_none(),
  6522. consumed: consumed_1,
  6523. rest: Chunk_empty(),
  6524. }
  6525. if (1 === quantile_1)
  6526. return {
  6527. quantile: quantile_1,
  6528. value: Option_some(unsafeLast(rest_1)),
  6529. consumed: consumed_1 + rest_1.length,
  6530. rest: Chunk_empty(),
  6531. }
  6532. const sameHead = splitWhere(n => n > unsafeHead(rest_1))(rest_1),
  6533. desired = quantile_1 * sampleCount_1,
  6534. allowedError = (error_1 / 2) * desired,
  6535. candConsumed = consumed_1 + sameHead[0].length,
  6536. candError = Math.abs(candConsumed - desired)
  6537. if (candConsumed < desired - allowedError) {
  6538. error_2 = error_1
  6539. sampleCount_2 = sampleCount_1
  6540. current_2 = Chunk_head(rest_1)
  6541. consumed_2 = candConsumed
  6542. quantile_2 = quantile_1
  6543. rest_2 = sameHead[1]
  6544. error_1 = error_2
  6545. sampleCount_1 = sampleCount_2
  6546. current_1 = current_2
  6547. consumed_1 = consumed_2
  6548. quantile_1 = quantile_2
  6549. rest_1 = rest_2
  6550. } else {
  6551. if (candConsumed > desired + allowedError)
  6552. return {
  6553. quantile: quantile_1,
  6554. value: current_1,
  6555. consumed: consumed_1,
  6556. rest: rest_1,
  6557. }
  6558. switch (current_1._tag) {
  6559. case "None":
  6560. error_2 = error_1
  6561. sampleCount_2 = sampleCount_1
  6562. current_2 = Chunk_head(rest_1)
  6563. consumed_2 = candConsumed
  6564. quantile_2 = quantile_1
  6565. rest_2 = sameHead[1]
  6566. error_1 = error_2
  6567. sampleCount_1 = sampleCount_2
  6568. current_1 = current_2
  6569. consumed_1 = consumed_2
  6570. quantile_1 = quantile_2
  6571. rest_1 = rest_2
  6572. continue
  6573. case "Some":
  6574. if (candError < Math.abs(desired - current_1.value)) {
  6575. error_2 = error_1
  6576. sampleCount_2 = sampleCount_1
  6577. current_2 = Chunk_head(rest_1)
  6578. consumed_2 = candConsumed
  6579. quantile_2 = quantile_1
  6580. rest_2 = sameHead[1]
  6581. error_1 = error_2
  6582. sampleCount_1 = sampleCount_2
  6583. current_1 = current_2
  6584. consumed_1 = consumed_2
  6585. quantile_1 = quantile_2
  6586. rest_1 = rest_2
  6587. continue
  6588. }
  6589. return {
  6590. quantile: quantile_1,
  6591. value: Option_some(current_1.value),
  6592. consumed: consumed_1,
  6593. rest: rest_1,
  6594. }
  6595. }
  6596. }
  6597. }
  6598. throw new Error(
  6599. "BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/io/issues"
  6600. )
  6601. },
  6602. MetricPairTypeId = Symbol.for("@effect/io/Metric/Pair"),
  6603. metricPairVariance = { _Type: _ => _ }
  6604. var registry_a
  6605. const MetricRegistryTypeId = Symbol.for("@effect/io/Metric/Registry")
  6606. class MetricRegistryImpl {
  6607. constructor() {
  6608. this[registry_a] = MetricRegistryTypeId
  6609. this.map = new MutableHashMapImpl()
  6610. }
  6611. snapshot() {
  6612. const result = []
  6613. for (const [key, hook] of this.map)
  6614. result.push(
  6615. ((metricKey = key),
  6616. (metricState = hook.get()),
  6617. { [MetricPairTypeId]: metricPairVariance, metricKey, metricState })
  6618. )
  6619. var metricKey, metricState
  6620. return mjs_HashSet_fromIterable(result)
  6621. }
  6622. get(key) {
  6623. const hook = getOrUndefined(MutableHashMap_get(key)(this.map))
  6624. if (null == hook) {
  6625. if (isCounterKey(key.keyType)) return this.getCounter(key)
  6626. if (isGaugeKey(key.keyType)) return this.getGauge(key)
  6627. if (isFrequencyKey(key.keyType)) return this.getFrequency(key)
  6628. if (isHistogramKey(key.keyType)) return this.getHistogram(key)
  6629. if (isSummaryKey(key.keyType)) return this.getSummary(key)
  6630. throw new Error(
  6631. "BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/io/issues"
  6632. )
  6633. }
  6634. return hook
  6635. }
  6636. getCounter(key) {
  6637. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6638. if (null == value) {
  6639. const counter = (_key => {
  6640. let sum = 0
  6641. return hook_make(
  6642. () => new CounterState(sum),
  6643. value => {
  6644. sum += value
  6645. }
  6646. )
  6647. })()
  6648. MutableHashMap_has(key)(this.map) ||
  6649. MutableHashMap_set(key, counter)(this.map)
  6650. value = counter
  6651. }
  6652. return value
  6653. }
  6654. getFrequency(key) {
  6655. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6656. if (null == value) {
  6657. const frequency = (_key => {
  6658. let count = 0
  6659. const values = new Map()
  6660. return hook_make(
  6661. () => {
  6662. return (
  6663. (occurrences = mjs_HashMap_fromIterable(
  6664. Array.from(values.entries()).map(([k, v]) => [k, v])
  6665. )),
  6666. new FrequencyState(occurrences)
  6667. )
  6668. var occurrences
  6669. },
  6670. word => {
  6671. count += 1
  6672. const slotCount = values.get(word) ?? 0
  6673. values.set(word, slotCount + 1)
  6674. }
  6675. )
  6676. })()
  6677. MutableHashMap_has(key)(this.map) ||
  6678. MutableHashMap_set(key, frequency)(this.map)
  6679. value = frequency
  6680. }
  6681. return value
  6682. }
  6683. getGauge(key) {
  6684. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6685. if (null == value) {
  6686. const gauge = ((_key, startAt) => {
  6687. let value = startAt
  6688. return hook_make(
  6689. () => (value => new GaugeState(value))(value),
  6690. v => {
  6691. value = v
  6692. }
  6693. )
  6694. })(0, 0)
  6695. MutableHashMap_has(key)(this.map) ||
  6696. MutableHashMap_set(key, gauge)(this.map)
  6697. value = gauge
  6698. }
  6699. return value
  6700. }
  6701. getHistogram(key) {
  6702. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6703. if (null == value) {
  6704. const histogram = (key => {
  6705. const bounds = key.keyType.boundaries.values,
  6706. size = bounds.length,
  6707. values = Array(size + 1),
  6708. boundaries = Array(size)
  6709. let count = 0,
  6710. sum = 0,
  6711. min = Number.MAX_VALUE,
  6712. max = Number.MIN_VALUE
  6713. mapWithIndex((i, n) => {
  6714. boundaries[i] = n
  6715. })(Chunk_sort(Order)(bounds))
  6716. return hook_make(
  6717. () =>
  6718. ((buckets, count, min, max, sum) =>
  6719. new HistogramState(buckets, count, min, max, sum))(
  6720. (() => {
  6721. const builder = []
  6722. let i = 0,
  6723. cumulated = 0
  6724. for (; i != size; ) {
  6725. const boundary = boundaries[i]
  6726. cumulated += values[i]
  6727. builder.push([boundary, cumulated])
  6728. i += 1
  6729. }
  6730. return Chunk_fromIterable(builder)
  6731. })(),
  6732. count,
  6733. min,
  6734. max,
  6735. sum
  6736. ),
  6737. value => {
  6738. let from = 0,
  6739. to = size
  6740. for (; from !== to; ) {
  6741. const mid = Math.floor(from + (to - from) / 2)
  6742. value <= boundaries[mid] ? (to = mid) : (from = mid)
  6743. to === from + 1 &&
  6744. (value <= boundaries[from] ? (to = from) : (from = to))
  6745. }
  6746. values[from] = values[from] + 1
  6747. count += 1
  6748. sum += value
  6749. value < min && (min = value)
  6750. value > max && (max = value)
  6751. }
  6752. )
  6753. })(key)
  6754. MutableHashMap_has(key)(this.map) ||
  6755. MutableHashMap_set(key, histogram)(this.map)
  6756. value = histogram
  6757. }
  6758. return value
  6759. }
  6760. getSummary(key) {
  6761. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6762. if (null == value) {
  6763. const summary = (key => {
  6764. const { error, maxAge, maxSize, quantiles } = key.keyType,
  6765. sortedQuantiles = Chunk_sort(Order)(quantiles),
  6766. values = Array(maxSize)
  6767. let head = 0,
  6768. count = 0,
  6769. sum = 0,
  6770. min = Number.MAX_VALUE,
  6771. max = Number.MIN_VALUE
  6772. return hook_make(
  6773. () =>
  6774. ((error, quantiles, count, min, max, sum) =>
  6775. new SummaryState(error, quantiles, count, min, max, sum))(
  6776. error,
  6777. (now => {
  6778. const builder = []
  6779. let i = 0
  6780. for (; i !== maxSize - 1; ) {
  6781. const item = values[i]
  6782. if (null != item) {
  6783. const [t, v] = item,
  6784. age = millis(now - t)
  6785. age.millis >= 0 && age <= maxAge && builder.push(v)
  6786. }
  6787. i += 1
  6788. }
  6789. return calculateQuantiles(
  6790. error,
  6791. sortedQuantiles,
  6792. Chunk_sort(Order)(Chunk_fromIterable(builder))
  6793. )
  6794. })(Date.now()),
  6795. count,
  6796. min,
  6797. max,
  6798. sum
  6799. ),
  6800. ([value, timestamp]) =>
  6801. ((value, timestamp) => {
  6802. if (maxSize > 0) {
  6803. head += 1
  6804. values[head % maxSize] = [timestamp, value]
  6805. }
  6806. count += 1
  6807. sum += value
  6808. value < min && (min = value)
  6809. value > max && (max = value)
  6810. })(value, timestamp)
  6811. )
  6812. })(key)
  6813. MutableHashMap_has(key)(this.map) ||
  6814. MutableHashMap_set(key, summary)(this.map)
  6815. value = summary
  6816. }
  6817. return value
  6818. }
  6819. }
  6820. registry_a = MetricRegistryTypeId
  6821. const MetricTypeId = Symbol.for("@effect/io/Metric"),
  6822. metricVariance = { _Type: _ => _, _In: _ => _, _Out: _ => _ },
  6823. globalMetricRegistry = globalValue(
  6824. Symbol.for("@effect/io/Metric/globalMetricRegistry"),
  6825. () => new MetricRegistryImpl()
  6826. ),
  6827. metric_counter = name =>
  6828. fromMetricKey((name => new MetricKeyImpl(name, counter))(name)),
  6829. fromMetricKey = key => {
  6830. const hook = extraTags => {
  6831. const fullKey = key_taggedWithLabelSet(extraTags)(key)
  6832. return globalMetricRegistry.get(fullKey)
  6833. }
  6834. return (function (keyType, unsafeUpdate, unsafeValue) {
  6835. const metric = Object.assign(
  6836. methodWithTrace(
  6837. (trace, restore) => effect =>
  6838. core_tap(effect, a =>
  6839. sync(() => restore(unsafeUpdate)(a, mjs_HashSet_empty()))
  6840. ).traced(trace)
  6841. ),
  6842. {
  6843. [MetricTypeId]: metricVariance,
  6844. keyType,
  6845. unsafeUpdate,
  6846. unsafeValue,
  6847. }
  6848. )
  6849. return metric
  6850. })(
  6851. key.keyType,
  6852. (input, extraTags) => hook(extraTags).update(input),
  6853. extraTags => hook(extraTags).get()
  6854. )
  6855. },
  6856. metric_histogram = (name, boundaries) =>
  6857. fromMetricKey(
  6858. ((name, boundaries) =>
  6859. new MetricKeyImpl(
  6860. name,
  6861. (boundaries => new HistogramKeyType(boundaries))(boundaries)
  6862. ))(name, boundaries)
  6863. )
  6864. var boundaries_a
  6865. const MetricBoundariesTypeId = Symbol.for("@effect/io/Metric/Boundaries")
  6866. class MetricBoundariesImpl {
  6867. constructor(values) {
  6868. this.values = values
  6869. this[boundaries_a] = MetricBoundariesTypeId
  6870. }
  6871. [((boundaries_a = MetricBoundariesTypeId), symbol)]() {
  6872. return combine(Hash_hash(this.values))(
  6873. Hash_hash("@effect/io/Metric/Boundaries")
  6874. )
  6875. }
  6876. [Equal_symbol](u) {
  6877. return isMetricBoundaries(u) && equals(this.values, u.values)
  6878. }
  6879. }
  6880. const isMetricBoundaries = u =>
  6881. "object" == typeof u && null != u && MetricBoundariesTypeId in u,
  6882. exponential = (start, factor, count) => {
  6883. return (chunk => {
  6884. const values = (self =>
  6885. unsafeFromArray(uniq_(toReadonlyArray(self))))(
  6886. Chunk_concat(Chunk_of(Number.POSITIVE_INFINITY))(chunk)
  6887. )
  6888. return new MetricBoundariesImpl(values)
  6889. })(
  6890. Chunk_map(i => start * Math.pow(factor, i))(
  6891. 0 <= (end = count - 1)
  6892. ? Chunk_makeBy(end - 0 + 1, i => 0 + i)
  6893. : Chunk_of(0)
  6894. )
  6895. )
  6896. var end
  6897. }
  6898. var supervisor_a, supervisor_b, supervisor_d
  6899. const SupervisorTypeId = Symbol.for("@effect/io/Supervisor"),
  6900. supervisorVariance = { _T: _ => _ }
  6901. class ProxySupervisor {
  6902. constructor(underlying, value0) {
  6903. this.underlying = underlying
  6904. this.value0 = value0
  6905. this[supervisor_a] = supervisorVariance
  6906. }
  6907. value() {
  6908. return bodyWithTrace(trace => this.value0().traced(trace))
  6909. }
  6910. onStart(context, effect, parent, fiber) {
  6911. this.underlying.onStart(context, effect, parent, fiber)
  6912. }
  6913. onEnd(value, fiber) {
  6914. this.underlying.onEnd(value, fiber)
  6915. }
  6916. onEffect(fiber, effect) {
  6917. this.underlying.onEffect(fiber, effect)
  6918. }
  6919. onSuspend(fiber) {
  6920. this.underlying.onSuspend(fiber)
  6921. }
  6922. onResume(fiber) {
  6923. this.underlying.onResume(fiber)
  6924. }
  6925. map(f) {
  6926. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  6927. }
  6928. zip(right) {
  6929. return new Zip(this, right)
  6930. }
  6931. }
  6932. supervisor_a = SupervisorTypeId
  6933. class Zip {
  6934. constructor(left, right) {
  6935. this.left = left
  6936. this.right = right
  6937. this[supervisor_b] = supervisorVariance
  6938. }
  6939. value() {
  6940. return bodyWithTrace(trace =>
  6941. core_zip(this.left.value(), this.right.value()).traced(trace)
  6942. )
  6943. }
  6944. onStart(context, effect, parent, fiber) {
  6945. this.left.onStart(context, effect, parent, fiber)
  6946. this.right.onStart(context, effect, parent, fiber)
  6947. }
  6948. onEnd(value, fiber) {
  6949. this.left.onEnd(value, fiber)
  6950. this.right.onEnd(value, fiber)
  6951. }
  6952. onEffect(fiber, effect) {
  6953. this.left.onEffect(fiber, effect)
  6954. this.right.onEffect(fiber, effect)
  6955. }
  6956. onSuspend(fiber) {
  6957. this.left.onSuspend(fiber)
  6958. this.right.onSuspend(fiber)
  6959. }
  6960. onResume(fiber) {
  6961. this.left.onResume(fiber)
  6962. this.right.onResume(fiber)
  6963. }
  6964. map(f) {
  6965. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  6966. }
  6967. zip(right) {
  6968. return new Zip(this, right)
  6969. }
  6970. }
  6971. supervisor_b = SupervisorTypeId
  6972. class Const {
  6973. constructor(effect) {
  6974. this.effect = effect
  6975. this[supervisor_d] = supervisorVariance
  6976. }
  6977. value() {
  6978. return bodyWithTrace(trace => this.effect.traced(trace))
  6979. }
  6980. onStart(_context, _effect, _parent, _fiber) {}
  6981. onEnd(_value, _fiber) {}
  6982. onEffect(_fiber, _effect) {}
  6983. onSuspend(_fiber) {}
  6984. onResume(_fiber) {}
  6985. map(f) {
  6986. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  6987. }
  6988. zip(right) {
  6989. return new Zip(this, right)
  6990. }
  6991. }
  6992. supervisor_d = SupervisorTypeId
  6993. const supervisor_none = (effect => new Const(effect))(core_unit()),
  6994. supervisor_patch_empty = { _tag: "Empty" },
  6995. supervisor_patch_combine = (self, that) => ({
  6996. _tag: "AndThen",
  6997. first: self,
  6998. second: that,
  6999. }),
  7000. removeSupervisor = (self, that) =>
  7001. equals(self, that)
  7002. ? supervisor_none
  7003. : self instanceof Zip
  7004. ? removeSupervisor(self.left, that).zip(
  7005. removeSupervisor(self.right, that)
  7006. )
  7007. : self,
  7008. patch_toSet = self =>
  7009. equals(self, supervisor_none)
  7010. ? mjs_HashSet_empty()
  7011. : self instanceof Zip
  7012. ? mjs_HashSet_union(patch_toSet(self.right))(patch_toSet(self.left))
  7013. : mjs_HashSet_make(self),
  7014. patch_differ = mjs_Differ_make({
  7015. empty: supervisor_patch_empty,
  7016. patch: (self, supervisor) =>
  7017. ((_supervisor, _patches) => {
  7018. let supervisor = _supervisor,
  7019. patches = _patches
  7020. for (; Chunk_isNonEmpty(patches); ) {
  7021. const head = Chunk_headNonEmpty(patches)
  7022. switch (head._tag) {
  7023. case "Empty":
  7024. patches = Chunk_tailNonEmpty(patches)
  7025. break
  7026. case "AddSupervisor":
  7027. supervisor = supervisor.zip(head.supervisor)
  7028. patches = Chunk_tailNonEmpty(patches)
  7029. break
  7030. case "RemoveSupervisor":
  7031. supervisor = removeSupervisor(supervisor, head.supervisor)
  7032. patches = Chunk_tailNonEmpty(patches)
  7033. break
  7034. case "AndThen":
  7035. patches = Chunk_prepend(head.first)(
  7036. Chunk_prepend(head.second)(Chunk_tailNonEmpty(patches))
  7037. )
  7038. }
  7039. }
  7040. return supervisor
  7041. })(supervisor, Chunk_of(self)),
  7042. combine: supervisor_patch_combine,
  7043. diff: (oldValue, newValue) => {
  7044. if (equals(oldValue, newValue)) return supervisor_patch_empty
  7045. const oldSupervisors = patch_toSet(oldValue),
  7046. newSupervisors = patch_toSet(newValue),
  7047. added = mjs_HashSet_reduce(
  7048. supervisor_patch_empty,
  7049. (patch, supervisor) =>
  7050. supervisor_patch_combine(patch, {
  7051. _tag: "AddSupervisor",
  7052. supervisor,
  7053. })
  7054. )(mjs_HashSet_difference(oldSupervisors)(newSupervisors)),
  7055. removed = mjs_HashSet_reduce(
  7056. supervisor_patch_empty,
  7057. (patch, supervisor) =>
  7058. supervisor_patch_combine(patch, {
  7059. _tag: "RemoveSupervisor",
  7060. supervisor,
  7061. })
  7062. )(mjs_HashSet_difference(newSupervisors)(oldSupervisors))
  7063. return supervisor_patch_combine(added, removed)
  7064. },
  7065. })
  7066. var fiberRuntime_a, fiberRuntime_b
  7067. const fibersStarted = metric_counter("effect_fiber_started"),
  7068. fiberSuccesses = metric_counter("effect_fiber_successes"),
  7069. fiberFailures = metric_counter("effect_fiber_failures"),
  7070. fiberLifetimes = metric_histogram(
  7071. "effect_fiber_lifetimes",
  7072. exponential(1, 2, 100)
  7073. ),
  7074. runtimeFiberVariance = { _E: _ => _, _A: _ => _ },
  7075. fiberRuntime_absurd = _ => {
  7076. throw new Error(
  7077. `BUG: FiberRuntime - ${JSON.stringify(
  7078. _
  7079. )} - please report an issue at https://github.com/Effect-TS/io/issues`
  7080. )
  7081. },
  7082. contOpSuccess = {
  7083. OnSuccess: (_, cont, value) => cont.i1(value),
  7084. OnSuccessAndFailure: (_, cont, value) => cont.i2(value),
  7085. RevertFlags: (self, cont, value) => {
  7086. self.patchRuntimeFlags(self._runtimeFlags, cont.patch)
  7087. return interruptible(self._runtimeFlags) && self.isInterrupted()
  7088. ? exitFailCause(self.getInterruptedCause())
  7089. : exitSucceed(value)
  7090. },
  7091. While: (self, cont, value) => {
  7092. cont.i2(value)
  7093. if (cont.i0()) {
  7094. self.pushStack(cont)
  7095. return cont.i1()
  7096. }
  7097. return core_unit()
  7098. },
  7099. },
  7100. drainQueueWhileRunningTable = {
  7101. InterruptSignal: (self, runtimeFlags, cur, message) => {
  7102. self.processNewInterruptSignal(message.cause)
  7103. return interruptible(runtimeFlags)
  7104. ? exitFailCause(message.cause)
  7105. : cur
  7106. },
  7107. Resume: (_self, _runtimeFlags, _cur, _message) => {
  7108. throw new Error(
  7109. "It is illegal to have multiple concurrent run loops in a single fiber"
  7110. )
  7111. },
  7112. Stateful: (self, runtimeFlags, cur, message) => {
  7113. message.onFiber(self, Status_running(runtimeFlags))
  7114. return cur
  7115. },
  7116. YieldNow: (_self, _runtimeFlags, cur, _message) =>
  7117. core_flatMap(() => cur)(yieldNow()),
  7118. }
  7119. class FiberRuntime {
  7120. constructor(fiberId, fiberRefs0, runtimeFlags0) {
  7121. this[fiberRuntime_a] = fiberVariance
  7122. this[fiberRuntime_b] = runtimeFiberVariance
  7123. this._queue = new MutableQueueImpl()
  7124. this._children = null
  7125. this._observers = new Array()
  7126. this._running = !1
  7127. this._stack = []
  7128. this._asyncInterruptor = null
  7129. this._asyncBlockingOn = null
  7130. this._exitValue = null
  7131. this._traceStack = []
  7132. this.run = () => {
  7133. this.drainQueueOnCurrentThread()
  7134. }
  7135. this._runtimeFlags = runtimeFlags0
  7136. this._fiberId = fiberId
  7137. this._fiberRefs = fiberRefs0
  7138. if (runtimeMetrics(runtimeFlags0)) {
  7139. const tags = this.getFiberRef(currentTags)
  7140. fibersStarted.unsafeUpdate(1, tags)
  7141. }
  7142. }
  7143. id() {
  7144. return this._fiberId
  7145. }
  7146. resume(effect) {
  7147. this.tell(resume(effect))
  7148. }
  7149. status() {
  7150. return this.ask((_, status) => status)
  7151. }
  7152. runtimeFlags() {
  7153. return this.ask((state, status) =>
  7154. (self => "Done" === self._tag)(status)
  7155. ? state._runtimeFlags
  7156. : status.runtimeFlags
  7157. )
  7158. }
  7159. scope() {
  7160. return new Local((fiber = this).id(), fiber)
  7161. var fiber
  7162. }
  7163. children() {
  7164. return this.ask(fiber => Chunk_fromIterable(fiber.getChildren()))
  7165. }
  7166. getChildren() {
  7167. null === this._children && (this._children = new Set())
  7168. return this._children
  7169. }
  7170. getSupervisor() {
  7171. return this.getFiberRef(currentSupervisor)
  7172. }
  7173. getInterruptedCause() {
  7174. return this.getFiberRef(interruptedCause)
  7175. }
  7176. fiberRefs() {
  7177. return this.ask(fiber => fiber.unsafeGetFiberRefs())
  7178. }
  7179. ask(f) {
  7180. return untraced(() =>
  7181. suspend(() => {
  7182. const deferred = deferredUnsafeMake(this._fiberId)
  7183. this.tell(
  7184. stateful((fiber, status) => {
  7185. deferredUnsafeDone(
  7186. deferred,
  7187. sync(() => f(fiber, status))
  7188. )
  7189. })
  7190. )
  7191. return deferredAwait(deferred)
  7192. })
  7193. )
  7194. }
  7195. tell(message) {
  7196. offer(message)(this._queue)
  7197. if (!this._running) {
  7198. this._running = !0
  7199. this.drainQueueLaterOnExecutor()
  7200. }
  7201. }
  7202. await() {
  7203. return untraced(() =>
  7204. asyncInterrupt(resume => {
  7205. const cb = exit => resume(succeed(exit))
  7206. this.tell(
  7207. stateful((fiber, _) => {
  7208. null !== fiber._exitValue
  7209. ? cb(this._exitValue)
  7210. : fiber.unsafeAddObserver(cb)
  7211. })
  7212. )
  7213. return sync(() =>
  7214. this.tell(
  7215. stateful((fiber, _) => {
  7216. fiber.unsafeRemoveObserver(cb)
  7217. })
  7218. )
  7219. )
  7220. }, this.id())
  7221. )
  7222. }
  7223. inheritAll() {
  7224. return untraced(() =>
  7225. withFiberRuntime((parentFiber, parentStatus) => {
  7226. const parentFiberId = parentFiber.id(),
  7227. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  7228. parentRuntimeFlags = parentStatus.runtimeFlags,
  7229. childFiberRefs = this.unsafeGetFiberRefs(),
  7230. updatedFiberRefs = joinAs(
  7231. parentFiberRefs,
  7232. parentFiberId,
  7233. childFiberRefs
  7234. )
  7235. parentFiber.setFiberRefs(updatedFiberRefs)
  7236. const updatedRuntimeFlags =
  7237. parentFiber.getFiberRef(currentRuntimeFlags),
  7238. patch = Patch_exclude(16)(
  7239. Patch_exclude(1)(
  7240. runtimeFlags_diff(parentRuntimeFlags, updatedRuntimeFlags)
  7241. )
  7242. )
  7243. return updateRuntimeFlags(patch)
  7244. })
  7245. )
  7246. }
  7247. poll() {
  7248. return untraced(() => sync(() => fromNullable(this._exitValue)))
  7249. }
  7250. unsafePoll() {
  7251. return this._exitValue
  7252. }
  7253. interruptAsFork(fiberId) {
  7254. return untraced(() =>
  7255. sync(() => this.tell(interruptSignal(interrupt(fiberId))))
  7256. )
  7257. }
  7258. unsafeAddObserver(observer) {
  7259. null !== this._exitValue
  7260. ? observer(this._exitValue)
  7261. : this._observers.push(observer)
  7262. }
  7263. unsafeRemoveObserver(observer) {
  7264. this._observers = this._observers.filter(o => o !== observer)
  7265. }
  7266. unsafeGetFiberRefs() {
  7267. this.setFiberRef(currentRuntimeFlags, this._runtimeFlags)
  7268. return this._fiberRefs
  7269. }
  7270. unsafeDeleteFiberRef(fiberRef) {
  7271. this._fiberRefs = delete_(this._fiberRefs, fiberRef)
  7272. }
  7273. getFiberRef(fiberRef) {
  7274. return getOrDefault(this._fiberRefs, fiberRef)
  7275. }
  7276. setFiberRef(fiberRef, value) {
  7277. this._fiberRefs = updatedAs(
  7278. this._fiberRefs,
  7279. this._fiberId,
  7280. fiberRef,
  7281. value
  7282. )
  7283. }
  7284. setFiberRefs(fiberRefs) {
  7285. this._fiberRefs = fiberRefs
  7286. }
  7287. addChild(child) {
  7288. this.getChildren().add(child)
  7289. }
  7290. removeChild(child) {
  7291. this.getChildren().delete(child)
  7292. }
  7293. drainQueueOnCurrentThread() {
  7294. let recurse = !0
  7295. for (; recurse; ) {
  7296. let evaluationSignal = "Continue"
  7297. const prev = globalThis[currentFiberURI]
  7298. globalThis[currentFiberURI] = this
  7299. try {
  7300. for (; "Continue" === evaluationSignal; )
  7301. evaluationSignal = MutableQueue_isEmpty(this._queue)
  7302. ? "Done"
  7303. : this.evaluateMessageWhileSuspended(
  7304. MutableQueue_poll(null)(this._queue)
  7305. )
  7306. } finally {
  7307. this._running = !1
  7308. globalThis[currentFiberURI] = prev
  7309. }
  7310. if (MutableQueue_isEmpty(this._queue) || this._running) recurse = !1
  7311. else {
  7312. this._running = !0
  7313. if ("Yield" === evaluationSignal) {
  7314. this.drainQueueLaterOnExecutor()
  7315. recurse = !1
  7316. } else recurse = !0
  7317. }
  7318. }
  7319. }
  7320. drainQueueLaterOnExecutor() {
  7321. this.getFiberRef(currentScheduler).scheduleTask(this.run)
  7322. }
  7323. drainQueueWhileRunning(runtimeFlags, cur0) {
  7324. let cur = cur0
  7325. for (; !MutableQueue_isEmpty(this._queue); ) {
  7326. const message = MutableQueue_poll(void 0)(this._queue)
  7327. cur = drainQueueWhileRunningTable[message._tag](
  7328. this,
  7329. runtimeFlags,
  7330. cur,
  7331. message
  7332. )
  7333. }
  7334. return cur
  7335. }
  7336. isInterrupted() {
  7337. return !(self =>
  7338. "Empty" === self._tag ||
  7339. cause_reduce(self, !0, (acc, cause) => {
  7340. switch (cause._tag) {
  7341. case "Empty":
  7342. return Option_some(acc)
  7343. case "Die":
  7344. case "Fail":
  7345. case "Interrupt":
  7346. return Option_some(!1)
  7347. default:
  7348. return Option_none()
  7349. }
  7350. }))(this.getFiberRef(interruptedCause))
  7351. }
  7352. addInterruptedCause(cause) {
  7353. const oldSC = this.getFiberRef(interruptedCause)
  7354. this.setFiberRef(interruptedCause, sequential(oldSC, cause))
  7355. }
  7356. processNewInterruptSignal(cause) {
  7357. this.addInterruptedCause(cause)
  7358. this.sendInterruptSignalToAllChildren()
  7359. }
  7360. sendInterruptSignalToAllChildren() {
  7361. if (null === this._children || 0 === this._children.size) return !1
  7362. let told = !1
  7363. for (const child of this._children) {
  7364. child.tell(interruptSignal(interrupt(this.id())))
  7365. told = !0
  7366. }
  7367. return told
  7368. }
  7369. interruptAllChildren() {
  7370. if (this.sendInterruptSignalToAllChildren()) {
  7371. const it = this._children.values()
  7372. this._children = null
  7373. let isDone = !1
  7374. const body = () => {
  7375. const next = it.next()
  7376. return next.done
  7377. ? sync(() => {
  7378. isDone = !0
  7379. })
  7380. : core_asUnit(next.value.await())
  7381. }
  7382. return whileLoop(
  7383. () => !isDone,
  7384. () => body(),
  7385. () => {}
  7386. )
  7387. }
  7388. return null
  7389. }
  7390. reportExitValue(exit) {
  7391. if (runtimeMetrics(this._runtimeFlags)) {
  7392. const tags = this.getFiberRef(currentTags)
  7393. switch (exit._tag) {
  7394. case "Success":
  7395. fiberSuccesses.unsafeUpdate(1, tags)
  7396. break
  7397. case "Failure":
  7398. fiberFailures.unsafeUpdate(1, tags)
  7399. }
  7400. }
  7401. if ("Failure" === exit._tag) {
  7402. const level = this.getFiberRef(unhandledErrorLogLevel)
  7403. isInterruptedOnly(exit.cause) ||
  7404. "Some" !== level._tag ||
  7405. this.log(
  7406. "Fiber terminated with a non handled error",
  7407. exit.cause,
  7408. level
  7409. )
  7410. }
  7411. }
  7412. setExitValue(exit) {
  7413. this._exitValue = exit
  7414. if (runtimeMetrics(this._runtimeFlags)) {
  7415. const tags = this.getFiberRef(currentTags),
  7416. startTimeMillis = this.id().startTimeMillis,
  7417. endTimeMillis = new Date().getTime()
  7418. fiberLifetimes.unsafeUpdate(
  7419. (endTimeMillis - startTimeMillis) / 1e3,
  7420. tags
  7421. )
  7422. }
  7423. this.reportExitValue(exit)
  7424. for (let i = this._observers.length - 1; i >= 0; i--)
  7425. this._observers[i](exit)
  7426. }
  7427. getLoggers() {
  7428. return this.getFiberRef(currentLoggers)
  7429. }
  7430. log(message, cause, overrideLogLevel) {
  7431. const logLevel = Option_isSome(overrideLogLevel)
  7432. ? overrideLogLevel.value
  7433. : this.getFiberRef(currentLogLevel),
  7434. spans = this.getFiberRef(currentLogSpan),
  7435. annotations = this.getFiberRef(currentLogAnnotations),
  7436. loggers = this.getLoggers(),
  7437. contextMap = this.unsafeGetFiberRefs()
  7438. mjs_HashSet_forEach(logger => {
  7439. logger.log(
  7440. this.id(),
  7441. logLevel,
  7442. message,
  7443. cause,
  7444. contextMap,
  7445. spans,
  7446. annotations
  7447. )
  7448. })(loggers)
  7449. }
  7450. evaluateMessageWhileSuspended(message) {
  7451. switch (message._tag) {
  7452. case "YieldNow":
  7453. return "Yield"
  7454. case "InterruptSignal":
  7455. this.processNewInterruptSignal(message.cause)
  7456. if (null !== this._asyncInterruptor) {
  7457. this._asyncInterruptor(exitFailCause(message.cause))
  7458. this._asyncInterruptor = null
  7459. }
  7460. return "Continue"
  7461. case "Resume":
  7462. this._asyncInterruptor = null
  7463. this._asyncBlockingOn = null
  7464. this.evaluateEffect(message.effect)
  7465. return "Continue"
  7466. case "Stateful":
  7467. message.onFiber(
  7468. this,
  7469. null !== this._exitValue
  7470. ? Status_done
  7471. : ((runtimeFlags = this._runtimeFlags),
  7472. (blockingOn = this._asyncBlockingOn),
  7473. new Suspended(runtimeFlags, blockingOn))
  7474. )
  7475. return "Continue"
  7476. default:
  7477. return fiberRuntime_absurd(message)
  7478. }
  7479. var runtimeFlags, blockingOn
  7480. }
  7481. evaluateEffect(effect0) {
  7482. this.getSupervisor().onResume(this)
  7483. try {
  7484. let effect =
  7485. interruptible(this._runtimeFlags) && this.isInterrupted()
  7486. ? exitFailCause(this.getInterruptedCause())
  7487. : effect0
  7488. for (; null !== effect; )
  7489. try {
  7490. const exit = this.runLoop(effect)
  7491. this._runtimeFlags = runtimeFlags_enable(16)(this._runtimeFlags)
  7492. const interruption = this.interruptAllChildren()
  7493. if (null !== interruption)
  7494. effect = untraced(() => core_flatMap(interruption, () => exit))
  7495. else {
  7496. MutableQueue_isEmpty(this._queue)
  7497. ? this.setExitValue(exit)
  7498. : this.tell(resume(exit))
  7499. effect = null
  7500. }
  7501. } catch (e) {
  7502. if (!isEffect(e)) throw e
  7503. if ("Yield" === e._tag)
  7504. if (cooperativeYielding(this._runtimeFlags)) {
  7505. this.tell({ _tag: "YieldNow" })
  7506. this.tell(resume(exitUnit()))
  7507. effect = null
  7508. } else effect = exitUnit()
  7509. else "Async" === e._tag && (effect = null)
  7510. }
  7511. } finally {
  7512. this.getSupervisor().onSuspend(this)
  7513. }
  7514. }
  7515. start(effect) {
  7516. if (this._running) this.tell(resume(effect))
  7517. else {
  7518. this._running = !0
  7519. const prev = globalThis[currentFiberURI]
  7520. globalThis[currentFiberURI] = this
  7521. try {
  7522. this.evaluateEffect(effect)
  7523. } finally {
  7524. this._running = !1
  7525. globalThis[currentFiberURI] = prev
  7526. MutableQueue_isEmpty(this._queue) ||
  7527. this.drainQueueLaterOnExecutor()
  7528. }
  7529. }
  7530. }
  7531. startFork(effect) {
  7532. this.tell(resume(effect))
  7533. }
  7534. patchRuntimeFlags(oldRuntimeFlags, patch) {
  7535. const newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, patch)
  7536. globalThis[currentFiberURI] = this
  7537. this._runtimeFlags = newRuntimeFlags
  7538. return newRuntimeFlags
  7539. }
  7540. initiateAsync(runtimeFlags, asyncRegister) {
  7541. let alreadyCalled = !1
  7542. const callback = effect => {
  7543. if (!alreadyCalled) {
  7544. alreadyCalled = !0
  7545. this.tell(resume(effect))
  7546. }
  7547. }
  7548. interruptible(runtimeFlags) && (this._asyncInterruptor = callback)
  7549. try {
  7550. asyncRegister(callback)
  7551. } catch (e) {
  7552. callback(failCause(die(e)))
  7553. }
  7554. }
  7555. pushStack(cont) {
  7556. this._stack.push(cont)
  7557. "trace" in cont && cont.trace && this._traceStack.push(cont.trace)
  7558. }
  7559. popStack() {
  7560. const item = this._stack.pop()
  7561. if (item) {
  7562. "trace" in item && item.trace && this._traceStack.pop()
  7563. return item
  7564. }
  7565. }
  7566. getNextSuccessCont() {
  7567. let frame = this.popStack()
  7568. for (; frame; ) {
  7569. if ("OnFailure" !== frame._tag && "Traced" !== frame._tag)
  7570. return frame
  7571. frame = this.popStack()
  7572. }
  7573. }
  7574. getNextFailCont() {
  7575. let frame = this.popStack()
  7576. for (; frame; ) {
  7577. if (
  7578. "OnSuccess" !== frame._tag &&
  7579. "While" !== frame._tag &&
  7580. "Traced" !== frame._tag
  7581. )
  7582. return frame
  7583. frame = this.popStack()
  7584. }
  7585. }
  7586. [((fiberRuntime_a = FiberTypeId),
  7587. (fiberRuntime_b = RuntimeFiberTypeId),
  7588. "Tag")](op) {
  7589. return core_map(fiberRefGet(currentContext), context =>
  7590. mjs_Context_unsafeGet(context, op)
  7591. )
  7592. }
  7593. Left(op) {
  7594. return exitFail(op.i0)
  7595. }
  7596. None(_) {
  7597. return exitFail(NoSuchElementException())
  7598. }
  7599. Right(op) {
  7600. return exitSucceed(op.i0)
  7601. }
  7602. Some(op) {
  7603. return exitSucceed(op.i0)
  7604. }
  7605. Sync(op) {
  7606. const value = op.i0(),
  7607. cont = this.getNextSuccessCont()
  7608. if (void 0 !== cont) {
  7609. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  7610. return contOpSuccess[cont._tag](this, cont, value)
  7611. }
  7612. throw exitSucceed(value)
  7613. }
  7614. Success(op) {
  7615. const oldCur = op,
  7616. cont = this.getNextSuccessCont()
  7617. if (void 0 !== cont) {
  7618. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  7619. return contOpSuccess[cont._tag](this, cont, oldCur.i0)
  7620. }
  7621. throw oldCur
  7622. }
  7623. Failure(op) {
  7624. let cause = op.i0
  7625. if (
  7626. (self => "Annotated" === self._tag)(cause) &&
  7627. isStackAnnotation(cause.annotation)
  7628. ) {
  7629. const stack = cause.annotation.stack,
  7630. currentStack = this.stackToLines()
  7631. cause = annotated(
  7632. cause.cause,
  7633. new StackAnnotation(
  7634. Chunk_take(runtimeDebug.traceStackLimit)(
  7635. dedupeAdjacent(
  7636. 0 === stack.length
  7637. ? currentStack
  7638. : 0 === currentStack.length ||
  7639. unsafeLast(stack) === unsafeLast(currentStack)
  7640. ? stack
  7641. : Chunk_concat(currentStack)(stack)
  7642. )
  7643. ),
  7644. cause.annotation.seq
  7645. )
  7646. )
  7647. } else
  7648. cause = annotated(
  7649. op.i0,
  7650. new StackAnnotation(
  7651. this.stackToLines(),
  7652. (self => getAndUpdate(self, n => n + 1))(globalErrorSeq)
  7653. )
  7654. )
  7655. const cont = this.getNextFailCont()
  7656. if (void 0 === cont) throw exitFailCause(cause)
  7657. switch (cont._tag) {
  7658. case "OnFailure":
  7659. case "OnSuccessAndFailure":
  7660. return interruptible(this._runtimeFlags) && this.isInterrupted()
  7661. ? exitFailCause(stripFailures(cause))
  7662. : cont.i1(cause)
  7663. case "RevertFlags":
  7664. this.patchRuntimeFlags(this._runtimeFlags, cont.patch)
  7665. return interruptible(this._runtimeFlags) && this.isInterrupted()
  7666. ? exitFailCause(sequential(cause, this.getInterruptedCause()))
  7667. : exitFailCause(cause)
  7668. default:
  7669. fiberRuntime_absurd(cont)
  7670. }
  7671. }
  7672. WithRuntime(op) {
  7673. return op.i0(this, Status_running(this._runtimeFlags))
  7674. }
  7675. UpdateRuntimeFlags(op) {
  7676. if (void 0 === op.i1) {
  7677. this.patchRuntimeFlags(this._runtimeFlags, op.i0)
  7678. return exitUnit()
  7679. }
  7680. {
  7681. const updateFlags = op.i0,
  7682. oldRuntimeFlags = this._runtimeFlags,
  7683. newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, updateFlags)
  7684. if (newRuntimeFlags === oldRuntimeFlags) return op.i1(oldRuntimeFlags)
  7685. if (interruptible(newRuntimeFlags) && this.isInterrupted())
  7686. return exitFailCause(this.getInterruptedCause())
  7687. {
  7688. this.patchRuntimeFlags(this._runtimeFlags, updateFlags)
  7689. const revertFlags = runtimeFlags_diff(
  7690. newRuntimeFlags,
  7691. oldRuntimeFlags
  7692. )
  7693. this.pushStack(new RevertFlags(revertFlags))
  7694. return op.i1(oldRuntimeFlags)
  7695. }
  7696. }
  7697. }
  7698. OnSuccess(op) {
  7699. this.pushStack(op)
  7700. return op.i0
  7701. }
  7702. Traced(op) {
  7703. this.pushStack(op)
  7704. return op.i0
  7705. }
  7706. OnFailure(op) {
  7707. this.pushStack(op)
  7708. return op.i0
  7709. }
  7710. OnSuccessAndFailure(op) {
  7711. this.pushStack(op)
  7712. return op.i0
  7713. }
  7714. Async(op) {
  7715. this._asyncBlockingOn = op.i1
  7716. this.initiateAsync(this._runtimeFlags, op.i0)
  7717. throw op
  7718. }
  7719. Yield(op) {
  7720. throw op
  7721. }
  7722. While(op) {
  7723. const check = op.i0,
  7724. body = op.i1
  7725. if (check()) {
  7726. this.pushStack(op)
  7727. return body()
  7728. }
  7729. return exitUnit()
  7730. }
  7731. Commit(op) {
  7732. return op.commit()
  7733. }
  7734. runLoop(effect0) {
  7735. let cur = effect0,
  7736. ops = 0
  7737. for (;;) {
  7738. opSupervision(this._runtimeFlags) &&
  7739. this.getSupervisor().onEffect(this, cur)
  7740. cur = this.drainQueueWhileRunning(this._runtimeFlags, cur)
  7741. ops += 1
  7742. if (ops >= 2048) {
  7743. ops = 0
  7744. const oldCur = cur
  7745. cur = core_flatMap(() => oldCur)(yieldNow())
  7746. }
  7747. try {
  7748. cur._tag in this || fiberRuntime_absurd(cur)
  7749. cur = this[cur._tag](cur)
  7750. } catch (e) {
  7751. if (isEffect(e)) {
  7752. if ("Yield" === e._tag || "Async" === e._tag) throw e
  7753. if ("Success" === e._tag || "Failure" === e._tag) return e
  7754. } else
  7755. cur = isEffectError(e)
  7756. ? exitFailCause(e.cause)
  7757. : isInterruptedException(e)
  7758. ? exitFailCause(sequential(die(e), interrupt(Id_none)))
  7759. : exitFailCause(die(e))
  7760. }
  7761. }
  7762. }
  7763. stackToLines() {
  7764. if (0 === this._traceStack.length) return Chunk_empty()
  7765. const lines = []
  7766. let current = this._traceStack.length - 1
  7767. for (; current >= 0 && lines.length < runtimeDebug.traceStackLimit; ) {
  7768. const value = this._traceStack[current]
  7769. lines.push(value)
  7770. current -= 1
  7771. }
  7772. return unsafeFromArray(lines)
  7773. }
  7774. }
  7775. const currentMinimumLogLevel = fiberRefUnsafeMake(
  7776. fromLiteral(runtimeDebug.minumumLogLevel)
  7777. ),
  7778. defaultLogger = makeLogger(
  7779. (fiberId, logLevel, message, cause, context, spans, annotations) => {
  7780. const formatted = stringLogger.log(
  7781. fiberId,
  7782. logLevel,
  7783. message,
  7784. cause,
  7785. context,
  7786. spans,
  7787. annotations
  7788. ),
  7789. filter = getOrDefault(context, currentMinimumLogLevel)
  7790. greaterThanEqual(filter)(logLevel) &&
  7791. globalThis.console.log(formatted)
  7792. }
  7793. ),
  7794. currentLoggers = fiberRefUnsafeMakeHashSet(
  7795. mjs_HashSet_make(defaultLogger)
  7796. ),
  7797. acquireRelease = dualWithTrace(
  7798. 2,
  7799. (trace, restore) => (acquire, release) =>
  7800. uninterruptible(
  7801. core_tap(acquire, a =>
  7802. addFinalizer(exit => restore(release)(a, exit))
  7803. )
  7804. ).traced(trace)
  7805. ),
  7806. addFinalizer = methodWithTrace(
  7807. (trace, restore) => finalizer =>
  7808. core_flatMap(context(), context =>
  7809. core_flatMap(scope(), scope =>
  7810. scopeAddFinalizerExit(scope, exit =>
  7811. core_asUnit(provideContext(context)(restore(finalizer)(exit)))
  7812. )
  7813. )
  7814. ).traced(trace)
  7815. ),
  7816. forEachPar = dualWithTrace(
  7817. 2,
  7818. (trace, restore) => (self, f) =>
  7819. fiberRefGetWith(currentParallelism, o =>
  7820. "None" === o._tag
  7821. ? forEachParUnbounded(self, restore(f))
  7822. : forEachParN(self, o.value, f)
  7823. ).traced(trace)
  7824. ),
  7825. forEachParUnbounded = (self, f) =>
  7826. suspend(() => {
  7827. const as = Array.from(self).map((v, i) => [v, i]),
  7828. array = new Array(as.length)
  7829. return core_zipRight(
  7830. forEachParUnboundedDiscard(as, ([a, i]) =>
  7831. core_flatMap(f(a), b => sync(() => (array[i] = b)))
  7832. ),
  7833. succeed(unsafeFromArray(array))
  7834. )
  7835. }),
  7836. forEachParUnboundedDiscard = (self, f) =>
  7837. suspend(() => {
  7838. const as = Array.from(self),
  7839. size = as.length
  7840. return 0 === size
  7841. ? core_unit()
  7842. : 1 === size
  7843. ? core_asUnit(f(as[0]))
  7844. : uninterruptibleMask(restore => {
  7845. const deferred = deferredUnsafeMake(Id_none)
  7846. let ref = 0
  7847. const process = transplant(graft =>
  7848. core_forEach(as, a =>
  7849. forkDaemon(
  7850. graft(
  7851. matchCauseEffect(
  7852. cause =>
  7853. core_zipRight(
  7854. deferredFail(deferred, void 0),
  7855. failCause(cause)
  7856. ),
  7857. () => {
  7858. ref + 1 === size
  7859. ? deferredUnsafeDone(deferred, core_unit())
  7860. : (ref += 1)
  7861. return core_unit()
  7862. }
  7863. )(restore(suspend(() => f(a))))
  7864. )
  7865. )
  7866. )
  7867. )
  7868. return core_flatMap(process, fibers =>
  7869. matchCauseEffect(
  7870. restore(deferredAwait(deferred)),
  7871. cause =>
  7872. core_flatMap(
  7873. forEachParUnbounded(fibers, interruptFiber),
  7874. exits => {
  7875. const exit = exitCollectAllPar(exits)
  7876. return "Some" === exit._tag &&
  7877. (self => "Failure" === self._tag)(exit.value)
  7878. ? failCause(
  7879. parallel(stripFailures(cause), exit.value.i0)
  7880. )
  7881. : failCause(stripFailures(cause))
  7882. }
  7883. ),
  7884. () => forEachDiscard(fibers, f => f.inheritAll())
  7885. )
  7886. )
  7887. })
  7888. }),
  7889. forEachParN = (self, n, f) =>
  7890. suspend(() => {
  7891. const as = Array.from(self).map((v, i) => [v, i]),
  7892. array = new Array(as.length)
  7893. return core_zipRight(
  7894. forEachParNDiscard(as, n, ([a, i]) =>
  7895. core_map(f(a), b => (array[i] = b))
  7896. ),
  7897. succeed(unsafeFromArray(array))
  7898. )
  7899. }),
  7900. forEachParNDiscard = (self, n, f) =>
  7901. suspend(() => {
  7902. const iterator = self[Symbol.iterator](),
  7903. worker = core_flatMap(
  7904. sync(() => iterator.next()),
  7905. next =>
  7906. next.done
  7907. ? core_unit()
  7908. : core_flatMap(core_asUnit(f(next.value)), () => worker)
  7909. ),
  7910. effects = []
  7911. for (let i = 0; i < n; i++) effects.push(worker)
  7912. return forEachParUnboundedDiscard(effects, Function_identity)
  7913. }),
  7914. forkDaemon = methodWithTrace(
  7915. trace => self => forkWithScopeOverride(self, globalScope).traced(trace)
  7916. ),
  7917. unsafeMakeChildFiber = (
  7918. effect,
  7919. parentFiber,
  7920. parentRuntimeFlags,
  7921. overrideScope = null
  7922. ) => {
  7923. const childId = Id_unsafeMake(),
  7924. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  7925. childFiberRefs = forkAs(parentFiberRefs, childId),
  7926. childFiber = new FiberRuntime(
  7927. childId,
  7928. childFiberRefs,
  7929. parentRuntimeFlags
  7930. ),
  7931. childContext = getOrDefault(childFiberRefs, currentContext),
  7932. supervisor = childFiber.getSupervisor()
  7933. supervisor.onStart(
  7934. childContext,
  7935. effect,
  7936. Option_some(parentFiber),
  7937. childFiber
  7938. )
  7939. childFiber.unsafeAddObserver(exit => supervisor.onEnd(exit, childFiber))
  7940. ;(null !== overrideScope
  7941. ? overrideScope
  7942. : getOrElse(() => parentFiber.scope())(
  7943. parentFiber.getFiberRef(forkScopeOverride)
  7944. )
  7945. ).add(parentRuntimeFlags, childFiber)
  7946. return childFiber
  7947. },
  7948. forkWithScopeOverride = (self, scopeOverride) =>
  7949. withFiberRuntime((parentFiber, parentStatus) =>
  7950. succeed(
  7951. ((
  7952. effect,
  7953. parentFiber,
  7954. parentRuntimeFlags,
  7955. overrideScope = null
  7956. ) => {
  7957. const childFiber = unsafeMakeChildFiber(
  7958. effect,
  7959. parentFiber,
  7960. parentRuntimeFlags,
  7961. overrideScope
  7962. )
  7963. childFiber.resume(effect)
  7964. return childFiber
  7965. })(self, parentFiber, parentStatus.runtimeFlags, scopeOverride)
  7966. )
  7967. ),
  7968. scope = methodWithTrace(trace => () => scopeTag.traced(trace)),
  7969. scopeWith = methodWithTrace(
  7970. (trace, restore) => f =>
  7971. core_flatMap(scopeTag, restore(f)).traced(trace)
  7972. ),
  7973. fiberRuntime_some = methodWithTrace(
  7974. trace => self =>
  7975. matchEffect(
  7976. self,
  7977. e => core_fail(Option_some(e)),
  7978. option => {
  7979. switch (option._tag) {
  7980. case "None":
  7981. return core_fail(Option_none())
  7982. case "Some":
  7983. return succeed(option.value)
  7984. }
  7985. }
  7986. ).traced(trace)
  7987. ),
  7988. scopeTag = Tag(),
  7989. scopeMake = methodWithTrace(
  7990. trace =>
  7991. (strategy = ExecutionStrategy_sequential) =>
  7992. core_map(releaseMapMake(), rm => ({
  7993. [ScopeTypeId]: ScopeTypeId,
  7994. [CloseableScopeTypeId]: CloseableScopeTypeId,
  7995. fork: strategy =>
  7996. bodyWithTrace(trace =>
  7997. uninterruptible(
  7998. core_flatMap(scope =>
  7999. core_as(scope)(
  8000. core_tap(fin => scopeAddFinalizerExit(scope, fin))(
  8001. releaseMapAdd(exit => scopeClose(scope, exit))(rm)
  8002. )
  8003. )
  8004. )(scopeMake(strategy))
  8005. ).traced(trace)
  8006. ),
  8007. close: exit =>
  8008. bodyWithTrace(trace =>
  8009. core_asUnit(
  8010. (
  8011. (strategy, exit) => self =>
  8012. suspend(() => {
  8013. switch (self.state._tag) {
  8014. case "Exited":
  8015. return core_unit()
  8016. case "Running": {
  8017. const finalizersMap = self.state.finalizers,
  8018. update = self.state.update,
  8019. finalizers = Array.from(finalizersMap.keys())
  8020. .sort((a, b) => b - a)
  8021. .map(key => finalizersMap.get(key))
  8022. self.state = {
  8023. _tag: "Exited",
  8024. nextKey: self.state.nextKey,
  8025. exit,
  8026. update,
  8027. }
  8028. return (self => "Sequential" === self._tag)(
  8029. strategy
  8030. )
  8031. ? core_flatMap(results =>
  8032. getOrElse(() => exitUnit())(
  8033. Option_map(exitAsUnit)(
  8034. exitCollectAllInternal(
  8035. results,
  8036. sequential
  8037. )
  8038. )
  8039. )
  8040. )(
  8041. core_forEach(fin =>
  8042. core_exit(update(fin)(exit))
  8043. )(finalizers)
  8044. )
  8045. : (self => "Parallel" === self._tag)(strategy)
  8046. ? core_flatMap(results =>
  8047. getOrElse(() => exitUnit())(
  8048. Option_map(exitAsUnit)(
  8049. exitCollectAllPar(results)
  8050. )
  8051. )
  8052. )(
  8053. forEachPar(fin =>
  8054. core_exit(update(fin)(exit))
  8055. )(finalizers)
  8056. )
  8057. : withParallelism(strategy.parallelism)(
  8058. core_flatMap(results =>
  8059. getOrElse(() => exitUnit())(
  8060. Option_map(exitAsUnit)(
  8061. exitCollectAllPar(results)
  8062. )
  8063. )
  8064. )(
  8065. forEachPar(fin =>
  8066. core_exit(update(fin)(exit))
  8067. )(finalizers)
  8068. )
  8069. )
  8070. }
  8071. }
  8072. })
  8073. )(
  8074. strategy,
  8075. exit
  8076. )(rm)
  8077. ).traced(trace)
  8078. ),
  8079. addFinalizer: fin =>
  8080. bodyWithTrace(trace =>
  8081. core_asUnit(releaseMapAdd(fin)(rm)).traced(trace)
  8082. ),
  8083. })).traced(trace)
  8084. ),
  8085. scopeExtend = dualWithTrace(
  8086. 2,
  8087. trace => (effect, scope) =>
  8088. contramapContext(
  8089. effect,
  8090. mjs_Context_merge(mjs_Context_make(scopeTag, scope))
  8091. ).traced(trace)
  8092. ),
  8093. fiberRefUnsafeMakeSupervisor = initial =>
  8094. fiberRefUnsafeMakePatch(initial, patch_differ, supervisor_patch_empty),
  8095. fiberRefLocallyScoped = dualWithTrace(
  8096. 2,
  8097. trace => (self, value) =>
  8098. core_asUnit(
  8099. acquireRelease(
  8100. core_flatMap(oldValue =>
  8101. core_as(oldValue)(fiberRefSet(self, value))
  8102. )(fiberRefGet(self)),
  8103. oldValue => fiberRefSet(self, oldValue)
  8104. )
  8105. ).traced(trace)
  8106. ),
  8107. fiberRefLocallyScopedWith = dualWithTrace(
  8108. 2,
  8109. (trace, restore) => (self, f) =>
  8110. fiberRefGetWith(self, a =>
  8111. fiberRefLocallyScoped(self, restore(f)(a))
  8112. ).traced(trace)
  8113. ),
  8114. currentRuntimeFlags = fiberRefUnsafeMakeRuntimeFlags(runtimeFlags_none),
  8115. currentSupervisor = fiberRefUnsafeMakeSupervisor(supervisor_none),
  8116. fiberInterruptFork = methodWithTrace(
  8117. trace => self =>
  8118. core_asUnit(forkDaemon(interruptFiber(self))).traced(trace)
  8119. ),
  8120. IntervalTypeId = Symbol.for("@effect/io/Schedule/Interval"),
  8121. interval_empty = {
  8122. [IntervalTypeId]: IntervalTypeId,
  8123. startMillis: 0,
  8124. endMillis: 0,
  8125. },
  8126. Interval_empty = interval_empty,
  8127. Interval_after = startMilliseconds => {
  8128. return (
  8129. (startMillis = startMilliseconds),
  8130. (endMillis = Number.POSITIVE_INFINITY),
  8131. startMillis > endMillis
  8132. ? interval_empty
  8133. : { [IntervalTypeId]: IntervalTypeId, startMillis, endMillis }
  8134. )
  8135. var startMillis, endMillis
  8136. },
  8137. IntervalsTypeId = Symbol.for("@effect/io/Schedule/Intervals"),
  8138. Intervals_make = intervals => ({
  8139. [IntervalsTypeId]: IntervalsTypeId,
  8140. intervals,
  8141. }),
  8142. Intervals_start = self =>
  8143. getOrElse(() => Interval_empty)(Chunk_head(self.intervals)).startMillis,
  8144. Decision_continueWith = interval => ({
  8145. _tag: "Continue",
  8146. intervals: Intervals_make(Chunk_of(interval)),
  8147. })
  8148. var schedule_a, schedule_b
  8149. const ScheduleTypeId = Symbol.for("@effect/io/Schedule"),
  8150. ScheduleDriverTypeId = Symbol.for("@effect/io/Schedule/Driver"),
  8151. scheduleVariance = { _Env: _ => _, _In: _ => _, _Out: _ => _ },
  8152. scheduleDriverVariance = { _Env: _ => _, _In: _ => _, _Out: _ => _ }
  8153. class ScheduleImpl {
  8154. constructor(initial, step) {
  8155. this.initial = initial
  8156. this.step = step
  8157. this[schedule_a] = scheduleVariance
  8158. }
  8159. }
  8160. schedule_a = ScheduleTypeId
  8161. class ScheduleDriverImpl {
  8162. constructor(schedule, ref) {
  8163. this.schedule = schedule
  8164. this.ref = ref
  8165. this[schedule_b] = scheduleDriverVariance
  8166. }
  8167. state() {
  8168. return bodyWithTrace(trace =>
  8169. core_map(Ref_get(this.ref), tuple => tuple[1]).traced(trace)
  8170. )
  8171. }
  8172. last() {
  8173. return bodyWithTrace(trace =>
  8174. core_flatMap(Ref_get(this.ref), ([element, _]) => {
  8175. switch (element._tag) {
  8176. case "None":
  8177. return failSync(() => NoSuchElementException())
  8178. case "Some":
  8179. return succeed(element.value)
  8180. }
  8181. }).traced(trace)
  8182. )
  8183. }
  8184. reset() {
  8185. return bodyWithTrace(trace =>
  8186. Ref_set(this.ref, [Option_none(), this.schedule.initial]).traced(
  8187. trace
  8188. )
  8189. )
  8190. }
  8191. next(input) {
  8192. return bodyWithTrace((trace, restore) =>
  8193. core_flatMap(state =>
  8194. core_flatMap(now =>
  8195. core_flatMap(([state, out, decision]) =>
  8196. (self => "Done" === self._tag)(decision)
  8197. ? core_zipRight(core_fail(Option_none()))(
  8198. Ref_set(this.ref, [Option_some(out), state])
  8199. )
  8200. : core_as(out)(
  8201. core_zipRight(
  8202. effect_sleep(
  8203. millis(Intervals_start(decision.intervals) - now)
  8204. )
  8205. )(Ref_set(this.ref, [Option_some(out), state]))
  8206. )
  8207. )(suspend(restore(() => this.schedule.step(now, input, state))))
  8208. )(Clock_currentTimeMillis())
  8209. )(core_map(Ref_get(this.ref), tuple => tuple[1])).traced(trace)
  8210. )
  8211. }
  8212. }
  8213. schedule_b = ScheduleDriverTypeId
  8214. const makeWithState = untracedMethod(
  8215. restore => (initial, step) => new ScheduleImpl(initial, restore(step))
  8216. ),
  8217. driver = methodWithTrace(
  8218. trace => self =>
  8219. core_map(ref => new ScheduleDriverImpl(self, ref))(
  8220. Ref_make([Option_none(), self.initial])
  8221. ).traced(trace)
  8222. ),
  8223. fixed = untracedMethod(
  8224. () => interval =>
  8225. makeWithState([Option_none(), 0], (now, _, [option, n]) =>
  8226. sync(() => {
  8227. const intervalMillis = interval.millis
  8228. switch (option._tag) {
  8229. case "None":
  8230. return [
  8231. [Option_some([now, now + intervalMillis]), n + 1],
  8232. n,
  8233. Decision_continueWith(Interval_after(now + intervalMillis)),
  8234. ]
  8235. case "Some": {
  8236. const [startMillis, lastRun] = option.value,
  8237. runningBehind = now > lastRun + intervalMillis,
  8238. boundary = equals(interval, zero)
  8239. ? interval
  8240. : millis(
  8241. intervalMillis -
  8242. ((now - startMillis) % intervalMillis)
  8243. ),
  8244. sleepTime = equals(boundary, zero) ? interval : boundary,
  8245. nextRun = runningBehind ? now : now + sleepTime.millis
  8246. return [
  8247. [Option_some([startMillis, nextRun]), n + 1],
  8248. n,
  8249. Decision_continueWith(Interval_after(nextRun)),
  8250. ]
  8251. }
  8252. }
  8253. })
  8254. )
  8255. ),
  8256. repeat_Effect = dualWithTrace(
  8257. 2,
  8258. trace => (self, schedule) =>
  8259. repeatOrElse_Effect(self, schedule, (e, _) => core_fail(e)).traced(
  8260. trace
  8261. )
  8262. ),
  8263. repeatOrElse_Effect = dualWithTrace(
  8264. 3,
  8265. (trace, restore) => (self, schedule, orElse) =>
  8266. core_map(
  8267. repeatOrElseEither_Effect(self, schedule, restore(orElse)),
  8268. merge
  8269. ).traced(trace)
  8270. ),
  8271. repeatOrElseEither_Effect = dualWithTrace(
  8272. 3,
  8273. (trace, restore) => (self, schedule, orElse) =>
  8274. core_flatMap(driver(schedule), driver =>
  8275. matchEffect(
  8276. self,
  8277. error =>
  8278. core_map(Either_left)(restore(orElse)(error, Option_none())),
  8279. value =>
  8280. repeatOrElseEitherEffectLoop(
  8281. self,
  8282. driver,
  8283. restore(orElse),
  8284. value
  8285. )
  8286. )
  8287. ).traced(trace)
  8288. ),
  8289. repeatOrElseEitherEffectLoop = (self, driver, orElse, value) =>
  8290. matchEffect(
  8291. () => core_map(Either_right)(orDie(driver.last())),
  8292. b =>
  8293. matchEffect(
  8294. error => core_map(Either_left)(orElse(error, Option_some(b))),
  8295. value => repeatOrElseEitherEffectLoop(self, driver, orElse, value)
  8296. )(self)
  8297. )(driver.next(value))
  8298. var circular_b, circular_c
  8299. class Semaphore {
  8300. constructor(permits) {
  8301. this.permits = permits
  8302. this.waiters = new Array()
  8303. this.taken = 0
  8304. this.take = n =>
  8305. bodyWithTrace(trace =>
  8306. asyncInterruptEither(resume => {
  8307. if (this.free < n) {
  8308. const observer = () => {
  8309. if (this.free >= n) {
  8310. const observerIndex = this.waiters.findIndex(
  8311. cb => cb === observer
  8312. )
  8313. ;-1 !== observerIndex &&
  8314. this.waiters.splice(observerIndex, 1)
  8315. this.taken += n
  8316. resume(succeed(n))
  8317. }
  8318. }
  8319. this.waiters.push(observer)
  8320. return Either_left(
  8321. sync(() => {
  8322. const observerIndex = this.waiters.findIndex(
  8323. cb => cb === observer
  8324. )
  8325. ;-1 !== observerIndex &&
  8326. this.waiters.splice(observerIndex, 1)
  8327. })
  8328. )
  8329. }
  8330. this.taken += n
  8331. return Either_right(succeed(n))
  8332. }).traced(trace)
  8333. )
  8334. this.release = n =>
  8335. bodyWithTrace(trace =>
  8336. withFiberRuntime(fiber => {
  8337. this.taken -= n
  8338. fiber.getFiberRef(currentScheduler).scheduleTask(() => {
  8339. this.waiters.forEach(wake => wake())
  8340. })
  8341. return core_unit()
  8342. }).traced(trace)
  8343. )
  8344. this.withPermits = n =>
  8345. bodyWithTrace(
  8346. trace => self =>
  8347. untraced(() =>
  8348. uninterruptibleMask(restore =>
  8349. core_flatMap(restore(this.take(n)), permits =>
  8350. circular_ensuring(restore(self), this.release(permits))
  8351. )
  8352. )
  8353. ).traced(trace)
  8354. )
  8355. }
  8356. get free() {
  8357. return this.permits - this.taken
  8358. }
  8359. }
  8360. const circular_ensuring = dualWithTrace(
  8361. 2,
  8362. trace => (self, finalizer) =>
  8363. uninterruptibleMask(restore =>
  8364. matchCauseEffect(
  8365. restore(self),
  8366. cause1 =>
  8367. matchCauseEffect(
  8368. finalizer,
  8369. cause2 => failCause(sequential(cause1, cause2)),
  8370. () => failCause(cause1)
  8371. ),
  8372. a => core_as(finalizer, a)
  8373. )
  8374. ).traced(trace)
  8375. )
  8376. const zipWithPar = dualWithTrace(
  8377. 3,
  8378. (trace, restoreTrace) => (self, that, f) =>
  8379. uninterruptibleMask(restore =>
  8380. transplant(graft => {
  8381. const deferred = deferredUnsafeMake(Id_none),
  8382. ref = MutableRef_make(!1)
  8383. return core_flatMap(([left, right]) =>
  8384. matchCauseEffect(
  8385. cause =>
  8386. core_zipRight(
  8387. core_flatMap(([left, right]) =>
  8388. exitMatch(
  8389. causes =>
  8390. failCause(parallel(stripFailures(cause), causes)),
  8391. () => failCause(stripFailures(cause))
  8392. )(exitZipWith(right, f, parallel)(left))
  8393. )(core_zip(_await(right))(_await(left)))
  8394. )(
  8395. core_zipRight(fiberInterruptFork(right))(
  8396. fiberInterruptFork(left)
  8397. )
  8398. ),
  8399. () =>
  8400. core_zipWith(
  8401. fiber_join(left),
  8402. fiber_join(right),
  8403. restoreTrace(f)
  8404. )
  8405. )(restore(deferredAwait(deferred)))
  8406. )(
  8407. core_zip(forkZipWithPar(that, graft, restore, deferred, ref))(
  8408. forkZipWithPar(self, graft, restore, deferred, ref)
  8409. )
  8410. )
  8411. })
  8412. ).traced(trace)
  8413. ),
  8414. forkZipWithPar = (self, graft, restore, deferred, ref) =>
  8415. forkDaemon(
  8416. matchCauseEffect(
  8417. graft(restore(self)),
  8418. cause =>
  8419. core_zipRight(deferredFail(deferred, void 0), failCause(cause)),
  8420. value => {
  8421. if (MutableRef_get(ref)) {
  8422. deferredUnsafeDone(deferred, core_unit())
  8423. return succeed(value)
  8424. }
  8425. MutableRef_set(!0)(ref)
  8426. return succeed(value)
  8427. }
  8428. )
  8429. ),
  8430. SynchronizedTypeId = Symbol.for("@effect/io/Ref/Synchronized"),
  8431. synchronizedVariance = { _A: _ => _ }
  8432. class SynchronizedImpl {
  8433. constructor(ref, withLock) {
  8434. this.ref = ref
  8435. this.withLock = withLock
  8436. this[circular_b] = synchronizedVariance
  8437. this[circular_c] = refVariance
  8438. }
  8439. modify(f) {
  8440. return bodyWithTrace((trace, restore) =>
  8441. this.modifyEffect(a => succeed(restore(f)(a))).traced(trace)
  8442. )
  8443. }
  8444. modifyEffect(f) {
  8445. return bodyWithTrace((trace, restore) =>
  8446. this.withLock(
  8447. core_flatMap(([b, a]) => core_as(ref_set(this.ref, a), b))(
  8448. core_flatMap(ref_get(this.ref), restore(f))
  8449. )
  8450. ).traced(trace)
  8451. )
  8452. }
  8453. }
  8454. ;(circular_b = SynchronizedTypeId), (circular_c = RefTypeId)
  8455. const makeSynchronized = methodWithTrace(
  8456. trace => value =>
  8457. sync(() => unsafeMakeSynchronized(value)).traced(trace)
  8458. ),
  8459. unsafeMakeSynchronized = value => {
  8460. const ref = ref_unsafeMake(value),
  8461. sem = new Semaphore(1)
  8462. return new SynchronizedImpl(ref, sem.withPermits(1))
  8463. },
  8464. Cause_fail = fail,
  8465. Cause_failureOrCause = failureOrCause,
  8466. Cause_pretty = cause_pretty_pretty,
  8467. modifyEffect = dualWithTrace(
  8468. 2,
  8469. (trace, restore) => (self, f) =>
  8470. self.modifyEffect(restore(f)).traced(trace)
  8471. ),
  8472. layer_proto = {
  8473. [Symbol.for("@effect/io/Layer")]: {
  8474. _RIn: _ => _,
  8475. _E: _ => _,
  8476. _ROut: _ => _,
  8477. },
  8478. },
  8479. isFresh = self => "Fresh" === self._tag
  8480. class MemoMap {
  8481. constructor(ref) {
  8482. this.ref = ref
  8483. }
  8484. getOrElseMemoize(layer, scope) {
  8485. return core_flatten(
  8486. modifyEffect(this.ref, map => {
  8487. const inMap = map.get(layer)
  8488. if (void 0 !== inMap) {
  8489. const [acquire, release] = inMap,
  8490. cached = onExit(
  8491. exitMatch(
  8492. () => core_unit(),
  8493. () => scopeAddFinalizerExit(scope, release)
  8494. )
  8495. )(
  8496. core_flatMap(([patch, b]) =>
  8497. core_as(b)(patchFiberRefs(patch))
  8498. )(acquire)
  8499. )
  8500. return succeed([cached, map])
  8501. }
  8502. return core_flatMap(observers =>
  8503. core_flatMap(deferred =>
  8504. core_map(finalizerRef => {
  8505. const resource = uninterruptibleMask(restore =>
  8506. core_flatMap(innerScope =>
  8507. core_flatMap(exit => {
  8508. switch (exit._tag) {
  8509. case "Failure":
  8510. return core_zipRight(failCause(exit.i0))(
  8511. core_zipRight(scopeClose(innerScope, exit))(
  8512. deferredFailCause(deferred, exit.i0)
  8513. )
  8514. )
  8515. case "Success":
  8516. return core_as(exit.i0[1])(
  8517. core_zipRight(
  8518. deferredSucceed(deferred, exit.i0)
  8519. )(
  8520. core_zipRight(
  8521. scopeAddFinalizerExit(scope, exit =>
  8522. core_flatMap(finalizer =>
  8523. finalizer(exit)
  8524. )(ref_get(finalizerRef))
  8525. )
  8526. )(
  8527. core_zipRight(
  8528. ref_update(observers, n => n + 1)
  8529. )(
  8530. ref_set(finalizerRef, exit =>
  8531. core_asUnit(
  8532. whenEffect(
  8533. ref_modify(observers, n => [
  8534. 1 === n,
  8535. n - 1,
  8536. ])
  8537. )(scopeClose(innerScope, exit))
  8538. )
  8539. )
  8540. )
  8541. )
  8542. )
  8543. )
  8544. }
  8545. })(
  8546. core_exit(
  8547. restore(
  8548. core_flatMap(withScope(layer, innerScope), f =>
  8549. diffFiberRefs(f(this))
  8550. )
  8551. )
  8552. )
  8553. )
  8554. )(scopeMake())
  8555. ),
  8556. memoized = [
  8557. onExit(
  8558. exitMatchEffect(
  8559. () => core_unit(),
  8560. () => ref_update(observers, n => n + 1)
  8561. )
  8562. )(deferredAwait(deferred)),
  8563. exit =>
  8564. core_flatMap(finalizer => finalizer(exit))(
  8565. ref_get(finalizerRef)
  8566. ),
  8567. ]
  8568. return [
  8569. resource,
  8570. isFresh(layer) ? map : map.set(layer, memoized),
  8571. ]
  8572. })(ref_make(() => core_unit()))
  8573. )(deferredMake())
  8574. )(ref_make(0))
  8575. })
  8576. )
  8577. }
  8578. }
  8579. const buildWithScope = dualWithTrace(
  8580. 2,
  8581. trace => (self, scope) =>
  8582. core_flatMap(
  8583. core_map(ref => new MemoMap(ref))(makeSynchronized(new Map())),
  8584. memoMap => core_flatMap(withScope(self, scope), run => run(memoMap))
  8585. ).traced(trace)
  8586. ),
  8587. withScope = (self, scope) => {
  8588. const op = self
  8589. switch (op._tag) {
  8590. case "ExtendScope":
  8591. return sync(
  8592. () => memoMap =>
  8593. scopeWith(scope => memoMap.getOrElseMemoize(op.layer, scope))
  8594. )
  8595. case "Fold":
  8596. return sync(
  8597. () => memoMap =>
  8598. matchCauseEffect(
  8599. cause => memoMap.getOrElseMemoize(op.failureK(cause), scope),
  8600. value => memoMap.getOrElseMemoize(op.successK(value), scope)
  8601. )(memoMap.getOrElseMemoize(op.layer, scope))
  8602. )
  8603. case "Fresh":
  8604. return sync(() => _ => buildWithScope(scope)(op.layer))
  8605. case "FromEffect":
  8606. return sync(() => _ => op.effect)
  8607. case "ProvideTo":
  8608. return sync(
  8609. () => memoMap =>
  8610. core_flatMap(env =>
  8611. provideContext(env)(
  8612. memoMap.getOrElseMemoize(op.second, scope)
  8613. )
  8614. )(memoMap.getOrElseMemoize(op.first, scope))
  8615. )
  8616. case "Scoped":
  8617. return sync(() => _ => scopeExtend(op.effect, scope))
  8618. case "Suspend":
  8619. return sync(
  8620. () => memoMap => memoMap.getOrElseMemoize(op.evaluate(), scope)
  8621. )
  8622. case "ZipWith":
  8623. return sync(
  8624. () => memoMap =>
  8625. core_zipWith(
  8626. memoMap.getOrElseMemoize(op.second, scope),
  8627. op.zipK
  8628. )(memoMap.getOrElseMemoize(op.first, scope))
  8629. )
  8630. case "ZipWithPar":
  8631. return sync(
  8632. () => memoMap =>
  8633. zipWithPar(
  8634. memoMap.getOrElseMemoize(op.second, scope),
  8635. op.zipK
  8636. )(memoMap.getOrElseMemoize(op.first, scope))
  8637. )
  8638. }
  8639. },
  8640. layer_fail = error => layer_failCause(Cause_fail(error)),
  8641. layer_failCause = cause => fromEffectContext(failCause(cause)),
  8642. layer_flatMap = untracedDual(
  8643. 2,
  8644. restore => (self, f) => matchLayer(self, layer_fail, restore(f))
  8645. )
  8646. function fromEffectContext(effect) {
  8647. const fromEffect = Object.create(layer_proto)
  8648. fromEffect._tag = "FromEffect"
  8649. fromEffect.effect = effect
  8650. return fromEffect
  8651. }
  8652. const matchCauseLayer = untracedDual(
  8653. 3,
  8654. restore => (self, onFailure, onSuccess) => {
  8655. const fold = Object.create(layer_proto)
  8656. fold._tag = "Fold"
  8657. fold.layer = self
  8658. fold.failureK = restore(onFailure)
  8659. fold.successK = restore(onSuccess)
  8660. return fold
  8661. }
  8662. ),
  8663. matchLayer = untracedDual(
  8664. 3,
  8665. restore => (self, onFailure, onSuccess) =>
  8666. matchCauseLayer(
  8667. self,
  8668. cause => {
  8669. const failureOrCause = Cause_failureOrCause(cause)
  8670. switch (failureOrCause._tag) {
  8671. case "Left":
  8672. return restore(onFailure)(failureOrCause.left)
  8673. case "Right":
  8674. return layer_failCause(failureOrCause.right)
  8675. }
  8676. },
  8677. restore(onSuccess)
  8678. )
  8679. ),
  8680. layer_merge = Function_dual(2, (self, that) =>
  8681. layer_zipWithPar(self, that, (a, b) => mjs_Context_merge(b)(a))
  8682. ),
  8683. scopedDiscard = effect =>
  8684. scopedContext(core_as(mjs_Context_empty())(effect)),
  8685. scopedContext = effect => {
  8686. const scoped = Object.create(layer_proto)
  8687. scoped._tag = "Scoped"
  8688. scoped.effect = effect
  8689. return scoped
  8690. },
  8691. layer_zipWithPar = untracedDual(
  8692. 3,
  8693. restore => (self, that, f) =>
  8694. (evaluate => {
  8695. const suspend = Object.create(layer_proto)
  8696. suspend._tag = "Suspend"
  8697. suspend.evaluate = evaluate
  8698. return suspend
  8699. })(() => {
  8700. const zipWithPar = Object.create(layer_proto)
  8701. zipWithPar._tag = "ZipWithPar"
  8702. zipWithPar.first = self
  8703. zipWithPar.second = that
  8704. zipWithPar.zipK = restore(f)
  8705. return zipWithPar
  8706. })
  8707. ),
  8708. provideLayer = dualWithTrace(
  8709. 2,
  8710. trace => (self, layer) =>
  8711. acquireUseRelease(
  8712. scopeMake(),
  8713. scope =>
  8714. core_flatMap(buildWithScope(layer, scope), context =>
  8715. provideContext(self, context)
  8716. ),
  8717. (scope, exit) => scopeClose(scope, exit)
  8718. ).traced(trace)
  8719. ),
  8720. provideSomeLayer = dualWithTrace(
  8721. 2,
  8722. trace => (self, layer) =>
  8723. provideLayer(
  8724. self,
  8725. layer_merge(layer)(fromEffectContext(context()))
  8726. ).traced(trace)
  8727. ),
  8728. withMinimumLogLevel = dualWithTrace(
  8729. 2,
  8730. trace => (self, level) =>
  8731. fiberRefLocally(currentMinimumLogLevel, level)(self).traced(trace)
  8732. ),
  8733. addLogger = methodWithTrace(
  8734. trace => logger =>
  8735. scopedDiscard(
  8736. fiberRefLocallyScopedWith(
  8737. currentLoggers,
  8738. mjs_HashSet_add(logger)
  8739. ).traced(trace)
  8740. )
  8741. ),
  8742. removeLogger = untracedMethod(
  8743. () => logger =>
  8744. scopedDiscard(
  8745. fiberRefLocallyScopedWith(
  8746. currentLoggers,
  8747. mjs_HashSet_remove(logger)
  8748. )
  8749. )
  8750. ),
  8751. replaceLogger = Function_dual(2, (self, that) =>
  8752. layer_flatMap(removeLogger(self), () => addLogger(that))
  8753. )
  8754. class AsyncFiber {
  8755. constructor(fiber) {
  8756. this.fiber = fiber
  8757. this._tag = "AsyncFiber"
  8758. }
  8759. toString() {
  8760. return `Fiber #${this.fiber.id().id} has suspended work asyncroniously`
  8761. }
  8762. [Symbol.for("nodejs.util.inspect.custom")]() {
  8763. return this.toString()
  8764. }
  8765. }
  8766. const FiberFailureId = Symbol.for("@effect/io/Runtime/FiberFailure"),
  8767. FiberFailureCauseId = Symbol.for("@effect/io/Runtime/FiberFailure/Cause"),
  8768. NodePrint = Symbol.for("nodejs.util.inspect.custom"),
  8769. unsafeRunPromise = runtime =>
  8770. methodWithTrace(
  8771. trace => effect =>
  8772. new Promise((resolve, reject) => {
  8773. ;(runtime =>
  8774. methodWithTrace(trace => (self, options) => {
  8775. const fiberId = Id_unsafeMake(),
  8776. effect = self.traced(trace)
  8777. let fiberRefs = FiberRefs_updatedAs(
  8778. runtime.fiberRefs,
  8779. fiberId,
  8780. currentContext,
  8781. runtime.context
  8782. )
  8783. options?.scheduler &&
  8784. (fiberRefs = FiberRefs_updatedAs(
  8785. fiberRefs,
  8786. fiberId,
  8787. currentScheduler,
  8788. options.scheduler
  8789. ))
  8790. options?.updateRefs &&
  8791. (fiberRefs = options.updateRefs(fiberRefs, fiberId))
  8792. const fiberRuntime = new FiberRuntime(
  8793. fiberId,
  8794. FiberRefs_forkAs(fiberRefs, fiberId),
  8795. runtime.runtimeFlags
  8796. ),
  8797. supervisor = fiberRuntime.getSupervisor()
  8798. if (supervisor !== supervisor_none) {
  8799. supervisor.onStart(
  8800. runtime.context,
  8801. effect,
  8802. Option_none(),
  8803. fiberRuntime
  8804. )
  8805. fiberRuntime.unsafeAddObserver(exit =>
  8806. supervisor.onEnd(exit, fiberRuntime)
  8807. )
  8808. }
  8809. globalScope.add(runtime.runtimeFlags, fiberRuntime)
  8810. fiberRuntime.start(effect)
  8811. return fiberRuntime
  8812. }))(runtime)(effect.traced(trace)).unsafeAddObserver(result => {
  8813. switch (result._tag) {
  8814. case "Success":
  8815. resolve(result.i0)
  8816. break
  8817. case "Failure":
  8818. reject(
  8819. (cause => {
  8820. const limit = Error.stackTraceLimit
  8821. Error.stackTraceLimit = 0
  8822. const error = new Error()
  8823. Error.stackTraceLimit = limit
  8824. const pretty = prettyErrors(cause)
  8825. if (pretty.length > 0) {
  8826. error.name = pretty[0].message.split(":")[0]
  8827. error.message = pretty[0].message.substring(
  8828. error.name.length + 2
  8829. )
  8830. error.stack = `${error.name}: ${error.message}\n${pretty[0].stack}`
  8831. }
  8832. error[FiberFailureId] = FiberFailureId
  8833. error[FiberFailureCauseId] = cause
  8834. error.toString = () => cause_pretty_pretty(cause)
  8835. error[NodePrint] = () => error.toString()
  8836. return error
  8837. })(result.i0)
  8838. )
  8839. }
  8840. })
  8841. })
  8842. )
  8843. class RuntimeImpl {
  8844. constructor(context, runtimeFlags, fiberRefs) {
  8845. this.context = context
  8846. this.runtimeFlags = runtimeFlags
  8847. this.fiberRefs = fiberRefs
  8848. }
  8849. }
  8850. const runtime_make = (context, runtimeFlags, fiberRefs) =>
  8851. new RuntimeImpl(context, runtimeFlags, fiberRefs),
  8852. defaultRuntimeFlags = runtimeFlags_make(1, 32),
  8853. Effect_asUnit = core_asUnit,
  8854. Effect_delay = delay,
  8855. Effect_bind = effect_bind,
  8856. Effect_bindDiscard = effect_bindDiscard,
  8857. bindValue_ = bindValue,
  8858. Effect_letDiscard = bindValueDiscard,
  8859. Effect_Do = effect_Do,
  8860. Effect_fail = core_fail,
  8861. Effect_filterOrElse = filterOrElse,
  8862. Effect_filterOrFail = filterOrFail,
  8863. Effect_flatMap = core_flatMap,
  8864. Effect_forEach = core_forEach,
  8865. Effect_forkDaemon = forkDaemon,
  8866. Effect_ignore = ignore,
  8867. Effect_isSuccess = effect_isSuccess,
  8868. Effect_log = log,
  8869. Effect_logDebug = logDebug,
  8870. Effect_logError = logError,
  8871. Effect_logInfo = logInfo,
  8872. Effect_logWarning = logWarning,
  8873. Effect_logAnnotate = logAnnotate,
  8874. Effect_map = core_map,
  8875. Effect_matchEffect = matchEffect,
  8876. Effect_orElseSucceed = orElseSucceed,
  8877. Effect_promise = promise,
  8878. Effect_provideSomeLayer = provideSomeLayer,
  8879. Effect_repeat = repeat_Effect,
  8880. Effect_some = fiberRuntime_some,
  8881. Effect_succeed = succeed,
  8882. Effect_sync = sync,
  8883. Effect_tap = core_tap,
  8884. Effect_tapErrorCause = tapErrorCause,
  8885. Effect_all = effect_all,
  8886. Effect_unit = core_unit,
  8887. runPromise = unsafeRunPromise(
  8888. runtime_make(
  8889. mjs_Context_empty(),
  8890. defaultRuntimeFlags,
  8891. FiberRefs_unsafeMake(new Map())
  8892. )
  8893. ),
  8894. Effect_withParallelismUnbounded = withParallelismUnbounded,
  8895. Effect_zipLeft = core_zipLeft,
  8896. Effect_zipRight = core_zipRight,
  8897. external_rxjs_namespaceObject = rxjs,
  8898. Schedule_fixed = fixed,
  8899. lib = observer => value => {
  8900. observer.next(value)
  8901. }
  8902. Promise.resolve(!1)
  8903. Promise.resolve(!0)
  8904. var PROMISE_RESOLVED_VOID = Promise.resolve()
  8905. function util_sleep(time, resolveWith) {
  8906. time || (time = 0)
  8907. return new Promise(function (res) {
  8908. return setTimeout(function () {
  8909. return res(resolveWith)
  8910. }, time)
  8911. })
  8912. }
  8913. function randomToken() {
  8914. return Math.random().toString(36).substring(2)
  8915. }
  8916. var lastMs = 0,
  8917. additional = 0
  8918. function microSeconds() {
  8919. var ms = new Date().getTime()
  8920. if (ms === lastMs) return 1e3 * ms + ++additional
  8921. lastMs = ms
  8922. additional = 0
  8923. return 1e3 * ms
  8924. }
  8925. var NativeMethod = {
  8926. create: function (channelName) {
  8927. var state = {
  8928. messagesCallback: null,
  8929. bc: new BroadcastChannel(channelName),
  8930. subFns: [],
  8931. }
  8932. state.bc.onmessage = function (msg) {
  8933. state.messagesCallback && state.messagesCallback(msg.data)
  8934. }
  8935. return state
  8936. },
  8937. close: function (channelState) {
  8938. channelState.bc.close()
  8939. channelState.subFns = []
  8940. },
  8941. onMessage: function (channelState, fn) {
  8942. channelState.messagesCallback = fn
  8943. },
  8944. postMessage: function (channelState, messageJson) {
  8945. try {
  8946. channelState.bc.postMessage(messageJson, !1)
  8947. return PROMISE_RESOLVED_VOID
  8948. } catch (err) {
  8949. return Promise.reject(err)
  8950. }
  8951. },
  8952. canBeUsed: function () {
  8953. if ("undefined" == typeof window) return !1
  8954. if ("function" == typeof BroadcastChannel) {
  8955. if (BroadcastChannel._pubkey)
  8956. throw new Error(
  8957. "BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill"
  8958. )
  8959. return !0
  8960. }
  8961. return !1
  8962. },
  8963. type: "native",
  8964. averageResponseTime: function () {
  8965. return 150
  8966. },
  8967. microSeconds,
  8968. },
  8969. ObliviousSet = (function () {
  8970. function ObliviousSet(ttl) {
  8971. this.ttl = ttl
  8972. this.map = new Map()
  8973. this._to = !1
  8974. }
  8975. ObliviousSet.prototype.has = function (value) {
  8976. return this.map.has(value)
  8977. }
  8978. ObliviousSet.prototype.add = function (value) {
  8979. var _this = this
  8980. this.map.set(value, now())
  8981. if (!this._to) {
  8982. this._to = !0
  8983. setTimeout(function () {
  8984. _this._to = !1
  8985. !(function (obliviousSet) {
  8986. for (
  8987. var olderThen = now() - obliviousSet.ttl,
  8988. iterator = obliviousSet.map[Symbol.iterator]();
  8989. ;
  8990.  
  8991. ) {
  8992. var next = iterator.next().value
  8993. if (!next) return
  8994. var value = next[0]
  8995. if (!(next[1] < olderThen)) return
  8996. obliviousSet.map.delete(value)
  8997. }
  8998. })(_this)
  8999. }, 0)
  9000. }
  9001. }
  9002. ObliviousSet.prototype.clear = function () {
  9003. this.map.clear()
  9004. }
  9005. return ObliviousSet
  9006. })()
  9007. function now() {
  9008. return new Date().getTime()
  9009. }
  9010. function options_fillOptionsWithDefaults() {
  9011. var originalOptions =
  9012. arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
  9013. options = JSON.parse(JSON.stringify(originalOptions))
  9014. void 0 === options.webWorkerSupport && (options.webWorkerSupport = !0)
  9015. options.idb || (options.idb = {})
  9016. options.idb.ttl || (options.idb.ttl = 45e3)
  9017. options.idb.fallbackInterval || (options.idb.fallbackInterval = 150)
  9018. originalOptions.idb &&
  9019. "function" == typeof originalOptions.idb.onclose &&
  9020. (options.idb.onclose = originalOptions.idb.onclose)
  9021. options.localstorage || (options.localstorage = {})
  9022. options.localstorage.removeTimeout ||
  9023. (options.localstorage.removeTimeout = 6e4)
  9024. originalOptions.methods && (options.methods = originalOptions.methods)
  9025. options.node || (options.node = {})
  9026. options.node.ttl || (options.node.ttl = 12e4)
  9027. options.node.maxParallelWrites || (options.node.maxParallelWrites = 2048)
  9028. void 0 === options.node.useFastPath && (options.node.useFastPath = !0)
  9029. return options
  9030. }
  9031. var OBJECT_STORE_ID = "messages",
  9032. TRANSACTION_SETTINGS = { durability: "relaxed" }
  9033. function getIdb() {
  9034. if ("undefined" != typeof indexedDB) return indexedDB
  9035. if ("undefined" != typeof window) {
  9036. if (void 0 !== window.mozIndexedDB) return window.mozIndexedDB
  9037. if (void 0 !== window.webkitIndexedDB) return window.webkitIndexedDB
  9038. if (void 0 !== window.msIndexedDB) return window.msIndexedDB
  9039. }
  9040. return !1
  9041. }
  9042. function commitIndexedDBTransaction(tx) {
  9043. tx.commit && tx.commit()
  9044. }
  9045. function _readLoop(state) {
  9046. state.closed ||
  9047. readNewMessages(state)
  9048. .then(function () {
  9049. return util_sleep(state.options.idb.fallbackInterval)
  9050. })
  9051. .then(function () {
  9052. return _readLoop(state)
  9053. })
  9054. }
  9055. function readNewMessages(state) {
  9056. return state.closed
  9057. ? PROMISE_RESOLVED_VOID
  9058. : state.messagesCallback
  9059. ? (function (db, lastCursorId) {
  9060. var tx = db.transaction(
  9061. OBJECT_STORE_ID,
  9062. "readonly",
  9063. TRANSACTION_SETTINGS
  9064. ),
  9065. objectStore = tx.objectStore(OBJECT_STORE_ID),
  9066. ret = [],
  9067. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  9068. if (objectStore.getAll) {
  9069. var getAllRequest = objectStore.getAll(keyRangeValue)
  9070. return new Promise(function (res, rej) {
  9071. getAllRequest.onerror = function (err) {
  9072. return rej(err)
  9073. }
  9074. getAllRequest.onsuccess = function (e) {
  9075. res(e.target.result)
  9076. }
  9077. })
  9078. }
  9079. return new Promise(function (res, rej) {
  9080. var openCursorRequest = (function () {
  9081. try {
  9082. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  9083. return objectStore.openCursor(keyRangeValue)
  9084. } catch (e) {
  9085. return objectStore.openCursor()
  9086. }
  9087. })()
  9088. openCursorRequest.onerror = function (err) {
  9089. return rej(err)
  9090. }
  9091. openCursorRequest.onsuccess = function (ev) {
  9092. var cursor = ev.target.result
  9093. if (cursor)
  9094. if (cursor.value.id < lastCursorId + 1)
  9095. cursor.continue(lastCursorId + 1)
  9096. else {
  9097. ret.push(cursor.value)
  9098. cursor.continue()
  9099. }
  9100. else {
  9101. commitIndexedDBTransaction(tx)
  9102. res(ret)
  9103. }
  9104. }
  9105. })
  9106. })(state.db, state.lastCursorId).then(function (newerMessages) {
  9107. var useMessages = newerMessages
  9108. .filter(function (msgObj) {
  9109. return !!msgObj
  9110. })
  9111. .map(function (msgObj) {
  9112. msgObj.id > state.lastCursorId &&
  9113. (state.lastCursorId = msgObj.id)
  9114. return msgObj
  9115. })
  9116. .filter(function (msgObj) {
  9117. return (function (msgObj, state) {
  9118. return !(
  9119. msgObj.uuid === state.uuid ||
  9120. state.eMIs.has(msgObj.id) ||
  9121. msgObj.data.time < state.messagesCallbackTime
  9122. )
  9123. })(msgObj, state)
  9124. })
  9125. .sort(function (msgObjA, msgObjB) {
  9126. return msgObjA.time - msgObjB.time
  9127. })
  9128. useMessages.forEach(function (msgObj) {
  9129. if (state.messagesCallback) {
  9130. state.eMIs.add(msgObj.id)
  9131. state.messagesCallback(msgObj.data)
  9132. }
  9133. })
  9134. return PROMISE_RESOLVED_VOID
  9135. })
  9136. : PROMISE_RESOLVED_VOID
  9137. }
  9138. var IndexedDBMethod = {
  9139. create: function (channelName, options) {
  9140. options = options_fillOptionsWithDefaults(options)
  9141. return (function (channelName) {
  9142. var dbName = "pubkey.broadcast-channel-0-" + channelName,
  9143. openRequest = getIdb().open(dbName)
  9144. openRequest.onupgradeneeded = function (ev) {
  9145. ev.target.result.createObjectStore(OBJECT_STORE_ID, {
  9146. keyPath: "id",
  9147. autoIncrement: !0,
  9148. })
  9149. }
  9150. return new Promise(function (res, rej) {
  9151. openRequest.onerror = function (ev) {
  9152. return rej(ev)
  9153. }
  9154. openRequest.onsuccess = function () {
  9155. res(openRequest.result)
  9156. }
  9157. })
  9158. })(channelName).then(function (db) {
  9159. var state = {
  9160. closed: !1,
  9161. lastCursorId: 0,
  9162. channelName,
  9163. options,
  9164. uuid: randomToken(),
  9165. eMIs: new ObliviousSet(2 * options.idb.ttl),
  9166. writeBlockPromise: PROMISE_RESOLVED_VOID,
  9167. messagesCallback: null,
  9168. readQueuePromises: [],
  9169. db,
  9170. }
  9171. db.onclose = function () {
  9172. state.closed = !0
  9173. options.idb.onclose && options.idb.onclose()
  9174. }
  9175. _readLoop(state)
  9176. return state
  9177. })
  9178. },
  9179. close: function (channelState) {
  9180. channelState.closed = !0
  9181. channelState.db.close()
  9182. },
  9183. onMessage: function (channelState, fn, time) {
  9184. channelState.messagesCallbackTime = time
  9185. channelState.messagesCallback = fn
  9186. readNewMessages(channelState)
  9187. },
  9188. postMessage: function (channelState, messageJson) {
  9189. channelState.writeBlockPromise = channelState.writeBlockPromise
  9190. .then(function () {
  9191. return (function (db, readerUuid, messageJson) {
  9192. var writeObject = {
  9193. uuid: readerUuid,
  9194. time: new Date().getTime(),
  9195. data: messageJson,
  9196. },
  9197. tx = db.transaction(
  9198. [OBJECT_STORE_ID],
  9199. "readwrite",
  9200. TRANSACTION_SETTINGS
  9201. )
  9202. return new Promise(function (res, rej) {
  9203. tx.oncomplete = function () {
  9204. return res()
  9205. }
  9206. tx.onerror = function (ev) {
  9207. return rej(ev)
  9208. }
  9209. tx.objectStore(OBJECT_STORE_ID).add(writeObject)
  9210. commitIndexedDBTransaction(tx)
  9211. })
  9212. })(channelState.db, channelState.uuid, messageJson)
  9213. })
  9214. .then(function () {
  9215. 0 === Math.floor(11 * Math.random() + 0) &&
  9216. (function (channelState) {
  9217. return ((db = channelState.db),
  9218. (ttl = channelState.options.idb.ttl),
  9219. (olderThen = new Date().getTime() - ttl),
  9220. (tx = db.transaction(
  9221. OBJECT_STORE_ID,
  9222. "readonly",
  9223. TRANSACTION_SETTINGS
  9224. )),
  9225. (objectStore = tx.objectStore(OBJECT_STORE_ID)),
  9226. (ret = []),
  9227. new Promise(function (res) {
  9228. objectStore.openCursor().onsuccess = function (ev) {
  9229. var cursor = ev.target.result
  9230. if (cursor) {
  9231. var msgObk = cursor.value
  9232. if (msgObk.time < olderThen) {
  9233. ret.push(msgObk)
  9234. cursor.continue()
  9235. } else {
  9236. commitIndexedDBTransaction(tx)
  9237. res(ret)
  9238. }
  9239. } else res(ret)
  9240. }
  9241. })).then(function (tooOld) {
  9242. return (function (channelState, ids) {
  9243. if (channelState.closed) return Promise.resolve([])
  9244. var objectStore = channelState.db
  9245. .transaction(
  9246. OBJECT_STORE_ID,
  9247. "readwrite",
  9248. TRANSACTION_SETTINGS
  9249. )
  9250. .objectStore(OBJECT_STORE_ID)
  9251. return Promise.all(
  9252. ids.map(function (id) {
  9253. var deleteRequest = objectStore.delete(id)
  9254. return new Promise(function (res) {
  9255. deleteRequest.onsuccess = function () {
  9256. return res()
  9257. }
  9258. })
  9259. })
  9260. )
  9261. })(
  9262. channelState,
  9263. tooOld.map(function (msg) {
  9264. return msg.id
  9265. })
  9266. )
  9267. })
  9268. var db, ttl, olderThen, tx, objectStore, ret
  9269. })(channelState)
  9270. })
  9271. return channelState.writeBlockPromise
  9272. },
  9273. canBeUsed: function () {
  9274. return !!getIdb()
  9275. },
  9276. type: "idb",
  9277. averageResponseTime: function (options) {
  9278. return 2 * options.idb.fallbackInterval
  9279. },
  9280. microSeconds,
  9281. }
  9282. function getLocalStorage() {
  9283. var localStorage
  9284. if ("undefined" == typeof window) return null
  9285. try {
  9286. localStorage = window.localStorage
  9287. localStorage =
  9288. window["ie8-eventlistener/storage"] || window.localStorage
  9289. } catch (e) {}
  9290. return localStorage
  9291. }
  9292. function storageKey(channelName) {
  9293. return "pubkey.broadcastChannel-" + channelName
  9294. }
  9295. function localstorage_canBeUsed() {
  9296. var ls = getLocalStorage()
  9297. if (!ls) return !1
  9298. try {
  9299. var key = "__broadcastchannel_check"
  9300. ls.setItem(key, "works")
  9301. ls.removeItem(key)
  9302. } catch (e) {
  9303. return !1
  9304. }
  9305. return !0
  9306. }
  9307. var LocalstorageMethod = {
  9308. create: function (channelName, options) {
  9309. options = options_fillOptionsWithDefaults(options)
  9310. if (!localstorage_canBeUsed())
  9311. throw new Error("BroadcastChannel: localstorage cannot be used")
  9312. var uuid = randomToken(),
  9313. eMIs = new ObliviousSet(options.localstorage.removeTimeout),
  9314. state = { channelName, uuid, eMIs }
  9315. state.listener = (function (channelName, fn) {
  9316. var key = storageKey(channelName),
  9317. listener = function (ev) {
  9318. ev.key === key &&
  9319. (function (msgObj) {
  9320. if (
  9321. state.messagesCallback &&
  9322. msgObj.uuid !== uuid &&
  9323. msgObj.token &&
  9324. !eMIs.has(msgObj.token) &&
  9325. !(
  9326. msgObj.data.time &&
  9327. msgObj.data.time < state.messagesCallbackTime
  9328. )
  9329. ) {
  9330. eMIs.add(msgObj.token)
  9331. state.messagesCallback(msgObj.data)
  9332. }
  9333. })(JSON.parse(ev.newValue))
  9334. }
  9335. window.addEventListener("storage", listener)
  9336. return listener
  9337. })(channelName)
  9338. return state
  9339. },
  9340. close: function (channelState) {
  9341. ;(listener = channelState.listener),
  9342. window.removeEventListener("storage", listener)
  9343. var listener
  9344. },
  9345. onMessage: function (channelState, fn, time) {
  9346. channelState.messagesCallbackTime = time
  9347. channelState.messagesCallback = fn
  9348. },
  9349. postMessage: function (channelState, messageJson) {
  9350. return new Promise(function (res) {
  9351. util_sleep().then(function () {
  9352. var key = storageKey(channelState.channelName),
  9353. writeObj = {
  9354. token: randomToken(),
  9355. time: new Date().getTime(),
  9356. data: messageJson,
  9357. uuid: channelState.uuid,
  9358. },
  9359. value = JSON.stringify(writeObj)
  9360. getLocalStorage().setItem(key, value)
  9361. var ev = document.createEvent("Event")
  9362. ev.initEvent("storage", !0, !0)
  9363. ev.key = key
  9364. ev.newValue = value
  9365. window.dispatchEvent(ev)
  9366. res()
  9367. })
  9368. })
  9369. },
  9370. canBeUsed: localstorage_canBeUsed,
  9371. type: "localstorage",
  9372. averageResponseTime: function () {
  9373. var userAgent = navigator.userAgent.toLowerCase()
  9374. return userAgent.includes("safari") && !userAgent.includes("chrome")
  9375. ? 240
  9376. : 120
  9377. },
  9378. microSeconds,
  9379. },
  9380. simulate_microSeconds = microSeconds,
  9381. SIMULATE_CHANNELS = new Set(),
  9382. SimulateMethod = {
  9383. create: function (channelName) {
  9384. var state = { name: channelName, messagesCallback: null }
  9385. SIMULATE_CHANNELS.add(state)
  9386. return state
  9387. },
  9388. close: function (channelState) {
  9389. SIMULATE_CHANNELS.delete(channelState)
  9390. },
  9391. onMessage: function (channelState, fn) {
  9392. channelState.messagesCallback = fn
  9393. },
  9394. postMessage: function (channelState, messageJson) {
  9395. return new Promise(function (res) {
  9396. return setTimeout(function () {
  9397. Array.from(SIMULATE_CHANNELS)
  9398. .filter(function (channel) {
  9399. return channel.name === channelState.name
  9400. })
  9401. .filter(function (channel) {
  9402. return channel !== channelState
  9403. })
  9404. .filter(function (channel) {
  9405. return !!channel.messagesCallback
  9406. })
  9407. .forEach(function (channel) {
  9408. return channel.messagesCallback(messageJson)
  9409. })
  9410. res()
  9411. }, 5)
  9412. })
  9413. },
  9414. canBeUsed: function () {
  9415. return !0
  9416. },
  9417. type: "simulate",
  9418. averageResponseTime: function () {
  9419. return 5
  9420. },
  9421. microSeconds: simulate_microSeconds,
  9422. },
  9423. METHODS = [NativeMethod, IndexedDBMethod, LocalstorageMethod],
  9424. OPEN_BROADCAST_CHANNELS = new Set(),
  9425. lastId = 0,
  9426. broadcast_channel_BroadcastChannel = function (name, options) {
  9427. this.id = lastId++
  9428. OPEN_BROADCAST_CHANNELS.add(this)
  9429. this.name = name
  9430. this.options = options_fillOptionsWithDefaults(options)
  9431. this.method = (function (options) {
  9432. var chooseMethods = []
  9433. .concat(options.methods, METHODS)
  9434. .filter(Boolean)
  9435. if (options.type) {
  9436. if ("simulate" === options.type) return SimulateMethod
  9437. var ret = chooseMethods.find(function (m) {
  9438. return m.type === options.type
  9439. })
  9440. if (ret) return ret
  9441. throw new Error("method-type " + options.type + " not found")
  9442. }
  9443. options.webWorkerSupport ||
  9444. (chooseMethods = chooseMethods.filter(function (m) {
  9445. return "idb" !== m.type
  9446. }))
  9447. var useMethod = chooseMethods.find(function (method) {
  9448. return method.canBeUsed()
  9449. })
  9450. if (useMethod) return useMethod
  9451. throw new Error(
  9452. "No usable method found in " +
  9453. JSON.stringify(
  9454. METHODS.map(function (m) {
  9455. return m.type
  9456. })
  9457. )
  9458. )
  9459. })(this.options)
  9460. this._iL = !1
  9461. this._onML = null
  9462. this._addEL = { message: [], internal: [] }
  9463. this._uMP = new Set()
  9464. this._befC = []
  9465. this._prepP = null
  9466. !(function (channel) {
  9467. var obj,
  9468. maybePromise = channel.method.create(channel.name, channel.options)
  9469. if ((obj = maybePromise) && "function" == typeof obj.then) {
  9470. channel._prepP = maybePromise
  9471. maybePromise.then(function (s) {
  9472. channel._state = s
  9473. })
  9474. } else channel._state = maybePromise
  9475. })(this)
  9476. }
  9477. broadcast_channel_BroadcastChannel._pubkey = !0
  9478. broadcast_channel_BroadcastChannel.prototype = {
  9479. postMessage: function (msg) {
  9480. if (this.closed)
  9481. throw new Error(
  9482. "BroadcastChannel.postMessage(): Cannot post message after channel has closed " +
  9483. JSON.stringify(msg)
  9484. )
  9485. return _post(this, "message", msg)
  9486. },
  9487. postInternal: function (msg) {
  9488. return _post(this, "internal", msg)
  9489. },
  9490. set onmessage(fn) {
  9491. var listenObj = { time: this.method.microSeconds(), fn }
  9492. _removeListenerObject(this, "message", this._onML)
  9493. if (fn && "function" == typeof fn) {
  9494. this._onML = listenObj
  9495. _addListenerObject(this, "message", listenObj)
  9496. } else this._onML = null
  9497. },
  9498. addEventListener: function (type, fn) {
  9499. _addListenerObject(this, type, { time: this.method.microSeconds(), fn })
  9500. },
  9501. removeEventListener: function (type, fn) {
  9502. _removeListenerObject(
  9503. this,
  9504. type,
  9505. this._addEL[type].find(function (obj) {
  9506. return obj.fn === fn
  9507. })
  9508. )
  9509. },
  9510. close: function () {
  9511. var _this = this
  9512. if (!this.closed) {
  9513. OPEN_BROADCAST_CHANNELS.delete(this)
  9514. this.closed = !0
  9515. var awaitPrepare = this._prepP ? this._prepP : PROMISE_RESOLVED_VOID
  9516. this._onML = null
  9517. this._addEL.message = []
  9518. return awaitPrepare
  9519. .then(function () {
  9520. return Promise.all(Array.from(_this._uMP))
  9521. })
  9522. .then(function () {
  9523. return Promise.all(
  9524. _this._befC.map(function (fn) {
  9525. return fn()
  9526. })
  9527. )
  9528. })
  9529. .then(function () {
  9530. return _this.method.close(_this._state)
  9531. })
  9532. }
  9533. },
  9534. get type() {
  9535. return this.method.type
  9536. },
  9537. get isClosed() {
  9538. return this.closed
  9539. },
  9540. }
  9541. function _post(broadcastChannel, type, msg) {
  9542. var msgObj = {
  9543. time: broadcastChannel.method.microSeconds(),
  9544. type,
  9545. data: msg,
  9546. }
  9547. return (
  9548. broadcastChannel._prepP
  9549. ? broadcastChannel._prepP
  9550. : PROMISE_RESOLVED_VOID
  9551. ).then(function () {
  9552. var sendPromise = broadcastChannel.method.postMessage(
  9553. broadcastChannel._state,
  9554. msgObj
  9555. )
  9556. broadcastChannel._uMP.add(sendPromise)
  9557. sendPromise.catch().then(function () {
  9558. return broadcastChannel._uMP.delete(sendPromise)
  9559. })
  9560. return sendPromise
  9561. })
  9562. }
  9563. function _hasMessageListeners(channel) {
  9564. return (
  9565. channel._addEL.message.length > 0 || channel._addEL.internal.length > 0
  9566. )
  9567. }
  9568. function _addListenerObject(channel, type, obj) {
  9569. channel._addEL[type].push(obj)
  9570. !(function (channel) {
  9571. if (!channel._iL && _hasMessageListeners(channel)) {
  9572. var listenerFn = function (msgObj) {
  9573. channel._addEL[msgObj.type].forEach(function (listenerObject) {
  9574. var minMessageTime = listenerObject.time - 1e5
  9575. msgObj.time >= minMessageTime && listenerObject.fn(msgObj.data)
  9576. })
  9577. },
  9578. time = channel.method.microSeconds()
  9579. if (channel._prepP)
  9580. channel._prepP.then(function () {
  9581. channel._iL = !0
  9582. channel.method.onMessage(channel._state, listenerFn, time)
  9583. })
  9584. else {
  9585. channel._iL = !0
  9586. channel.method.onMessage(channel._state, listenerFn, time)
  9587. }
  9588. }
  9589. })(channel)
  9590. }
  9591. function _removeListenerObject(channel, type, obj) {
  9592. channel._addEL[type] = channel._addEL[type].filter(function (o) {
  9593. return o !== obj
  9594. })
  9595. !(function (channel) {
  9596. if (channel._iL && !_hasMessageListeners(channel)) {
  9597. channel._iL = !1
  9598. var time = channel.method.microSeconds()
  9599. channel.method.onMessage(channel._state, null, time)
  9600. }
  9601. })(channel)
  9602. }
  9603. Object.prototype.toString.call("undefined" != typeof process ? process : 0),
  9604. new Set()
  9605. const external_DeepDiff_namespaceObject = DeepDiff
  9606. var fast_deep_equal = __webpack_require__(204),
  9607. fast_deep_equal_default = __webpack_require__.n(fast_deep_equal)
  9608. const mapObject = f => o =>
  9609. pipe(Object.entries(o), ReadonlyArray_map(f), Object.fromEntries),
  9610. makePageState = mapObject(([k, v]) => [
  9611. k,
  9612. { ele: Option_none(), read: v },
  9613. ]),
  9614. removeOldChats = mainState => maxChatCount =>
  9615. pipe(
  9616. Effect_sync(() =>
  9617. mainState.flowChats.sort((a, b) =>
  9618. a.animationEnded === b.animationEnded
  9619. ? 0
  9620. : a.animationEnded
  9621. ? -1
  9622. : 1
  9623. )
  9624. ),
  9625. Effect_zipRight(
  9626. Effect_sync(() =>
  9627. mainState.flowChats.splice(
  9628. 0,
  9629. Math.max(0, mainState.flowChats.length - maxChatCount)
  9630. )
  9631. )
  9632. ),
  9633. Effect_flatMap(
  9634. Effect_forEach(x =>
  9635. pipe(
  9636. Effect_logDebug("RemoveChat"),
  9637. Effect_zipRight(
  9638. Effect_sync(() => {
  9639. x.element.remove()
  9640. })
  9641. )
  9642. )
  9643. )
  9644. )
  9645. ),
  9646. external_m_namespaceObject = m
  9647. var external_m_default = __webpack_require__.n(external_m_namespaceObject)
  9648. const getChatFontSize = mainState =>
  9649. Math.round(
  9650. ((Math.max(mainState.config.fontSize - 0.2, 0.01) *
  9651. mainState.playerRect.height) /
  9652. mainState.config.laneCount) *
  9653. (mainState.config.flowY2 - mainState.config.flowY1) *
  9654. 100
  9655. ) / 100,
  9656. textShadow = shadowColor =>
  9657. flow(
  9658. x => `${x}px`,
  9659. x => (a, b) => `${a}${x} ${b}${x} ${shadowColor}99`,
  9660. x => join(", ")([x("-", "-"), x("", "-"), x("-", ""), x("", "")])
  9661. ),
  9662. textStyle = { fontFamily: "inherit" },
  9663. renderChat = chat => mainState =>
  9664. Effect_sync(() =>
  9665. external_m_default().render(
  9666. chat.element,
  9667. ((chat, mainState) =>
  9668. pipe(
  9669. mainState.config,
  9670. config => ({ data: chat.getData(config), config }),
  9671. ({ data, config }) =>
  9672. external_m_default()(
  9673. "span",
  9674. {
  9675. style: {
  9676. fontSize: `${getChatFontSize(mainState)}px`,
  9677. visibility: config.displayChats ? "visible" : "hidden",
  9678. color:
  9679. "owner" === data.authorType
  9680. ? config.ownerColor
  9681. : "moderator" === data.authorType
  9682. ? config.moderatorColor
  9683. : "member" === data.authorType
  9684. ? config.memberColor
  9685. : config.color,
  9686. fontWeight: config.fontWeight.toString(),
  9687. fontFamily: config.font,
  9688. opacity: config.chatOpacity.toString(),
  9689. textShadow: textShadow(config.shadowColor)(
  9690. config.shadowFontWeight
  9691. ),
  9692. },
  9693. },
  9694. pipe(
  9695. [
  9696. pipe(
  9697. data.authorName,
  9698. Option_filter(x => x.visible),
  9699. Option_map(x =>
  9700. external_m_default()(
  9701. "span",
  9702. {
  9703. style: {
  9704. color: getOrUndefined(data.textColor),
  9705. fontSize: "0.84em",
  9706. ...textStyle,
  9707. },
  9708. },
  9709. `${x.content}: `
  9710. )
  9711. )
  9712. ),
  9713. pipe(
  9714. data.messageElement,
  9715. Option_map(x =>
  9716. ((message, config) => {
  9717. const eleWin =
  9718. message.ownerDocument.defaultView ?? window,
  9719. { maxChatLength } = config
  9720. return pipe(
  9721. Array.from(message.childNodes),
  9722. ReadonlyArray_reduce(
  9723. { vnodes: [], length: 0 },
  9724. ({ vnodes, length }, node) =>
  9725. length >= maxChatLength
  9726. ? { vnodes, length }
  9727. : !config.textOnly &&
  9728. node instanceof eleWin.HTMLImageElement
  9729. ? {
  9730. vnodes: [
  9731. ...vnodes,
  9732. external_m_default()("img", {
  9733. style: {
  9734. height: "1em",
  9735. width: "1em",
  9736. verticalAlign: "text-top",
  9737. },
  9738. src: node.src.replace(
  9739. /=w\d+-h\d+-c-k-nd$/,
  9740. ""
  9741. ),
  9742. alt: node.alt,
  9743. }),
  9744. ],
  9745. length: length + 1,
  9746. }
  9747. : pipe(
  9748. node.textContent ?? "",
  9749. slice(0, maxChatLength),
  9750. x =>
  9751. node instanceof
  9752. eleWin.HTMLAnchorElement
  9753. ? {
  9754. vnodes: [
  9755. ...vnodes,
  9756. external_m_default()(
  9757. "span",
  9758. {
  9759. style: {
  9760. fontSize: "0.84em",
  9761. textDecoration:
  9762. "underline",
  9763. ...textStyle,
  9764. },
  9765. },
  9766. x
  9767. ),
  9768. ],
  9769. length: length + x.length,
  9770. }
  9771. : {
  9772. vnodes: [
  9773. ...vnodes,
  9774. external_m_default().fragment(
  9775. {},
  9776. x
  9777. ),
  9778. ],
  9779. length: length + x.length,
  9780. }
  9781. )
  9782. )
  9783. )
  9784. })(x, config)
  9785. ),
  9786. Option_map(x =>
  9787. external_m_default()(
  9788. "span",
  9789. {
  9790. style: {
  9791. color: getOrUndefined(data.textColor),
  9792. ...textStyle,
  9793. },
  9794. },
  9795. x.vnodes
  9796. )
  9797. )
  9798. ),
  9799. pipe(
  9800. data.paymentInfo,
  9801. Option_filter(x => x.visible),
  9802. Option_map(x =>
  9803. external_m_default()(
  9804. "span",
  9805. {
  9806. style: {
  9807. color: getOrUndefined(data.paidColor),
  9808. fontSize: "0.84em",
  9809. ...textStyle,
  9810. },
  9811. },
  9812. external_m_default()(
  9813. "strong",
  9814. { style: textStyle },
  9815. x.content
  9816. )
  9817. )
  9818. )
  9819. ),
  9820. ],
  9821. ReadonlyArray_compact
  9822. )
  9823. )
  9824. ))(chat, mainState)
  9825. )
  9826. ),
  9827. Bicovariant_mapLeft = F =>
  9828. Function_dual(2, (self, f) => F.bimap(self, f, Function_identity)),
  9829. Bicovariant_map = F =>
  9830. Function_dual(2, (self, f) => F.bimap(self, Function_identity, f)),
  9831. getFirst = self => self[0],
  9832. getSecond = self => self[1],
  9833. Tuple_bimap = Function_dual(3, (self, f, g) => [f(self[0]), g(self[1])]),
  9834. Tuple_Bicovariant = { bimap: Tuple_bimap },
  9835. mapFirst = Bicovariant_mapLeft(Tuple_Bicovariant),
  9836. mapSecond = Bicovariant_map(Tuple_Bicovariant),
  9837. external_window_hash_it_namespaceObject = window["hash-it"]
  9838. var external_window_hash_it_default = __webpack_require__.n(
  9839. external_window_hash_it_namespaceObject
  9840. )
  9841. const external_window_micro_memoize_namespaceObject =
  9842. window["micro-memoize"]
  9843. var external_window_micro_memoize_default = __webpack_require__.n(
  9844. external_window_micro_memoize_namespaceObject
  9845. )
  9846. const getFlowChatProgress = chat =>
  9847. pipe(
  9848. chat.animation,
  9849. flatMapNullable(x => x.currentTime),
  9850. getOrElse(() => 0),
  9851. x =>
  9852. ("number" == typeof x ? x : x.to("ms").value) /
  9853. chat.animationDuration
  9854. ),
  9855. getFlowChatRect = (chat, mainState) =>
  9856. pipe(
  9857. mainState.config,
  9858. x =>
  9859. mainState.playerRect.width * x.flowX2 -
  9860. (chat.width + mainState.playerRect.width * (x.flowX2 - x.flowX1)) *
  9861. getFlowChatProgress(chat),
  9862. x => new DOMRect(x, chat.y, chat.width, chat.height)
  9863. ),
  9864. getChatLane = (flowChat, progress) => mainState => {
  9865. const flowWidth =
  9866. mainState.playerRect.width *
  9867. (mainState.config.flowX2 - mainState.config.flowX1),
  9868. chatRect = getFlowChatRect(flowChat, mainState),
  9869. chatWidth = chatRect.width,
  9870. chatHeight = chatRect.height,
  9871. chatX = chatRect.x,
  9872. { flowChats } = mainState,
  9873. chatIndex = flowChats.indexOf(flowChat),
  9874. movingChats = pipe(
  9875. flowChats,
  9876. take(chatIndex >= 0 ? chatIndex : flowChats.length),
  9877. ReadonlyArray_filter(
  9878. chat => !chat.animationEnded && chat.width > 0
  9879. ),
  9880. sort(Order_contramap(x => x.lane)(Order))
  9881. ),
  9882. tooCloseTo = external_window_micro_memoize_default()(
  9883. x => {
  9884. const otherRect = getFlowChatRect(x, mainState),
  9885. otherWidth = otherRect.width,
  9886. otherX = otherRect.x,
  9887. gap =
  9888. (chatHeight * otherWidth * chatWidth) ** 0.333 *
  9889. mainState.config.minSpacing
  9890. return (
  9891. (flowWidth - otherX) / (flowWidth + otherWidth) - progress <
  9892. (chatWidth + gap) / (flowWidth + chatWidth) ||
  9893. otherX + otherWidth + gap > chatX
  9894. )
  9895. },
  9896. { maxSize: 1e3 }
  9897. ),
  9898. occupyInfo = pipe(
  9899. movingChats,
  9900. ReadonlyArray_map(x => ({
  9901. tooClose: () => tooCloseTo(x),
  9902. lane: x.lane,
  9903. })),
  9904. append({ tooClose: () => !0, lane: mainState.config.laneCount })
  9905. ),
  9906. index = occupyInfo.findIndex(x => x.lane >= flowChat.lane),
  9907. bottomFreeLane = pipe(
  9908. occupyInfo.slice(index),
  9909. findFirst(x => x.tooClose()),
  9910. Option_map(x => x.lane),
  9911. getOrElse(() => mainState.config.laneCount)
  9912. ),
  9913. topFreeLane = pipe(
  9914. occupyInfo.slice(0, index),
  9915. findLast(x => x.tooClose()),
  9916. Option_map(x => x.lane),
  9917. getOrElse(() => -1)
  9918. ),
  9919. formerLaneInterval = Math.min(
  9920. flowChat.lane - topFreeLane,
  9921. bottomFreeLane - flowChat.lane,
  9922. 1
  9923. )
  9924. return pipe(
  9925. occupyInfo,
  9926. ReadonlyArray_reduce(
  9927. { maxInterval: 0, maxIntervalLane: 0, lastLane: -1 },
  9928. ({ maxInterval, maxIntervalLane, lastLane }, info) =>
  9929. maxInterval > 0.999 || !info.tooClose()
  9930. ? { maxInterval, maxIntervalLane, lastLane }
  9931. : (() => {
  9932. const nextLane = info.lane,
  9933. interLane = Math.min(
  9934. Math.max((lastLane + nextLane) / 2, 0),
  9935. mainState.config.laneCount - 1
  9936. ),
  9937. newInterval = Math.min(
  9938. interLane - lastLane,
  9939. nextLane - interLane,
  9940. 1
  9941. )
  9942. return newInterval - maxInterval > 0.001
  9943. ? {
  9944. maxInterval: newInterval,
  9945. maxIntervalLane: Math.max(lastLane + newInterval, 0),
  9946. lastLane: nextLane,
  9947. }
  9948. : { maxInterval, maxIntervalLane, lastLane: nextLane }
  9949. })()
  9950. ),
  9951. x => ({
  9952. lane:
  9953. Math.abs(formerLaneInterval - x.maxInterval) < 0.001
  9954. ? flowChat.lane
  9955. : x.maxIntervalLane,
  9956. interval: x.maxInterval,
  9957. })
  9958. )
  9959. },
  9960. getLaneY = (lane, mainState) =>
  9961. mainState.playerRect.height *
  9962. ((lane / mainState.config.laneCount + 0.005) *
  9963. (mainState.config.flowY2 - mainState.config.flowY1) +
  9964. mainState.config.flowY1),
  9965. intervalTooSmall = interval => config =>
  9966. config.noOverlap && interval < 0.999,
  9967. setChatPlayState = chat => mainState =>
  9968. pipe(
  9969. chat,
  9970. liftPredicate(x => !x.animationEnded),
  9971. Effect_map(x => x.animation),
  9972. Effect_flatMap(Function_identity),
  9973. Effect_tap(x =>
  9974. Effect_sync(
  9975. mainState.chatPlaying ? () => x.play() : () => x.pause()
  9976. )
  9977. ),
  9978. Effect_flatMap(x =>
  9979. Effect_sync(() => {
  9980. x.playbackRate = mainState.config.flowSpeed / 15
  9981. })
  9982. ),
  9983. Effect_ignore
  9984. ),
  9985. getWidth = external_window_micro_memoize_default()(
  9986. ele => ele?.getBoundingClientRect().width ?? 0,
  9987. {
  9988. maxSize: 2e3,
  9989. transformKey: ReadonlyArray_map(external_window_hash_it_default()),
  9990. }
  9991. ),
  9992. setChatAnimation = chat => mainState =>
  9993. pipe(
  9994. { fontSize: getChatFontSize(mainState) },
  9995. Effect_succeed,
  9996. Effect_tap(x =>
  9997. Effect_sync(() => {
  9998. chat.element.style.transform = `translate(${
  9999. mainState.playerRect.width *
  10000. (mainState.config.flowX2 - mainState.config.flowX1)
  10001. }px, -${2 * x.fontSize}px)`
  10002. })
  10003. ),
  10004. Effect_filterOrFail(() => !chat.animationEnded, Option_none),
  10005. Effect_tap(x =>
  10006. Effect_sync(() => {
  10007. chat.animationDuration = 6400
  10008. chat.width = getWidth(chat.element.firstElementChild)
  10009. chat.height = x.fontSize
  10010. })
  10011. ),
  10012. Effect_map(() => getFlowChatProgress(chat)),
  10013. Effect_map(progress => ({
  10014. progress,
  10015. ...getChatLane(chat, progress)(mainState),
  10016. })),
  10017. Effect_filterOrElse(
  10018. x => !intervalTooSmall(x.interval)(mainState.config),
  10019. () =>
  10020. pipe(
  10021. chat.animation,
  10022. Effect_flatMap(x =>
  10023. Effect_sync(() => {
  10024. x.finish()
  10025. chat.animation = Option_none()
  10026. })
  10027. ),
  10028. Effect_zipRight(Effect_fail(Option_none()))
  10029. )
  10030. ),
  10031. Effect_tap(x =>
  10032. Effect_sync(() => {
  10033. chat.lane = x.lane
  10034. })
  10035. ),
  10036. Effect_map(x => ({ ...x, laneY: getLaneY(chat.lane, mainState) })),
  10037. Effect_tap(ctx =>
  10038. pipe(
  10039. [
  10040. pipe(
  10041. chat.animation,
  10042. Effect_flatMap(x => Effect_sync(() => x.cancel())),
  10043. Effect_ignore
  10044. ),
  10045. pipe(
  10046. [
  10047. [
  10048. mainState.playerRect.width *
  10049. (mainState.config.flowX2 - mainState.config.flowX1),
  10050. ctx.laneY,
  10051. ],
  10052. [-chat.width, ctx.laneY],
  10053. ],
  10054. ReadonlyArray_map(
  10055. pipe(
  10056. x => `${x}px`,
  10057. x => Tuple_bimap(x, x)
  10058. )
  10059. ),
  10060. ReadonlyArray_map(([x, y]) => `translate(${x}, ${y})`),
  10061. ReadonlyArray_bindTo("transform"),
  10062. x =>
  10063. Effect_sync(() =>
  10064. chat.element.animate(x, {
  10065. duration: 6400,
  10066. easing: mainState.config.timingFunction,
  10067. })
  10068. ),
  10069. Effect_tap(x =>
  10070. Effect_sync(() => {
  10071. x.onfinish = () => {
  10072. chat.animationEnded = !0
  10073. }
  10074. chat.y = ctx.laneY
  10075. const newTime = 6400 * ctx.progress
  10076. x.currentTime = newTime
  10077. })
  10078. ),
  10079. Effect_flatMap(x =>
  10080. Effect_sync(() => {
  10081. chat.animation = Option_some(x)
  10082. })
  10083. ),
  10084. Effect_zipRight(setChatPlayState(chat)(mainState))
  10085. ),
  10086. ],
  10087. x => Effect_all(x)
  10088. )
  10089. ),
  10090. Effect_isSuccess
  10091. ),
  10092. tapEffect = f =>
  10093. (0, external_rxjs_namespaceObject.concatMap)(x =>
  10094. (0, external_rxjs_namespaceObject.from)(runPromise(f(x))).pipe(
  10095. (0, external_rxjs_namespaceObject.map)(() => x)
  10096. )
  10097. ),
  10098. configStream = (provideLog, mainState, co, chatScreen, live) =>
  10099. (0, external_rxjs_namespaceObject.defer)(() =>
  10100. (0, external_rxjs_namespaceObject.merge)(
  10101. (0, external_rxjs_namespaceObject.merge)(
  10102. co.bannedWordRegexes,
  10103. co.bannedWords,
  10104. co.bannedUsers
  10105. ),
  10106. pipe(
  10107. co.fieldScale,
  10108. (0, external_rxjs_namespaceObject.startWith)(
  10109. mainState.config.fieldScale
  10110. ),
  10111. (0, external_rxjs_namespaceObject.map)(
  10112. (
  10113. live => scale =>
  10114. pipe(
  10115. live.chatField.ele,
  10116. Effect_flatMap(field =>
  10117. pipe(
  10118. [
  10119. pipe(
  10120. fromNullable(field.parentElement),
  10121. Option_map(x =>
  10122. Effect_sync(() =>
  10123. Object.assign(x.style, {
  10124. transformOrigin:
  10125. (scale >= 1 ? "top" : "bottom") + " left",
  10126. transform: `scale(${scale})`,
  10127. width: 100 / scale + "%",
  10128. height: 100 / scale + "%",
  10129. })
  10130. )
  10131. )
  10132. ),
  10133. pipe(
  10134. live.chatScroller.ele,
  10135. Option_map(scroller =>
  10136. Effect_sync(() => {
  10137. scroller.scrollTop = scroller.scrollHeight
  10138. })
  10139. )
  10140. ),
  10141. ],
  10142. ReadonlyArray_compact,
  10143. x => Effect_all(x)
  10144. )
  10145. ),
  10146. Effect_ignore
  10147. )
  10148. )(live)
  10149. ),
  10150. tapEffect(provideLog)
  10151. ),
  10152. pipe(
  10153. (0, external_rxjs_namespaceObject.merge)(
  10154. pipe(
  10155. (0, external_rxjs_namespaceObject.merge)(
  10156. co.font,
  10157. co.fontSize,
  10158. co.fontWeight,
  10159. co.laneCount,
  10160. co.minSpacing,
  10161. co.flowY1,
  10162. co.flowY2,
  10163. pipe(
  10164. co.flowX1,
  10165. (0, external_rxjs_namespaceObject.startWith)(
  10166. mainState.config.flowX1
  10167. ),
  10168. tapEffect(x =>
  10169. provideLog(
  10170. Effect_sync(() =>
  10171. Object.assign(chatScreen.style, {
  10172. left: 100 * x + "%",
  10173. width: 100 * (mainState.config.flowX2 - x) + "%",
  10174. })
  10175. )
  10176. )
  10177. )
  10178. ),
  10179. pipe(
  10180. co.flowX2,
  10181. tapEffect(x =>
  10182. provideLog(
  10183. Effect_sync(() =>
  10184. Object.assign(chatScreen.style, {
  10185. left: 100 * mainState.config.flowX1 + "%",
  10186. width: 100 * (x - mainState.config.flowX1) + "%",
  10187. })
  10188. )
  10189. )
  10190. )
  10191. ),
  10192. co.textOnly
  10193. ),
  10194. (0, external_rxjs_namespaceObject.map)(() => ({
  10195. render: !0,
  10196. setAnimation: !0,
  10197. }))
  10198. ),
  10199. pipe(
  10200. (0, external_rxjs_namespaceObject.merge)(
  10201. co.color,
  10202. co.ownerColor,
  10203. co.moderatorColor,
  10204. co.memberColor,
  10205. co.shadowColor,
  10206. co.chatOpacity,
  10207. co.shadowFontWeight,
  10208. co.displayChats
  10209. ),
  10210. (0, external_rxjs_namespaceObject.map)(() => ({ render: !0 }))
  10211. ),
  10212. pipe(
  10213. co.flowSpeed,
  10214. (0, external_rxjs_namespaceObject.map)(() => ({
  10215. setPlayState: !0,
  10216. }))
  10217. ),
  10218. pipe(
  10219. (0, external_rxjs_namespaceObject.merge)(
  10220. pipe(
  10221. co.maxChatCount,
  10222. (0, external_rxjs_namespaceObject.map)(
  10223. removeOldChats(mainState)
  10224. ),
  10225. tapEffect(provideLog)
  10226. ),
  10227. co.noOverlap,
  10228. co.timingFunction
  10229. ),
  10230. (0, external_rxjs_namespaceObject.map)(() => ({
  10231. setAnimation: !0,
  10232. }))
  10233. )
  10234. ),
  10235. (0, external_rxjs_namespaceObject.throttleTime)(180, void 0, {
  10236. leading: !0,
  10237. trailing: !0,
  10238. }),
  10239. (0, external_rxjs_namespaceObject.map)(x => ({
  10240. render: !1,
  10241. setAnimation: !1,
  10242. setPlayState: !1,
  10243. ...x,
  10244. })),
  10245. tapEffect(c =>
  10246. provideLog(
  10247. pipe(
  10248. mainState.flowChats,
  10249. ReadonlyArray_filter(x => !x.animationEnded),
  10250. ReadonlyArray_map(chat =>
  10251. pipe(
  10252. [
  10253. pipe(
  10254. renderChat(chat),
  10255. liftPredicate(() => c.render)
  10256. ),
  10257. c.setAnimation
  10258. ? Option_some(setChatAnimation(chat))
  10259. : c.setPlayState
  10260. ? Option_some(setChatPlayState(chat))
  10261. : Option_none(),
  10262. ],
  10263. ReadonlyArray_compact,
  10264. ReadonlyArray_map(apply(mainState)),
  10265. x => Effect_all(x)
  10266. )
  10267. ),
  10268. x => Effect_all(x),
  10269. Effect_asUnit
  10270. )
  10271. )
  10272. )
  10273. ),
  10274. co.lang,
  10275. co.maxChatLength,
  10276. co.simplifyChatField,
  10277. co.createBanButton,
  10278. co.createChats,
  10279. co.displayModName,
  10280. co.displaySuperChatAuthor,
  10281. co.fieldScale
  10282. )
  10283. ),
  10284. external_jsep_namespaceObject = jsep
  10285. var external_jsep_default = __webpack_require__.n(
  10286. external_jsep_namespaceObject
  10287. ),
  10288. u = {
  10289. "||": function (r, e) {
  10290. return r || e
  10291. },
  10292. "&&": function (r, e) {
  10293. return r && e
  10294. },
  10295. "|": function (r, e) {
  10296. return r | e
  10297. },
  10298. "^": function (r, e) {
  10299. return r ^ e
  10300. },
  10301. "&": function (r, e) {
  10302. return r & e
  10303. },
  10304. "==": function (r, e) {
  10305. return r == e
  10306. },
  10307. "!=": function (r, e) {
  10308. return r != e
  10309. },
  10310. "===": function (r, e) {
  10311. return r === e
  10312. },
  10313. "!==": function (r, e) {
  10314. return r !== e
  10315. },
  10316. "<": function (r, e) {
  10317. return r < e
  10318. },
  10319. ">": function (r, e) {
  10320. return r > e
  10321. },
  10322. "<=": function (r, e) {
  10323. return r <= e
  10324. },
  10325. ">=": function (r, e) {
  10326. return r >= e
  10327. },
  10328. "<<": function (r, e) {
  10329. return r << e
  10330. },
  10331. ">>": function (r, e) {
  10332. return r >> e
  10333. },
  10334. ">>>": function (r, e) {
  10335. return r >>> e
  10336. },
  10337. "+": function (r, e) {
  10338. return r + e
  10339. },
  10340. "-": function (r, e) {
  10341. return r - e
  10342. },
  10343. "*": function (r, e) {
  10344. return r * e
  10345. },
  10346. "/": function (r, e) {
  10347. return r / e
  10348. },
  10349. "%": function (r, e) {
  10350. return r % e
  10351. },
  10352. },
  10353. i = {
  10354. "-": function (r) {
  10355. return -r
  10356. },
  10357. "+": function (r) {
  10358. return +r
  10359. },
  10360. "~": function (r) {
  10361. return ~r
  10362. },
  10363. "!": function (r) {
  10364. return !r
  10365. },
  10366. }
  10367. function s(r, e) {
  10368. return r.map(function (r) {
  10369. return a(r, e)
  10370. })
  10371. }
  10372. function c(r, e) {
  10373. var n,
  10374. t = a(r.object, e)
  10375. if (
  10376. ((n = r.computed ? a(r.property, e) : r.property.name),
  10377. /^__proto__|prototype|constructor$/.test(n))
  10378. )
  10379. throw Error('Access to member "' + n + '" disallowed.')
  10380. return [t, t[n]]
  10381. }
  10382. function a(r, e) {
  10383. var n = r
  10384. switch (n.type) {
  10385. case "ArrayExpression":
  10386. return s(n.elements, e)
  10387. case "BinaryExpression":
  10388. return u[n.operator](a(n.left, e), a(n.right, e))
  10389. case "CallExpression":
  10390. var t, o, l
  10391. if (
  10392. ("MemberExpression" === n.callee.type
  10393. ? ((t = (l = c(n.callee, e))[0]), (o = l[1]))
  10394. : (o = a(n.callee, e)),
  10395. "function" != typeof o)
  10396. )
  10397. return
  10398. return o.apply(t, s(n.arguments, e))
  10399. case "ConditionalExpression":
  10400. return a(n.test, e) ? a(n.consequent, e) : a(n.alternate, e)
  10401. case "Identifier":
  10402. return e[n.name]
  10403. case "Literal":
  10404. return n.value
  10405. case "LogicalExpression":
  10406. return "||" === n.operator
  10407. ? a(n.left, e) || a(n.right, e)
  10408. : "&&" === n.operator
  10409. ? a(n.left, e) && a(n.right, e)
  10410. : u[n.operator](a(n.left, e), a(n.right, e))
  10411. case "MemberExpression":
  10412. return c(n, e)[1]
  10413. case "ThisExpression":
  10414. return e
  10415. case "UnaryExpression":
  10416. return i[n.operator](a(n.argument, e))
  10417. default:
  10418. return
  10419. }
  10420. }
  10421. const defaultFilter = config =>
  10422. external_jsep_default()(
  10423. `\nor([\nRA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  10424. config.bannedWords
  10425. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nRA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  10426. config.bannedWordRegexes
  10427. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nO.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  10428. config.bannedUsers
  10429. )})\n)(authorID)\n])\n`
  10430. ),
  10431. Chainable_bind = F =>
  10432. Function_dual(3, (self, name, f) =>
  10433. F.flatMap(self, a =>
  10434. F.map(f(a), b => Object.assign({}, a, { [name]: b }))
  10435. )
  10436. ),
  10437. Identity_map = Function_dual(2, (self, f) => f(self)),
  10438. Identity_imap = imap(Identity_map),
  10439. Identity_Covariant = { imap: Identity_imap, map: Identity_map },
  10440. Identity_Invariant = { imap: Identity_imap },
  10441. Identity_Chainable = {
  10442. imap: Identity_imap,
  10443. map: Identity_map,
  10444. flatMap: Function_dual(2, (self, f) => f(self)),
  10445. },
  10446. Identity_bindTo = Invariant_bindTo(Identity_Invariant),
  10447. Identity_let_ = let_(Identity_Covariant),
  10448. Identity_bind = Chainable_bind(Identity_Chainable),
  10449. Identity_letDiscard = letDiscard(Identity_Chainable),
  10450. external_astring_namespaceObject = astring,
  10451. fycKey = key => `FYC_${key}`,
  10452. languages = ["FYC_EN", "FYC_JA"],
  10453. stringsArgs = [
  10454. [],
  10455. flow(split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty))),
  10456. join("\n"),
  10457. ],
  10458. sc = (k, d) => {
  10459. return (
  10460. (key = fycKey(k)),
  10461. (defaultValue = d),
  10462. {
  10463. gmKey: key,
  10464. getValue: Effect_promise(
  10465. async () => await GM.getValue(key, defaultValue)
  10466. ),
  10467. defaultValue,
  10468. toGm: Function_identity,
  10469. }
  10470. )
  10471. var key, defaultValue
  10472. },
  10473. ic = (k, d, c, g) => {
  10474. return (
  10475. (key = fycKey(k)),
  10476. (toConfig = c),
  10477. pipe(
  10478. { gmKey: key, defaultValue: (defaultValue = d), toGm: g },
  10479. Identity_letDiscard(
  10480. "getValue",
  10481. pipe(
  10482. Effect_promise(() => GM.getValue(key)),
  10483. Effect_map(x => (void 0 !== x ? toConfig(x) : defaultValue))
  10484. )
  10485. )
  10486. )
  10487. )
  10488. var key, defaultValue, toConfig
  10489. },
  10490. src_defaultGMConfig = pipe(
  10491. {
  10492. lang: ic(
  10493. "LANG",
  10494. "FYC_EN",
  10495. x => (languages.includes(x) ? x : "FYC_EN"),
  10496. x => x
  10497. ),
  10498. font: sc("FONT", "MS PGothic"),
  10499. chatOpacity: sc("OPACITY", 0.8),
  10500. color: sc("COLOR", "#ffffff"),
  10501. ownerColor: sc("COLOR_OWNER", "#ffd600"),
  10502. moderatorColor: sc("COLOR_MODERATOR", "#c564ff"),
  10503. memberColor: sc("COLOR_MEMBER", "#9fffff"),
  10504. fontSize: sc("SIZE", 1),
  10505. fontWeight: sc("WEIGHT", 730),
  10506. shadowFontWeight: sc("WEIGHT_SHADOW", 1),
  10507. maxChatCount: sc("LIMIT", 40),
  10508. flowSpeed: sc("SPEED", 18),
  10509. maxChatLength: sc("MAX", 100),
  10510. laneCount: sc("LANE_DIV", 12),
  10511. bannedWords: ic("NG_WORDS", ...stringsArgs),
  10512. bannedWordRegexes: ic("NG_REG_WORDS", ...stringsArgs),
  10513. bannedUsers: ic("NG_USERS", ...stringsArgs),
  10514. createChats: sc("TOGGLE_CREATE_COMMENTS", !0),
  10515. noOverlap: sc("NO_OVERLAP", !0),
  10516. createBanButton: sc("NG_BUTTON", !0),
  10517. simplifyChatField: sc("SIMPLE_CHAT_FIELD", !1),
  10518. displayModName: sc("DISPLAY_MODERATOR_NAME", !0),
  10519. displaySuperChatAuthor: sc("DISPLAY_SUPER_CHAT_AUTHOR", !0),
  10520. textOnly: sc("TEXT_ONLY", !1),
  10521. timingFunction: sc("TIMING_FUNCTION", "linear"),
  10522. displayChats: sc("DISPLAY_COMMENTS", !0),
  10523. minSpacing: sc("MIN_SPACING", 0.5),
  10524. fieldScale: sc("FIELD_SCALE", 1),
  10525. flowY1: sc("flowY1", 0),
  10526. flowY2: sc("flowY2", 1),
  10527. flowX1: sc("flowX1", 0),
  10528. flowX2: sc("flowX2", 1),
  10529. shadowColor: sc("shadowColor", "#000000"),
  10530. logEvents: sc("logEvents", !0),
  10531. },
  10532. Identity_bind("filterExp", x =>
  10533. ic(
  10534. "filterExp",
  10535. external_jsep_default()(
  10536. `\n or([\n RA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  10537. x.bannedWords.defaultValue
  10538. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n RA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  10539. x.bannedWordRegexes.defaultValue
  10540. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n O.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  10541. x.bannedUsers.defaultValue
  10542. )})\n )(authorID)\n ])\n `
  10543. ),
  10544. external_jsep_default(),
  10545. external_astring_namespaceObject.generate
  10546. )
  10547. )
  10548. ),
  10549. src_listeningBroadcastConfigKeys = [
  10550. "lang",
  10551. "bannedWords",
  10552. "bannedWordRegexes",
  10553. "bannedUsers",
  10554. "filterExp",
  10555. "simplifyChatField",
  10556. "createBanButton",
  10557. "fieldScale",
  10558. ],
  10559. chatApp = pipe(
  10560. Effect_sync(() => document.querySelector("#chatframe")),
  10561. Effect_flatMap(
  10562. flow(
  10563. fromNullable,
  10564. Option_filter(
  10565. flow(
  10566. x => x.contentDocument?.readyState,
  10567. x => "loading" === x || "complete" === x
  10568. )
  10569. ),
  10570. flatMapNullable(x => x.contentDocument),
  10571. orElse(() => Option_some(document)),
  10572. flatMapNullable(x => x.querySelector("yt-live-chat-app"))
  10573. )
  10574. )
  10575. ),
  10576. livePageYt = {
  10577. toggleChatBtnParent: pipe(
  10578. Effect_sync(() => document.querySelector(".ytp-right-controls")),
  10579. Effect_flatMap(fromNullable)
  10580. ),
  10581. settingsToggleNextElement: pipe(
  10582. Effect_sync(() => document.querySelector("#menu-container")),
  10583. Effect_flatMap(
  10584. flow(
  10585. fromNullable,
  10586. Option_filter(x => null !== x.offsetParent),
  10587. flatMapNullable(x =>
  10588. x.querySelector(".dropdown-trigger.ytd-menu-renderer")
  10589. ),
  10590. orElse(() =>
  10591. fromNullable(
  10592. document.querySelector(
  10593. "#top-row .dropdown-trigger.ytd-menu-renderer"
  10594. )
  10595. )
  10596. )
  10597. )
  10598. )
  10599. ),
  10600. settingsContainer: pipe(
  10601. Effect_sync(() => document.body),
  10602. Effect_flatMap(fromNullable)
  10603. ),
  10604. player: pipe(
  10605. Effect_sync(() => document.querySelector("#movie_player")),
  10606. Effect_flatMap(fromNullable)
  10607. ),
  10608. video: pipe(
  10609. Effect_sync(() =>
  10610. document.querySelector("video.video-stream.html5-main-video")
  10611. ),
  10612. Effect_flatMap(fromNullable)
  10613. ),
  10614. chatField: pipe(
  10615. chatApp,
  10616. Effect_flatMap(
  10617. flow(
  10618. x => x.querySelector("#items.yt-live-chat-item-list-renderer"),
  10619. fromNullable
  10620. )
  10621. )
  10622. ),
  10623. chatTicker: pipe(
  10624. chatApp,
  10625. Effect_flatMap(
  10626. flow(
  10627. x => x.querySelector("#items.yt-live-chat-ticker-renderer"),
  10628. fromNullable
  10629. )
  10630. )
  10631. ),
  10632. chatScroller: pipe(
  10633. chatApp,
  10634. Effect_flatMap(
  10635. flow(
  10636. x =>
  10637. x.querySelector(
  10638. "#item-scroller.yt-live-chat-item-list-renderer"
  10639. ),
  10640. fromNullable
  10641. )
  10642. )
  10643. ),
  10644. offlineSlate: pipe(
  10645. Effect_sync(() => document.querySelector(".ytp-offline-slate")),
  10646. Effect_flatMap(fromNullable)
  10647. ),
  10648. },
  10649. FiberRef_locally = fiberRefLocally,
  10650. logMeta = fiberRefUnsafeMake(Option_none()),
  10651. logWithMeta = level => message => data =>
  10652. pipe(
  10653. Effect_log(message),
  10654. FiberRef_locally(logMeta, Option_some(data)),
  10655. x => locally(level)(x)
  10656. ),
  10657. mainCss = pipe(
  10658. Effect_sync(() => document.createElement("style")),
  10659. Effect_tap(x =>
  10660. Effect_sync(() => {
  10661. x.innerHTML =
  10662. ".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}"
  10663. })
  10664. )
  10665. ),
  10666. makeChatScreen = pipe(
  10667. Effect_sync(() => document.createElement("div")),
  10668. Effect_tap(x =>
  10669. Effect_sync(() =>
  10670. Object.assign(x.style, {
  10671. pointerEvents: "none",
  10672. zIndex: "30",
  10673. position: "absolute",
  10674. overflow: "hidden",
  10675. height: "100%",
  10676. width: "100%",
  10677. })
  10678. )
  10679. )
  10680. ),
  10681. observePair = con =>
  10682. pipe(
  10683. Effect_Do(),
  10684. Effect_bindDiscard(
  10685. "subject",
  10686. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  10687. ),
  10688. Effect_bind("observer", x =>
  10689. Effect_sync(() => new con(lib(x.subject)))
  10690. )
  10691. ),
  10692. emptyElement = document.createElement("span"),
  10693. appendChatMessage = flip(chat =>
  10694. Effect_flatMap(x =>
  10695. Effect_sync(() => chat.querySelector("#content #message")?.append(x))
  10696. )
  10697. ),
  10698. external_Swal_namespaceObject = Swal
  10699. var external_Swal_default = __webpack_require__.n(
  10700. external_Swal_namespaceObject
  10701. )
  10702. const defaultToast = external_Swal_default().mixin({
  10703. toast: !0,
  10704. position: "bottom-left",
  10705. timer: 2500,
  10706. timerProgressBar: !0,
  10707. showConfirmButton: !1,
  10708. didOpen: toast => {
  10709. toast.addEventListener(
  10710. "pointerenter",
  10711. external_Swal_default().stopTimer
  10712. )
  10713. toast.addEventListener(
  10714. "pointerleave",
  10715. external_Swal_default().resumeTimer
  10716. )
  10717. },
  10718. }),
  10719. template = runPromise(
  10720. pipe(
  10721. document.createElement("button"),
  10722. Effect_succeed,
  10723. Effect_tap(x =>
  10724. Effect_sync(() =>
  10725. x.classList.add("style-scope", "yt-icon-button", "fyc_button")
  10726. )
  10727. ),
  10728. Effect_tap(x =>
  10729. Effect_sync(() =>
  10730. Object.assign(x.style, {
  10731. padding: "0px",
  10732. width: "20px",
  10733. height: "20px",
  10734. fill: "#fff",
  10735. })
  10736. )
  10737. ),
  10738. Effect_tap(x =>
  10739. Effect_sync(() =>
  10740. x.setAttribute("aria-label", "NGに入れる(Ban this user)")
  10741. )
  10742. ),
  10743. Effect_tap(x =>
  10744. Effect_sync(() => {
  10745. x.innerHTML =
  10746. '<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>'
  10747. })
  10748. )
  10749. )
  10750. ),
  10751. filter_filterOperators = {
  10752. flip,
  10753. flow: fns => flow(...fns),
  10754. and: Monoid_booleanEvery.combineAll,
  10755. or: Monoid_booleanSome.combineAll,
  10756. RA: { some: ReadonlyArray_some, compact: ReadonlyArray_compact },
  10757. O: { exists },
  10758. inText: text => x => includes(x)(text.content),
  10759. eqText: text => x => text.content === x,
  10760. matchedByText: text => x => Boolean(text.content.match(RegExp(x, "u"))),
  10761. isVisible: x => x.visible,
  10762. }
  10763. var typed_assert_build = __webpack_require__(52)
  10764. const tapNonNull = (x, message) => {
  10765. typed_assert_build.Xd(x, message)
  10766. return x
  10767. },
  10768. parseChat = chat => {
  10769. const chatType = chat.querySelector(
  10770. ".yt-live-chat-ticker-paid-message-item-renderer"
  10771. )
  10772. ? "ticker"
  10773. : chat.querySelector(".yt-live-chat-membership-item-renderer")
  10774. ? "membership"
  10775. : chat.querySelector(
  10776. ".yt-live-chat-viewer-engagement-message-renderer"
  10777. )
  10778. ? "engagement"
  10779. : "normal",
  10780. isPaid =
  10781. "ticker" === chatType || Boolean(chat.querySelector("#card")),
  10782. paymentInfo = pipe(
  10783. fromNullable(
  10784. isPaid
  10785. ? chat.querySelector(
  10786. join(", ")([
  10787. "#purchase-amount",
  10788. "#purchase-amount-chip",
  10789. "#content>#text",
  10790. ])
  10791. )?.textContent
  10792. : void 0
  10793. ),
  10794. Option_map(x => ({ visible: !0, content: x }))
  10795. ),
  10796. authorType = chat.querySelector(".owner")
  10797. ? "owner"
  10798. : chat.querySelector(".moderator")
  10799. ? "moderator"
  10800. : chat.querySelector(".member")
  10801. ? "member"
  10802. : "normal",
  10803. messageElement = fromNullable(chat.querySelector("#message")),
  10804. isPaidNormal =
  10805. !!Option_isSome(paymentInfo) &&
  10806. Boolean(chat.querySelector(".yt-live-chat-paid-message-renderer")),
  10807. isPaidSticker =
  10808. !(!Option_isSome(paymentInfo) || isPaidNormal) &&
  10809. Boolean(chat.querySelector(".yt-live-chat-paid-sticker-renderer")),
  10810. textColor = fromNullable(
  10811. isPaidNormal
  10812. ? window
  10813. .getComputedStyle(tapNonNull(chat.querySelector("#header")))
  10814. .getPropertyValue("background-color")
  10815. : isPaidSticker
  10816. ? window
  10817. .getComputedStyle(chat)
  10818. .getPropertyValue(
  10819. "--yt-live-chat-paid-sticker-chip-background-color"
  10820. )
  10821. : void 0
  10822. ),
  10823. paidColor = fromNullable(
  10824. isPaidNormal
  10825. ? window
  10826. .getComputedStyle(tapNonNull(chat.querySelector("#content")))
  10827. .getPropertyValue("background-color")
  10828. : isPaidSticker
  10829. ? window
  10830. .getComputedStyle(chat)
  10831. .getPropertyValue(
  10832. "--yt-live-chat-paid-sticker-background-color"
  10833. )
  10834. : void 0
  10835. ),
  10836. authorPhotoMatches = chat
  10837. .querySelector(join(" ")(["#author-photo", "img"]))
  10838. ?.src.match(/ggpht\.com\/(ytc\/)?(.*)=/),
  10839. authorID = fromNullable(authorPhotoMatches?.at(-1)),
  10840. authorName = fromNullable(
  10841. chat.querySelector("#author-name")?.textContent
  10842. ),
  10843. message = pipe(
  10844. messageElement,
  10845. Option_map(x => ({ visible: !0, content: x.innerHTML }))
  10846. ),
  10847. messageText = pipe(
  10848. messageElement,
  10849. Option_map(x => ({ visible: !0, content: x.textContent ?? "" }))
  10850. )
  10851. return config => ({
  10852. chatType,
  10853. authorType,
  10854. authorID,
  10855. authorName: pipe(
  10856. authorName,
  10857. Option_map(x => ({
  10858. visible:
  10859. ("moderator" === authorType && config.displayModName) ||
  10860. (Option_isSome(paymentInfo) && config.displaySuperChatAuthor),
  10861. content: x,
  10862. }))
  10863. ),
  10864. messageElement,
  10865. message,
  10866. messageText,
  10867. paymentInfo,
  10868. textColor,
  10869. paidColor,
  10870. })
  10871. },
  10872. onChatFieldMutate = (chatScrn, mainState, getConfig, setConfig) =>
  10873. flow(
  10874. ReadonlyArray_flatMap(e => Array.from(e.addedNodes)),
  10875. ReadonlyArray_filter(x => x.children.length > 0),
  10876. ReadonlyArray_reverse,
  10877. ReadonlyArray_map(chat =>
  10878. pipe(
  10879. { getData: parseChat(chat), config: mainState.config },
  10880. Identity_let_("data", x => x.getData(x.config)),
  10881. Effect_succeed,
  10882. Effect_zipLeft(Effect_logDebug("Chat detected")),
  10883. Effect_bind("banned", x => {
  10884. return pipe(
  10885. ((data = x.data),
  10886. (config = x.config),
  10887. pipe(
  10888. data,
  10889. liftPredicate(() =>
  10890. pipe(config.filterExp, x =>
  10891. a(
  10892. x,
  10893. (data => ({
  10894. ...filter_filterOperators,
  10895. authorName: data.authorName,
  10896. message: data.message,
  10897. messageText: data.messageText,
  10898. paymentInfo: data.paymentInfo,
  10899. authorID: pipe(
  10900. data.authorID,
  10901. Option_map(x => ({ visible: !1, content: x }))
  10902. ),
  10903. }))(data)
  10904. )
  10905. )
  10906. ),
  10907. Option_map(x => [
  10908. pipe(
  10909. x.message,
  10910. Option_map(m => m.content)
  10911. ),
  10912. pipe(
  10913. x.paymentInfo,
  10914. Option_map(p => p.content)
  10915. ),
  10916. ]),
  10917. Option_map(ReadonlyArray_map(getOrElse(() => ""))),
  10918. Option_map(JSON.stringify),
  10919. Effect_flatMap(x => Effect_logDebug(`Filtered: ${x}`)),
  10920. Effect_isSuccess
  10921. ))
  10922. )
  10923. var data, config
  10924. }),
  10925. Effect_flatMap(ctx =>
  10926. ctx.banned
  10927. ? Effect_sync(() => {
  10928. chat.style.display = "none"
  10929. })
  10930. : Effect_all([
  10931. pipe(
  10932. ctx.config.createChats &&
  10933. "normal" === ctx.data.chatType,
  10934. liftPredicate(Function_identity),
  10935. Effect_flatMap(() =>
  10936. ((getData, chatScrn, mainState) =>
  10937. pipe(
  10938. {
  10939. getData,
  10940. element: emptyElement,
  10941. lane: -1,
  10942. animation: Option_none(),
  10943. animationDuration: 0,
  10944. animationEnded: !1,
  10945. width: 2,
  10946. height: getChatFontSize(mainState),
  10947. y: 0,
  10948. },
  10949. x => getChatLane(x, 0)(mainState).interval,
  10950. intervalTooSmall,
  10951. x => x(mainState.config)
  10952. )
  10953. ? Effect_unit()
  10954. : pipe(
  10955. mainState.flowChats,
  10956. findFirstIndex(
  10957. chat =>
  10958. chat.animationEnded ||
  10959. mainState.flowChats.length >=
  10960. mainState.config.maxChatCount
  10961. ),
  10962. offScreenIndex =>
  10963. pipe(
  10964. offScreenIndex,
  10965. Option_map(index =>
  10966. pipe(
  10967. mainState.flowChats,
  10968. unsafeGet(index),
  10969. x => x.element
  10970. )
  10971. ),
  10972. getOrElse(() =>
  10973. document.createElement("span")
  10974. ),
  10975. Effect_succeed,
  10976. Effect_tap(element =>
  10977. pipe(
  10978. offScreenIndex,
  10979. match(
  10980. () =>
  10981. pipe(
  10982. Effect_sync(() =>
  10983. chatScrn.append(element)
  10984. ),
  10985. Effect_zipLeft(
  10986. Effect_logDebug(
  10987. "Flow chat added"
  10988. )
  10989. )
  10990. ),
  10991. i =>
  10992. pipe(
  10993. Effect_sync(
  10994. () =>
  10995. mainState.flowChats.splice(
  10996. i,
  10997. 1
  10998. )?.[0]?.animation ??
  10999. Option_none()
  11000. ),
  11001. Effect_some,
  11002. Effect_flatMap(oldAnimation =>
  11003. Effect_sync(() =>
  11004. oldAnimation.cancel()
  11005. )
  11006. ),
  11007. Effect_ignore
  11008. )
  11009. )
  11010. )
  11011. )
  11012. ),
  11013. Effect_flatMap(element =>
  11014. pipe(
  11015. {
  11016. getData,
  11017. element,
  11018. lane: -1,
  11019. animation: Option_none(),
  11020. animationDuration: 0,
  11021. animationEnded: !1,
  11022. width: 2,
  11023. height: getChatFontSize(mainState),
  11024. y: 0,
  11025. },
  11026. Effect_succeed,
  11027. Effect_zipLeft(
  11028. Effect_sync(() =>
  11029. element.classList.add("fyc_chat")
  11030. )
  11031. )
  11032. )
  11033. ),
  11034. Effect_flatMap(flowChat =>
  11035. pipe(
  11036. mainState,
  11037. Effect_succeed,
  11038. Effect_tap(renderChat(flowChat)),
  11039. Effect_flatMap(
  11040. setChatAnimation(flowChat)
  11041. ),
  11042. Effect_flatMap(x =>
  11043. x
  11044. ? Effect_sync(() =>
  11045. mainState.flowChats.push(flowChat)
  11046. )
  11047. : pipe(
  11048. Effect_sync(() =>
  11049. flowChat.element.remove()
  11050. ),
  11051. Effect_zipLeft(
  11052. Effect_logDebug(
  11053. "Flow chat removed"
  11054. )
  11055. )
  11056. )
  11057. )
  11058. )
  11059. )
  11060. ))(ctx.getData, chatScrn, mainState)
  11061. ),
  11062. Effect_ignore
  11063. ),
  11064. pipe(
  11065. ctx.data.authorID,
  11066. Option_filter(() => ctx.config.createBanButton),
  11067. Option_filter(() => !chat.children.namedItem("card")),
  11068. Effect_flatMap(x => {
  11069. return appendChatMessage(
  11070. ((id = x),
  11071. getConfig => setConfig => chat =>
  11072. pipe(
  11073. getConfig.bannedUsers,
  11074. Effect_filterOrFail(
  11075. x => !x.includes(id),
  11076. Option_none
  11077. ),
  11078. Effect_map(
  11079. flow(uniq(String_Equivalence), append(id))
  11080. ),
  11081. Effect_flatMap(x =>
  11082. pipe(
  11083. setConfig.bannedUsers(x),
  11084. Effect_zipRight(
  11085. Effect_sync(() =>
  11086. defaultToast.fire({
  11087. title: `Added Banned User: ${id}`,
  11088. icon: "success",
  11089. })
  11090. )
  11091. )
  11092. )
  11093. ),
  11094. Effect_ignore,
  11095. Effect_zipRight(
  11096. Effect_sync(() => {
  11097. chat.style.display = "none"
  11098. })
  11099. ),
  11100. onclick =>
  11101. pipe(
  11102. Effect_promise(() => template),
  11103. Effect_map(x => x.cloneNode(!0)),
  11104. Effect_tap(x =>
  11105. Effect_sync(() => {
  11106. x.onclick = () => runPromise(onclick)
  11107. })
  11108. )
  11109. )
  11110. ))(getConfig)(setConfig)(chat)
  11111. )(chat)
  11112. var id
  11113. }),
  11114. Effect_zipLeft(Effect_logDebug("Ban button added")),
  11115. Effect_ignore
  11116. ),
  11117. pipe(
  11118. ctx.config.simplifyChatField,
  11119. liftPredicate(Function_identity),
  11120. Effect_flatMap(() =>
  11121. (chat =>
  11122. chat.querySelector(
  11123. ".style-scope.yt-live-chat-paid-message-renderer"
  11124. )
  11125. ? Effect_unit()
  11126. : pipe(
  11127. [
  11128. "#author-photo",
  11129. "yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer",
  11130. ],
  11131. ReadonlyArray_map(x =>
  11132. fromNullable(chat.querySelector(x))
  11133. ),
  11134. ReadonlyArray_compact,
  11135. ReadonlyArray_map(x =>
  11136. Effect_sync(() => {
  11137. x.style.display = "none"
  11138. })
  11139. ),
  11140. append(
  11141. Effect_sync(() => {
  11142. chat.style.borderBottom =
  11143. "1px solid var(--yt-spec-text-secondary)"
  11144. })
  11145. ),
  11146. x => Effect_all(x)
  11147. ))(chat)
  11148. ),
  11149. Effect_zipLeft(Effect_logDebug("Chat simplified")),
  11150. Effect_ignore
  11151. ),
  11152. ])
  11153. )
  11154. )
  11155. ),
  11156. x => Effect_all(x)
  11157. ),
  11158. Editable_of = x => [x, Option_none()],
  11159. fromValueText = v => t => [v, Option_some([t, Option_none()])],
  11160. Editable_value = getFirst,
  11161. Editable_text = flow(getSecond, Option_map(getFirst)),
  11162. error = flow(getSecond, flatMap(getSecond)),
  11163. setValue = flow(constant, x => mapFirst(x)),
  11164. setText = x =>
  11165. mapSecond(
  11166. flow(
  11167. Option_map(mapFirst(constant(x))),
  11168. orElse(constant(Option_some([x, Option_none()])))
  11169. )
  11170. ),
  11171. hasError = flow(error, Option_isSome),
  11172. exceptions = ["timingFunction", "lang"],
  11173. isEditable = k => v =>
  11174. ("number" == typeof v ||
  11175. "string" == typeof v ||
  11176. (Array.isArray(v) && ("string" == typeof v[0] || 0 === v.length))) &&
  11177. !ReadonlyArray_some(x => x === k)(exceptions),
  11178. RefinedConstructorsTypeId = Symbol.for("@effect/data/Brand/Refined"),
  11179. nominal = () =>
  11180. Object.assign(args => args, {
  11181. [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
  11182. option: args => Option_some(args),
  11183. either: args => Either_right(args),
  11184. refine: _args => !0,
  11185. }),
  11186. external_LZString_namespaceObject = LZString,
  11187. makeCompressedLogBlock = nominal(),
  11188. makeLog = nominal(),
  11189. decompressBlock = x =>
  11190. pipe(
  11191. (0, external_LZString_namespaceObject.decompressFromUTF16)(x),
  11192. JSON.parse
  11193. ),
  11194. importLog = s =>
  11195. makeLog(
  11196. pipe(
  11197. "<" === s[0] ? s.slice(5, -6) : s,
  11198. x => JSON.parse(x),
  11199. x => ({
  11200. nextId: x.nextId,
  11201. ...pipe(
  11202. x.blocks,
  11203. mapNonEmpty(
  11204. external_LZString_namespaceObject.decompressFromEncodedURIComponent
  11205. ),
  11206. matchRight(
  11207. () => ({ compressedBlocks: [], lastBlock: [] }),
  11208. (init, last) => ({
  11209. compressedBlocks: ReadonlyArray_map(
  11210. init,
  11211. flow(
  11212. external_LZString_namespaceObject.compressToUTF16,
  11213. makeCompressedLogBlock
  11214. )
  11215. ),
  11216. lastBlock: JSON.parse(last),
  11217. })
  11218. )
  11219. ),
  11220. })
  11221. )
  11222. ),
  11223. settingStateInit = config =>
  11224. pipe(
  11225. config,
  11226. mapObject(([k, v]) => [
  11227. k,
  11228. isEditable(k)(v) ? Editable_of(v) : "filterExp" === k ? void 0 : v,
  11229. ]),
  11230. x => ({
  11231. ...x,
  11232. showPanel: !1,
  11233. mainTab: 0,
  11234. logTab: 0,
  11235. timingStepCount: Editable_of(
  11236. parseInt(
  11237. config.timingFunction.match(/^steps\((\d+),.+/)?.[1] ?? "150",
  11238. 10
  11239. )
  11240. ),
  11241. eventLog: makeLog({
  11242. nextId: 0,
  11243. compressedBlocks: [],
  11244. lastBlock: [],
  11245. }),
  11246. panelRect: new DOMRectReadOnly(0, 0, 660, 395),
  11247. })
  11248. )
  11249. var EMPTY_OBJ = {},
  11250. EMPTY_ARR = [],
  11251. hyperapp_id = a => a,
  11252. hyperapp_map = EMPTY_ARR.map,
  11253. isArray = Array.isArray,
  11254. enqueue =
  11255. "undefined" != typeof requestAnimationFrame
  11256. ? requestAnimationFrame
  11257. : setTimeout,
  11258. createClass = obj => {
  11259. var out = ""
  11260. if ("string" == typeof obj) return obj
  11261. if (isArray(obj))
  11262. for (var tmp, k = 0; k < obj.length; k++)
  11263. (tmp = createClass(obj[k])) && (out += (out && " ") + tmp)
  11264. else for (var k in obj) obj[k] && (out += (out && " ") + k)
  11265. return out
  11266. },
  11267. shouldRestart = (a, b) => {
  11268. for (var k in { ...a, ...b })
  11269. if ("function" == typeof (isArray(a[k]) ? a[k][0] : a[k])) b[k] = a[k]
  11270. else if (a[k] !== b[k]) return !0
  11271. },
  11272. getKey = vdom => (null == vdom ? vdom : vdom.key),
  11273. patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
  11274. if ("style" === key)
  11275. for (var k in { ...oldValue, ...newValue }) {
  11276. oldValue =
  11277. null == newValue || null == newValue[k] ? "" : newValue[k]
  11278. "-" === k[0]
  11279. ? node[key].setProperty(k, oldValue)
  11280. : (node[key][k] = oldValue)
  11281. }
  11282. else
  11283. "o" === key[0] && "n" === key[1]
  11284. ? ((node.events || (node.events = {}))[(key = key.slice(2))] =
  11285. newValue)
  11286. ? oldValue || node.addEventListener(key, listener)
  11287. : node.removeEventListener(key, listener)
  11288. : !isSvg && "list" !== key && "form" !== key && key in node
  11289. ? (node[key] = newValue ?? "")
  11290. : null == newValue || !1 === newValue
  11291. ? node.removeAttribute(key)
  11292. : node.setAttribute(key, newValue)
  11293. },
  11294. createNode = (vdom, listener, isSvg) => {
  11295. var props = vdom.props,
  11296. node =
  11297. 3 === vdom.type
  11298. ? document.createTextNode(vdom.tag)
  11299. : (isSvg = isSvg || "svg" === vdom.tag)
  11300. ? document.createElementNS(
  11301. "http://www.w3.org/2000/svg",
  11302. vdom.tag,
  11303. props.is && props
  11304. )
  11305. : document.createElement(vdom.tag, props.is && props)
  11306. for (var k in props)
  11307. patchProperty(node, k, null, props[k], listener, isSvg)
  11308. for (var i = 0; i < vdom.children.length; i++)
  11309. node.appendChild(
  11310. createNode(
  11311. (vdom.children[i] = maybeVNode(vdom.children[i])),
  11312. listener,
  11313. isSvg
  11314. )
  11315. )
  11316. return (vdom.node = node)
  11317. },
  11318. hyperapp_patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
  11319. if (oldVNode === newVNode);
  11320. else if (null != oldVNode && 3 === oldVNode.type && 3 === newVNode.type)
  11321. oldVNode.tag !== newVNode.tag && (node.nodeValue = newVNode.tag)
  11322. else if (null == oldVNode || oldVNode.tag !== newVNode.tag) {
  11323. node = parent.insertBefore(
  11324. createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
  11325. node
  11326. )
  11327. null != oldVNode && parent.removeChild(oldVNode.node)
  11328. } else {
  11329. var tmpVKid,
  11330. oldVKid,
  11331. oldKey,
  11332. newKey,
  11333. oldProps = oldVNode.props,
  11334. newProps = newVNode.props,
  11335. oldVKids = oldVNode.children,
  11336. newVKids = newVNode.children,
  11337. oldHead = 0,
  11338. newHead = 0,
  11339. oldTail = oldVKids.length - 1,
  11340. newTail = newVKids.length - 1
  11341. isSvg = isSvg || "svg" === newVNode.tag
  11342. for (var i in { ...oldProps, ...newProps })
  11343. ("value" === i || "selected" === i || "checked" === i
  11344. ? node[i]
  11345. : oldProps[i]) !== newProps[i] &&
  11346. patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
  11347. for (
  11348. ;
  11349. newHead <= newTail &&
  11350. oldHead <= oldTail &&
  11351. null != (oldKey = getKey(oldVKids[oldHead])) &&
  11352. oldKey === getKey(newVKids[newHead]);
  11353.  
  11354. )
  11355. hyperapp_patch(
  11356. node,
  11357. oldVKids[oldHead].node,
  11358. oldVKids[oldHead],
  11359. (newVKids[newHead] = maybeVNode(
  11360. newVKids[newHead++],
  11361. oldVKids[oldHead++]
  11362. )),
  11363. listener,
  11364. isSvg
  11365. )
  11366. for (
  11367. ;
  11368. newHead <= newTail &&
  11369. oldHead <= oldTail &&
  11370. null != (oldKey = getKey(oldVKids[oldTail])) &&
  11371. oldKey === getKey(newVKids[newTail]);
  11372.  
  11373. )
  11374. hyperapp_patch(
  11375. node,
  11376. oldVKids[oldTail].node,
  11377. oldVKids[oldTail],
  11378. (newVKids[newTail] = maybeVNode(
  11379. newVKids[newTail--],
  11380. oldVKids[oldTail--]
  11381. )),
  11382. listener,
  11383. isSvg
  11384. )
  11385. if (oldHead > oldTail)
  11386. for (; newHead <= newTail; )
  11387. node.insertBefore(
  11388. createNode(
  11389. (newVKids[newHead] = maybeVNode(newVKids[newHead++])),
  11390. listener,
  11391. isSvg
  11392. ),
  11393. (oldVKid = oldVKids[oldHead]) && oldVKid.node
  11394. )
  11395. else if (newHead > newTail)
  11396. for (; oldHead <= oldTail; )
  11397. node.removeChild(oldVKids[oldHead++].node)
  11398. else {
  11399. var keyed = {},
  11400. newKeyed = {}
  11401. for (i = oldHead; i <= oldTail; i++)
  11402. null != (oldKey = oldVKids[i].key) &&
  11403. (keyed[oldKey] = oldVKids[i])
  11404. for (; newHead <= newTail; ) {
  11405. oldKey = getKey((oldVKid = oldVKids[oldHead]))
  11406. newKey = getKey(
  11407. (newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid))
  11408. )
  11409. if (
  11410. newKeyed[oldKey] ||
  11411. (null != newKey && newKey === getKey(oldVKids[oldHead + 1]))
  11412. ) {
  11413. null == oldKey && node.removeChild(oldVKid.node)
  11414. oldHead++
  11415. } else if (null == newKey || 1 === oldVNode.type) {
  11416. if (null == oldKey) {
  11417. hyperapp_patch(
  11418. node,
  11419. oldVKid && oldVKid.node,
  11420. oldVKid,
  11421. newVKids[newHead],
  11422. listener,
  11423. isSvg
  11424. )
  11425. newHead++
  11426. }
  11427. oldHead++
  11428. } else {
  11429. if (oldKey === newKey) {
  11430. hyperapp_patch(
  11431. node,
  11432. oldVKid.node,
  11433. oldVKid,
  11434. newVKids[newHead],
  11435. listener,
  11436. isSvg
  11437. )
  11438. newKeyed[newKey] = !0
  11439. oldHead++
  11440. } else if (null != (tmpVKid = keyed[newKey])) {
  11441. hyperapp_patch(
  11442. node,
  11443. node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
  11444. tmpVKid,
  11445. newVKids[newHead],
  11446. listener,
  11447. isSvg
  11448. )
  11449. newKeyed[newKey] = !0
  11450. } else
  11451. hyperapp_patch(
  11452. node,
  11453. oldVKid && oldVKid.node,
  11454. null,
  11455. newVKids[newHead],
  11456. listener,
  11457. isSvg
  11458. )
  11459. newHead++
  11460. }
  11461. }
  11462. for (; oldHead <= oldTail; )
  11463. null == getKey((oldVKid = oldVKids[oldHead++])) &&
  11464. node.removeChild(oldVKid.node)
  11465. for (var i in keyed)
  11466. null == newKeyed[i] && node.removeChild(keyed[i].node)
  11467. }
  11468. }
  11469. return (newVNode.node = node)
  11470. },
  11471. maybeVNode = (newVNode, oldVNode) =>
  11472. !0 !== newVNode && !1 !== newVNode && newVNode
  11473. ? "function" == typeof newVNode.tag
  11474. ? ((!oldVNode ||
  11475. null == oldVNode.memo ||
  11476. ((a, b) => {
  11477. for (var k in a) if (a[k] !== b[k]) return !0
  11478. for (var k in b) if (a[k] !== b[k]) return !0
  11479. })(oldVNode.memo, newVNode.memo)) &&
  11480. ((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
  11481. oldVNode)
  11482. : newVNode
  11483. : hyperapp_text(""),
  11484. recycleNode = node =>
  11485. 3 === node.nodeType
  11486. ? hyperapp_text(node.nodeValue, node)
  11487. : createVNode(
  11488. node.nodeName.toLowerCase(),
  11489. EMPTY_OBJ,
  11490. hyperapp_map.call(node.childNodes, recycleNode),
  11491. 1,
  11492. node
  11493. ),
  11494. createVNode = (tag, { key, ...props }, children, type, node) => ({
  11495. tag,
  11496. props,
  11497. key,
  11498. children,
  11499. type,
  11500. node,
  11501. }),
  11502. hyperapp_text = (value, node) =>
  11503. createVNode(value, EMPTY_OBJ, EMPTY_ARR, 3, node),
  11504. h = (tag, { class: c, ...props }, children = EMPTY_ARR) =>
  11505. createVNode(
  11506. tag,
  11507. { ...props, ...(c ? { class: createClass(c) } : EMPTY_OBJ) },
  11508. isArray(children) ? children : [children]
  11509. ),
  11510. app = ({
  11511. node,
  11512. view,
  11513. subscriptions,
  11514. dispatch = hyperapp_id,
  11515. init = EMPTY_OBJ,
  11516. }) => {
  11517. var state,
  11518. busy,
  11519. vdom = node && recycleNode(node),
  11520. subs = [],
  11521. update = newState => {
  11522. if (state !== newState) {
  11523. null == (state = newState) &&
  11524. (dispatch = subscriptions = render = hyperapp_id)
  11525. subscriptions &&
  11526. (subs = ((oldSubs, newSubs = EMPTY_ARR, dispatch) => {
  11527. for (
  11528. var oldSub, newSub, subs = [], i = 0;
  11529. i < oldSubs.length || i < newSubs.length;
  11530. i++
  11531. ) {
  11532. oldSub = oldSubs[i]
  11533. newSub = newSubs[i]
  11534. subs.push(
  11535. newSub && !0 !== newSub
  11536. ? !oldSub ||
  11537. newSub[0] !== oldSub[0] ||
  11538. shouldRestart(newSub[1], oldSub[1])
  11539. ? [
  11540. newSub[0],
  11541. newSub[1],
  11542. (oldSub && oldSub[2](),
  11543. newSub[0](dispatch, newSub[1])),
  11544. ]
  11545. : oldSub
  11546. : oldSub && oldSub[2]()
  11547. )
  11548. }
  11549. return subs
  11550. })(subs, subscriptions(state), dispatch))
  11551. view && !busy && enqueue(render, (busy = !0))
  11552. }
  11553. },
  11554. render = () =>
  11555. (node = hyperapp_patch(
  11556. node.parentNode,
  11557. node,
  11558. vdom,
  11559. (vdom = view(state)),
  11560. listener,
  11561. (busy = !1)
  11562. )),
  11563. listener = function (event) {
  11564. dispatch(this.events[event.type], event)
  11565. }
  11566. return (
  11567. (dispatch = dispatch((action, props) =>
  11568. "function" == typeof action
  11569. ? dispatch(action(state, props))
  11570. : isArray(action)
  11571. ? "function" == typeof action[0]
  11572. ? dispatch(action[0], action[1])
  11573. : action
  11574. .slice(1)
  11575. .map(
  11576. fx => fx && !0 !== fx && (fx[0] || fx)(dispatch, fx[1]),
  11577. update(action[0])
  11578. )
  11579. : update(action)
  11580. ))(init),
  11581. dispatch
  11582. )
  11583. }
  11584. const makeComponent = x => tag => ({ tag, view: x(tag) }),
  11585. node_option = (value, label, selected) =>
  11586. h("option", { value, selected }, hyperapp_text(label)),
  11587. tabContainer = style => ontabSelect => labels => tabs => mainTab =>
  11588. h("div", { style: style.container }, [
  11589. h(
  11590. "div",
  11591. {},
  11592. pipe(
  11593. labels,
  11594. ReadonlyArray_map((x, i) =>
  11595. h(
  11596. "span",
  11597. {
  11598. style: {
  11599. ...style.label,
  11600. ...(mainTab === i ? style.labelFocus : {}),
  11601. display: "inline-block",
  11602. },
  11603. onpointerdown: [ontabSelect, i],
  11604. },
  11605. hyperapp_text(x)
  11606. )
  11607. )
  11608. )
  11609. ),
  11610. h(
  11611. "div",
  11612. {
  11613. style: {
  11614. ...style.tab,
  11615. overflow: "auto",
  11616. boxSizing: "border-box",
  11617. },
  11618. },
  11619. pipe(
  11620. tabs,
  11621. ReadonlyArray_get(mainTab),
  11622. match(
  11623. () => {},
  11624. x => x()
  11625. )
  11626. )
  11627. ),
  11628. ]),
  11629. defaultText = {
  11630. setting: ["Settings", "設定"],
  11631. font: ["Font", "フォント"],
  11632. color: ["Color(Normal)", "色(通常)"],
  11633. ownerColor: ["Color(Owner)", "色(オーナー)"],
  11634. moderatorColor: ["Color(Moderator)", "色(モデレーター)"],
  11635. memberColor: ["Color(Member)", "色(メンバー)"],
  11636. feedback: ["Feedback", "バグ報告と要望"],
  11637. eventLog: ["Event log", "イベントログ"],
  11638. giveFeedback: [
  11639. "Give your feedbacks here(Please attach the event log for bug reports)",
  11640. "バグ報告、要望はこちら(バグの場合は、イベントログを添付してください)",
  11641. ],
  11642. chatOpacity: ["Opacity", "不透明度"],
  11643. fontSize: ["Size", "サイズ"],
  11644. fontWeight: ["Weight", "太さ"],
  11645. shadowFontWeight: ["Weight(Shadow)", "太さ(影)"],
  11646. flowSpeed: ["Speed", "速度"],
  11647. maxChatCount: ["Max number of chats", "最大表示数"],
  11648. maxChatLength: ["Max number of characters", "最大文字数"],
  11649. laneCount: ["Number of rows", "行数"],
  11650. bannedWords: ["Banned Words", "NGワード"],
  11651. bannedWordRegexes: ["Banned Words(Regex)", "NGワード(正規表現)"],
  11652. bannedUsers: ["Banned Users", "NGユーザー"],
  11653. simplifyChatField: ["Simplify", "簡略化する"],
  11654. createBanButton: ["Show ban button", "NGボタンを表示する"],
  11655. displayModName: [
  11656. "Show moderator's name",
  11657. "モデレーターの名前を表示する",
  11658. ],
  11659. displaySuperChatAuthor: [
  11660. "Show super chat author",
  11661. "スパチャの作成者を表示する",
  11662. ],
  11663. createChats: ["Create flowing chats", "チャットを流す"],
  11664. textOnly: ["Text only(ignore emojis)", "文字のみ(絵文字を無視する)"],
  11665. error: ["Error", "エラー"],
  11666. video: ["Video", "画面"],
  11667. chatField: ["Chat Window", "チャット欄"],
  11668. useStepTiming: ["Move chat in steps", "チャットを段階的に動かす"],
  11669. timingStepCount: ["└Step Count", "└段階数"],
  11670. chatFilter: ["Chat Filter", "チャットフィルター"],
  11671. flowChat: ["Flow Chat", "チャット流れ"],
  11672. clearFlowChats: ["Clear Flowing Chats", "流れるチャットをクリアする"],
  11673. flowNewChatIf: [
  11674. "A new chat will appear if all of the followings are met:",
  11675. "新しいチャットは以下のすべてを満たす場合に流れます:",
  11676. ],
  11677. noOverlap: ["└Chats won't overlap", "└他のチャットと重ならない"],
  11678. minSpacing: ["Min spacing between chats", "チャットの最小間隔"],
  11679. fieldScale: ["Scale", "拡大率"],
  11680. copy: ["Copy", "コピーする"],
  11681. showChats: ["Show chats", "チャットを表示する"],
  11682. hideChats: ["Hide chats", "チャットを非表示にする"],
  11683. flowY1: ["Flow area top edge", "流れ範囲の上端"],
  11684. flowY2: ["Flow area bottom edge", "流れ範囲の下端"],
  11685. flowX1: ["Flow area left edge", "流れ範囲の左端"],
  11686. flowX2: ["Flow area right edge", "流れ範囲の右端"],
  11687. shadowColor: ["Color(Shadow)", "色(影)"],
  11688. invalidColor: ["Invalid color", "無効な色"],
  11689. inputNonNumberic: ["Input isn't a number", "入力値が数字でない"],
  11690. invalidSetting: ["Invalid setting", "無効な設定値"],
  11691. logEvents: ["Enable event logging", "イベントログを有効にする"],
  11692. importLog: ["Import event log", "イベントログを取り込む"],
  11693. },
  11694. getText = key => language =>
  11695. defaultText[key]["FYC_EN" === language ? 0 : 1],
  11696. languageLabels = ["English", "日本語"],
  11697. panelBoxStyle = width => ({
  11698. flex: `0 0 ${width}px`,
  11699. width: `${width}px`,
  11700. margin: "2px",
  11701. }),
  11702. computed = {
  11703. useStepTiming: s => Boolean(s.timingFunction.match(/^steps\(.+/)),
  11704. },
  11705. getState = k => (k in computed ? computed[k] : s => s[k])
  11706. var util, objectUtil
  11707. !(function (util) {
  11708. util.assertEqual = val => val
  11709. util.assertIs = function (_arg) {}
  11710. util.assertNever = function (_x) {
  11711. throw new Error()
  11712. }
  11713. util.arrayToEnum = items => {
  11714. const obj = {}
  11715. for (const item of items) obj[item] = item
  11716. return obj
  11717. }
  11718. util.getValidEnumValues = obj => {
  11719. const validKeys = util
  11720. .objectKeys(obj)
  11721. .filter(k => "number" != typeof obj[obj[k]]),
  11722. filtered = {}
  11723. for (const k of validKeys) filtered[k] = obj[k]
  11724. return util.objectValues(filtered)
  11725. }
  11726. util.objectValues = obj =>
  11727. util.objectKeys(obj).map(function (e) {
  11728. return obj[e]
  11729. })
  11730. util.objectKeys =
  11731. "function" == typeof Object.keys
  11732. ? obj => Object.keys(obj)
  11733. : object => {
  11734. const keys = []
  11735. for (const key in object)
  11736. Object.prototype.hasOwnProperty.call(object, key) &&
  11737. keys.push(key)
  11738. return keys
  11739. }
  11740. util.find = (arr, checker) => {
  11741. for (const item of arr) if (checker(item)) return item
  11742. }
  11743. util.isInteger =
  11744. "function" == typeof Number.isInteger
  11745. ? val => Number.isInteger(val)
  11746. : val =>
  11747. "number" == typeof val && isFinite(val) && Math.floor(val) === val
  11748. util.joinValues = function (array, separator = " | ") {
  11749. return array
  11750. .map(val => ("string" == typeof val ? `'${val}'` : val))
  11751. .join(separator)
  11752. }
  11753. util.jsonStringifyReplacer = (_, value) =>
  11754. "bigint" == typeof value ? value.toString() : value
  11755. })(util || (util = {}))
  11756. !(function (objectUtil) {
  11757. objectUtil.mergeShapes = (first, second) => ({ ...first, ...second })
  11758. })(objectUtil || (objectUtil = {}))
  11759. const ZodParsedType = util.arrayToEnum([
  11760. "string",
  11761. "nan",
  11762. "number",
  11763. "integer",
  11764. "float",
  11765. "boolean",
  11766. "date",
  11767. "bigint",
  11768. "symbol",
  11769. "function",
  11770. "undefined",
  11771. "null",
  11772. "array",
  11773. "object",
  11774. "unknown",
  11775. "promise",
  11776. "void",
  11777. "never",
  11778. "map",
  11779. "set",
  11780. ]),
  11781. getParsedType = data => {
  11782. switch (typeof data) {
  11783. case "undefined":
  11784. return ZodParsedType.undefined
  11785. case "string":
  11786. return ZodParsedType.string
  11787. case "number":
  11788. return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number
  11789. case "boolean":
  11790. return ZodParsedType.boolean
  11791. case "function":
  11792. return ZodParsedType.function
  11793. case "bigint":
  11794. return ZodParsedType.bigint
  11795. case "symbol":
  11796. return ZodParsedType.symbol
  11797. case "object":
  11798. return Array.isArray(data)
  11799. ? ZodParsedType.array
  11800. : null === data
  11801. ? ZodParsedType.null
  11802. : data.then &&
  11803. "function" == typeof data.then &&
  11804. data.catch &&
  11805. "function" == typeof data.catch
  11806. ? ZodParsedType.promise
  11807. : "undefined" != typeof Map && data instanceof Map
  11808. ? ZodParsedType.map
  11809. : "undefined" != typeof Set && data instanceof Set
  11810. ? ZodParsedType.set
  11811. : "undefined" != typeof Date && data instanceof Date
  11812. ? ZodParsedType.date
  11813. : ZodParsedType.object
  11814. default:
  11815. return ZodParsedType.unknown
  11816. }
  11817. },
  11818. ZodIssueCode = util.arrayToEnum([
  11819. "invalid_type",
  11820. "invalid_literal",
  11821. "custom",
  11822. "invalid_union",
  11823. "invalid_union_discriminator",
  11824. "invalid_enum_value",
  11825. "unrecognized_keys",
  11826. "invalid_arguments",
  11827. "invalid_return_type",
  11828. "invalid_date",
  11829. "invalid_string",
  11830. "too_small",
  11831. "too_big",
  11832. "invalid_intersection_types",
  11833. "not_multiple_of",
  11834. "not_finite",
  11835. ])
  11836. class ZodError extends Error {
  11837. constructor(issues) {
  11838. super()
  11839. this.issues = []
  11840. this.addIssue = sub => {
  11841. this.issues = [...this.issues, sub]
  11842. }
  11843. this.addIssues = (subs = []) => {
  11844. this.issues = [...this.issues, ...subs]
  11845. }
  11846. const actualProto = new.target.prototype
  11847. Object.setPrototypeOf
  11848. ? Object.setPrototypeOf(this, actualProto)
  11849. : (this.__proto__ = actualProto)
  11850. this.name = "ZodError"
  11851. this.issues = issues
  11852. }
  11853. get errors() {
  11854. return this.issues
  11855. }
  11856. format(_mapper) {
  11857. const mapper =
  11858. _mapper ||
  11859. function (issue) {
  11860. return issue.message
  11861. },
  11862. fieldErrors = { _errors: [] },
  11863. processError = error => {
  11864. for (const issue of error.issues)
  11865. if ("invalid_union" === issue.code)
  11866. issue.unionErrors.map(processError)
  11867. else if ("invalid_return_type" === issue.code)
  11868. processError(issue.returnTypeError)
  11869. else if ("invalid_arguments" === issue.code)
  11870. processError(issue.argumentsError)
  11871. else if (0 === issue.path.length)
  11872. fieldErrors._errors.push(mapper(issue))
  11873. else {
  11874. let curr = fieldErrors,
  11875. i = 0
  11876. for (; i < issue.path.length; ) {
  11877. const el = issue.path[i]
  11878. if (i === issue.path.length - 1) {
  11879. curr[el] = curr[el] || { _errors: [] }
  11880. curr[el]._errors.push(mapper(issue))
  11881. } else curr[el] = curr[el] || { _errors: [] }
  11882. curr = curr[el]
  11883. i++
  11884. }
  11885. }
  11886. }
  11887. processError(this)
  11888. return fieldErrors
  11889. }
  11890. toString() {
  11891. return this.message
  11892. }
  11893. get message() {
  11894. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2)
  11895. }
  11896. get isEmpty() {
  11897. return 0 === this.issues.length
  11898. }
  11899. flatten(mapper = issue => issue.message) {
  11900. const fieldErrors = {},
  11901. formErrors = []
  11902. for (const sub of this.issues)
  11903. if (sub.path.length > 0) {
  11904. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []
  11905. fieldErrors[sub.path[0]].push(mapper(sub))
  11906. } else formErrors.push(mapper(sub))
  11907. return { formErrors, fieldErrors }
  11908. }
  11909. get formErrors() {
  11910. return this.flatten()
  11911. }
  11912. }
  11913. ZodError.create = issues => new ZodError(issues)
  11914. const errorMap = (issue, _ctx) => {
  11915. let message
  11916. switch (issue.code) {
  11917. case ZodIssueCode.invalid_type:
  11918. message =
  11919. issue.received === ZodParsedType.undefined
  11920. ? "Required"
  11921. : `Expected ${issue.expected}, received ${issue.received}`
  11922. break
  11923. case ZodIssueCode.invalid_literal:
  11924. message = `Invalid literal value, expected ${JSON.stringify(
  11925. issue.expected,
  11926. util.jsonStringifyReplacer
  11927. )}`
  11928. break
  11929. case ZodIssueCode.unrecognized_keys:
  11930. message = `Unrecognized key(s) in object: ${util.joinValues(
  11931. issue.keys,
  11932. ", "
  11933. )}`
  11934. break
  11935. case ZodIssueCode.invalid_union:
  11936. message = "Invalid input"
  11937. break
  11938. case ZodIssueCode.invalid_union_discriminator:
  11939. message = `Invalid discriminator value. Expected ${util.joinValues(
  11940. issue.options
  11941. )}`
  11942. break
  11943. case ZodIssueCode.invalid_enum_value:
  11944. message = `Invalid enum value. Expected ${util.joinValues(
  11945. issue.options
  11946. )}, received '${issue.received}'`
  11947. break
  11948. case ZodIssueCode.invalid_arguments:
  11949. message = "Invalid function arguments"
  11950. break
  11951. case ZodIssueCode.invalid_return_type:
  11952. message = "Invalid function return type"
  11953. break
  11954. case ZodIssueCode.invalid_date:
  11955. message = "Invalid date"
  11956. break
  11957. case ZodIssueCode.invalid_string:
  11958. if ("object" == typeof issue.validation)
  11959. if ("includes" in issue.validation) {
  11960. message = `Invalid input: must include "${issue.validation.includes}"`
  11961. "number" == typeof issue.validation.position &&
  11962. (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)
  11963. } else
  11964. "startsWith" in issue.validation
  11965. ? (message = `Invalid input: must start with "${issue.validation.startsWith}"`)
  11966. : "endsWith" in issue.validation
  11967. ? (message = `Invalid input: must end with "${issue.validation.endsWith}"`)
  11968. : util.assertNever(issue.validation)
  11969. else
  11970. message =
  11971. "regex" !== issue.validation
  11972. ? `Invalid ${issue.validation}`
  11973. : "Invalid"
  11974. break
  11975. case ZodIssueCode.too_small:
  11976. message =
  11977. "array" === issue.type
  11978. ? `Array must contain ${
  11979. issue.exact
  11980. ? "exactly"
  11981. : issue.inclusive
  11982. ? "at least"
  11983. : "more than"
  11984. } ${issue.minimum} element(s)`
  11985. : "string" === issue.type
  11986. ? `String must contain ${
  11987. issue.exact
  11988. ? "exactly"
  11989. : issue.inclusive
  11990. ? "at least"
  11991. : "over"
  11992. } ${issue.minimum} character(s)`
  11993. : "number" === issue.type
  11994. ? `Number must be ${
  11995. issue.exact
  11996. ? "exactly equal to "
  11997. : issue.inclusive
  11998. ? "greater than or equal to "
  11999. : "greater than "
  12000. }${issue.minimum}`
  12001. : "date" === issue.type
  12002. ? `Date must be ${
  12003. issue.exact
  12004. ? "exactly equal to "
  12005. : issue.inclusive
  12006. ? "greater than or equal to "
  12007. : "greater than "
  12008. }${new Date(Number(issue.minimum))}`
  12009. : "Invalid input"
  12010. break
  12011. case ZodIssueCode.too_big:
  12012. message =
  12013. "array" === issue.type
  12014. ? `Array must contain ${
  12015. issue.exact
  12016. ? "exactly"
  12017. : issue.inclusive
  12018. ? "at most"
  12019. : "less than"
  12020. } ${issue.maximum} element(s)`
  12021. : "string" === issue.type
  12022. ? `String must contain ${
  12023. issue.exact
  12024. ? "exactly"
  12025. : issue.inclusive
  12026. ? "at most"
  12027. : "under"
  12028. } ${issue.maximum} character(s)`
  12029. : "number" === issue.type
  12030. ? `Number must be ${
  12031. issue.exact
  12032. ? "exactly"
  12033. : issue.inclusive
  12034. ? "less than or equal to"
  12035. : "less than"
  12036. } ${issue.maximum}`
  12037. : "bigint" === issue.type
  12038. ? `BigInt must be ${
  12039. issue.exact
  12040. ? "exactly"
  12041. : issue.inclusive
  12042. ? "less than or equal to"
  12043. : "less than"
  12044. } ${issue.maximum}`
  12045. : "date" === issue.type
  12046. ? `Date must be ${
  12047. issue.exact
  12048. ? "exactly"
  12049. : issue.inclusive
  12050. ? "smaller than or equal to"
  12051. : "smaller than"
  12052. } ${new Date(Number(issue.maximum))}`
  12053. : "Invalid input"
  12054. break
  12055. case ZodIssueCode.custom:
  12056. message = "Invalid input"
  12057. break
  12058. case ZodIssueCode.invalid_intersection_types:
  12059. message = "Intersection results could not be merged"
  12060. break
  12061. case ZodIssueCode.not_multiple_of:
  12062. message = `Number must be a multiple of ${issue.multipleOf}`
  12063. break
  12064. case ZodIssueCode.not_finite:
  12065. message = "Number must be finite"
  12066. break
  12067. default:
  12068. message = _ctx.defaultError
  12069. util.assertNever(issue)
  12070. }
  12071. return { message }
  12072. }
  12073. let overrideErrorMap = errorMap
  12074. function getErrorMap() {
  12075. return overrideErrorMap
  12076. }
  12077. const makeIssue = params => {
  12078. const { data, path, errorMaps, issueData } = params,
  12079. fullPath = [...path, ...(issueData.path || [])],
  12080. fullIssue = { ...issueData, path: fullPath }
  12081. let errorMessage = ""
  12082. const maps = errorMaps
  12083. .filter(m => !!m)
  12084. .slice()
  12085. .reverse()
  12086. for (const map of maps)
  12087. errorMessage = map(fullIssue, {
  12088. data,
  12089. defaultError: errorMessage,
  12090. }).message
  12091. return {
  12092. ...issueData,
  12093. path: fullPath,
  12094. message: issueData.message || errorMessage,
  12095. }
  12096. }
  12097. function addIssueToContext(ctx, issueData) {
  12098. const issue = makeIssue({
  12099. issueData,
  12100. data: ctx.data,
  12101. path: ctx.path,
  12102. errorMaps: [
  12103. ctx.common.contextualErrorMap,
  12104. ctx.schemaErrorMap,
  12105. getErrorMap(),
  12106. errorMap,
  12107. ].filter(x => !!x),
  12108. })
  12109. ctx.common.issues.push(issue)
  12110. }
  12111. class ParseStatus {
  12112. constructor() {
  12113. this.value = "valid"
  12114. }
  12115. dirty() {
  12116. "valid" === this.value && (this.value = "dirty")
  12117. }
  12118. abort() {
  12119. "aborted" !== this.value && (this.value = "aborted")
  12120. }
  12121. static mergeArray(status, results) {
  12122. const arrayValue = []
  12123. for (const s of results) {
  12124. if ("aborted" === s.status) return INVALID
  12125. "dirty" === s.status && status.dirty()
  12126. arrayValue.push(s.value)
  12127. }
  12128. return { status: status.value, value: arrayValue }
  12129. }
  12130. static async mergeObjectAsync(status, pairs) {
  12131. const syncPairs = []
  12132. for (const pair of pairs)
  12133. syncPairs.push({ key: await pair.key, value: await pair.value })
  12134. return ParseStatus.mergeObjectSync(status, syncPairs)
  12135. }
  12136. static mergeObjectSync(status, pairs) {
  12137. const finalObject = {}
  12138. for (const pair of pairs) {
  12139. const { key, value } = pair
  12140. if ("aborted" === key.status) return INVALID
  12141. if ("aborted" === value.status) return INVALID
  12142. "dirty" === key.status && status.dirty()
  12143. "dirty" === value.status && status.dirty()
  12144. ;(void 0 !== value.value || pair.alwaysSet) &&
  12145. (finalObject[key.value] = value.value)
  12146. }
  12147. return { status: status.value, value: finalObject }
  12148. }
  12149. }
  12150. const INVALID = Object.freeze({ status: "aborted" }),
  12151. DIRTY = value => ({ status: "dirty", value }),
  12152. OK = value => ({ status: "valid", value }),
  12153. isAborted = x => "aborted" === x.status,
  12154. isDirty = x => "dirty" === x.status,
  12155. isValid = x => "valid" === x.status,
  12156. isAsync = x => "undefined" != typeof Promise && x instanceof Promise
  12157. var errorUtil
  12158. !(function (errorUtil) {
  12159. errorUtil.errToObj = message =>
  12160. "string" == typeof message ? { message } : message || {}
  12161. errorUtil.toString = message =>
  12162. "string" == typeof message
  12163. ? message
  12164. : null == message
  12165. ? void 0
  12166. : message.message
  12167. })(errorUtil || (errorUtil = {}))
  12168. class ParseInputLazyPath {
  12169. constructor(parent, value, path, key) {
  12170. this._cachedPath = []
  12171. this.parent = parent
  12172. this.data = value
  12173. this._path = path
  12174. this._key = key
  12175. }
  12176. get path() {
  12177. this._cachedPath.length ||
  12178. (this._key instanceof Array
  12179. ? this._cachedPath.push(...this._path, ...this._key)
  12180. : this._cachedPath.push(...this._path, this._key))
  12181. return this._cachedPath
  12182. }
  12183. }
  12184. const handleResult = (ctx, result) => {
  12185. if (isValid(result)) return { success: !0, data: result.value }
  12186. if (!ctx.common.issues.length)
  12187. throw new Error("Validation failed but no issues detected.")
  12188. return {
  12189. success: !1,
  12190. get error() {
  12191. if (this._error) return this._error
  12192. const error = new ZodError(ctx.common.issues)
  12193. this._error = error
  12194. return this._error
  12195. },
  12196. }
  12197. }
  12198. function processCreateParams(params) {
  12199. if (!params) return {}
  12200. const { errorMap, invalid_type_error, required_error, description } =
  12201. params
  12202. if (errorMap && (invalid_type_error || required_error))
  12203. throw new Error(
  12204. 'Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.'
  12205. )
  12206. return errorMap
  12207. ? { errorMap, description }
  12208. : {
  12209. errorMap: (iss, ctx) =>
  12210. "invalid_type" !== iss.code
  12211. ? { message: ctx.defaultError }
  12212. : void 0 === ctx.data
  12213. ? {
  12214. message:
  12215. null != required_error
  12216. ? required_error
  12217. : ctx.defaultError,
  12218. }
  12219. : {
  12220. message:
  12221. null != invalid_type_error
  12222. ? invalid_type_error
  12223. : ctx.defaultError,
  12224. },
  12225. description,
  12226. }
  12227. }
  12228. class ZodType {
  12229. constructor(def) {
  12230. this.spa = this.safeParseAsync
  12231. this._def = def
  12232. this.parse = this.parse.bind(this)
  12233. this.safeParse = this.safeParse.bind(this)
  12234. this.parseAsync = this.parseAsync.bind(this)
  12235. this.safeParseAsync = this.safeParseAsync.bind(this)
  12236. this.spa = this.spa.bind(this)
  12237. this.refine = this.refine.bind(this)
  12238. this.refinement = this.refinement.bind(this)
  12239. this.superRefine = this.superRefine.bind(this)
  12240. this.optional = this.optional.bind(this)
  12241. this.nullable = this.nullable.bind(this)
  12242. this.nullish = this.nullish.bind(this)
  12243. this.array = this.array.bind(this)
  12244. this.promise = this.promise.bind(this)
  12245. this.or = this.or.bind(this)
  12246. this.and = this.and.bind(this)
  12247. this.transform = this.transform.bind(this)
  12248. this.brand = this.brand.bind(this)
  12249. this.default = this.default.bind(this)
  12250. this.catch = this.catch.bind(this)
  12251. this.describe = this.describe.bind(this)
  12252. this.pipe = this.pipe.bind(this)
  12253. this.isNullable = this.isNullable.bind(this)
  12254. this.isOptional = this.isOptional.bind(this)
  12255. }
  12256. get description() {
  12257. return this._def.description
  12258. }
  12259. _getType(input) {
  12260. return getParsedType(input.data)
  12261. }
  12262. _getOrReturnCtx(input, ctx) {
  12263. return (
  12264. ctx || {
  12265. common: input.parent.common,
  12266. data: input.data,
  12267. parsedType: getParsedType(input.data),
  12268. schemaErrorMap: this._def.errorMap,
  12269. path: input.path,
  12270. parent: input.parent,
  12271. }
  12272. )
  12273. }
  12274. _processInputParams(input) {
  12275. return {
  12276. status: new ParseStatus(),
  12277. ctx: {
  12278. common: input.parent.common,
  12279. data: input.data,
  12280. parsedType: getParsedType(input.data),
  12281. schemaErrorMap: this._def.errorMap,
  12282. path: input.path,
  12283. parent: input.parent,
  12284. },
  12285. }
  12286. }
  12287. _parseSync(input) {
  12288. const result = this._parse(input)
  12289. if (isAsync(result))
  12290. throw new Error("Synchronous parse encountered promise.")
  12291. return result
  12292. }
  12293. _parseAsync(input) {
  12294. const result = this._parse(input)
  12295. return Promise.resolve(result)
  12296. }
  12297. parse(data, params) {
  12298. const result = this.safeParse(data, params)
  12299. if (result.success) return result.data
  12300. throw result.error
  12301. }
  12302. safeParse(data, params) {
  12303. var _a
  12304. const ctx = {
  12305. common: {
  12306. issues: [],
  12307. async:
  12308. null !== (_a = null == params ? void 0 : params.async) &&
  12309. void 0 !== _a &&
  12310. _a,
  12311. contextualErrorMap: null == params ? void 0 : params.errorMap,
  12312. },
  12313. path: (null == params ? void 0 : params.path) || [],
  12314. schemaErrorMap: this._def.errorMap,
  12315. parent: null,
  12316. data,
  12317. parsedType: getParsedType(data),
  12318. },
  12319. result = this._parseSync({ data, path: ctx.path, parent: ctx })
  12320. return handleResult(ctx, result)
  12321. }
  12322. async parseAsync(data, params) {
  12323. const result = await this.safeParseAsync(data, params)
  12324. if (result.success) return result.data
  12325. throw result.error
  12326. }
  12327. async safeParseAsync(data, params) {
  12328. const ctx = {
  12329. common: {
  12330. issues: [],
  12331. contextualErrorMap: null == params ? void 0 : params.errorMap,
  12332. async: !0,
  12333. },
  12334. path: (null == params ? void 0 : params.path) || [],
  12335. schemaErrorMap: this._def.errorMap,
  12336. parent: null,
  12337. data,
  12338. parsedType: getParsedType(data),
  12339. },
  12340. maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }),
  12341. result = await (isAsync(maybeAsyncResult)
  12342. ? maybeAsyncResult
  12343. : Promise.resolve(maybeAsyncResult))
  12344. return handleResult(ctx, result)
  12345. }
  12346. refine(check, message) {
  12347. const getIssueProperties = val =>
  12348. "string" == typeof message || void 0 === message
  12349. ? { message }
  12350. : "function" == typeof message
  12351. ? message(val)
  12352. : message
  12353. return this._refinement((val, ctx) => {
  12354. const result = check(val),
  12355. setError = () =>
  12356. ctx.addIssue({
  12357. code: ZodIssueCode.custom,
  12358. ...getIssueProperties(val),
  12359. })
  12360. if ("undefined" != typeof Promise && result instanceof Promise)
  12361. return result.then(data => {
  12362. if (data) return !0
  12363. setError()
  12364. return !1
  12365. })
  12366. if (result) return !0
  12367. setError()
  12368. return !1
  12369. })
  12370. }
  12371. refinement(check, refinementData) {
  12372. return this._refinement((val, ctx) => {
  12373. if (check(val)) return !0
  12374. ctx.addIssue(
  12375. "function" == typeof refinementData
  12376. ? refinementData(val, ctx)
  12377. : refinementData
  12378. )
  12379. return !1
  12380. })
  12381. }
  12382. _refinement(refinement) {
  12383. return new ZodEffects({
  12384. schema: this,
  12385. typeName: ZodFirstPartyTypeKind.ZodEffects,
  12386. effect: { type: "refinement", refinement },
  12387. })
  12388. }
  12389. superRefine(refinement) {
  12390. return this._refinement(refinement)
  12391. }
  12392. optional() {
  12393. return ZodOptional.create(this, this._def)
  12394. }
  12395. nullable() {
  12396. return ZodNullable.create(this, this._def)
  12397. }
  12398. nullish() {
  12399. return this.nullable().optional()
  12400. }
  12401. array() {
  12402. return ZodArray.create(this, this._def)
  12403. }
  12404. promise() {
  12405. return ZodPromise.create(this, this._def)
  12406. }
  12407. or(option) {
  12408. return ZodUnion.create([this, option], this._def)
  12409. }
  12410. and(incoming) {
  12411. return ZodIntersection.create(this, incoming, this._def)
  12412. }
  12413. transform(transform) {
  12414. return new ZodEffects({
  12415. ...processCreateParams(this._def),
  12416. schema: this,
  12417. typeName: ZodFirstPartyTypeKind.ZodEffects,
  12418. effect: { type: "transform", transform },
  12419. })
  12420. }
  12421. default(def) {
  12422. const defaultValueFunc = "function" == typeof def ? def : () => def
  12423. return new ZodDefault({
  12424. ...processCreateParams(this._def),
  12425. innerType: this,
  12426. defaultValue: defaultValueFunc,
  12427. typeName: ZodFirstPartyTypeKind.ZodDefault,
  12428. })
  12429. }
  12430. brand() {
  12431. return new ZodBranded({
  12432. typeName: ZodFirstPartyTypeKind.ZodBranded,
  12433. type: this,
  12434. ...processCreateParams(this._def),
  12435. })
  12436. }
  12437. catch(def) {
  12438. const catchValueFunc = "function" == typeof def ? def : () => def
  12439. return new ZodCatch({
  12440. ...processCreateParams(this._def),
  12441. innerType: this,
  12442. catchValue: catchValueFunc,
  12443. typeName: ZodFirstPartyTypeKind.ZodCatch,
  12444. })
  12445. }
  12446. describe(description) {
  12447. return new (0, this.constructor)({ ...this._def, description })
  12448. }
  12449. pipe(target) {
  12450. return ZodPipeline.create(this, target)
  12451. }
  12452. isOptional() {
  12453. return this.safeParse(void 0).success
  12454. }
  12455. isNullable() {
  12456. return this.safeParse(null).success
  12457. }
  12458. }
  12459. const cuidRegex = /^c[^\s-]{8,}$/i,
  12460. cuid2Regex = /^[a-z][a-z0-9]*$/,
  12461. ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/,
  12462. uuidRegex =
  12463. /^([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,
  12464. emailRegex =
  12465. /^(([^<>()[\]\\.,;:\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,})+))$/,
  12466. emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,
  12467. ipv4Regex =
  12468. /^(((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}))$/,
  12469. ipv6Regex =
  12470. /^(([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})))$/
  12471. class ZodString extends ZodType {
  12472. constructor() {
  12473. super(...arguments)
  12474. this._regex = (regex, validation, message) =>
  12475. this.refinement(data => regex.test(data), {
  12476. validation,
  12477. code: ZodIssueCode.invalid_string,
  12478. ...errorUtil.errToObj(message),
  12479. })
  12480. this.nonempty = message => this.min(1, errorUtil.errToObj(message))
  12481. this.trim = () =>
  12482. new ZodString({
  12483. ...this._def,
  12484. checks: [...this._def.checks, { kind: "trim" }],
  12485. })
  12486. this.toLowerCase = () =>
  12487. new ZodString({
  12488. ...this._def,
  12489. checks: [...this._def.checks, { kind: "toLowerCase" }],
  12490. })
  12491. this.toUpperCase = () =>
  12492. new ZodString({
  12493. ...this._def,
  12494. checks: [...this._def.checks, { kind: "toUpperCase" }],
  12495. })
  12496. }
  12497. _parse(input) {
  12498. this._def.coerce && (input.data = String(input.data))
  12499. if (this._getType(input) !== ZodParsedType.string) {
  12500. const ctx = this._getOrReturnCtx(input)
  12501. addIssueToContext(ctx, {
  12502. code: ZodIssueCode.invalid_type,
  12503. expected: ZodParsedType.string,
  12504. received: ctx.parsedType,
  12505. })
  12506. return INVALID
  12507. }
  12508. const status = new ParseStatus()
  12509. let ctx
  12510. for (const check of this._def.checks)
  12511. if ("min" === check.kind) {
  12512. if (input.data.length < check.value) {
  12513. ctx = this._getOrReturnCtx(input, ctx)
  12514. addIssueToContext(ctx, {
  12515. code: ZodIssueCode.too_small,
  12516. minimum: check.value,
  12517. type: "string",
  12518. inclusive: !0,
  12519. exact: !1,
  12520. message: check.message,
  12521. })
  12522. status.dirty()
  12523. }
  12524. } else if ("max" === check.kind) {
  12525. if (input.data.length > check.value) {
  12526. ctx = this._getOrReturnCtx(input, ctx)
  12527. addIssueToContext(ctx, {
  12528. code: ZodIssueCode.too_big,
  12529. maximum: check.value,
  12530. type: "string",
  12531. inclusive: !0,
  12532. exact: !1,
  12533. message: check.message,
  12534. })
  12535. status.dirty()
  12536. }
  12537. } else if ("length" === check.kind) {
  12538. const tooBig = input.data.length > check.value,
  12539. tooSmall = input.data.length < check.value
  12540. if (tooBig || tooSmall) {
  12541. ctx = this._getOrReturnCtx(input, ctx)
  12542. tooBig
  12543. ? addIssueToContext(ctx, {
  12544. code: ZodIssueCode.too_big,
  12545. maximum: check.value,
  12546. type: "string",
  12547. inclusive: !0,
  12548. exact: !0,
  12549. message: check.message,
  12550. })
  12551. : tooSmall &&
  12552. addIssueToContext(ctx, {
  12553. code: ZodIssueCode.too_small,
  12554. minimum: check.value,
  12555. type: "string",
  12556. inclusive: !0,
  12557. exact: !0,
  12558. message: check.message,
  12559. })
  12560. status.dirty()
  12561. }
  12562. } else if ("email" === check.kind) {
  12563. if (!emailRegex.test(input.data)) {
  12564. ctx = this._getOrReturnCtx(input, ctx)
  12565. addIssueToContext(ctx, {
  12566. validation: "email",
  12567. code: ZodIssueCode.invalid_string,
  12568. message: check.message,
  12569. })
  12570. status.dirty()
  12571. }
  12572. } else if ("emoji" === check.kind) {
  12573. if (!emojiRegex.test(input.data)) {
  12574. ctx = this._getOrReturnCtx(input, ctx)
  12575. addIssueToContext(ctx, {
  12576. validation: "emoji",
  12577. code: ZodIssueCode.invalid_string,
  12578. message: check.message,
  12579. })
  12580. status.dirty()
  12581. }
  12582. } else if ("uuid" === check.kind) {
  12583. if (!uuidRegex.test(input.data)) {
  12584. ctx = this._getOrReturnCtx(input, ctx)
  12585. addIssueToContext(ctx, {
  12586. validation: "uuid",
  12587. code: ZodIssueCode.invalid_string,
  12588. message: check.message,
  12589. })
  12590. status.dirty()
  12591. }
  12592. } else if ("cuid" === check.kind) {
  12593. if (!cuidRegex.test(input.data)) {
  12594. ctx = this._getOrReturnCtx(input, ctx)
  12595. addIssueToContext(ctx, {
  12596. validation: "cuid",
  12597. code: ZodIssueCode.invalid_string,
  12598. message: check.message,
  12599. })
  12600. status.dirty()
  12601. }
  12602. } else if ("cuid2" === check.kind) {
  12603. if (!cuid2Regex.test(input.data)) {
  12604. ctx = this._getOrReturnCtx(input, ctx)
  12605. addIssueToContext(ctx, {
  12606. validation: "cuid2",
  12607. code: ZodIssueCode.invalid_string,
  12608. message: check.message,
  12609. })
  12610. status.dirty()
  12611. }
  12612. } else if ("ulid" === check.kind) {
  12613. if (!ulidRegex.test(input.data)) {
  12614. ctx = this._getOrReturnCtx(input, ctx)
  12615. addIssueToContext(ctx, {
  12616. validation: "ulid",
  12617. code: ZodIssueCode.invalid_string,
  12618. message: check.message,
  12619. })
  12620. status.dirty()
  12621. }
  12622. } else if ("url" === check.kind)
  12623. try {
  12624. new URL(input.data)
  12625. } catch (_a) {
  12626. ctx = this._getOrReturnCtx(input, ctx)
  12627. addIssueToContext(ctx, {
  12628. validation: "url",
  12629. code: ZodIssueCode.invalid_string,
  12630. message: check.message,
  12631. })
  12632. status.dirty()
  12633. }
  12634. else if ("regex" === check.kind) {
  12635. check.regex.lastIndex = 0
  12636. if (!check.regex.test(input.data)) {
  12637. ctx = this._getOrReturnCtx(input, ctx)
  12638. addIssueToContext(ctx, {
  12639. validation: "regex",
  12640. code: ZodIssueCode.invalid_string,
  12641. message: check.message,
  12642. })
  12643. status.dirty()
  12644. }
  12645. } else if ("trim" === check.kind) input.data = input.data.trim()
  12646. else if ("includes" === check.kind) {
  12647. if (!input.data.includes(check.value, check.position)) {
  12648. ctx = this._getOrReturnCtx(input, ctx)
  12649. addIssueToContext(ctx, {
  12650. code: ZodIssueCode.invalid_string,
  12651. validation: { includes: check.value, position: check.position },
  12652. message: check.message,
  12653. })
  12654. status.dirty()
  12655. }
  12656. } else if ("toLowerCase" === check.kind)
  12657. input.data = input.data.toLowerCase()
  12658. else if ("toUpperCase" === check.kind)
  12659. input.data = input.data.toUpperCase()
  12660. else if ("startsWith" === check.kind) {
  12661. if (!input.data.startsWith(check.value)) {
  12662. ctx = this._getOrReturnCtx(input, ctx)
  12663. addIssueToContext(ctx, {
  12664. code: ZodIssueCode.invalid_string,
  12665. validation: { startsWith: check.value },
  12666. message: check.message,
  12667. })
  12668. status.dirty()
  12669. }
  12670. } else if ("endsWith" === check.kind) {
  12671. if (!input.data.endsWith(check.value)) {
  12672. ctx = this._getOrReturnCtx(input, ctx)
  12673. addIssueToContext(ctx, {
  12674. code: ZodIssueCode.invalid_string,
  12675. validation: { endsWith: check.value },
  12676. message: check.message,
  12677. })
  12678. status.dirty()
  12679. }
  12680. } else if ("datetime" === check.kind) {
  12681. if (
  12682. !(
  12683. (args = check).precision
  12684. ? args.offset
  12685. ? new RegExp(
  12686. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`
  12687. )
  12688. : new RegExp(
  12689. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`
  12690. )
  12691. : 0 === args.precision
  12692. ? args.offset
  12693. ? new RegExp(
  12694. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  12695. )
  12696. : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")
  12697. : args.offset
  12698. ? new RegExp(
  12699. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  12700. )
  12701. : new RegExp(
  12702. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"
  12703. )
  12704. ).test(input.data)
  12705. ) {
  12706. ctx = this._getOrReturnCtx(input, ctx)
  12707. addIssueToContext(ctx, {
  12708. code: ZodIssueCode.invalid_string,
  12709. validation: "datetime",
  12710. message: check.message,
  12711. })
  12712. status.dirty()
  12713. }
  12714. } else if ("ip" === check.kind) {
  12715. if (
  12716. !((ip = input.data),
  12717. (version = check.version),
  12718. (("v4" === version || !version) && ipv4Regex.test(ip)) ||
  12719. (("v6" === version || !version) && ipv6Regex.test(ip)))
  12720. ) {
  12721. ctx = this._getOrReturnCtx(input, ctx)
  12722. addIssueToContext(ctx, {
  12723. validation: "ip",
  12724. code: ZodIssueCode.invalid_string,
  12725. message: check.message,
  12726. })
  12727. status.dirty()
  12728. }
  12729. } else util.assertNever(check)
  12730. var ip, version, args
  12731. return { status: status.value, value: input.data }
  12732. }
  12733. _addCheck(check) {
  12734. return new ZodString({
  12735. ...this._def,
  12736. checks: [...this._def.checks, check],
  12737. })
  12738. }
  12739. email(message) {
  12740. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) })
  12741. }
  12742. url(message) {
  12743. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) })
  12744. }
  12745. emoji(message) {
  12746. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) })
  12747. }
  12748. uuid(message) {
  12749. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) })
  12750. }
  12751. cuid(message) {
  12752. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) })
  12753. }
  12754. cuid2(message) {
  12755. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) })
  12756. }
  12757. ulid(message) {
  12758. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) })
  12759. }
  12760. ip(options) {
  12761. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) })
  12762. }
  12763. datetime(options) {
  12764. var _a
  12765. return "string" == typeof options
  12766. ? this._addCheck({
  12767. kind: "datetime",
  12768. precision: null,
  12769. offset: !1,
  12770. message: options,
  12771. })
  12772. : this._addCheck({
  12773. kind: "datetime",
  12774. precision:
  12775. void 0 === (null == options ? void 0 : options.precision)
  12776. ? null
  12777. : null == options
  12778. ? void 0
  12779. : options.precision,
  12780. offset:
  12781. null !== (_a = null == options ? void 0 : options.offset) &&
  12782. void 0 !== _a &&
  12783. _a,
  12784. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  12785. })
  12786. }
  12787. regex(regex, message) {
  12788. return this._addCheck({
  12789. kind: "regex",
  12790. regex,
  12791. ...errorUtil.errToObj(message),
  12792. })
  12793. }
  12794. includes(value, options) {
  12795. return this._addCheck({
  12796. kind: "includes",
  12797. value,
  12798. position: null == options ? void 0 : options.position,
  12799. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  12800. })
  12801. }
  12802. startsWith(value, message) {
  12803. return this._addCheck({
  12804. kind: "startsWith",
  12805. value,
  12806. ...errorUtil.errToObj(message),
  12807. })
  12808. }
  12809. endsWith(value, message) {
  12810. return this._addCheck({
  12811. kind: "endsWith",
  12812. value,
  12813. ...errorUtil.errToObj(message),
  12814. })
  12815. }
  12816. min(minLength, message) {
  12817. return this._addCheck({
  12818. kind: "min",
  12819. value: minLength,
  12820. ...errorUtil.errToObj(message),
  12821. })
  12822. }
  12823. max(maxLength, message) {
  12824. return this._addCheck({
  12825. kind: "max",
  12826. value: maxLength,
  12827. ...errorUtil.errToObj(message),
  12828. })
  12829. }
  12830. length(len, message) {
  12831. return this._addCheck({
  12832. kind: "length",
  12833. value: len,
  12834. ...errorUtil.errToObj(message),
  12835. })
  12836. }
  12837. get isDatetime() {
  12838. return !!this._def.checks.find(ch => "datetime" === ch.kind)
  12839. }
  12840. get isEmail() {
  12841. return !!this._def.checks.find(ch => "email" === ch.kind)
  12842. }
  12843. get isURL() {
  12844. return !!this._def.checks.find(ch => "url" === ch.kind)
  12845. }
  12846. get isEmoji() {
  12847. return !!this._def.checks.find(ch => "emoji" === ch.kind)
  12848. }
  12849. get isUUID() {
  12850. return !!this._def.checks.find(ch => "uuid" === ch.kind)
  12851. }
  12852. get isCUID() {
  12853. return !!this._def.checks.find(ch => "cuid" === ch.kind)
  12854. }
  12855. get isCUID2() {
  12856. return !!this._def.checks.find(ch => "cuid2" === ch.kind)
  12857. }
  12858. get isULID() {
  12859. return !!this._def.checks.find(ch => "ulid" === ch.kind)
  12860. }
  12861. get isIP() {
  12862. return !!this._def.checks.find(ch => "ip" === ch.kind)
  12863. }
  12864. get minLength() {
  12865. let min = null
  12866. for (const ch of this._def.checks)
  12867. "min" === ch.kind &&
  12868. (null === min || ch.value > min) &&
  12869. (min = ch.value)
  12870. return min
  12871. }
  12872. get maxLength() {
  12873. let max = null
  12874. for (const ch of this._def.checks)
  12875. "max" === ch.kind &&
  12876. (null === max || ch.value < max) &&
  12877. (max = ch.value)
  12878. return max
  12879. }
  12880. }
  12881. ZodString.create = params => {
  12882. var _a
  12883. return new ZodString({
  12884. checks: [],
  12885. typeName: ZodFirstPartyTypeKind.ZodString,
  12886. coerce:
  12887. null !== (_a = null == params ? void 0 : params.coerce) &&
  12888. void 0 !== _a &&
  12889. _a,
  12890. ...processCreateParams(params),
  12891. })
  12892. }
  12893. function floatSafeRemainder(val, step) {
  12894. const valDecCount = (val.toString().split(".")[1] || "").length,
  12895. stepDecCount = (step.toString().split(".")[1] || "").length,
  12896. decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount
  12897. return (
  12898. (parseInt(val.toFixed(decCount).replace(".", "")) %
  12899. parseInt(step.toFixed(decCount).replace(".", ""))) /
  12900. Math.pow(10, decCount)
  12901. )
  12902. }
  12903. class ZodNumber extends ZodType {
  12904. constructor() {
  12905. super(...arguments)
  12906. this.min = this.gte
  12907. this.max = this.lte
  12908. this.step = this.multipleOf
  12909. }
  12910. _parse(input) {
  12911. this._def.coerce && (input.data = Number(input.data))
  12912. if (this._getType(input) !== ZodParsedType.number) {
  12913. const ctx = this._getOrReturnCtx(input)
  12914. addIssueToContext(ctx, {
  12915. code: ZodIssueCode.invalid_type,
  12916. expected: ZodParsedType.number,
  12917. received: ctx.parsedType,
  12918. })
  12919. return INVALID
  12920. }
  12921. let ctx
  12922. const status = new ParseStatus()
  12923. for (const check of this._def.checks)
  12924. if ("int" === check.kind) {
  12925. if (!util.isInteger(input.data)) {
  12926. ctx = this._getOrReturnCtx(input, ctx)
  12927. addIssueToContext(ctx, {
  12928. code: ZodIssueCode.invalid_type,
  12929. expected: "integer",
  12930. received: "float",
  12931. message: check.message,
  12932. })
  12933. status.dirty()
  12934. }
  12935. } else if ("min" === check.kind) {
  12936. if (
  12937. check.inclusive
  12938. ? input.data < check.value
  12939. : input.data <= check.value
  12940. ) {
  12941. ctx = this._getOrReturnCtx(input, ctx)
  12942. addIssueToContext(ctx, {
  12943. code: ZodIssueCode.too_small,
  12944. minimum: check.value,
  12945. type: "number",
  12946. inclusive: check.inclusive,
  12947. exact: !1,
  12948. message: check.message,
  12949. })
  12950. status.dirty()
  12951. }
  12952. } else if ("max" === check.kind) {
  12953. if (
  12954. check.inclusive
  12955. ? input.data > check.value
  12956. : input.data >= check.value
  12957. ) {
  12958. ctx = this._getOrReturnCtx(input, ctx)
  12959. addIssueToContext(ctx, {
  12960. code: ZodIssueCode.too_big,
  12961. maximum: check.value,
  12962. type: "number",
  12963. inclusive: check.inclusive,
  12964. exact: !1,
  12965. message: check.message,
  12966. })
  12967. status.dirty()
  12968. }
  12969. } else if ("multipleOf" === check.kind) {
  12970. if (0 !== floatSafeRemainder(input.data, check.value)) {
  12971. ctx = this._getOrReturnCtx(input, ctx)
  12972. addIssueToContext(ctx, {
  12973. code: ZodIssueCode.not_multiple_of,
  12974. multipleOf: check.value,
  12975. message: check.message,
  12976. })
  12977. status.dirty()
  12978. }
  12979. } else if ("finite" === check.kind) {
  12980. if (!Number.isFinite(input.data)) {
  12981. ctx = this._getOrReturnCtx(input, ctx)
  12982. addIssueToContext(ctx, {
  12983. code: ZodIssueCode.not_finite,
  12984. message: check.message,
  12985. })
  12986. status.dirty()
  12987. }
  12988. } else util.assertNever(check)
  12989. return { status: status.value, value: input.data }
  12990. }
  12991. gte(value, message) {
  12992. return this.setLimit("min", value, !0, errorUtil.toString(message))
  12993. }
  12994. gt(value, message) {
  12995. return this.setLimit("min", value, !1, errorUtil.toString(message))
  12996. }
  12997. lte(value, message) {
  12998. return this.setLimit("max", value, !0, errorUtil.toString(message))
  12999. }
  13000. lt(value, message) {
  13001. return this.setLimit("max", value, !1, errorUtil.toString(message))
  13002. }
  13003. setLimit(kind, value, inclusive, message) {
  13004. return new ZodNumber({
  13005. ...this._def,
  13006. checks: [
  13007. ...this._def.checks,
  13008. { kind, value, inclusive, message: errorUtil.toString(message) },
  13009. ],
  13010. })
  13011. }
  13012. _addCheck(check) {
  13013. return new ZodNumber({
  13014. ...this._def,
  13015. checks: [...this._def.checks, check],
  13016. })
  13017. }
  13018. int(message) {
  13019. return this._addCheck({
  13020. kind: "int",
  13021. message: errorUtil.toString(message),
  13022. })
  13023. }
  13024. positive(message) {
  13025. return this._addCheck({
  13026. kind: "min",
  13027. value: 0,
  13028. inclusive: !1,
  13029. message: errorUtil.toString(message),
  13030. })
  13031. }
  13032. negative(message) {
  13033. return this._addCheck({
  13034. kind: "max",
  13035. value: 0,
  13036. inclusive: !1,
  13037. message: errorUtil.toString(message),
  13038. })
  13039. }
  13040. nonpositive(message) {
  13041. return this._addCheck({
  13042. kind: "max",
  13043. value: 0,
  13044. inclusive: !0,
  13045. message: errorUtil.toString(message),
  13046. })
  13047. }
  13048. nonnegative(message) {
  13049. return this._addCheck({
  13050. kind: "min",
  13051. value: 0,
  13052. inclusive: !0,
  13053. message: errorUtil.toString(message),
  13054. })
  13055. }
  13056. multipleOf(value, message) {
  13057. return this._addCheck({
  13058. kind: "multipleOf",
  13059. value,
  13060. message: errorUtil.toString(message),
  13061. })
  13062. }
  13063. finite(message) {
  13064. return this._addCheck({
  13065. kind: "finite",
  13066. message: errorUtil.toString(message),
  13067. })
  13068. }
  13069. safe(message) {
  13070. return this._addCheck({
  13071. kind: "min",
  13072. inclusive: !0,
  13073. value: Number.MIN_SAFE_INTEGER,
  13074. message: errorUtil.toString(message),
  13075. })._addCheck({
  13076. kind: "max",
  13077. inclusive: !0,
  13078. value: Number.MAX_SAFE_INTEGER,
  13079. message: errorUtil.toString(message),
  13080. })
  13081. }
  13082. get minValue() {
  13083. let min = null
  13084. for (const ch of this._def.checks)
  13085. "min" === ch.kind &&
  13086. (null === min || ch.value > min) &&
  13087. (min = ch.value)
  13088. return min
  13089. }
  13090. get maxValue() {
  13091. let max = null
  13092. for (const ch of this._def.checks)
  13093. "max" === ch.kind &&
  13094. (null === max || ch.value < max) &&
  13095. (max = ch.value)
  13096. return max
  13097. }
  13098. get isInt() {
  13099. return !!this._def.checks.find(
  13100. ch =>
  13101. "int" === ch.kind ||
  13102. ("multipleOf" === ch.kind && util.isInteger(ch.value))
  13103. )
  13104. }
  13105. get isFinite() {
  13106. let max = null,
  13107. min = null
  13108. for (const ch of this._def.checks) {
  13109. if (
  13110. "finite" === ch.kind ||
  13111. "int" === ch.kind ||
  13112. "multipleOf" === ch.kind
  13113. )
  13114. return !0
  13115. "min" === ch.kind
  13116. ? (null === min || ch.value > min) && (min = ch.value)
  13117. : "max" === ch.kind &&
  13118. (null === max || ch.value < max) &&
  13119. (max = ch.value)
  13120. }
  13121. return Number.isFinite(min) && Number.isFinite(max)
  13122. }
  13123. }
  13124. ZodNumber.create = params =>
  13125. new ZodNumber({
  13126. checks: [],
  13127. typeName: ZodFirstPartyTypeKind.ZodNumber,
  13128. coerce: (null == params ? void 0 : params.coerce) || !1,
  13129. ...processCreateParams(params),
  13130. })
  13131. class ZodBigInt extends ZodType {
  13132. constructor() {
  13133. super(...arguments)
  13134. this.min = this.gte
  13135. this.max = this.lte
  13136. }
  13137. _parse(input) {
  13138. this._def.coerce && (input.data = BigInt(input.data))
  13139. if (this._getType(input) !== ZodParsedType.bigint) {
  13140. const ctx = this._getOrReturnCtx(input)
  13141. addIssueToContext(ctx, {
  13142. code: ZodIssueCode.invalid_type,
  13143. expected: ZodParsedType.bigint,
  13144. received: ctx.parsedType,
  13145. })
  13146. return INVALID
  13147. }
  13148. let ctx
  13149. const status = new ParseStatus()
  13150. for (const check of this._def.checks)
  13151. if ("min" === check.kind) {
  13152. if (
  13153. check.inclusive
  13154. ? input.data < check.value
  13155. : input.data <= check.value
  13156. ) {
  13157. ctx = this._getOrReturnCtx(input, ctx)
  13158. addIssueToContext(ctx, {
  13159. code: ZodIssueCode.too_small,
  13160. type: "bigint",
  13161. minimum: check.value,
  13162. inclusive: check.inclusive,
  13163. message: check.message,
  13164. })
  13165. status.dirty()
  13166. }
  13167. } else if ("max" === check.kind) {
  13168. if (
  13169. check.inclusive
  13170. ? input.data > check.value
  13171. : input.data >= check.value
  13172. ) {
  13173. ctx = this._getOrReturnCtx(input, ctx)
  13174. addIssueToContext(ctx, {
  13175. code: ZodIssueCode.too_big,
  13176. type: "bigint",
  13177. maximum: check.value,
  13178. inclusive: check.inclusive,
  13179. message: check.message,
  13180. })
  13181. status.dirty()
  13182. }
  13183. } else if ("multipleOf" === check.kind) {
  13184. if (input.data % check.value !== BigInt(0)) {
  13185. ctx = this._getOrReturnCtx(input, ctx)
  13186. addIssueToContext(ctx, {
  13187. code: ZodIssueCode.not_multiple_of,
  13188. multipleOf: check.value,
  13189. message: check.message,
  13190. })
  13191. status.dirty()
  13192. }
  13193. } else util.assertNever(check)
  13194. return { status: status.value, value: input.data }
  13195. }
  13196. gte(value, message) {
  13197. return this.setLimit("min", value, !0, errorUtil.toString(message))
  13198. }
  13199. gt(value, message) {
  13200. return this.setLimit("min", value, !1, errorUtil.toString(message))
  13201. }
  13202. lte(value, message) {
  13203. return this.setLimit("max", value, !0, errorUtil.toString(message))
  13204. }
  13205. lt(value, message) {
  13206. return this.setLimit("max", value, !1, errorUtil.toString(message))
  13207. }
  13208. setLimit(kind, value, inclusive, message) {
  13209. return new ZodBigInt({
  13210. ...this._def,
  13211. checks: [
  13212. ...this._def.checks,
  13213. { kind, value, inclusive, message: errorUtil.toString(message) },
  13214. ],
  13215. })
  13216. }
  13217. _addCheck(check) {
  13218. return new ZodBigInt({
  13219. ...this._def,
  13220. checks: [...this._def.checks, check],
  13221. })
  13222. }
  13223. positive(message) {
  13224. return this._addCheck({
  13225. kind: "min",
  13226. value: BigInt(0),
  13227. inclusive: !1,
  13228. message: errorUtil.toString(message),
  13229. })
  13230. }
  13231. negative(message) {
  13232. return this._addCheck({
  13233. kind: "max",
  13234. value: BigInt(0),
  13235. inclusive: !1,
  13236. message: errorUtil.toString(message),
  13237. })
  13238. }
  13239. nonpositive(message) {
  13240. return this._addCheck({
  13241. kind: "max",
  13242. value: BigInt(0),
  13243. inclusive: !0,
  13244. message: errorUtil.toString(message),
  13245. })
  13246. }
  13247. nonnegative(message) {
  13248. return this._addCheck({
  13249. kind: "min",
  13250. value: BigInt(0),
  13251. inclusive: !0,
  13252. message: errorUtil.toString(message),
  13253. })
  13254. }
  13255. multipleOf(value, message) {
  13256. return this._addCheck({
  13257. kind: "multipleOf",
  13258. value,
  13259. message: errorUtil.toString(message),
  13260. })
  13261. }
  13262. get minValue() {
  13263. let min = null
  13264. for (const ch of this._def.checks)
  13265. "min" === ch.kind &&
  13266. (null === min || ch.value > min) &&
  13267. (min = ch.value)
  13268. return min
  13269. }
  13270. get maxValue() {
  13271. let max = null
  13272. for (const ch of this._def.checks)
  13273. "max" === ch.kind &&
  13274. (null === max || ch.value < max) &&
  13275. (max = ch.value)
  13276. return max
  13277. }
  13278. }
  13279. ZodBigInt.create = params => {
  13280. var _a
  13281. return new ZodBigInt({
  13282. checks: [],
  13283. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  13284. coerce:
  13285. null !== (_a = null == params ? void 0 : params.coerce) &&
  13286. void 0 !== _a &&
  13287. _a,
  13288. ...processCreateParams(params),
  13289. })
  13290. }
  13291. class ZodBoolean extends ZodType {
  13292. _parse(input) {
  13293. this._def.coerce && (input.data = Boolean(input.data))
  13294. if (this._getType(input) !== ZodParsedType.boolean) {
  13295. const ctx = this._getOrReturnCtx(input)
  13296. addIssueToContext(ctx, {
  13297. code: ZodIssueCode.invalid_type,
  13298. expected: ZodParsedType.boolean,
  13299. received: ctx.parsedType,
  13300. })
  13301. return INVALID
  13302. }
  13303. return OK(input.data)
  13304. }
  13305. }
  13306. ZodBoolean.create = params =>
  13307. new ZodBoolean({
  13308. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  13309. coerce: (null == params ? void 0 : params.coerce) || !1,
  13310. ...processCreateParams(params),
  13311. })
  13312. class ZodDate extends ZodType {
  13313. _parse(input) {
  13314. this._def.coerce && (input.data = new Date(input.data))
  13315. if (this._getType(input) !== ZodParsedType.date) {
  13316. const ctx = this._getOrReturnCtx(input)
  13317. addIssueToContext(ctx, {
  13318. code: ZodIssueCode.invalid_type,
  13319. expected: ZodParsedType.date,
  13320. received: ctx.parsedType,
  13321. })
  13322. return INVALID
  13323. }
  13324. if (isNaN(input.data.getTime())) {
  13325. addIssueToContext(this._getOrReturnCtx(input), {
  13326. code: ZodIssueCode.invalid_date,
  13327. })
  13328. return INVALID
  13329. }
  13330. const status = new ParseStatus()
  13331. let ctx
  13332. for (const check of this._def.checks)
  13333. if ("min" === check.kind) {
  13334. if (input.data.getTime() < check.value) {
  13335. ctx = this._getOrReturnCtx(input, ctx)
  13336. addIssueToContext(ctx, {
  13337. code: ZodIssueCode.too_small,
  13338. message: check.message,
  13339. inclusive: !0,
  13340. exact: !1,
  13341. minimum: check.value,
  13342. type: "date",
  13343. })
  13344. status.dirty()
  13345. }
  13346. } else if ("max" === check.kind) {
  13347. if (input.data.getTime() > check.value) {
  13348. ctx = this._getOrReturnCtx(input, ctx)
  13349. addIssueToContext(ctx, {
  13350. code: ZodIssueCode.too_big,
  13351. message: check.message,
  13352. inclusive: !0,
  13353. exact: !1,
  13354. maximum: check.value,
  13355. type: "date",
  13356. })
  13357. status.dirty()
  13358. }
  13359. } else util.assertNever(check)
  13360. return { status: status.value, value: new Date(input.data.getTime()) }
  13361. }
  13362. _addCheck(check) {
  13363. return new ZodDate({
  13364. ...this._def,
  13365. checks: [...this._def.checks, check],
  13366. })
  13367. }
  13368. min(minDate, message) {
  13369. return this._addCheck({
  13370. kind: "min",
  13371. value: minDate.getTime(),
  13372. message: errorUtil.toString(message),
  13373. })
  13374. }
  13375. max(maxDate, message) {
  13376. return this._addCheck({
  13377. kind: "max",
  13378. value: maxDate.getTime(),
  13379. message: errorUtil.toString(message),
  13380. })
  13381. }
  13382. get minDate() {
  13383. let min = null
  13384. for (const ch of this._def.checks)
  13385. "min" === ch.kind &&
  13386. (null === min || ch.value > min) &&
  13387. (min = ch.value)
  13388. return null != min ? new Date(min) : null
  13389. }
  13390. get maxDate() {
  13391. let max = null
  13392. for (const ch of this._def.checks)
  13393. "max" === ch.kind &&
  13394. (null === max || ch.value < max) &&
  13395. (max = ch.value)
  13396. return null != max ? new Date(max) : null
  13397. }
  13398. }
  13399. ZodDate.create = params =>
  13400. new ZodDate({
  13401. checks: [],
  13402. coerce: (null == params ? void 0 : params.coerce) || !1,
  13403. typeName: ZodFirstPartyTypeKind.ZodDate,
  13404. ...processCreateParams(params),
  13405. })
  13406. class ZodSymbol extends ZodType {
  13407. _parse(input) {
  13408. if (this._getType(input) !== ZodParsedType.symbol) {
  13409. const ctx = this._getOrReturnCtx(input)
  13410. addIssueToContext(ctx, {
  13411. code: ZodIssueCode.invalid_type,
  13412. expected: ZodParsedType.symbol,
  13413. received: ctx.parsedType,
  13414. })
  13415. return INVALID
  13416. }
  13417. return OK(input.data)
  13418. }
  13419. }
  13420. ZodSymbol.create = params =>
  13421. new ZodSymbol({
  13422. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  13423. ...processCreateParams(params),
  13424. })
  13425. class ZodUndefined extends ZodType {
  13426. _parse(input) {
  13427. if (this._getType(input) !== ZodParsedType.undefined) {
  13428. const ctx = this._getOrReturnCtx(input)
  13429. addIssueToContext(ctx, {
  13430. code: ZodIssueCode.invalid_type,
  13431. expected: ZodParsedType.undefined,
  13432. received: ctx.parsedType,
  13433. })
  13434. return INVALID
  13435. }
  13436. return OK(input.data)
  13437. }
  13438. }
  13439. ZodUndefined.create = params =>
  13440. new ZodUndefined({
  13441. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  13442. ...processCreateParams(params),
  13443. })
  13444. class ZodNull extends ZodType {
  13445. _parse(input) {
  13446. if (this._getType(input) !== ZodParsedType.null) {
  13447. const ctx = this._getOrReturnCtx(input)
  13448. addIssueToContext(ctx, {
  13449. code: ZodIssueCode.invalid_type,
  13450. expected: ZodParsedType.null,
  13451. received: ctx.parsedType,
  13452. })
  13453. return INVALID
  13454. }
  13455. return OK(input.data)
  13456. }
  13457. }
  13458. ZodNull.create = params =>
  13459. new ZodNull({
  13460. typeName: ZodFirstPartyTypeKind.ZodNull,
  13461. ...processCreateParams(params),
  13462. })
  13463. class ZodAny extends ZodType {
  13464. constructor() {
  13465. super(...arguments)
  13466. this._any = !0
  13467. }
  13468. _parse(input) {
  13469. return OK(input.data)
  13470. }
  13471. }
  13472. ZodAny.create = params =>
  13473. new ZodAny({
  13474. typeName: ZodFirstPartyTypeKind.ZodAny,
  13475. ...processCreateParams(params),
  13476. })
  13477. class ZodUnknown extends ZodType {
  13478. constructor() {
  13479. super(...arguments)
  13480. this._unknown = !0
  13481. }
  13482. _parse(input) {
  13483. return OK(input.data)
  13484. }
  13485. }
  13486. ZodUnknown.create = params =>
  13487. new ZodUnknown({
  13488. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  13489. ...processCreateParams(params),
  13490. })
  13491. class ZodNever extends ZodType {
  13492. _parse(input) {
  13493. const ctx = this._getOrReturnCtx(input)
  13494. addIssueToContext(ctx, {
  13495. code: ZodIssueCode.invalid_type,
  13496. expected: ZodParsedType.never,
  13497. received: ctx.parsedType,
  13498. })
  13499. return INVALID
  13500. }
  13501. }
  13502. ZodNever.create = params =>
  13503. new ZodNever({
  13504. typeName: ZodFirstPartyTypeKind.ZodNever,
  13505. ...processCreateParams(params),
  13506. })
  13507. class ZodVoid extends ZodType {
  13508. _parse(input) {
  13509. if (this._getType(input) !== ZodParsedType.undefined) {
  13510. const ctx = this._getOrReturnCtx(input)
  13511. addIssueToContext(ctx, {
  13512. code: ZodIssueCode.invalid_type,
  13513. expected: ZodParsedType.void,
  13514. received: ctx.parsedType,
  13515. })
  13516. return INVALID
  13517. }
  13518. return OK(input.data)
  13519. }
  13520. }
  13521. ZodVoid.create = params =>
  13522. new ZodVoid({
  13523. typeName: ZodFirstPartyTypeKind.ZodVoid,
  13524. ...processCreateParams(params),
  13525. })
  13526. class ZodArray extends ZodType {
  13527. _parse(input) {
  13528. const { ctx, status } = this._processInputParams(input),
  13529. def = this._def
  13530. if (ctx.parsedType !== ZodParsedType.array) {
  13531. addIssueToContext(ctx, {
  13532. code: ZodIssueCode.invalid_type,
  13533. expected: ZodParsedType.array,
  13534. received: ctx.parsedType,
  13535. })
  13536. return INVALID
  13537. }
  13538. if (null !== def.exactLength) {
  13539. const tooBig = ctx.data.length > def.exactLength.value,
  13540. tooSmall = ctx.data.length < def.exactLength.value
  13541. if (tooBig || tooSmall) {
  13542. addIssueToContext(ctx, {
  13543. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  13544. minimum: tooSmall ? def.exactLength.value : void 0,
  13545. maximum: tooBig ? def.exactLength.value : void 0,
  13546. type: "array",
  13547. inclusive: !0,
  13548. exact: !0,
  13549. message: def.exactLength.message,
  13550. })
  13551. status.dirty()
  13552. }
  13553. }
  13554. if (null !== def.minLength && ctx.data.length < def.minLength.value) {
  13555. addIssueToContext(ctx, {
  13556. code: ZodIssueCode.too_small,
  13557. minimum: def.minLength.value,
  13558. type: "array",
  13559. inclusive: !0,
  13560. exact: !1,
  13561. message: def.minLength.message,
  13562. })
  13563. status.dirty()
  13564. }
  13565. if (null !== def.maxLength && ctx.data.length > def.maxLength.value) {
  13566. addIssueToContext(ctx, {
  13567. code: ZodIssueCode.too_big,
  13568. maximum: def.maxLength.value,
  13569. type: "array",
  13570. inclusive: !0,
  13571. exact: !1,
  13572. message: def.maxLength.message,
  13573. })
  13574. status.dirty()
  13575. }
  13576. if (ctx.common.async)
  13577. return Promise.all(
  13578. [...ctx.data].map((item, i) =>
  13579. def.type._parseAsync(
  13580. new ParseInputLazyPath(ctx, item, ctx.path, i)
  13581. )
  13582. )
  13583. ).then(result => ParseStatus.mergeArray(status, result))
  13584. const result = [...ctx.data].map((item, i) =>
  13585. def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))
  13586. )
  13587. return ParseStatus.mergeArray(status, result)
  13588. }
  13589. get element() {
  13590. return this._def.type
  13591. }
  13592. min(minLength, message) {
  13593. return new ZodArray({
  13594. ...this._def,
  13595. minLength: { value: minLength, message: errorUtil.toString(message) },
  13596. })
  13597. }
  13598. max(maxLength, message) {
  13599. return new ZodArray({
  13600. ...this._def,
  13601. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  13602. })
  13603. }
  13604. length(len, message) {
  13605. return new ZodArray({
  13606. ...this._def,
  13607. exactLength: { value: len, message: errorUtil.toString(message) },
  13608. })
  13609. }
  13610. nonempty(message) {
  13611. return this.min(1, message)
  13612. }
  13613. }
  13614. ZodArray.create = (schema, params) =>
  13615. new ZodArray({
  13616. type: schema,
  13617. minLength: null,
  13618. maxLength: null,
  13619. exactLength: null,
  13620. typeName: ZodFirstPartyTypeKind.ZodArray,
  13621. ...processCreateParams(params),
  13622. })
  13623. function deepPartialify(schema) {
  13624. if (schema instanceof ZodObject) {
  13625. const newShape = {}
  13626. for (const key in schema.shape) {
  13627. const fieldSchema = schema.shape[key]
  13628. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema))
  13629. }
  13630. return new ZodObject({ ...schema._def, shape: () => newShape })
  13631. }
  13632. return schema instanceof ZodArray
  13633. ? new ZodArray({ ...schema._def, type: deepPartialify(schema.element) })
  13634. : schema instanceof ZodOptional
  13635. ? ZodOptional.create(deepPartialify(schema.unwrap()))
  13636. : schema instanceof ZodNullable
  13637. ? ZodNullable.create(deepPartialify(schema.unwrap()))
  13638. : schema instanceof ZodTuple
  13639. ? ZodTuple.create(schema.items.map(item => deepPartialify(item)))
  13640. : schema
  13641. }
  13642. class ZodObject extends ZodType {
  13643. constructor() {
  13644. super(...arguments)
  13645. this._cached = null
  13646. this.nonstrict = this.passthrough
  13647. this.augment = this.extend
  13648. }
  13649. _getCached() {
  13650. if (null !== this._cached) return this._cached
  13651. const shape = this._def.shape(),
  13652. keys = util.objectKeys(shape)
  13653. return (this._cached = { shape, keys })
  13654. }
  13655. _parse(input) {
  13656. if (this._getType(input) !== ZodParsedType.object) {
  13657. const ctx = this._getOrReturnCtx(input)
  13658. addIssueToContext(ctx, {
  13659. code: ZodIssueCode.invalid_type,
  13660. expected: ZodParsedType.object,
  13661. received: ctx.parsedType,
  13662. })
  13663. return INVALID
  13664. }
  13665. const { status, ctx } = this._processInputParams(input),
  13666. { shape, keys: shapeKeys } = this._getCached(),
  13667. extraKeys = []
  13668. if (
  13669. !(
  13670. this._def.catchall instanceof ZodNever &&
  13671. "strip" === this._def.unknownKeys
  13672. )
  13673. )
  13674. for (const key in ctx.data)
  13675. shapeKeys.includes(key) || extraKeys.push(key)
  13676. const pairs = []
  13677. for (const key of shapeKeys) {
  13678. const keyValidator = shape[key],
  13679. value = ctx.data[key]
  13680. pairs.push({
  13681. key: { status: "valid", value: key },
  13682. value: keyValidator._parse(
  13683. new ParseInputLazyPath(ctx, value, ctx.path, key)
  13684. ),
  13685. alwaysSet: key in ctx.data,
  13686. })
  13687. }
  13688. if (this._def.catchall instanceof ZodNever) {
  13689. const unknownKeys = this._def.unknownKeys
  13690. if ("passthrough" === unknownKeys)
  13691. for (const key of extraKeys)
  13692. pairs.push({
  13693. key: { status: "valid", value: key },
  13694. value: { status: "valid", value: ctx.data[key] },
  13695. })
  13696. else if ("strict" === unknownKeys) {
  13697. if (extraKeys.length > 0) {
  13698. addIssueToContext(ctx, {
  13699. code: ZodIssueCode.unrecognized_keys,
  13700. keys: extraKeys,
  13701. })
  13702. status.dirty()
  13703. }
  13704. } else if ("strip" !== unknownKeys)
  13705. throw new Error(
  13706. "Internal ZodObject error: invalid unknownKeys value."
  13707. )
  13708. } else {
  13709. const catchall = this._def.catchall
  13710. for (const key of extraKeys) {
  13711. const value = ctx.data[key]
  13712. pairs.push({
  13713. key: { status: "valid", value: key },
  13714. value: catchall._parse(
  13715. new ParseInputLazyPath(ctx, value, ctx.path, key)
  13716. ),
  13717. alwaysSet: key in ctx.data,
  13718. })
  13719. }
  13720. }
  13721. return ctx.common.async
  13722. ? Promise.resolve()
  13723. .then(async () => {
  13724. const syncPairs = []
  13725. for (const pair of pairs) {
  13726. const key = await pair.key
  13727. syncPairs.push({
  13728. key,
  13729. value: await pair.value,
  13730. alwaysSet: pair.alwaysSet,
  13731. })
  13732. }
  13733. return syncPairs
  13734. })
  13735. .then(syncPairs => ParseStatus.mergeObjectSync(status, syncPairs))
  13736. : ParseStatus.mergeObjectSync(status, pairs)
  13737. }
  13738. get shape() {
  13739. return this._def.shape()
  13740. }
  13741. strict(message) {
  13742. errorUtil.errToObj
  13743. return new ZodObject({
  13744. ...this._def,
  13745. unknownKeys: "strict",
  13746. ...(void 0 !== message
  13747. ? {
  13748. errorMap: (issue, ctx) => {
  13749. var _a, _b, _c, _d
  13750. const defaultError =
  13751. null !==
  13752. (_c =
  13753. null === (_b = (_a = this._def).errorMap) ||
  13754. void 0 === _b
  13755. ? void 0
  13756. : _b.call(_a, issue, ctx).message) && void 0 !== _c
  13757. ? _c
  13758. : ctx.defaultError
  13759. return "unrecognized_keys" === issue.code
  13760. ? {
  13761. message:
  13762. null !== (_d = errorUtil.errToObj(message).message) &&
  13763. void 0 !== _d
  13764. ? _d
  13765. : defaultError,
  13766. }
  13767. : { message: defaultError }
  13768. },
  13769. }
  13770. : {}),
  13771. })
  13772. }
  13773. strip() {
  13774. return new ZodObject({ ...this._def, unknownKeys: "strip" })
  13775. }
  13776. passthrough() {
  13777. return new ZodObject({ ...this._def, unknownKeys: "passthrough" })
  13778. }
  13779. extend(augmentation) {
  13780. return new ZodObject({
  13781. ...this._def,
  13782. shape: () => ({ ...this._def.shape(), ...augmentation }),
  13783. })
  13784. }
  13785. merge(merging) {
  13786. return new ZodObject({
  13787. unknownKeys: merging._def.unknownKeys,
  13788. catchall: merging._def.catchall,
  13789. shape: () => ({ ...this._def.shape(), ...merging._def.shape() }),
  13790. typeName: ZodFirstPartyTypeKind.ZodObject,
  13791. })
  13792. }
  13793. setKey(key, schema) {
  13794. return this.augment({ [key]: schema })
  13795. }
  13796. catchall(index) {
  13797. return new ZodObject({ ...this._def, catchall: index })
  13798. }
  13799. pick(mask) {
  13800. const shape = {}
  13801. util.objectKeys(mask).forEach(key => {
  13802. mask[key] && this.shape[key] && (shape[key] = this.shape[key])
  13803. })
  13804. return new ZodObject({ ...this._def, shape: () => shape })
  13805. }
  13806. omit(mask) {
  13807. const shape = {}
  13808. util.objectKeys(this.shape).forEach(key => {
  13809. mask[key] || (shape[key] = this.shape[key])
  13810. })
  13811. return new ZodObject({ ...this._def, shape: () => shape })
  13812. }
  13813. deepPartial() {
  13814. return deepPartialify(this)
  13815. }
  13816. partial(mask) {
  13817. const newShape = {}
  13818. util.objectKeys(this.shape).forEach(key => {
  13819. const fieldSchema = this.shape[key]
  13820. mask && !mask[key]
  13821. ? (newShape[key] = fieldSchema)
  13822. : (newShape[key] = fieldSchema.optional())
  13823. })
  13824. return new ZodObject({ ...this._def, shape: () => newShape })
  13825. }
  13826. required(mask) {
  13827. const newShape = {}
  13828. util.objectKeys(this.shape).forEach(key => {
  13829. if (mask && !mask[key]) newShape[key] = this.shape[key]
  13830. else {
  13831. let newField = this.shape[key]
  13832. for (; newField instanceof ZodOptional; )
  13833. newField = newField._def.innerType
  13834. newShape[key] = newField
  13835. }
  13836. })
  13837. return new ZodObject({ ...this._def, shape: () => newShape })
  13838. }
  13839. keyof() {
  13840. return createZodEnum(util.objectKeys(this.shape))
  13841. }
  13842. }
  13843. ZodObject.create = (shape, params) =>
  13844. new ZodObject({
  13845. shape: () => shape,
  13846. unknownKeys: "strip",
  13847. catchall: ZodNever.create(),
  13848. typeName: ZodFirstPartyTypeKind.ZodObject,
  13849. ...processCreateParams(params),
  13850. })
  13851. ZodObject.strictCreate = (shape, params) =>
  13852. new ZodObject({
  13853. shape: () => shape,
  13854. unknownKeys: "strict",
  13855. catchall: ZodNever.create(),
  13856. typeName: ZodFirstPartyTypeKind.ZodObject,
  13857. ...processCreateParams(params),
  13858. })
  13859. ZodObject.lazycreate = (shape, params) =>
  13860. new ZodObject({
  13861. shape,
  13862. unknownKeys: "strip",
  13863. catchall: ZodNever.create(),
  13864. typeName: ZodFirstPartyTypeKind.ZodObject,
  13865. ...processCreateParams(params),
  13866. })
  13867. class ZodUnion extends ZodType {
  13868. _parse(input) {
  13869. const { ctx } = this._processInputParams(input),
  13870. options = this._def.options
  13871. if (ctx.common.async)
  13872. return Promise.all(
  13873. options.map(async option => {
  13874. const childCtx = {
  13875. ...ctx,
  13876. common: { ...ctx.common, issues: [] },
  13877. parent: null,
  13878. }
  13879. return {
  13880. result: await option._parseAsync({
  13881. data: ctx.data,
  13882. path: ctx.path,
  13883. parent: childCtx,
  13884. }),
  13885. ctx: childCtx,
  13886. }
  13887. })
  13888. ).then(function (results) {
  13889. for (const result of results)
  13890. if ("valid" === result.result.status) return result.result
  13891. for (const result of results)
  13892. if ("dirty" === result.result.status) {
  13893. ctx.common.issues.push(...result.ctx.common.issues)
  13894. return result.result
  13895. }
  13896. const unionErrors = results.map(
  13897. result => new ZodError(result.ctx.common.issues)
  13898. )
  13899. addIssueToContext(ctx, {
  13900. code: ZodIssueCode.invalid_union,
  13901. unionErrors,
  13902. })
  13903. return INVALID
  13904. })
  13905. {
  13906. let dirty
  13907. const issues = []
  13908. for (const option of options) {
  13909. const childCtx = {
  13910. ...ctx,
  13911. common: { ...ctx.common, issues: [] },
  13912. parent: null,
  13913. },
  13914. result = option._parseSync({
  13915. data: ctx.data,
  13916. path: ctx.path,
  13917. parent: childCtx,
  13918. })
  13919. if ("valid" === result.status) return result
  13920. "dirty" !== result.status ||
  13921. dirty ||
  13922. (dirty = { result, ctx: childCtx })
  13923. childCtx.common.issues.length && issues.push(childCtx.common.issues)
  13924. }
  13925. if (dirty) {
  13926. ctx.common.issues.push(...dirty.ctx.common.issues)
  13927. return dirty.result
  13928. }
  13929. const unionErrors = issues.map(issues => new ZodError(issues))
  13930. addIssueToContext(ctx, {
  13931. code: ZodIssueCode.invalid_union,
  13932. unionErrors,
  13933. })
  13934. return INVALID
  13935. }
  13936. }
  13937. get options() {
  13938. return this._def.options
  13939. }
  13940. }
  13941. ZodUnion.create = (types, params) =>
  13942. new ZodUnion({
  13943. options: types,
  13944. typeName: ZodFirstPartyTypeKind.ZodUnion,
  13945. ...processCreateParams(params),
  13946. })
  13947. const getDiscriminator = type =>
  13948. type instanceof ZodLazy
  13949. ? getDiscriminator(type.schema)
  13950. : type instanceof ZodEffects
  13951. ? getDiscriminator(type.innerType())
  13952. : type instanceof ZodLiteral
  13953. ? [type.value]
  13954. : type instanceof ZodEnum
  13955. ? type.options
  13956. : type instanceof ZodNativeEnum
  13957. ? Object.keys(type.enum)
  13958. : type instanceof ZodDefault
  13959. ? getDiscriminator(type._def.innerType)
  13960. : type instanceof ZodUndefined
  13961. ? [void 0]
  13962. : type instanceof ZodNull
  13963. ? [null]
  13964. : null
  13965. class ZodDiscriminatedUnion extends ZodType {
  13966. _parse(input) {
  13967. const { ctx } = this._processInputParams(input)
  13968. if (ctx.parsedType !== ZodParsedType.object) {
  13969. addIssueToContext(ctx, {
  13970. code: ZodIssueCode.invalid_type,
  13971. expected: ZodParsedType.object,
  13972. received: ctx.parsedType,
  13973. })
  13974. return INVALID
  13975. }
  13976. const discriminator = this.discriminator,
  13977. discriminatorValue = ctx.data[discriminator],
  13978. option = this.optionsMap.get(discriminatorValue)
  13979. if (!option) {
  13980. addIssueToContext(ctx, {
  13981. code: ZodIssueCode.invalid_union_discriminator,
  13982. options: Array.from(this.optionsMap.keys()),
  13983. path: [discriminator],
  13984. })
  13985. return INVALID
  13986. }
  13987. return ctx.common.async
  13988. ? option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  13989. : option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })
  13990. }
  13991. get discriminator() {
  13992. return this._def.discriminator
  13993. }
  13994. get options() {
  13995. return this._def.options
  13996. }
  13997. get optionsMap() {
  13998. return this._def.optionsMap
  13999. }
  14000. static create(discriminator, options, params) {
  14001. const optionsMap = new Map()
  14002. for (const type of options) {
  14003. const discriminatorValues = getDiscriminator(
  14004. type.shape[discriminator]
  14005. )
  14006. if (!discriminatorValues)
  14007. throw new Error(
  14008. `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`
  14009. )
  14010. for (const value of discriminatorValues) {
  14011. if (optionsMap.has(value))
  14012. throw new Error(
  14013. `Discriminator property ${String(
  14014. discriminator
  14015. )} has duplicate value ${String(value)}`
  14016. )
  14017. optionsMap.set(value, type)
  14018. }
  14019. }
  14020. return new ZodDiscriminatedUnion({
  14021. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  14022. discriminator,
  14023. options,
  14024. optionsMap,
  14025. ...processCreateParams(params),
  14026. })
  14027. }
  14028. }
  14029. function mergeValues(a, b) {
  14030. const aType = getParsedType(a),
  14031. bType = getParsedType(b)
  14032. if (a === b) return { valid: !0, data: a }
  14033. if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  14034. const bKeys = util.objectKeys(b),
  14035. sharedKeys = util
  14036. .objectKeys(a)
  14037. .filter(key => -1 !== bKeys.indexOf(key)),
  14038. newObj = { ...a, ...b }
  14039. for (const key of sharedKeys) {
  14040. const sharedValue = mergeValues(a[key], b[key])
  14041. if (!sharedValue.valid) return { valid: !1 }
  14042. newObj[key] = sharedValue.data
  14043. }
  14044. return { valid: !0, data: newObj }
  14045. }
  14046. if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  14047. if (a.length !== b.length) return { valid: !1 }
  14048. const newArray = []
  14049. for (let index = 0; index < a.length; index++) {
  14050. const sharedValue = mergeValues(a[index], b[index])
  14051. if (!sharedValue.valid) return { valid: !1 }
  14052. newArray.push(sharedValue.data)
  14053. }
  14054. return { valid: !0, data: newArray }
  14055. }
  14056. return aType === ZodParsedType.date &&
  14057. bType === ZodParsedType.date &&
  14058. +a == +b
  14059. ? { valid: !0, data: a }
  14060. : { valid: !1 }
  14061. }
  14062. class ZodIntersection extends ZodType {
  14063. _parse(input) {
  14064. const { status, ctx } = this._processInputParams(input),
  14065. handleParsed = (parsedLeft, parsedRight) => {
  14066. if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID
  14067. const merged = mergeValues(parsedLeft.value, parsedRight.value)
  14068. if (!merged.valid) {
  14069. addIssueToContext(ctx, {
  14070. code: ZodIssueCode.invalid_intersection_types,
  14071. })
  14072. return INVALID
  14073. }
  14074. ;(isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty()
  14075. return { status: status.value, value: merged.data }
  14076. }
  14077. return ctx.common.async
  14078. ? Promise.all([
  14079. this._def.left._parseAsync({
  14080. data: ctx.data,
  14081. path: ctx.path,
  14082. parent: ctx,
  14083. }),
  14084. this._def.right._parseAsync({
  14085. data: ctx.data,
  14086. path: ctx.path,
  14087. parent: ctx,
  14088. }),
  14089. ]).then(([left, right]) => handleParsed(left, right))
  14090. : handleParsed(
  14091. this._def.left._parseSync({
  14092. data: ctx.data,
  14093. path: ctx.path,
  14094. parent: ctx,
  14095. }),
  14096. this._def.right._parseSync({
  14097. data: ctx.data,
  14098. path: ctx.path,
  14099. parent: ctx,
  14100. })
  14101. )
  14102. }
  14103. }
  14104. ZodIntersection.create = (left, right, params) =>
  14105. new ZodIntersection({
  14106. left,
  14107. right,
  14108. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  14109. ...processCreateParams(params),
  14110. })
  14111. class ZodTuple extends ZodType {
  14112. _parse(input) {
  14113. const { status, ctx } = this._processInputParams(input)
  14114. if (ctx.parsedType !== ZodParsedType.array) {
  14115. addIssueToContext(ctx, {
  14116. code: ZodIssueCode.invalid_type,
  14117. expected: ZodParsedType.array,
  14118. received: ctx.parsedType,
  14119. })
  14120. return INVALID
  14121. }
  14122. if (ctx.data.length < this._def.items.length) {
  14123. addIssueToContext(ctx, {
  14124. code: ZodIssueCode.too_small,
  14125. minimum: this._def.items.length,
  14126. inclusive: !0,
  14127. exact: !1,
  14128. type: "array",
  14129. })
  14130. return INVALID
  14131. }
  14132. if (!this._def.rest && ctx.data.length > this._def.items.length) {
  14133. addIssueToContext(ctx, {
  14134. code: ZodIssueCode.too_big,
  14135. maximum: this._def.items.length,
  14136. inclusive: !0,
  14137. exact: !1,
  14138. type: "array",
  14139. })
  14140. status.dirty()
  14141. }
  14142. const items = [...ctx.data]
  14143. .map((item, itemIndex) => {
  14144. const schema = this._def.items[itemIndex] || this._def.rest
  14145. return schema
  14146. ? schema._parse(
  14147. new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)
  14148. )
  14149. : null
  14150. })
  14151. .filter(x => !!x)
  14152. return ctx.common.async
  14153. ? Promise.all(items).then(results =>
  14154. ParseStatus.mergeArray(status, results)
  14155. )
  14156. : ParseStatus.mergeArray(status, items)
  14157. }
  14158. get items() {
  14159. return this._def.items
  14160. }
  14161. rest(rest) {
  14162. return new ZodTuple({ ...this._def, rest })
  14163. }
  14164. }
  14165. ZodTuple.create = (schemas, params) => {
  14166. if (!Array.isArray(schemas))
  14167. throw new Error("You must pass an array of schemas to z.tuple([ ... ])")
  14168. return new ZodTuple({
  14169. items: schemas,
  14170. typeName: ZodFirstPartyTypeKind.ZodTuple,
  14171. rest: null,
  14172. ...processCreateParams(params),
  14173. })
  14174. }
  14175. class ZodRecord extends ZodType {
  14176. get keySchema() {
  14177. return this._def.keyType
  14178. }
  14179. get valueSchema() {
  14180. return this._def.valueType
  14181. }
  14182. _parse(input) {
  14183. const { status, ctx } = this._processInputParams(input)
  14184. if (ctx.parsedType !== ZodParsedType.object) {
  14185. addIssueToContext(ctx, {
  14186. code: ZodIssueCode.invalid_type,
  14187. expected: ZodParsedType.object,
  14188. received: ctx.parsedType,
  14189. })
  14190. return INVALID
  14191. }
  14192. const pairs = [],
  14193. keyType = this._def.keyType,
  14194. valueType = this._def.valueType
  14195. for (const key in ctx.data)
  14196. pairs.push({
  14197. key: keyType._parse(
  14198. new ParseInputLazyPath(ctx, key, ctx.path, key)
  14199. ),
  14200. value: valueType._parse(
  14201. new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
  14202. ),
  14203. })
  14204. return ctx.common.async
  14205. ? ParseStatus.mergeObjectAsync(status, pairs)
  14206. : ParseStatus.mergeObjectSync(status, pairs)
  14207. }
  14208. get element() {
  14209. return this._def.valueType
  14210. }
  14211. static create(first, second, third) {
  14212. return new ZodRecord(
  14213. second instanceof ZodType
  14214. ? {
  14215. keyType: first,
  14216. valueType: second,
  14217. typeName: ZodFirstPartyTypeKind.ZodRecord,
  14218. ...processCreateParams(third),
  14219. }
  14220. : {
  14221. keyType: ZodString.create(),
  14222. valueType: first,
  14223. typeName: ZodFirstPartyTypeKind.ZodRecord,
  14224. ...processCreateParams(second),
  14225. }
  14226. )
  14227. }
  14228. }
  14229. class ZodMap extends ZodType {
  14230. _parse(input) {
  14231. const { status, ctx } = this._processInputParams(input)
  14232. if (ctx.parsedType !== ZodParsedType.map) {
  14233. addIssueToContext(ctx, {
  14234. code: ZodIssueCode.invalid_type,
  14235. expected: ZodParsedType.map,
  14236. received: ctx.parsedType,
  14237. })
  14238. return INVALID
  14239. }
  14240. const keyType = this._def.keyType,
  14241. valueType = this._def.valueType,
  14242. pairs = [...ctx.data.entries()].map(([key, value], index) => ({
  14243. key: keyType._parse(
  14244. new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])
  14245. ),
  14246. value: valueType._parse(
  14247. new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])
  14248. ),
  14249. }))
  14250. if (ctx.common.async) {
  14251. const finalMap = new Map()
  14252. return Promise.resolve().then(async () => {
  14253. for (const pair of pairs) {
  14254. const key = await pair.key,
  14255. value = await pair.value
  14256. if ("aborted" === key.status || "aborted" === value.status)
  14257. return INVALID
  14258. ;("dirty" !== key.status && "dirty" !== value.status) ||
  14259. status.dirty()
  14260. finalMap.set(key.value, value.value)
  14261. }
  14262. return { status: status.value, value: finalMap }
  14263. })
  14264. }
  14265. {
  14266. const finalMap = new Map()
  14267. for (const pair of pairs) {
  14268. const key = pair.key,
  14269. value = pair.value
  14270. if ("aborted" === key.status || "aborted" === value.status)
  14271. return INVALID
  14272. ;("dirty" !== key.status && "dirty" !== value.status) ||
  14273. status.dirty()
  14274. finalMap.set(key.value, value.value)
  14275. }
  14276. return { status: status.value, value: finalMap }
  14277. }
  14278. }
  14279. }
  14280. ZodMap.create = (keyType, valueType, params) =>
  14281. new ZodMap({
  14282. valueType,
  14283. keyType,
  14284. typeName: ZodFirstPartyTypeKind.ZodMap,
  14285. ...processCreateParams(params),
  14286. })
  14287. class ZodSet extends ZodType {
  14288. _parse(input) {
  14289. const { status, ctx } = this._processInputParams(input)
  14290. if (ctx.parsedType !== ZodParsedType.set) {
  14291. addIssueToContext(ctx, {
  14292. code: ZodIssueCode.invalid_type,
  14293. expected: ZodParsedType.set,
  14294. received: ctx.parsedType,
  14295. })
  14296. return INVALID
  14297. }
  14298. const def = this._def
  14299. if (null !== def.minSize && ctx.data.size < def.minSize.value) {
  14300. addIssueToContext(ctx, {
  14301. code: ZodIssueCode.too_small,
  14302. minimum: def.minSize.value,
  14303. type: "set",
  14304. inclusive: !0,
  14305. exact: !1,
  14306. message: def.minSize.message,
  14307. })
  14308. status.dirty()
  14309. }
  14310. if (null !== def.maxSize && ctx.data.size > def.maxSize.value) {
  14311. addIssueToContext(ctx, {
  14312. code: ZodIssueCode.too_big,
  14313. maximum: def.maxSize.value,
  14314. type: "set",
  14315. inclusive: !0,
  14316. exact: !1,
  14317. message: def.maxSize.message,
  14318. })
  14319. status.dirty()
  14320. }
  14321. const valueType = this._def.valueType
  14322. function finalizeSet(elements) {
  14323. const parsedSet = new Set()
  14324. for (const element of elements) {
  14325. if ("aborted" === element.status) return INVALID
  14326. "dirty" === element.status && status.dirty()
  14327. parsedSet.add(element.value)
  14328. }
  14329. return { status: status.value, value: parsedSet }
  14330. }
  14331. const elements = [...ctx.data.values()].map((item, i) =>
  14332. valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))
  14333. )
  14334. return ctx.common.async
  14335. ? Promise.all(elements).then(elements => finalizeSet(elements))
  14336. : finalizeSet(elements)
  14337. }
  14338. min(minSize, message) {
  14339. return new ZodSet({
  14340. ...this._def,
  14341. minSize: { value: minSize, message: errorUtil.toString(message) },
  14342. })
  14343. }
  14344. max(maxSize, message) {
  14345. return new ZodSet({
  14346. ...this._def,
  14347. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  14348. })
  14349. }
  14350. size(size, message) {
  14351. return this.min(size, message).max(size, message)
  14352. }
  14353. nonempty(message) {
  14354. return this.min(1, message)
  14355. }
  14356. }
  14357. ZodSet.create = (valueType, params) =>
  14358. new ZodSet({
  14359. valueType,
  14360. minSize: null,
  14361. maxSize: null,
  14362. typeName: ZodFirstPartyTypeKind.ZodSet,
  14363. ...processCreateParams(params),
  14364. })
  14365. class ZodFunction extends ZodType {
  14366. constructor() {
  14367. super(...arguments)
  14368. this.validate = this.implement
  14369. }
  14370. _parse(input) {
  14371. const { ctx } = this._processInputParams(input)
  14372. if (ctx.parsedType !== ZodParsedType.function) {
  14373. addIssueToContext(ctx, {
  14374. code: ZodIssueCode.invalid_type,
  14375. expected: ZodParsedType.function,
  14376. received: ctx.parsedType,
  14377. })
  14378. return INVALID
  14379. }
  14380. function makeArgsIssue(args, error) {
  14381. return makeIssue({
  14382. data: args,
  14383. path: ctx.path,
  14384. errorMaps: [
  14385. ctx.common.contextualErrorMap,
  14386. ctx.schemaErrorMap,
  14387. getErrorMap(),
  14388. errorMap,
  14389. ].filter(x => !!x),
  14390. issueData: {
  14391. code: ZodIssueCode.invalid_arguments,
  14392. argumentsError: error,
  14393. },
  14394. })
  14395. }
  14396. function makeReturnsIssue(returns, error) {
  14397. return makeIssue({
  14398. data: returns,
  14399. path: ctx.path,
  14400. errorMaps: [
  14401. ctx.common.contextualErrorMap,
  14402. ctx.schemaErrorMap,
  14403. getErrorMap(),
  14404. errorMap,
  14405. ].filter(x => !!x),
  14406. issueData: {
  14407. code: ZodIssueCode.invalid_return_type,
  14408. returnTypeError: error,
  14409. },
  14410. })
  14411. }
  14412. const params = { errorMap: ctx.common.contextualErrorMap },
  14413. fn = ctx.data
  14414. return this._def.returns instanceof ZodPromise
  14415. ? OK(async (...args) => {
  14416. const error = new ZodError([]),
  14417. parsedArgs = await this._def.args
  14418. .parseAsync(args, params)
  14419. .catch(e => {
  14420. error.addIssue(makeArgsIssue(args, e))
  14421. throw error
  14422. }),
  14423. result = await fn(...parsedArgs)
  14424. return await this._def.returns._def.type
  14425. .parseAsync(result, params)
  14426. .catch(e => {
  14427. error.addIssue(makeReturnsIssue(result, e))
  14428. throw error
  14429. })
  14430. })
  14431. : OK((...args) => {
  14432. const parsedArgs = this._def.args.safeParse(args, params)
  14433. if (!parsedArgs.success)
  14434. throw new ZodError([makeArgsIssue(args, parsedArgs.error)])
  14435. const result = fn(...parsedArgs.data),
  14436. parsedReturns = this._def.returns.safeParse(result, params)
  14437. if (!parsedReturns.success)
  14438. throw new ZodError([
  14439. makeReturnsIssue(result, parsedReturns.error),
  14440. ])
  14441. return parsedReturns.data
  14442. })
  14443. }
  14444. parameters() {
  14445. return this._def.args
  14446. }
  14447. returnType() {
  14448. return this._def.returns
  14449. }
  14450. args(...items) {
  14451. return new ZodFunction({
  14452. ...this._def,
  14453. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  14454. })
  14455. }
  14456. returns(returnType) {
  14457. return new ZodFunction({ ...this._def, returns: returnType })
  14458. }
  14459. implement(func) {
  14460. return this.parse(func)
  14461. }
  14462. strictImplement(func) {
  14463. return this.parse(func)
  14464. }
  14465. static create(args, returns, params) {
  14466. return new ZodFunction({
  14467. args: args || ZodTuple.create([]).rest(ZodUnknown.create()),
  14468. returns: returns || ZodUnknown.create(),
  14469. typeName: ZodFirstPartyTypeKind.ZodFunction,
  14470. ...processCreateParams(params),
  14471. })
  14472. }
  14473. }
  14474. class ZodLazy extends ZodType {
  14475. get schema() {
  14476. return this._def.getter()
  14477. }
  14478. _parse(input) {
  14479. const { ctx } = this._processInputParams(input)
  14480. return this._def
  14481. .getter()
  14482. ._parse({ data: ctx.data, path: ctx.path, parent: ctx })
  14483. }
  14484. }
  14485. ZodLazy.create = (getter, params) =>
  14486. new ZodLazy({
  14487. getter,
  14488. typeName: ZodFirstPartyTypeKind.ZodLazy,
  14489. ...processCreateParams(params),
  14490. })
  14491. class ZodLiteral extends ZodType {
  14492. _parse(input) {
  14493. if (input.data !== this._def.value) {
  14494. const ctx = this._getOrReturnCtx(input)
  14495. addIssueToContext(ctx, {
  14496. received: ctx.data,
  14497. code: ZodIssueCode.invalid_literal,
  14498. expected: this._def.value,
  14499. })
  14500. return INVALID
  14501. }
  14502. return { status: "valid", value: input.data }
  14503. }
  14504. get value() {
  14505. return this._def.value
  14506. }
  14507. }
  14508. ZodLiteral.create = (value, params) =>
  14509. new ZodLiteral({
  14510. value,
  14511. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  14512. ...processCreateParams(params),
  14513. })
  14514. function createZodEnum(values, params) {
  14515. return new ZodEnum({
  14516. values,
  14517. typeName: ZodFirstPartyTypeKind.ZodEnum,
  14518. ...processCreateParams(params),
  14519. })
  14520. }
  14521. class ZodEnum extends ZodType {
  14522. _parse(input) {
  14523. if ("string" != typeof input.data) {
  14524. const ctx = this._getOrReturnCtx(input),
  14525. expectedValues = this._def.values
  14526. addIssueToContext(ctx, {
  14527. expected: util.joinValues(expectedValues),
  14528. received: ctx.parsedType,
  14529. code: ZodIssueCode.invalid_type,
  14530. })
  14531. return INVALID
  14532. }
  14533. if (-1 === this._def.values.indexOf(input.data)) {
  14534. const ctx = this._getOrReturnCtx(input),
  14535. expectedValues = this._def.values
  14536. addIssueToContext(ctx, {
  14537. received: ctx.data,
  14538. code: ZodIssueCode.invalid_enum_value,
  14539. options: expectedValues,
  14540. })
  14541. return INVALID
  14542. }
  14543. return OK(input.data)
  14544. }
  14545. get options() {
  14546. return this._def.values
  14547. }
  14548. get enum() {
  14549. const enumValues = {}
  14550. for (const val of this._def.values) enumValues[val] = val
  14551. return enumValues
  14552. }
  14553. get Values() {
  14554. const enumValues = {}
  14555. for (const val of this._def.values) enumValues[val] = val
  14556. return enumValues
  14557. }
  14558. get Enum() {
  14559. const enumValues = {}
  14560. for (const val of this._def.values) enumValues[val] = val
  14561. return enumValues
  14562. }
  14563. extract(values) {
  14564. return ZodEnum.create(values)
  14565. }
  14566. exclude(values) {
  14567. return ZodEnum.create(this.options.filter(opt => !values.includes(opt)))
  14568. }
  14569. }
  14570. ZodEnum.create = createZodEnum
  14571. class ZodNativeEnum extends ZodType {
  14572. _parse(input) {
  14573. const nativeEnumValues = util.getValidEnumValues(this._def.values),
  14574. ctx = this._getOrReturnCtx(input)
  14575. if (
  14576. ctx.parsedType !== ZodParsedType.string &&
  14577. ctx.parsedType !== ZodParsedType.number
  14578. ) {
  14579. const expectedValues = util.objectValues(nativeEnumValues)
  14580. addIssueToContext(ctx, {
  14581. expected: util.joinValues(expectedValues),
  14582. received: ctx.parsedType,
  14583. code: ZodIssueCode.invalid_type,
  14584. })
  14585. return INVALID
  14586. }
  14587. if (-1 === nativeEnumValues.indexOf(input.data)) {
  14588. const expectedValues = util.objectValues(nativeEnumValues)
  14589. addIssueToContext(ctx, {
  14590. received: ctx.data,
  14591. code: ZodIssueCode.invalid_enum_value,
  14592. options: expectedValues,
  14593. })
  14594. return INVALID
  14595. }
  14596. return OK(input.data)
  14597. }
  14598. get enum() {
  14599. return this._def.values
  14600. }
  14601. }
  14602. ZodNativeEnum.create = (values, params) =>
  14603. new ZodNativeEnum({
  14604. values,
  14605. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  14606. ...processCreateParams(params),
  14607. })
  14608. class ZodPromise extends ZodType {
  14609. unwrap() {
  14610. return this._def.type
  14611. }
  14612. _parse(input) {
  14613. const { ctx } = this._processInputParams(input)
  14614. if (
  14615. ctx.parsedType !== ZodParsedType.promise &&
  14616. !1 === ctx.common.async
  14617. ) {
  14618. addIssueToContext(ctx, {
  14619. code: ZodIssueCode.invalid_type,
  14620. expected: ZodParsedType.promise,
  14621. received: ctx.parsedType,
  14622. })
  14623. return INVALID
  14624. }
  14625. const promisified =
  14626. ctx.parsedType === ZodParsedType.promise
  14627. ? ctx.data
  14628. : Promise.resolve(ctx.data)
  14629. return OK(
  14630. promisified.then(data =>
  14631. this._def.type.parseAsync(data, {
  14632. path: ctx.path,
  14633. errorMap: ctx.common.contextualErrorMap,
  14634. })
  14635. )
  14636. )
  14637. }
  14638. }
  14639. ZodPromise.create = (schema, params) =>
  14640. new ZodPromise({
  14641. type: schema,
  14642. typeName: ZodFirstPartyTypeKind.ZodPromise,
  14643. ...processCreateParams(params),
  14644. })
  14645. class ZodEffects extends ZodType {
  14646. innerType() {
  14647. return this._def.schema
  14648. }
  14649. sourceType() {
  14650. return this._def.schema._def.typeName ===
  14651. ZodFirstPartyTypeKind.ZodEffects
  14652. ? this._def.schema.sourceType()
  14653. : this._def.schema
  14654. }
  14655. _parse(input) {
  14656. const { status, ctx } = this._processInputParams(input),
  14657. effect = this._def.effect || null
  14658. if ("preprocess" === effect.type) {
  14659. const processed = effect.transform(ctx.data)
  14660. return ctx.common.async
  14661. ? Promise.resolve(processed).then(processed =>
  14662. this._def.schema._parseAsync({
  14663. data: processed,
  14664. path: ctx.path,
  14665. parent: ctx,
  14666. })
  14667. )
  14668. : this._def.schema._parseSync({
  14669. data: processed,
  14670. path: ctx.path,
  14671. parent: ctx,
  14672. })
  14673. }
  14674. const checkCtx = {
  14675. addIssue: arg => {
  14676. addIssueToContext(ctx, arg)
  14677. arg.fatal ? status.abort() : status.dirty()
  14678. },
  14679. get path() {
  14680. return ctx.path
  14681. },
  14682. }
  14683. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx)
  14684. if ("refinement" === effect.type) {
  14685. const executeRefinement = acc => {
  14686. const result = effect.refinement(acc, checkCtx)
  14687. if (ctx.common.async) return Promise.resolve(result)
  14688. if (result instanceof Promise)
  14689. throw new Error(
  14690. "Async refinement encountered during synchronous parse operation. Use .parseAsync instead."
  14691. )
  14692. return acc
  14693. }
  14694. if (!1 === ctx.common.async) {
  14695. const inner = this._def.schema._parseSync({
  14696. data: ctx.data,
  14697. path: ctx.path,
  14698. parent: ctx,
  14699. })
  14700. if ("aborted" === inner.status) return INVALID
  14701. "dirty" === inner.status && status.dirty()
  14702. executeRefinement(inner.value)
  14703. return { status: status.value, value: inner.value }
  14704. }
  14705. return this._def.schema
  14706. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  14707. .then(inner => {
  14708. if ("aborted" === inner.status) return INVALID
  14709. "dirty" === inner.status && status.dirty()
  14710. return executeRefinement(inner.value).then(() => ({
  14711. status: status.value,
  14712. value: inner.value,
  14713. }))
  14714. })
  14715. }
  14716. if ("transform" === effect.type) {
  14717. if (!1 === ctx.common.async) {
  14718. const base = this._def.schema._parseSync({
  14719. data: ctx.data,
  14720. path: ctx.path,
  14721. parent: ctx,
  14722. })
  14723. if (!isValid(base)) return base
  14724. const result = effect.transform(base.value, checkCtx)
  14725. if (result instanceof Promise)
  14726. throw new Error(
  14727. "Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."
  14728. )
  14729. return { status: status.value, value: result }
  14730. }
  14731. return this._def.schema
  14732. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  14733. .then(base =>
  14734. isValid(base)
  14735. ? Promise.resolve(effect.transform(base.value, checkCtx)).then(
  14736. result => ({ status: status.value, value: result })
  14737. )
  14738. : base
  14739. )
  14740. }
  14741. util.assertNever(effect)
  14742. }
  14743. }
  14744. ZodEffects.create = (schema, effect, params) =>
  14745. new ZodEffects({
  14746. schema,
  14747. typeName: ZodFirstPartyTypeKind.ZodEffects,
  14748. effect,
  14749. ...processCreateParams(params),
  14750. })
  14751. ZodEffects.createWithPreprocess = (preprocess, schema, params) =>
  14752. new ZodEffects({
  14753. schema,
  14754. effect: { type: "preprocess", transform: preprocess },
  14755. typeName: ZodFirstPartyTypeKind.ZodEffects,
  14756. ...processCreateParams(params),
  14757. })
  14758. class ZodOptional extends ZodType {
  14759. _parse(input) {
  14760. return this._getType(input) === ZodParsedType.undefined
  14761. ? OK(void 0)
  14762. : this._def.innerType._parse(input)
  14763. }
  14764. unwrap() {
  14765. return this._def.innerType
  14766. }
  14767. }
  14768. ZodOptional.create = (type, params) =>
  14769. new ZodOptional({
  14770. innerType: type,
  14771. typeName: ZodFirstPartyTypeKind.ZodOptional,
  14772. ...processCreateParams(params),
  14773. })
  14774. class ZodNullable extends ZodType {
  14775. _parse(input) {
  14776. return this._getType(input) === ZodParsedType.null
  14777. ? OK(null)
  14778. : this._def.innerType._parse(input)
  14779. }
  14780. unwrap() {
  14781. return this._def.innerType
  14782. }
  14783. }
  14784. ZodNullable.create = (type, params) =>
  14785. new ZodNullable({
  14786. innerType: type,
  14787. typeName: ZodFirstPartyTypeKind.ZodNullable,
  14788. ...processCreateParams(params),
  14789. })
  14790. class ZodDefault extends ZodType {
  14791. _parse(input) {
  14792. const { ctx } = this._processInputParams(input)
  14793. let data = ctx.data
  14794. ctx.parsedType === ZodParsedType.undefined &&
  14795. (data = this._def.defaultValue())
  14796. return this._def.innerType._parse({ data, path: ctx.path, parent: ctx })
  14797. }
  14798. removeDefault() {
  14799. return this._def.innerType
  14800. }
  14801. }
  14802. ZodDefault.create = (type, params) =>
  14803. new ZodDefault({
  14804. innerType: type,
  14805. typeName: ZodFirstPartyTypeKind.ZodDefault,
  14806. defaultValue:
  14807. "function" == typeof params.default
  14808. ? params.default
  14809. : () => params.default,
  14810. ...processCreateParams(params),
  14811. })
  14812. class ZodCatch extends ZodType {
  14813. _parse(input) {
  14814. const { ctx } = this._processInputParams(input),
  14815. newCtx = { ...ctx, common: { ...ctx.common, issues: [] } },
  14816. result = this._def.innerType._parse({
  14817. data: newCtx.data,
  14818. path: newCtx.path,
  14819. parent: { ...newCtx },
  14820. })
  14821. return isAsync(result)
  14822. ? result.then(result => ({
  14823. status: "valid",
  14824. value:
  14825. "valid" === result.status
  14826. ? result.value
  14827. : this._def.catchValue({
  14828. get error() {
  14829. return new ZodError(newCtx.common.issues)
  14830. },
  14831. input: newCtx.data,
  14832. }),
  14833. }))
  14834. : {
  14835. status: "valid",
  14836. value:
  14837. "valid" === result.status
  14838. ? result.value
  14839. : this._def.catchValue({
  14840. get error() {
  14841. return new ZodError(newCtx.common.issues)
  14842. },
  14843. input: newCtx.data,
  14844. }),
  14845. }
  14846. }
  14847. removeCatch() {
  14848. return this._def.innerType
  14849. }
  14850. }
  14851. ZodCatch.create = (type, params) =>
  14852. new ZodCatch({
  14853. innerType: type,
  14854. typeName: ZodFirstPartyTypeKind.ZodCatch,
  14855. catchValue:
  14856. "function" == typeof params.catch ? params.catch : () => params.catch,
  14857. ...processCreateParams(params),
  14858. })
  14859. class ZodNaN extends ZodType {
  14860. _parse(input) {
  14861. if (this._getType(input) !== ZodParsedType.nan) {
  14862. const ctx = this._getOrReturnCtx(input)
  14863. addIssueToContext(ctx, {
  14864. code: ZodIssueCode.invalid_type,
  14865. expected: ZodParsedType.nan,
  14866. received: ctx.parsedType,
  14867. })
  14868. return INVALID
  14869. }
  14870. return { status: "valid", value: input.data }
  14871. }
  14872. }
  14873. ZodNaN.create = params =>
  14874. new ZodNaN({
  14875. typeName: ZodFirstPartyTypeKind.ZodNaN,
  14876. ...processCreateParams(params),
  14877. })
  14878. const BRAND = Symbol("zod_brand")
  14879. class ZodBranded extends ZodType {
  14880. _parse(input) {
  14881. const { ctx } = this._processInputParams(input),
  14882. data = ctx.data
  14883. return this._def.type._parse({ data, path: ctx.path, parent: ctx })
  14884. }
  14885. unwrap() {
  14886. return this._def.type
  14887. }
  14888. }
  14889. class ZodPipeline extends ZodType {
  14890. _parse(input) {
  14891. const { status, ctx } = this._processInputParams(input)
  14892. if (ctx.common.async)
  14893. return (async () => {
  14894. const inResult = await this._def.in._parseAsync({
  14895. data: ctx.data,
  14896. path: ctx.path,
  14897. parent: ctx,
  14898. })
  14899. if ("aborted" === inResult.status) return INVALID
  14900. if ("dirty" === inResult.status) {
  14901. status.dirty()
  14902. return DIRTY(inResult.value)
  14903. }
  14904. return this._def.out._parseAsync({
  14905. data: inResult.value,
  14906. path: ctx.path,
  14907. parent: ctx,
  14908. })
  14909. })()
  14910. {
  14911. const inResult = this._def.in._parseSync({
  14912. data: ctx.data,
  14913. path: ctx.path,
  14914. parent: ctx,
  14915. })
  14916. if ("aborted" === inResult.status) return INVALID
  14917. if ("dirty" === inResult.status) {
  14918. status.dirty()
  14919. return { status: "dirty", value: inResult.value }
  14920. }
  14921. return this._def.out._parseSync({
  14922. data: inResult.value,
  14923. path: ctx.path,
  14924. parent: ctx,
  14925. })
  14926. }
  14927. }
  14928. static create(a, b) {
  14929. return new ZodPipeline({
  14930. in: a,
  14931. out: b,
  14932. typeName: ZodFirstPartyTypeKind.ZodPipeline,
  14933. })
  14934. }
  14935. }
  14936. const custom = (check, params = {}, fatal) =>
  14937. check
  14938. ? ZodAny.create().superRefine((data, ctx) => {
  14939. var _a, _b
  14940. if (!check(data)) {
  14941. const p =
  14942. "function" == typeof params
  14943. ? params(data)
  14944. : "string" == typeof params
  14945. ? { message: params }
  14946. : params,
  14947. _fatal =
  14948. null ===
  14949. (_b =
  14950. null !== (_a = p.fatal) && void 0 !== _a
  14951. ? _a
  14952. : fatal) ||
  14953. void 0 === _b ||
  14954. _b,
  14955. p2 = "string" == typeof p ? { message: p } : p
  14956. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal })
  14957. }
  14958. })
  14959. : ZodAny.create(),
  14960. late = { object: ZodObject.lazycreate }
  14961. var ZodFirstPartyTypeKind
  14962. !(function (ZodFirstPartyTypeKind) {
  14963. ZodFirstPartyTypeKind.ZodString = "ZodString"
  14964. ZodFirstPartyTypeKind.ZodNumber = "ZodNumber"
  14965. ZodFirstPartyTypeKind.ZodNaN = "ZodNaN"
  14966. ZodFirstPartyTypeKind.ZodBigInt = "ZodBigInt"
  14967. ZodFirstPartyTypeKind.ZodBoolean = "ZodBoolean"
  14968. ZodFirstPartyTypeKind.ZodDate = "ZodDate"
  14969. ZodFirstPartyTypeKind.ZodSymbol = "ZodSymbol"
  14970. ZodFirstPartyTypeKind.ZodUndefined = "ZodUndefined"
  14971. ZodFirstPartyTypeKind.ZodNull = "ZodNull"
  14972. ZodFirstPartyTypeKind.ZodAny = "ZodAny"
  14973. ZodFirstPartyTypeKind.ZodUnknown = "ZodUnknown"
  14974. ZodFirstPartyTypeKind.ZodNever = "ZodNever"
  14975. ZodFirstPartyTypeKind.ZodVoid = "ZodVoid"
  14976. ZodFirstPartyTypeKind.ZodArray = "ZodArray"
  14977. ZodFirstPartyTypeKind.ZodObject = "ZodObject"
  14978. ZodFirstPartyTypeKind.ZodUnion = "ZodUnion"
  14979. ZodFirstPartyTypeKind.ZodDiscriminatedUnion = "ZodDiscriminatedUnion"
  14980. ZodFirstPartyTypeKind.ZodIntersection = "ZodIntersection"
  14981. ZodFirstPartyTypeKind.ZodTuple = "ZodTuple"
  14982. ZodFirstPartyTypeKind.ZodRecord = "ZodRecord"
  14983. ZodFirstPartyTypeKind.ZodMap = "ZodMap"
  14984. ZodFirstPartyTypeKind.ZodSet = "ZodSet"
  14985. ZodFirstPartyTypeKind.ZodFunction = "ZodFunction"
  14986. ZodFirstPartyTypeKind.ZodLazy = "ZodLazy"
  14987. ZodFirstPartyTypeKind.ZodLiteral = "ZodLiteral"
  14988. ZodFirstPartyTypeKind.ZodEnum = "ZodEnum"
  14989. ZodFirstPartyTypeKind.ZodEffects = "ZodEffects"
  14990. ZodFirstPartyTypeKind.ZodNativeEnum = "ZodNativeEnum"
  14991. ZodFirstPartyTypeKind.ZodOptional = "ZodOptional"
  14992. ZodFirstPartyTypeKind.ZodNullable = "ZodNullable"
  14993. ZodFirstPartyTypeKind.ZodDefault = "ZodDefault"
  14994. ZodFirstPartyTypeKind.ZodCatch = "ZodCatch"
  14995. ZodFirstPartyTypeKind.ZodPromise = "ZodPromise"
  14996. ZodFirstPartyTypeKind.ZodBranded = "ZodBranded"
  14997. ZodFirstPartyTypeKind.ZodPipeline = "ZodPipeline"
  14998. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}))
  14999. const stringType = ZodString.create,
  15000. numberType = ZodNumber.create,
  15001. nanType = ZodNaN.create,
  15002. bigIntType = ZodBigInt.create,
  15003. booleanType = ZodBoolean.create,
  15004. dateType = ZodDate.create,
  15005. symbolType = ZodSymbol.create,
  15006. undefinedType = ZodUndefined.create,
  15007. nullType = ZodNull.create,
  15008. anyType = ZodAny.create,
  15009. unknownType = ZodUnknown.create,
  15010. neverType = ZodNever.create,
  15011. voidType = ZodVoid.create,
  15012. arrayType = ZodArray.create,
  15013. objectType = ZodObject.create,
  15014. strictObjectType = ZodObject.strictCreate,
  15015. unionType = ZodUnion.create,
  15016. discriminatedUnionType = ZodDiscriminatedUnion.create,
  15017. intersectionType = ZodIntersection.create,
  15018. tupleType = ZodTuple.create,
  15019. recordType = ZodRecord.create,
  15020. lib_mapType = ZodMap.create,
  15021. setType = ZodSet.create,
  15022. functionType = ZodFunction.create,
  15023. lazyType = ZodLazy.create,
  15024. literalType = ZodLiteral.create,
  15025. enumType = ZodEnum.create,
  15026. nativeEnumType = ZodNativeEnum.create,
  15027. promiseType = ZodPromise.create,
  15028. effectsType = ZodEffects.create,
  15029. optionalType = ZodOptional.create,
  15030. nullableType = ZodNullable.create,
  15031. preprocessType = ZodEffects.createWithPreprocess,
  15032. pipelineType = ZodPipeline.create,
  15033. coerce = {
  15034. string: arg => ZodString.create({ ...arg, coerce: !0 }),
  15035. number: arg => ZodNumber.create({ ...arg, coerce: !0 }),
  15036. boolean: arg => ZodBoolean.create({ ...arg, coerce: !0 }),
  15037. bigint: arg => ZodBigInt.create({ ...arg, coerce: !0 }),
  15038. date: arg => ZodDate.create({ ...arg, coerce: !0 }),
  15039. },
  15040. NEVER = INVALID
  15041. var z = Object.freeze({
  15042. __proto__: null,
  15043. defaultErrorMap: errorMap,
  15044. setErrorMap: function (map) {
  15045. overrideErrorMap = map
  15046. },
  15047. getErrorMap,
  15048. makeIssue,
  15049. EMPTY_PATH: [],
  15050. addIssueToContext,
  15051. ParseStatus,
  15052. INVALID,
  15053. DIRTY,
  15054. OK,
  15055. isAborted,
  15056. isDirty,
  15057. isValid,
  15058. isAsync,
  15059. get util() {
  15060. return util
  15061. },
  15062. get objectUtil() {
  15063. return objectUtil
  15064. },
  15065. ZodParsedType,
  15066. getParsedType,
  15067. ZodType,
  15068. ZodString,
  15069. ZodNumber,
  15070. ZodBigInt,
  15071. ZodBoolean,
  15072. ZodDate,
  15073. ZodSymbol,
  15074. ZodUndefined,
  15075. ZodNull,
  15076. ZodAny,
  15077. ZodUnknown,
  15078. ZodNever,
  15079. ZodVoid,
  15080. ZodArray,
  15081. ZodObject,
  15082. ZodUnion,
  15083. ZodDiscriminatedUnion,
  15084. ZodIntersection,
  15085. ZodTuple,
  15086. ZodRecord,
  15087. ZodMap,
  15088. ZodSet,
  15089. ZodFunction,
  15090. ZodLazy,
  15091. ZodLiteral,
  15092. ZodEnum,
  15093. ZodNativeEnum,
  15094. ZodPromise,
  15095. ZodEffects,
  15096. ZodTransformer: ZodEffects,
  15097. ZodOptional,
  15098. ZodNullable,
  15099. ZodDefault,
  15100. ZodCatch,
  15101. ZodNaN,
  15102. BRAND,
  15103. ZodBranded,
  15104. ZodPipeline,
  15105. custom,
  15106. Schema: ZodType,
  15107. ZodSchema: ZodType,
  15108. late,
  15109. get ZodFirstPartyTypeKind() {
  15110. return ZodFirstPartyTypeKind
  15111. },
  15112. coerce,
  15113. any: anyType,
  15114. array: arrayType,
  15115. bigint: bigIntType,
  15116. boolean: booleanType,
  15117. date: dateType,
  15118. discriminatedUnion: discriminatedUnionType,
  15119. effect: effectsType,
  15120. enum: enumType,
  15121. function: functionType,
  15122. instanceof: (
  15123. cls,
  15124. params = { message: `Input not instance of ${cls.name}` }
  15125. ) => custom(data => data instanceof cls, params),
  15126. intersection: intersectionType,
  15127. lazy: lazyType,
  15128. literal: literalType,
  15129. map: lib_mapType,
  15130. nan: nanType,
  15131. nativeEnum: nativeEnumType,
  15132. never: neverType,
  15133. null: nullType,
  15134. nullable: nullableType,
  15135. number: numberType,
  15136. object: objectType,
  15137. oboolean: () => booleanType().optional(),
  15138. onumber: () => numberType().optional(),
  15139. optional: optionalType,
  15140. ostring: () => stringType().optional(),
  15141. pipeline: pipelineType,
  15142. preprocess: preprocessType,
  15143. promise: promiseType,
  15144. record: recordType,
  15145. set: setType,
  15146. strictObject: strictObjectType,
  15147. string: stringType,
  15148. symbol: symbolType,
  15149. transformer: effectsType,
  15150. tuple: tupleType,
  15151. undefined: undefinedType,
  15152. union: unionType,
  15153. unknown: unknownType,
  15154. void: voidType,
  15155. NEVER,
  15156. ZodIssueCode,
  15157. quotelessJson: obj =>
  15158. JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"),
  15159. ZodError,
  15160. })
  15161. const configEffect = (k, v) => c => () =>
  15162. runPromise(c.provideLog(c.setConfig[k](v))),
  15163. stepTiming = stepCount => `steps(${stepCount}, jump-end)`,
  15164. setComputed = {
  15165. useStepTiming: v => c => s =>
  15166. pipe(
  15167. v ? stepTiming(Editable_value(s.timingStepCount)) : "linear",
  15168. timingFunction => [
  15169. { ...s, timingFunction },
  15170. configEffect("timingFunction", timingFunction)(c),
  15171. ]
  15172. ),
  15173. },
  15174. settingUI_setComputed = setComputed,
  15175. setRange = keyA => keyB => bFn => vA => commander => s =>
  15176. pipe(
  15177. { a: Editable_value(vA) },
  15178. Identity_let_("b", ({ a }) => bFn(a)(Editable_value(s[keyB]))),
  15179. ({ a, b }) =>
  15180. pipe(
  15181. [configEffect(keyA, a), configEffect(keyB, b)],
  15182. xs => c =>
  15183. pipe(
  15184. xs,
  15185. ReadonlyArray_map(x => x(c)),
  15186. effects => [
  15187. { ...s, [keyA]: vA, [keyB]: setValue(b)(s[keyB]) },
  15188. ...effects,
  15189. ]
  15190. )
  15191. )(commander)
  15192. ),
  15193. setState = {
  15194. flowY1: setRange("flowY1")("flowY2")(a => b => Math.max(b, a + 0.05)),
  15195. flowY2: setRange("flowY2")("flowY1")(a => b => Math.min(b, a - 0.05)),
  15196. flowX1: setRange("flowX1")("flowX2")(a => b => Math.max(b, a + 0.05)),
  15197. flowX2: setRange("flowX2")("flowX1")(a => b => Math.min(b, a - 0.05)),
  15198. timingStepCount: v => c => s =>
  15199. pipe(stepTiming(Editable_value(v)), timingFunction => [
  15200. { ...s, timingStepCount: v, timingFunction },
  15201. configEffect("timingFunction", timingFunction)(c),
  15202. ]),
  15203. },
  15204. settingUI_setState = setState,
  15205. updateAt = k => v =>
  15206. pipe(
  15207. k in settingUI_setComputed
  15208. ? settingUI_setComputed[k](v)
  15209. : k in settingUI_setState
  15210. ? settingUI_setState[k](v)
  15211. : c => s =>
  15212. [
  15213. { ...s, [k]: v },
  15214. ...(k in c.setConfig && "filterExp" !== k
  15215. ? [
  15216. configEffect(
  15217. k,
  15218. Array.isArray(v) &&
  15219. 2 === v.length &&
  15220. isEditable(k)(v[0])
  15221. ? Editable_value(v)
  15222. : v
  15223. )(c),
  15224. ]
  15225. : []),
  15226. ]
  15227. ),
  15228. checkboxNode = label => c => s => {
  15229. return ((label, checked, onchange) =>
  15230. h(
  15231. "div",
  15232. {},
  15233. h("label", {}, [
  15234. hyperapp_text(label),
  15235. h("input", { type: "checkbox", checked, onchange }),
  15236. ])
  15237. ))(
  15238. getText(label)(s.lang),
  15239. getState(label)(s),
  15240. ((key = label),
  15241. flip((s, e) =>
  15242. pipe(
  15243. (e =>
  15244. z.instanceof(HTMLInputElement).parse(e.currentTarget).checked)(
  15245. e
  15246. ),
  15247. updateAt(key),
  15248. flip,
  15249. apply(s)
  15250. )
  15251. ))(c)
  15252. )
  15253. var key
  15254. },
  15255. mapSettingNodes = f => xs => c => s =>
  15256. pipe(
  15257. xs,
  15258. ReadonlyArray_map(x => x(c)(s)),
  15259. f
  15260. ),
  15261. errorText = subject => edit =>
  15262. pipe(
  15263. edit,
  15264. error,
  15265. Option_map(x => `${subject}${"" === x ? "" : ": "}${x}`),
  15266. getOrElse(constant(""))
  15267. ),
  15268. rangeRow = (min, max, step, action) => value =>
  15269. h("div", {}, [
  15270. h("input", {
  15271. style: { width: "150px", verticalAlign: "middle" },
  15272. type: "range",
  15273. min,
  15274. max,
  15275. step,
  15276. value: Editable_value(value).toString(),
  15277. oninput: action.onchange,
  15278. }),
  15279. h("input", {
  15280. style: {
  15281. width: "30px",
  15282. backgroundColor: "transparent",
  15283. color: "inherit",
  15284. borderWidth: "1px",
  15285. verticalAlign: "middle",
  15286. borderColor: hasError(value) ? "#f55" : void 0,
  15287. },
  15288. inputmode: "decimal",
  15289. value: pipe(
  15290. value,
  15291. Editable_text,
  15292. getOrElse(
  15293. constant(
  15294. Editable_value(value)
  15295. .toFixed(4)
  15296. .replace(/\.?0+$/, "")
  15297. )
  15298. )
  15299. ),
  15300. ...action,
  15301. }),
  15302. ]),
  15303. settingRow = (label, error, content) =>
  15304. h("div", {}, [
  15305. h("span", {}, hyperapp_text(label)),
  15306. h(
  15307. "span",
  15308. {
  15309. style: {
  15310. color: "#f55",
  15311. marginLeft: "5px",
  15312. whiteSpace: "pre-wrap",
  15313. },
  15314. },
  15315. hyperapp_text(error)
  15316. ),
  15317. h("div", {}, content),
  15318. ]),
  15319. setter_setEditNumber = editing => value => state =>
  15320. pipe(
  15321. value,
  15322. Number.parseFloat,
  15323. editing
  15324. ? x =>
  15325. Number.isNaN(x) || "." === value.at(-1)
  15326. ? pipe(state, setText(value))
  15327. : fromValueText(x)(value)
  15328. : x =>
  15329. Number.isNaN(x)
  15330. ? pipe(
  15331. state,
  15332. mapSecond(constant(Option_some([value, Option_some("")])))
  15333. )
  15334. : Editable_of(x)
  15335. ),
  15336. updateInput = (
  15337. (getState, updateAt) => key => setter => c => (s, e) =>
  15338. pipe(
  15339. (e => {
  15340. const target = e.currentTarget ?? e.__target
  15341. if (
  15342. target instanceof HTMLSelectElement ||
  15343. target instanceof HTMLTextAreaElement ||
  15344. target instanceof HTMLInputElement
  15345. )
  15346. return target.value
  15347. throw Error("Event target type isn't acceptable.")
  15348. })(e),
  15349. setter,
  15350. apply(getState(key)(s)),
  15351. updateAt(key),
  15352. x => x(c)(s)
  15353. )
  15354. )(getState, updateAt),
  15355. editAction = (key, setter) => c => ({
  15356. oninput: updateInput(key)(setter(!0))(c),
  15357. onchange: updateInput(key)(setter(!1))(c),
  15358. }),
  15359. numberNode = (label, min, max, step) => c => s =>
  15360. settingRow(
  15361. getText(label)(s.lang),
  15362. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  15363. [
  15364. rangeRow(
  15365. min,
  15366. max,
  15367. step,
  15368. editAction(label, setter_setEditNumber)(c)
  15369. )(getState(label)(s)),
  15370. ]
  15371. ),
  15372. settingUI_chatFieldPanel = pipe(
  15373. [
  15374. pipe(
  15375. [
  15376. numberNode("fieldScale", 0.7, 1.5, 0.05),
  15377. checkboxNode("simplifyChatField"),
  15378. checkboxNode("createBanButton"),
  15379. ],
  15380. mapSettingNodes(x => h("div", { style: panelBoxStyle(644) }, x))
  15381. ),
  15382. ],
  15383. mapSettingNodes(Function_identity)
  15384. ),
  15385. action = {
  15386. copy: () => s =>
  15387. Effect_map(
  15388. Effect_promise(async () => {
  15389. return GM.setClipboard(
  15390. ((x = s.eventLog),
  15391. `<pre>${JSON.stringify({
  15392. nextId: x.nextId,
  15393. blocks: pipe(
  15394. x.compressedBlocks,
  15395. ReadonlyArray_map(
  15396. external_LZString_namespaceObject.decompressFromUTF16
  15397. ),
  15398. append(JSON.stringify(x.lastBlock)),
  15399. mapNonEmpty(
  15400. external_LZString_namespaceObject.compressToEncodedURIComponent
  15401. )
  15402. ),
  15403. })}</pre>`)
  15404. )
  15405. var x
  15406. }),
  15407. () => s
  15408. ),
  15409. clearFlowChats: c => s => Effect_map(c.act.clearFlowChats, () => s),
  15410. importLog: () => s =>
  15411. pipe(
  15412. Effect_promise(() =>
  15413. external_Swal_default().fire({
  15414. input: "textarea",
  15415. inputLabel: getText("importLog")(s.lang),
  15416. })
  15417. ),
  15418. Effect_map(x =>
  15419. x.isConfirmed ? { ...s, eventLog: importLog(x.value ?? "") } : s
  15420. )
  15421. ),
  15422. },
  15423. buttonNode = label => c => state =>
  15424. h(
  15425. "button",
  15426. {
  15427. type: "button",
  15428. onclick: s => [
  15429. s,
  15430. d =>
  15431. runPromise(
  15432. c.provideLog(
  15433. pipe(
  15434. action[label](c)(s),
  15435. Effect_flatMap(newS => Effect_sync(() => d(newS)))
  15436. )
  15437. )
  15438. ),
  15439. ],
  15440. },
  15441. hyperapp_text(getText(label)(state.lang))
  15442. ),
  15443. feedbackPanel = c => s =>
  15444. pipe(
  15445. getState("eventLog")(s).compressedBlocks.length + 1,
  15446. logPageCount => [
  15447. pipe(
  15448. [checkboxNode("logEvents"), buttonNode("importLog")],
  15449. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15450. )(c)(s),
  15451. h("div", { style: panelBoxStyle(428) }, [
  15452. h(
  15453. "a",
  15454. {
  15455. style: { color: "#f0f" },
  15456. href: "https://greasyfork.org/en/scripts/411442-flow-youtube-chat/feedback",
  15457. target: "_blank",
  15458. },
  15459. hyperapp_text(getText("giveFeedback")(s.lang))
  15460. ),
  15461. h("div", {}, [
  15462. h("span", {}, hyperapp_text(getText("eventLog")(s.lang))),
  15463. buttonNode("copy")(c)(s),
  15464. tabContainer({
  15465. container: {},
  15466. label: { padding: "4px", width: "2em", textAlign: "center" },
  15467. labelFocus: { background: "#666" },
  15468. tab: {
  15469. height: "251px",
  15470. display: "flex",
  15471. flexDirection: "column",
  15472. padding: "6px",
  15473. },
  15474. })((_, n) => updateAt("logTab")(n)(c))(
  15475. pipe(makeBy(logPageCount, x => `${x}`))
  15476. )(
  15477. pipe(getState("eventLog")(s), l =>
  15478. makeBy(
  15479. logPageCount,
  15480. i => () =>
  15481. pipe(
  15482. ReadonlyArray_get(l.compressedBlocks, i),
  15483. Option_map(decompressBlock),
  15484. getOrElse(() => l.lastBlock),
  15485. ReadonlyArray_map((x, j) =>
  15486. h("div", { style: { display: "flex" } }, [
  15487. h(
  15488. "div",
  15489. {
  15490. style: {
  15491. userSelect: "none",
  15492. flex: "0 0 2em",
  15493. },
  15494. },
  15495. hyperapp_text(x.id)
  15496. ),
  15497. h(
  15498. "div",
  15499. {
  15500. style: {
  15501. background: j % 2 == 0 ? "#fff" : "#ddd",
  15502. color: "#000",
  15503. flex: "auto",
  15504. wordBreak: "break-all",
  15505. whiteSpace: "break-spaces",
  15506. padding: "0 2px",
  15507. },
  15508. },
  15509. hyperapp_text(`[${x.level}] ${x.text}`)
  15510. ),
  15511. ])
  15512. )
  15513. )
  15514. )
  15515. )
  15516. )(getState("logTab")(s)),
  15517. ]),
  15518. ]),
  15519. ]
  15520. ),
  15521. setter_setEditRegexes = editing => value =>
  15522. pipe(
  15523. value,
  15524. split(/\r\n|\n/),
  15525. ReadonlyArray_filter(not(isEmpty)),
  15526. Identity_bindTo("regexes"),
  15527. Identity_let_("errors", ({ regexes }) =>
  15528. pipe(
  15529. regexes,
  15530. ReadonlyArray_map((x, i) => {
  15531. try {
  15532. RegExp(x, "u")
  15533. return Option_none()
  15534. } catch (e) {
  15535. return Option_some(`${e} in regex number ${i}`)
  15536. }
  15537. }),
  15538. (Semigroup =>
  15539. fromSemigroup(
  15540. Semigroup_make((self, that) =>
  15541. Option_isNone(self)
  15542. ? that
  15543. : Option_isNone(that)
  15544. ? self
  15545. : Option_some(Semigroup.combine(self.value, that.value))
  15546. ),
  15547. Option_none()
  15548. ))(intercalate("\n")(Semigroup)).combineAll
  15549. )
  15550. ),
  15551. ctx =>
  15552. editing
  15553. ? setText(value)
  15554. : pipe(
  15555. ctx.errors,
  15556. Option_map(x =>
  15557. mapSecond(() => Option_some([value, Option_some(x)]))
  15558. ),
  15559. getOrElse(() => () => Editable_of(ctx.regexes))
  15560. )
  15561. ),
  15562. setter_setEditStrings = editing => value =>
  15563. pipe(value, split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty)), x =>
  15564. constant(
  15565. editing ? [x, Option_some([value, Option_none()])] : Editable_of(x)
  15566. )
  15567. ),
  15568. textAreaRow = (rows, action) => value =>
  15569. h("textarea", {
  15570. rows,
  15571. style: {
  15572. resize: "none",
  15573. boxSizing: "border-box",
  15574. width: "100%",
  15575. borderColor: hasError(value) ? "#f55" : void 0,
  15576. },
  15577. value: pipe(
  15578. value,
  15579. Editable_text,
  15580. getOrElse(pipe(Editable_value(value), join("\n"), constant))
  15581. ),
  15582. ...action,
  15583. }),
  15584. textAreaNode = (label, rows, setter) => c => s =>
  15585. settingRow(
  15586. getText(label)(s.lang),
  15587. errorText(getText("invalidSetting")(s.lang))(s[label]),
  15588. [textAreaRow(rows, editAction(label, setter)(c))(getState(label)(s))]
  15589. ),
  15590. filterPanelOld = c => s =>
  15591. [
  15592. h(
  15593. "div",
  15594. { style: panelBoxStyle(212) },
  15595. textAreaNode("bannedWords", 18, setter_setEditStrings)(c)(s)
  15596. ),
  15597. h(
  15598. "div",
  15599. { style: panelBoxStyle(212) },
  15600. textAreaNode("bannedWordRegexes", 18, setter_setEditRegexes)(c)(s)
  15601. ),
  15602. h(
  15603. "div",
  15604. { style: panelBoxStyle(212) },
  15605. textAreaNode("bannedUsers", 18, setter_setEditStrings)(c)(s)
  15606. ),
  15607. ],
  15608. colorPicker = action => color =>
  15609. h("input", {
  15610. style: { width: "36px", verticalAlign: "middle" },
  15611. type: "color",
  15612. value: color,
  15613. oninput: action.onchange,
  15614. }),
  15615. textInput = action => value =>
  15616. h("input", {
  15617. style: {
  15618. verticalAlign: "middle",
  15619. width: "5.5em",
  15620. borderColor: hasError(value) ? "#f55" : void 0,
  15621. },
  15622. maxlength: 20,
  15623. value: pipe(
  15624. value,
  15625. Editable_text,
  15626. getOrElse(constant(Editable_value(value)))
  15627. ),
  15628. ...action,
  15629. })
  15630. var validate_color_lib = __webpack_require__(694),
  15631. lib_default = __webpack_require__.n(validate_color_lib)
  15632. const setter_setEditColor = editing => value =>
  15633. editing
  15634. ? lib_default()(value)
  15635. ? constant(fromValueText(value)(value))
  15636. : setText(value)
  15637. : lib_default()(value)
  15638. ? constant(Editable_of(value))
  15639. : mapSecond(constant(Option_some([value, Option_some("")]))),
  15640. setter_setEditInt = editing => value => state =>
  15641. pipe(
  15642. value,
  15643. Number.parseInt,
  15644. editing
  15645. ? x =>
  15646. Number.isNaN(x) || "." === value.at(-1)
  15647. ? pipe(state, setText(value))
  15648. : fromValueText(x)(value)
  15649. : x =>
  15650. Number.isNaN(x)
  15651. ? pipe(
  15652. state,
  15653. mapSecond(constant(Option_some([value, Option_some("")])))
  15654. )
  15655. : Editable_of(x)
  15656. ),
  15657. intNode = (label, min, max, step) => c => s =>
  15658. settingRow(
  15659. getText(label)(s.lang),
  15660. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  15661. [
  15662. rangeRow(
  15663. min,
  15664. max,
  15665. step,
  15666. editAction(label, setter_setEditInt)(c)
  15667. )(getState(label)(s)),
  15668. ]
  15669. ),
  15670. setter_setEditString = editing =>
  15671. flow(x => constant(editing ? fromValueText(x)(x) : Editable_of(x))),
  15672. fonts = currentFont => [
  15673. ["", "Default", "デフォルト"],
  15674. ["arial", "Arial", "Arial"],
  15675. ["arial black", "Arial Black", "Arial Black"],
  15676. ["arial narrow", "Arial Narrow", "Arial Narrow"],
  15677. ["Century", "Century", "Century"],
  15678. ["Comic Sans MS", "Comic Sans MS", "Comic Sans MS"],
  15679. ["Courier", "Courier", "Courier"],
  15680. ["cursive", "cursive", "cursive"],
  15681. ["fantasy", "fantasy", "fantasy"],
  15682. ["Impact", "Impact", "Impact"],
  15683. ["Meiryo", "Meiryo", "メイリオ"],
  15684. ["Meiryo UI", "Meiryo UI", "メイリオ UI"],
  15685. ["monospace", "monospace", "monospace"],
  15686. ["Monotype Corsiva", "Monotype Corsiva", "Monotype Corsiva"],
  15687. ["MS PGothic", "MS PGothic", "MS Pゴシック"],
  15688. ["MS Gothic", "MS Gothic", "MS ゴシック"],
  15689. ["MS Sans Serif", "MS Sans Serif", "MS Sans Serif"],
  15690. ["MS Serif", "MS Serif", "MS Serif"],
  15691. ["MS UI Gothic", "MS UI Gothic", "MS UI Gothic"],
  15692. ["sans-serif", "Sans-serif", "Sans-serif"],
  15693. ["serif", "Serif", "Serif"],
  15694. ["Times New Roman", "Times New Roman", "Times New Roman"],
  15695. ["Yu Gothic", "Yu Gothic", "遊ゴシック"],
  15696. ["YuGothic", "YuGothic", "游ゴシック体"],
  15697. [currentFont, "Custom", "カスタム"],
  15698. ],
  15699. settingUI_textRowStyle = { width: "70%", boxSizing: "border-box" },
  15700. colorTextOutput = textStyle => color =>
  15701. h(
  15702. "span",
  15703. { style: { ...textStyle, color } },
  15704. hyperapp_text("Aa1あア亜")
  15705. ),
  15706. validColor = x => lib_default()(x.replace(/grey/gi, "gray")),
  15707. lib_setEditColor = editing => value =>
  15708. editing
  15709. ? validColor(value)
  15710. ? constant(fromValueText(value)(value))
  15711. : setText(value)
  15712. : validColor(value)
  15713. ? constant(Editable_of(value))
  15714. : mapSecond(constant(Option_some([value, Option_some("")]))),
  15715. exampleTextStyle = s => ({
  15716. fontFamily: Editable_value(s.font),
  15717. fontWeight: Editable_value(s.fontWeight).toString(),
  15718. textShadow: textShadow(Editable_value(s.shadowColor))(
  15719. Editable_value(s.shadowFontWeight)
  15720. ),
  15721. }),
  15722. textColorNode = label => c => s =>
  15723. settingRow(
  15724. getText(label)(s.lang),
  15725. errorText(getText("invalidColor")(s.lang))(s[label]),
  15726. pipe(
  15727. {
  15728. a: editAction(label, lib_setEditColor)(c),
  15729. v: Editable_value(s[label]),
  15730. },
  15731. ({ a, v }) => [
  15732. colorPicker(a)(v),
  15733. textInput(a)(s[label]),
  15734. colorTextOutput(exampleTextStyle(s))(v),
  15735. ]
  15736. )
  15737. ),
  15738. flowChatPanel = pipe(
  15739. [
  15740. pipe(
  15741. [
  15742. c => s =>
  15743. pipe(Editable_value(s.font), font =>
  15744. settingRow(getText("font")(s.lang), "", [
  15745. h(
  15746. "select",
  15747. {
  15748. style: settingUI_textRowStyle,
  15749. onchange: updateInput("font")(setter_setEditString(!1))(
  15750. c
  15751. ),
  15752. },
  15753. pipe(
  15754. fonts(font),
  15755. findFirstIndex(x => x[0] === font),
  15756. getOrElse(() => 0),
  15757. index =>
  15758. pipe(
  15759. fonts(font),
  15760. ReadonlyArray_map((f, i) =>
  15761. node_option(
  15762. f[0],
  15763. pipe(
  15764. languages,
  15765. findFirstIndex(x => x === s.lang),
  15766. Option_map(x => unsafeGet(x + 1)(f)),
  15767. getOrElse(() => "Error")
  15768. ),
  15769. i === index
  15770. )
  15771. )
  15772. )
  15773. )
  15774. ),
  15775. h("input", {
  15776. style: settingUI_textRowStyle,
  15777. maxlength: 20,
  15778. value: font,
  15779. ...editAction("font", setter_setEditString),
  15780. }),
  15781. ])
  15782. ),
  15783. textColorNode("color"),
  15784. textColorNode("ownerColor"),
  15785. textColorNode("moderatorColor"),
  15786. textColorNode("memberColor"),
  15787. ((label = "shadowColor"),
  15788. c => s =>
  15789. settingRow(
  15790. getText(label)(s.lang),
  15791. errorText(getText("invalidColor")(s.lang))(s[label]),
  15792. pipe(editAction(label, setter_setEditColor)(c), x => [
  15793. colorPicker(x)(Editable_value(s[label])),
  15794. textInput(x)(s[label]),
  15795. ])
  15796. )),
  15797. ],
  15798. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15799. ),
  15800. pipe(
  15801. [
  15802. numberNode("chatOpacity", 0, 1, 0.05),
  15803. numberNode("fontSize", 0.3, 2, 0.05),
  15804. numberNode("fontWeight", 10, 1e3, 10),
  15805. numberNode("shadowFontWeight", 0, 3, 0.1),
  15806. numberNode("flowSpeed", 1, 50, 1),
  15807. intNode("maxChatCount", 5, 200, 5),
  15808. intNode("maxChatLength", 5, 200, 5),
  15809. intNode("laneCount", 1, 25, 1),
  15810. ],
  15811. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15812. ),
  15813. pipe(
  15814. [
  15815. numberNode("flowY1", 0, 0.95, 0.01),
  15816. numberNode("flowY2", 0.05, 1, 0.01),
  15817. numberNode("flowX1", 0, 0.95, 0.01),
  15818. numberNode("flowX2", 0.05, 1, 0.01),
  15819. numberNode("minSpacing", 0, 2.5, 0.1),
  15820. c => s =>
  15821. h("div", {}, [
  15822. checkboxNode("useStepTiming")(c)(s),
  15823. h(
  15824. "div",
  15825. {
  15826. style: {
  15827. opacity: getState("useStepTiming")(s) ? void 0 : "0.5",
  15828. },
  15829. },
  15830. intNode("timingStepCount", 1, 400, 1)(c)(s)
  15831. ),
  15832. ]),
  15833. checkboxNode("createChats"),
  15834. checkboxNode("displayModName"),
  15835. checkboxNode("displaySuperChatAuthor"),
  15836. checkboxNode("textOnly"),
  15837. () => s => hyperapp_text(getText("flowNewChatIf")(s.lang)),
  15838. checkboxNode("noOverlap"),
  15839. buttonNode("clearFlowChats"),
  15840. ],
  15841. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15842. ),
  15843. ],
  15844. mapSettingNodes(Function_identity)
  15845. )
  15846. var label
  15847. const settingUI_flowChatPanel = flowChatPanel,
  15848. simpleWrap = (comp, init) =>
  15849. pipe(
  15850. Effect_sync(() => document.createElement(comp.tag)),
  15851. Effect_flatMap(node =>
  15852. Effect_sync(() => ({
  15853. node,
  15854. dispatch: app({ init, view: comp.view, node }),
  15855. }))
  15856. )
  15857. ),
  15858. toggleSettingsPanelComponent = flow(
  15859. syncState => (x, e) =>
  15860. pipe({ ...x, showPanel: !x.showPanel }, newState => [
  15861. newState,
  15862. x.showPanel
  15863. ? () => z.instanceof(HTMLElement).parse(e.currentTarget).blur()
  15864. : () => {},
  15865. () =>
  15866. runPromise(syncState(oldState => ({ ...oldState, ...newState }))),
  15867. ]),
  15868. toggle => state =>
  15869. h(
  15870. "button",
  15871. {
  15872. class: "fyc_button",
  15873. style: {
  15874. background: "rgba(0,0,0,0)",
  15875. marginLeft: "10px",
  15876. whiteSpace: "nowrap",
  15877. },
  15878. onclick: toggle,
  15879. },
  15880. [
  15881. h(
  15882. "svg",
  15883. {
  15884. preserveAspectRatio: "xMidYMid meet",
  15885. viewBox: "0 0 640 640",
  15886. width: "15",
  15887. height: "15",
  15888. style: { position: "relative", top: "1px" },
  15889. },
  15890. [
  15891. h(
  15892. "defs",
  15893. {},
  15894. h("path", {
  15895. id: "d1TbzTC1zI",
  15896. 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",
  15897. })
  15898. ),
  15899. h("use", {
  15900. href: "#d1TbzTC1zI",
  15901. opacity: "1",
  15902. fill: "var(--iron-icon-fill-color, currentcolor)",
  15903. "fill-opacity": "1",
  15904. }),
  15905. ]
  15906. ),
  15907. h(
  15908. "span",
  15909. {
  15910. style: {
  15911. position: "relative",
  15912. top: "-2px",
  15913. marginLeft: "8px,",
  15914. },
  15915. },
  15916. hyperapp_text(getText("setting")(state.lang))
  15917. ),
  15918. ]
  15919. ),
  15920. button =>
  15921. makeComponent(
  15922. tag => s => h(tag, { style: { display: "flex" } }, button(s))
  15923. )("span")
  15924. ),
  15925. videoToggleStream = video =>
  15926. pipe(
  15927. [["playing"], ["waiting", "pause"]],
  15928. ReadonlyArray_map((x, i) => [x, 0 === i]),
  15929. ReadonlyArray_flatMap(([xs, b]) =>
  15930. pipe(
  15931. xs,
  15932. ReadonlyArray_map(x => [x, b])
  15933. )
  15934. ),
  15935. ReadonlyArray_map(([x, b]) =>
  15936. pipe(
  15937. (0, external_rxjs_namespaceObject.fromEvent)(video, x),
  15938. (0, external_rxjs_namespaceObject.map)(() => b)
  15939. )
  15940. ),
  15941. x => (0, external_rxjs_namespaceObject.merge)(...x)
  15942. ),
  15943. Logger_make = makeLogger,
  15944. Logger_replace = replaceLogger,
  15945. Logger_withMinimumLogLevel = withMinimumLogLevel,
  15946. Logger_zip = logger_zip,
  15947. Logger_defaultLogger = defaultLogger
  15948. var LogAnnotationKeys
  15949. !(function (LogAnnotationKeys) {
  15950. LogAnnotationKeys.name = "name"
  15951. })(LogAnnotationKeys || (LogAnnotationKeys = {}))
  15952. const src_LogAnnotationKeys = LogAnnotationKeys,
  15953. maxEventLogBlockCount = Math.floor(50),
  15954. preserveEventLogBlockCount = Math.floor(0.2 * maxEventLogBlockCount),
  15955. getConsoleLog = x =>
  15956. (x === Trace
  15957. ? console.trace
  15958. : x === Level_Debug
  15959. ? console.debug
  15960. : x === Info
  15961. ? console.info
  15962. : x === Warning
  15963. ? console.warn
  15964. : x === Level_Error || x === Fatal
  15965. ? console.error
  15966. : console.log
  15967. ).bind(console),
  15968. metaLogger = Logger_make(
  15969. (fiberId, logLevel, message, cause, context, span, annotations) =>
  15970. runPromise(
  15971. pipe(
  15972. () =>
  15973. `${pipe(
  15974. annotations,
  15975. mjs_HashMap_get(src_LogAnnotationKeys.name),
  15976. match(
  15977. () => "",
  15978. x => `[${x}] `
  15979. )
  15980. )}${message}`,
  15981. getStr =>
  15982. pipe(
  15983. FiberRefs_getOrDefault(context, logMeta),
  15984. match(
  15985. () =>
  15986. greaterThanEqual(Warning)(logLevel)
  15987. ? Effect_sync(() => getConsoleLog(logLevel)(getStr()))
  15988. : Effect_unit(),
  15989. meta =>
  15990. Effect_sync(() =>
  15991. getConsoleLog(logLevel)(`${getStr()}: `, meta)
  15992. )
  15993. )
  15994. )
  15995. )
  15996. )
  15997. )
  15998. runPromise(
  15999. pipe(
  16000. Effect_Do(),
  16001. Effect_letDiscard(
  16002. "settingUpdateApps",
  16003. new external_rxjs_namespaceObject.BehaviorSubject([])
  16004. ),
  16005. bindValue_("provideLog", x => {
  16006. return (
  16007. (settingUpdateApps = x.settingUpdateApps),
  16008. effect => {
  16009. return pipe(
  16010. Effect_succeed(
  16011. Logger_replace(
  16012. Logger_defaultLogger,
  16013. Logger_zip(metaLogger)(
  16014. ((apps = settingUpdateApps),
  16015. Logger_make((fiberId, logLevel, message) =>
  16016. runPromise(
  16017. (
  16018. apps => dispatchable =>
  16019. pipe(
  16020. apps,
  16021. ReadonlyArray_map(x =>
  16022. Effect_sync(() => x(dispatchable))
  16023. ),
  16024. x => Effect_all(x)
  16025. )
  16026. )(apps.getValue())(s => {
  16027. return s.logEvents
  16028. ? {
  16029. ...s,
  16030. eventLog: ((text = message),
  16031. (level = logLevel.label),
  16032. flow(
  16033. x =>
  16034. x.compressedBlocks.length ===
  16035. maxEventLogBlockCount
  16036. ? (
  16037. i => log =>
  16038. i > log.compressedBlocks.length
  16039. ? log
  16040. : makeLog({
  16041. nextId: log.nextId,
  16042. ...(i ===
  16043. log.compressedBlocks.length
  16044. ? {
  16045. lastBlock: [],
  16046. compressedBlocks:
  16047. log.compressedBlocks,
  16048. }
  16049. : {
  16050. lastBlock:
  16051. log.lastBlock,
  16052. compressedBlocks:
  16053. ReadonlyArray_remove(
  16054. log.compressedBlocks,
  16055. i
  16056. ),
  16057. }),
  16058. })
  16059. )(
  16060. Math.floor(
  16061. preserveEventLogBlockCount
  16062. )
  16063. )(x)
  16064. : x,
  16065. (
  16066. (text, level) => log =>
  16067. makeLog({
  16068. nextId: log.nextId + 1,
  16069. ...pipe(
  16070. log.lastBlock,
  16071. append({
  16072. id: log.nextId,
  16073. text,
  16074. level,
  16075. }),
  16076. x =>
  16077. 200 === x.length
  16078. ? {
  16079. compressedBlocks: append(
  16080. log.compressedBlocks,
  16081. makeCompressedLogBlock(
  16082. (0,
  16083. external_LZString_namespaceObject.compressToUTF16)(
  16084. JSON.stringify(x)
  16085. )
  16086. )
  16087. ),
  16088. lastBlock: [],
  16089. }
  16090. : {
  16091. compressedBlocks:
  16092. log.compressedBlocks,
  16093. lastBlock: x,
  16094. }
  16095. ),
  16096. })
  16097. )(text, level)
  16098. ))(s.eventLog),
  16099. }
  16100. : s
  16101. var text, level
  16102. })
  16103. )
  16104. ))
  16105. )
  16106. )
  16107. ),
  16108. Effect_flatMap(logLayer =>
  16109. pipe(
  16110. effect,
  16111. Effect_tapErrorCause(x => Effect_logError(Cause_pretty(x))),
  16112. Effect_provideSomeLayer(logLayer)
  16113. )
  16114. ),
  16115. Effect_logAnnotate(src_LogAnnotationKeys.name, "FYC"),
  16116. Logger_withMinimumLogLevel(Level_Debug)
  16117. )
  16118. var apps
  16119. }
  16120. )
  16121. var settingUpdateApps
  16122. }),
  16123. Effect_flatMap(({ settingUpdateApps, provideLog }) =>
  16124. provideLog(
  16125. pipe(
  16126. src_defaultGMConfig,
  16127. x => ({ gmConfig: x, configKeys: Object.keys(x) }),
  16128. Effect_succeed,
  16129. Effect_letDiscard("updateSettingState", dispatchable =>
  16130. provideLog(
  16131. pipe(
  16132. settingUpdateApps.getValue(),
  16133. ReadonlyArray_map(x => Effect_sync(() => x(dispatchable))),
  16134. x => Effect_all(x)
  16135. )
  16136. )
  16137. ),
  16138. Effect_bind("config", ctx => {
  16139. return (
  16140. (config = ctx.gmConfig),
  16141. pipe(
  16142. Object.entries(config),
  16143. ReadonlyArray_map(([k, c]) =>
  16144. pipe(
  16145. c.getValue,
  16146. Effect_map(x => [k, x])
  16147. )
  16148. ),
  16149. x => Effect_all(x),
  16150. Effect_map(Object.fromEntries)
  16151. )
  16152. )
  16153. var config
  16154. }),
  16155. bindValue_("getConfig", ctx =>
  16156. (c =>
  16157. pipe(
  16158. c,
  16159. mapObject(([x]) => [x, Effect_sync(() => c[x])])
  16160. ))(ctx.config)
  16161. ),
  16162. flow(
  16163. bindValue_("mainState", x => ({
  16164. chatPlaying: !0,
  16165. playerRect: new DOMRectReadOnly(0, 0, 600, 400),
  16166. config: x.config,
  16167. flowChats: [],
  16168. })),
  16169. bindValue_("configSubject", ctx =>
  16170. pipe(
  16171. ctx.configKeys,
  16172. ReadonlyArray_map(x => [
  16173. x,
  16174. new external_rxjs_namespaceObject.Subject(),
  16175. ]),
  16176. Object.fromEntries
  16177. )
  16178. ),
  16179. bindValue_("setterFromKeysMap", ctx =>
  16180. (
  16181. keys => f =>
  16182. pipe(
  16183. keys,
  16184. ReadonlyArray_map(x => [x, f(x)]),
  16185. Object.fromEntries
  16186. )
  16187. )(ctx.configKeys)
  16188. ),
  16189. bindValue_("setConfigPlain", ctx =>
  16190. ctx.setterFromKeysMap(
  16191. key => val =>
  16192. Effect_promise(async () => {
  16193. Object.assign(ctx.mainState.config, { [key]: val })
  16194. ctx.configSubject[key].next(val)
  16195. })
  16196. )
  16197. ),
  16198. bindValue_(
  16199. "changedConfigMap",
  16200. ctx => key => val =>
  16201. pipe(
  16202. Effect_promise(async () => ctx.config[key]),
  16203. Effect_filterOrFail(
  16204. x => !fast_deep_equal_default()(x, val),
  16205. Option_none
  16206. ),
  16207. Effect_flatMap(() => ctx.setConfigPlain[key](val))
  16208. )
  16209. ),
  16210. bindValue_("setChangedConfig", ctx =>
  16211. ctx.setterFromKeysMap(
  16212. key => val =>
  16213. pipe(ctx.changedConfigMap(key)(val), Effect_ignore)
  16214. )
  16215. ),
  16216. Effect_letDiscard(
  16217. "channel",
  16218. new broadcast_channel_BroadcastChannel("fyc-0615654655528523")
  16219. )
  16220. ),
  16221. flow(
  16222. bindValue_("setConfig", ctx =>
  16223. ctx.setterFromKeysMap(
  16224. key => val =>
  16225. pipe(
  16226. ctx.changedConfigMap(key)(val),
  16227. Effect_zipRight(
  16228. Effect_promise(() =>
  16229. ctx.channel.postMessage([key, val])
  16230. )
  16231. ),
  16232. Effect_zipRight(
  16233. Effect_promise(() =>
  16234. pipe(ctx.gmConfig[key], x =>
  16235. GM.setValue(x.gmKey, x.toGm(val))
  16236. )
  16237. )
  16238. ),
  16239. Effect_ignore
  16240. )
  16241. )
  16242. ),
  16243. Effect_bindDiscard(
  16244. "reinitSubject",
  16245. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  16246. ),
  16247. bindValue_("reinitialize", ctx =>
  16248. provideLog(
  16249. Effect_sync(() => {
  16250. requestAnimationFrame(() => lib(ctx.reinitSubject)())
  16251. })
  16252. )
  16253. ),
  16254. Effect_tap(ctx =>
  16255. ctx.setConfigPlain.filterExp(defaultFilter(ctx.config))
  16256. ),
  16257. bindValue_("toggleChatButtonInit", ctx => ({
  16258. lang: ctx.config.lang,
  16259. displayChats: ctx.config.displayChats,
  16260. })),
  16261. Effect_bind("wrappedToggleChat", ctx => {
  16262. return simpleWrap(
  16263. ((setConfig = ctx.setConfig),
  16264. pipe(
  16265. "button",
  16266. makeComponent(
  16267. tag => state =>
  16268. pipe(
  16269. getText(
  16270. state.displayChats ? "hideChats" : "showChats"
  16271. )(state.lang),
  16272. label =>
  16273. h(
  16274. tag,
  16275. {
  16276. class: "ytp-button",
  16277. style: {
  16278. background: "none",
  16279. border: "none",
  16280. cursor: "pointer",
  16281. float: "left",
  16282. fontSize: "1em",
  16283. height: "4em",
  16284. outline: "none",
  16285. overflow: "visible",
  16286. padding: "0 0 0em",
  16287. position: "relative",
  16288. width: "48px",
  16289. display: "flex",
  16290. alignItems: "center",
  16291. },
  16292. type: "button",
  16293. "aria-label": label,
  16294. title: label,
  16295. onclick: s =>
  16296. pipe(!s.displayChats, displayChats => [
  16297. { ...s, displayChats },
  16298. () =>
  16299. runPromise(
  16300. setConfig.displayChats(displayChats)
  16301. ),
  16302. ]),
  16303. },
  16304. [
  16305. h(
  16306. "svg",
  16307. {
  16308. style: { width: "36px" },
  16309. viewBox: "0 0 36 36",
  16310. },
  16311. [
  16312. h("path", {
  16313. class: "chat-button-path",
  16314. d: "m11 12h17q1 0 1 1v9q0 1-1 1h-1v2l-4-2h-12q-1 0-1-1v-9q0-1 1-1z",
  16315. fill: "#fff",
  16316. "fill-opacity": state.displayChats
  16317. ? "1"
  16318. : "0",
  16319. stroke: "#fff",
  16320. "stroke-width": "2",
  16321. }),
  16322. ]
  16323. ),
  16324. ]
  16325. )
  16326. )
  16327. )
  16328. )),
  16329. ctx.toggleChatButtonInit
  16330. )
  16331. var setConfig
  16332. }),
  16333. Effect_bind("wrappedSettings", ctx =>
  16334. simpleWrap(
  16335. pipe(
  16336. (c => state => {
  16337. return state.showPanel
  16338. ? h(
  16339. "div",
  16340. {
  16341. class: "fyc_panel",
  16342. style: {
  16343. backgroundColor: "rgba(30,30,30,0.9)",
  16344. position: "absolute",
  16345. zIndex: "1000",
  16346. color: "#fff",
  16347. fontSize: "14px",
  16348. overflow: "auto",
  16349. left: `${state.panelRect.x}px`,
  16350. top: `${state.panelRect.y}px`,
  16351. width: `${state.panelRect.width}px`,
  16352. height: `${state.panelRect.height}px`,
  16353. border: "solid 1px #666",
  16354. fontFamily: "MS PGothic",
  16355. lineHeight: "1.2",
  16356. colorScheme: "dark",
  16357. },
  16358. },
  16359. [
  16360. h(
  16361. "div",
  16362. {
  16363. style: {
  16364. position: "absolute",
  16365. inset: "3px 3px auto auto",
  16366. },
  16367. },
  16368. [
  16369. hyperapp_text("🌐"),
  16370. h(
  16371. "select",
  16372. {
  16373. onchange: updateInput("lang")(
  16374. ((allowedStrings = [
  16375. "FYC_EN",
  16376. "FYC_JA",
  16377. ]),
  16378. value => state =>
  16379. pipe(
  16380. value,
  16381. liftPredicate(x =>
  16382. ReadonlyArray_contains(
  16383. String_Equivalence
  16384. )(allowedStrings, x)
  16385. ),
  16386. getOrElse(() => state)
  16387. ))
  16388. )(c),
  16389. },
  16390. pipe(
  16391. languages,
  16392. zip(languageLabels),
  16393. ReadonlyArray_map(([lang, label]) =>
  16394. node_option(
  16395. lang,
  16396. label,
  16397. lang === state.lang
  16398. )
  16399. )
  16400. )
  16401. ),
  16402. ]
  16403. ),
  16404. tabContainer({
  16405. container: {},
  16406. label: { padding: "6px" },
  16407. labelFocus: { background: "#666" },
  16408. tab: {
  16409. height: "364px",
  16410. display: "flex",
  16411. padding: "6px",
  16412. },
  16413. })((s, n) => updateAt("mainTab")(n)(c)(s))(
  16414. pipe(
  16415. [
  16416. "flowChat",
  16417. "chatFilter",
  16418. "chatField",
  16419. "feedback",
  16420. ],
  16421. ReadonlyArray_map(getText),
  16422. ReadonlyArray_map(apply(state.lang))
  16423. )
  16424. )(
  16425. pipe(
  16426. [
  16427. settingUI_flowChatPanel,
  16428. filterPanelOld,
  16429. settingUI_chatFieldPanel,
  16430. feedbackPanel,
  16431. ],
  16432. ReadonlyArray_map(apply(c)),
  16433. ReadonlyArray_map(constant),
  16434. ReadonlyArray_map(flip),
  16435. ReadonlyArray_map(apply(state))
  16436. )
  16437. )(getState("mainTab")(state)),
  16438. ]
  16439. )
  16440. : h("div", {})
  16441. var allowedStrings
  16442. })({
  16443. setConfig: ctx.setConfig,
  16444. act: {
  16445. clearFlowChats: removeOldChats(ctx.mainState)(0),
  16446. },
  16447. provideLog,
  16448. }),
  16449. panel =>
  16450. makeComponent(
  16451. tag => s =>
  16452. h(tag, { style: { display: "contents" } }, panel(s))
  16453. )("span")
  16454. ),
  16455. settingStateInit(ctx.config)
  16456. )
  16457. ),
  16458. Effect_bind("wrappedToggleSettings", ctx =>
  16459. simpleWrap(
  16460. toggleSettingsPanelComponent(ctx.updateSettingState),
  16461. settingStateInit(ctx.config)
  16462. )
  16463. )
  16464. ),
  16465. flow(
  16466. Effect_tap(ctx =>
  16467. Effect_sync(() =>
  16468. settingUpdateApps.next([
  16469. ctx.wrappedSettings.dispatch,
  16470. ctx.wrappedToggleSettings.dispatch,
  16471. ])
  16472. )
  16473. ),
  16474. Effect_letDiscard(
  16475. "settingsRectSubject",
  16476. new external_rxjs_namespaceObject.BehaviorSubject(
  16477. new DOMRectReadOnly(0, 0, 660, 395)
  16478. )
  16479. ),
  16480. Effect_tap(ctx =>
  16481. pipe(
  16482. [
  16483. "Version: 1.16.1",
  16484. `User Agent: ${window.navigator.userAgent}`,
  16485. `GMConfig: ${JSON.stringify(ctx.config, void 0, "\t")}`,
  16486. ],
  16487. ReadonlyArray_map(Effect_logDebug),
  16488. x => Effect_all(x)
  16489. )
  16490. ),
  16491. Effect_zipLeft(
  16492. pipe(
  16493. Effect_logDebug("10s..."),
  16494. Effect_repeat(Schedule_fixed(seconds(10))),
  16495. Effect_delay(seconds(10)),
  16496. Effect_forkDaemon
  16497. )
  16498. )
  16499. ),
  16500. bindValue_("co", ctx =>
  16501. pipe(
  16502. ctx.configSubject,
  16503. mapObject(([k, value]) => [
  16504. k,
  16505. pipe(
  16506. value,
  16507. tapEffect(v =>
  16508. provideLog(
  16509. pipe(
  16510. v,
  16511. x => s => ({ ...s, [k]: x }),
  16512. Effect_succeed,
  16513. Effect_tap(() => {
  16514. return ctx.updateSettingState(
  16515. ((key = k),
  16516. value => state => ({
  16517. ...state,
  16518. [key]: isEditable(key)(value)
  16519. ? setValue(value)(state[key])
  16520. : "filterExp" === key
  16521. ? void 0
  16522. : value,
  16523. }))(v)
  16524. )
  16525. var key
  16526. }),
  16527. Effect_zipLeft(
  16528. pipe(
  16529. [
  16530. "bannedWords",
  16531. "bannedUsers",
  16532. "bannedWordRegexes",
  16533. ],
  16534. ReadonlyArray_contains(String_Equivalence)(k),
  16535. x =>
  16536. x
  16537. ? ctx.setConfig.filterExp(
  16538. defaultFilter(ctx.config)
  16539. )
  16540. : Effect_unit()
  16541. )
  16542. ),
  16543. Effect_flatMap(x =>
  16544. k in ctx.toggleChatButtonInit
  16545. ? Effect_sync(() =>
  16546. ctx.wrappedToggleChat.dispatch(x)
  16547. )
  16548. : Effect_unit()
  16549. ),
  16550. x => () => runPromise(provideLog(x)),
  16551. x => Effect_sync(() => requestAnimationFrame(x))
  16552. )
  16553. )
  16554. ),
  16555. (0, external_rxjs_namespaceObject.share)()
  16556. ),
  16557. ])
  16558. )
  16559. ),
  16560. Effect_letDiscard("livePage", livePageYt),
  16561. bindValue_("live", ctx => makePageState(ctx.livePage)),
  16562. Effect_bindDiscard("chatScreen", makeChatScreen),
  16563. Effect_bind("all$", ctx => {
  16564. return pipe(
  16565. {
  16566. eq:
  16567. ((E = strict()),
  16568. Equivalence_make(
  16569. (x, y) =>
  16570. x === y ||
  16571. (Option_isNone(x)
  16572. ? Option_isNone(y)
  16573. : !Option_isNone(y) && E(x.value, y.value))
  16574. )),
  16575. initDelay: 100,
  16576. urlDelay: 1700,
  16577. changeDetectInterval: 700,
  16578. bodyResizeDetectInterval: 300,
  16579. errorRetryInterval: 5e3,
  16580. liveElementKeys: Object.keys(ctx.livePage),
  16581. tapUpdateSettingsRect: ob =>
  16582. (0, external_rxjs_namespaceObject.switchMap)(value => {
  16583. return pipe(
  16584. ctx.settingsRectSubject,
  16585. (0, external_rxjs_namespaceObject.first)(),
  16586. (0, external_rxjs_namespaceObject.map)(
  16587. ((toggleSettingsElement =
  16588. ctx.wrappedToggleSettings.node),
  16589. nextSettingsRect => last =>
  16590. pipe(
  16591. Effect_succeed(toggleSettingsElement),
  16592. Effect_filterOrFail(
  16593. x => null !== x.offsetParent,
  16594. Option_none
  16595. ),
  16596. Effect_map(x => x.getBoundingClientRect()),
  16597. Effect_map(
  16598. x =>
  16599. new DOMRectReadOnly(
  16600. Math.max(
  16601. 0,
  16602. x.right + window.scrollX - 660
  16603. ),
  16604. Math.max(0, x.y + window.scrollY - 395),
  16605. 660,
  16606. Math.min(x.y + window.scrollY, 395)
  16607. )
  16608. ),
  16609. Effect_orElseSucceed(
  16610. () =>
  16611. new DOMRectReadOnly(-660, -395, 660, 395)
  16612. ),
  16613. Effect_filterOrFail(
  16614. x =>
  16615. x.x !== last.x ||
  16616. x.y !== last.y ||
  16617. x.width !== last.width ||
  16618. x.height !== last.height,
  16619. Option_none
  16620. ),
  16621. Effect_tap(nextSettingsRect),
  16622. Effect_ignore
  16623. ))(rect =>
  16624. Effect_sync(() =>
  16625. ctx.settingsRectSubject.next(rect)
  16626. )
  16627. )
  16628. ),
  16629. tapEffect(provideLog),
  16630. (0, external_rxjs_namespaceObject.map)(() => value)
  16631. )
  16632. var toggleSettingsElement
  16633. })(ob),
  16634. config$: configStream(
  16635. provideLog,
  16636. ctx.mainState,
  16637. ctx.co,
  16638. ctx.chatScreen,
  16639. ctx.live
  16640. ),
  16641. },
  16642. Effect_succeed,
  16643. Effect_bindDiscard("css", mainCss),
  16644. Effect_bindDiscard(
  16645. "documentMutationPair",
  16646. observePair(MutationObserver)
  16647. ),
  16648. Effect_bindDiscard(
  16649. "chatMutationPair",
  16650. observePair(MutationObserver)
  16651. ),
  16652. Effect_bindDiscard(
  16653. "playerResizePair",
  16654. observePair(ResizeObserver)
  16655. ),
  16656. Effect_bindDiscard(
  16657. "bodyResizePair",
  16658. observePair(ResizeObserver)
  16659. ),
  16660. Effect_map(c =>
  16661. pipe(
  16662. ctx.reinitSubject,
  16663. (0, external_rxjs_namespaceObject.observeOn)(
  16664. external_rxjs_namespaceObject.asyncScheduler
  16665. ),
  16666. (0, external_rxjs_namespaceObject.delay)(c.initDelay),
  16667. tapEffect(() => provideLog(Effect_logInfo("Init"))),
  16668. (0, external_rxjs_namespaceObject.switchMap)(() =>
  16669. pipe(
  16670. (0, external_rxjs_namespaceObject.interval)(
  16671. c.changeDetectInterval
  16672. ),
  16673. c.tapUpdateSettingsRect,
  16674. (0, external_rxjs_namespaceObject.concatMap)(index =>
  16675. pipe(
  16676. (0, external_rxjs_namespaceObject.from)(
  16677. runPromise(
  16678. provideLog(
  16679. pipe(
  16680. c.liveElementKeys,
  16681. ReadonlyArray_map(key =>
  16682. pipe(
  16683. ctx.live[key],
  16684. x => x.read,
  16685. Effect_matchEffect(
  16686. () => Effect_succeed(Option_none()),
  16687. flow(Option_some, Effect_succeed)
  16688. ),
  16689. Effect_map(
  16690. liftPredicate(
  16691. newEle =>
  16692. !c.eq(ctx.live[key].ele, newEle)
  16693. )
  16694. ),
  16695. Effect_map(
  16696. Option_map(
  16697. flow(
  16698. Effect_succeed,
  16699. Effect_tap(x =>
  16700. Effect_sync(() => {
  16701. ctx.live[key].ele = x
  16702. })
  16703. ),
  16704. Effect_map(Option_isSome),
  16705. Effect_map(
  16706. x =>
  16707. `${key} ${
  16708. x ? "found" : "lost"
  16709. }`
  16710. ),
  16711. Effect_flatMap(Effect_logDebug)
  16712. )
  16713. )
  16714. ),
  16715. Effect_flatMap(
  16716. match(
  16717. () => Effect_succeed(!1),
  16718. Effect_zipRight(
  16719. Effect_succeed(!0)
  16720. )
  16721. )
  16722. )
  16723. )
  16724. ),
  16725. x => Effect_all(x),
  16726. Effect_map(
  16727. ReadonlyArray_some(Function_identity)
  16728. )
  16729. )
  16730. )
  16731. )
  16732. ),
  16733. (0, external_rxjs_namespaceObject.filter)(
  16734. Function_identity
  16735. ),
  16736. (0, external_rxjs_namespaceObject.map)(
  16737. () => index
  16738. )
  16739. )
  16740. ),
  16741. (0, external_rxjs_namespaceObject.startWith)(0)
  16742. )
  16743. ),
  16744. tapEffect(() =>
  16745. provideLog(
  16746. pipe(
  16747. Effect_logDebug("Loading..."),
  16748. Effect_zipRight(removeOldChats(ctx.mainState)(0)),
  16749. Effect_zipRight(
  16750. Effect_sync(() => {
  16751. c.documentMutationPair.observer.disconnect()
  16752. c.documentMutationPair.observer.observe(
  16753. document,
  16754. { childList: !0, subtree: !0 }
  16755. )
  16756. c.chatMutationPair.observer.disconnect()
  16757. c.playerResizePair.observer.disconnect()
  16758. c.bodyResizePair.observer.disconnect()
  16759. document.head.append(c.css)
  16760. })
  16761. ),
  16762. Effect_zipRight(
  16763. pipe(
  16764. [
  16765. pipe(
  16766. ctx.live.chatField.ele,
  16767. Option_map(x =>
  16768. Effect_sync(() =>
  16769. c.chatMutationPair.observer.observe(x, {
  16770. childList: !0,
  16771. })
  16772. )
  16773. )
  16774. ),
  16775. pipe(
  16776. ctx.live.chatTicker.ele,
  16777. Option_map(x =>
  16778. Effect_sync(() =>
  16779. c.chatMutationPair.observer.observe(x, {
  16780. childList: !0,
  16781. })
  16782. )
  16783. )
  16784. ),
  16785. pipe(
  16786. ctx.live.player.ele,
  16787. Option_map(
  16788. flow(
  16789. Effect_succeed,
  16790. Effect_tap(x =>
  16791. Effect_sync(() =>
  16792. c.playerResizePair.observer.observe(
  16793. x
  16794. )
  16795. )
  16796. ),
  16797. Effect_flatMap(x =>
  16798. Effect_sync(() =>
  16799. x.prepend(ctx.chatScreen)
  16800. )
  16801. )
  16802. )
  16803. )
  16804. ),
  16805. pipe(
  16806. ctx.live.toggleChatBtnParent.ele,
  16807. Option_map(x =>
  16808. Effect_sync(() =>
  16809. x.prepend(ctx.wrappedToggleChat.node)
  16810. )
  16811. )
  16812. ),
  16813. pipe(
  16814. ctx.live.settingsToggleNextElement.ele,
  16815. Option_map(x =>
  16816. Effect_sync(() =>
  16817. x.before(ctx.wrappedToggleSettings.node)
  16818. )
  16819. )
  16820. ),
  16821. pipe(
  16822. ctx.live.settingsContainer.ele,
  16823. Option_map(x =>
  16824. Effect_sync(() =>
  16825. x.append(ctx.wrappedSettings.node)
  16826. )
  16827. )
  16828. ),
  16829. pipe(
  16830. document.body,
  16831. fromNullable,
  16832. Option_map(x =>
  16833. Effect_sync(() =>
  16834. c.bodyResizePair.observer.observe(x)
  16835. )
  16836. )
  16837. ),
  16838. ],
  16839. ReadonlyArray_compact,
  16840. append(
  16841. pipe(
  16842. ctx.live.video.ele,
  16843. Option_filter(x => !x.paused),
  16844. orElse(() => ctx.live.offlineSlate.ele),
  16845. Option_isSome,
  16846. x =>
  16847. Effect_sync(() => {
  16848. Object.assign(ctx.mainState, {
  16849. chatPlaying: x,
  16850. })
  16851. })
  16852. )
  16853. ),
  16854. x => Effect_all(x)
  16855. )
  16856. )
  16857. )
  16858. )
  16859. ),
  16860. (0, external_rxjs_namespaceObject.switchMap)(() =>
  16861. (0, external_rxjs_namespaceObject.merge)(
  16862. pipe(
  16863. (0, external_rxjs_namespaceObject.fromEvent)(
  16864. ctx.channel,
  16865. "message"
  16866. ),
  16867. (0, external_rxjs_namespaceObject.map)(
  16868. ([key, val]) =>
  16869. pipe(
  16870. src_listeningBroadcastConfigKeys.includes(
  16871. key
  16872. ),
  16873. x =>
  16874. x
  16875. ? ctx.setChangedConfig[key](val)
  16876. : Effect_sync(() => {})
  16877. )
  16878. ),
  16879. tapEffect(provideLog)
  16880. ),
  16881. ...pipe(
  16882. ctx.configKeys,
  16883. ReadonlyArray_map(key =>
  16884. pipe(
  16885. ctx.co[key],
  16886. (0, external_rxjs_namespaceObject.startWith)(
  16887. ctx.config[key]
  16888. ),
  16889. (0, external_rxjs_namespaceObject.bufferCount)(
  16890. 2,
  16891. 1
  16892. ),
  16893. (0, external_rxjs_namespaceObject.map)(
  16894. ([x, y]) =>
  16895. (0, external_DeepDiff_namespaceObject.diff)(
  16896. x,
  16897. y
  16898. )
  16899. ),
  16900. (0, external_rxjs_namespaceObject.map)(x =>
  16901. Effect_logDebug(
  16902. `Config ${key}: ${JSON.stringify(
  16903. x,
  16904. void 0,
  16905. 2
  16906. )}`
  16907. )
  16908. ),
  16909. tapEffect(provideLog)
  16910. )
  16911. )
  16912. ),
  16913. c.config$,
  16914. pipe(
  16915. ctx.live.video.ele,
  16916. match(
  16917. () => external_rxjs_namespaceObject.EMPTY,
  16918. flow(
  16919. videoToggleStream,
  16920. (0, external_rxjs_namespaceObject.map)(
  16921. playing =>
  16922. playing ||
  16923. Option_isSome(ctx.live.offlineSlate.ele)
  16924. ),
  16925. (0, external_rxjs_namespaceObject.map)(
  16926. chatPlaying =>
  16927. pipe(
  16928. Effect_sync(() => {
  16929. ctx.mainState.chatPlaying = chatPlaying
  16930. }),
  16931. Effect_zipRight(
  16932. pipe(
  16933. ctx.mainState.flowChats,
  16934. ReadonlyArray_map(setChatPlayState),
  16935. ReadonlyArray_map(
  16936. apply(ctx.mainState)
  16937. ),
  16938. x => Effect_all(x)
  16939. )
  16940. )
  16941. )
  16942. ),
  16943. tapEffect(provideLog)
  16944. )
  16945. )
  16946. ),
  16947. pipe(
  16948. c.chatMutationPair.subject,
  16949. (0, external_rxjs_namespaceObject.map)(
  16950. onChatFieldMutate(
  16951. ctx.chatScreen,
  16952. ctx.mainState,
  16953. ctx.getConfig,
  16954. ctx.setConfig
  16955. )
  16956. ),
  16957. tapEffect(provideLog)
  16958. ),
  16959. pipe(
  16960. c.documentMutationPair.subject,
  16961. (0, external_rxjs_namespaceObject.map)(
  16962. () => window.location.href
  16963. ),
  16964. (0,
  16965. external_rxjs_namespaceObject.distinctUntilChanged)(),
  16966. (0, external_rxjs_namespaceObject.skip)(1),
  16967. c.tapUpdateSettingsRect,
  16968. (0, external_rxjs_namespaceObject.map)(x =>
  16969. Effect_all([
  16970. Effect_logDebug(`URL Changed: ${x}`),
  16971. removeOldChats(ctx.mainState)(0),
  16972. Effect_logDebug(`Wait for ${c.urlDelay}ms...`),
  16973. ])
  16974. ),
  16975. tapEffect(provideLog),
  16976. (0, external_rxjs_namespaceObject.delay)(
  16977. c.urlDelay
  16978. ),
  16979. tapEffect(() => ctx.reinitialize)
  16980. ),
  16981. pipe(
  16982. c.playerResizePair.subject,
  16983. (0, external_rxjs_namespaceObject.throttleTime)(
  16984. 500,
  16985. void 0,
  16986. { leading: !0, trailing: !0 }
  16987. ),
  16988. (0, external_rxjs_namespaceObject.startWith)([]),
  16989. (0, external_rxjs_namespaceObject.map)(
  16990. flow(
  16991. () => ctx.live.player.ele,
  16992. Option_map(x => x.getBoundingClientRect()),
  16993. match(
  16994. () => Effect_unit(),
  16995. x => {
  16996. return (
  16997. (rect = x),
  16998. (mainState = ctx.mainState),
  16999. pipe(
  17000. rect,
  17001. Effect_succeed,
  17002. Effect_tap(x =>
  17003. Effect_logDebug(
  17004. `Resize [${x.width.toFixed(
  17005. 1
  17006. )}, ${x.height.toFixed(1)}]`
  17007. )
  17008. ),
  17009. Effect_flatMap(
  17010. flow(
  17011. x =>
  17012. Effect_sync(() =>
  17013. Object.assign(mainState, {
  17014. playerRect: x,
  17015. })
  17016. ),
  17017. Effect_map(
  17018. () => mainState.flowChats
  17019. ),
  17020. Effect_map(
  17021. ReadonlyArray_flatMap(x => [
  17022. renderChat(x)(mainState),
  17023. setChatAnimation(x)(mainState),
  17024. ])
  17025. ),
  17026. Effect_flatMap(x => Effect_all(x))
  17027. )
  17028. )
  17029. )
  17030. )
  17031. var rect, mainState
  17032. }
  17033. )
  17034. )
  17035. ),
  17036. tapEffect(provideLog)
  17037. ),
  17038. pipe(
  17039. c.bodyResizePair.subject,
  17040. (0, external_rxjs_namespaceObject.throttleTime)(
  17041. c.bodyResizeDetectInterval,
  17042. void 0,
  17043. { leading: !0, trailing: !0 }
  17044. ),
  17045. (0, external_rxjs_namespaceObject.startWith)([]),
  17046. c.tapUpdateSettingsRect
  17047. ),
  17048. pipe(
  17049. ctx.settingsRectSubject,
  17050. tapEffect(panelRect =>
  17051. ctx.updateSettingState(s => ({ ...s, panelRect }))
  17052. )
  17053. )
  17054. )
  17055. ),
  17056. (0, external_rxjs_namespaceObject.retry)({
  17057. delay: e =>
  17058. pipe(
  17059. e,
  17060. external_rxjs_namespaceObject.of,
  17061. tapEffect(() =>
  17062. provideLog(
  17063. logWithMeta(Level_Error)(`Errored: ${e}`)(e)
  17064. )
  17065. ),
  17066. (0, external_rxjs_namespaceObject.delay)(
  17067. c.errorRetryInterval
  17068. ),
  17069. tapEffect(() => ctx.reinitialize)
  17070. ),
  17071. })
  17072. )
  17073. )
  17074. )
  17075. var E
  17076. }),
  17077. Effect_tap(ctx =>
  17078. Effect_sync(() =>
  17079. ctx.all$.subscribe({
  17080. error: x =>
  17081. runPromise(
  17082. logWithMeta(Level_Error)(`Stream Errored: ${x}`)(x)
  17083. ),
  17084. complete: () =>
  17085. runPromise(Effect_logWarning("Stream complete")),
  17086. })
  17087. )
  17088. ),
  17089. Effect_tap(ctx => ctx.reinitialize)
  17090. )
  17091. )
  17092. ),
  17093. Effect_withParallelismUnbounded
  17094. )
  17095. )
  17096. })()
  17097. })()