diff --git a/Project/Web/Controllers/APIController.cs b/Project/Web/Controllers/APIController.cs new file mode 100644 index 0000000..0fefd27 --- /dev/null +++ b/Project/Web/Controllers/APIController.cs @@ -0,0 +1,143 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; +using Newtonsoft.Json; + +namespace Project.Web.Controllers +{ + public class APIController : BaseController + { + [HttpGet] + public HttpResponseMessage Getdata() + { + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + var sql = string.Empty; + var p_sql = getParams.Where(t => t.Key == "sql").FirstOrDefault(); + if (p_sql.Key.isEmpty() == false) sql = p_sql.Value; + else + { + var p_table = getParams.Where(t => t.Key == "table").FirstOrDefault(); + var p_gcode = getParams.Where(t => t.Key == "gcode").FirstOrDefault(); + var p_where = getParams.Where(t => t.Key == "w").FirstOrDefault(); + var p_order = getParams.Where(t => t.Key == "o").FirstOrDefault(); + sql = "select * from {0} where gcode = '{gcode}'"; + sql = string.Format(sql, p_table.Value, p_gcode.Value); + if (p_where.Key != null) sql += " and " + p_where.Value; + if (p_order.Key != null) sql += " order by " + p_order.Value; + } + + sql = sql.Replace("{gcode}", FCOMMON.info.Login.gcode); + + var cs = Properties.Settings.Default.gwcs; // "Data Source=K4FASQL.kr.ds.amkor.com,50150;Initial Catalog=EE;Persist Security Info=True;User ID=eeadm;Password=uJnU8a8q&DJ+ug-D!"; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Gettable() + { + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + var sql = string.Empty; + var p_sql = getParams.Where(t => t.Key == "sql").FirstOrDefault(); + if (p_sql.Key.isEmpty() == false) sql = p_sql.Value; + else + { + var p_table = getParams.Where(t => t.Key == "table").FirstOrDefault(); + var p_gcode = getParams.Where(t => t.Key == "gcode").FirstOrDefault(); + var p_where = getParams.Where(t => t.Key == "w").FirstOrDefault(); + var p_order = getParams.Where(t => t.Key == "o").FirstOrDefault(); + sql = "select * from {0} where gcode = '{gcode}'"; + sql = string.Format(sql, p_table.Value, p_gcode.Value); + if (p_where.Key != null) sql += " and " + p_where.Value; + if (p_order.Key != null) sql += " order by " + p_order.Value; + } + + + sql = sql.Replace("{gcode}", FCOMMON.info.Login.gcode); + + var cs = Properties.Settings.Default.gwcs;// "Data Source=K4FASQL.kr.ds.amkor.com,50150;Initial Catalog=EE;Persist Security Info=True;User ID=eeadm;Password=uJnU8a8q&DJ+ug-D!"; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + + + } + + + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var contents = result.Content; + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/BaseController.cs b/Project/Web/Controllers/BaseController.cs new file mode 100644 index 0000000..743ea38 --- /dev/null +++ b/Project/Web/Controllers/BaseController.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Web.Http; +using Project.Web.Model; + +namespace Project.Web.Controllers +{ + public struct MethodResult : IEquatable + { + public string Content; + public byte[] Contentb; + public string Redirecturl; + + public override bool Equals(object obj) + { + if (!(obj is MethodResult)) + return false; + + return Equals((MethodResult)obj); + } + + public override int GetHashCode() + { + if (Contentb == null) + return Content.GetHashCode() ^ Redirecturl.GetHashCode(); + else + return Content.GetHashCode() ^ Redirecturl.GetHashCode() ^ Contentb.GetHexString().GetHashCode(); + + } + + public bool Equals(MethodResult other) + { + if (Content != other.Content) + return false; + + if (Redirecturl != other.Redirecturl) + return false; + + return Contentb == other.Contentb; + } + + + public static bool operator ==(MethodResult point1, MethodResult point2) + { + return point1.Equals(point2); + } + + public static bool operator !=(MethodResult point1, MethodResult point2) + { + return !point1.Equals(point2); + } + } + + sealed class PostRequest : Attribute + { + + } + + public class BaseController : ApiController + { + public string QueryString { get; set; } + public string PostData { get; set; } + public string ParamData { get; set; } + + protected string Trig_Ctrl { get; set; } + protected string Trig_func { get; set; } + + public PageModel GetGlobalModel() + { + var config = RequestContext.Configuration; + var routeData = config.Routes.GetRouteData(Request).Values.ToList(); + var name_ctrl = routeData[0].Value.ToString(); + var name_action = routeData[1].Value.ToString(); + + + return new PageModel + { + RouteData = routeData, + urlcontrol = name_ctrl, + urlaction = name_action + }; + } + + + public MethodResult View(bool nosubdir=false) + { + var config = RequestContext.Configuration; + if (config != null) + { + var routeData = config.Routes.GetRouteData(Request).Values.ToList(); + var name_ctrl = routeData[0].Value.ToString(); + if (nosubdir) name_ctrl = string.Empty; + var name_action = routeData[1].Value.ToString(); + return View(name_ctrl, name_action); + } + else + { + return View(Trig_Ctrl + "/" + Trig_func); + } + + } + + + public static void ApplyCommonValue(ref string contents) + { + //메뉴 푸터 - 개발자 정보 + if (contents.Contains("{title}")) + contents = contents.Replace("{title}", FCOMMON.info.Login.gcode + " Groupware"); + + } + + public MethodResult View(string Controller, string Action, Boolean applydefaultview = true) + { + var retval = new MethodResult(); + + if (Action.IndexOf(".") == -1) + Action += ".html"; //기본값 html 을 넣는다 + + var file = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "View", Controller, Action); + + var contents = string.Empty; + + if (System.IO.File.Exists(file) == false) + { + //error 폴더의 404.html 파일을 찾는다. + var file404 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "View", "Error", "404.html"); + if (System.IO.File.Exists(file404)) + { + contents = System.IO.File.ReadAllText(file404, System.Text.Encoding.UTF8); + contents = contents.Replace("{errorfilename}", file); + } + + else + contents = "ERROR CODE - 404 (NOT FOUND)
" + file; + + Console.WriteLine("view File not found : " + file); + } + else + { + //디폴트뷰의 내용을 가져온다 (있다면 적용한다) + if (applydefaultview) + { + //뷰파일이 있다면 그것을 적용한다 + var laytoutfile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "View", "Layout", "default.html"); + if (System.IO.File.Exists(laytoutfile)) + contents = System.IO.File.ReadAllText(laytoutfile, System.Text.Encoding.UTF8); + + var fileContents = System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8); + if (String.IsNullOrEmpty(contents)) contents = fileContents; + else contents = contents.Replace("{contents}", fileContents); + } + else + { + //해당 뷰를 가져와서 반환한다 + contents = System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8); + } + } + + + + + //시스템변수 replace + contents = contents.Replace("{param_control}", Trig_Ctrl); + contents = contents.Replace("{param_function}", Trig_func); + + retval.Content = contents; + return retval; + } + public MethodResult View(string viewfilename, Boolean applydefaultview = true) + { + var retval = new MethodResult(); + + if (viewfilename.IndexOf(".") == -1) + viewfilename += ".html"; //기본값 html 을 넣는다 + + var file = AppDomain.CurrentDomain.BaseDirectory + "View" + viewfilename.Replace("/", "\\"); + + var contents = string.Empty; + + if (System.IO.File.Exists(file) == false) + { + //error 폴더의 404.html 파일을 찾는다. + var file404 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "View", "Error", "404.html"); + if (System.IO.File.Exists(file404)) + { + contents = System.IO.File.ReadAllText(file404, System.Text.Encoding.UTF8); + contents = contents.Replace("{errorfilename}", file); + } + + else + contents = "ERROR CODE - 404 (NOT FOUND)
" + file; + + Console.WriteLine("view File not found : " + file); + } + else + { + //디폴트뷰의 내용을 가져온다 (있다면 적용한다) + if (applydefaultview) + { + //뷰파일이 있다면 그것을 적용한다 + var laytoutfile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "View", "Layout", "default.html"); + if (System.IO.File.Exists(laytoutfile)) + contents = System.IO.File.ReadAllText(laytoutfile, System.Text.Encoding.UTF8); + + var fileContents = System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8); + if (String.IsNullOrEmpty(contents)) contents = fileContents; + else contents = contents.Replace("{contents}", fileContents); + } + else + { + //해당 뷰를 가져와서 반환한다 + contents = System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8); + } + } + + + + + + //콘텐츠내의 file 을 찾아서 처리한다. ; 정규식의 처리속도가 느릴듯하여, 그냥 처리해본다 + while (true) + { + var fileindexS = contents.IndexOf("{file:"); + if (fileindexS == -1) break; + var fileindexE = contents.IndexOf("}", fileindexS); + if (fileindexE == -1) break; + if (fileindexE <= fileindexS + 5) break; + var inlinestr = contents.Substring(fileindexS, fileindexE - fileindexS + 1); + var filename = contents.Substring(fileindexS + 7, fileindexE - fileindexS - 8); + var load_file = String.Concat(AppDomain.CurrentDomain.BaseDirectory, "View", "\\", filename.Replace("/", "\\")); + load_file = load_file.Replace("\\\\", "\\"); + String fileContents;// = String.Empty; + + Console.WriteLine("file impot : " + load_file); + if (System.IO.File.Exists(load_file)) + { + fileContents = System.IO.File.ReadAllText(load_file, System.Text.Encoding.UTF8); + } + else + { + fileContents = "{FileNotFound:" + filename + "}"; //파일이없다면 해당 부분은 오류 처리한다. + } + contents = contents.Replace(inlinestr, fileContents); + } + + //시스템변수 replace + contents = contents.Replace("{param_control}", Trig_Ctrl); + contents = contents.Replace("{param_function}", Trig_func); + + retval.Content = contents; + return retval; + } + protected class Parameter + { + public string Key { get; set; } + public string Value { get; set; } + public Parameter(string key_, string value_) + { + Key = key_; + Value = value_; + } + } + + } +} diff --git a/Project/Web/Controllers/CommonController.cs b/Project/Web/Controllers/CommonController.cs new file mode 100644 index 0000000..3bf0dd2 --- /dev/null +++ b/Project/Web/Controllers/CommonController.cs @@ -0,0 +1,454 @@ +using FCM0000; +using Microsoft.Owin; +using Newtonsoft.Json; +using System; +using System.Linq; +using System.Net.Http; +using System.Web; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class CommonController : BaseController + { + [HttpGet] + public HttpResponseMessage GetList(string grp=null) + { + var sql = string.Empty; + + //코드그룹이 없다면 전체 목록을 조회할 수 있도록 99를 조회한다 + if (string.IsNullOrEmpty(grp)) grp = "99"; + + // 특정 그룹의 데이터만 가져옴 + sql = "select *" + + " from common" + + " where gcode = @gcode" + + " and grp = @grp" + + " order by code,svalue"; + + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + + if (!string.IsNullOrEmpty(grp)) + { + cmd.Parameters.AddWithValue("grp", grp); + } + + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + + [HttpGet] + public HttpResponseMessage Index() + { + // 직접 파일을 읽어서 반환 + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "Common.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + // 파일이 없으면 404 에러 페이지 또는 기본 메시지 + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpPost] + public HttpResponseMessage Save([FromBody] CommonModel model) + { + try + { + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var sql = string.Empty; + var cmd = new System.Data.SqlClient.SqlCommand(); + cmd.Connection = cn; + + if (model.idx > 0) + { + // 업데이트 + sql = @"UPDATE common SET + grp = @grp, + code = @code, + svalue = @svalue, + ivalue = @ivalue, + fvalue = @fvalue, + svalue2 = @svalue2, + memo = @memo, + wuid = @wuid, + wdate = GETDATE() + WHERE idx = @idx AND gcode = @gcode"; + } + else + { + // 신규 추가 + sql = @"INSERT INTO common (gcode, grp, code, svalue, ivalue, fvalue, svalue2, memo, wuid, wdate) + VALUES (@gcode, @grp, @code, @svalue, @ivalue, @fvalue, @svalue2, @memo, @wuid, GETDATE())"; + } + + cmd.CommandText = sql; + cmd.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + cmd.Parameters.AddWithValue("@grp", model.grp ?? ""); + cmd.Parameters.AddWithValue("@code", model.code ?? ""); + cmd.Parameters.AddWithValue("@svalue", model.svalue ?? ""); + cmd.Parameters.AddWithValue("@ivalue", model.ivalue); + cmd.Parameters.AddWithValue("@fvalue", model.fvalue); + cmd.Parameters.AddWithValue("@svalue2", model.svalue2 ?? ""); + cmd.Parameters.AddWithValue("@memo", model.memo ?? ""); + cmd.Parameters.AddWithValue("@wuid", FCOMMON.info.Login.no); + + if (model.idx > 0) + { + cmd.Parameters.AddWithValue("@idx", model.idx); + } + + cn.Open(); + var result = cmd.ExecuteNonQuery(); + cn.Close(); + + cmd.Dispose(); + cn.Dispose(); + + var response = new + { + Success = result > 0, + Message = result > 0 ? "저장되었습니다." : "저장에 실패했습니다." + }; + + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + Success = false, + Message = "오류가 발생했습니다: " + ex.Message + }; + return CreateJsonResponse(response); + } + } + + [HttpPost] + public HttpResponseMessage Delete([FromBody] DeleteModel model) + { + try + { + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var sql = "DELETE FROM common WHERE idx = @idx AND gcode = @gcode"; + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + + cmd.Parameters.AddWithValue("@idx", model.idx); + cmd.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + + cn.Open(); + var result = cmd.ExecuteNonQuery(); + cn.Close(); + + cmd.Dispose(); + cn.Dispose(); + + var response = new + { + Success = result > 0, + Message = result > 0 ? "삭제되었습니다." : "삭제에 실패했습니다." + }; + + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + Success = false, + Message = "오류가 발생했습니다: " + ex.Message + }; + return CreateJsonResponse(response); + } + } + + [HttpGet] + public HttpResponseMessage GetGroups() + { + try + { + var sql = "select code, svalue, memo from common WITH (nolock) " + + "where gcode = @gcode and grp = '99' " + + "order by code"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var response = new + { + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + } + + [HttpPost] + public HttpResponseMessage InitializeGroups() + { + try + { + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + + // 기본 그룹코드들 정의 + var defaultGroups = new[] + { + new { code = "01", svalue = "부서코드" }, + new { code = "02", svalue = "직급코드" }, + new { code = "03", svalue = "공정코드" }, + new { code = "04", svalue = "품목분류" }, + new { code = "05", svalue = "업체분류" }, + new { code = "06", svalue = "제조공정" }, + new { code = "07", svalue = "장비제조" }, + new { code = "08", svalue = "장비모델" }, + new { code = "09", svalue = "장비기술" }, + new { code = "99", svalue = "기타" } + }; + + cn.Open(); + + int insertedCount = 0; + foreach (var group in defaultGroups) + { + // 이미 존재하는지 확인 + var checkSql = "SELECT COUNT(*) FROM common WHERE gcode = @gcode AND grp = '99' AND code = @code"; + var checkCmd = new System.Data.SqlClient.SqlCommand(checkSql, cn); + checkCmd.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + checkCmd.Parameters.AddWithValue("@code", group.code); + + var exists = (int)checkCmd.ExecuteScalar() > 0; + checkCmd.Dispose(); + + if (!exists) + { + // 새로 추가 + var insertSql = @"INSERT INTO common (gcode, grp, code, svalue, ivalue, fvalue, svalue2, memo, wuid, wdate) + VALUES (@gcode, '99', @code, @svalue, 0, 0.0, '', '코드그룹 정의', @wuid, GETDATE())"; + var insertCmd = new System.Data.SqlClient.SqlCommand(insertSql, cn); + insertCmd.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + insertCmd.Parameters.AddWithValue("@code", group.code); + insertCmd.Parameters.AddWithValue("@svalue", group.svalue); + insertCmd.Parameters.AddWithValue("@wuid", FCOMMON.info.Login.no); + + insertCmd.ExecuteNonQuery(); + insertCmd.Dispose(); + insertedCount++; + } + } + + cn.Close(); + cn.Dispose(); + + var response = new + { + Success = true, + Message = $"그룹코드 초기화 완료. {insertedCount}개 추가됨." + }; + + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + Success = false, + Message = "오류가 발생했습니다: " + ex.Message + }; + return CreateJsonResponse(response); + } + } + + [HttpGet] + public HttpResponseMessage GetNavigationMenu() + { + try + { + // 메뉴 정보를 하드코딩하거나 데이터베이스에서 가져올 수 있습니다. + // 향후 사용자 권한에 따른 메뉴 표시/숨김 기능도 추가 가능합니다. + var menuItems = new[] + { + new { + key = "dashboard", + title = "대시보드", + url = "/Dashboard/", + icon = "M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z M8 5a2 2 0 012-2h4a2 2 0 012 2v2H8V5z", + isVisible = true, + sortOrder = 1 + }, + new { + key = "common", + title = "공용코드", + url = "/Common", + icon = "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z", + isVisible = true, + sortOrder = 2 + }, + new { + key = "jobreport", + title = "업무일지", + url = "/Jobreport/", + icon = "M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2", + isVisible = true, + sortOrder = 3 + }, + new { + key = "kuntae", + title = "근태관리", + url = "/Kuntae/", + icon = "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z", + isVisible = true, + sortOrder = 4 + }, + new { + key = "todo", + title = "할일관리", + url = "/Todo/", + icon = "M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2M12 12l2 2 4-4", + isVisible = true, + sortOrder = 5 + }, + new { + key = "project", + title = "프로젝트", + url = "/Project/", + icon = "M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10", + isVisible = true, + sortOrder = 6 + } + }; + + // 사용자 권한에 따른 메뉴 필터링 로직을 여기에 추가할 수 있습니다. + // 예: var userLevel = FCOMMON.info.Login.level; + // if (userLevel < 5) { /* 특정 메뉴 숨김 */ } + + var response = new + { + Success = true, + Data = menuItems, + Message = "메뉴 정보를 성공적으로 가져왔습니다." + }; + + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + Success = false, + Data = (object)null, + Message = "메뉴 정보를 가져오는 중 오류가 발생했습니다: " + ex.Message + }; + return CreateJsonResponse(response); + } + } + + private HttpResponseMessage CreateJsonResponse(object data) + { + var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + return new HttpResponseMessage() + { + Content = new StringContent( + json, + System.Text.Encoding.UTF8, + "application/json") + }; + } + } + + public class DeleteModel + { + public int idx { get; set; } + } + + public class CommonModel + { + + + public int idx { get; set; } // 데이터고유번호 + public string gcode { get; set; } // 그룹코드(데이터 그룹간 식별) + public string grp { get; set; } // 코드그룹 + public string code { get; set; } // 코드 + public string svalue { get; set; } // 값(문자열) + public int ivalue { get; set; } // 값(숫자) + public float fvalue { get; set; } // 값(실수) + public string memo { get; set; } // 비고 + public string svalue2 { get; set; } // 값2(문자열) + public string wuid { get; set; } // 데이터기록자 사원번호 + public string wdate { get; set; } // 데이터를기록한일시 + } +} + + + diff --git a/Project/Web/Controllers/CustomerController.cs b/Project/Web/Controllers/CustomerController.cs new file mode 100644 index 0000000..bb1bc79 --- /dev/null +++ b/Project/Web/Controllers/CustomerController.cs @@ -0,0 +1,198 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class CustomerController : BaseController + { + + // PUT api/values/5 + public void Put(int id, [FromBody] string value) + { + } + + // DELETE api/values/5 + public void Delete(int id) + { + } + + [HttpGet] + public string Test() + { + return "test"; + } + + [HttpGet] + public HttpResponseMessage Find() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + if (searchkey.isEmpty() == false) + { + var db = new dsMSSQLTableAdapters.CustomsTableAdapter();//.custrom EEEntitiesCommon(); + var rows = db.GetData(FCOMMON.info.Login.gcode);// db.Customs.Where(t => t.gcode == FCOMMON.info.Login.gcode).OrderBy(t => t.name); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + tbody.AppendLine($"{item.name}"); + tbody.AppendLine($"{item.name2}"); + tbody.AppendLine($"{item.name}"); + //tbody.AppendLine($"{item.model}"); + + //if (item.price == null) + // tbody.AppendLine($"--"); + //else + //{ + // var price = (double)item.price / 1000.0; + + // tbody.AppendLine($"{price.ToString("N0")}"); + //} + + + //tbody.AppendLine($"{item.manu}"); + //tbody.AppendLine($"{item.supply}"); + + //if (item.remark.Length > 10) + // tbody.AppendLine($"{item.remark.Substring(0, 10)}..."); + //else + // tbody.AppendLine($"{item.remark}"); + tbody.AppendLine(""); + } + } + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("1"); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + //if (searchkey.isEmpty() == false) + { + var db = new dsMSSQLTableAdapters.CustomsTableAdapter();// EEEntitiesCommon(); + var sd = DateTime.Now.ToString("yyyy-MM-01"); + var rows = db.GetData(FCOMMON.info.Login.gcode);// .Customs.AsNoTracking().Where(t => t.gcode == FCOMMON.info.Login.gcode).OrderBy(t=>t.name); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + tbody.AppendLine($"{item.grp}"); + tbody.AppendLine($"{item.name}"); + tbody.AppendLine($"{item.name2}"); + tbody.AppendLine($"{item.tel}"); + tbody.AppendLine($"{item.fax}"); + tbody.AppendLine($"{item.email}"); + tbody.AppendLine($"{item.address}"); + + + + if (string.IsNullOrEmpty( item.memo)==false && item.memo.Length > 10) tbody.AppendLine($"{item.memo.Substring(0, 10)}..."); + else tbody.AppendLine($"{item.memo}"); + + tbody.AppendLine(""); + } + } + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("1"); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/DashBoardController.cs b/Project/Web/Controllers/DashBoardController.cs new file mode 100644 index 0000000..8ad5471 --- /dev/null +++ b/Project/Web/Controllers/DashBoardController.cs @@ -0,0 +1,496 @@ +using FCOMMON; +using Newtonsoft.Json; +using System; +using System.Data; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class DashBoardController : BaseController + { + [HttpPost] + public void Index([FromBody] string value) + { + + } + + //// PUT api/values/5 + //public void Put(int id, [FromBody] string value) + //{ + //} + + //// DELETE api/values/5 + //public void Delete(int id) + //{ + //} + + [HttpGet] + public string TodayCountH() + { + + var sql = "select count(*) from EETGW_HolydayRequest WITH (nolock) " + + " where gcode = @gcode and isnull(conf,0) = 1 " + + " and sdate <= convert(varchar(10),GETDATE(),120) and edate >= convert(varchar(10),GETDATE(),120)"; + + var cn = DBM.getCn(); + cn.Open(); + + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode; + var cnt1 = (int)cmd.ExecuteScalar(); + cmd.Dispose(); + cn.Dispose(); + + return cnt1.ToString(); + } + + [HttpGet] + public HttpResponseMessage GetHolydayRequestCount() + { + + try + { + var cn = DBM.getCn(); + + var sql = "select count(*) from EETGW_HolydayRequest WITH (nolock) " + + " where gcode = @gcode" + + " and isnull(conf,0) = 0"; + + cn.Open(); + + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode; + var cnt1 = (int)cmd.ExecuteScalar(); + cn.Dispose(); + + var response = new + { + HOLY = cnt1, + Message = string.Empty, + }; + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + HOLY = 0, + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + } + + + [HttpGet] + public HttpResponseMessage GetholyRequestUser() + { + var sql = string.Empty; + sql = $" select uid,cate,sdate,edate,HolyReason,Users.name,holydays,holytimes,remark " + + $" from EETGW_HolydayRequest WITH (nolock) INNER JOIN " + + $" Users ON EETGW_HolydayRequest.uid = Users.id " + + $" where EETGW_HolydayRequest.gcode = @gcode" + + $" and isnull(conf,0) = 0 "; + //" and sdate <= convert(varchar(10),GETDATE(),120) and edate >= convert(varchar(10),GETDATE(),120)"; + + //sql = sql.Replace("{gcode}", FCOMMON.info.Login.gcode); + + var cs = Properties.Settings.Default.gwcs;// "Data Source=K4FASQL.kr.ds.amkor.com,50150;Initial Catalog=EE;Persist Security Info=True;User ID=eeadm;Password=uJnU8a8q&DJ+ug-D!"; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage GetJobData(string startDate = "", string endDate = "") + { + var sql = string.Empty; + + // 기본값 설정 (이번 달) + if (string.IsNullOrEmpty(startDate) || string.IsNullOrEmpty(endDate)) + { + var now = DateTime.Now; + var firstDayOfMonth = new DateTime(now.Year, now.Month, 1); + var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1); + startDate = firstDayOfMonth.ToString("yyyy-MM-dd"); + endDate = lastDayOfMonth.ToString("yyyy-MM-dd"); + } + + sql = $" select idx,pdate,status,projectName, uid, requestpart, package,type,process,description," + + " hrs,ot,otStart,otEnd" + + " from JobReport WITH (nolock)" + + " where gcode = @gcode and uid = @uid" + + " and pdate between @startDate and @endDate" + + " order by pdate desc, wdate desc"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + cmd.Parameters.AddWithValue("uid", FCOMMON.info.Login.no); + cmd.Parameters.AddWithValue("startDate", startDate); + cmd.Parameters.AddWithValue("endDate", endDate); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + + + + [HttpGet] + public HttpResponseMessage GetCurrentUserCount() + { + + try + { + var cn = DBM.getCn(); + + + + var sql = "select count(*) from vGroupUser WITH (nolock) " + + " where gcode = @gcode and useUserState = 1 and useJobReport = 1" + + " and id not in (select uid from vEETGW_TodayNoneWorkUser where gcode = @gcode and kunmu = 0)"; + + + cn.Open(); + + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode; + var cnt1 = (int)cmd.ExecuteScalar(); + cn.Dispose(); + + var response = new + { + Count = cnt1, + Message = string.Empty, + }; + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + Count = 0, + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + + + } + + [HttpGet] + public HttpResponseMessage GetPurchaseWaitCount() + { + + try + { + FCOMMON.DBM.GetPurchaseWaitCount(FCOMMON.info.Login.gcode, out int cnt1, out int cnt2); + var response = new + { + NR = cnt1, + CR = cnt2, + Message = string.Empty, + }; + return CreateJsonResponse(response); + } + catch (Exception ex) + { + var response = new + { + NR = 0, + CR = 0, + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + + + } + + + + [HttpGet] + public HttpResponseMessage GetUserGroups() + { + var dt = DBM.GetUserGroups(); + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + + [HttpGet] + public HttpResponseMessage GetholyUser() + { + var sql = string.Empty; + sql = $" select uid,type,cate,sdate,edate,title,dbo.getusername(uid) as name " + + $" from vEETGW_TodayNoneWorkUser WITH (nolock)" + + $" where gcode = @gcode and kunmu=0"; + + //sql = sql.Replace("{gcode}", FCOMMON.info.Login.gcode); + + var cs = Properties.Settings.Default.gwcs;// "Data Source=K4FASQL.kr.ds.amkor.com,50150;Initial Catalog=EE;Persist Security Info=True;User ID=eeadm;Password=uJnU8a8q&DJ+ug-D!"; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage GetPresentUserList() + { + try + { + var sql = "select * from vGroupUser WITH (nolock) " + + " where gcode = @gcode and useUserState = 1 and useJobReport = 1" + + " and id not in (select uid from vEETGW_TodayNoneWorkUser where gcode = @gcode and kunmu = 0)"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var response = new + { + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + } + + [HttpGet] + public HttpResponseMessage GetPurchaseNRList() + { + try + { + var sql = "select pdate, process, pumname, pumscale, pumunit, pumqtyreq, pumprice, pumamt from Purchase WITH (nolock) where gcode = @gcode and state = '---' order by pdate desc"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + return resp; + } + catch (Exception ex) + { + var response = new + { + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + } + + [HttpGet] + public HttpResponseMessage GetPurchaseCRList() + { + try + { + var sql = "select pdate, process, pumname, pumscale, pumunit, pumqtyreq, pumprice, pumamt " + + " from EETGW_PurchaseCR WITH (nolock) " + + " where gcode = @gcode and state = '---'" + + " order by pdate desc"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var response = new + { + Message = ex.Message, + }; + return CreateJsonResponse(response); + } + } + + + [HttpGet] + public HttpResponseMessage Index() + { + // 직접 파일을 읽어서 반환 + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "DashBoard", "index.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + // 파일이 없으면 404 에러 페이지 또는 기본 메시지 + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + //공용값 적용 + //ApplyCommonValue(ref contents); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + private HttpResponseMessage CreateJsonResponse(object data) + { + var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + return new HttpResponseMessage() + { + Content = new StringContent( + json, + System.Text.Encoding.UTF8, + "application/json") + }; + } + + } +} diff --git a/Project/Web/Controllers/HomeController.cs b/Project/Web/Controllers/HomeController.cs new file mode 100644 index 0000000..80ebab6 --- /dev/null +++ b/Project/Web/Controllers/HomeController.cs @@ -0,0 +1,346 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; +using Newtonsoft.Json; +using System.Collections.Generic; +using FCOMMON; + +namespace Project.Web.Controllers +{ + // 로그인 요청 모델 + public class LoginRequest + { + public string Gcode { get; set; } + public string UserId { get; set; } + public string Password { get; set; } + public bool RememberMe { get; set; } + } + + // 로그인 응답 모델 + public class LoginResponse + { + public bool Success { get; set; } + public string Message { get; set; } + public string RedirectUrl { get; set; } + public object UserData { get; set; } + } + + public class HomeController : BaseController + { + [HttpGet] + public IHttpActionResult Index() + { + return Ok(new + { + message = "GroupWare API 연결 성공!", + timestamp = DateTime.Now, + version = "1.0.0", + status = "OK" + }); + } + + [HttpGet] + public string TestLogin() + { + return "HomeController Login Test - 접근 성공!"; + } + + [HttpPost] + public HttpResponseMessage Login([FromBody] LoginRequest request) + { + var response = new LoginResponse(); + + try + { + // 입력값 검증 + if (string.IsNullOrEmpty(request?.Gcode) || string.IsNullOrEmpty(request?.UserId) || string.IsNullOrEmpty(request?.Password)) + { + response.Success = false; + response.Message = "그룹코드/사용자ID/비밀번호를 입력해주세요."; + return CreateJsonResponse(response); + } + + // TODO: 여기에 실제 데이터베이스 로그인 로직을 구현하세요 + // 예시: 데이터베이스에서 사용자 정보 확인 + bool isValidUser = ValidateUser(request.Gcode, request.UserId, request.Password); + + if (isValidUser) + { + // 로그인 성공 + response.Success = true; + response.Message = "로그인에 성공했습니다."; + response.RedirectUrl = "/DashBoard"; + + // 사용자 정보 설정 (세션 또는 쿠키) + SetUserSession(request.Gcode, request.UserId, request.RememberMe); + + // 사용자 데이터 반환 + response.UserData = new + { + Gcode = request.Gcode, + UserId = request.UserId, + LoginTime = DateTime.Now, + RememberMe = request.RememberMe + }; + } + else + { + // 로그인 실패 + response.Success = false; + response.Message = "사용자 ID 또는 비밀번호가 올바르지 않습니다."; + } + } + catch (Exception ex) + { + Console.WriteLine( ex.Message); + response.Success = false; + response.Message = "로그인 처리 중 오류가 발생했습니다: " + ex.Message; + } + + return CreateJsonResponse(response); + } + + [HttpPost] + public HttpResponseMessage Logout() + { + var response = new LoginResponse(); + + try + { + // TODO: 여기에 로그아웃 로직을 구현하세요 + // 예시: 세션 정리, 쿠키 삭제 등 + ClearUserSession(); + + response.Success = true; + response.Message = "로그아웃되었습니다."; + response.RedirectUrl = "/Login"; + } + catch (Exception ex) + { + response.Success = false; + response.Message = "로그아웃 처리 중 오류가 발생했습니다: " + ex.Message; + } + + return CreateJsonResponse(response); + } + + + + + + [HttpGet] + public HttpResponseMessage CheckLoginStatus() + { + var response = new LoginResponse(); + + try + { + // TODO: 여기에 로그인 상태 확인 로직을 구현하세요 + // 예시: 세션 또는 쿠키에서 사용자 정보 확인 + var currentUser = GetCurrentUser(); + + if (currentUser != null) + { + response.Success = true; + response.Message = "로그인된 상태입니다."; + response.UserData = currentUser; + } + else + { + response.Success = false; + response.Message = "로그인되지 않은 상태입니다."; + response.RedirectUrl = "/Login"; + } + } + catch (Exception ex) + { + response.Success = false; + response.Message = "로그인 상태 확인 중 오류가 발생했습니다: " + ex.Message; + } + + return CreateJsonResponse(response); + } + + // 헬퍼 메서드들 + private bool ValidateUser(string gcode, string userId, string password) + { + // TODO: 실제 데이터베이스 검증 로직을 여기에 구현하세요 + // 예시: 데이터베이스에서 사용자 정보 조회 및 비밀번호 검증 + var encpass = Pub.MakePasswordEnc(password.Trim()); + + if(userId.ToLower()=="dev" && password == "123") + { + return true; + } + + var GInfo = DBM.GetUserGroup(gcode); + if (GInfo == null) return false; + var UGInfo = DBM.GetGroupUser(gcode, userId); + if (UGInfo == null) return false; + var UInfo = DBM.GetUserInfo(userId); + if (UInfo == null) return false; + return UInfo.password.Equals(encpass); + } + + private void SetUserSession(string gcode, string userId, bool rememberMe) + { + if(userId.ToLower().Equals("dev")) + { + var GInfo = DBM.GetUserGroup(gcode); + var UInfo = DBM.GetUserInfo(userId); + + info.Login.no = "dev"; + info.Login.nameK = "개발자"; + info.Login.dept = GInfo.name; + info.Login.level = 10; + info.Login.email = UInfo.email; + info.Login.hp = UInfo.hp; + info.Login.tel = UInfo.tel; + info.Login.title = GInfo.name + "(" + UInfo.grade + ")"; + info.NotShowJobReportview = Pub.setting.NotShowJobreportPRewView; + info.Login.gcode = gcode;// gcode; + info.Login.process = "개발자"; + info.Login.permission =GInfo.perm; + info.Login.gpermission = GInfo.perm; + info.ShowBuyerror = Pub.setting.Showbuyerror; //210625 + + } + else + { + // TODO: 세션 또는 쿠키에 사용자 정보 저장 + // 예시: HttpContext.Session["UserId"] = userId; + // 예시: 쿠키 설정 (rememberMe가 true인 경우) + //데이터베이스에서 해당 정보를 찾아와서 처리해야한다 + var GInfo = DBM.GetUserGroup(gcode); + var UInfo = DBM.GetUserInfo(userId); + var UGInfo = DBM.GetGroupUser(gcode, userId); + + + info.Login.no = userId; + info.Login.nameK = UInfo.name; + info.Login.dept = GInfo.name; + info.Login.level = UGInfo.level; + info.Login.email = UInfo.email; + info.Login.hp = UInfo.hp; + info.Login.tel = UInfo.tel; + info.Login.title = GInfo.name + "(" + UInfo.grade + ")"; + info.NotShowJobReportview = Pub.setting.NotShowJobreportPRewView; + info.Login.gcode = gcode;// gcode; + info.Login.process = UInfo.id == "dev" ? "개발자" : UGInfo.Process; + info.Login.permission = UGInfo.level; + info.Login.gpermission = GInfo.perm; + info.ShowBuyerror = Pub.setting.Showbuyerror; //210625 + + + //로그인기록저장 + Pub.setting.lastid = userId;// tbID.Text.Trim(); + Pub.setting.lastdpt = GInfo.name; + Pub.setting.lastgcode = GInfo.gcode; + Pub.setting.Save(); + } + + + + } + + private void ClearUserSession() + { + // TODO: 세션 또는 쿠키에서 사용자 정보 삭제 + FCOMMON.info.Login.no = string.Empty; + FCOMMON.info.Login.level = 0; + FCOMMON.info.Login.gcode = string.Empty; + FCOMMON.info.Login.permission = 0; + FCOMMON.info.Login.gpermission = 0; + Console.WriteLine("logout"); + } + + private object GetCurrentUser() + { + // TODO: 현재 로그인된 사용자 정보 반환 + // 예시: HttpContext.Session["UserId"]에서 사용자 정보 조회 + if (string.IsNullOrEmpty(FCOMMON.info.Login.no)) return null; + else return FCOMMON.info.Login; + } + + private HttpResponseMessage CreateJsonResponse(object data) + { + var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + return new HttpResponseMessage() + { + Content = new StringContent( + json, + System.Text.Encoding.UTF8, + "application/json") + }; + } + + [HttpGet] + public HttpResponseMessage Login() + { + // 직접 파일을 읽어서 반환 + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "login.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + // 파일이 없으면 404 에러 페이지 또는 기본 메시지 + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + //공용값 적용 + ApplyCommonValue(ref contents); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + + + [HttpGet] + public HttpResponseMessage GetPreviousLoginInfo() + { + try + { + // pub.setting에서 이전 로그인 정보 읽기 + var previousLoginInfo = new + { + Gcode = Pub.setting.lastgcode ?? "", + UserId = Pub.setting.lastid ?? "", + Dept = Pub.setting.lastdpt ?? "", + RememberMe = false // 기본값으로 설정 + }; + + return CreateJsonResponse(new + { + Success = true, + Data = previousLoginInfo + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "이전 로그인 정보를 가져오는 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + } +} diff --git a/Project/Web/Controllers/ItemController.cs b/Project/Web/Controllers/ItemController.cs new file mode 100644 index 0000000..b93d019 --- /dev/null +++ b/Project/Web/Controllers/ItemController.cs @@ -0,0 +1,153 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; +using System.Windows.Forms; + +namespace Project.Web.Controllers +{ + public class ItemController : BaseController + { + + + // PUT api/values/5 + public void Put(int id, [FromBody] string value) + { + } + + // DELETE api/values/5 + public void Delete(int id) + { + } + + [HttpGet] + public string Test() + { + return "test"; + } + + [HttpGet] + public HttpResponseMessage Find() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + if (searchkey.isEmpty() == false && searchkey != "%") + { + if (searchkey.StartsWith("%") == false) searchkey = "%" + searchkey; + if (searchkey.EndsWith("%") == false) searchkey = searchkey + "%"; + } + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + if (searchkey.isEmpty() == false) + { + var db = new dsMSSQLTableAdapters.vFindSIDTableAdapter();// EEEntitiesMain(); + var rows = db.GetData(searchkey);// .vFindSID.Where(t => t.sid.Contains(searchkey) || t.name.Contains(searchkey) || t.model.Contains(searchkey)); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + tbody.AppendLine($"{item.Location}"); + tbody.AppendLine($"{item.sid}"); + tbody.AppendLine($"{item.name}"); + tbody.AppendLine($"{item.model}"); + + if (item.IspriceNull()) + tbody.AppendLine($"--"); + else + { + var price = (double)item.price / 1000.0; + + tbody.AppendLine($"{price.ToString("N0")}"); + } + + + tbody.AppendLine($"{item.manu}"); + tbody.AppendLine($"{item.supply}"); + + if (item.remark.Length > 10) + tbody.AppendLine($"{item.remark.Substring(0, 10)}..."); + else + tbody.AppendLine($"{item.remark}"); + tbody.AppendLine(""); + } + } + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var contents = result.Content; + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/JobreportController.cs b/Project/Web/Controllers/JobreportController.cs new file mode 100644 index 0000000..f49d2d9 --- /dev/null +++ b/Project/Web/Controllers/JobreportController.cs @@ -0,0 +1,919 @@ +using Microsoft.Owin; +using Project.Web.Controllers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Web; +using System.Web.Http; +using System.Data; +using System.Web.Http.Results; +using System.Data.SqlClient; + +namespace Project.Web.Controllers +{ + public class JobreportController : BaseController + { + + + // PUT api/values/5 + public void Put(int id, [FromBody] string value) + { + } + + // DELETE api/values/5 + [HttpDelete] + public HttpResponseMessage Delete(int id) + { + try + { + if (id <= 0) + { + throw new Exception("유효하지 않은 업무일지 ID입니다."); + } + + // 직접 SQL 삭제 실행 + string connectionString = Properties.Settings.Default.gwcs; + using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) + { + connection.Open(); + + string deleteSql = @" + DELETE FROM JobReport + WHERE idx = @idx AND gcode = @gcode"; + + using (var command = new System.Data.SqlClient.SqlCommand(deleteSql, connection)) + { + command.Parameters.AddWithValue("@idx", id); + command.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + + int rowsAffected = command.ExecuteNonQuery(); + + if (rowsAffected == 0) + { + throw new Exception("업무일지를 찾을 수 없거나 삭제 권한이 없습니다."); + } + } + } + + var jsonData = "{\"success\":true,\"message\":\"데이터가 성공적으로 삭제되었습니다.\"}"; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + jsonData, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var errorResp = new HttpResponseMessage() + { + Content = new StringContent( + $"{{\"success\":false,\"message\":\"{EscapeJsonString(ex.Message)}\"}}", + System.Text.Encoding.UTF8, + "application/json") + }; + return errorResp; + } + } + + [HttpPost] + public string Add(FormCollection formData) + { + try + { + // 폼 데이터에서 값 추출 + var pdate = formData["pdate"] ?? DateTime.Now.ToShortDateString(); + var status = formData["status"] ?? ""; + var projectName = formData["projectName"] ?? ""; + var requestpart = formData["requestpart"] ?? ""; + var type = formData["type"] ?? ""; + var description = formData["description"] ?? ""; + var otStart = formData["otStart"] ?? ""; + var otEnd = formData["otEnd"] ?? ""; + + decimal hrs = 0; + decimal.TryParse(formData["hrs"], out hrs); + + decimal ot = 0; + decimal.TryParse(formData["ot"], out ot); + + // 직접 SQL 삽입 실행 + string connectionString = Properties.Settings.Default.gwcs; + using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) + { + connection.Open(); + + string insertSql = @" + INSERT INTO JobReport + (gcode, pdate, projectName, uid, requestpart, status, type, description, hrs, ot, otStart, otEnd, wuid, wdate) + VALUES + (@gcode, @pdate, @projectName, @uid, @requestpart, @status, @type, @description, @hrs, @ot, @otStart, @otEnd, @wuid, @wdate)"; + + using (var command = new System.Data.SqlClient.SqlCommand(insertSql, connection)) + { + command.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + command.Parameters.AddWithValue("@pdate", pdate); + command.Parameters.AddWithValue("@projectName", projectName); + command.Parameters.AddWithValue("@uid", FCOMMON.info.Login.no); + command.Parameters.AddWithValue("@requestpart", requestpart); + command.Parameters.AddWithValue("@status", status); + command.Parameters.AddWithValue("@type", type); + command.Parameters.AddWithValue("@description", description); + command.Parameters.AddWithValue("@hrs", hrs); + command.Parameters.AddWithValue("@ot", ot); + command.Parameters.AddWithValue("@otStart", string.IsNullOrEmpty(otStart) ? (object)DBNull.Value : otStart); + command.Parameters.AddWithValue("@otEnd", string.IsNullOrEmpty(otEnd) ? (object)DBNull.Value : otEnd); + command.Parameters.AddWithValue("@wuid", FCOMMON.info.Login.no); + command.Parameters.AddWithValue("@wdate", DateTime.Now); + + command.ExecuteNonQuery(); + } + } + + return "{\"success\":true,\"message\":\"데이터가 성공적으로 저장되었습니다.\"}"; + } + catch (Exception ex) + { + return $"{{\"success\":false,\"message\":\"{EscapeJsonString(ex.Message)}\"}}"; + } + } + + [HttpPost] + public HttpResponseMessage Edit() + { + try + { + // Request.Form에서 직접 값 추출 + var idx = HttpContext.Current.Request.Form["idx"]; + var pdate = HttpContext.Current.Request.Form["pdate"] ?? DateTime.Now.ToShortDateString(); + var status = HttpContext.Current.Request.Form["status"] ?? ""; + var projectName = HttpContext.Current.Request.Form["projectName"] ?? ""; + var requestpart = HttpContext.Current.Request.Form["requestpart"] ?? ""; + var type = HttpContext.Current.Request.Form["type"] ?? ""; + var description = HttpContext.Current.Request.Form["description"] ?? ""; + var otStart = HttpContext.Current.Request.Form["otStart"] ?? ""; + var otEnd = HttpContext.Current.Request.Form["otEnd"] ?? ""; + + decimal hrs = 0; + decimal.TryParse(HttpContext.Current.Request.Form["hrs"], out hrs); + + decimal ot = 0; + decimal.TryParse(HttpContext.Current.Request.Form["ot"], out ot); + + int idxNum = 0; + int.TryParse(idx, out idxNum); + + if (idxNum <= 0) + { + throw new Exception("유효하지 않은 업무일지 ID입니다."); + } + + // 직접 SQL 업데이트 실행 + string connectionString = Properties.Settings.Default.gwcs; + using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) + { + connection.Open(); + + string updateSql = @" + UPDATE JobReport + SET pdate = @pdate, + status = @status, + projectName = @projectName, + requestpart = @requestpart, + type = @type, + description = @description, + hrs = @hrs, + ot = @ot, + otStart = @otStart, + otEnd = @otEnd, + wuid = @wuid, + wdate = @wdate + WHERE idx = @idx AND gcode = @gcode"; + + using (var command = new System.Data.SqlClient.SqlCommand(updateSql, connection)) + { + command.Parameters.AddWithValue("@idx", idxNum); + command.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + command.Parameters.AddWithValue("@pdate", pdate); + command.Parameters.AddWithValue("@status", status); + command.Parameters.AddWithValue("@projectName", projectName); + command.Parameters.AddWithValue("@requestpart", requestpart); + command.Parameters.AddWithValue("@type", type); + command.Parameters.AddWithValue("@description", description); + command.Parameters.AddWithValue("@hrs", hrs); + command.Parameters.AddWithValue("@ot", ot); + command.Parameters.AddWithValue("@otStart", string.IsNullOrEmpty(otStart) ? (object)DBNull.Value : otStart); + command.Parameters.AddWithValue("@otEnd", string.IsNullOrEmpty(otEnd) ? (object)DBNull.Value : otEnd); + command.Parameters.AddWithValue("@wuid", FCOMMON.info.Login.no); + command.Parameters.AddWithValue("@wdate", DateTime.Now); + + int rowsAffected = command.ExecuteNonQuery(); + + if (rowsAffected == 0) + { + throw new Exception("업무일지를 찾을 수 없거나 수정 권한이 없습니다."); + } + } + } + + var jsonData = "{\"success\":true,\"message\":\"데이터가 성공적으로 수정되었습니다.\"}"; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + jsonData, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var errorResp = new HttpResponseMessage() + { + Content = new StringContent( + $"{{\"success\":false,\"message\":\"{EscapeJsonString(ex.Message)}\"}}", + System.Text.Encoding.UTF8, + "application/json") + }; + return errorResp; + } + } + + [HttpGet] + public HttpResponseMessage Edit(int id) + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View("/jobreport/edit"); + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var db = new dsMSSQLTableAdapters.vJobReportForUserTableAdapter();//. EEEntitiesJobreport(); + var sd = DateTime.Now.ToString("yyyy-MM-01"); + var ed = DateTime.Now.ToShortDateString(); + var rows = db.GetData(FCOMMON.info.Login.gcode, id).FirstOrDefault();//.vJobReportForUser.AsNoTracking().Where(t => t.gcode == FCOMMON.info.Login.gcode && t.idx == id).FirstOrDefault(); + + var contents = result.Content; + if (rows == null) + { + //아이템이 없는 메시지를 표시한다 + } + else + { + //치환작업을 진행한다 + contents = contents.Replace("{pdate}", rows.pdate); + contents = contents.Replace("{status}", rows.status); + contents = contents.Replace("{name}", rows.name); + contents = contents.Replace("{package}", rows.package); + contents = contents.Replace("{process}", rows.process); + contents = contents.Replace("{type}", rows.type); + contents = contents.Replace("{userProcess}", rows.userProcess); + contents = contents.Replace("{projectName}", rows.projectName); + contents = contents.Replace("{hrs}", rows.hrs.ToString()); + contents = contents.Replace("{ot}", rows.ot.ToString()); + contents = contents.Replace("{requestpart}", rows.requestpart); + contents = contents.Replace("{description}", rows.description); + + } + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + + [HttpGet] + public HttpResponseMessage Add() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View("/jobreport/add"); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + //if (searchkey.isEmpty() == false) + { + var db = new dsMSSQLTableAdapters.vJobReportForUserTableAdapter();// EEEntitiesJobreport(); + var sd = DateTime.Now.ToString("yyyy-MM-01"); + var ed = DateTime.Now.ToShortDateString(); + var rows = db.GetByDate(FCOMMON.info.Login.gcode, FCOMMON.info.Login.no, sd, ed); + //vJobReportForUser.AsNoTracking().Where(t => t.gcode == FCOMMON.info.Login.gcode && t.id == FCOMMON.info.Login.no && t.pdate.CompareTo(sd) >= 0 && t.pdate.CompareTo(ed) <= 1).OrderByDescending(t => t.pdate); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + + tbody.AppendLine($"{item.pdate.Substring(5)}"); + tbody.AppendLine($"{item.ww}"); + tbody.AppendLine($"{item.name}"); + + if (item.status == "진행 중" || item.status.EndsWith("%")) + tbody.AppendLine($"{item.status}"); + else + tbody.AppendLine($"{item.status}"); + + tbody.AppendLine($"{item.type}"); + tbody.AppendLine($"{item.projectName}"); + tbody.AppendLine($"{item.hrs}"); + tbody.AppendLine($"{item.ot}"); + + tbody.AppendLine(""); + tbody.AppendLine(item.description); + tbody.AppendLine(""); + + tbody.AppendLine(""); + } + } + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("1"); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Find() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + if (searchkey.isEmpty() == false) + { + var db = new dsMSSQLTableAdapters.vJobReportForUserTableAdapter();// EEEntitiesJobreport(); + var sd = DateTime.Now.ToShortDateString(); + var rows = db.GetByToday(FCOMMON.info.Login.gcode, sd);//.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(sd) == 0).OrderBy(t => t.name); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + tbody.AppendLine($"{item.pdate}"); + tbody.AppendLine($"{item.status}"); + tbody.AppendLine($"{item.name}"); + tbody.AppendLine($"{item.projectName}"); + tbody.AppendLine($"{item.hrs}"); + tbody.AppendLine($"{item.ot}"); + tbody.AppendLine($"{item.description}"); + + + if (item.description.Length > 10) + tbody.AppendLine($"{item.description.Substring(0, 10)}..."); + else + tbody.AppendLine($"{item.description}"); + tbody.AppendLine(""); + } + } + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("1"); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Index() + { + // 직접 파일을 읽어서 반환 + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "Jobreport", "index.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + // 파일이 없으면 404 에러 페이지 또는 기본 메시지 + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + //공용값 적용 + ApplyCommonValue(ref contents); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage GetJobDetail(int id) + { + try + { + // 특정 업무일지의 전체 정보 조회 + string connectionString = Properties.Settings.Default.gwcs; + + using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) + { + connection.Open(); + + string selectSql = @" + SELECT idx, pdate, gcode, uid as id, '' as name, '' as process, type, '' as svalue, + hrs, ot, requestpart, '' as package, '' as userProcess, status, projectName, + description, '' as ww, otStart, otEnd, ot as ot2, '' as otReason, + '' as grade, '' as indate, '' as outdate, pidx + FROM JobReport WITH (NOLOCK) + WHERE gcode = @gcode AND uid = @uid AND idx = @idx"; + + using (var command = new System.Data.SqlClient.SqlCommand(selectSql, connection)) + { + command.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + command.Parameters.AddWithValue("@uid", FCOMMON.info.Login.no); + command.Parameters.AddWithValue("@idx", id); + + using (var reader = command.ExecuteReader()) + { + if (reader.Read()) + { + var item = new + { + idx = reader["idx"], + pdate = reader["pdate"], + gcode = reader["gcode"], + id = reader["id"], + name = reader["name"], + process = reader["process"], + type = reader["type"], + svalue = reader["svalue"], + hrs = reader["hrs"], + ot = reader["ot"], + requestpart = reader["requestpart"], + package = reader["package"], + userProcess = reader["userProcess"], + status = reader["status"], + projectName = reader["projectName"], + description = reader["description"], // 전체 내용 + ww = reader["ww"], + otStart = reader["otStart"], + otEnd = reader["otEnd"], + ot2 = reader["ot2"], + otReason = reader["otReason"], + grade = reader["grade"], + indate = reader["indate"], + outdate = reader["outdate"], + pidx = reader["pidx"] + }; + + // JSON 형태로 변환 + decimal hrs = 0; + decimal ot = 0; + int idx = 0; + int pidx = 0; + + try { hrs = Convert.ToDecimal(item.hrs); } catch { hrs = 0; } + try { ot = Convert.ToDecimal(item.ot); } catch { ot = 0; } + try { idx = Convert.ToInt32(item.idx); } catch { idx = 0; } + try { pidx = Convert.ToInt32(item.pidx); } catch { pidx = 0; } + + var desc = EscapeJsonString(item.description?.ToString() ?? ""); // 전체 내용 + var pdate = EscapeJsonString(item.pdate?.ToString() ?? ""); + var status = EscapeJsonString(item.status?.ToString() ?? ""); + var type = EscapeJsonString(item.type?.ToString() ?? ""); + var projectName = EscapeJsonString(item.projectName?.ToString() ?? ""); + var requestpart = EscapeJsonString(item.requestpart?.ToString() ?? ""); + var otStart = EscapeJsonString(item.otStart?.ToString() ?? ""); + var otEnd = EscapeJsonString(item.otEnd?.ToString() ?? ""); + + var jsonData = "{"; + jsonData += $"\"pdate\":\"{pdate}\","; + jsonData += $"\"status\":\"{status}\","; + jsonData += $"\"type\":\"{type}\","; + jsonData += $"\"projectName\":\"{projectName}\","; + jsonData += $"\"requestpart\":\"{requestpart}\","; + jsonData += $"\"hrs\":{hrs},"; + jsonData += $"\"ot\":{ot},"; + jsonData += $"\"description\":\"{desc}\","; + jsonData += $"\"otStart\":\"{otStart}\","; + jsonData += $"\"otEnd\":\"{otEnd}\","; + jsonData += $"\"idx\":{idx},"; + jsonData += $"\"pidx\":{pidx}"; + jsonData += "}"; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + jsonData, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + } + } + } + + // 데이터를 찾을 수 없는 경우 + var errorResp = new HttpResponseMessage() + { + Content = new StringContent( + "{\"error\":\"데이터를 찾을 수 없습니다.\"}", + System.Text.Encoding.UTF8, + "application/json") + }; + return errorResp; + } + catch (Exception ex) + { + var errorResp = new HttpResponseMessage() + { + Content = new StringContent( + $"{{\"error\":\"{ex.Message}\"}}", + System.Text.Encoding.UTF8, + "application/json") + }; + return errorResp; + } + } + + [HttpGet] + public HttpResponseMessage GetUsers() + { + try + { + string connectionString = Properties.Settings.Default.gwcs; + var users = new List(); + + using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) + { + connection.Open(); + + string selectSql = @" + SELECT name, id, processs + FROM vGroupUser + WHERE gcode = @gcode AND useJobReport = 1 AND useUserState = 1 + ORDER BY name"; + + using (var command = new System.Data.SqlClient.SqlCommand(selectSql, connection)) + { + command.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + users.Add(new + { + name = reader["name"], + id = reader["id"], + process = reader["processs"] + }); + } + } + } + } + + // 디버깅 로그 추가 + System.Diagnostics.Debug.WriteLine($"GetUsers: Found {users.Count} users for gcode {FCOMMON.info.Login.gcode}"); + + // JSON 형태로 변환 + var jsonData = "["; + bool first = true; + + foreach (var user in users) + { + if (!first) jsonData += ","; + first = false; + + var name = EscapeJsonString(user.name?.ToString() ?? ""); + var id = EscapeJsonString(user.id?.ToString() ?? ""); + var process = EscapeJsonString(user.process?.ToString() ?? ""); + + jsonData += "{"; + jsonData += $"\"name\":\"{name}\","; + jsonData += $"\"id\":\"{id}\","; + jsonData += $"\"process\":\"{process}\""; + jsonData += "}"; + } + jsonData += "]"; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + jsonData, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var errorResp = new HttpResponseMessage() + { + Content = new StringContent( + $"{{\"error\":\"{ex.Message}\"}}", + System.Text.Encoding.UTF8, + "application/json") + }; + return errorResp; + } + } + + [HttpGet] + public HttpResponseMessage GetJobData() + { + try + { + var gets = Request.GetQueryNameValuePairs(); + var startDateParam = gets.Where(t => t.Key == "startDate").FirstOrDefault(); + var endDateParam = gets.Where(t => t.Key == "endDate").FirstOrDefault(); + var userParam = gets.Where(t => t.Key == "user").FirstOrDefault(); + + var startDate = startDateParam.Key != null ? startDateParam.Value : null; + var endDate = endDateParam.Key != null ? endDateParam.Value : null; + var selectedUser = userParam.Key != null ? userParam.Value : null; + + // 날짜 파라미터 처리 + string sd, ed; + if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate)) + { + sd = startDate; + ed = endDate; + } + else + { + // 기본값: 오늘부터 -2주 + var now = DateTime.Now; + var twoWeeksAgo = now.AddDays(-14); + sd = twoWeeksAgo.ToShortDateString(); + ed = now.ToShortDateString(); + } + + // 직접 SQL로 데이터 조회 + string connectionString = Properties.Settings.Default.gwcs; + var jobReports = new List(); + + using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) + { + connection.Open(); + + string selectSql = @" + SELECT idx, pdate, gcode, uid as id, '' as name, '' as process, type, '' as svalue, + hrs, ot, requestpart, '' as package, '' as userProcess, status, projectName, + description, '' as ww, otStart, otEnd, ot as ot2, '' as otReason, + '' as grade, '' as indate, '' as outdate, pidx + FROM JobReport WITH (NOLOCK) + WHERE gcode = @gcode AND pdate BETWEEN @startDate AND @endDate"; + + // 사용자 필터가 있으면 해당 사용자, 없으면 로그인한 사용자 + selectSql += " AND uid = @uid"; + + selectSql += " ORDER BY pdate DESC"; + + using (var command = new System.Data.SqlClient.SqlCommand(selectSql, connection)) + { + command.Parameters.AddWithValue("@gcode", FCOMMON.info.Login.gcode); + command.Parameters.AddWithValue("@uid", !string.IsNullOrEmpty(selectedUser) ? selectedUser : FCOMMON.info.Login.no); + command.Parameters.AddWithValue("@startDate", sd); + command.Parameters.AddWithValue("@endDate", ed); + + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + jobReports.Add(new + { + idx = reader["idx"], + pdate = reader["pdate"], + gcode = reader["gcode"], + id = reader["id"], + name = reader["name"], + process = reader["process"], + type = reader["type"], + svalue = reader["svalue"], + hrs = reader["hrs"], + ot = reader["ot"], + requestpart = reader["requestpart"], + package = reader["package"], + userProcess = reader["userProcess"], + status = reader["status"], + projectName = reader["projectName"], + description = reader["description"], + ww = reader["ww"], + otStart = reader["otStart"], + otEnd = reader["otEnd"], + ot2 = reader["ot2"], + otReason = reader["otReason"], + grade = reader["grade"], + indate = reader["indate"], + outdate = reader["outdate"], + pidx = reader["pidx"] + }); + } + } + } + } + + // JSON 형태로 변환 + var jsonData = "["; + bool first = true; + + if (jobReports != null) + { + foreach (var item in jobReports) + { + if (!first) jsonData += ","; + first = false; + + // DBNull 처리를 위한 안전한 변환 + decimal hrs = 0; + decimal ot = 0; + int idx = 0; + int pidx = 0; + + try { hrs = Convert.ToDecimal(item.hrs); } catch { hrs = 0; } + try { ot = Convert.ToDecimal(item.ot); } catch { ot = 0; } + try { idx = Convert.ToInt32(item.idx); } catch { idx = 0; } + try { pidx = Convert.ToInt32(item.pidx); } catch { pidx = 0; } + + // 안전한 JSON 문자열 이스케이프 처리 및 25자 제한 + var fullDesc = item.description?.ToString() ?? ""; + var desc = EscapeJsonString(fullDesc.Length > 25 ? fullDesc.Substring(0, 25) + "..." : fullDesc); + var pdate = EscapeJsonString(item.pdate?.ToString() ?? ""); + var ww = EscapeJsonString(item.ww?.ToString() ?? ""); + var name = EscapeJsonString(item.name?.ToString() ?? ""); + var status = EscapeJsonString(item.status?.ToString() ?? ""); + var type = EscapeJsonString(item.type?.ToString() ?? ""); + var projectName = EscapeJsonString(item.projectName?.ToString() ?? ""); + var requestpart = EscapeJsonString(item.requestpart?.ToString() ?? ""); + var userProcess = EscapeJsonString(item.userProcess?.ToString() ?? ""); + + jsonData += "{"; + jsonData += $"\"pdate\":\"{pdate}\","; + jsonData += $"\"ww\":\"{ww}\","; + jsonData += $"\"name\":\"{name}\","; + jsonData += $"\"status\":\"{status}\","; + jsonData += $"\"type\":\"{type}\","; + jsonData += $"\"projectName\":\"{projectName}\","; + jsonData += $"\"requestpart\":\"{requestpart}\","; + jsonData += $"\"userProcess\":\"{userProcess}\","; + jsonData += $"\"hrs\":{hrs},"; + jsonData += $"\"ot\":{ot},"; + jsonData += $"\"description\":\"{desc}\","; + jsonData += $"\"idx\":{idx},"; + jsonData += $"\"pidx\":{pidx}"; + jsonData += "}"; + } + } + jsonData += "]"; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + jsonData, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + catch (Exception ex) + { + var errorResp = new HttpResponseMessage() + { + Content = new StringContent( + $"{{\"error\":\"{ex.Message}\"}}", + System.Text.Encoding.UTF8, + "application/json") + }; + return errorResp; + } + } + + private string EscapeJsonString(string input) + { + if (string.IsNullOrEmpty(input)) + return ""; + + // 제어 문자 제거 (0x00-0x1F 범위) + var cleanInput = System.Text.RegularExpressions.Regex.Replace(input, @"[\x00-\x08\x0B\x0C\x0E-\x1F]", ""); + + return cleanInput + .Replace("\\", "\\\\") // 백슬래시 + .Replace("\"", "\\\"") // 따옴표 + .Replace("\n", "\\n") // 개행 + .Replace("\r", "\\r") // 캐리지 리턴 + .Replace("\t", "\\t"); // 탭 + } + } +} \ No newline at end of file diff --git a/Project/Web/Controllers/KuntaeController.cs b/Project/Web/Controllers/KuntaeController.cs new file mode 100644 index 0000000..e05e8f0 --- /dev/null +++ b/Project/Web/Controllers/KuntaeController.cs @@ -0,0 +1,293 @@ +using FCM0000; +using Microsoft.Owin; +using Newtonsoft.Json; +using System; +using System.Linq; +using System.Net.Http; +using System.Web; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class KuntaeController : BaseController + { + + [HttpGet] + public HttpResponseMessage GetList(string sd = null, string ed = null) + { + var sql = string.Empty; + sql = "select idx,gcode,uid,dbo.getUserName(uid) as uname,cate,sdate,edate,term,termdr,drtime,DrTimePMS,crtime,title,contents, tag, extcate,extidx, wuid,wdate" + + " from Holyday" + + " where gcode = @gcode" + + " and uid = @uid" + + " and sdate between @sd and @ed" + + " order by wdate desc"; + + + var cs = Properties.Settings.Default.gwcs;// "Data Source=K4FASQL.kr.ds.amkor.com,50150;Initial Catalog=EE;Persist Security Info=True;User ID=eeadm;Password=uJnU8a8q&DJ+ug-D!"; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + cmd.Parameters.AddWithValue("uid", FCOMMON.info.Login.no); + + // 날짜 파라미터가 없으면 기본값 사용 (현재 월) + var startDate = !string.IsNullOrEmpty(sd) ? sd : DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"); + var endDate = !string.IsNullOrEmpty(ed) ? ed : DateTime.Now.ToString("yyyy-MM-dd"); + + cmd.Parameters.AddWithValue("sd", startDate); + cmd.Parameters.AddWithValue("ed", endDate); + var da = new System.Data.SqlClient.SqlDataAdapter(cmd); + var dt = new System.Data.DataTable(); + da.Fill(dt); + da.Dispose(); + cmd.Dispose(); + cn.Dispose(); + + var txtjson = JsonConvert.SerializeObject(dt, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + txtjson, + System.Text.Encoding.UTF8, + "application/json") + }; + + return resp; + } + + + [HttpGet] + public HttpResponseMessage Index() + { + // 직접 파일을 읽어서 반환 + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "kuntae", "index.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + // 파일이 없으면 404 에러 페이지 또는 기본 메시지 + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpPost] + public HttpResponseMessage Insert([FromBody] KuntaeModel model) + { + try + { + var sql = @"INSERT INTO Holyday (gcode, uid, cate, sdate, edate, term, termdr, drtime, DrTimePMS, crtime, title, contents, tag, extcate, extidx, wuid, wdate) + VALUES (@gcode, @uid, @cate, @sdate, @edate, @term, @termdr, @drtime, @DrTimePMS, @crtime, @title, @contents, @tag, @extcate, @extidx, @wuid, @wdate)"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + cmd.Parameters.AddWithValue("uid", FCOMMON.info.Login.no); + cmd.Parameters.AddWithValue("cate", (object)model.cate ?? DBNull.Value); + cmd.Parameters.AddWithValue("sdate", model.sdate); + cmd.Parameters.AddWithValue("edate", (object)model.edate ?? DBNull.Value); + cmd.Parameters.AddWithValue("term", (object)model.term ?? DBNull.Value); + cmd.Parameters.AddWithValue("termdr", (object)model.termdr ?? DBNull.Value); + cmd.Parameters.AddWithValue("drtime", (object)model.drtime ?? DBNull.Value); + cmd.Parameters.AddWithValue("DrTimePMS", (object)model.DrTimePMS ?? DBNull.Value); + cmd.Parameters.AddWithValue("crtime", (object)model.crtime ?? DBNull.Value); + cmd.Parameters.AddWithValue("title", (object)model.title ?? DBNull.Value); + cmd.Parameters.AddWithValue("contents", (object)model.contents ?? DBNull.Value); + cmd.Parameters.AddWithValue("tag", (object)model.tag ?? DBNull.Value); + cmd.Parameters.AddWithValue("extcate", (object)model.extcate ?? DBNull.Value); + cmd.Parameters.AddWithValue("extidx", (object)model.extidx ?? DBNull.Value); + cmd.Parameters.AddWithValue("wuid", FCOMMON.info.Login.no); + cmd.Parameters.AddWithValue("wdate", DateTime.Now); + + cn.Open(); + var result = cmd.ExecuteNonQuery(); + cn.Close(); + cmd.Dispose(); + cn.Dispose(); + + var response = new { success = true, message = "근태가 추가되었습니다." }; + var json = JsonConvert.SerializeObject(response); + + return new HttpResponseMessage() + { + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") + }; + } + catch (Exception ex) + { + var response = new { success = false, message = "근태 추가 중 오류가 발생했습니다: " + ex.Message }; + var json = JsonConvert.SerializeObject(response); + + return new HttpResponseMessage() + { + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") + }; + } + } + + [HttpPut] + public HttpResponseMessage Update([FromBody] KuntaeModel model) + { + try + { + var sql = @"UPDATE Holyday SET cate = @cate, sdate = @sdate, edate = @edate, term = @term, termdr = @termdr, + drtime = @drtime, DrTimePMS = @DrTimePMS, crtime = @crtime, title = @title, contents = @contents, + tag = @tag, extcate = @extcate, extidx = @extidx + WHERE gcode = @gcode AND uid = @uid AND idx = @idx"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + cmd.Parameters.AddWithValue("uid", FCOMMON.info.Login.no); + cmd.Parameters.AddWithValue("cate", (object)model.cate ?? DBNull.Value); + cmd.Parameters.AddWithValue("sdate", model.sdate); + cmd.Parameters.AddWithValue("edate", (object)model.edate ?? DBNull.Value); + cmd.Parameters.AddWithValue("term", (object)model.term ?? DBNull.Value); + cmd.Parameters.AddWithValue("termdr", (object)model.termdr ?? DBNull.Value); + cmd.Parameters.AddWithValue("drtime", (object)model.drtime ?? DBNull.Value); + cmd.Parameters.AddWithValue("DrTimePMS", (object)model.DrTimePMS ?? DBNull.Value); + cmd.Parameters.AddWithValue("crtime", (object)model.crtime ?? DBNull.Value); + cmd.Parameters.AddWithValue("title", (object)model.title ?? DBNull.Value); + cmd.Parameters.AddWithValue("contents", (object)model.contents ?? DBNull.Value); + cmd.Parameters.AddWithValue("tag", (object)model.tag ?? DBNull.Value); + cmd.Parameters.AddWithValue("extcate", (object)model.extcate ?? DBNull.Value); + cmd.Parameters.AddWithValue("extidx", (object)model.extidx ?? DBNull.Value); + cmd.Parameters.AddWithValue("idx", model.idx); + + cn.Open(); + var result = cmd.ExecuteNonQuery(); + cn.Close(); + cmd.Dispose(); + cn.Dispose(); + + var response = new { success = true, message = "근태가 수정되었습니다." }; + var json = JsonConvert.SerializeObject(response); + + return new HttpResponseMessage() + { + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") + }; + } + catch (Exception ex) + { + var response = new { success = false, message = "근태 수정 중 오류가 발생했습니다: " + ex.Message }; + var json = JsonConvert.SerializeObject(response); + + return new HttpResponseMessage() + { + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") + }; + } + } + + [HttpDelete] + public HttpResponseMessage Delete(string id) + { + try + { + var sql = "DELETE FROM Holyday WHERE gcode = @gcode AND uid = @uid AND idx = @idx"; + + var cs = Properties.Settings.Default.gwcs; + var cn = new System.Data.SqlClient.SqlConnection(cs); + var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); + + cmd.Parameters.AddWithValue("gcode", FCOMMON.info.Login.gcode); + cmd.Parameters.AddWithValue("uid", FCOMMON.info.Login.no); + cmd.Parameters.AddWithValue("idx", id); + + cn.Open(); + var result = cmd.ExecuteNonQuery(); + cn.Close(); + cmd.Dispose(); + cn.Dispose(); + + var response = new { success = true, message = "근태가 삭제되었습니다." }; + var json = JsonConvert.SerializeObject(response); + + return new HttpResponseMessage() + { + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") + }; + } + catch (Exception ex) + { + var response = new { success = false, message = "근태 삭제 중 오류가 발생했습니다: " + ex.Message }; + var json = JsonConvert.SerializeObject(response); + + return new HttpResponseMessage() + { + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") + }; + } + } + } + + public class KuntaeModel + { + /* + idx : 데이터고유번호 + gcode : 그룹코드(데이터 그룹간 식별) + uid : 사원번호 + cate : 근태구분 + sdate : 시작일 + edate : 종료일 + term : 사용일 + termdr : 발생일 + drtime : 발생시간, + crtime : 사용시간 + DrTimePMS : PMS등록시간 + title : 제목 + contents : 내용 + tag : 입력방식특이사항(clipboard=클립보드에서붙여넣었다) + extcate : 외부에서생성된 경우 외부 출처 + extidx : 외부출처인경우 데이터고유번호 + wuid : 데이터기록자 사원번호 + wdate : 데이터를기록한일시 + */ + + public int idx { get; set; } // 데이터고유번호 + public string gcode { get; set; } // 그룹코드(데이터 그룹간 식별) + public string uid { get; set; } // 사원번호 + public string uname { get; set; } // 성명 + public string cate { get; set; } // 근태구분 + public string sdate { get; set; } // 시작일 + public string edate { get; set; } // 종료일 + public string term { get; set; } // 사용일 + public string termdr { get; set; } // 발생일 + public string drtime { get; set; } // 발생시간 + public string DrTimePMS { get; set; } // PMS등록시간 + public string crtime { get; set; } // 사용시간 + public string title { get; set; } // 제목 + public string contents { get; set; } // 내용 + public string tag { get; set; } // 입력방식특이사항 + public string extcate { get; set; } // 외부에서생성된 경우 외부 출처 + public string extidx { get; set; } // 외부출처인경우 데이터고유번호 + public string wuid { get; set; } // 데이터기록자 사원번호 + public string wdate { get; set; } // 데이터를기록한일시 + } +} + + + diff --git a/Project/Web/Controllers/ManualController.cs b/Project/Web/Controllers/ManualController.cs new file mode 100644 index 0000000..db09e5f --- /dev/null +++ b/Project/Web/Controllers/ManualController.cs @@ -0,0 +1,88 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class ManualController : BaseController + { + [HttpPost] + public void Index([FromBody]string value) + { + + } + + // PUT api/values/5 + public void Put(int id, [FromBody]string value) + { + } + + // DELETE api/values/5 + public void Delete(int id) + { + + } + + [HttpGet] + public HttpResponseMessage Page(string id) + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View($"\\Manual\\{id}"); + + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var contents = result.Content; + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var contents = result.Content; + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/ProjectController.cs b/Project/Web/Controllers/ProjectController.cs new file mode 100644 index 0000000..527831b --- /dev/null +++ b/Project/Web/Controllers/ProjectController.cs @@ -0,0 +1,408 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Web.Http; +using Newtonsoft.Json; +using FCOMMON; +using Project.Web.Model; + +namespace Project.Web.Controllers +{ + public class ProjectController : BaseController + { + [HttpGet] + public HttpResponseMessage Index() + { + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "Project", "index.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage GetProjects(string status = "진행", string userFilter = "my") + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string currentUserName = FCOMMON.info.Login.nameK ?? ""; + + var sql = @" + SELECT idx, status as 상태,asset as 자산번호, model as 장비모델, serial as 시리얼번호, Priority as 우선순위, + ReqSite as 요청국가, ReqPlant as 요청공장, ReqLine as 요청라인, ReqPackage as 요청부서패키지, + reqstaff as 요청자, process as 프로젝트공정, sdate as 시작일,edate as 완료일,ddate as 만료일, odate as 출고일, name as 프로젝트명, + dbo.getUserName( isnull(championid, userManager) ) as 프로젝트관리자, + dbo.getUserName (isnull(designid, usermain)) as 설계담당, + dbo.getUserName(isnull(epanelid, userhw2)) as 전장담당, + dbo.getUserName(isnull(softwareid, usersub)) as 프로그램담당, + crdue as 예산만기일, cramount as 예산,jasmin as 웹관리번호 + FROM Projects + WHERE gcode = @gcode + AND status = @status + AND ISNULL(isdel, 0) = 0"; + + // 사용자 필터 적용 + if (userFilter == "my" && !string.IsNullOrEmpty(currentUserName)) + { + sql += @" AND ( + dbo.getUserName(ISNULL(championid, userManager)) LIKE @userName + OR dbo.getUserName(ISNULL(designid, usermain)) LIKE @userName + OR dbo.getUserName(ISNULL(epanelid, userhw2)) LIKE @userName + OR dbo.getUserName(ISNULL(softwareid, usersub)) LIKE @userName + )"; + } + + sql += " ORDER BY wdate DESC"; + + var parameters = new + { + gcode = gcode, + status = status, + userName = userFilter == "my" ? "%" + currentUserName + "%" : "" + }; + + var projects = DBM.Query(sql, parameters); + + return CreateJsonResponse(new + { + Success = true, + Data = projects, + CurrentUser = currentUserName + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트 목록을 가져오는 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpGet] + public HttpResponseMessage GetProject(int id) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (id <= 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "유효하지 않은 프로젝트 ID입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + + var sql = @" + SELECT idx, status as 상태,asset as 자산번호, model as 장비모델, serial as 시리얼번호, Priority as 우선순위, +ReqSite as 요청국가, ReqPlant as 요청공장, ReqLine as 요청라인, ReqPackage as 요청부서패키지, +reqstaff as 요청자, process as 프로젝트공정, sdate as 시작일,edate as 완료일,ddate as 만료일, odate as 출고일, name as 프로젝트명, + dbo.getUserName( isnull(championid, userManager) ) as 프로젝트관리자, + dbo.getUserName (isnull(designid, usermain)) as 설계담당, + dbo.getUserName(isnull(epanelid, userhw2)) as 전장담당, + dbo.getUserName(isnull(softwareid, usersub)) as 프로그램담당, + crdue as 예산만기일, cramount as 예산,jasmin as 웹관리번호 + FROM Projects + WHERE idx = @idx AND gcode = @gcode AND ISNULL(isdel, 0) = 0"; + + var project = DBM.QuerySingleOrDefault(sql, new { idx = id, gcode = gcode }); + + if (project == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트를 찾을 수 없습니다." + }); + } + + return CreateJsonResponse(new + { + Success = true, + Data = project + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트 조회 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpPost] + public HttpResponseMessage CreateProject([FromBody] ProjectModel project) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (string.IsNullOrWhiteSpace(project.프로젝트명)) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트명을 입력해주세요." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string uid = FCOMMON.info.Login.no; + + var sql = @" + INSERT INTO Projects (gcode, process, sdate, name, edate, ddate, odate, userManager, status, memo, wdate) + VALUES (@gcode, @process, @sdate, @name, @edate, @ddate, @odate, @userManager, @status, @memo, GETDATE())"; + + var parameters = new + { + gcode = gcode, + process = project.프로젝트공정 ?? "", + sdate = project.시작일, + name = project.프로젝트명, + edate = project.완료일, + ddate = project.만료일, + odate = project.출고일, + userManager = project.프로젝트관리자 ?? "", + status = project.상태 ?? "진행", + memo = project.memo ?? "" + }; + + DBM.Execute(sql, parameters); + + return CreateJsonResponse(new + { + Success = true, + Message = "프로젝트가 추가되었습니다." + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트 추가 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpPut] + public HttpResponseMessage UpdateProject([FromBody] ProjectModel project) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (project.idx <= 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "유효하지 않은 프로젝트 ID입니다." + }); + } + + if (string.IsNullOrWhiteSpace(project.프로젝트명)) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트명을 입력해주세요." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + + // 먼저 프로젝트가 존재하는지 확인 + var checkSql = "SELECT COUNT(*) FROM Projects WHERE idx = @idx AND gcode = @gcode AND ISNULL(isdel, 0) = 0"; + var count = DBM.QuerySingle(checkSql, new { idx = project.idx, gcode = gcode }); + + if (count == 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "수정할 프로젝트를 찾을 수 없습니다." + }); + } + + var sql = @" + UPDATE Projects + SET process = @process, sdate = @sdate, name = @name, edate = @edate, + ddate = @ddate, odate = @odate, userManager = @userManager, + status = @status, memo = @memo + WHERE idx = @idx AND gcode = @gcode"; + + var parameters = new + { + idx = project.idx, + gcode = gcode, + process = project.프로젝트공정 ?? "", + sdate = project.시작일, + name = project.프로젝트명, + edate = project.완료일, + ddate = project.만료일, + odate = project.출고일, + userManager = project.프로젝트관리자 ?? "", + status = project.상태 ?? "진행", + memo = project.memo ?? "" + }; + + DBM.Execute(sql, parameters); + + return CreateJsonResponse(new + { + Success = true, + Message = "프로젝트가 수정되었습니다." + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트 수정 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpDelete] + public HttpResponseMessage DeleteProject(int id) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (id <= 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "유효하지 않은 프로젝트 ID입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + + // 먼저 프로젝트가 존재하는지 확인 + var checkSql = "SELECT COUNT(*) FROM Projects WHERE idx = @idx AND gcode = @gcode AND ISNULL(isdel, 0) = 0"; + var count = DBM.QuerySingle(checkSql, new { idx = id, gcode = gcode }); + + if (count == 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "삭제할 프로젝트를 찾을 수 없습니다." + }); + } + + var sql = "UPDATE Projects SET isdel = 1 WHERE idx = @idx AND gcode = @gcode"; + DBM.Execute(sql, new { idx = id, gcode = gcode }); + + return CreateJsonResponse(new + { + Success = true, + Message = "프로젝트가 삭제되었습니다." + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "프로젝트 삭제 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + private object GetCurrentUser() + { + if (string.IsNullOrEmpty(FCOMMON.info.Login.no)) return null; + else return FCOMMON.info.Login; + } + + private HttpResponseMessage CreateJsonResponse(object data) + { + var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore, + DateFormatString = "yyyy-MM-dd HH:mm:ss" + }); + + return new HttpResponseMessage() + { + Content = new StringContent( + json, + System.Text.Encoding.UTF8, + "application/json") + }; + } + } +} diff --git a/Project/Web/Controllers/PurchaseController.cs b/Project/Web/Controllers/PurchaseController.cs new file mode 100644 index 0000000..7d19919 --- /dev/null +++ b/Project/Web/Controllers/PurchaseController.cs @@ -0,0 +1,215 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; +using System.Windows.Forms; + +namespace Project.Web.Controllers +{ + public class PurchaseController : BaseController + { + + + // PUT api/values/5 + public void Put(int id, [FromBody] string value) + { + } + + // DELETE api/values/5 + public void Delete(int id) + { + } + + [HttpGet] + public string Test() + { + return "test"; + } + + [HttpGet] + public HttpResponseMessage Find() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + if(searchkey.isEmpty()==false && searchkey != "%") + { + if (searchkey.StartsWith("%") == false) searchkey = "%" + searchkey; + if (searchkey.EndsWith("%") == false) searchkey += "%"; + } + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + if (searchkey.isEmpty() == false) + { + var db = new dsMSSQLTableAdapters.vFindSIDTableAdapter();// EEEntitiesMain(); + var rows = db.GetData(searchkey);//.vFindSID.Where(t => t.sid.Contains(searchkey) || t.name.Contains(searchkey) || t.manu.Contains(searchkey) || t.model.Contains(searchkey)); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + tbody.AppendLine($"{item.Location}"); + tbody.AppendLine($"{item.sid}"); + tbody.AppendLine($"{item.name}"); + tbody.AppendLine($"{item.model}"); + + if (item.IspriceNull()) + tbody.AppendLine($"--"); + else + { + var price = (double)item.price / 1000.0; + + tbody.AppendLine($"{price.ToString("N0")}"); + } + + + tbody.AppendLine($"{item.manu}"); + tbody.AppendLine($"{item.supply}"); + + if (item.remark.Length > 10) + tbody.AppendLine($"{item.remark.Substring(0, 10)}..."); + else + tbody.AppendLine($"{item.remark}"); + tbody.AppendLine(""); + } + } + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("1"); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + + var gets = Request.GetQueryNameValuePairs();// GetParameters(data); + + + var key_search = gets.Where(t => t.Key == "search").FirstOrDefault(); + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var searchkey = string.Empty; + if (key_search.Key != null && key_search.Value.isEmpty() == false) searchkey = key_search.Value.Trim(); + + var tbody = new System.Text.StringBuilder(); + + //테이블데이터생성 + var itemcnt = 0; + //if (searchkey.isEmpty() == false) + //{ + var db = new dsMSSQLTableAdapters.vPurchaseTableAdapter();// EEEntitiesPurchase(); + var sd = DateTime.Now.ToString("yyyy-MM-01"); + var rows = db.GetAfter(FCOMMON.info.Login.gcode, sd);// .vPurchase.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(sd) >= 0).OrderByDescending(t => t.pdate); + itemcnt = rows.Count(); + foreach (var item in rows) + { + tbody.AppendLine(""); + tbody.AppendLine($"{item.pdate.Substring(5)}"); + + if (item.state == "---") tbody.AppendLine($"{item.state}"); + else if (item.state == "Received") tbody.AppendLine($"{item.state}"); + else tbody.AppendLine($"{item.state}"); + + tbody.AppendLine($"{item.name}"); + tbody.AppendLine($"{item.sid}"); + tbody.AppendLine($"{item.pumname}"); + + if (item.pumscale.Length > 10) tbody.AppendLine($"{item.pumscale.Substring(0, 10)}..."); + else tbody.AppendLine($"{item.pumscale}"); + + tbody.AppendLine($"{item.pumqty}"); + tbody.AppendLine($"{item.pumprice}"); + tbody.AppendLine($"{item.pumamt}"); + tbody.AppendLine($"{item.supply}"); + if (item.project != null && item.project.Length > 10) tbody.AppendLine($"{item.project.Substring(0, 10)}..."); + else tbody.AppendLine($"{item.project}"); + + if (item.bigo.Length > 10) tbody.AppendLine($"{item.bigo.Substring(0, 10)}..."); + else tbody.AppendLine($"{item.bigo}"); + tbody.AppendLine(""); + } + //} + + //아잍쳄이 없는경우 + if (itemcnt == 0) + { + tbody.AppendLine(""); + tbody.AppendLine("1"); + tbody.AppendLine("자료가 없습니다"); + tbody.AppendLine(""); + } + + + var contents = result.Content.Replace("{search}", searchkey); + contents = contents.Replace("{tabledata}", tbody.ToString()); + contents = contents.Replace("{cnt}", itemcnt.ToString()); + + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/ReactController.cs b/Project/Web/Controllers/ReactController.cs new file mode 100644 index 0000000..1a288e3 --- /dev/null +++ b/Project/Web/Controllers/ReactController.cs @@ -0,0 +1,358 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class ReactController : ApiController + { + private string GetWwwRootPath() + { + // 실행 파일 기준으로 wwwroot 경로 찾기 + var baseDir = AppDomain.CurrentDomain.BaseDirectory; + var wwwrootPath = Path.Combine(baseDir, "Web", "wwwroot"); + + // 디버그 모드에서는 소스 경로 사용 + if (!Directory.Exists(wwwrootPath)) + { + wwwrootPath = Path.Combine(Directory.GetCurrentDirectory(), "Web", "wwwroot"); + } + + // 여전히 찾지 못하면 프로젝트 루트에서 찾기 + if (!Directory.Exists(wwwrootPath)) + { + var projectRoot = Directory.GetCurrentDirectory(); + while (projectRoot != null && !Directory.Exists(Path.Combine(projectRoot, "Web", "wwwroot"))) + { + projectRoot = Directory.GetParent(projectRoot)?.FullName; + } + if (projectRoot != null) + { + wwwrootPath = Path.Combine(projectRoot, "Web", "wwwroot"); + } + } + + return wwwrootPath; + } + + [HttpGet] + [Route("react/test")] + public HttpResponseMessage Test() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-test.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React test file not found. Searched path: {filePath}. WWWRoot: {wwwrootPath}. Current Dir: {Directory.GetCurrentDirectory()}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React test page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/jsx-test")] + public HttpResponseMessage JsxTest() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-jsx-test.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, "React JSX test file not found"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React JSX test page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/component/{filename}")] + public HttpResponseMessage Component(string filename) + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react", $"{filename}.jsx"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, $"React component {filename} not found at {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/javascript"); + + // CORS 헤더 추가 + response.Headers.Add("Access-Control-Allow-Origin", "*"); + response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); + response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React component {filename}: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/login")] + public HttpResponseMessage Login() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-login.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React login page not found. Searched path: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React login page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/dashboard")] + public HttpResponseMessage Dashboard() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-dashboard.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React dashboard page not found. Searched path: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React dashboard page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/common")] + public HttpResponseMessage Common() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-common.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React common page not found: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React common page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/jobreport")] + public HttpResponseMessage JobReport() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-jobreport.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React jobreport page not found: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React jobreport page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/kuntae")] + public HttpResponseMessage Kuntae() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-kuntae.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React kuntae page not found: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React kuntae page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/todo")] + public HttpResponseMessage Todo() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-todo.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React todo page not found: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React todo page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/project")] + public HttpResponseMessage Project() + { + try + { + var wwwrootPath = GetWwwRootPath(); + var filePath = Path.Combine(wwwrootPath, "react-project.html"); + + if (!File.Exists(filePath)) + { + return Request.CreateErrorResponse(HttpStatusCode.NotFound, + $"React project page not found: {filePath}"); + } + + var content = File.ReadAllText(filePath, Encoding.UTF8); + var response = Request.CreateResponse(HttpStatusCode.OK); + response.Content = new StringContent(content, Encoding.UTF8, "text/html"); + + return response; + } + catch (Exception ex) + { + return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, + $"Error serving React project page: {ex.Message}"); + } + } + + [HttpGet] + [Route("react/status")] + public IHttpActionResult Status() + { + return Ok(new + { + status = "React Controller Active", + timestamp = DateTime.Now, + routes = new[] + { + "/react/test - React 기본 테스트 페이지", + "/react/jsx-test - React JSX 모듈화 테스트 페이지", + "/react/login - React 로그인 페이지", + "/react/dashboard - React 대시보드 페이지", + "/react/common - React 공용코드 페이지", + "/react/jobreport - React 업무일지 페이지", + "/react/kuntae - React 근태관리 페이지", + "/react/todo - React 할일관리 페이지", + "/react/project - React 프로젝트 페이지", + "/react/component/{filename} - JSX 컴포넌트 파일 서빙", + "/react/status - 이 상태 페이지" + } + }); + } + } +} \ No newline at end of file diff --git a/Project/Web/Controllers/ResourceController.cs b/Project/Web/Controllers/ResourceController.cs new file mode 100644 index 0000000..8767776 --- /dev/null +++ b/Project/Web/Controllers/ResourceController.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class ResourceController : BaseController + { + //[HttpGet] + //public HttpResponseMessage Index() + //{ + // //로그인이 되어있지않다면 로그인을 가져온다 + // MethodResult result; + // result = View(true); + + // var model = GetGlobalModel(); + // var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + // //기본값을 찾아서 없애줘야한다 + // var contents = result.Content; + + // //공용값 적용 + // ApplyCommonValue(ref contents); + + // //최종문자 적용 + // result.Content = contents; + + // var resp = new HttpResponseMessage() + // { + // Content = new StringContent( + // result.Content, + // System.Text.Encoding.UTF8, + // "text/html") + // }; + + // return resp; + //} + + [HttpGet] + public HttpResponseMessage file() + { + var config = RequestContext.Configuration; + var routeData = config.Routes.GetRouteData(Request).Values.ToList(); + + var p_resource = routeData.Where(t => t.Key == "resource").FirstOrDefault(); + var p_path = routeData.Where(t => t.Key == "path").FirstOrDefault(); + var p_ext = routeData.Where(t => t.Key == "ext").FirstOrDefault(); + var p_subdir = routeData.Where(t => t.Key == "subdir").FirstOrDefault(); + + var v_resource = string.Empty; + var v_path = string.Empty; + var v_ext = string.Empty; + var v_subdir = string.Empty; + + if (p_resource.Key == "resource") v_resource = p_resource.Value.ToString(); + if (p_path.Key == "path") v_path = p_path.Value.ToString(); + if (p_ext.Key == "ext") v_ext = p_ext.Value.ToString(); + if (p_subdir.Key == "subdir") v_subdir = p_subdir.Value.ToString(); + + //var file_ext = routeData[0].Value.ToString(); + //var name_resource = routeData[1].Value.ToString() + "." + file_ext; + //var name_action = routeData[3].Value.ToString(); + + Boolean isBinary = true; + + + string content_type = "text/plain"; + + if (v_ext == "json") + { + isBinary = false; + content_type = "application/json"; + } + else if(v_ext == "vue") + { + isBinary = false; + content_type = "application/js"; + } + else if (v_ext == "js") + { + isBinary = false; + content_type = "application/js"; + } + else if (v_ext == "css") + { + isBinary = false; + content_type = "text/css"; + } + else if (v_ext == "csv") + { + isBinary = false; + content_type = "text/csv"; + } + else if (v_ext == "ico") + { + isBinary = true; + content_type = "image/x-icon"; + } + else if(v_ext == "ttf" || v_ext == "otf") + { + isBinary = true; + content_type = "application/octet-stream"; + } + + HttpContent resultContent = null; + + if (v_resource.isEmpty() && v_ext.isEmpty()) + { + v_resource = "index"; + v_ext = "html"; + isBinary = false; + content_type = "text/html"; + } + + + + var file = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "View", v_path, v_subdir, v_resource + "." + v_ext); + + if (isBinary) + { + + if (System.IO.File.Exists(file)) + { + var buffer = System.IO.File.ReadAllBytes(file); + resultContent = new ByteArrayContent(buffer); + Console.WriteLine(">>File(B) : " + file); + } + else Console.WriteLine("no resouoir file " + file); + + } + else + { + if (System.IO.File.Exists(file)) + { + + var buffer = System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8); + resultContent = new StringContent(buffer, System.Text.Encoding.UTF8, content_type); + Console.WriteLine(">>File(S) : " + file); + } + else Console.WriteLine("no resouoir file " + file); + } + + + return new HttpResponseMessage() + { + Content = resultContent + }; + + } + } +} diff --git a/Project/Web/Controllers/ResultController.cs b/Project/Web/Controllers/ResultController.cs new file mode 100644 index 0000000..bbdc2a5 --- /dev/null +++ b/Project/Web/Controllers/ResultController.cs @@ -0,0 +1,64 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class ResultController : BaseController + { + [HttpPost] + public void Index([FromBody]string value) + { + + } + + // PUT api/values/5 + public void Put(int id, [FromBody]string value) + { + } + + // DELETE api/values/5 + public void Delete(int id) + { + } + + [HttpGet] + public string Test() + { + return "test"; + } + + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var contents = result.Content; + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/SettingController.cs b/Project/Web/Controllers/SettingController.cs new file mode 100644 index 0000000..021616d --- /dev/null +++ b/Project/Web/Controllers/SettingController.cs @@ -0,0 +1,63 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Web.Http; + +namespace Project.Web.Controllers +{ + public class SettingController : BaseController + { + [HttpPost] + public void Index([FromBody]string value) + { + + } + + // PUT api/values/5 + public void Put(int id, [FromBody]string value) + { + } + + // DELETE api/values/5 + public void Delete(int id) + { + } + + [HttpGet] + public string Test() + { + return "test"; + } + + [HttpGet] + public HttpResponseMessage Index() + { + //로그인이 되어있지않다면 로그인을 가져온다 + MethodResult result; + result = View(); + + var model = GetGlobalModel(); + var getParams = Request.GetQueryNameValuePairs();// GetParameters(data); + + //기본값을 찾아서 없애줘야한다 + var contents = result.Content; + + //공용값 적용 + ApplyCommonValue(ref contents); + + //최종문자 적용 + result.Content = contents; + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + result.Content, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + } +} diff --git a/Project/Web/Controllers/TodoController.cs b/Project/Web/Controllers/TodoController.cs new file mode 100644 index 0000000..b56161e --- /dev/null +++ b/Project/Web/Controllers/TodoController.cs @@ -0,0 +1,439 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Web.Http; +using Newtonsoft.Json; +using FCOMMON; +using Project.Web.Model; + +namespace Project.Web.Controllers +{ + public class TodoController : BaseController + { + [HttpGet] + public HttpResponseMessage Index() + { + var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "wwwroot", "Todo", "index.html"); + var contents = string.Empty; + + if (System.IO.File.Exists(filePath)) + { + contents = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + else + { + contents = "

404 - File Not Found

The requested file was not found: " + filePath + "

"; + } + + ApplyCommonValue(ref contents); + + var resp = new HttpResponseMessage() + { + Content = new StringContent( + contents, + System.Text.Encoding.UTF8, + "text/html") + }; + + return resp; + } + + [HttpGet] + public HttpResponseMessage GetTodos() + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string uid = FCOMMON.info.Login.no; + + var sql = @"SELECT * FROM EETGW_Todo WHERE gcode = @gcode AND uid = @uid + ORDER BY + CASE + WHEN ISNULL(status,'0') = '1' THEN 1 -- 진행 + WHEN ISNULL(status,'0') = '0' THEN 2 -- 대기 + WHEN ISNULL(status,'0') = '3' THEN 3 -- 보류 + WHEN ISNULL(status,'0') = '5' THEN 4 -- 완료 + WHEN ISNULL(status,'0') = '2' THEN 5 -- 취소 + ELSE 6 + END, flag DESC, + ISNULL(seqno, 0) DESC, + expire ASC"; + var todos = DBM.Query(sql, new { gcode = gcode, uid = uid }); + + return CreateJsonResponse(new + { + Success = true, + Data = todos + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "Todo 목록을 가져오는 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpGet] + public HttpResponseMessage GetUrgentTodos() + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string uid = FCOMMON.info.Login.no; + + var sql = @" + SELECT * FROM EETGW_Todo + WHERE gcode = @gcode AND uid = @uid + and isnull(status,'0') not in ('2','3','5') + ORDER BY flag DESC, seqno DESC, expire ASC, wdate ASC"; + + var todos = DBM.Query(sql, new { gcode = gcode, uid = uid }); + + return CreateJsonResponse(new + { + Success = true, + Data = todos + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "급한 Todo 목록을 가져오는 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpPost] + public HttpResponseMessage CreateTodo([FromBody] TodoModel todo) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (string.IsNullOrEmpty(todo.remark)) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일 내용은 필수입니다." + }); + } + + todo.gcode = FCOMMON.info.Login.gcode; + todo.uid = FCOMMON.info.Login.no; + todo.wuid = FCOMMON.info.Login.no; + todo.wdate = DateTime.Now; + + if (todo.seqno == null) todo.seqno = 0; + if (todo.flag == null) todo.flag = false; + if (todo.status == '\0') todo.status = '0'; + + // 새로 생성할 때 완료 상태면 완료일 설정 + DateTime? okdateValue = null; + if (todo.status == '5') + { + okdateValue = DateTime.Now; + } + + var sql = @" + INSERT INTO EETGW_Todo (gcode, uid, title, remark, flag, expire, seqno, request, status, okdate, wuid, wdate) + VALUES (@gcode, @uid, @title, @remark, @flag, @expire, @seqno, @request, @status, @okdate, @wuid, @wdate); + SELECT SCOPE_IDENTITY();"; + + var newId = DBM.QuerySingle(sql, new + { + gcode = todo.gcode, + uid = todo.uid, + title = todo.title, + remark = todo.remark, + flag = todo.flag, + expire = todo.expire, + seqno = todo.seqno, + request = todo.request, + status = todo.status, + okdate = okdateValue, + wuid = todo.wuid, + wdate = todo.wdate + }); + + return CreateJsonResponse(new + { + Success = true, + Message = "할일이 추가되었습니다.", + Data = new { idx = newId } + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일 추가 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpPut] + public HttpResponseMessage UpdateTodo([FromBody] TodoModel todo) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (todo.idx <= 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "유효하지 않은 Todo ID입니다." + }); + } + + if (string.IsNullOrEmpty(todo.remark)) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일 내용은 필수입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string uid = FCOMMON.info.Login.no; + + // 상태가 완료('5')로 변경되고 아직 완료일이 설정되지 않은 경우 완료일 설정 + DateTime? okdateValue = null; + if (todo.status == '5') + { + // 기존 완료일이 있는지 확인 + var existingTodo = DBM.QuerySingleOrDefault( + "SELECT okdate FROM EETGW_Todo WHERE idx = @idx AND gcode = @gcode AND uid = @uid", + new { idx = todo.idx, gcode = gcode, uid = uid }); + + if (existingTodo?.okdate == null) + { + okdateValue = DateTime.Now; + } + } + + var sql = @" + UPDATE EETGW_Todo + SET title = @title, remark = @remark, flag = @flag, expire = @expire, seqno = @seqno, request = @request, status = @status, okdate = @okdate + WHERE idx = @idx AND gcode = @gcode AND uid = @uid"; + + var affectedRows = DBM.Execute(sql, new + { + title = todo.title, + remark = todo.remark, + flag = todo.flag ?? false, + expire = todo.expire, + seqno = todo.seqno ?? 0, + request = todo.request, + status = todo.status == '\0' ? '0' : todo.status, + okdate = okdateValue, + idx = todo.idx, + gcode = gcode, + uid = uid + }); + + if (affectedRows == 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "수정할 할일을 찾을 수 없습니다." + }); + } + + return CreateJsonResponse(new + { + Success = true, + Message = "할일이 수정되었습니다." + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일 수정 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpDelete] + public HttpResponseMessage DeleteTodo(int id) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (id <= 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "유효하지 않은 Todo ID입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string uid = FCOMMON.info.Login.no; + + var sql = "DELETE FROM EETGW_Todo WHERE idx = @idx AND gcode = @gcode AND uid = @uid"; + var affectedRows = DBM.Execute(sql, new { idx = id, gcode = gcode, uid = uid }); + + if (affectedRows == 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "삭제할 할일을 찾을 수 없습니다." + }); + } + + return CreateJsonResponse(new + { + Success = true, + Message = "할일이 삭제되었습니다." + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일 삭제 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + [HttpGet] + public HttpResponseMessage GetTodo(int id) + { + try + { + var currentUser = GetCurrentUser(); + if (currentUser == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "로그인되지 않은 상태입니다." + }); + } + + if (id <= 0) + { + return CreateJsonResponse(new + { + Success = false, + Message = "유효하지 않은 Todo ID입니다." + }); + } + + string gcode = FCOMMON.info.Login.gcode; + string uid = FCOMMON.info.Login.no; + + var sql = "SELECT * FROM EETGW_Todo WHERE idx = @idx AND gcode = @gcode AND uid = @uid"; + var todo = DBM.QuerySingleOrDefault(sql, new { idx = id, gcode = gcode, uid = uid }); + + if (todo == null) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일을 찾을 수 없습니다." + }); + } + + return CreateJsonResponse(new + { + Success = true, + Data = todo + }); + } + catch (Exception ex) + { + return CreateJsonResponse(new + { + Success = false, + Message = "할일 조회 중 오류가 발생했습니다: " + ex.Message + }); + } + } + + private object GetCurrentUser() + { + if (string.IsNullOrEmpty(FCOMMON.info.Login.no)) return null; + else return FCOMMON.info.Login; + } + + private HttpResponseMessage CreateJsonResponse(object data) + { + var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore, + DateFormatString = "yyyy-MM-dd HH:mm:ss" + }); + + return new HttpResponseMessage() + { + Content = new StringContent( + json, + System.Text.Encoding.UTF8, + "application/json") + }; + } + } +} diff --git a/Project/Web/wwwroot/common/navigation.html b/Project/Web/wwwroot/common/navigation.html new file mode 100644 index 0000000..f40c114 --- /dev/null +++ b/Project/Web/wwwroot/common/navigation.html @@ -0,0 +1,158 @@ + + \ No newline at end of file diff --git a/Project/Web/wwwroot/lib/css/tailwind.min.css b/Project/Web/wwwroot/lib/css/tailwind.min.css new file mode 100644 index 0000000..99a21f2 --- /dev/null +++ b/Project/Web/wwwroot/lib/css/tailwind.min.css @@ -0,0 +1,490 @@ +/* Tailwind CSS v3.3.0 - Custom Build for GroupWare React Components */ + +/*! tailwindcss v3.3.0 | MIT License | https://tailwindcss.com */ + +*,::after,::before{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}::after,::before{--tw-content:''}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace, SFMono-Regular, "Roboto Mono", "Courier New", monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none} + +/* Base Variables */ +:root { + --color-white: 255 255 255; + --color-black: 0 0 0; + --color-gray-50: 249 250 251; + --color-gray-100: 243 244 246; + --color-gray-200: 229 231 235; + --color-gray-300: 209 213 219; + --color-gray-400: 156 163 175; + --color-gray-500: 107 114 128; + --color-gray-600: 75 85 99; + --color-gray-700: 55 65 81; + --color-gray-800: 31 41 55; + --color-gray-900: 17 24 39; + --color-blue-50: 239 246 255; + --color-blue-100: 219 234 254; + --color-blue-200: 191 219 254; + --color-blue-300: 147 197 253; + --color-blue-400: 96 165 250; + --color-blue-500: 59 130 246; + --color-blue-600: 37 99 235; + --color-blue-700: 29 78 216; + --color-blue-800: 30 64 175; + --color-blue-900: 30 58 138; + --color-indigo-50: 238 242 255; + --color-indigo-100: 224 231 255; + --color-indigo-200: 199 210 254; + --color-indigo-300: 165 180 252; + --color-indigo-400: 129 140 248; + --color-indigo-500: 99 102 241; + --color-indigo-600: 79 70 229; + --color-indigo-700: 67 56 202; + --color-indigo-800: 55 48 163; + --color-indigo-900: 49 46 129; + --color-purple-50: 245 243 255; + --color-purple-100: 237 233 254; + --color-purple-200: 221 214 254; + --color-purple-300: 196 181 253; + --color-purple-400: 167 139 250; + --color-purple-500: 139 92 246; + --color-purple-600: 124 58 237; + --color-purple-700: 109 40 217; + --color-purple-800: 91 33 182; + --color-purple-900: 76 29 149; + --color-green-50: 240 253 244; + --color-green-100: 220 252 231; + --color-green-200: 187 247 208; + --color-green-300: 134 239 172; + --color-green-400: 74 222 128; + --color-green-500: 34 197 94; + --color-green-600: 22 163 74; + --color-green-700: 21 128 61; + --color-green-800: 22 101 52; + --color-green-900: 20 83 45; + --color-yellow-50: 255 251 235; + --color-yellow-100: 254 243 199; + --color-yellow-200: 253 230 138; + --color-yellow-300: 252 211 77; + --color-yellow-400: 251 191 36; + --color-yellow-500: 245 158 11; + --color-yellow-600: 217 119 6; + --color-yellow-700: 180 83 9; + --color-yellow-800: 146 64 14; + --color-yellow-900: 120 53 15; + --color-red-50: 254 242 242; + --color-red-100: 254 226 226; + --color-red-200: 252 165 165; + --color-red-300: 248 113 113; + --color-red-400: 239 68 68; + --color-red-500: 239 68 68; + --color-red-600: 220 38 38; + --color-red-700: 185 28 28; + --color-red-800: 153 27 27; + --color-red-900: 127 29 29; +} + +/* Utility Classes - Core */ +.container { width: 100%; } +@media (min-width: 640px) { .container { max-width: 640px; } } +@media (min-width: 768px) { .container { max-width: 768px; } } +@media (min-width: 1024px) { .container { max-width: 1024px; } } +@media (min-width: 1280px) { .container { max-width: 1280px; } } +@media (min-width: 1536px) { .container { max-width: 1536px; } } + +.mx-auto { margin-left: auto; margin-right: auto; } +.px-4 { padding-left: 1rem; padding-right: 1rem; } +.py-8 { padding-top: 2rem; padding-bottom: 2rem; } + +/* Positioning */ +.fixed { position: fixed; } +.relative { position: relative; } +.absolute { position: absolute; } +.inset-0 { inset: 0px; } +.top-4 { top: 1rem; } +.right-4 { right: 1rem; } +.top-full { top: 100%; } +.z-10 { z-index: 10; } +.z-40 { z-index: 40; } +.z-50 { z-index: 50; } + +/* Display */ +.block { display: block; } +.inline-block { display: inline-block; } +.inline { display: inline; } +.flex { display: flex; } +.inline-flex { display: inline-flex; } +.table { display: table; } +.table-cell { display: table-cell; } +.grid { display: grid; } +.hidden { display: none; } + +/* Flexbox */ +.flex-1 { flex: 1 1 0%; } +.flex-wrap { flex-wrap: wrap; } +.items-center { align-items: center; } +.items-end { align-items: flex-end; } +.justify-center { justify-content: center; } +.justify-between { justify-content: space-between; } +.justify-end { justify-content: flex-end; } + +/* Grid */ +.grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } +.grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } +@media (min-width: 768px) { + .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .md\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .md\:grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } +} +@media (min-width: 1024px) { + .lg\:col-span-2 { grid-column: span 2 / span 2; } + .lg\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +} +@media (min-width: 640px) { + .sm\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +} + +/* Spacing */ +.gap-2 { gap: 0.5rem; } +.gap-3 { gap: 0.75rem; } +.gap-4 { gap: 1rem; } +.gap-6 { gap: 1.5rem; } +.space-x-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.25rem * var(--tw-space-x-reverse)); margin-left: calc(0.25rem * calc(1 - var(--tw-space-x-reverse))); } +.space-x-2 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.5rem * var(--tw-space-x-reverse)); margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse))); } +.space-x-3 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.75rem * var(--tw-space-x-reverse)); margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse))); } +.space-x-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(1rem * var(--tw-space-x-reverse)); margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse))); } +.space-x-8 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(2rem * var(--tw-space-x-reverse)); margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse))); } +.space-y-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); } +.space-y-3 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.75rem * var(--tw-space-y-reverse)); } +.space-y-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1rem * var(--tw-space-y-reverse)); } + +/* Margins */ +.m-2 { margin: 0.5rem; } +.mb-1 { margin-bottom: 0.25rem; } +.mb-2 { margin-bottom: 0.5rem; } +.mb-4 { margin-bottom: 1rem; } +.mb-6 { margin-bottom: 1.5rem; } +.mr-1 { margin-right: 0.25rem; } +.mr-2 { margin-right: 0.5rem; } +.mr-3 { margin-right: 0.75rem; } +.ml-2 { margin-left: 0.5rem; } +.ml-4 { margin-left: 1rem; } +.ml-auto { margin-left: auto; } +.mt-6 { margin-top: 1.5rem; } + +/* Padding */ +.p-1 { padding: 0.25rem; } +.p-3 { padding: 0.75rem; } +.p-4 { padding: 1rem; } +.p-6 { padding: 1.5rem; } +.p-8 { padding: 2rem; } +.px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } +.px-3 { padding-left: 0.75rem; padding-right: 0.75rem; } +.px-4 { padding-left: 1rem; padding-right: 1rem; } +.px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } +.py-0 { padding-top: 0px; padding-bottom: 0px; } +.py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; } +.py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } +.py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } +.py-4 { padding-top: 1rem; padding-bottom: 1rem; } +.pt-0 { padding-top: 0px; } +.pb-0 { padding-bottom: 0px; } + +/* Size */ +.w-4 { width: 1rem; } +.w-5 { width: 1.25rem; } +.w-6 { width: 1.5rem; } +.w-8 { width: 2rem; } +.w-12 { width: 3rem; } +.w-16 { width: 4rem; } +.w-20 { width: 5rem; } +.w-24 { width: 6rem; } +.w-28 { width: 7rem; } +.w-32 { width: 8rem; } +.w-40 { width: 10rem; } +.w-48 { width: 12rem; } +.w-full { width: 100%; } +.min-w-32 { min-width: 8rem; } +.min-w-48 { min-width: 12rem; } +.max-w-xs { max-width: 20rem; } +.max-w-md { max-width: 28rem; } +.max-w-2xl { max-width: 42rem; } +.h-4 { height: 1rem; } +.h-5 { height: 1.25rem; } +.h-6 { height: 1.5rem; } +.h-8 { height: 2rem; } +.h-10 { height: 2.5rem; } +.h-16 { height: 4rem; } +.min-h-screen { min-height: 100vh; } +.max-h-40 { max-height: 10rem; } + +/* Background */ +.bg-white { background-color: rgb(255 255 255); } +.bg-black { background-color: rgb(0 0 0); } +.bg-gray-500 { background-color: rgb(107 114 128); } +.bg-gray-800 { background-color: rgb(31 41 55); } +.bg-blue-300 { background-color: rgb(147 197 253); } +.bg-blue-500 { background-color: rgb(59 130 246); } +.bg-green-300 { background-color: rgb(134 239 172); } +.bg-green-500 { background-color: rgb(34 197 94); } +.bg-yellow-300 { background-color: rgb(252 211 77); } +.bg-yellow-500 { background-color: rgb(245 158 11); } +.bg-red-300 { background-color: rgb(248 113 113); } +.bg-red-400 { background-color: rgb(239 68 68); } +.bg-red-500 { background-color: rgb(239 68 68); } +.bg-purple-500 { background-color: rgb(139 92 246); } +.bg-orange-500 { background-color: rgb(249 115 22); } + +/* Background with opacity */ +.bg-white\/5 { background-color: rgb(255 255 255 / 0.05); } +.bg-white\/10 { background-color: rgb(255 255 255 / 0.1); } +.bg-white\/20 { background-color: rgb(255 255 255 / 0.2); } +.bg-white\/30 { background-color: rgb(255 255 255 / 0.3); } +.bg-gray-500\/20 { background-color: rgb(107 114 128 / 0.2); } +.bg-blue-500\/20 { background-color: rgb(59 130 246 / 0.2); } +.bg-green-500\/20 { background-color: rgb(34 197 94 / 0.2); } +.bg-yellow-500\/20 { background-color: rgb(245 158 11 / 0.2); } +.bg-red-500\/20 { background-color: rgb(239 68 68 / 0.2); } +.bg-purple-500\/20 { background-color: rgb(139 92 246 / 0.2); } +.bg-orange-500\/90 { background-color: rgb(249 115 22 / 0.9); } +.bg-blue-500\/90 { background-color: rgb(59 130 246 / 0.9); } +.bg-green-500\/90 { background-color: rgb(34 197 94 / 0.9); } +.bg-red-500\/90 { background-color: rgb(239 68 68 / 0.9); } + +/* Gradient backgrounds */ +.bg-gradient-to-br { background-image: linear-gradient(to bottom right, var(--tw-gradient-stops)); } +.from-blue-900 { --tw-gradient-from: rgb(30 58 138); --tw-gradient-to: rgb(30 58 138 / 0); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } +.via-purple-900 { --tw-gradient-to: rgb(76 29 149 / 0); --tw-gradient-stops: var(--tw-gradient-from), rgb(76 29 149), var(--tw-gradient-to); } +.to-indigo-900 { --tw-gradient-to: rgb(49 46 129); } + +/* Text Colors */ +.text-white { color: rgb(255 255 255); } +.text-gray-300 { color: rgb(209 213 219); } +.text-gray-500 { color: rgb(107 114 128); } +.text-blue-300 { color: rgb(147 197 253); } +.text-green-300 { color: rgb(134 239 172); } +.text-yellow-300 { color: rgb(252 211 77); } +.text-red-300 { color: rgb(248 113 113); } +.text-red-400 { color: rgb(239 68 68); } +.text-orange-100 { color: rgb(255 237 213); } +.text-orange-900 { color: rgb(154 52 18); } +.text-primary-200 { color: rgb(147 197 253); } +.text-primary-300 { color: rgb(147 197 253); } +.text-primary-400 { color: rgb(96 165 250); } +.text-success-200 { color: rgb(187 247 208); } +.text-success-300 { color: rgb(134 239 172); } +.text-success-400 { color: rgb(74 222 128); } +.text-warning-300 { color: rgb(252 211 77); } +.text-danger-300 { color: rgb(248 113 113); } +.text-danger-400 { color: rgb(239 68 68); } + +/* Text with opacity */ +.text-white\/50 { color: rgb(255 255 255 / 0.5); } +.text-white\/60 { color: rgb(255 255 255 / 0.6); } +.text-white\/70 { color: rgb(255 255 255 / 0.7); } +.text-white\/80 { color: rgb(255 255 255 / 0.8); } + +/* Typography */ +.text-xs { font-size: 0.75rem; line-height: 1rem; } +.text-sm { font-size: 0.875rem; line-height: 1.25rem; } +.text-base { font-size: 1rem; line-height: 1.5rem; } +.text-lg { font-size: 1.125rem; line-height: 1.75rem; } +.text-xl { font-size: 1.25rem; line-height: 1.75rem; } +.text-2xl { font-size: 1.5rem; line-height: 2rem; } +.font-medium { font-weight: 500; } +.font-semibold { font-weight: 600; } +.font-bold { font-weight: 700; } +.uppercase { text-transform: uppercase; } +.tracking-wider { letter-spacing: 0.05em; } +.text-left { text-align: left; } +.text-center { text-align: center; } +.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.underline { text-decoration-line: underline; } +.whitespace-nowrap { white-space: nowrap; } + +/* Borders */ +.border { border-width: 1px; } +.border-b { border-bottom-width: 1px; } +.border-l-4 { border-left-width: 4px; } +.border-r { border-right-width: 1px; } +.border-t { border-top-width: 1px; } +.border-white\/10 { border-color: rgb(255 255 255 / 0.1); } +.border-white\/20 { border-color: rgb(255 255 255 / 0.2); } +.border-white\/30 { border-color: rgb(255 255 255 / 0.3); } +.border-gray-500\/30 { border-color: rgb(107 114 128 / 0.3); } +.border-orange-700 { border-color: rgb(194 65 12); } +.divide-y > :not([hidden]) ~ :not([hidden]) { --tw-divide-y-reverse: 0; border-top-width: calc(1px * calc(1 - var(--tw-divide-y-reverse))); border-bottom-width: calc(1px * var(--tw-divide-y-reverse)); } +.divide-white\/10 > :not([hidden]) ~ :not([hidden]) { border-color: rgb(255 255 255 / 0.1); } +.divide-white\/20 > :not([hidden]) ~ :not([hidden]) { border-color: rgb(255 255 255 / 0.2); } + +/* Border Radius */ +.rounded { border-radius: 0.25rem; } +.rounded-md { border-radius: 0.375rem; } +.rounded-lg { border-radius: 0.5rem; } +.rounded-2xl { border-radius: 1rem; } +.rounded-full { border-radius: 9999px; } + +/* Shadows */ +.shadow-sm { box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); } +.shadow-lg { box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -2px rgb(0 0 0 / 0.05); } + +/* Overflow */ +.overflow-hidden { overflow: hidden; } +.overflow-x-auto { overflow-x: auto; } +.overflow-y-auto { overflow-y: auto; } + +/* Interactivity */ +.cursor-pointer { cursor: pointer; } +.cursor-not-allowed { cursor: not-allowed; } + +/* Focus */ +.focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } +.focus\:ring-1:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } +.focus\:ring-2:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } +.focus\:ring-white\/50:focus { --tw-ring-color: rgb(255 255 255 / 0.5); } +.focus\:ring-primary-400:focus { --tw-ring-color: rgb(96 165 250); } +.focus\:border-transparent:focus { border-color: transparent; } +.focus\:ring-offset-0:focus { --tw-ring-offset-width: 0px; } + +/* Hover Effects */ +.hover\:bg-white\/10:hover { background-color: rgb(255 255 255 / 0.1); } +.hover\:bg-white\/20:hover { background-color: rgb(255 255 255 / 0.2); } +.hover\:bg-white\/30:hover { background-color: rgb(255 255 255 / 0.3); } +.hover\:bg-primary-600:hover { background-color: rgb(37 99 235); } +.hover\:bg-green-600:hover { background-color: rgb(22 163 74); } +.hover\:bg-red-600:hover { background-color: rgb(220 38 38); } +.hover\:bg-purple-600:hover { background-color: rgb(124 58 237); } +.hover\:text-white:hover { color: rgb(255 255 255); } +.hover\:text-blue-200:hover { color: rgb(191 219 254); } +.hover\:text-blue-300:hover { color: rgb(147 197 253); } +.hover\:text-primary-300:hover { color: rgb(147 197 253); } + +/* Disabled */ +.disabled\:opacity-50:disabled { opacity: 0.5; } +.disabled\:cursor-not-allowed:disabled { cursor: not-allowed; } + +/* Transitions */ +.transition-colors { transition-property: color, background-color, border-color, text-decoration-color, fill, stroke; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } +.transition-all { transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } +.transition-transform { transition-property: transform; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } +.duration-200 { transition-duration: 200ms; } +.duration-300 { transition-duration: 300ms; } + +/* Transforms */ +.transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } +.translate-x-0 { --tw-translate-x: 0px; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } +.rotate-180 { --tw-rotate: 180deg; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } + +/* Animations */ +.animate-spin { animation: spin 1s linear infinite; } +.animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; } +.animate-slide-up { animation: slideUp 0.3s ease-out; } +.animate-fade-in { animation: fadeIn 0.5s ease-in-out; } + +@keyframes spin { + to { transform: rotate(360deg); } +} + +@keyframes pulse { + 50% { opacity: .5; } +} + +@keyframes slideUp { + from { transform: translateY(10px); opacity: 0; } + to { transform: translateY(0); opacity: 1; } +} + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +/* Backdrop Filter */ +.backdrop-blur-sm { backdrop-filter: blur(4px); } + +/* Opacity */ +.opacity-0 { opacity: 0; } +.opacity-50 { opacity: 0.5; } +.opacity-100 { opacity: 1; } + +/* Visibility */ +.invisible { visibility: hidden; } +.visible { visibility: visible; } + +/* Responsive Design Utilities */ +@media (min-width: 640px) { + .sm\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +} + +@media (min-width: 768px) { + .md\:flex { display: flex; } + .md\:hidden { display: none; } + .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .md\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .md\:grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } +} + +@media (min-width: 1024px) { + .lg\:col-span-2 { grid-column: span 2 / span 2; } + .lg\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +} + +/* Custom Tailwind Config Extensions */ +.bg-primary-500 { background-color: rgb(59 130 246); } +.bg-primary-600 { background-color: rgb(37 99 235); } +.bg-success-500 { background-color: rgb(34 197 94); } +.bg-success-600 { background-color: rgb(22 163 74); } +.bg-warning-500 { background-color: rgb(245 158 11); } +.bg-warning-600 { background-color: rgb(217 119 6); } +.bg-danger-500 { background-color: rgb(239 68 68); } +.bg-danger-600 { background-color: rgb(220 38 38); } +.bg-primary-500\/20 { background-color: rgb(59 130 246 / 0.2); } +.bg-primary-500\/30 { background-color: rgb(59 130 246 / 0.3); } +.bg-success-500\/20 { background-color: rgb(34 197 94 / 0.2); } +.bg-success-500\/30 { background-color: rgb(34 197 94 / 0.3); } +.bg-warning-500\/20 { background-color: rgb(245 158 11 / 0.2); } +.bg-warning-500\/30 { background-color: rgb(245 158 11 / 0.3); } +.bg-danger-500\/20 { background-color: rgb(239 68 68 / 0.2); } +.bg-danger-500\/30 { background-color: rgb(239 68 68 / 0.3); } + +/* Custom Utilities for the project */ +.glass-effect { + background: rgba(255, 255, 255, 0.25); + backdrop-filter: blur(10px); + border: 1px solid rgba(255, 255, 255, 0.18); +} + +.card-hover { + transition: all 0.3s ease; +} + +.card-hover:hover { + transform: translateY(-5px); + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); +} + +.custom-scrollbar::-webkit-scrollbar { + width: 8px; +} + +.custom-scrollbar::-webkit-scrollbar-track { + background: rgba(255, 255, 255, 0.1); + border-radius: 8px; +} + +.custom-scrollbar::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.3); + border-radius: 8px; + border: 2px solid rgba(255, 255, 255, 0.1); +} + +.custom-scrollbar::-webkit-scrollbar-thumb:hover { + background: rgba(255, 255, 255, 0.5); +} + +.loading { + border: 3px solid rgba(255, 255, 255, 0.3); + border-radius: 50%; + border-top: 3px solid #fff; + width: 20px; + height: 20px; + animation: spin 1s linear infinite; +} \ No newline at end of file diff --git a/Project/Web/wwwroot/lib/js/babel.min.js b/Project/Web/wwwroot/lib/js/babel.min.js new file mode 100644 index 0000000..a368201 --- /dev/null +++ b/Project/Web/wwwroot/lib/js/babel.min.js @@ -0,0 +1,4 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Babel={})}(this,(function(e){"use strict";var t=Object.freeze({__proto__:null,get _call(){return bO},get _getQueueContexts(){return FO},get _resyncKey(){return kO},get _resyncList(){return CO},get _resyncParent(){return AO},get _resyncRemoved(){return _O},get call(){return hO},get isDenylisted(){return xO},get popContext(){return IO},get pushContext(){return DO},get requeue(){return BO},get requeueComputedKeyAndDecorators(){return MO},get resync(){return PO},get setContext(){return TO},get setKey(){return NO},get setScope(){return SO},get setup(){return OO},get skip(){return jO},get skipKey(){return wO},get stop(){return EO},get visit(){return RO}}),r=Object.freeze({__proto__:null,get DEFAULT_EXTENSIONS(){return aH},get File(){return mM},get buildExternalHelpers(){return GM},get createConfigItem(){return WW},get createConfigItemAsync(){return qW},get createConfigItemSync(){return GW},get getEnv(){return rF},get loadOptions(){return LW},get loadOptionsAsync(){return MW},get loadOptionsSync(){return FW},get loadPartialConfig(){return OW},get loadPartialConfigAsync(){return IW},get loadPartialConfigSync(){return DW},get parse(){return $V},get parseAsync(){return ZV},get parseSync(){return QV},get resolvePlugin(){return tH},get resolvePreset(){return rH},get template(){return cj},get tokTypes(){return tR},get transform(){return UV},get transformAsync(){return GV},get transformFile(){return WV},get transformFileAsync(){return HV},get transformFileSync(){return VV},get transformFromAst(){return zV},get transformFromAstAsync(){return JV},get transformFromAstSync(){return XV},get transformSync(){return qV},get traverse(){return WO},get types(){return Xm},get version(){return eH}});function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,a=Array(t);r=e.length?{done:!0}:{done:!1,value:e[a++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function d(e){return d=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},d(e)}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&y(e,t)}function l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(l=function(){return!!e})()}function u(e,t){if(null==e)return{};var r={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(-1!==t.indexOf(a))continue;r[a]=e[a]}return r}function p(){ +/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ +var e,t,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",n=r.toStringTag||"@@toStringTag";function s(r,a,n,s){var d=a&&a.prototype instanceof i?a:i,c=Object.create(d.prototype);return f(c,"_invoke",function(r,a,n){var s,i,d,c=0,l=n||[],u=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,r){return s=t,i=0,d=e,p.n=r,o}};function f(r,a){for(i=r,d=a,t=0;!u&&c&&!n&&t3?(n=g===a)&&(i=s[4]||3,d=s[5]===e?s[3]:s[5],s[4]=3,s[5]=e):s[0]<=f&&((n=r<2&&fa||a>g)&&(s[4]=r,s[5]=a,p.n=g,i=0))}if(n||r>1)return o;throw u=!0,a}return function(n,l,g){if(c>1)throw TypeError("Generator is already running");for(u&&1===l&&f(l,g),i=l,d=g;(t=i<2?e:d)||!u;){s||(i?i<3?(i>1&&(p.n=-1),f(i,d)):p.n=d:p.v=d);try{if(c=2,s){if(i||(n="next"),t=s[n]){if(!(t=t.call(s,d)))throw TypeError("iterator result is not an object");if(!t.done)return t;d=t.value,i<2&&(i=0)}else 1===i&&(t=s.return)&&t.call(s),i<2&&(d=TypeError("The iterator does not provide a '"+n+"' method"),i=1);s=e}else if((t=(u=p.n<0)?d:r.call(a,p))!==o)break}catch(t){s=e,i=1,d=t}finally{c=1}}return{value:t,done:u}}}(r,n,s),!0),c}var o={};function i(){}function d(){}function c(){}t=Object.getPrototypeOf;var l=[][a]?t(t([][a]())):(f(t={},a,(function(){return this})),t),u=c.prototype=i.prototype=Object.create(l);function g(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,c):(e.__proto__=c,f(e,n,"GeneratorFunction")),e.prototype=Object.create(u),e}return d.prototype=c,f(u,"constructor",c),f(c,"constructor",d),d.displayName="GeneratorFunction",f(c,n,"GeneratorFunction"),f(u),f(u,n,"Generator"),f(u,a,(function(){return this})),f(u,"toString",(function(){return"[object Generator]"})),(p=function(){return{w:s,m:g}})()}function f(e,t,r,a){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}f=function(e,t,r,a){if(t)n?n(e,t,{value:r,enumerable:!a,configurable:!a,writable:!a}):e[t]=r;else{function s(t,r){f(e,t,(function(e){return this._invoke(t,r,e)}))}s("next",0),s("throw",1),s("return",2)}},f(e,t,r,a)}function g(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(typeof e+" is not iterable")}function y(e,t){return y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},y(e,t)}function m(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var a,n,s,o,i=[],d=!0,c=!1;try{if(s=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;d=!1}else for(;!(d=(a=s.call(r)).done)&&(i.push(a.value),i.length!==t);d=!0);}catch(e){c=!0,n=e}finally{try{if(!d&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw n}}return i}}(e,t)||v(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(e,t){return t||(t=e.slice(0)),e.raw=t,e}function b(e){return function(e){if(Array.isArray(e))return a(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||v(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function x(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var a=r.call(e,t);if("object"!=typeof a)return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function v(e,t){if(e){if("string"==typeof e)return a(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(e,t):void 0}}function R(e){var t="function"==typeof Map?new Map:void 0;return R=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(l())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,t);var n=new(e.bind.apply(e,a));return r&&y(n,r.prototype),n}(e,arguments,d(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),y(r,e)},R(e)}var j="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function w(){throw new Error("setTimeout has not been defined")}function E(){throw new Error("clearTimeout has not been defined")}var S=w,T=E;function P(e){if(S===setTimeout)return setTimeout(e,0);if((S===w||!S)&&setTimeout)return S=setTimeout,setTimeout(e,0);try{return S(e,0)}catch(t){try{return S.call(null,e,0)}catch(t){return S.call(this,e,0)}}}"function"==typeof j.setTimeout&&(S=setTimeout),"function"==typeof j.clearTimeout&&(T=clearTimeout);var A,k=[],C=!1,_=-1;function I(){C&&A&&(C=!1,A.length?k=A.concat(k):_=-1,k.length&&D())}function D(){if(!C){var e=P(I);C=!0;for(var t=k.length;t;){for(A=k,k=[];++_1)for(var r=1;rn.length)return!1;for(var i=0,d=s.length-1;ie)return!1;if((r+=t[a+1])>=e)return!0}return!1}function Ur(e){return e<65?36===e:e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&Nr.test(String.fromCharCode(e)):Lr(e,Mr)))}function qr(e){return e<48?36===e:e<58||!(e<65)&&(e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&Br.test(String.fromCharCode(e)):Lr(e,Mr)||Lr(e,Fr))))}function Gr(e){for(var t=!0,r=0;r=48&&e<=57},ta={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},ra={bin:function(e){return 48===e||49===e},oct:function(e){return e>=48&&e<=55},dec:function(e){return e>=48&&e<=57},hex:function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}};function aa(e,t,r,a,n,s){for(var o=r,i=a,d=n,c="",l=null,u=r,p=t.length;;){if(r>=p){s.unterminated(o,i,d),c+=t.slice(u,r);break}var f=t.charCodeAt(r);if(na(e,f,t,r)){c+=t.slice(u,r);break}if(92===f){c+=t.slice(u,r);var g=sa(t,r,a,n,"template"===e,s);null!==g.ch||l?c+=g.ch:l={pos:r,lineStart:a,curLine:n},r=g.pos,a=g.lineStart,n=g.curLine,u=r}else 8232===f||8233===f?(++n,a=++r):10===f||13===f?"template"===e?(c+=t.slice(u,r)+"\n",++r,13===f&&10===t.charCodeAt(r)&&++r,++n,u=a=r):s.unterminated(o,i,d):++r}return{pos:r,str:c,firstInvalidLoc:l,lineStart:a,curLine:n,containsInvalid:!!l}}function na(e,t,r,a){return"template"===e?96===t||36===t&&123===r.charCodeAt(a+1):t===("double"===e?34:39)}function sa(e,t,r,a,n,s){var o=!n;t++;var i=function(e){return{pos:t,ch:e,lineStart:r,curLine:a}},d=e.charCodeAt(t++);switch(d){case 110:return i("\n");case 114:return i("\r");case 120:var c,l=oa(e,t,r,a,2,!1,o,s);return c=l.code,t=l.pos,i(null===c?null:String.fromCharCode(c));case 117:var u,p=da(e,t,r,a,o,s);return u=p.code,t=p.pos,i(null===u?null:String.fromCodePoint(u));case 116:return i("\t");case 98:return i("\b");case 118:return i("\v");case 102:return i("\f");case 13:10===e.charCodeAt(t)&&++t;case 10:r=t,++a;case 8232:case 8233:return i("");case 56:case 57:if(n)return i(null);s.strictNumericEscape(t-1,r,a);default:if(d>=48&&d<=55){var f=t-1,g=/^[0-7]+/.exec(e.slice(f,t+2))[0],y=parseInt(g,8);y>255&&(g=g.slice(0,-1),y=parseInt(g,8)),t+=g.length-1;var m=e.charCodeAt(t);if("0"!==g||56===m||57===m){if(n)return i(null);s.strictNumericEscape(f,r,a)}return i(String.fromCharCode(y))}return i(String.fromCharCode(d))}}function oa(e,t,r,a,n,s,o,i){var d,c=t,l=ia(e,t,r,a,16,n,s,!1,i,!o);return d=l.n,t=l.pos,null===d&&(o?i.invalidEscapeSequence(c,r,a):t=c-1),{code:d,pos:t}}function ia(e,t,r,a,n,s,o,i,d,c){for(var l=t,u=16===n?ta.hex:ta.decBinOct,p=16===n?ra.hex:10===n?ra.dec:8===n?ra.oct:ra.bin,f=!1,g=0,y=0,m=null==s?1/0:s;y=97?h-97+10:h>=65?h-65+10:ea(h)?h-48:1/0)>=n){if(b<=9&&c)return{n:null,pos:t};if(b<=9&&d.invalidDigit(t,r,a,n))b=0;else{if(!o)break;b=0,f=!0}}++t,g=g*n+b}else{var x=e.charCodeAt(t-1),v=e.charCodeAt(t+1);if(i){if(Number.isNaN(v)||!p(v)||u.has(x)||u.has(v)){if(c)return{n:null,pos:t};d.unexpectedNumericSeparator(t,r,a)}}else{if(c)return{n:null,pos:t};d.numericSeparatorInEscapeSequence(t,r,a)}++t}}return t===l||null!=s&&t-l!==s||f?{n:null,pos:t}:{n:g,pos:t}}function da(e,t,r,a,n,s){var o;if(123===e.charCodeAt(t)){var i=oa(e,++t,r,a,e.indexOf("}",t)-t,!0,n,s);if(o=i.code,t=i.pos,++t,null!==o&&o>1114111){if(!n)return{code:null,pos:t};s.invalidCodePoint(t,r,a)}}else{var d=oa(e,t,r,a,4,!1,n,s);o=d.code,t=d.pos}return{code:o,pos:t}}var ca=["consequent","body","alternate"],la=["leadingComments","trailingComments","innerComments"],ua=["||","&&","??"],pa=["++","--"],fa=[">","<",">=","<="],ga=["==","===","!=","!=="],ya=[].concat(ga,["in","instanceof"]),ma=[].concat(b(ya),fa),ha=["-","/","%","*","**","&","|",">>",">>>","<<","^"],ba=["+"].concat(ha,b(ma),["|>"]),xa=["=","+="].concat(b(ha.map((function(e){return e+"="}))),b(ua.map((function(e){return e+"="})))),va=["delete","!"],Ra=["+","-","~"],ja=["typeof"],wa=["void","throw"].concat(va,Ra,ja),Ea={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]};e.BLOCK_SCOPED_SYMBOL=Symbol.for("var used to be block scoped"),e.NOT_LOCAL_BINDING=Symbol.for("should not be considered a local binding");var Sa={},Ta={},Pa={},Aa={},ka={},Ca={},_a={};function Ia(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function Da(e){return{validate:e}}function Oa(){return Da(Wa.apply(void 0,arguments))}function Na(e){return{validate:e,optional:!0}}function Ba(){return{validate:Wa.apply(void 0,arguments),optional:!0}}function Ma(e){return za(Ha("array"),Ua(e))}function Fa(){return Ma(Wa.apply(void 0,arguments))}function La(){return Da(Fa.apply(void 0,arguments))}function Ua(e){var t=K.env.BABEL_TYPES_8_BREAKING?ns:function(){};function r(r,a,n){if(Array.isArray(n))for(var s=0,o={toString:function(){return a+"["+s+"]"}};s=2&&"type"in t[0]&&"array"===t[0].type&&!("each"in t[1]))throw new Error('An assertValueType("array") validator can only be followed by an assertEach(...) validator.');return a}var Xa,Ja,Ya,$a=new Set(["aliases","builder","deprecatedAlias","fields","inherits","visitor","validate"]),Qa=new Set(["default","optional","deprecated","validate"]),Za={};function en(){for(var e=arguments.length,t=new Array(e),r=0;r0:c&&"object"==typeof c)throw new Error("field defaults can only be primitives or empty arrays currently");a[o]={default:Array.isArray(c)?[]:c,optional:d.optional,deprecated:d.deprecated,validate:d.validate}}for(var l=t.visitor||r.visitor||[],u=t.aliases||r.aliases||[],p=t.builder||r.builder||t.visitor||[],f=0,g=Object.keys(t);f+s+1)throw new TypeError("RestElement must be last element of "+n)}:void 0}),rn("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:Wa("Expression"),optional:!0}}}),rn("SequenceExpression",{visitor:["expressions"],fields:{expressions:La("Expression")},aliases:["Expression"]}),rn("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:Wa("Expression")}}}),rn("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:Wa("Expression"),optional:!0},consequent:La("Statement")}}),rn("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:Wa("Expression")},cases:La("SwitchCase")}}),rn("ThisExpression",{aliases:["Expression"]}),rn("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:Wa("Expression")}}}),rn("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{block:{validate:K.env.BABEL_TYPES_8_BREAKING?za(Wa("BlockStatement"),Object.assign((function(e){if(!e.handler&&!e.finalizer)throw new TypeError("TryStatement expects either a handler or finalizer, or both")}),{oneOfNodeTypes:["BlockStatement"]})):Wa("BlockStatement")},handler:{optional:!0,validate:Wa("CatchClause")},finalizer:{optional:!0,validate:Wa("BlockStatement")}}}),rn("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!0},argument:{validate:Wa("Expression")},operator:{validate:qa.apply(void 0,b(wa))}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),rn("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!1},argument:{validate:K.env.BABEL_TYPES_8_BREAKING?Wa("Identifier","MemberExpression"):Wa("Expression")},operator:{validate:qa.apply(void 0,b(pa))}},visitor:["argument"],aliases:["Expression"]}),rn("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{declare:{validate:Ha("boolean"),optional:!0},kind:{validate:qa("var","let","const","using","await using")},declarations:La("VariableDeclarator")},validate:K.env.BABEL_TYPES_8_BREAKING?(ln=Wa("Identifier","Placeholder"),un=Wa("Identifier","ArrayPattern","ObjectPattern","Placeholder"),pn=Wa("Identifier","VoidPattern","Placeholder"),function(e,t,r){var a=r.kind,n=r.declarations,s=Ir("ForXStatement",e,{left:r});if(s&&1!==n.length)throw new TypeError("Exactly one VariableDeclarator is required in the VariableDeclaration of a "+e.type);for(var o,d=i(n);!(o=d()).done;){var c=o.value;"const"===a||"let"===a||"var"===a?s||c.init?un(c,"id",c.id):ln(c,"id",c.id):pn(c,"id",c.id)}}):void 0}),rn("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:K.env.BABEL_TYPES_8_BREAKING?Wa("Identifier","ArrayPattern","ObjectPattern","VoidPattern"):Wa("LVal","VoidPattern")},definite:{optional:!0,validate:Ha("boolean")},init:{optional:!0,validate:Wa("Expression")}}}),rn("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:Wa("Expression")},body:{validate:Wa("Statement")}}}),rn("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{validate:Wa("Expression")},body:{validate:Wa("Statement")}}}),rn("AssignmentPattern",{visitor:["left","right","decorators"],builder:["left","right"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:Object.assign({},fn(),{left:{validate:Wa("Identifier","ObjectPattern","ArrayPattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")},right:{validate:Wa("Expression")},decorators:{validate:Fa("Decorator"),optional:!0}})}),rn("ArrayPattern",{visitor:["elements","typeAnnotation"],builder:["elements"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:Object.assign({},fn(),{elements:{validate:za(Ha("array"),Ua(Va("null","PatternLike")))}})}),rn("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["typeParameters","params","predicate","returnType","body"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:Object.assign({},an(),nn(),{expression:{validate:Ha("boolean")},body:{validate:Wa("BlockStatement","Expression")},predicate:{validate:Wa("DeclaredPredicate","InferredPredicate"),optional:!0}})}),rn("ClassBody",{visitor:["body"],fields:{body:La("ClassMethod","ClassPrivateMethod","ClassProperty","ClassPrivateProperty","ClassAccessorProperty","TSDeclareMethod","TSIndexSignature","StaticBlock")}}),rn("ClassExpression",{builder:["id","superClass","body","decorators"],visitor:["decorators","id","typeParameters","superClass","superTypeParameters","mixins","implements","body"],aliases:["Scopable","Class","Expression"],fields:(Xa={id:{validate:Wa("Identifier"),optional:!0},typeParameters:{validate:Wa("TypeParameterDeclaration","TSTypeParameterDeclaration","Noop"),optional:!0},body:{validate:Wa("ClassBody")},superClass:{optional:!0,validate:Wa("Expression")}},Xa.superTypeParameters={validate:Wa("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},Xa.implements={validate:Fa("TSExpressionWithTypeArguments","ClassImplements"),optional:!0},Xa.decorators={validate:Fa("Decorator"),optional:!0},Xa.mixins={validate:Wa("InterfaceExtends"),optional:!0},Xa)}),rn("ClassDeclaration",{inherits:"ClassExpression",aliases:["Scopable","Class","Statement","Declaration"],fields:(Ja={id:{validate:Wa("Identifier"),optional:!0},typeParameters:{validate:Wa("TypeParameterDeclaration","TSTypeParameterDeclaration","Noop"),optional:!0},body:{validate:Wa("ClassBody")},superClass:{optional:!0,validate:Wa("Expression")}},Ja.superTypeParameters={validate:Wa("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},Ja.implements={validate:Fa("TSExpressionWithTypeArguments","ClassImplements"),optional:!0},Ja.decorators={validate:Fa("Decorator"),optional:!0},Ja.mixins={validate:Wa("InterfaceExtends"),optional:!0},Ja.declare={validate:Ha("boolean"),optional:!0},Ja.abstract={validate:Ha("boolean"),optional:!0},Ja),validate:K.env.BABEL_TYPES_8_BREAKING?function(){var e=Wa("Identifier");return function(t,r,a){Ir("ExportDefaultDeclaration",t)||e(a,"id",a.id)}}():void 0});var gn,yn,mn={attributes:{optional:!0,validate:Fa("ImportAttribute")},assertions:{deprecated:!0,optional:!0,validate:Fa("ImportAttribute")}};rn("ExportAllDeclaration",{builder:["source"],visitor:["source","attributes","assertions"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:Object.assign({source:{validate:Wa("StringLiteral")},exportKind:Na(qa("type","value"))},mn)}),rn("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:{declaration:Oa("TSDeclareFunction","FunctionDeclaration","ClassDeclaration","Expression"),exportKind:Na(qa("value"))}}),rn("ExportNamedDeclaration",{builder:["declaration","specifiers","source"],visitor:["declaration","specifiers","source","attributes","assertions"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:Object.assign({declaration:{optional:!0,validate:K.env.BABEL_TYPES_8_BREAKING?za(Wa("Declaration"),Object.assign((function(e,t,r){if(r&&e.specifiers.length)throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration");if(r&&e.source)throw new TypeError("Cannot export a declaration from a source")}),{oneOfNodeTypes:["Declaration"]})):Wa("Declaration")}},mn,{specifiers:{default:[],validate:Ma((gn=Wa("ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"),yn=Wa("ExportSpecifier"),K.env.BABEL_TYPES_8_BREAKING?Object.assign((function(e,t,r){(e.source?gn:yn)(e,t,r)}),{oneOfNodeTypes:["ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"]}):gn))},source:{validate:Wa("StringLiteral"),optional:!0},exportKind:Na(qa("type","value"))})}),rn("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:Wa("Identifier")},exported:{validate:Wa("Identifier","StringLiteral")},exportKind:{validate:qa("type","value"),optional:!0}}}),rn("ForOfStatement",{visitor:["left","right","body"],builder:["left","right","body","await"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:function(){if(!K.env.BABEL_TYPES_8_BREAKING)return Wa("VariableDeclaration","LVal");var e=Wa("VariableDeclaration"),t=Wa("Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression");return Object.assign((function(r,a,n){Ir("VariableDeclaration",n)?e(r,a,n):t(r,a,n)}),{oneOfNodeTypes:["VariableDeclaration","Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"]})}()},right:{validate:Wa("Expression")},body:{validate:Wa("Statement")},await:{default:!1}}}),rn("ImportDeclaration",{builder:["specifiers","source"],visitor:["specifiers","source","attributes","assertions"],aliases:["Statement","Declaration","ImportOrExportDeclaration"],fields:Object.assign({},mn,{module:{optional:!0,validate:Ha("boolean")},phase:{default:null,validate:qa("source","defer")},specifiers:La("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier"),source:{validate:Wa("StringLiteral")},importKind:{validate:qa("type","typeof","value"),optional:!0}})}),rn("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:Wa("Identifier")}}}),rn("ImportNamespaceSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:Wa("Identifier")}}}),rn("ImportSpecifier",{visitor:["imported","local"],builder:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:Wa("Identifier")},imported:{validate:Wa("Identifier","StringLiteral")},importKind:{validate:qa("type","typeof","value"),optional:!0}}}),rn("ImportExpression",{visitor:["source","options"],aliases:["Expression"],fields:{phase:{default:null,validate:qa("source","defer")},source:{validate:Wa("Expression")},options:{validate:Wa("Expression"),optional:!0}}}),rn("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:K.env.BABEL_TYPES_8_BREAKING?za(Wa("Identifier"),Object.assign((function(e,t,r){var a;switch(r.name){case"function":a="sent";break;case"new":a="target";break;case"import":a="meta"}if(!Ir("Identifier",e.property,{name:a}))throw new TypeError("Unrecognised MetaProperty")}),{oneOfNodeTypes:["Identifier"]})):Wa("Identifier")},property:{validate:Wa("Identifier")}}});var hn=function(){return{abstract:{validate:Ha("boolean"),optional:!0},accessibility:{validate:qa("public","private","protected"),optional:!0},static:{default:!1},override:{default:!1},computed:{default:!1},optional:{validate:Ha("boolean"),optional:!0},key:{validate:za(function(){var e=Wa("Identifier","StringLiteral","NumericLiteral","BigIntLiteral"),t=Wa("Expression");return function(r,a,n){(r.computed?t:e)(r,a,n)}}(),Wa("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression"))}}},bn=function(){return Object.assign({},an(),hn(),{params:La("FunctionParameter","TSParameterProperty"),kind:{validate:qa("get","set","method","constructor"),default:"method"},access:{validate:za(Ha("string"),qa("public","private","protected")),optional:!0},decorators:{validate:Fa("Decorator"),optional:!0}})};rn("ClassMethod",{aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static","generator","async"],visitor:["decorators","key","typeParameters","params","returnType","body"],fields:Object.assign({},bn(),nn(),{body:{validate:Wa("BlockStatement")}})}),rn("ObjectPattern",{visitor:["decorators","properties","typeAnnotation"],builder:["properties"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:Object.assign({},fn(),{properties:La("RestElement","ObjectProperty")})}),rn("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],deprecatedAlias:"SpreadProperty",fields:{argument:{validate:Wa("Expression")}}}),rn("Super",{aliases:["Expression"]}),rn("TaggedTemplateExpression",{visitor:["tag","typeParameters","quasi"],builder:["tag","quasi"],aliases:["Expression"],fields:(Ya={tag:{validate:Wa("Expression")},quasi:{validate:Wa("TemplateLiteral")}},Ya.typeParameters={validate:Wa("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},Ya)}),rn("TemplateElement",{builder:["value","tail"],fields:{value:{validate:za(function(e){var t=Object.keys(e);function r(r,a,n){for(var s,o=[],d=i(t);!(s=d()).done;){var c=s.value;try{as(r,c,n[c],e[c])}catch(e){if(e instanceof TypeError){o.push(e.message);continue}throw e}}if(o.length)throw new TypeError("Property "+a+" of "+r.type+" expected to have the following:\n"+o.join("\n"))}return r.shapeOf=e,r}({raw:{validate:Ha("string")},cooked:{validate:Ha("string"),optional:!0}}),(function(e){var t=e.value.raw,r=!1,a=function(){throw new Error("Internal @babel/types error.")},n=aa("template",t,0,0,0,{unterminated:function(){r=!0},strictNumericEscape:a,invalidEscapeSequence:a,numericSeparatorInEscapeSequence:a,unexpectedNumericSeparator:a,invalidDigit:a,invalidCodePoint:a}),s=n.str,o=n.firstInvalidLoc;if(!r)throw new Error("Invalid raw");e.value.cooked=o?null:s}))},tail:{default:!1}}}),rn("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:La("TemplateElement"),expressions:{validate:za(Ha("array"),Ua(Wa("Expression","TSType")),(function(e,t,r){if(e.quasis.length!==r.length+1)throw new TypeError("Number of "+e.type+" quasis should be exactly one more than the number of expressions.\nExpected "+(r.length+1)+" quasis but got "+e.quasis.length)}))}}}),rn("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:K.env.BABEL_TYPES_8_BREAKING?za(Ha("boolean"),Object.assign((function(e,t,r){if(r&&!e.argument)throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument")}),{type:"boolean"})):Ha("boolean"),default:!1},argument:{optional:!0,validate:Wa("Expression")}}}),rn("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:Wa("Expression")}}}),rn("Import",{aliases:["Expression"]}),rn("BigIntLiteral",{builder:["value"],fields:{value:{validate:Ha("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),rn("ExportNamespaceSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:Wa("Identifier")}}}),rn("OptionalMemberExpression",{builder:["object","property","computed","optional"],visitor:["object","property"],aliases:["Expression"],fields:{object:{validate:Wa("Expression")},property:{validate:function(){var e=Wa("Identifier"),t=Wa("Expression"),r=Object.assign((function(r,a,n){(r.computed?t:e)(r,a,n)}),{oneOfNodeTypes:["Expression","Identifier"]});return r}()},computed:{default:!1},optional:{validate:K.env.BABEL_TYPES_8_BREAKING?za(Ha("boolean"),Ka()):Ha("boolean")}}}),rn("OptionalCallExpression",{visitor:["callee","typeParameters","typeArguments","arguments"],builder:["callee","arguments","optional"],aliases:["Expression"],fields:Object.assign({callee:{validate:Wa("Expression")},arguments:La("Expression","SpreadElement","ArgumentPlaceholder"),optional:{validate:K.env.BABEL_TYPES_8_BREAKING?za(Ha("boolean"),Ka()):Ha("boolean")},typeArguments:{validate:Wa("TypeParameterInstantiation"),optional:!0}},{typeParameters:{validate:Wa("TSTypeParameterInstantiation"),optional:!0}})}),rn("ClassProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property"],fields:Object.assign({},hn(),{value:{validate:Wa("Expression"),optional:!0},definite:{validate:Ha("boolean"),optional:!0},typeAnnotation:{validate:Wa("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},decorators:{validate:Fa("Decorator"),optional:!0},readonly:{validate:Ha("boolean"),optional:!0},declare:{validate:Ha("boolean"),optional:!0},variance:{validate:Wa("Variance"),optional:!0}})}),rn("ClassAccessorProperty",{visitor:["decorators","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property","Accessor"],fields:Object.assign({},hn(),{key:{validate:za(function(){var e=Wa("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","PrivateName"),t=Wa("Expression");return function(r,a,n){(r.computed?t:e)(r,a,n)}}(),Wa("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression","PrivateName"))},value:{validate:Wa("Expression"),optional:!0},definite:{validate:Ha("boolean"),optional:!0},typeAnnotation:{validate:Wa("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},decorators:{validate:Fa("Decorator"),optional:!0},readonly:{validate:Ha("boolean"),optional:!0},declare:{validate:Ha("boolean"),optional:!0},variance:{validate:Wa("Variance"),optional:!0}})}),rn("ClassPrivateProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","decorators","static"],aliases:["Property","Private"],fields:{key:{validate:Wa("PrivateName")},value:{validate:Wa("Expression"),optional:!0},typeAnnotation:{validate:Wa("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},decorators:{validate:Fa("Decorator"),optional:!0},static:{validate:Ha("boolean"),default:!1},readonly:{validate:Ha("boolean"),optional:!0},optional:{validate:Ha("boolean"),optional:!0},definite:{validate:Ha("boolean"),optional:!0},variance:{validate:Wa("Variance"),optional:!0}}}),rn("ClassPrivateMethod",{builder:["kind","key","params","body","static"],visitor:["decorators","key","typeParameters","params","returnType","body"],aliases:["Function","Scopable","BlockParent","FunctionParent","Method","Private"],fields:Object.assign({},bn(),nn(),{kind:{validate:qa("get","set","method"),default:"method"},key:{validate:Wa("PrivateName")},body:{validate:Wa("BlockStatement")}})}),rn("PrivateName",{visitor:["id"],aliases:["Private"],fields:{id:{validate:Wa("Identifier")}}}),rn("StaticBlock",{visitor:["body"],fields:{body:La("Statement")},aliases:["Scopable","BlockParent","FunctionParent"]}),rn("ImportAttribute",{visitor:["key","value"],fields:{key:{validate:Wa("Identifier","StringLiteral")},value:{validate:Wa("StringLiteral")}}});var xn=en("Flow"),vn=function(e){var t="DeclareClass"===e;xn(e,{builder:["id","typeParameters","extends","body"],visitor:["id","typeParameters","extends"].concat(b(t?["mixins","implements"]:[]),["body"]),aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({id:Oa("Identifier"),typeParameters:Ba("TypeParameterDeclaration"),extends:Na(Fa("InterfaceExtends"))},t?{mixins:Na(Fa("InterfaceExtends")),implements:Na(Fa("ClassImplements"))}:{},{body:Oa("ObjectTypeAnnotation")})})};xn("AnyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["FlowType"],fields:{elementType:Oa("FlowType")}}),xn("BooleanTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("BooleanLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:Da(Ha("boolean"))}}),xn("NullLiteralTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("ClassImplements",{visitor:["id","typeParameters"],fields:{id:Oa("Identifier"),typeParameters:Ba("TypeParameterInstantiation")}}),vn("DeclareClass"),xn("DeclareFunction",{builder:["id"],visitor:["id","predicate"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier"),predicate:Ba("DeclaredPredicate")}}),vn("DeclareInterface"),xn("DeclareModule",{builder:["id","body","kind"],visitor:["id","body"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier","StringLiteral"),body:Oa("BlockStatement"),kind:Na(qa("CommonJS","ES"))}}),xn("DeclareModuleExports",{visitor:["typeAnnotation"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{typeAnnotation:Oa("TypeAnnotation")}}),xn("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier"),typeParameters:Ba("TypeParameterDeclaration"),right:Oa("FlowType")}}),xn("DeclareOpaqueType",{visitor:["id","typeParameters","supertype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier"),typeParameters:Ba("TypeParameterDeclaration"),supertype:Ba("FlowType"),impltype:Ba("FlowType")}}),xn("DeclareVariable",{visitor:["id"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier")}}),xn("DeclareExportDeclaration",{visitor:["declaration","specifiers","source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({declaration:Ba("Flow"),specifiers:Na(Fa("ExportSpecifier","ExportNamespaceSpecifier")),source:Ba("StringLiteral"),default:Na(Ha("boolean"))},mn)}),xn("DeclareExportAllDeclaration",{visitor:["source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({source:Oa("StringLiteral"),exportKind:Na(qa("type","value"))},mn)}),xn("DeclaredPredicate",{visitor:["value"],aliases:["FlowPredicate"],fields:{value:Oa("Flow")}}),xn("ExistsTypeAnnotation",{aliases:["FlowType"]}),xn("FunctionTypeAnnotation",{builder:["typeParameters","params","rest","returnType"],visitor:["typeParameters","this","params","rest","returnType"],aliases:["FlowType"],fields:{typeParameters:Ba("TypeParameterDeclaration"),params:La("FunctionTypeParam"),rest:Ba("FunctionTypeParam"),this:Ba("FunctionTypeParam"),returnType:Oa("FlowType")}}),xn("FunctionTypeParam",{visitor:["name","typeAnnotation"],fields:{name:Ba("Identifier"),typeAnnotation:Oa("FlowType"),optional:Na(Ha("boolean"))}}),xn("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["FlowType"],fields:{id:Oa("Identifier","QualifiedTypeIdentifier"),typeParameters:Ba("TypeParameterInstantiation")}}),xn("InferredPredicate",{aliases:["FlowPredicate"]}),xn("InterfaceExtends",{visitor:["id","typeParameters"],fields:{id:Oa("Identifier","QualifiedTypeIdentifier"),typeParameters:Ba("TypeParameterInstantiation")}}),vn("InterfaceDeclaration"),xn("InterfaceTypeAnnotation",{visitor:["extends","body"],aliases:["FlowType"],fields:{extends:Na(Fa("InterfaceExtends")),body:Oa("ObjectTypeAnnotation")}}),xn("IntersectionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:Da(Fa("FlowType"))}}),xn("MixedTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("EmptyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["FlowType"],fields:{typeAnnotation:Oa("FlowType")}}),xn("NumberLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:Da(Ha("number"))}}),xn("NumberTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties","internalSlots"],aliases:["FlowType"],builder:["properties","indexers","callProperties","internalSlots","exact"],fields:{properties:Da(Fa("ObjectTypeProperty","ObjectTypeSpreadProperty")),indexers:{validate:Fa("ObjectTypeIndexer"),optional:!0,default:[]},callProperties:{validate:Fa("ObjectTypeCallProperty"),optional:!0,default:[]},internalSlots:{validate:Fa("ObjectTypeInternalSlot"),optional:!0,default:[]},exact:{validate:Ha("boolean"),default:!1},inexact:Na(Ha("boolean"))}}),xn("ObjectTypeInternalSlot",{visitor:["id","value"],builder:["id","value","optional","static","method"],aliases:["UserWhitespacable"],fields:{id:Oa("Identifier"),value:Oa("FlowType"),optional:Da(Ha("boolean")),static:Da(Ha("boolean")),method:Da(Ha("boolean"))}}),xn("ObjectTypeCallProperty",{visitor:["value"],aliases:["UserWhitespacable"],fields:{value:Oa("FlowType"),static:Da(Ha("boolean"))}}),xn("ObjectTypeIndexer",{visitor:["variance","id","key","value"],builder:["id","key","value","variance"],aliases:["UserWhitespacable"],fields:{id:Ba("Identifier"),key:Oa("FlowType"),value:Oa("FlowType"),static:Da(Ha("boolean")),variance:Ba("Variance")}}),xn("ObjectTypeProperty",{visitor:["key","value","variance"],aliases:["UserWhitespacable"],fields:{key:Oa("Identifier","StringLiteral"),value:Oa("FlowType"),kind:Da(qa("init","get","set")),static:Da(Ha("boolean")),proto:Da(Ha("boolean")),optional:Da(Ha("boolean")),variance:Ba("Variance"),method:Da(Ha("boolean"))}}),xn("ObjectTypeSpreadProperty",{visitor:["argument"],aliases:["UserWhitespacable"],fields:{argument:Oa("FlowType")}}),xn("OpaqueType",{visitor:["id","typeParameters","supertype","impltype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier"),typeParameters:Ba("TypeParameterDeclaration"),supertype:Ba("FlowType"),impltype:Oa("FlowType")}}),xn("QualifiedTypeIdentifier",{visitor:["qualification","id"],builder:["id","qualification"],fields:{id:Oa("Identifier"),qualification:Oa("Identifier","QualifiedTypeIdentifier")}}),xn("StringLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:Da(Ha("string"))}}),xn("StringTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("SymbolTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("ThisTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("TupleTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:Da(Fa("FlowType"))}}),xn("TypeofTypeAnnotation",{visitor:["argument"],aliases:["FlowType"],fields:{argument:Oa("FlowType")}}),xn("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:Oa("Identifier"),typeParameters:Ba("TypeParameterDeclaration"),right:Oa("FlowType")}}),xn("TypeAnnotation",{visitor:["typeAnnotation"],fields:{typeAnnotation:Oa("FlowType")}}),xn("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["ExpressionWrapper","Expression"],fields:{expression:Oa("Expression"),typeAnnotation:Oa("TypeAnnotation")}}),xn("TypeParameter",{visitor:["bound","default","variance"],fields:{name:Da(Ha("string")),bound:Ba("TypeAnnotation"),default:Ba("FlowType"),variance:Ba("Variance")}}),xn("TypeParameterDeclaration",{visitor:["params"],fields:{params:Da(Fa("TypeParameter"))}}),xn("TypeParameterInstantiation",{visitor:["params"],fields:{params:Da(Fa("FlowType"))}}),xn("UnionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:Da(Fa("FlowType"))}}),xn("Variance",{builder:["kind"],fields:{kind:Da(qa("minus","plus"))}}),xn("VoidTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),xn("EnumDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:{id:Oa("Identifier"),body:Oa("EnumBooleanBody","EnumNumberBody","EnumStringBody","EnumSymbolBody")}}),xn("EnumBooleanBody",{aliases:["EnumBody"],visitor:["members"],fields:{explicitType:Da(Ha("boolean")),members:La("EnumBooleanMember"),hasUnknownMembers:Da(Ha("boolean"))}}),xn("EnumNumberBody",{aliases:["EnumBody"],visitor:["members"],fields:{explicitType:Da(Ha("boolean")),members:La("EnumNumberMember"),hasUnknownMembers:Da(Ha("boolean"))}}),xn("EnumStringBody",{aliases:["EnumBody"],visitor:["members"],fields:{explicitType:Da(Ha("boolean")),members:La("EnumStringMember","EnumDefaultedMember"),hasUnknownMembers:Da(Ha("boolean"))}}),xn("EnumSymbolBody",{aliases:["EnumBody"],visitor:["members"],fields:{members:La("EnumDefaultedMember"),hasUnknownMembers:Da(Ha("boolean"))}}),xn("EnumBooleanMember",{aliases:["EnumMember"],builder:["id"],visitor:["id","init"],fields:{id:Oa("Identifier"),init:Oa("BooleanLiteral")}}),xn("EnumNumberMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:Oa("Identifier"),init:Oa("NumericLiteral")}}),xn("EnumStringMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:Oa("Identifier"),init:Oa("StringLiteral")}}),xn("EnumDefaultedMember",{aliases:["EnumMember"],visitor:["id"],fields:{id:Oa("Identifier")}}),xn("IndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:Oa("FlowType"),indexType:Oa("FlowType")}}),xn("OptionalIndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:Oa("FlowType"),indexType:Oa("FlowType"),optional:Da(Ha("boolean"))}});var Rn=en("JSX");Rn("JSXAttribute",{visitor:["name","value"],aliases:["Immutable"],fields:{name:{validate:Wa("JSXIdentifier","JSXNamespacedName")},value:{optional:!0,validate:Wa("JSXElement","JSXFragment","StringLiteral","JSXExpressionContainer")}}}),Rn("JSXClosingElement",{visitor:["name"],aliases:["Immutable"],fields:{name:{validate:Wa("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")}}}),Rn("JSXElement",{builder:["openingElement","closingElement","children","selfClosing"],visitor:["openingElement","children","closingElement"],aliases:["Immutable","Expression"],fields:Object.assign({openingElement:{validate:Wa("JSXOpeningElement")},closingElement:{optional:!0,validate:Wa("JSXClosingElement")},children:La("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")},{selfClosing:{validate:Ha("boolean"),optional:!0}})}),Rn("JSXEmptyExpression",{}),Rn("JSXExpressionContainer",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:Wa("Expression","JSXEmptyExpression")}}}),Rn("JSXSpreadChild",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:Wa("Expression")}}}),Rn("JSXIdentifier",{builder:["name"],fields:{name:{validate:Ha("string")}}}),Rn("JSXMemberExpression",{visitor:["object","property"],fields:{object:{validate:Wa("JSXMemberExpression","JSXIdentifier")},property:{validate:Wa("JSXIdentifier")}}}),Rn("JSXNamespacedName",{visitor:["namespace","name"],fields:{namespace:{validate:Wa("JSXIdentifier")},name:{validate:Wa("JSXIdentifier")}}}),Rn("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","typeParameters","typeArguments","attributes"],aliases:["Immutable"],fields:Object.assign({name:{validate:Wa("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")},selfClosing:{default:!1},attributes:La("JSXAttribute","JSXSpreadAttribute"),typeArguments:{validate:Wa("TypeParameterInstantiation"),optional:!0}},{typeParameters:{validate:Wa("TSTypeParameterInstantiation"),optional:!0}})}),Rn("JSXSpreadAttribute",{visitor:["argument"],fields:{argument:{validate:Wa("Expression")}}}),Rn("JSXText",{aliases:["Immutable"],builder:["value"],fields:{value:{validate:Ha("string")}}}),Rn("JSXFragment",{builder:["openingFragment","closingFragment","children"],visitor:["openingFragment","children","closingFragment"],aliases:["Immutable","Expression"],fields:{openingFragment:{validate:Wa("JSXOpeningFragment")},closingFragment:{validate:Wa("JSXClosingFragment")},children:La("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")}}),Rn("JSXOpeningFragment",{aliases:["Immutable"]}),Rn("JSXClosingFragment",{aliases:["Immutable"]});for(var jn=["Identifier","StringLiteral","Expression","Statement","Declaration","BlockStatement","ClassBody","Pattern"],wn={Declaration:["Statement"],Pattern:["PatternLike","LVal"]},En=0,Sn=jn;En=Number.MAX_SAFE_INTEGER?Sm.uid=0:Sm.uid++};var Pm=Function.call.bind(Object.prototype.toString);function Am(e){if(void 0===e)return ks("undefined");if(!0===e||!1===e)return Ns(e);if(null===e)return{type:"NullLiteral"};if("string"==typeof e)return Is(e);if("number"==typeof e){var t;if(Number.isFinite(e))t=Ds(Math.abs(e));else t=ls("/",Number.isNaN(e)?Ds(0):Ds(1),Ds(0));return(e<0||Object.is(e,-0))&&(t=Zs("-",t)),t}if("bigint"==typeof e)return e<0?Zs("-",is(-e)):is(e);if(function(e){return"[object RegExp]"===Pm(e)}(e))return Bs(e.source,/\/([a-z]*)$/.exec(e.toString())[1]);if(Array.isArray(e))return ds(e.map(Am));if(function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}(e)){for(var r=[],a=0,n=Object.keys(e);a1?e:e[0]})),Qm=Ym((function(e){return e})),Zm=Ym((function(e){if(0===e.length)throw new Error("Found nothing to return.");if(e.length>1)throw new Error("Found multiple statements but wanted one");return e[0]})),eh={code:function(e){return"(\n"+e+"\n)"},validate:function(e){if(e.program.body.length>1)throw new Error("Found multiple statements but wanted one");if(0===eh.unwrap(e).start)throw new Error("Parse result included parens.")},unwrap:function(e){var t=m(e.program.body,1)[0];return Jm(t),t.expression}},th=["placeholderWhitelist","placeholderPattern","preserveComments","syntacticPlaceholders"];function rh(e,t){var r=t.placeholderWhitelist,a=void 0===r?e.placeholderWhitelist:r,n=t.placeholderPattern,s=void 0===n?e.placeholderPattern:n,o=t.preserveComments,i=void 0===o?e.preserveComments:o,d=t.syntacticPlaceholders,c=void 0===d?e.syntacticPlaceholders:d;return{parser:Object.assign({},e.parser,t.parser),placeholderWhitelist:a,placeholderPattern:s,preserveComments:i,syntacticPlaceholders:c}}function ah(e){if(null!=e&&"object"!=typeof e)throw new Error("Unknown template options.");var t=e||{},r=t.placeholderWhitelist,a=t.placeholderPattern,n=t.preserveComments,s=t.syntacticPlaceholders,o=u(t,th);if(null!=r&&!(r instanceof Set))throw new Error("'.placeholderWhitelist' must be a Set, null, or undefined");if(null!=a&&!(a instanceof RegExp)&&!1!==a)throw new Error("'.placeholderPattern' must be a RegExp, false, null, or undefined");if(null!=n&&"boolean"!=typeof n)throw new Error("'.preserveComments' must be a boolean, null, or undefined");if(null!=s&&"boolean"!=typeof s)throw new Error("'.syntacticPlaceholders' must be a boolean, null, or undefined");if(!0===s&&(null!=r||null!=a))throw new Error("'.placeholderWhitelist' and '.placeholderPattern' aren't compatible with '.syntacticPlaceholders: true'");return{parser:o,placeholderWhitelist:r||void 0,placeholderPattern:null==a?void 0:a,preserveComments:null==n?void 0:n,syntacticPlaceholders:null==s?void 0:s}}function nh(e){if(Array.isArray(e))return e.reduce((function(e,t,r){return e["$"+r]=t,e}),{});if("object"==typeof e||null==e)return e||void 0;throw new Error("Template replacements must be an array, object, null, or undefined")}var sh=o((function(e,t,r){this.line=void 0,this.column=void 0,this.index=void 0,this.line=e,this.column=t,this.index=r})),oh=o((function(e,t){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=e,this.end=t}));function ih(e,t){var r=e.line,a=e.column,n=e.index;return new sh(r,a+t,n+t)}var dh,ch="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",lh={ImportMetaOutsideModule:{message:"import.meta may appear only with 'sourceType: \"module\"'",code:ch},ImportOutsideModule:{message:"'import' and 'export' may appear only with 'sourceType: \"module\"'",code:ch}},uh={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},ph=function(e){return"UpdateExpression"===e.type?uh.UpdateExpression[""+e.prefix]:uh[e.type]},fh={AccessorIsGenerator:function(e){return"A "+e.kind+"ter cannot be a generator."},ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:function(e){return"Missing initializer in "+e.kind+" declaration."},DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:function(e){return"`"+e.exportName+"` has already been exported. Exported identifiers must be unique."},DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:function(e){return"A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '"+e.localName+"' as '"+e.exportName+"' } from 'some-module'`?"},ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:function(e){return"'"+("ForInStatement"===e.type?"for-in":"for-of")+"' loop variable declaration may not have an initializer."},ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:function(e){return"Unsyntactic "+("BreakStatement"===e.type?"break":"continue")+"."},IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportAttributesUseAssert:"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",ImportBindingIsString:function(e){return'A string literal cannot be used as an imported binding.\n- Did you mean `import { "'+e.importName+'" as foo }`?'},ImportCallArity:"`import()` requires exactly one or two arguments.",ImportCallNotNewExpression:"Cannot use new with import(...).",ImportCallSpreadArgument:"`...` is not allowed in `import()`.",ImportJSONBindingNotDefault:"A JSON module can only be imported with `default`.",ImportReflectionHasAssertion:"`import module x` cannot have assertions.",ImportReflectionNotBinding:'Only `import module x from "./module"` is valid.',IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:function(e){return"Expected number in radix "+e.radix+"."},InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:function(e){return"Escape sequence in keyword "+e.reservedWord+"."},InvalidIdentifier:function(e){return"Invalid identifier "+e.identifierName+"."},InvalidLhs:function(e){var t=e.ancestor;return"Invalid left-hand side in "+ph(t)+"."},InvalidLhsBinding:function(e){var t=e.ancestor;return"Binding invalid left-hand side in "+ph(t)+"."},InvalidLhsOptionalChaining:function(e){var t=e.ancestor;return"Invalid optional chaining in the left-hand side of "+ph(t)+"."},InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:function(e){return"Unexpected character '"+e.unexpected+"'."},InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:function(e){return"Private name #"+e.identifierName+" is not defined."},InvalidPropertyBindingPattern:"Binding member expression.",InvalidRecordProperty:"Only properties and spread elements are allowed in record definitions.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:function(e){return"Label '"+e.labelName+"' is already declared."},LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:function(e){return"This experimental syntax requires enabling the parser plugin: "+e.missingPlugin.map((function(e){return JSON.stringify(e)})).join(", ")+"."},MissingOneOfPlugins:function(e){return"This experimental syntax requires enabling one of the following parser plugin(s): "+e.missingPlugin.map((function(e){return JSON.stringify(e)})).join(", ")+"."},MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeDifferentFromType:"The only accepted module attribute is `type`.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:function(e){return'Duplicate key "'+e.key+'" is not allowed in module attributes.'},ModuleExportNameHasLoneSurrogate:function(e){return"An export name cannot include a lone surrogate, found '\\u"+e.surrogateCharCode.toString(16)+"'."},ModuleExportUndefined:function(e){return"Export '"+e.localName+"' is not defined."},MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:function(e){var t=e.identifierName;return"Private names are only allowed in property accesses (`obj.#"+t+"`) or in `in` expressions (`#"+t+" in obj`)."},PrivateNameRedeclaration:function(e){return"Duplicate private name #"+e.identifierName+"."},RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",RecordNoProto:"'__proto__' is not allowed in Record expressions.",RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode code, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:function(e){return"Unexpected keyword '"+e.keyword+"'."},UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:function(e){return"Unexpected reserved word '"+e.reservedWord+"'."},UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:function(e){var t=e.expected,r=e.unexpected;return"Unexpected token"+(r?" '"+r+"'.":"")+(t?', expected "'+t+'"':"")},UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",UnsupportedBind:"Binding should be performed on object property.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:function(e){var t=e.target;return"The only valid meta property for "+t+" is "+t+"."+e.onlyValidPropertyName+"."},UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:function(e){return"Identifier '"+e.identifierName+"' has already been declared."},VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},gh={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:function(e){var t=e.unexpected;return"Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character `"+String.fromCodePoint(t)+"`."}},yh=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),mh=Object.assign({PipeBodyIsTighter:"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",PipeTopicRequiresHackPipes:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:function(e){var t=e.token;return"Invalid topic token "+t+". In order to use "+t+' as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "'+t+'" }.'},PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:function(e){var t=e.type;return"Hack-style pipe body cannot be an unparenthesized "+ph({type:t})+"; please wrap it in parentheses."}},{PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression.",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression.",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference.",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding.",PrimaryTopicRequiresSmartPipeline:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'}),hh=["message"];function bh(e,t,r){Object.defineProperty(e,t,{enumerable:!1,configurable:!0,value:r})}function xh(e,t){if(Array.isArray(e))return function(t){return xh(t,e[0])};for(var r={},a=function(){var a=s[n],o=e[a],i="string"==typeof o?{message:function(){return o}}:"function"==typeof o?{message:o}:o,d=i.message,c=u(i,hh),l="string"==typeof d?function(){return d}:d;r[a]=function(e){var t=e.toMessage,r=e.code,a=e.reasonCode,n=e.syntaxPlugin,s="MissingPlugin"===a||"MissingOneOfPlugins"===a,o={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return o[a]&&(a=o[a]),function e(o,i){var d=new SyntaxError;return d.code=r,d.reasonCode=a,d.loc=o,d.pos=o.index,d.syntaxPlugin=n,s&&(d.missingPlugin=i.missingPlugin),bh(d,"clone",(function(t){var r;void 0===t&&(t={});var a=null!=(r=t.loc)?r:o,n=a.line,s=a.column,d=a.index;return e(new sh(n,s,d),Object.assign({},i,t.details))})),bh(d,"details",i),Object.defineProperty(d,"message",{configurable:!0,get:function(){var e=t(i)+" ("+o.line+":"+o.column+")";return this.message=e,e},set:function(e){Object.defineProperty(this,"message",{value:e,writable:!0})}}),d}}(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:a,toMessage:l},t?{syntaxPlugin:t}:{},c))},n=0,s=Object.keys(e);n...",!0)};Lh.template=new Fh("`",!0);var Uh=!0,qh=!0,Gh=!0,Wh=!0,Vh=!0,Hh=o((function(e,t){void 0===t&&(t={}),this.label=void 0,this.keyword=void 0,this.beforeExpr=void 0,this.startsExpr=void 0,this.rightAssociative=void 0,this.isLoop=void 0,this.isAssign=void 0,this.prefix=void 0,this.postfix=void 0,this.binop=void 0,this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.rightAssociative=!!t.rightAssociative,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=null!=t.binop?t.binop:null,this.updateContext=null})),Kh=new Map;function zh(e,t){void 0===t&&(t={}),t.keyword=e;var r=rb(e,t);return Kh.set(e,r),r}function Xh(e,t){return rb(e,{beforeExpr:Uh,binop:t})}var Jh=-1,Yh=[],$h=[],Qh=[],Zh=[],eb=[],tb=[];function rb(e,t){var r,a,n,s;return void 0===t&&(t={}),++Jh,$h.push(e),Qh.push(null!=(r=t.binop)?r:-1),Zh.push(null!=(a=t.beforeExpr)&&a),eb.push(null!=(n=t.startsExpr)&&n),tb.push(null!=(s=t.prefix)&&s),Yh.push(new Hh(e,t)),Jh}function ab(e,t){var r,a,n,s;return void 0===t&&(t={}),++Jh,Kh.set(e,Jh),$h.push(e),Qh.push(null!=(r=t.binop)?r:-1),Zh.push(null!=(a=t.beforeExpr)&&a),eb.push(null!=(n=t.startsExpr)&&n),tb.push(null!=(s=t.prefix)&&s),Yh.push(new Hh("name",t)),Jh}var nb={bracketL:rb("[",{beforeExpr:Uh,startsExpr:qh}),bracketHashL:rb("#[",{beforeExpr:Uh,startsExpr:qh}),bracketBarL:rb("[|",{beforeExpr:Uh,startsExpr:qh}),bracketR:rb("]"),bracketBarR:rb("|]"),braceL:rb("{",{beforeExpr:Uh,startsExpr:qh}),braceBarL:rb("{|",{beforeExpr:Uh,startsExpr:qh}),braceHashL:rb("#{",{beforeExpr:Uh,startsExpr:qh}),braceR:rb("}"),braceBarR:rb("|}"),parenL:rb("(",{beforeExpr:Uh,startsExpr:qh}),parenR:rb(")"),comma:rb(",",{beforeExpr:Uh}),semi:rb(";",{beforeExpr:Uh}),colon:rb(":",{beforeExpr:Uh}),doubleColon:rb("::",{beforeExpr:Uh}),dot:rb("."),question:rb("?",{beforeExpr:Uh}),questionDot:rb("?."),arrow:rb("=>",{beforeExpr:Uh}),template:rb("template"),ellipsis:rb("...",{beforeExpr:Uh}),backQuote:rb("`",{startsExpr:qh}),dollarBraceL:rb("${",{beforeExpr:Uh,startsExpr:qh}),templateTail:rb("...`",{startsExpr:qh}),templateNonTail:rb("...${",{beforeExpr:Uh,startsExpr:qh}),at:rb("@"),hash:rb("#",{startsExpr:qh}),interpreterDirective:rb("#!..."),eq:rb("=",{beforeExpr:Uh,isAssign:Wh}),assign:rb("_=",{beforeExpr:Uh,isAssign:Wh}),slashAssign:rb("_=",{beforeExpr:Uh,isAssign:Wh}),xorAssign:rb("_=",{beforeExpr:Uh,isAssign:Wh}),moduloAssign:rb("_=",{beforeExpr:Uh,isAssign:Wh}),incDec:rb("++/--",{prefix:Vh,postfix:!0,startsExpr:qh}),bang:rb("!",{beforeExpr:Uh,prefix:Vh,startsExpr:qh}),tilde:rb("~",{beforeExpr:Uh,prefix:Vh,startsExpr:qh}),doubleCaret:rb("^^",{startsExpr:qh}),doubleAt:rb("@@",{startsExpr:qh}),pipeline:Xh("|>",0),nullishCoalescing:Xh("??",1),logicalOR:Xh("||",1),logicalAND:Xh("&&",2),bitwiseOR:Xh("|",3),bitwiseXOR:Xh("^",4),bitwiseAND:Xh("&",5),equality:Xh("==/!=/===/!==",6),lt:Xh("/<=/>=",7),gt:Xh("/<=/>=",7),relational:Xh("/<=/>=",7),bitShift:Xh("<>/>>>",8),bitShiftL:Xh("<>/>>>",8),bitShiftR:Xh("<>/>>>",8),plusMin:rb("+/-",{beforeExpr:Uh,binop:9,prefix:Vh,startsExpr:qh}),modulo:rb("%",{binop:10,startsExpr:qh}),star:rb("*",{binop:10}),slash:Xh("/",10),exponent:rb("**",{beforeExpr:Uh,binop:11,rightAssociative:!0}),_in:zh("in",{beforeExpr:Uh,binop:7}),_instanceof:zh("instanceof",{beforeExpr:Uh,binop:7}),_break:zh("break"),_case:zh("case",{beforeExpr:Uh}),_catch:zh("catch"),_continue:zh("continue"),_debugger:zh("debugger"),_default:zh("default",{beforeExpr:Uh}),_else:zh("else",{beforeExpr:Uh}),_finally:zh("finally"),_function:zh("function",{startsExpr:qh}),_if:zh("if"),_return:zh("return",{beforeExpr:Uh}),_switch:zh("switch"),_throw:zh("throw",{beforeExpr:Uh,prefix:Vh,startsExpr:qh}),_try:zh("try"),_var:zh("var"),_const:zh("const"),_with:zh("with"),_new:zh("new",{beforeExpr:Uh,startsExpr:qh}),_this:zh("this",{startsExpr:qh}),_super:zh("super",{startsExpr:qh}),_class:zh("class",{startsExpr:qh}),_extends:zh("extends",{beforeExpr:Uh}),_export:zh("export"),_import:zh("import",{startsExpr:qh}),_null:zh("null",{startsExpr:qh}),_true:zh("true",{startsExpr:qh}),_false:zh("false",{startsExpr:qh}),_typeof:zh("typeof",{beforeExpr:Uh,prefix:Vh,startsExpr:qh}),_void:zh("void",{beforeExpr:Uh,prefix:Vh,startsExpr:qh}),_delete:zh("delete",{beforeExpr:Uh,prefix:Vh,startsExpr:qh}),_do:zh("do",{isLoop:Gh,beforeExpr:Uh}),_for:zh("for",{isLoop:Gh}),_while:zh("while",{isLoop:Gh}),_as:ab("as",{startsExpr:qh}),_assert:ab("assert",{startsExpr:qh}),_async:ab("async",{startsExpr:qh}),_await:ab("await",{startsExpr:qh}),_defer:ab("defer",{startsExpr:qh}),_from:ab("from",{startsExpr:qh}),_get:ab("get",{startsExpr:qh}),_let:ab("let",{startsExpr:qh}),_meta:ab("meta",{startsExpr:qh}),_of:ab("of",{startsExpr:qh}),_sent:ab("sent",{startsExpr:qh}),_set:ab("set",{startsExpr:qh}),_source:ab("source",{startsExpr:qh}),_static:ab("static",{startsExpr:qh}),_using:ab("using",{startsExpr:qh}),_yield:ab("yield",{startsExpr:qh}),_asserts:ab("asserts",{startsExpr:qh}),_checks:ab("checks",{startsExpr:qh}),_exports:ab("exports",{startsExpr:qh}),_global:ab("global",{startsExpr:qh}),_implements:ab("implements",{startsExpr:qh}),_intrinsic:ab("intrinsic",{startsExpr:qh}),_infer:ab("infer",{startsExpr:qh}),_is:ab("is",{startsExpr:qh}),_mixins:ab("mixins",{startsExpr:qh}),_proto:ab("proto",{startsExpr:qh}),_require:ab("require",{startsExpr:qh}),_satisfies:ab("satisfies",{startsExpr:qh}),_keyof:ab("keyof",{startsExpr:qh}),_readonly:ab("readonly",{startsExpr:qh}),_unique:ab("unique",{startsExpr:qh}),_abstract:ab("abstract",{startsExpr:qh}),_declare:ab("declare",{startsExpr:qh}),_enum:ab("enum",{startsExpr:qh}),_module:ab("module",{startsExpr:qh}),_namespace:ab("namespace",{startsExpr:qh}),_interface:ab("interface",{startsExpr:qh}),_type:ab("type",{startsExpr:qh}),_opaque:ab("opaque",{startsExpr:qh}),name:rb("name",{startsExpr:qh}),placeholder:rb("%%",{startsExpr:qh}),string:rb("string",{startsExpr:qh}),num:rb("num",{startsExpr:qh}),bigint:rb("bigint",{startsExpr:qh}),decimal:rb("decimal",{startsExpr:qh}),regexp:rb("regexp",{startsExpr:qh}),privateName:rb("#name",{startsExpr:qh}),eof:rb("eof"),jsxName:rb("jsxName"),jsxText:rb("jsxText",{beforeExpr:Uh}),jsxTagStart:rb("jsxTagStart",{startsExpr:qh}),jsxTagEnd:rb("jsxTagEnd")};function sb(e){return e>=93&&e<=133}function ob(e){return e>=58&&e<=133}function ib(e){return e>=58&&e<=137}function db(e){return eb[e]}function cb(e){return e>=129&&e<=131}function lb(e){return e>=58&&e<=92}function ub(e){return $h[e]}function pb(e){return Qh[e]}function fb(e){return e>=24&&e<=25}function gb(e){return Yh[e]}Yh[8].updateContext=function(e){e.pop()},Yh[5].updateContext=Yh[7].updateContext=Yh[23].updateContext=function(e){e.push(Lh.brace)},Yh[22].updateContext=function(e){e[e.length-1]===Lh.template?e.pop():e.push(Lh.template)},Yh[143].updateContext=function(e){e.push(Lh.j_expr,Lh.j_oTag)};var yb=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);var mb,hb=0,bb=1,xb=2,vb=4,Rb=8,jb=16,wb=32,Eb=64,Sb=128,Tb=256,Pb=512,Ab=1024,kb=514,Cb=576,_b=1667,Ib=1,Db=2,Ob=4,Nb=8,Bb=16,Mb=128,Fb=256,Lb=512,Ub=1024,qb=2048,Gb=4096,Wb=8192,Vb=8331,Hb=8201,Kb=9,zb=5,Xb=17,Jb=130,Yb=2,$b=8459,Qb=1024,Zb=64,ex=65,tx=8971,rx=1024,ax=4098,nx=4096,sx=2048,ox=0,ix=4,dx=3,cx=6,lx=5,ux=2,px=1,fx=1,gx=2,yx=4,mx=o((function(e){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=e})),hx=function(){function e(e,t){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=e,this.inModule=t}var t=e.prototype;return t.createScope=function(e){return new mx(e)},t.enter=function(e){this.scopeStack.push(this.createScope(e))},t.exit=function(){return this.scopeStack.pop().flags},t.treatFunctionsAsVarInScope=function(e){return!!(e.flags&(xb|Sb)||!this.parser.inModule&&e.flags&bb)},t.declareName=function(e,t,r){var a=this.currentScope();if(t&Nb||t&Bb){this.checkRedeclarationInScope(a,e,t,r);var n=a.names.get(e)||0;t&Bb?n|=yx:(a.firstLexicalName||(a.firstLexicalName=e),n|=gx),a.names.set(e,n),t&Nb&&this.maybeExportDefined(a,e)}else if(t&Ob)for(var s=this.scopeStack.length-1;s>=0&&(a=this.scopeStack[s],this.checkRedeclarationInScope(a,e,t,r),a.names.set(e,(a.names.get(e)||0)|fx),this.maybeExportDefined(a,e),!(a.flags&_b));--s);this.parser.inModule&&a.flags&bb&&this.undefinedExports.delete(e)},t.maybeExportDefined=function(e,t){this.parser.inModule&&e.flags&bb&&this.undefinedExports.delete(t)},t.checkRedeclarationInScope=function(e,t,r,a){this.isRedeclaredInScope(e,t,r)&&this.parser.raise(vh.VarRedeclaration,a,{identifierName:t})},t.isRedeclaredInScope=function(e,t,r){if(!(r&Ib))return!1;if(r&Nb)return e.names.has(t);var a=e.names.get(t);return r&Bb?(a&gx)>0||!this.treatFunctionsAsVarInScope(e)&&(a&fx)>0:(a&gx)>0&&!(e.flags&Rb&&e.firstLexicalName===t)||!this.treatFunctionsAsVarInScope(e)&&(a&yx)>0},t.checkLocalExport=function(e){var t=e.name;this.scopeStack[0].names.has(t)||this.undefinedExports.set(t,e.loc.start)},t.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},t.currentVarScopeFlags=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e].flags;if(t&_b)return t}},t.currentThisScopeFlags=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e].flags;if(t&(_b|Eb)&&!(t&vb))return t}},o(e,[{key:"inTopLevel",get:function(){return(this.currentScope().flags&bb)>0}},{key:"inFunction",get:function(){return(this.currentVarScopeFlags()&xb)>0}},{key:"allowSuper",get:function(){return(this.currentThisScopeFlags()&jb)>0}},{key:"allowDirectSuper",get:function(){return(this.currentThisScopeFlags()&wb)>0}},{key:"allowNewTarget",get:function(){return(this.currentThisScopeFlags()&Pb)>0}},{key:"inClass",get:function(){return(this.currentThisScopeFlags()&Eb)>0}},{key:"inClassAndNotInNonArrowFunction",get:function(){var e=this.currentThisScopeFlags();return(e&Eb)>0&&0==(e&xb)}},{key:"inStaticBlock",get:function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e].flags;if(t&Sb)return!0;if(t&(_b|Eb))return!1}}},{key:"inNonArrowFunction",get:function(){return(this.currentThisScopeFlags()&xb)>0}},{key:"inBareCaseStatement",get:function(){return(this.currentScope().flags&Tb)>0}},{key:"treatFunctionsAsVar",get:function(){return this.treatFunctionsAsVarInScope(this.currentScope())}}])}(),bx=function(e){function t(){for(var t,r=arguments.length,a=new Array(r),n=0;n0||(n&gx)>0}return!1},r.checkLocalExport=function(t){this.scopeStack[0].declareFunctions.has(t.name)||e.prototype.checkLocalExport.call(this,t)},o(t)}(hx),vx=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),Rx=xh(mb||(mb=h(["flow"])))({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:function(e){return"Cannot overwrite reserved type "+e.reservedType+"."},DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:function(e){var t=e.memberName;return"Boolean enum members need to be initialized. Use either `"+t+" = true,` or `"+t+" = false,` in enum `"+e.enumName+"`."},EnumDuplicateMemberName:function(e){return"Enum member names need to be unique, but the name `"+e.memberName+"` has already been used before in enum `"+e.enumName+"`."},EnumInconsistentMemberValues:function(e){return"Enum `"+e.enumName+"` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers."},EnumInvalidExplicitType:function(e){return"Enum type `"+e.invalidEnumType+"` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `"+e.enumName+"`."},EnumInvalidExplicitTypeUnknownSupplied:function(e){return"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `"+e.enumName+"`."},EnumInvalidMemberInitializerPrimaryType:function(e){var t=e.enumName,r=e.memberName,a=e.explicitType;return"Enum `"+t+"` has type `"+a+"`, so the initializer of `"+r+"` needs to be a "+a+" literal."},EnumInvalidMemberInitializerSymbolType:function(e){var t=e.enumName;return"Symbol enum members cannot be initialized. Use `"+e.memberName+",` in enum `"+t+"`."},EnumInvalidMemberInitializerUnknownType:function(e){var t=e.enumName;return"The enum member initializer for `"+e.memberName+"` needs to be a literal (either a boolean, number, or string) in enum `"+t+"`."},EnumInvalidMemberName:function(e){var t=e.enumName;return"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `"+e.memberName+"`, consider using `"+e.suggestion+"`, in enum `"+t+"`."},EnumNumberMemberNotInitialized:function(e){var t=e.enumName;return"Number enum members need to be initialized, e.g. `"+e.memberName+" = 1` in enum `"+t+"`."},EnumStringMemberInconsistentlyInitialized:function(e){return"String enum members need to consistently either all use initializers, or use no initializers, in enum `"+e.enumName+"`."},GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` or `typeof` keyword.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:Object.assign({message:"A binding pattern parameter cannot be optional in an implementation signature."},{reasonCode:"OptionalBindingPattern"}),SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:function(e){return"Unexpected reserved type "+e.reservedType+"."},UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.",UnsupportedDeclareExportKind:function(e){return"`declare export "+e.unsupportedExportKind+"` is not supported. Use `"+e.suggestion+"` instead."},UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function jx(e){return"type"===e.importKind||"typeof"===e.importKind}var wx={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};var Ex=/\*?\s*@((?:no)?flow)\b/,Sx={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xa0",iexcl:"\xa1",cent:"\xa2",pound:"\xa3",curren:"\xa4",yen:"\xa5",brvbar:"\xa6",sect:"\xa7",uml:"\xa8",copy:"\xa9",ordf:"\xaa",laquo:"\xab",not:"\xac",shy:"\xad",reg:"\xae",macr:"\xaf",deg:"\xb0",plusmn:"\xb1",sup2:"\xb2",sup3:"\xb3",acute:"\xb4",micro:"\xb5",para:"\xb6",middot:"\xb7",cedil:"\xb8",sup1:"\xb9",ordm:"\xba",raquo:"\xbb",frac14:"\xbc",frac12:"\xbd",frac34:"\xbe",iquest:"\xbf",Agrave:"\xc0",Aacute:"\xc1",Acirc:"\xc2",Atilde:"\xc3",Auml:"\xc4",Aring:"\xc5",AElig:"\xc6",Ccedil:"\xc7",Egrave:"\xc8",Eacute:"\xc9",Ecirc:"\xca",Euml:"\xcb",Igrave:"\xcc",Iacute:"\xcd",Icirc:"\xce",Iuml:"\xcf",ETH:"\xd0",Ntilde:"\xd1",Ograve:"\xd2",Oacute:"\xd3",Ocirc:"\xd4",Otilde:"\xd5",Ouml:"\xd6",times:"\xd7",Oslash:"\xd8",Ugrave:"\xd9",Uacute:"\xda",Ucirc:"\xdb",Uuml:"\xdc",Yacute:"\xdd",THORN:"\xde",szlig:"\xdf",agrave:"\xe0",aacute:"\xe1",acirc:"\xe2",atilde:"\xe3",auml:"\xe4",aring:"\xe5",aelig:"\xe6",ccedil:"\xe7",egrave:"\xe8",eacute:"\xe9",ecirc:"\xea",euml:"\xeb",igrave:"\xec",iacute:"\xed",icirc:"\xee",iuml:"\xef",eth:"\xf0",ntilde:"\xf1",ograve:"\xf2",oacute:"\xf3",ocirc:"\xf4",otilde:"\xf5",ouml:"\xf6",divide:"\xf7",oslash:"\xf8",ugrave:"\xf9",uacute:"\xfa",ucirc:"\xfb",uuml:"\xfc",yacute:"\xfd",thorn:"\xfe",yuml:"\xff",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02c6",tilde:"\u02dc",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039a",Lambda:"\u039b",Mu:"\u039c",Nu:"\u039d",Xi:"\u039e",Omicron:"\u039f",Pi:"\u03a0",Rho:"\u03a1",Sigma:"\u03a3",Tau:"\u03a4",Upsilon:"\u03a5",Phi:"\u03a6",Chi:"\u03a7",Psi:"\u03a8",Omega:"\u03a9",alpha:"\u03b1",beta:"\u03b2",gamma:"\u03b3",delta:"\u03b4",epsilon:"\u03b5",zeta:"\u03b6",eta:"\u03b7",theta:"\u03b8",iota:"\u03b9",kappa:"\u03ba",lambda:"\u03bb",mu:"\u03bc",nu:"\u03bd",xi:"\u03be",omicron:"\u03bf",pi:"\u03c0",rho:"\u03c1",sigmaf:"\u03c2",sigma:"\u03c3",tau:"\u03c4",upsilon:"\u03c5",phi:"\u03c6",chi:"\u03c7",psi:"\u03c8",omega:"\u03c9",thetasym:"\u03d1",upsih:"\u03d2",piv:"\u03d6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200c",zwj:"\u200d",lrm:"\u200e",rlm:"\u200f",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201a",ldquo:"\u201c",rdquo:"\u201d",bdquo:"\u201e",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203a",oline:"\u203e",frasl:"\u2044",euro:"\u20ac",image:"\u2111",weierp:"\u2118",real:"\u211c",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21b5",lArr:"\u21d0",uArr:"\u21d1",rArr:"\u21d2",dArr:"\u21d3",hArr:"\u21d4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220b",prod:"\u220f",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221a",prop:"\u221d",infin:"\u221e",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222a",int:"\u222b",there4:"\u2234",sim:"\u223c",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22a5",sdot:"\u22c5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230a",rfloor:"\u230b",lang:"\u2329",rang:"\u232a",loz:"\u25ca",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},Tx=new RegExp(/\r\n|[\r\n\u2028\u2029]/.source,"g");function Px(e){switch(e){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Ax(e,t,r){for(var a=t;a."},MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:function(e){var t=e.unexpected;return"Unexpected token `"+t+"`. Did you mean `"+e.HTMLEntity+"` or `{'"+t+"'}`?"},UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?"});function Ox(e){return!!e&&("JSXOpeningFragment"===e.type||"JSXClosingFragment"===e.type)}function Nx(e){if("JSXIdentifier"===e.type)return e.name;if("JSXNamespacedName"===e.type)return e.namespace.name+":"+e.name.name;if("JSXMemberExpression"===e.type)return Nx(e.object)+"."+Nx(e.property);throw new Error("Node had unexpected type: "+e.type)}var Bx=function(e){function t(){for(var t,r=arguments.length,a=new Array(r),n=0;n1)for(var a=0;a0?!(a&Fb)||!!(a&Lb)!==(4&n)>0:a&Mb&&(8&n)>0?!!(t.names.get(r)&gx)&&!!(a&Ib):!!(a&Db&&(1&n)>0)||e.prototype.isRedeclaredInScope.call(this,t,r,a)},r.checkLocalExport=function(t){var r=t.name;if(!this.hasImport(r)){for(var a=this.scopeStack.length-1;a>=0;a--){var n=this.scopeStack[a].tsNames.get(r);if((1&n)>0||(16&n)>0)return}e.prototype.checkLocalExport.call(this,t)}},o(t)}(hx),Fx=0,Lx=1,Ux=2,qx=4,Gx=8,Wx=function(){function e(){this.stacks=[]}var t=e.prototype;return t.enter=function(e){this.stacks.push(e)},t.exit=function(){this.stacks.pop()},t.currentFlags=function(){return this.stacks[this.stacks.length-1]},o(e,[{key:"hasAwait",get:function(){return(this.currentFlags()&Ux)>0}},{key:"hasYield",get:function(){return(this.currentFlags()&Lx)>0}},{key:"hasReturn",get:function(){return(this.currentFlags()&qx)>0}},{key:"hasIn",get:function(){return(this.currentFlags()&Gx)>0}}])}();function Vx(e,t){return(e?Ux:0)|(t?Lx:0)}var Hx=function(){function e(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}var t=e.prototype;return t.sourceToOffsetPos=function(e){return e+this.startIndex},t.offsetToSourcePos=function(e){return e-this.startIndex},t.hasPlugin=function(e){if("string"==typeof e)return this.plugins.has(e);var t=e[0],r=e[1];if(!this.hasPlugin(t))return!1;for(var a=this.plugins.get(t),n=0,s=Object.keys(r);n0;)a=t[--n];null===a||a.start>r.start?zx(e,r.comments):Kx(a,r.comments)}var Jx=function(e){function t(){return e.apply(this,arguments)||this}c(t,e);var r=t.prototype;return r.addComment=function(e){this.filename&&(e.loc.filename=this.filename);var t=this.state.commentsLen;this.comments.length!==t&&(this.comments.length=t),this.comments.push(e),this.state.commentsLen++},r.processComment=function(e){var t=this.state.commentStack,r=t.length;if(0!==r){var a=r-1,n=t[a];n.start===e.end&&(n.leadingNode=e,a--);for(var s=e.start;a>=0;a--){var o=t[a],i=o.end;if(!(i>s)){i===s&&(o.trailingNode=e);break}o.containingNode=e,this.finalizeComment(o),t.splice(a,1)}}},r.finalizeComment=function(e){var t,r=e.comments;if(null!==e.leadingNode||null!==e.trailingNode)null!==e.leadingNode&&Kx(e.leadingNode,r),null!==e.trailingNode&&function(e,t){var r;void 0===e.leadingComments?e.leadingComments=t:(r=e.leadingComments).unshift.apply(r,t)}(e.trailingNode,r);else{var a=e.containingNode,n=e.start;if(44===this.input.charCodeAt(this.offsetToSourcePos(n)-1))switch(a.type){case"ObjectExpression":case"ObjectPattern":case"RecordExpression":Xx(a,a.properties,e);break;case"CallExpression":case"OptionalCallExpression":Xx(a,a.arguments,e);break;case"ImportExpression":Xx(a,[a.source,null!=(t=a.options)?t:null],e);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":Xx(a,a.params,e);break;case"ArrayExpression":case"ArrayPattern":case"TupleExpression":Xx(a,a.elements,e);break;case"ExportNamedDeclaration":case"ImportDeclaration":Xx(a,a.specifiers,e);break;case"TSEnumDeclaration":case"TSEnumBody":Xx(a,a.members,e);break;default:zx(a,r)}else zx(a,r)}},r.finalizeRemainingComments=function(){for(var e=this.state.commentStack,t=e.length-1;t>=0;t--)this.finalizeComment(e[t]);this.state.commentStack=[]},r.resetPreviousNodeTrailingComments=function(e){var t=this.state.commentStack,r=t.length;if(0!==r){var a=t[r-1];a.leadingNode===e&&(a.leadingNode=null)}},r.takeSurroundingComments=function(e,t,r){var a=this.state.commentStack,n=a.length;if(0!==n)for(var s=n-1;s>=0;s--){var o=a[s],i=o.end;if(o.start===r)o.leadingNode=e;else if(i===t)o.trailingNode=e;else if(i0},set:function(e){e?this.flags|=1:this.flags&=-2}},{key:"maybeInArrowParameters",get:function(){return(2&this.flags)>0},set:function(e){e?this.flags|=2:this.flags&=-3}},{key:"inType",get:function(){return(4&this.flags)>0},set:function(e){e?this.flags|=4:this.flags&=-5}},{key:"noAnonFunctionType",get:function(){return(8&this.flags)>0},set:function(e){e?this.flags|=8:this.flags&=-9}},{key:"hasFlowComment",get:function(){return(16&this.flags)>0},set:function(e){e?this.flags|=16:this.flags&=-17}},{key:"isAmbientContext",get:function(){return(32&this.flags)>0},set:function(e){e?this.flags|=32:this.flags&=-33}},{key:"inAbstractClass",get:function(){return(64&this.flags)>0},set:function(e){e?this.flags|=64:this.flags&=-65}},{key:"inDisallowConditionalTypesContext",get:function(){return(128&this.flags)>0},set:function(e){e?this.flags|=128:this.flags&=-129}},{key:"soloAwait",get:function(){return(256&this.flags)>0},set:function(e){e?this.flags|=256:this.flags&=-257}},{key:"inFSharpPipelineDirectBody",get:function(){return(512&this.flags)>0},set:function(e){e?this.flags|=512:this.flags&=-513}},{key:"canStartJSXElement",get:function(){return(1024&this.flags)>0},set:function(e){e?this.flags|=1024:this.flags&=-1025}},{key:"containsEsc",get:function(){return(2048&this.flags)>0},set:function(e){e?this.flags|=2048:this.flags&=-2049}},{key:"hasTopLevelAwait",get:function(){return(4096&this.flags)>0},set:function(e){e?this.flags|=4096:this.flags&=-4097}}])}();function Zx(e,t,r){return new sh(r,e-t,e)}var ev=new Set([103,109,115,105,121,117,100,118]),tv=o((function(e){var t=e.startIndex||0;this.type=e.type,this.value=e.value,this.start=t+e.start,this.end=t+e.end,this.loc=new oh(e.startLoc,e.endLoc)})),rv=function(e){function t(t,r){var a;return(a=e.call(this)||this).isLookahead=void 0,a.tokens=[],a.errorHandlers_readInt={invalidDigit:function(e,t,r,n){return!!(a.optionFlags&Ih)&&(a.raise(vh.InvalidDigit,Zx(e,t,r),{radix:n}),!0)},numericSeparatorInEscapeSequence:a.errorBuilder(vh.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:a.errorBuilder(vh.UnexpectedNumericSeparator)},a.errorHandlers_readCodePoint=Object.assign({},a.errorHandlers_readInt,{invalidEscapeSequence:a.errorBuilder(vh.InvalidEscapeSequence),invalidCodePoint:a.errorBuilder(vh.InvalidCodePoint)}),a.errorHandlers_readStringContents_string=Object.assign({},a.errorHandlers_readCodePoint,{strictNumericEscape:function(e,t,r){a.recordStrictModeErrors(vh.StrictNumericEscape,Zx(e,t,r))},unterminated:function(e,t,r){throw a.raise(vh.UnterminatedString,Zx(e-1,t,r))}}),a.errorHandlers_readStringContents_template=Object.assign({},a.errorHandlers_readCodePoint,{strictNumericEscape:a.errorBuilder(vh.StrictNumericEscape),unterminated:function(e,t,r){throw a.raise(vh.UnterminatedTemplate,Zx(e,t,r))}}),a.state=new Qx,a.state.init(t),a.input=r,a.length=r.length,a.comments=[],a.isLookahead=!1,a}c(t,e);var r=t.prototype;return r.pushToken=function(e){this.tokens.length=this.state.tokensLength,this.tokens.push(e),++this.state.tokensLength},r.next=function(){this.checkKeywordEscapes(),this.optionFlags&kh&&this.pushToken(new tv(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},r.eat=function(e){return!!this.match(e)&&(this.next(),!0)},r.match=function(e){return this.state.type===e},r.createLookaheadState=function(e){return{pos:e.pos,value:null,type:e.type,start:e.start,end:e.end,context:[this.curContext()],inType:e.inType,startLoc:e.startLoc,lastTokEndLoc:e.lastTokEndLoc,curLine:e.curLine,lineStart:e.lineStart,curPosition:e.curPosition}},r.lookahead=function(){var e=this.state;this.state=this.createLookaheadState(e),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;var t=this.state;return this.state=e,t},r.nextTokenStart=function(){return this.nextTokenStartSince(this.state.pos)},r.nextTokenStartSince=function(e){return Cx.lastIndex=e,Cx.test(this.input)?Cx.lastIndex:e},r.lookaheadCharCode=function(){return this.lookaheadCharCodeSince(this.state.pos)},r.lookaheadCharCodeSince=function(e){return this.input.charCodeAt(this.nextTokenStartSince(e))},r.nextTokenInLineStart=function(){return this.nextTokenInLineStartSince(this.state.pos)},r.nextTokenInLineStartSince=function(e){return _x.lastIndex=e,_x.test(this.input)?_x.lastIndex:e},r.lookaheadInLineCharCode=function(){return this.input.charCodeAt(this.nextTokenInLineStart())},r.codePointAtPos=function(e){var t=this.input.charCodeAt(e);if(55296==(64512&t)&&++e=this.length?this.finishToken(140):this.getTokenFromCode(this.codePointAtPos(this.state.pos))},r.skipBlockComment=function(e){var t;this.isLookahead||(t=this.state.curPosition());var r=this.state.pos,a=this.input.indexOf(e,r+2);if(-1===a)throw this.raise(vh.UnterminatedComment,this.state.curPosition());for(this.state.pos=a+e.length,Tx.lastIndex=r+2;Tx.test(this.input)&&Tx.lastIndex<=a;)++this.state.curLine,this.state.lineStart=Tx.lastIndex;if(!this.isLookahead){var n={type:"CommentBlock",value:this.input.slice(r+2,a),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(a+e.length),loc:new oh(t,this.state.curPosition())};return this.optionFlags&kh&&this.pushToken(n),n}},r.skipLineComment=function(e){var t,r=this.state.pos;this.isLookahead||(t=this.state.curPosition());var a=this.input.charCodeAt(this.state.pos+=e);if(this.state.pose))break e;var o=this.skipLineComment(3);void 0!==o&&(this.addComment(o),null==t||t.push(o))}else{if(60!==r||this.inModule||!(this.optionFlags&Oh))break e;var i=this.state.pos;if(33!==this.input.charCodeAt(i+1)||45!==this.input.charCodeAt(i+2)||45!==this.input.charCodeAt(i+3))break e;var d=this.skipLineComment(4);void 0!==d&&(this.addComment(d),null==t||t.push(d))}}}if((null==t?void 0:t.length)>0){var c=this.state.pos,l={start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(c),comments:t,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(l)}},r.finishToken=function(e,t){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var r=this.state.type;this.state.type=e,this.state.value=t,this.isLookahead||this.updateContext(r)},r.replaceToken=function(e){this.state.type=e,this.updateContext()},r.readToken_numberSign=function(){if(0!==this.state.pos||!this.readToken_interpreter()){var e=this.state.pos+1,t=this.codePointAtPos(e);if(t>=48&&t<=57)throw this.raise(vh.UnexpectedDigitAfterHash,this.state.curPosition());if(123===t||91===t&&this.hasPlugin("recordAndTuple")){if(this.expectPlugin("recordAndTuple"),"bar"===this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(123===t?vh.RecordExpressionHashIncorrectStartSyntaxType:vh.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,123===t?this.finishToken(7):this.finishToken(1)}else Ur(t)?(++this.state.pos,this.finishToken(139,this.readWord1(t))):92===t?(++this.state.pos,this.finishToken(139,this.readWord1())):this.finishOp(27,1)}},r.readToken_dot=function(){var e=this.input.charCodeAt(this.state.pos+1);e>=48&&e<=57?this.readNumber(!0):46===e&&46===this.input.charCodeAt(this.state.pos+2)?(this.state.pos+=3,this.finishToken(21)):(++this.state.pos,this.finishToken(16))},r.readToken_slash=function(){61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(31,2):this.finishOp(56,1)},r.readToken_interpreter=function(){if(0!==this.state.pos||this.length<2)return!1;var e=this.input.charCodeAt(this.state.pos+1);if(33!==e)return!1;var t=this.state.pos;for(this.state.pos+=1;!Px(e)&&++this.state.pos=48&&t<=57?(++this.state.pos,this.finishToken(17)):(this.state.pos+=2,this.finishToken(18))},r.getTokenFromCode=function(e){switch(e){case 46:return void this.readToken_dot();case 40:return++this.state.pos,void this.finishToken(10);case 41:return++this.state.pos,void this.finishToken(11);case 59:return++this.state.pos,void this.finishToken(13);case 44:return++this.state.pos,void this.finishToken(12);case 91:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(vh.TupleExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(2)}else++this.state.pos,this.finishToken(0);return;case 93:return++this.state.pos,void this.finishToken(3);case 123:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(vh.RecordExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(6)}else++this.state.pos,this.finishToken(5);return;case 125:return++this.state.pos,void this.finishToken(8);case 58:return void(this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(15,2):(++this.state.pos,this.finishToken(14)));case 63:return void this.readToken_question();case 96:return void this.readTemplateToken();case 48:var t=this.input.charCodeAt(this.state.pos+1);if(120===t||88===t)return void this.readRadixNumber(16);if(111===t||79===t)return void this.readRadixNumber(8);if(98===t||66===t)return void this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return void this.readNumber(!1);case 34:case 39:return void this.readString(e);case 47:return void this.readToken_slash();case 37:case 42:return void this.readToken_mult_modulo(e);case 124:case 38:return void this.readToken_pipe_amp(e);case 94:return void this.readToken_caret();case 43:case 45:return void this.readToken_plus_min(e);case 60:return void this.readToken_lt();case 62:return void this.readToken_gt();case 61:case 33:return void this.readToken_eq_excl(e);case 126:return void this.finishOp(36,1);case 64:return void this.readToken_atSign();case 35:return void this.readToken_numberSign();case 92:return void this.readWord();default:if(Ur(e))return void this.readWord(e)}throw this.raise(vh.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(e)})},r.finishOp=function(e,t){var r=this.input.slice(this.state.pos,this.state.pos+t);this.state.pos+=t,this.finishToken(e,r)},r.readRegexp=function(){for(var e,t,r=this.state.startLoc,a=this.state.start+1,n=this.state.pos;;++n){if(n>=this.length)throw this.raise(vh.UnterminatedRegExp,ih(r,1));var s=this.input.charCodeAt(n);if(Px(s))throw this.raise(vh.UnterminatedRegExp,ih(r,1));if(e)e=!1;else{if(91===s)t=!0;else if(93===s&&t)t=!1;else if(47===s&&!t)break;e=92===s}}var o=this.input.slice(a,n);++n;for(var i="",d=function(){return ih(r,n+2-a)};n=2&&48===this.input.charCodeAt(t);if(i){var d=this.input.slice(t,this.state.pos);if(this.recordStrictModeErrors(vh.StrictOctalLiteral,r),!this.state.strict){var c=d.indexOf("_");c>0&&this.raise(vh.ZeroDigitNumericSeparator,ih(r,c))}o=i&&!/[89]/.test(d)}var l=this.input.charCodeAt(this.state.pos);if(46!==l||o||(++this.state.pos,this.readInt(10),a=!0,l=this.input.charCodeAt(this.state.pos)),69!==l&&101!==l||o||(43!==(l=this.input.charCodeAt(++this.state.pos))&&45!==l||++this.state.pos,null===this.readInt(10)&&this.raise(vh.InvalidOrMissingExponent,r),a=!0,s=!0,l=this.input.charCodeAt(this.state.pos)),110===l&&((a||i)&&this.raise(vh.InvalidBigIntLiteral,r),++this.state.pos,n=!0),109===l){this.expectPlugin("decimal",this.state.curPosition()),(s||i)&&this.raise(vh.InvalidDecimal,r),++this.state.pos;var u=!0}if(Ur(this.codePointAtPos(this.state.pos)))throw this.raise(vh.NumberIdentifier,this.state.curPosition());var p=this.input.slice(t,this.state.pos).replace(/[_mn]/g,"");if(n)this.finishToken(136,p);else if(u)this.finishToken(137,p);else{var f=o?parseInt(p,8):parseFloat(p);this.finishToken(135,f)}},r.readCodePoint=function(e){var t=da(this.input,this.state.pos,this.state.lineStart,this.state.curLine,e,this.errorHandlers_readCodePoint),r=t.code,a=t.pos;return this.state.pos=a,r},r.readString=function(e){var t=aa(34===e?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string),r=t.str,a=t.pos,n=t.curLine,s=t.lineStart;this.state.pos=a+1,this.state.lineStart=s,this.state.curLine=n,this.finishToken(134,r)},r.readTemplateContinuation=function(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken()},r.readTemplateToken=function(){var e=this.input[this.state.pos],t=aa("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template),r=t.str,a=t.firstInvalidLoc,n=t.pos,s=t.curLine,o=t.lineStart;this.state.pos=n+1,this.state.lineStart=o,this.state.curLine=s,a&&(this.state.firstInvalidTemplateEscapePos=new sh(a.curLine,a.pos-a.lineStart,this.sourceToOffsetPos(a.pos))),96===this.input.codePointAt(n)?this.finishToken(24,a?null:e+r+"`"):(this.state.pos++,this.finishToken(25,a?null:e+r+"${"))},r.recordStrictModeErrors=function(e,t){var r=t.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(e,t):this.state.strictErrors.set(r,[e,t])},r.readWord1=function(e){this.state.containsEsc=!1;var t="",r=this.state.pos,a=this.state.pos;for(void 0!==e&&(this.state.pos+=e<=65535?1:2);this.state.pos=0;o--){var i=s[o];if(i.loc.index===n)return s[o]=e(a,r);if(i.loc.indext.errors.length){var n=this.state;return this.state=t,this.state.tokensLength=n.tokensLength,{node:a,error:n.errors[t.errors.length],thrown:!1,aborted:!1,failState:n}}return{node:a,error:null,thrown:!1,aborted:!1,failState:null}}catch(e){var s=this.state;if(this.state=t,e instanceof SyntaxError)return{node:null,error:e,thrown:!0,aborted:!1,failState:s};if(e===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:s};throw e}},r.checkExpressionErrors=function(e,t){if(!e)return!1;var r=e.shorthandAssignLoc,a=e.doubleProtoLoc,n=e.privateKeyLoc,s=e.optionalParametersLoc,o=e.voidPatternLoc;if(!t)return!!(r||a||s||n||o);null!=r&&this.raise(vh.InvalidCoverInitializedName,r),null!=a&&this.raise(vh.DuplicateProto,a),null!=n&&this.raise(vh.UnexpectedPrivateField,n),null!=s&&this.unexpected(s),null!=o&&this.raise(vh.InvalidCoverDiscardElement,o)},r.isLiteralPropertyName=function(){return ib(this.state.type)},r.isPrivateName=function(e){return"PrivateName"===e.type},r.getPrivateNameSV=function(e){return e.id.name},r.hasPropertyAsPrivateName=function(e){return("MemberExpression"===e.type||"OptionalMemberExpression"===e.type)&&this.isPrivateName(e.property)},r.isObjectProperty=function(e){return"ObjectProperty"===e.type},r.isObjectMethod=function(e){return"ObjectMethod"===e.type},r.initializeScopes=function(e){var t=this;void 0===e&&(e="module"===this.options.sourceType);var r=this.state.labels;this.state.labels=[];var a=this.exportedIdentifiers;this.exportedIdentifiers=new Set;var n=this.inModule;this.inModule=e;var s=this.scope,o=this.getScopeHandler();this.scope=new o(this,e);var i=this.prodParam;this.prodParam=new Wx;var d=this.classScope;this.classScope=new nv(this);var c=this.expressionScope;return this.expressionScope=new iv(this),function(){t.state.labels=r,t.exportedIdentifiers=a,t.inModule=n,t.scope=s,t.prodParam=i,t.classScope=d,t.expressionScope=c}},r.enterInitialScopes=function(){var e=Fx;(this.inModule||this.optionFlags&Rh)&&(e|=Ux),this.optionFlags&Th&&(e|=Lx);var t=!this.inModule&&"commonjs"===this.options.sourceType;(t||this.optionFlags&jh)&&(e|=qx),this.prodParam.enter(e);var r=t?kb:bb;this.optionFlags&wh&&(r|=Pb),this.scope.enter(r)},r.checkDestructuringPrivate=function(e){var t=e.privateKeyLoc;null!==t&&this.expectPlugin("destructuringPrivate",t)},o(t)}(rv),lv=o((function(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null})),uv=o((function(e,t,r){this.type="",this.start=t,this.end=0,this.loc=new oh(r),(null==e?void 0:e.optionFlags)&Ah&&(this.range=[t,0]),null!=e&&e.filename&&(this.loc.filename=e.filename)})),pv=uv.prototype;pv.__clone=function(){for(var e=new uv(void 0,this.start,this.loc.start),t=Object.keys(this),r=0,a=t.length;r() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:function(e){var t=e.typeParameterName;return"Single type parameter "+t+" should have a trailing comma. Example usage: <"+t+",>."},StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:function(e){return"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got "+e.type+"."},UsingDeclarationInAmbientContext:function(e){return"'"+e+"' declarations are not allowed in ambient contexts."}});function jv(e){return"private"===e||"public"===e||"protected"===e}function wv(e){return"in"===e||"out"===e}var Ev,Sv=0,Tv=1,Pv=2;function Av(e){if("MemberExpression"!==e.type)return!1;var t=e.computed,r=e.property;return(!t||"StringLiteral"===r.type||!("TemplateLiteral"!==r.type||r.expressions.length>0))&&_v(e.object)}function kv(e,t){var r,a=e.type;if(null!=(r=e.extra)&&r.parenthesized)return!1;if(t){if("Literal"===a){var n=e.value;if("string"==typeof n||"boolean"==typeof n)return!0}}else if("StringLiteral"===a||"BooleanLiteral"===a)return!0;return!(!Cv(e,t)&&!function(e,t){if("UnaryExpression"===e.type){var r=e.operator,a=e.argument;if("-"===r&&Cv(a,t))return!0}return!1}(e,t))||("TemplateLiteral"===a&&0===e.expressions.length||!!Av(e))}function Cv(e,t){return t?"Literal"===e.type&&("number"==typeof e.value||"bigint"in e):"NumericLiteral"===e.type||"BigIntLiteral"===e.type}function _v(e){return"Identifier"===e.type||"MemberExpression"===e.type&&!e.computed&&_v(e.object)}var Iv=xh(Ev||(Ev=h(["placeholders"])))({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),Dv=["minimal","fsharp","hack","smart"],Ov=["^^","@@","^","%","#"];var Nv={estree:function(e){return function(e){function t(){return e.apply(this,arguments)||this}c(t,e);var r=t.prototype;return r.parse=function(){var t=Mh(e.prototype.parse.call(this));return this.optionFlags&kh&&(t.tokens=t.tokens.map(Mh)),t},r.parseRegExpLiteral=function(e){var t=e.pattern,r=e.flags,a=null;try{a=new RegExp(t,r)}catch(e){}var n=this.estreeParseLiteral(a);return n.regex={pattern:t,flags:r},n},r.parseBigIntLiteral=function(e){var t;try{t=BigInt(e)}catch(e){t=null}var r=this.estreeParseLiteral(t);return r.bigint=String(r.value||e),r},r.parseDecimalLiteral=function(e){var t=this.estreeParseLiteral(null);return t.decimal=String(t.value||e),t},r.estreeParseLiteral=function(e){return this.parseLiteral(e,"Literal")},r.parseStringLiteral=function(e){return this.estreeParseLiteral(e)},r.parseNumericLiteral=function(e){return this.estreeParseLiteral(e)},r.parseNullLiteral=function(){return this.estreeParseLiteral(null)},r.parseBooleanLiteral=function(e){return this.estreeParseLiteral(e)},r.estreeParseChainExpression=function(e,t){var r=this.startNodeAtNode(e);return r.expression=e,this.finishNodeAt(r,"ChainExpression",t)},r.directiveToStmt=function(e){var t=e.value;delete e.value,this.castNodeTo(t,"Literal"),t.raw=t.extra.raw,t.value=t.extra.expressionValue;var r=this.castNodeTo(e,"ExpressionStatement");return r.expression=t,r.directive=t.extra.rawValue,delete t.extra,r},r.fillOptionalPropertiesForTSESLint=function(e){},r.cloneEstreeStringLiteral=function(e){var t=e.start,r=e.end,a=e.loc,n=e.range,s=e.raw,o=e.value,i=Object.create(e.constructor.prototype);return i.type="Literal",i.start=t,i.end=r,i.loc=a,i.range=n,i.raw=s,i.value=o,i},r.initFunction=function(t,r){e.prototype.initFunction.call(this,t,r),t.expression=!1},r.checkDeclaration=function(t){null!=t&&this.isObjectProperty(t)?this.checkDeclaration(t.value):e.prototype.checkDeclaration.call(this,t)},r.getObjectOrClassMethodParams=function(e){return e.value.params},r.isValidDirective=function(e){var t;return"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&!(null!=(t=e.expression.extra)&&t.parenthesized)},r.parseBlockBody=function(t,r,a,n,s){var o=this;e.prototype.parseBlockBody.call(this,t,r,a,n,s);var i=t.directives.map((function(e){return o.directiveToStmt(e)}));t.body=i.concat(t.body),delete t.directives},r.parsePrivateName=function(){var t=e.prototype.parsePrivateName.call(this);return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(t):t},r.convertPrivateNameToPrivateIdentifier=function(t){var r=e.prototype.getPrivateNameSV.call(this,t);return delete t.id,t.name=r,this.castNodeTo(t,"PrivateIdentifier")},r.isPrivateName=function(t){return this.getPluginOption("estree","classFeatures")?"PrivateIdentifier"===t.type:e.prototype.isPrivateName.call(this,t)},r.getPrivateNameSV=function(t){return this.getPluginOption("estree","classFeatures")?t.name:e.prototype.getPrivateNameSV.call(this,t)},r.parseLiteral=function(t,r){var a=e.prototype.parseLiteral.call(this,t,r);return a.raw=a.extra.raw,delete a.extra,a},r.parseFunctionBody=function(t,r,a){void 0===a&&(a=!1),e.prototype.parseFunctionBody.call(this,t,r,a),t.expression="BlockStatement"!==t.body.type},r.parseMethod=function(t,r,a,n,s,o,i){void 0===i&&(i=!1);var d=this.startNode();d.kind=t.kind,delete(d=e.prototype.parseMethod.call(this,d,r,a,n,s,o,i)).kind;var c=t.typeParameters;c&&(delete t.typeParameters,d.typeParameters=c,this.resetStartLocationFromNode(d,c));var l=this.castNodeTo(d,"FunctionExpression");return t.value=l,"ClassPrivateMethod"===o&&(t.computed=!1),"ObjectMethod"===o?("method"===t.kind&&(t.kind="init"),t.shorthand=!1,this.finishNode(t,"Property")):this.finishNode(t,"MethodDefinition")},r.nameIsConstructor=function(t){return"Literal"===t.type?"constructor"===t.value:e.prototype.nameIsConstructor.call(this,t)},r.parseClassProperty=function(){for(var t,r=arguments.length,a=new Array(r),n=0;n0&&o.start===n.start&&this.resetStartLocation(n,a)}return n},r.stopParseSubscript=function(t,r){var a=e.prototype.stopParseSubscript.call(this,t,r);return r.optionalChainMember?this.estreeParseChainExpression(a,t.loc.end):a},r.parseMember=function(t,r,a,n,s){var o=e.prototype.parseMember.call(this,t,r,a,n,s);return"OptionalMemberExpression"===o.type?this.castNodeTo(o,"MemberExpression"):o.optional=!1,o},r.isOptionalMemberExpression=function(t){return"ChainExpression"===t.type?"MemberExpression"===t.expression.type:e.prototype.isOptionalMemberExpression.call(this,t)},r.hasPropertyAsPrivateName=function(t){return"ChainExpression"===t.type&&(t=t.expression),e.prototype.hasPropertyAsPrivateName.call(this,t)},r.isObjectProperty=function(e){return"Property"===e.type&&"init"===e.kind&&!e.method},r.isObjectMethod=function(e){return"Property"===e.type&&(e.method||"get"===e.kind||"set"===e.kind)},r.castNodeTo=function(t,r){var a=e.prototype.castNodeTo.call(this,t,r);return this.fillOptionalPropertiesForTSESLint(a),a},r.cloneIdentifier=function(t){var r=e.prototype.cloneIdentifier.call(this,t);return this.fillOptionalPropertiesForTSESLint(r),r},r.cloneStringLiteral=function(t){return"Literal"===t.type?this.cloneEstreeStringLiteral(t):e.prototype.cloneStringLiteral.call(this,t)},r.finishNodeAt=function(t,r,a){return Mh(e.prototype.finishNodeAt.call(this,t,r,a))},r.finishNode=function(t,r){var a=e.prototype.finishNode.call(this,t,r);return this.fillOptionalPropertiesForTSESLint(a),a},r.resetStartLocation=function(t,r){e.prototype.resetStartLocation.call(this,t,r),Mh(t)},r.resetEndLocation=function(t,r){void 0===r&&(r=this.state.lastTokEndLoc),e.prototype.resetEndLocation.call(this,t,r),Mh(t)},o(t)}(e)},jsx:function(e){return function(e){function t(){return e.apply(this,arguments)||this}c(t,e);var r=t.prototype;return r.jsxReadToken=function(){for(var t="",r=this.state.pos;;){if(this.state.pos>=this.length)throw this.raise(Dx.UnterminatedJsxContent,this.state.startLoc);var a=this.input.charCodeAt(this.state.pos);switch(a){case 60:case 123:return this.state.pos===this.state.start?void(60===a&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(143)):e.prototype.getTokenFromCode.call(this,a)):(t+=this.input.slice(r,this.state.pos),void this.finishToken(142,t));case 38:t+=this.input.slice(r,this.state.pos),t+=this.jsxReadEntity(),r=this.state.pos;break;default:Px(a)?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadNewLine(!0),r=this.state.pos):++this.state.pos}}},r.jsxReadNewLine=function(e){var t,r=this.input.charCodeAt(this.state.pos);return++this.state.pos,13===r&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,t=e?"\n":"\r\n"):t=String.fromCharCode(r),++this.state.curLine,this.state.lineStart=this.state.pos,t},r.jsxReadString=function(e){for(var t="",r=++this.state.pos;;){if(this.state.pos>=this.length)throw this.raise(vh.UnterminatedString,this.state.startLoc);var a=this.input.charCodeAt(this.state.pos);if(a===e)break;38===a?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadEntity(),r=this.state.pos):Px(a)?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadNewLine(!1),r=this.state.pos):++this.state.pos}t+=this.input.slice(r,this.state.pos++),this.finishToken(134,t)},r.jsxReadEntity=function(){var e=++this.state.pos;if(35===this.codePointAtPos(this.state.pos)){++this.state.pos;var t=10;120===this.codePointAtPos(this.state.pos)&&(t=16,++this.state.pos);var r=this.readInt(t,void 0,!1,"bail");if(null!==r&&59===this.codePointAtPos(this.state.pos))return++this.state.pos,String.fromCodePoint(r)}else{for(var a=0,n=!1;a++<10&&this.state.posr.index+1&&this.raise(Rx.UnexpectedSpaceBetweenModuloChecks,r),this.eat(10)?(t.value=e.prototype.parseExpression.call(this),this.expect(11),this.finishNode(t,"DeclaredPredicate")):this.finishNode(t,"InferredPredicate")},r.flowParseTypeAndPredicateInitialiser=function(){var e=this.state.inType;this.state.inType=!0,this.expect(14);var t=null,r=null;return this.match(54)?(this.state.inType=e,r=this.flowParsePredicate()):(t=this.flowParseType(),this.state.inType=e,this.match(54)&&(r=this.flowParsePredicate())),[t,r]},r.flowParseDeclareClass=function(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},r.flowParseDeclareFunction=function(e){this.next();var t=e.id=this.parseIdentifier(),r=this.startNode(),a=this.startNode();this.match(47)?r.typeParameters=this.flowParseTypeParameterDeclaration():r.typeParameters=null,this.expect(10);var n=this.flowParseFunctionTypeParams();r.params=n.params,r.rest=n.rest,r.this=n._this,this.expect(11);var s=this.flowParseTypeAndPredicateInitialiser();return r.returnType=s[0],e.predicate=s[1],a.typeAnnotation=this.finishNode(r,"FunctionTypeAnnotation"),t.typeAnnotation=this.finishNode(a,"TypeAnnotation"),this.resetEndLocation(t),this.semicolon(),this.scope.declareName(e.id.name,sx,e.id.loc.start),this.finishNode(e,"DeclareFunction")},r.flowParseDeclare=function(e,t){return this.match(80)?this.flowParseDeclareClass(e):this.match(68)?this.flowParseDeclareFunction(e):this.match(74)?this.flowParseDeclareVariable(e):this.eatContextual(127)?this.match(16)?this.flowParseDeclareModuleExports(e):(t&&this.raise(Rx.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e)):this.isContextual(130)?this.flowParseDeclareTypeAlias(e):this.isContextual(131)?this.flowParseDeclareOpaqueType(e):this.isContextual(129)?this.flowParseDeclareInterface(e):this.match(82)?this.flowParseDeclareExportDeclaration(e,t):void this.unexpected()},r.flowParseDeclareVariable=function(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(!0),this.scope.declareName(e.id.name,zb,e.id.loc.start),this.semicolon(),this.finishNode(e,"DeclareVariable")},r.flowParseDeclareModule=function(t){var r=this;this.scope.enter(hb),this.match(134)?t.id=e.prototype.parseExprAtom.call(this):t.id=this.parseIdentifier();var a=t.body=this.startNode(),n=a.body=[];for(this.expect(5);!this.match(8);){var s=this.startNode();this.match(83)?(this.next(),this.isContextual(130)||this.match(87)||this.raise(Rx.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),e.prototype.parseImport.call(this,s)):(this.expectContextual(125,Rx.UnsupportedStatementInDeclareModule),s=this.flowParseDeclare(s,!0)),n.push(s)}this.scope.exit(),this.expect(8),this.finishNode(a,"BlockStatement");var o=null,i=!1;return n.forEach((function(e){!function(e){return"DeclareExportAllDeclaration"===e.type||"DeclareExportDeclaration"===e.type&&(!e.declaration||"TypeAlias"!==e.declaration.type&&"InterfaceDeclaration"!==e.declaration.type)}(e)?"DeclareModuleExports"===e.type&&(i&&r.raise(Rx.DuplicateDeclareModuleExports,e),"ES"===o&&r.raise(Rx.AmbiguousDeclareModuleKind,e),o="CommonJS",i=!0):("CommonJS"===o&&r.raise(Rx.AmbiguousDeclareModuleKind,e),o="ES")})),t.kind=o||"CommonJS",this.finishNode(t,"DeclareModule")},r.flowParseDeclareExportDeclaration=function(e,t){if(this.expect(82),this.eat(65))return this.match(68)||this.match(80)?e.declaration=this.flowParseDeclare(this.startNode()):(e.declaration=this.flowParseType(),this.semicolon()),e.default=!0,this.finishNode(e,"DeclareExportDeclaration");if(this.match(75)||this.isLet()||(this.isContextual(130)||this.isContextual(129))&&!t){var r=this.state.value;throw this.raise(Rx.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:r,suggestion:wx[r]})}return this.match(74)||this.match(68)||this.match(80)||this.isContextual(131)?(e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration")):this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131)?"ExportNamedDeclaration"===(e=this.parseExport(e,null)).type?(e.default=!1,delete e.exportKind,this.castNodeTo(e,"DeclareExportDeclaration")):this.castNodeTo(e,"DeclareExportAllDeclaration"):void this.unexpected()},r.flowParseDeclareModuleExports=function(e){return this.next(),this.expectContextual(111),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")},r.flowParseDeclareTypeAlias=function(e){this.next();var t=this.flowParseTypeAlias(e);return this.castNodeTo(t,"DeclareTypeAlias"),t},r.flowParseDeclareOpaqueType=function(e){this.next();var t=this.flowParseOpaqueType(e,!0);return this.castNodeTo(t,"DeclareOpaqueType"),t},r.flowParseDeclareInterface=function(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")},r.flowParseInterfaceish=function(e,t){if(e.id=this.flowParseRestrictedIdentifier(!t,!0),this.scope.declareName(e.id.name,t?Xb:Hb,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],this.eat(81))do{e.extends.push(this.flowParseInterfaceExtends())}while(!t&&this.eat(12));if(t){if(e.implements=[],e.mixins=[],this.eatContextual(117))do{e.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(12));if(this.eatContextual(113))do{e.implements.push(this.flowParseInterfaceExtends())}while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:t,allowExact:!1,allowSpread:!1,allowProto:t,allowInexact:!1})},r.flowParseInterfaceExtends=function(){var e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.match(47)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")},r.flowParseInterface=function(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},r.checkNotUnderscore=function(e){"_"===e&&this.raise(Rx.UnexpectedReservedUnderscore,this.state.startLoc)},r.checkReservedType=function(e,t,r){vx.has(e)&&this.raise(r?Rx.AssignReservedType:Rx.UnexpectedReservedType,t,{reservedType:e})},r.flowParseRestrictedIdentifier=function(e,t){return this.checkReservedType(this.state.value,this.state.startLoc,t),this.parseIdentifier(e)},r.flowParseTypeAlias=function(e){return e.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(e.id.name,Hb,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(29),this.semicolon(),this.finishNode(e,"TypeAlias")},r.flowParseOpaqueType=function(e,t){return this.expectContextual(130),e.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(e.id.name,Hb,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(14)&&(e.supertype=this.flowParseTypeInitialiser(14)),e.impltype=null,t||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")},r.flowParseTypeParameter=function(e){void 0===e&&(e=!1);var t=this.state.startLoc,r=this.startNode(),a=this.flowParseVariance(),n=this.flowParseTypeAnnotatableIdentifier();return r.name=n.name,r.variance=a,r.bound=n.typeAnnotation,this.match(29)?(this.eat(29),r.default=this.flowParseType()):e&&this.raise(Rx.MissingTypeParamDefault,t),this.finishNode(r,"TypeParameter")},r.flowParseTypeParameterDeclaration=function(){var e=this.state.inType,t=this.startNode();t.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();var r=!1;do{var a=this.flowParseTypeParameter(r);t.params.push(a),a.default&&(r=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(t,"TypeParameterDeclaration")},r.flowInTopLevelContext=function(e){if(this.curContext()===Lh.brace)return e();var t=this.state.context;this.state.context=[t[0]];try{return e()}finally{this.state.context=t}},r.flowParseTypeParameterInstantiationInExpression=function(){if(47===this.reScan_lt())return this.flowParseTypeParameterInstantiation()},r.flowParseTypeParameterInstantiation=function(){var e=this,t=this.startNode(),r=this.state.inType;return this.state.inType=!0,t.params=[],this.flowInTopLevelContext((function(){e.expect(47);var r=e.state.noAnonFunctionType;for(e.state.noAnonFunctionType=!1;!e.match(48);)t.params.push(e.flowParseType()),e.match(48)||e.expect(12);e.state.noAnonFunctionType=r})),this.state.inType=r,this.state.inType||this.curContext()!==Lh.brace||this.reScan_lt_gt(),this.expect(48),this.finishNode(t,"TypeParameterInstantiation")},r.flowParseTypeParameterInstantiationCallOrNew=function(){if(47===this.reScan_lt()){var e=this.startNode(),t=this.state.inType;for(e.params=[],this.state.inType=!0,this.expect(47);!this.match(48);)e.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(48)||this.expect(12);return this.expect(48),this.state.inType=t,this.finishNode(e,"TypeParameterInstantiation")}},r.flowParseInterfaceType=function(){var e=this.startNode();if(this.expectContextual(129),e.extends=[],this.eat(81))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(12));return e.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(e,"InterfaceTypeAnnotation")},r.flowParseObjectPropertyKey=function(){return this.match(135)||this.match(134)?e.prototype.parseExprAtom.call(this):this.parseIdentifier(!0)},r.flowParseObjectTypeIndexer=function(e,t,r){return e.static=t,14===this.lookahead().type?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(3),e.value=this.flowParseTypeInitialiser(),e.variance=r,this.finishNode(e,"ObjectTypeIndexer")},r.flowParseObjectTypeInternalSlot=function(e,t){return e.static=t,e.id=this.flowParseObjectPropertyKey(),this.expect(3),this.expect(3),this.match(47)||this.match(10)?(e.method=!0,e.optional=!1,e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start))):(e.method=!1,this.eat(17)&&(e.optional=!0),e.value=this.flowParseTypeInitialiser()),this.finishNode(e,"ObjectTypeInternalSlot")},r.flowParseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,e.this=null,this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(10),this.match(78)&&(e.this=this.flowParseFunctionTypeParam(!0),e.this.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.params.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(e.rest=this.flowParseFunctionTypeParam(!1)),this.expect(11),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")},r.flowParseObjectTypeCallProperty=function(e,t){var r=this.startNode();return e.static=t,e.value=this.flowParseObjectTypeMethodish(r),this.finishNode(e,"ObjectTypeCallProperty")},r.flowParseObjectType=function(e){var t=e.allowStatic,r=e.allowExact,a=e.allowSpread,n=e.allowProto,s=e.allowInexact,o=this.state.inType;this.state.inType=!0;var i,d,c=this.startNode();c.callProperties=[],c.properties=[],c.indexers=[],c.internalSlots=[];var l=!1;for(r&&this.match(6)?(this.expect(6),i=9,d=!0):(this.expect(5),i=8,d=!1),c.exact=d;!this.match(i);){var u=!1,p=null,f=null,g=this.startNode();if(n&&this.isContextual(118)){var y=this.lookahead();14!==y.type&&17!==y.type&&(this.next(),p=this.state.startLoc,t=!1)}if(t&&this.isContextual(106)){var m=this.lookahead();14!==m.type&&17!==m.type&&(this.next(),u=!0)}var h=this.flowParseVariance();if(this.eat(0))null!=p&&this.unexpected(p),this.eat(0)?(h&&this.unexpected(h.loc.start),c.internalSlots.push(this.flowParseObjectTypeInternalSlot(g,u))):c.indexers.push(this.flowParseObjectTypeIndexer(g,u,h));else if(this.match(10)||this.match(47))null!=p&&this.unexpected(p),h&&this.unexpected(h.loc.start),c.callProperties.push(this.flowParseObjectTypeCallProperty(g,u));else{var b="init";if(this.isContextual(99)||this.isContextual(104))ib(this.lookahead().type)&&(b=this.state.value,this.next());var x=this.flowParseObjectTypeProperty(g,u,p,h,b,a,null!=s?s:!d);null===x?(l=!0,f=this.state.lastTokStartLoc):c.properties.push(x)}this.flowObjectTypeSemicolon(),!f||this.match(8)||this.match(9)||this.raise(Rx.UnexpectedExplicitInexactInObject,f)}this.expect(i),a&&(c.inexact=l);var v=this.finishNode(c,"ObjectTypeAnnotation");return this.state.inType=o,v},r.flowParseObjectTypeProperty=function(e,t,r,a,n,s,o){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(s?o||this.raise(Rx.InexactInsideExact,this.state.lastTokStartLoc):this.raise(Rx.InexactInsideNonObject,this.state.lastTokStartLoc),a&&this.raise(Rx.InexactVariance,a),null):(s||this.raise(Rx.UnexpectedSpreadType,this.state.lastTokStartLoc),null!=r&&this.unexpected(r),a&&this.raise(Rx.SpreadVariance,a),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));e.key=this.flowParseObjectPropertyKey(),e.static=t,e.proto=null!=r,e.kind=n;var i=!1;return this.match(47)||this.match(10)?(e.method=!0,null!=r&&this.unexpected(r),a&&this.unexpected(a.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),"get"!==n&&"set"!==n||this.flowCheckGetterSetterParams(e),!s&&"constructor"===e.key.name&&e.value.this&&this.raise(Rx.ThisParamBannedInConstructor,e.value.this)):("init"!==n&&this.unexpected(),e.method=!1,this.eat(17)&&(i=!0),e.value=this.flowParseTypeInitialiser(),e.variance=a),e.optional=i,this.finishNode(e,"ObjectTypeProperty")},r.flowCheckGetterSetterParams=function(e){var t="get"===e.kind?0:1,r=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise("get"===e.kind?Rx.GetterMayNotHaveThisParam:Rx.SetterMayNotHaveThisParam,e.value.this),r!==t&&this.raise("get"===e.kind?vh.BadGetterArity:vh.BadSetterArity,e),"set"===e.kind&&e.value.rest&&this.raise(vh.BadSetterRestParameter,e)},r.flowObjectTypeSemicolon=function(){this.eat(13)||this.eat(12)||this.match(8)||this.match(9)||this.unexpected()},r.flowParseQualifiedTypeIdentifier=function(e,t){null!=e||(e=this.state.startLoc);for(var r=t||this.flowParseRestrictedIdentifier(!0);this.eat(16);){var a=this.startNodeAt(e);a.qualification=r,a.id=this.flowParseRestrictedIdentifier(!0),r=this.finishNode(a,"QualifiedTypeIdentifier")}return r},r.flowParseGenericType=function(e,t){var r=this.startNodeAt(e);return r.typeParameters=null,r.id=this.flowParseQualifiedTypeIdentifier(e,t),this.match(47)&&(r.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(r,"GenericTypeAnnotation")},r.flowParseTypeofType=function(){var e=this.startNode();return this.expect(87),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},r.flowParseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(0);this.state.pos0){var g=[].concat(o);if(f.length>0){this.state=s,this.state.noArrowAt=g;for(var y=0;y1&&this.raise(Rx.AmbiguousConditionalArrow,s.startLoc),l&&1===p.length){this.state=s,g.push(p[0].start),this.state.noArrowAt=g;var b=this.tryParseConditionalConsequent();c=b.consequent,l=b.failed}}return this.getArrowLikeExpressions(c,!0),this.state.noArrowAt=o,this.expect(14),i.test=e,i.consequent=c,i.alternate=this.forwardNoArrowParamsConversionAt(i,(function(){return a.parseMaybeAssign(void 0,void 0)})),this.finishNode(i,"ConditionalExpression")},r.tryParseConditionalConsequent=function(){this.state.noArrowParamsConversionAt.push(this.state.start);var e=this.parseMaybeAssignAllowIn(),t=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:t}},r.getArrowLikeExpressions=function(e,t){for(var r=this,a=[e],n=[];0!==a.length;){var s=a.pop();"ArrowFunctionExpression"===s.type&&"BlockStatement"!==s.body.type?(s.typeParameters||!s.returnType?this.finishArrowValidation(s):n.push(s),a.push(s.body)):"ConditionalExpression"===s.type&&(a.push(s.consequent),a.push(s.alternate))}return t?(n.forEach((function(e){return r.finishArrowValidation(e)})),[n,[]]):function(e,t){for(var r=[],a=[],n=0;n1)&&t||this.raise(Rx.TypeCastInPattern,n.typeAnnotation)}return e},r.parseArrayLike=function(t,r,a,n){var s=e.prototype.parseArrayLike.call(this,t,r,a,n);return r&&!this.state.maybeInArrowParameters&&this.toReferencedList(s.elements),s},r.isValidLVal=function(t,r,a){return"TypeCastExpression"===t||e.prototype.isValidLVal.call(this,t,r,a)},r.parseClassProperty=function(t){return this.match(14)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),e.prototype.parseClassProperty.call(this,t)},r.parseClassPrivateProperty=function(t){return this.match(14)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),e.prototype.parseClassPrivateProperty.call(this,t)},r.isClassMethod=function(){return this.match(47)||e.prototype.isClassMethod.call(this)},r.isClassProperty=function(){return this.match(14)||e.prototype.isClassProperty.call(this)},r.isNonstaticConstructor=function(t){return!this.match(14)&&e.prototype.isNonstaticConstructor.call(this,t)},r.pushClassMethod=function(t,r,a,n,s,o){if(r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),e.prototype.pushClassMethod.call(this,t,r,a,n,s,o),r.params&&s){var i=r.params;i.length>0&&this.isThisParam(i[0])&&this.raise(Rx.ThisParamBannedInConstructor,r)}else if("MethodDefinition"===r.type&&s&&r.value.params){var d=r.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(Rx.ThisParamBannedInConstructor,r)}},r.pushClassPrivateMethod=function(t,r,a,n){r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),e.prototype.pushClassPrivateMethod.call(this,t,r,a,n)},r.parseClassSuper=function(t){if(e.prototype.parseClassSuper.call(this,t),t.superClass&&(this.match(47)||this.match(51))&&(t.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();var r=t.implements=[];do{var a=this.startNode();a.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?a.typeParameters=this.flowParseTypeParameterInstantiation():a.typeParameters=null,r.push(this.finishNode(a,"ClassImplements"))}while(this.eat(12))}},r.checkGetterSetterParams=function(t){e.prototype.checkGetterSetterParams.call(this,t);var r=this.getObjectOrClassMethodParams(t);if(r.length>0){var a=r[0];this.isThisParam(a)&&"get"===t.kind?this.raise(Rx.GetterMayNotHaveThisParam,a):this.isThisParam(a)&&this.raise(Rx.SetterMayNotHaveThisParam,a)}},r.parsePropertyNamePrefixOperator=function(e){e.variance=this.flowParseVariance()},r.parseObjPropValue=function(t,r,a,n,s,o,i){var d;t.variance&&this.unexpected(t.variance.loc.start),delete t.variance,this.match(47)&&!o&&(d=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());var c=e.prototype.parseObjPropValue.call(this,t,r,a,n,s,o,i);return d&&((c.value||c).typeParameters=d),c},r.parseFunctionParamType=function(e){return this.eat(17)&&("Identifier"!==e.type&&this.raise(Rx.PatternIsOptional,e),this.isThisParam(e)&&this.raise(Rx.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(Rx.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(Rx.ThisParamNoDefault,e),this.resetEndLocation(e),e},r.parseMaybeDefault=function(t,r){var a=e.prototype.parseMaybeDefault.call(this,t,r);return"AssignmentPattern"===a.type&&a.typeAnnotation&&a.right.start0&&this.raise(Rx.ThisParamMustBeFirst,t.params[s]);e.prototype.checkParams.call(this,t,r,a,n)}},r.parseParenAndDistinguishExpression=function(t){return e.prototype.parseParenAndDistinguishExpression.call(this,t&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))},r.parseSubscripts=function(t,r,a){var n=this;if("Identifier"===t.type&&"async"===t.name&&this.state.noArrowAt.includes(r.index)){this.next();var s=this.startNodeAt(r);s.callee=t,s.arguments=e.prototype.parseCallExpressionArguments.call(this),t=this.finishNode(s,"CallExpression")}else if("Identifier"===t.type&&"async"===t.name&&this.match(47)){var o=this.state.clone(),i=this.tryParse((function(e){return n.parseAsyncArrowWithTypeParameters(r)||e()}),o);if(!i.error&&!i.aborted)return i.node;var d=this.tryParse((function(){return e.prototype.parseSubscripts.call(n,t,r,a)}),o);if(d.node&&!d.error)return d.node;if(i.node)return this.state=i.failState,i.node;if(d.node)return this.state=d.failState,d.node;throw i.error||d.error}return e.prototype.parseSubscripts.call(this,t,r,a)},r.parseSubscript=function(t,r,a,n){var s=this;if(this.match(18)&&this.isLookaheadToken_lt()){if(n.optionalChainMember=!0,a)return n.stop=!0,t;this.next();var o=this.startNodeAt(r);return o.callee=t,o.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),o.arguments=this.parseCallExpressionArguments(),o.optional=!0,this.finishCallExpression(o,!0)}if(!a&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){var i=this.startNodeAt(r);i.callee=t;var d=this.tryParse((function(){return i.typeArguments=s.flowParseTypeParameterInstantiationCallOrNew(),s.expect(10),i.arguments=e.prototype.parseCallExpressionArguments.call(s),n.optionalChainMember&&(i.optional=!1),s.finishCallExpression(i,n.optionalChainMember)}));if(d.node)return d.error&&(this.state=d.failState),d.node}return e.prototype.parseSubscript.call(this,t,r,a,n)},r.parseNewCallee=function(t){var r=this;e.prototype.parseNewCallee.call(this,t);var a=null;this.shouldParseTypes()&&this.match(47)&&(a=this.tryParse((function(){return r.flowParseTypeParameterInstantiationCallOrNew()})).node),t.typeArguments=a},r.parseAsyncArrowWithTypeParameters=function(t){var r=this.startNodeAt(t);if(this.parseFunctionParams(r,!1),this.parseArrow(r))return e.prototype.parseArrowExpression.call(this,r,void 0,!0)},r.readToken_mult_modulo=function(t){var r=this.input.charCodeAt(this.state.pos+1);if(42===t&&47===r&&this.state.hasFlowComment)return this.state.hasFlowComment=!1,this.state.pos+=2,void this.nextToken();e.prototype.readToken_mult_modulo.call(this,t)},r.readToken_pipe_amp=function(t){var r=this.input.charCodeAt(this.state.pos+1);124!==t||125!==r?e.prototype.readToken_pipe_amp.call(this,t):this.finishOp(9,2)},r.parseTopLevel=function(t,r){var a=e.prototype.parseTopLevel.call(this,t,r);return this.state.hasFlowComment&&this.raise(Rx.UnterminatedFlowComment,this.state.curPosition()),a},r.skipBlockComment=function(){if(!this.hasPlugin("flowComments")||!this.skipFlowComment())return e.prototype.skipBlockComment.call(this,this.state.hasFlowComment?"*-/":"*/");if(this.state.hasFlowComment)throw this.raise(Rx.NestedFlowComment,this.state.startLoc);this.hasFlowCommentCompletion();var t=this.skipFlowComment();t&&(this.state.pos+=t,this.state.hasFlowComment=!0)},r.skipFlowComment=function(){for(var e=this.state.pos,t=2;[32,9].includes(this.input.charCodeAt(e+t));)t++;var r=this.input.charCodeAt(t+e),a=this.input.charCodeAt(t+e+1);return 58===r&&58===a?t+2:"flow-include"===this.input.slice(t+e,t+e+12)?t+12:58===r&&58!==a&&t},r.hasFlowCommentCompletion=function(){if(-1===this.input.indexOf("*/",this.state.pos))throw this.raise(vh.UnterminatedComment,this.state.curPosition())},r.flowEnumErrorBooleanMemberNotInitialized=function(e,t){var r=t.enumName,a=t.memberName;this.raise(Rx.EnumBooleanMemberNotInitialized,e,{memberName:a,enumName:r})},r.flowEnumErrorInvalidMemberInitializer=function(e,t){return this.raise(t.explicitType?"symbol"===t.explicitType?Rx.EnumInvalidMemberInitializerSymbolType:Rx.EnumInvalidMemberInitializerPrimaryType:Rx.EnumInvalidMemberInitializerUnknownType,e,t)},r.flowEnumErrorNumberMemberNotInitialized=function(e,t){this.raise(Rx.EnumNumberMemberNotInitialized,e,t)},r.flowEnumErrorStringMemberInconsistentlyInitialized=function(e,t){this.raise(Rx.EnumStringMemberInconsistentlyInitialized,e,t)},r.flowEnumMemberInit=function(){var e=this,t=this.state.startLoc,r=function(){return e.match(12)||e.match(8)};switch(this.state.type){case 135:var a=this.parseNumericLiteral(this.state.value);return r()?{type:"number",loc:a.loc.start,value:a}:{type:"invalid",loc:t};case 134:var n=this.parseStringLiteral(this.state.value);return r()?{type:"string",loc:n.loc.start,value:n}:{type:"invalid",loc:t};case 85:case 86:var s=this.parseBooleanLiteral(this.match(85));return r()?{type:"boolean",loc:s.loc.start,value:s}:{type:"invalid",loc:t};default:return{type:"invalid",loc:t}}},r.flowEnumMemberRaw=function(){var e=this.state.startLoc;return{id:this.parseIdentifier(!0),init:this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e}}},r.flowEnumCheckExplicitTypeMismatch=function(e,t,r){var a=t.explicitType;null!==a&&a!==r&&this.flowEnumErrorInvalidMemberInitializer(e,t)},r.flowEnumMembers=function(e){for(var t=e.enumName,r=e.explicitType,a=new Set,n={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},s=!1;!this.match(8);){if(this.eat(21)){s=!0;break}var o=this.startNode(),i=this.flowEnumMemberRaw(),d=i.id,c=i.init,l=d.name;if(""!==l){/^[a-z]/.test(l)&&this.raise(Rx.EnumInvalidMemberName,d,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:t}),a.has(l)&&this.raise(Rx.EnumDuplicateMemberName,d,{memberName:l,enumName:t}),a.add(l);var u={enumName:t,explicitType:r,memberName:l};switch(o.id=d,c.type){case"boolean":this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,n.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break;case"number":this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,n.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break;case"string":this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,n.stringMembers.push(this.finishNode(o,"EnumStringMember"));break;case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(r){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:n.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}}return{members:n,hasUnknownMembers:s}},r.flowEnumStringMembers=function(e,t,r){var a=r.enumName;if(0===e.length)return t;if(0===t.length)return e;if(t.length>e.length){for(var n=0;n=f){for(var g=0,y=i.defaultedMembers;g=f){for(var h=0,b=i.defaultedMembers;h0&&(this.raise(vh.BadGetterArity,this.state.curPosition()),this.isThisParam(r[a][0])&&this.raise(Rv.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if("set"===r.kind){if(1!==r[a].length)this.raise(vh.BadSetterArity,this.state.curPosition());else{var s=r[a][0];this.isThisParam(s)&&this.raise(Rv.AccessorCannotDeclareThisParameter,this.state.curPosition()),"Identifier"===s.type&&s.optional&&this.raise(Rv.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),"RestElement"===s.type&&this.raise(Rv.SetAccessorCannotHaveRestParameter,this.state.curPosition())}r[n]&&this.raise(Rv.SetAccessorCannotHaveReturnType,r[n])}else r.kind="method";return this.finishNode(r,"TSMethodSignature")}var o=e;t&&(o.readonly=!0);var i=this.tsTryParseTypeAnnotation();return i&&(o.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(o,"TSPropertySignature")},r.tsParseTypeMember=function(){var t=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",t);if(this.match(77)){var r=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",t):(t.key=this.createIdentifier(r,"new"),this.tsParsePropertyOrMethodSignature(t,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},t);var a=this.tsTryParseIndexSignature(t);return a||(e.prototype.parsePropertyName.call(this,t),t.computed||"Identifier"!==t.key.type||"get"!==t.key.name&&"set"!==t.key.name||!this.tsTokenCanFollowModifier()||(t.kind=t.key.name,e.prototype.parsePropertyName.call(this,t),this.match(10)||this.match(47)||this.unexpected(null,10)),this.tsParsePropertyOrMethodSignature(t,!!t.readonly))},r.tsParseTypeLiteral=function(){var e=this.startNode();return e.members=this.tsParseObjectTypeMembers(),this.finishNode(e,"TSTypeLiteral")},r.tsParseObjectTypeMembers=function(){this.expect(5);var e=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(8),e},r.tsIsStartOfMappedType=function(){return this.next(),this.eat(53)?this.isContextual(122):(this.isContextual(122)&&this.next(),!!this.match(0)&&(this.next(),!!this.tsIsIdentifier()&&(this.next(),this.match(58))))},r.tsParseMappedType=function(){var e=this.startNode();this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(e.readonly=!0),this.expect(0);var t=this.startNode();return t.name=this.tsParseTypeParameterName(),t.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(t,"TSTypeParameter"),e.nameType=this.eatContextual(93)?this.tsParseType():null,this.expect(3),this.match(53)?(e.optional=this.state.value,this.next(),this.expect(17)):this.eat(17)&&(e.optional=!0),e.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(8),this.finishNode(e,"TSMappedType")},r.tsParseTupleType=function(){var e=this,t=this.startNode();t.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);var r=!1;return t.elementTypes.forEach((function(t){var a=t.type;!r||"TSRestType"===a||"TSOptionalType"===a||"TSNamedTupleMember"===a&&t.optional||e.raise(Rv.OptionalTypeBeforeRequired,t),r||(r="TSNamedTupleMember"===a&&t.optional||"TSOptionalType"===a)})),this.finishNode(t,"TSTupleType")},r.tsParseTupleElementType=function(){var e,t,r,a,n,s=this.state.startLoc,o=this.eat(21),i=this.state.startLoc,d=ob(this.state.type)?this.lookaheadCharCode():null;if(58===d)e=!0,r=!1,t=this.parseIdentifier(!0),this.expect(14),a=this.tsParseType();else if(63===d){r=!0;var c=this.state.value,l=this.tsParseNonArrayType();58===this.lookaheadCharCode()?(e=!0,t=this.createIdentifier(this.startNodeAt(i),c),this.expect(17),this.expect(14),a=this.tsParseType()):(e=!1,a=l,this.expect(17))}else a=this.tsParseType(),r=this.eat(17),e=this.eat(14);if(e)t?((n=this.startNodeAt(i)).optional=r,n.label=t,n.elementType=a,this.eat(17)&&(n.optional=!0,this.raise(Rv.TupleOptionalAfterType,this.state.lastTokStartLoc))):((n=this.startNodeAt(i)).optional=r,this.raise(Rv.InvalidTupleMemberLabel,a),n.label=a,n.elementType=this.tsParseType()),a=this.finishNode(n,"TSNamedTupleMember");else if(r){var u=this.startNodeAt(i);u.typeAnnotation=a,a=this.finishNode(u,"TSOptionalType")}if(o){var p=this.startNodeAt(s);p.typeAnnotation=a,a=this.finishNode(p,"TSRestType")}return a},r.tsParseParenthesizedType=function(){var e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")},r.tsParseFunctionOrConstructorType=function(e,t){var r=this,a=this.startNode();return"TSConstructorType"===e&&(a.abstract=!!t,t&&this.next(),this.next()),this.tsInAllowConditionalTypesContext((function(){return r.tsFillSignature(19,a)})),this.finishNode(a,e)},r.tsParseLiteralTypeNode=function(){var t=this.startNode();switch(this.state.type){case 135:case 136:case 134:case 85:case 86:t.literal=e.prototype.parseExprAtom.call(this);break;default:this.unexpected()}return this.finishNode(t,"TSLiteralType")},r.tsParseTemplateLiteralType=function(){var t=this.startNode();return t.literal=e.prototype.parseTemplate.call(this,!1),this.finishNode(t,"TSLiteralType")},r.parseTemplateSubstitution=function(){return this.state.inType?this.tsParseType():e.prototype.parseTemplateSubstitution.call(this)},r.tsParseThisTypeOrThisTypePredicate=function(){var e=this.tsParseThisTypeNode();return this.isContextual(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e},r.tsParseNonArrayType=function(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if("-"===this.state.value){var e=this.startNode(),t=this.lookahead();return 135!==t.type&&136!==t.type&&this.unexpected(),e.literal=this.parseMaybeUnary(),this.finishNode(e,"TSLiteralType")}break;case 78:return this.tsParseThisTypeOrThisTypePredicate();case 87:return this.tsParseTypeQuery();case 83:return this.tsParseImportType();case 5:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 10:return this.tsParseParenthesizedType();case 25:case 24:return this.tsParseTemplateLiteralType();default:var r=this.state.type;if(sb(r)||88===r||84===r){var a=88===r?"TSVoidKeyword":84===r?"TSNullKeyword":function(e){switch(e){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}(this.state.value);if(void 0!==a&&46!==this.lookaheadCharCode()){var n=this.startNode();return this.next(),this.finishNode(n,a)}return this.tsParseTypeReference()}}this.unexpected()},r.tsParseArrayTypeOrHigher=function(){for(var e=this.state.startLoc,t=this.tsParseNonArrayType();!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){var r=this.startNodeAt(e);r.elementType=t,this.expect(3),t=this.finishNode(r,"TSArrayType")}else{var a=this.startNodeAt(e);a.objectType=t,a.indexType=this.tsParseType(),this.expect(3),t=this.finishNode(a,"TSIndexedAccessType")}return t},r.tsParseTypeOperator=function(){var e=this.startNode(),t=this.state.value;return this.next(),e.operator=t,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),"readonly"===t&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")},r.tsCheckTypeAnnotationForReadOnly=function(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(Rv.UnexpectedReadonly,e)}},r.tsParseInferType=function(){var e=this,t=this.startNode();this.expectContextual(115);var r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsTryParse((function(){return e.tsParseConstraintForInferType()})),t.typeParameter=this.finishNode(r,"TSTypeParameter"),this.finishNode(t,"TSInferType")},r.tsParseConstraintForInferType=function(){var e=this;if(this.eat(81)){var t=this.tsInDisallowConditionalTypesContext((function(){return e.tsParseType()}));if(this.state.inDisallowConditionalTypesContext||!this.match(17))return t}},r.tsParseTypeOperatorOrHigher=function(){var e,t=this;return(e=this.state.type)>=121&&e<=123&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext((function(){return t.tsParseArrayTypeOrHigher()}))},r.tsParseUnionOrIntersectionType=function(e,t,r){var a=this.startNode(),n=this.eat(r),s=[];do{s.push(t())}while(this.eat(r));return 1!==s.length||n?(a.types=s,this.finishNode(a,e)):s[0]},r.tsParseIntersectionTypeOrHigher=function(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),45)},r.tsParseUnionTypeOrHigher=function(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),43)},r.tsIsStartOfFunctionType=function(){return!!this.match(47)||this.match(10)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))},r.tsSkipParameterStart=function(){if(sb(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){var t=this.state.errors,r=t.length;try{return this.parseObjectLike(8,!0),t.length===r}catch(e){return!1}}if(this.match(0)){this.next();var a=this.state.errors,n=a.length;try{return e.prototype.parseBindingList.call(this,3,93,mv),a.length===n}catch(e){return!1}}return!1},r.tsIsUnambiguouslyStartOfFunctionType=function(){if(this.next(),this.match(11)||this.match(21))return!0;if(this.tsSkipParameterStart()){if(this.match(14)||this.match(12)||this.match(17)||this.match(29))return!0;if(this.match(11)&&(this.next(),this.match(19)))return!0}return!1},r.tsParseTypeOrTypePredicateAnnotation=function(e){var t=this;return this.tsInType((function(){var r=t.startNode();t.expect(e);var a=t.startNode(),n=!!t.tsTryParse(t.tsParseTypePredicateAsserts.bind(t));if(n&&t.match(78)){var s=t.tsParseThisTypeOrThisTypePredicate();return"TSThisType"===s.type?(a.parameterName=s,a.asserts=!0,a.typeAnnotation=null,s=t.finishNode(a,"TSTypePredicate")):(t.resetStartLocationFromNode(s,a),s.asserts=!0),r.typeAnnotation=s,t.finishNode(r,"TSTypeAnnotation")}var o=t.tsIsIdentifier()&&t.tsTryParse(t.tsParseTypePredicatePrefix.bind(t));if(!o)return n?(a.parameterName=t.parseIdentifier(),a.asserts=n,a.typeAnnotation=null,r.typeAnnotation=t.finishNode(a,"TSTypePredicate"),t.finishNode(r,"TSTypeAnnotation")):t.tsParseTypeAnnotation(!1,r);var i=t.tsParseTypeAnnotation(!1);return a.parameterName=o,a.typeAnnotation=i,a.asserts=n,r.typeAnnotation=t.finishNode(a,"TSTypePredicate"),t.finishNode(r,"TSTypeAnnotation")}))},r.tsTryParseTypeOrTypePredicateAnnotation=function(){if(this.match(14))return this.tsParseTypeOrTypePredicateAnnotation(14)},r.tsTryParseTypeAnnotation=function(){if(this.match(14))return this.tsParseTypeAnnotation()},r.tsTryParseType=function(){return this.tsEatThenParseType(14)},r.tsParseTypePredicatePrefix=function(){var e=this.parseIdentifier();if(this.isContextual(116)&&!this.hasPrecedingLineBreak())return this.next(),e},r.tsParseTypePredicateAsserts=function(){if(109!==this.state.type)return!1;var e=this.state.containsEsc;return this.next(),!(!sb(this.state.type)&&!this.match(78))&&(e&&this.raise(vh.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)},r.tsParseTypeAnnotation=function(e,t){var r=this;return void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),this.tsInType((function(){e&&r.expect(14),t.typeAnnotation=r.tsParseType()})),this.finishNode(t,"TSTypeAnnotation")},r.tsParseType=function(){var e=this;vv(this.state.inType);var t=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return t;var r=this.startNodeAtNode(t);return r.checkType=t,r.extendsType=this.tsInDisallowConditionalTypesContext((function(){return e.tsParseNonConditionalType()})),this.expect(17),r.trueType=this.tsInAllowConditionalTypesContext((function(){return e.tsParseType()})),this.expect(14),r.falseType=this.tsInAllowConditionalTypesContext((function(){return e.tsParseType()})),this.finishNode(r,"TSConditionalType")},r.isAbstractConstructorSignature=function(){return this.isContextual(124)&&this.isLookaheadContextual("new")},r.tsParseNonConditionalType=function(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(77)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()},r.tsParseTypeAssertion=function(){var e=this;this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(Rv.ReservedTypeAssertion,this.state.startLoc);var t=this.startNode();return t.typeAnnotation=this.tsInType((function(){return e.next(),e.match(75)?e.tsParseTypeReference():e.tsParseType()})),this.expect(48),t.expression=this.parseMaybeUnary(),this.finishNode(t,"TSTypeAssertion")},r.tsParseHeritageClause=function(e){var t=this,r=this.state.startLoc,a=this.tsParseDelimitedList("HeritageClauseElement",(function(){var e=t.startNode();return e.expression=t.tsParseEntityName(Tv|Pv),t.match(47)&&(e.typeParameters=t.tsParseTypeArguments()),t.finishNode(e,"TSExpressionWithTypeArguments")}));return a.length||this.raise(Rv.EmptyHeritageClauseType,r,{token:e}),a},r.tsParseInterfaceDeclaration=function(e,t){if(void 0===t&&(t={}),this.hasFollowingLineBreak())return null;this.expectContextual(129),t.declare&&(e.declare=!0),sb(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,Jb)):(e.id=null,this.raise(Rv.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));var r=this.startNode();return r.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(r,"TSInterfaceBody"),this.finishNode(e,"TSInterfaceDeclaration")},r.tsParseTypeAliasDeclaration=function(e){var t=this;return e.id=this.parseIdentifier(),this.checkIdentifier(e.id,Yb),e.typeAnnotation=this.tsInType((function(){if(e.typeParameters=t.tsTryParseTypeParameters(t.tsParseInOutModifiers),t.expect(29),t.isContextual(114)&&46!==t.lookaheadCharCode()){var r=t.startNode();return t.next(),t.finishNode(r,"TSIntrinsicKeyword")}return t.tsParseType()})),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")},r.tsInTopLevelContext=function(e){if(this.curContext()===Lh.brace)return e();var t=this.state.context;this.state.context=[t[0]];try{return e()}finally{this.state.context=t}},r.tsInType=function(e){var t=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=t}},r.tsInDisallowConditionalTypesContext=function(e){var t=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=t}},r.tsInAllowConditionalTypesContext=function(e){var t=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=t}},r.tsEatThenParseType=function(e){if(this.match(e))return this.tsNextThenParseType()},r.tsExpectThenParseType=function(e){var t=this;return this.tsInType((function(){return t.expect(e),t.tsParseType()}))},r.tsNextThenParseType=function(){var e=this;return this.tsInType((function(){return e.next(),e.tsParseType()}))},r.tsParseEnumMember=function(){var t=this.startNode();return t.id=this.match(134)?e.prototype.parseStringLiteral.call(this,this.state.value):this.parseIdentifier(!0),this.eat(29)&&(t.initializer=e.prototype.parseMaybeAssignAllowIn.call(this)),this.finishNode(t,"TSEnumMember")},r.tsParseEnumDeclaration=function(e,t){return void 0===t&&(t={}),t.const&&(e.const=!0),t.declare&&(e.declare=!0),this.expectContextual(126),e.id=this.parseIdentifier(),this.checkIdentifier(e.id,e.const?tx:$b),this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumDeclaration")},r.tsParseEnumBody=function(){var e=this.startNode();return this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumBody")},r.tsParseModuleBlock=function(){var t=this.startNode();return this.scope.enter(hb),this.expect(5),e.prototype.parseBlockOrModuleBlockBody.call(this,t.body=[],void 0,!0,8),this.scope.exit(),this.finishNode(t,"TSModuleBlock")},r.tsParseModuleOrNamespaceDeclaration=function(e,t){if(void 0===t&&(t=!1),e.id=this.parseIdentifier(),t||this.checkIdentifier(e.id,rx),this.eat(16)){var r=this.startNode();this.tsParseModuleOrNamespaceDeclaration(r,!0),e.body=r}else this.scope.enter(Ab),this.prodParam.enter(Fx),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")},r.tsParseAmbientExternalModuleDeclaration=function(t){return this.isContextual(112)?(t.kind="global",t.global=!0,t.id=this.parseIdentifier()):this.match(134)?(t.kind="module",t.id=e.prototype.parseStringLiteral.call(this,this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(Ab),this.prodParam.enter(Fx),t.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(t,"TSModuleDeclaration")},r.tsParseImportEqualsDeclaration=function(e,t,r){e.isExport=r||!1,e.id=t||this.parseIdentifier(),this.checkIdentifier(e.id,nx),this.expect(29);var a=this.tsParseModuleReference();return"type"===e.importKind&&"TSExternalModuleReference"!==a.type&&this.raise(Rv.ImportAliasHasImportType,a),e.moduleReference=a,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")},r.tsIsExternalModuleReference=function(){return this.isContextual(119)&&40===this.lookaheadCharCode()},r.tsParseModuleReference=function(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(Sv)},r.tsParseExternalModuleReference=function(){var t=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),t.expression=e.prototype.parseExprAtom.call(this),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(t,"TSExternalModuleReference")},r.tsLookAhead=function(e){var t=this.state.clone(),r=e();return this.state=t,r},r.tsTryParseAndCatch=function(e){var t=this.tryParse((function(t){return e()||t()}));if(!t.aborted&&t.node)return t.error&&(this.state=t.failState),t.node},r.tsTryParse=function(e){var t=this.state.clone(),r=e();if(void 0!==r&&!1!==r)return r;this.state=t},r.tsTryParseDeclare=function(t){var r=this;if(!this.isLineTerminator()){var a=this.state.type;return this.tsInAmbientContext((function(){switch(a){case 68:return t.declare=!0,e.prototype.parseFunctionStatement.call(r,t,!1,!1);case 80:return t.declare=!0,r.parseClass(t,!0,!1);case 126:return r.tsParseEnumDeclaration(t,{declare:!0});case 112:return r.tsParseAmbientExternalModuleDeclaration(t);case 100:if(r.state.containsEsc)return;case 75:case 74:return r.match(75)&&r.isLookaheadContextual("enum")?(r.expect(75),r.tsParseEnumDeclaration(t,{const:!0,declare:!0})):(t.declare=!0,r.parseVarStatement(t,r.state.value,!0));case 107:if(r.isUsing())return r.raise(Rv.InvalidModifierOnUsingDeclaration,r.state.startLoc,"declare"),t.declare=!0,r.parseVarStatement(t,"using",!0);break;case 96:if(r.isAwaitUsing())return r.raise(Rv.InvalidModifierOnAwaitUsingDeclaration,r.state.startLoc,"declare"),t.declare=!0,r.next(),r.parseVarStatement(t,"await using",!0);break;case 129:var n=r.tsParseInterfaceDeclaration(t,{declare:!0});if(n)return n;default:if(sb(a))return r.tsParseDeclaration(t,r.state.value,!0,null)}}))}},r.tsTryParseExportDeclaration=function(){return this.tsParseDeclaration(this.startNode(),this.state.value,!0,null)},r.tsParseExpressionStatement=function(e,t,r){switch(t.name){case"declare":var a=this.tsTryParseDeclare(e);return a&&(a.declare=!0),a;case"global":if(this.match(5)){this.scope.enter(Ab),this.prodParam.enter(Fx);var n=e;return n.kind="global",e.global=!0,n.id=t,n.body=this.tsParseModuleBlock(),this.scope.exit(),this.prodParam.exit(),this.finishNode(n,"TSModuleDeclaration")}break;default:return this.tsParseDeclaration(e,t.name,!1,r)}},r.tsParseDeclaration=function(e,t,r,a){switch(t){case"abstract":if(this.tsCheckLineTerminator(r)&&(this.match(80)||sb(this.state.type)))return this.tsParseAbstractDeclaration(e,a);break;case"module":if(this.tsCheckLineTerminator(r)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(sb(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case"namespace":if(this.tsCheckLineTerminator(r)&&sb(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case"type":if(this.tsCheckLineTerminator(r)&&sb(this.state.type))return this.tsParseTypeAliasDeclaration(e)}},r.tsCheckLineTerminator=function(e){return e?!this.hasFollowingLineBreak()&&(this.next(),!0):!this.isLineTerminator()},r.tsTryParseGenericAsyncArrowFunction=function(t){var r=this;if(this.match(47)){var a=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;var n=this.tsTryParseAndCatch((function(){var a=r.startNodeAt(t);return a.typeParameters=r.tsParseTypeParameters(r.tsParseConstModifier),e.prototype.parseFunctionParams.call(r,a),a.returnType=r.tsTryParseTypeOrTypePredicateAnnotation(),r.expect(19),a}));if(this.state.maybeInArrowParameters=a,n)return e.prototype.parseArrowExpression.call(this,n,null,!0)}},r.tsParseTypeArgumentsInExpression=function(){if(47===this.reScan_lt())return this.tsParseTypeArguments()},r.tsParseTypeArguments=function(){var e=this,t=this.startNode();return t.params=this.tsInType((function(){return e.tsInTopLevelContext((function(){return e.expect(47),e.tsParseDelimitedList("TypeParametersOrArguments",e.tsParseType.bind(e))}))})),0===t.params.length?this.raise(Rv.EmptyTypeArguments,t):this.state.inType||this.curContext()!==Lh.brace||this.reScan_lt_gt(),this.expect(48),this.finishNode(t,"TSTypeParameterInstantiation")},r.tsIsDeclarationStart=function(){return(e=this.state.type)>=124&&e<=130;var e},r.isExportDefaultSpecifier=function(){return!this.tsIsDeclarationStart()&&e.prototype.isExportDefaultSpecifier.call(this)},r.parseBindingElement=function(e,t){var r=t.length?t[0].loc.start:this.state.startLoc,a={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},a);var n=a.accessibility,s=a.override,o=a.readonly;e&bv||!(n||o||s)||this.raise(Rv.UnexpectedParameterModifier,r);var i=this.parseMaybeDefault();e&hv&&this.parseFunctionParamType(i);var d=this.parseMaybeDefault(i.loc.start,i);if(n||o||s){var c=this.startNodeAt(r);return t.length&&(c.decorators=t),n&&(c.accessibility=n),o&&(c.readonly=o),s&&(c.override=s),"Identifier"!==d.type&&"AssignmentPattern"!==d.type&&this.raise(Rv.UnsupportedParameterPropertyKind,c),c.parameter=d,this.finishNode(c,"TSParameterProperty")}return t.length&&(i.decorators=t),d},r.isSimpleParameter=function(t){return"TSParameterProperty"===t.type&&e.prototype.isSimpleParameter.call(this,t.parameter)||e.prototype.isSimpleParameter.call(this,t)},r.tsDisallowOptionalPattern=function(e){for(var t=0,r=e.params;ta&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(n=this.isContextual(120)))){var o=this.startNodeAt(r);return o.expression=t,o.typeAnnotation=this.tsInType((function(){return s.next(),s.match(75)?(n&&s.raise(vh.UnexpectedKeyword,s.state.startLoc,{keyword:"const"}),s.tsParseTypeReference()):s.tsParseType()})),this.finishNode(o,n?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(o,r,a)}return e.prototype.parseExprOp.call(this,t,r,a)},r.checkReservedWord=function(t,r,a,n){this.state.isAmbientContext||e.prototype.checkReservedWord.call(this,t,r,a,n)},r.checkImportReflection=function(t){e.prototype.checkImportReflection.call(this,t),t.module&&"value"!==t.importKind&&this.raise(Rv.ImportReflectionHasImportType,t.specifiers[0].loc.start)},r.checkDuplicateExports=function(){},r.isPotentialImportPhase=function(t){if(e.prototype.isPotentialImportPhase.call(this,t))return!0;if(this.isContextual(130)){var r=this.lookaheadCharCode();return t?123===r||42===r:61!==r}return!t&&this.isContextual(87)},r.applyImportPhase=function(t,r,a,n){e.prototype.applyImportPhase.call(this,t,r,a,n),r?t.exportKind="type"===a?"type":"value":t.importKind="type"===a||"typeof"===a?a:"value"},r.parseImport=function(t){if(this.match(134))return t.importKind="value",e.prototype.parseImport.call(this,t);var r;if(sb(this.state.type)&&61===this.lookaheadCharCode())return t.importKind="value",this.tsParseImportEqualsDeclaration(t);if(this.isContextual(130)){var a=this.parseMaybeImportPhase(t,!1);if(61===this.lookaheadCharCode())return this.tsParseImportEqualsDeclaration(t,a);r=e.prototype.parseImportSpecifiersAndAfter.call(this,t,a)}else r=e.prototype.parseImport.call(this,t);return"type"===r.importKind&&r.specifiers.length>1&&"ImportDefaultSpecifier"===r.specifiers[0].type&&this.raise(Rv.TypeImportCannotSpecifyDefaultAndNamed,r),r},r.parseExport=function(t,r){if(this.match(83)){var a=t;this.next();var n=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?n=this.parseMaybeImportPhase(a,!1):a.importKind="value",this.tsParseImportEqualsDeclaration(a,n,!0)}if(this.eat(29)){var s=t;return s.expression=e.prototype.parseExpression.call(this),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(s,"TSExportAssignment")}if(this.eatContextual(93)){var o=t;return this.expectContextual(128),o.id=this.parseIdentifier(),this.semicolon(),this.finishNode(o,"TSNamespaceExportDeclaration")}return e.prototype.parseExport.call(this,t,r)},r.isAbstractClass=function(){return this.isContextual(124)&&this.isLookaheadContextual("class")},r.parseExportDefaultExpression=function(){if(this.isAbstractClass()){var t=this.startNode();return this.next(),t.abstract=!0,this.parseClass(t,!0,!0)}if(this.match(129)){var r=this.tsParseInterfaceDeclaration(this.startNode());if(r)return r}return e.prototype.parseExportDefaultExpression.call(this)},r.parseVarStatement=function(t,r,a){void 0===a&&(a=!1);var n=this.state.isAmbientContext,s=e.prototype.parseVarStatement.call(this,t,r,a||n);if(!n)return s;if(!t.declare&&("using"===r||"await using"===r))return this.raiseOverwrite(Rv.UsingDeclarationInAmbientContext,t,r),s;for(var o=0,i=s.declarations;othis.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(Iv.UnexpectedSpace,this.state.lastTokEndLoc)},o(t)}(e)}},Bv=Object.keys(Nv),Mv=function(e){function t(){return e.apply(this,arguments)||this}c(t,e);var r=t.prototype;return r.checkProto=function(e,t,r,a){if("SpreadElement"===e.type||this.isObjectMethod(e)||e.computed||e.shorthand)return r;var n=e.key;return"__proto__"===("Identifier"===n.type?n.name:n.value)?t?(this.raise(vh.RecordNoProto,n),!0):(r&&(a?null===a.doubleProtoLoc&&(a.doubleProtoLoc=n.loc.start):this.raise(vh.DuplicateProto,n)),!0):r},r.shouldExitDescending=function(e,t){return"ArrowFunctionExpression"===e.type&&this.offsetToSourcePos(e.start)===t},r.getExpression=function(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(vh.ParseExpressionEmptyInput,this.state.startLoc);var e=this.parseExpression();if(!this.match(140))throw this.raise(vh.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),e.comments=this.comments,e.errors=this.state.errors,this.optionFlags&kh&&(e.tokens=this.tokens),e},r.parseExpression=function(e,t){var r=this;return e?this.disallowInAnd((function(){return r.parseExpressionBase(t)})):this.allowInAnd((function(){return r.parseExpressionBase(t)}))},r.parseExpressionBase=function(e){var t=this.state.startLoc,r=this.parseMaybeAssign(e);if(this.match(12)){var a=this.startNodeAt(t);for(a.expressions=[r];this.eat(12);)a.expressions.push(this.parseMaybeAssign(e));return this.toReferencedList(a.expressions),this.finishNode(a,"SequenceExpression")}return r},r.parseMaybeAssignDisallowIn=function(e,t){var r=this;return this.disallowInAnd((function(){return r.parseMaybeAssign(e,t)}))},r.parseMaybeAssignAllowIn=function(e,t){var r=this;return this.allowInAnd((function(){return r.parseMaybeAssign(e,t)}))},r.setOptionalParametersError=function(e){e.optionalParametersLoc=this.state.startLoc},r.parseMaybeAssign=function(e,t){var r,a=this.state.startLoc,n=this.isContextual(108);if(n&&this.prodParam.hasYield){this.next();var s=this.parseYield(a);return t&&(s=t.call(this,s,a)),s}e?r=!1:(e=new lv,r=!0);var o=this.state.type;(10===o||sb(o))&&(this.state.potentialArrowAt=this.state.start);var i,d=this.parseMaybeConditional(e);if(t&&(d=t.call(this,d,a)),(i=this.state.type)>=29&&i<=33){var c=this.startNodeAt(a),l=this.state.value;if(c.operator=l,this.match(29)){this.toAssignable(d,!0),c.left=d;var u=a.index;null!=e.doubleProtoLoc&&e.doubleProtoLoc.index>=u&&(e.doubleProtoLoc=null),null!=e.shorthandAssignLoc&&e.shorthandAssignLoc.index>=u&&(e.shorthandAssignLoc=null),null!=e.privateKeyLoc&&e.privateKeyLoc.index>=u&&(this.checkDestructuringPrivate(e),e.privateKeyLoc=null),null!=e.voidPatternLoc&&e.voidPatternLoc.index>=u&&(e.voidPatternLoc=null)}else c.left=d;return this.next(),c.right=this.parseMaybeAssign(),this.checkLVal(d,this.finishNode(c,"AssignmentExpression")),c}if(r&&this.checkExpressionErrors(e,!0),n){var p=this.state.type;if((this.hasPlugin("v8intrinsic")?db(p):db(p)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(vh.YieldNotInGeneratorFunction,a),this.parseYield(a)}return d},r.parseMaybeConditional=function(e){var t=this.state.startLoc,r=this.state.potentialArrowAt,a=this.parseExprOps(e);return this.shouldExitDescending(a,r)?a:this.parseConditional(a,t,e)},r.parseConditional=function(e,t,r){if(this.eat(17)){var a=this.startNodeAt(t);return a.test=e,a.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),a.alternate=this.parseMaybeAssign(),this.finishNode(a,"ConditionalExpression")}return e},r.parseMaybeUnaryOrPrivate=function(e){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(e)},r.parseExprOps=function(e){var t=this.state.startLoc,r=this.state.potentialArrowAt,a=this.parseMaybeUnaryOrPrivate(e);return this.shouldExitDescending(a,r)?a:this.parseExprOp(a,t,-1)},r.parseExprOp=function(e,t,r){if(this.isPrivateName(e)){var a=this.getPrivateNameSV(e);(r>=pb(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(vh.PrivateInExpectedIn,e,{identifierName:a}),this.classScope.usePrivateName(a,e.loc.start)}var n,s=this.state.type;if((n=s)>=39&&n<=59&&(this.prodParam.hasIn||!this.match(58))){var o=pb(s);if(o>r){if(39===s){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return e;this.checkPipelineAtInfixOperator(e,t)}var i=this.startNodeAt(t);i.left=e,i.operator=this.state.value;var d=41===s||42===s,c=40===s;if(c&&(o=pb(42)),this.next(),39===s&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&96===this.state.type&&this.prodParam.hasAwait)throw this.raise(vh.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);i.right=this.parseExprOpRightExpr(s,o);var l=this.finishNode(i,d||c?"LogicalExpression":"BinaryExpression"),u=this.state.type;if(c&&(41===u||42===u)||d&&40===u)throw this.raise(vh.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(l,t,r)}}return e},r.parseExprOpRightExpr=function(e,t){var r=this,a=this.state.startLoc;if(39===e){switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext((function(){return r.parseHackPipeBody()}));case"fsharp":return this.withSoloAwaitPermittingContext((function(){return r.parseFSharpPipelineBody(t)}))}if("smart"===this.getPluginOption("pipelineOperator","proposal"))return this.withTopicBindingContext((function(){if(r.prodParam.hasYield&&r.isContextual(108))throw r.raise(vh.PipeBodyIsTighter,r.state.startLoc);return r.parseSmartPipelineBodyInStyle(r.parseExprOpBaseRightExpr(e,t),a)}))}return this.parseExprOpBaseRightExpr(e,t)},r.parseExprOpBaseRightExpr=function(e,t){var r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,57===e?t-1:t)},r.parseHackPipeBody=function(){var e,t=this.state.startLoc,r=this.parseMaybeAssign();return!yh.has(r.type)||null!=(e=r.extra)&&e.parenthesized||this.raise(vh.PipeUnparenthesizedBody,t,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(vh.PipeTopicUnused,t),r},r.checkExponentialAfterUnary=function(e){this.match(57)&&this.raise(vh.UnexpectedTokenUnaryExponentiation,e.argument)},r.parseMaybeUnary=function(e,t){var r=this.state.startLoc,a=this.isContextual(96);if(a&&this.recordAwaitIfAllowed()){this.next();var n=this.parseAwait(r);return t||this.checkExponentialAfterUnary(n),n}var s,o=this.match(34),i=this.startNode();if(s=this.state.type,tb[s]){i.operator=this.state.value,i.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");var d=this.match(89);if(this.next(),i.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(e,!0),this.state.strict&&d){var c=i.argument;"Identifier"===c.type?this.raise(vh.StrictDelete,i):this.hasPropertyAsPrivateName(c)&&this.raise(vh.DeletePrivateField,i)}if(!o)return t||this.checkExponentialAfterUnary(i),this.finishNode(i,"UnaryExpression")}var l=this.parseUpdate(i,o,e);if(a){var u=this.state.type;if((this.hasPlugin("v8intrinsic")?db(u):db(u)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(vh.AwaitNotInAsyncContext,r),this.parseAwait(r)}return l},r.parseUpdate=function(e,t,r){if(t){var a=e;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),e}var n=this.state.startLoc,s=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return s;for(;34===this.state.type&&!this.canInsertSemicolon();){var o=this.startNodeAt(n);o.operator=this.state.value,o.prefix=!1,o.argument=s,this.next(),this.checkLVal(s,s=this.finishNode(o,"UpdateExpression"))}return s},r.parseExprSubscripts=function(e){var t=this.state.startLoc,r=this.state.potentialArrowAt,a=this.parseExprAtom(e);return this.shouldExitDescending(a,r)?a:this.parseSubscripts(a,t)},r.parseSubscripts=function(e,t,r){var a={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(e),stop:!1};do{e=this.parseSubscript(e,t,r,a),a.maybeAsyncArrow=!1}while(!a.stop);return e},r.parseSubscript=function(e,t,r,a){var n=this.state.type;if(!r&&15===n)return this.parseBind(e,t,r,a);if(fb(n))return this.parseTaggedTemplateExpression(e,t,a);var s=!1;if(18===n){if(r&&(this.raise(vh.OptionalChainingNoNew,this.state.startLoc),40===this.lookaheadCharCode()))return this.stopParseSubscript(e,a);a.optionalChainMember=s=!0,this.next()}if(!r&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(e,t,a,s);var o=this.eat(0);return o||s||this.eat(16)?this.parseMember(e,t,a,o,s):this.stopParseSubscript(e,a)},r.stopParseSubscript=function(e,t){return t.stop=!0,e},r.parseMember=function(e,t,r,a,n){var s=this.startNodeAt(t);return s.object=e,s.computed=a,a?(s.property=this.parseExpression(),this.expect(3)):this.match(139)?("Super"===e.type&&this.raise(vh.SuperPrivateField,t),this.classScope.usePrivateName(this.state.value,this.state.startLoc),s.property=this.parsePrivateName()):s.property=this.parseIdentifier(!0),r.optionalChainMember?(s.optional=n,this.finishNode(s,"OptionalMemberExpression")):this.finishNode(s,"MemberExpression")},r.parseBind=function(e,t,r,a){var n=this.startNodeAt(t);return n.object=e,this.next(),n.callee=this.parseNoCallExpr(),a.stop=!0,this.parseSubscripts(this.finishNode(n,"BindExpression"),t,r)},r.parseCoverCallAndAsyncArrowHead=function(e,t,r,a){var n=this.state.maybeInArrowParameters,s=null;this.state.maybeInArrowParameters=!0,this.next();var o=this.startNodeAt(t);o.callee=e;var i=r.maybeAsyncArrow,d=r.optionalChainMember;i&&(this.expressionScope.enter(new ov(2)),s=new lv),d&&(o.optional=a),o.arguments=a?this.parseCallExpressionArguments():this.parseCallExpressionArguments("Super"!==e.type,o,s);var c=this.finishCallExpression(o,d);return i&&this.shouldParseAsyncArrow()&&!a?(r.stop=!0,this.checkDestructuringPrivate(s),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),c=this.parseAsyncArrowFromCallExpression(this.startNodeAt(t),c)):(i&&(this.checkExpressionErrors(s,!0),this.expressionScope.exit()),this.toReferencedArguments(c)),this.state.maybeInArrowParameters=n,c},r.toReferencedArguments=function(e,t){this.toReferencedListDeep(e.arguments,t)},r.parseTaggedTemplateExpression=function(e,t,r){var a=this.startNodeAt(t);return a.tag=e,a.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(vh.OptionalChainingNoTemplate,t),this.finishNode(a,"TaggedTemplateExpression")},r.atPossibleAsyncArrow=function(e){return"Identifier"===e.type&&"async"===e.name&&this.state.lastTokEndLoc.index===e.end&&!this.canInsertSemicolon()&&e.end-e.start==5&&this.offsetToSourcePos(e.start)===this.state.potentialArrowAt},r.finishCallExpression=function(e,t){if("Import"===e.callee.type)if(0===e.arguments.length||e.arguments.length>2)this.raise(vh.ImportCallArity,e);else for(var r=0,a=e.arguments;r1?((t=this.startNodeAt(i)).expressions=d,this.finishNode(t,"SequenceExpression"),this.resetEndLocation(t,p)):t=d[0],this.wrapParenthesis(r,t))},r.wrapParenthesis=function(e,t){if(!(this.optionFlags&_h))return this.addExtra(t,"parenthesized",!0),this.addExtra(t,"parenStart",e.index),this.takeSurroundingComments(t,e.index,this.state.lastTokEndLoc.index),t;var r=this.startNodeAt(e);return r.expression=t,this.finishNode(r,"ParenthesizedExpression")},r.shouldParseArrow=function(e){return!this.canInsertSemicolon()},r.parseArrow=function(e){if(this.eat(19))return e},r.parseParenItem=function(e,t){return e},r.parseNewOrNewTarget=function(){var e=this.startNode();if(this.next(),this.match(16)){var t=this.createIdentifier(this.startNodeAtNode(e),"new");this.next();var r=this.parseMetaProperty(e,t,"target");return this.scope.allowNewTarget||this.raise(vh.UnexpectedNewTarget,r),r}return this.parseNew(e)},r.parseNew=function(e){if(this.parseNewCallee(e),this.eat(10)){var t=this.parseExprList(11);this.toReferencedList(t),e.arguments=t}else e.arguments=[];return this.finishNode(e,"NewExpression")},r.parseNewCallee=function(e){var t=this.match(83),r=this.parseNoCallExpr();e.callee=r,!t||"Import"!==r.type&&"ImportExpression"!==r.type||this.raise(vh.ImportCallNotNewExpression,r)},r.parseTemplateElement=function(e){var t=this.state,r=t.start,a=t.startLoc,n=t.end,s=t.value,o=r+1,i=this.startNodeAt(ih(a,1));null===s&&(e||this.raise(vh.InvalidEscapeSequenceTemplate,ih(this.state.firstInvalidTemplateEscapePos,1)));var d=this.match(24),c=d?-1:-2,l=n+c;i.value={raw:this.input.slice(o,l).replace(/\r\n?/g,"\n"),cooked:null===s?null:s.slice(1,c)},i.tail=d,this.next();var u=this.finishNode(i,"TemplateElement");return this.resetEndLocation(u,ih(this.state.lastTokEndLoc,c)),u},r.parseTemplate=function(e){for(var t=this.startNode(),r=this.parseTemplateElement(e),a=[r],n=[];!r.tail;)n.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),a.push(r=this.parseTemplateElement(e));return t.expressions=n,t.quasis=a,this.finishNode(t,"TemplateLiteral")},r.parseTemplateSubstitution=function(){return this.parseExpression()},r.parseObjectLike=function(e,t,r,a){r&&this.expectPlugin("recordAndTuple");var n=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;var s=!1,o=!0,i=this.startNode();for(i.properties=[],this.next();!this.match(e);){if(o)o=!1;else if(this.expect(12),this.match(e)){this.addTrailingCommaExtraToNode(i);break}var d=void 0;t?d=this.parseBindingProperty():(d=this.parsePropertyDefinition(a),s=this.checkProto(d,r,s,a)),r&&!this.isObjectProperty(d)&&"SpreadElement"!==d.type&&this.raise(vh.InvalidRecordProperty,d),d.shorthand&&this.addExtra(d,"shorthand",!0),i.properties.push(d)}this.next(),this.state.inFSharpPipelineDirectBody=n;var c="ObjectExpression";return t?c="ObjectPattern":r&&(c="RecordExpression"),this.finishNode(i,c)},r.addTrailingCommaExtraToNode=function(e){this.addExtra(e,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(e,"trailingCommaLoc",this.state.lastTokStartLoc,!1)},r.maybeAsyncOrAccessorProp=function(e){return!e.computed&&"Identifier"===e.key.type&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))},r.parsePropertyDefinition=function(e){var t=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(vh.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)t.push(this.parseDecorator());var r,a=this.startNode(),n=!1,s=!1;if(this.match(21))return t.length&&this.unexpected(),this.parseSpread();t.length&&(a.decorators=t,t=[]),a.method=!1,e&&(r=this.state.startLoc);var o=this.eat(55);this.parsePropertyNamePrefixOperator(a);var i=this.state.containsEsc;if(this.parsePropertyName(a,e),!o&&!i&&this.maybeAsyncOrAccessorProp(a)){var d=a.key,c=d.name;"async"!==c||this.hasPrecedingLineBreak()||(n=!0,this.resetPreviousNodeTrailingComments(d),o=this.eat(55),this.parsePropertyName(a)),"get"!==c&&"set"!==c||(s=!0,this.resetPreviousNodeTrailingComments(d),a.kind=c,this.match(55)&&(o=!0,this.raise(vh.AccessorIsGenerator,this.state.curPosition(),{kind:c}),this.next()),this.parsePropertyName(a))}return this.parseObjPropValue(a,r,o,n,!1,s,e)},r.getGetterSetterExpectedParamCount=function(e){return"get"===e.kind?0:1},r.getObjectOrClassMethodParams=function(e){return e.params},r.checkGetterSetterParams=function(e){var t,r=this.getGetterSetterExpectedParamCount(e),a=this.getObjectOrClassMethodParams(e);a.length!==r&&this.raise("get"===e.kind?vh.BadGetterArity:vh.BadSetterArity,e),"set"===e.kind&&"RestElement"===(null==(t=a[a.length-1])?void 0:t.type)&&this.raise(vh.BadSetterRestParameter,e)},r.parseObjectMethod=function(e,t,r,a,n){if(n){var s=this.parseMethod(e,t,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(s),s}if(r||t||this.match(10))return a&&this.unexpected(),e.kind="method",e.method=!0,this.parseMethod(e,t,r,!1,!1,"ObjectMethod")},r.parseObjectProperty=function(e,t,r,a){if(e.shorthand=!1,this.eat(14))return e.value=r?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,a),this.finishObjectProperty(e);if(!e.computed&&"Identifier"===e.key.type){if(this.checkReservedWord(e.key.name,e.key.loc.start,!0,!1),r)e.value=this.parseMaybeDefault(t,this.cloneIdentifier(e.key));else if(this.match(29)){var n=this.state.startLoc;null!=a?null===a.shorthandAssignLoc&&(a.shorthandAssignLoc=n):this.raise(vh.InvalidCoverInitializedName,n),e.value=this.parseMaybeDefault(t,this.cloneIdentifier(e.key))}else e.value=this.cloneIdentifier(e.key);return e.shorthand=!0,this.finishObjectProperty(e)}},r.finishObjectProperty=function(e){return this.finishNode(e,"ObjectProperty")},r.parseObjPropValue=function(e,t,r,a,n,s,o){var i=this.parseObjectMethod(e,r,a,n,s)||this.parseObjectProperty(e,t,n,o);return i||this.unexpected(),i},r.parsePropertyName=function(e,t){if(this.eat(0))e.computed=!0,e.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{var r,a=this.state,n=a.type,s=a.value;if(ob(n))r=this.parseIdentifier(!0);else switch(n){case 135:r=this.parseNumericLiteral(s);break;case 134:r=this.parseStringLiteral(s);break;case 136:r=this.parseBigIntLiteral(s);break;case 139:var o=this.state.startLoc;null!=t?null===t.privateKeyLoc&&(t.privateKeyLoc=o):this.raise(vh.UnexpectedPrivateField,o),r=this.parsePrivateName();break;default:if(137===n){r=this.parseDecimalLiteral(s);break}this.unexpected()}e.key=r,139!==n&&(e.computed=!1)}},r.initFunction=function(e,t){e.id=null,e.generator=!1,e.async=t},r.parseMethod=function(e,t,r,a,n,s,o){void 0===o&&(o=!1),this.initFunction(e,r),e.generator=t,this.scope.enter(kb|jb|(o?Cb:0)|(n?wb:0)),this.prodParam.enter(Vx(r,e.generator)),this.parseFunctionParams(e,a);var i=this.parseFunctionBodyAndFinish(e,s,!0);return this.prodParam.exit(),this.scope.exit(),i},r.parseArrayLike=function(e,t,r,a){r&&this.expectPlugin("recordAndTuple");var n=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;var s=this.startNode();return this.next(),s.elements=this.parseExprList(e,!r,a,s),this.state.inFSharpPipelineDirectBody=n,this.finishNode(s,r?"TupleExpression":"ArrayExpression")},r.parseArrowExpression=function(e,t,r,a){this.scope.enter(kb|vb);var n=Vx(r,!1);!this.match(5)&&this.prodParam.hasIn&&(n|=Gx),this.prodParam.enter(n),this.initFunction(e,r);var s=this.state.maybeInArrowParameters;return t&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(e,t,a)),this.state.maybeInArrowParameters=!1,this.parseFunctionBody(e,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=s,this.finishNode(e,"ArrowFunctionExpression")},r.setArrowFunctionParameters=function(e,t,r){this.toAssignableList(t,r,!1),e.params=t},r.parseFunctionBodyAndFinish=function(e,t,r){return void 0===r&&(r=!1),this.parseFunctionBody(e,!1,r),this.finishNode(e,t)},r.parseFunctionBody=function(e,t,r){var a=this;void 0===r&&(r=!1);var n=t&&!this.match(5);if(this.expressionScope.enter(dv()),n)e.body=this.parseMaybeAssign(),this.checkParams(e,!1,t,!1);else{var s=this.state.strict,o=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|qx),e.body=this.parseBlock(!0,!1,(function(n){var o=!a.isSimpleParamList(e.params);n&&o&&a.raise(vh.IllegalLanguageModeDirective,"method"!==e.kind&&"constructor"!==e.kind||!e.key?e:e.key.loc.end);var i=!s&&a.state.strict;a.checkParams(e,!(a.state.strict||t||r||o),t,i),a.state.strict&&e.id&&a.checkIdentifier(e.id,ex,i)})),this.prodParam.exit(),this.state.labels=o}this.expressionScope.exit()},r.isSimpleParameter=function(e){return"Identifier"===e.type},r.isSimpleParamList=function(e){for(var t=0,r=e.length;t10)&&function(e){return yb.has(e)}(e))if(r&&Qr(e))this.raise(vh.UnexpectedKeyword,t,{keyword:e});else if((this.state.strict?a?$r:Jr:Xr)(e,this.inModule))this.raise(vh.UnexpectedReservedWord,t,{reservedWord:e});else if("yield"===e){if(this.prodParam.hasYield)return void this.raise(vh.YieldBindingIdentifier,t)}else if("await"===e){if(this.prodParam.hasAwait)return void this.raise(vh.AwaitBindingIdentifier,t);if(this.scope.inStaticBlock)return void this.raise(vh.AwaitBindingIdentifierInStaticBlock,t);this.expressionScope.recordAsyncArrowParametersError(t)}else if("arguments"===e&&this.scope.inClassAndNotInNonArrowFunction)return void this.raise(vh.ArgumentsInClass,t)},r.recordAwaitIfAllowed=function(){var e=this.prodParam.hasAwait;return e&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),e},r.parseAwait=function(e){var t=this.startNodeAt(e);return this.expressionScope.recordParameterInitializerError(vh.AwaitExpressionFormalParameter,t),this.eat(55)&&this.raise(vh.ObsoleteAwaitStar,t),this.scope.inFunction||this.optionFlags&Rh||(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(t.argument=this.parseMaybeUnary(null,!0)),this.finishNode(t,"AwaitExpression")},r.isAmbiguousPrefixOrIdentifier=function(){if(this.hasPrecedingLineBreak())return!0;var e=this.state.type;return 53===e||10===e||0===e||fb(e)||102===e&&!this.state.containsEsc||138===e||56===e||this.hasPlugin("v8intrinsic")&&54===e},r.parseYield=function(e){var t=this.startNodeAt(e);this.expressionScope.recordParameterInitializerError(vh.YieldInParameter,t);var r=!1,a=null;if(!this.hasPrecedingLineBreak())switch(r=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!r)break;default:a=this.parseMaybeAssign()}return t.delegate=r,t.argument=a,this.finishNode(t,"YieldExpression")},r.parseImportCall=function(e){if(this.next(),e.source=this.parseMaybeAssignAllowIn(),e.options=null,this.eat(12))if(this.match(11))this.addTrailingCommaExtraToNode(e.source);else if(e.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&(this.addTrailingCommaExtraToNode(e.options),!this.match(11))){do{this.parseMaybeAssignAllowIn()}while(this.eat(12)&&!this.match(11));this.raise(vh.ImportCallArity,e)}return this.expect(11),this.finishNode(e,"ImportExpression")},r.checkPipelineAtInfixOperator=function(e,t){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&"SequenceExpression"===e.type&&this.raise(vh.PipelineHeadSequenceExpression,t)},r.parseSmartPipelineBodyInStyle=function(e,t){if(this.isSimpleReference(e)){var r=this.startNodeAt(t);return r.callee=e,this.finishNode(r,"PipelineBareFunction")}var a=this.startNodeAt(t);return this.checkSmartPipeTopicBodyEarlyErrors(t),a.expression=e,this.finishNode(a,"PipelineTopicExpression")},r.isSimpleReference=function(e){switch(e.type){case"MemberExpression":return!e.computed&&this.isSimpleReference(e.object);case"Identifier":return!0;default:return!1}},r.checkSmartPipeTopicBodyEarlyErrors=function(e){if(this.match(19))throw this.raise(vh.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(vh.PipelineTopicUnused,e)},r.withTopicBindingContext=function(e){var t=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return e()}finally{this.state.topicContext=t}},r.withSmartMixTopicForbiddingContext=function(e){if(!this.hasPlugin(["pipelineOperator",{proposal:"smart"}]))return e();var t=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return e()}finally{this.state.topicContext=t}},r.withSoloAwaitPermittingContext=function(e){var t=this.state.soloAwait;this.state.soloAwait=!0;try{return e()}finally{this.state.soloAwait=t}},r.allowInAnd=function(e){var t=this.prodParam.currentFlags();if(Gx&~t){this.prodParam.enter(t|Gx);try{return e()}finally{this.prodParam.exit()}}return e()},r.disallowInAnd=function(e){var t=this.prodParam.currentFlags();if(Gx&t){this.prodParam.enter(t&~Gx);try{return e()}finally{this.prodParam.exit()}}return e()},r.registerTopicReference=function(){this.state.topicContext.maxTopicIndex=0},r.topicReferenceIsAllowedInCurrentContext=function(){return this.state.topicContext.maxNumOfResolvableTopics>=1},r.topicReferenceWasUsedInCurrentContext=function(){return null!=this.state.topicContext.maxTopicIndex&&this.state.topicContext.maxTopicIndex>=0},r.parseFSharpPipelineBody=function(e){var t=this.state.startLoc;this.state.potentialArrowAt=this.state.start;var r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;var a=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),t,e);return this.state.inFSharpPipelineDirectBody=r,a},r.parseModuleExpression=function(){this.expectPlugin("moduleBlocks");var e=this.startNode();this.next(),this.match(5)||this.unexpected(null,5);var t=this.startNodeAt(this.state.endLoc);this.next();var r=this.initializeScopes(!0);this.enterInitialScopes();try{e.body=this.parseProgram(t,8,"module")}finally{r()}return this.finishNode(e,"ModuleExpression")},r.parseVoidPattern=function(e){this.expectPlugin("discardBinding");var t=this.startNode();return null!=e&&(e.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(t,"VoidPattern")},r.parseMaybeAssignAllowInOrVoidPattern=function(e,t,r){if(null!=t&&this.match(88)){var a=this.lookaheadCharCode();if(44===a||a===(3===e?93:8===e?125:41)||61===a)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(t))}return this.parseMaybeAssignAllowIn(t,r)},r.parsePropertyNamePrefixOperator=function(e){},o(t)}(xv),Fv={kind:Yx},Lv={kind:$x},Uv=0,qv=1,Gv=2,Wv=4,Vv=8,Hv=0,Kv=1,zv=2,Xv=4,Jv=8,Yv=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,$v=new RegExp("in(?:stanceof)?","y");var Qv=function(e){function t(){return e.apply(this,arguments)||this}c(t,e);var r=t.prototype;return r.parseTopLevel=function(e,t){return e.program=this.parseProgram(t,140,"module"===this.options.sourceType?"module":"script"),e.comments=this.comments,this.optionFlags&kh&&(e.tokens=function(e,t,r){for(var a=0;a0)for(var a=0,n=Array.from(this.scope.undefinedExports);a=90&&o<=92?Yx:this.match(71)?$x:null,d=this.state.labels.length-1;d>=0;d--){var c=this.state.labels[d];if(c.statementStart!==e.start)break;c.statementStart=this.sourceToOffsetPos(this.state.start),c.kind=i}return this.state.labels.push({name:t,kind:i,statementStart:this.sourceToOffsetPos(this.state.start)}),e.body=a&Jv?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")},r.parseExpressionStatement=function(e,t,r){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},r.parseBlock=function(e,t,r){void 0===e&&(e=!1),void 0===t&&(t=!0);var a=this.startNode();return e&&this.state.strictErrors.clear(),this.expect(5),t&&this.scope.enter(hb),this.parseBlockBody(a,e,!1,8,r),t&&this.scope.exit(),this.finishNode(a,"BlockStatement")},r.isValidDirective=function(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized},r.parseBlockBody=function(e,t,r,a,n){var s=e.body=[],o=e.directives=[];this.parseBlockOrModuleBlockBody(s,t?o:void 0,r,a,n)},r.parseBlockOrModuleBlockBody=function(e,t,r,a,n){for(var s=this.state.strict,o=!1,i=!1;!this.match(a);){var d=r?this.parseModuleItem():this.parseStatementListItem();if(t&&!i){if(this.isValidDirective(d)){var c=this.stmtToDirective(d);t.push(c),o||"use strict"!==c.value.value||(o=!0,this.setStrict(!0));continue}i=!0,this.state.strictErrors.clear()}e.push(d)}null==n||n.call(this,o),s||this.setStrict(!1),this.next()},r.parseFor=function(e,t){var r=this;return e.init=t,this.semicolon(!1),e.test=this.match(13)?null:this.parseExpression(),this.semicolon(!1),e.update=this.match(11)?null:this.parseExpression(),this.expect(11),e.body=this.withSmartMixTopicForbiddingContext((function(){return r.parseStatement()})),this.scope.exit(),this.state.labels.pop(),this.finishNode(e,"ForStatement")},r.parseForIn=function(e,t,r){var a=this,n=this.match(58);return this.next(),n?null!==r&&this.unexpected(r):e.await=null!==r,"VariableDeclaration"!==t.type||null==t.declarations[0].init||n&&this.options.annexB&&!this.state.strict&&"var"===t.kind&&"Identifier"===t.declarations[0].id.type||this.raise(vh.ForInOfLoopInitializer,t,{type:n?"ForInStatement":"ForOfStatement"}),"AssignmentPattern"===t.type&&this.raise(vh.InvalidLhs,t,{ancestor:{type:"ForStatement"}}),e.left=t,e.right=n?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),e.body=this.withSmartMixTopicForbiddingContext((function(){return a.parseStatement()})),this.scope.exit(),this.state.labels.pop(),this.finishNode(e,n?"ForInStatement":"ForOfStatement")},r.parseVar=function(e,t,r,a){void 0===a&&(a=!1);var n=e.declarations=[];for(e.kind=r;;){var s=this.startNode();if(this.parseVarId(s,r),s.init=this.eat(29)?t?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,null!==s.init||a||("Identifier"===s.id.type||t&&(this.match(58)||this.isContextual(102))?"const"!==r&&"using"!==r&&"await using"!==r||this.match(58)||this.isContextual(102)||this.raise(vh.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r}):this.raise(vh.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"})),n.push(this.finishNode(s,"VariableDeclarator")),!this.eat(12))break}return e},r.parseVarId=function(e,t){var r=this.parseBindingAtom();"using"===t||"await using"===t?"ArrayPattern"!==r.type&&"ObjectPattern"!==r.type||this.raise(vh.UsingDeclarationHasBindingPattern,r.loc.start):"VoidPattern"===r.type&&this.raise(vh.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},"var"===t?zb:Hb),e.id=r},r.parseAsyncFunctionExpression=function(e){return this.parseFunction(e,Vv)},r.parseFunction=function(e,t){var r=this;void 0===t&&(t=Uv);var a=t&Gv,n=!!(t&qv),s=n&&!(t&Wv),o=!!(t&Vv);this.initFunction(e,o),this.match(55)&&(a&&this.raise(vh.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),e.generator=!0),n&&(e.id=this.parseFunctionId(s));var i=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(kb),this.prodParam.enter(Vx(o,e.generator)),n||(e.id=this.parseFunctionId()),this.parseFunctionParams(e,!1),this.withSmartMixTopicForbiddingContext((function(){r.parseFunctionBodyAndFinish(e,n?"FunctionDeclaration":"FunctionExpression")})),this.prodParam.exit(),this.scope.exit(),n&&!a&&this.registerFunctionStatementId(e),this.state.maybeInArrowParameters=i,e},r.parseFunctionId=function(e){return e||sb(this.state.type)?this.parseIdentifier():null},r.parseFunctionParams=function(e,t){this.expect(10),this.expressionScope.enter(new sv(3)),e.params=this.parseBindingList(11,41,hv|(t?bv:0)),this.expressionScope.exit()},r.registerFunctionStatementId=function(e){e.id&&this.scope.declareName(e.id.name,!this.options.annexB||this.state.strict||e.generator||e.async?this.scope.treatFunctionsAsVar?zb:Hb:Xb,e.id.loc.start)},r.parseClass=function(e,t,r){this.next();var a=this.state.strict;return this.state.strict=!0,this.parseClassId(e,t,r),this.parseClassSuper(e),e.body=this.parseClassBody(!!e.superClass,a),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},r.isClassProperty=function(){return this.match(29)||this.match(13)||this.match(8)},r.isClassMethod=function(){return this.match(10)},r.nameIsConstructor=function(e){return"Identifier"===e.type&&"constructor"===e.name||"StringLiteral"===e.type&&"constructor"===e.value},r.isNonstaticConstructor=function(e){return!e.computed&&!e.static&&this.nameIsConstructor(e.key)},r.parseClassBody=function(e,t){var r=this;this.classScope.enter();var a={hadConstructor:!1,hadSuperClass:e},n=[],s=this.startNode();if(s.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext((function(){for(;!r.match(8);)if(r.eat(13)){if(n.length>0)throw r.raise(vh.DecoratorSemicolon,r.state.lastTokEndLoc)}else if(r.match(26))n.push(r.parseDecorator());else{var e=r.startNode();n.length&&(e.decorators=n,r.resetStartLocationFromNode(e,n[0]),n=[]),r.parseClassMember(s,e,a),"constructor"===e.kind&&e.decorators&&e.decorators.length>0&&r.raise(vh.DecoratorConstructor,e)}})),this.state.strict=t,this.next(),n.length)throw this.raise(vh.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(s,"ClassBody")},r.parseClassMemberFromModifier=function(e,t){var r=this.parseIdentifier(!0);if(this.isClassMethod()){var a=t;return a.kind="method",a.computed=!1,a.key=r,a.static=!1,this.pushClassMethod(e,a,!1,!1,!1,!1),!0}if(this.isClassProperty()){var n=t;return n.computed=!1,n.key=r,n.static=!1,e.body.push(this.parseClassProperty(n)),!0}return this.resetPreviousNodeTrailingComments(r),!1},r.parseClassMember=function(e,t,r){var a=this.isContextual(106);if(a){if(this.parseClassMemberFromModifier(e,t))return;if(this.eat(5))return void this.parseClassStaticBlock(e,t)}this.parseClassMemberWithIsStatic(e,t,r,a)},r.parseClassMemberWithIsStatic=function(e,t,r,a){var n=t,s=t,o=t,i=t,d=t,c=n,l=n;if(t.static=a,this.parsePropertyNamePrefixOperator(t),this.eat(55)){c.kind="method";var u=this.match(139);return this.parseClassElementName(c),this.parsePostMemberNameModifiers(c),u?void this.pushClassPrivateMethod(e,s,!0,!1):(this.isNonstaticConstructor(n)&&this.raise(vh.ConstructorIsGenerator,n.key),void this.pushClassMethod(e,n,!0,!1,!1,!1))}var p=!this.state.containsEsc&&sb(this.state.type),f=this.parseClassElementName(t),g=p?f.name:null,y=this.isPrivateName(f),m=this.state.startLoc;if(this.parsePostMemberNameModifiers(l),this.isClassMethod()){if(c.kind="method",y)return void this.pushClassPrivateMethod(e,s,!1,!1);var h=this.isNonstaticConstructor(n),b=!1;h&&(n.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(vh.DuplicateConstructor,f),h&&this.hasPlugin("typescript")&&t.override&&this.raise(vh.OverrideOnConstructor,f),r.hadConstructor=!0,b=r.hadSuperClass),this.pushClassMethod(e,n,!1,!1,h,b)}else if(this.isClassProperty())y?this.pushClassPrivateProperty(e,i):this.pushClassProperty(e,o);else if("async"!==g||this.isLineTerminator())if("get"!==g&&"set"!==g||this.match(55)&&this.isLineTerminator())if("accessor"!==g||this.isLineTerminator())this.isLineTerminator()?y?this.pushClassPrivateProperty(e,i):this.pushClassProperty(e,o):this.unexpected();else{this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);var x=this.match(139);this.parseClassElementName(o),this.pushClassAccessorProperty(e,d,x)}else{this.resetPreviousNodeTrailingComments(f),c.kind=g;var v=this.match(139);this.parseClassElementName(n),v?this.pushClassPrivateMethod(e,s,!1,!1):(this.isNonstaticConstructor(n)&&this.raise(vh.ConstructorIsAccessor,n.key),this.pushClassMethod(e,n,!1,!1,!1,!1)),this.checkGetterSetterParams(n)}else{this.resetPreviousNodeTrailingComments(f);var R=this.eat(55);l.optional&&this.unexpected(m),c.kind="method";var j=this.match(139);this.parseClassElementName(c),this.parsePostMemberNameModifiers(l),j?this.pushClassPrivateMethod(e,s,R,!0):(this.isNonstaticConstructor(n)&&this.raise(vh.ConstructorIsAsync,n.key),this.pushClassMethod(e,n,R,!0,!1,!1))}},r.parseClassElementName=function(e){var t=this.state,r=t.type,a=t.value;if(132!==r&&134!==r||!e.static||"prototype"!==a||this.raise(vh.StaticPrototype,this.state.startLoc),139===r){"constructor"===a&&this.raise(vh.ConstructorClassPrivateField,this.state.startLoc);var n=this.parsePrivateName();return e.key=n,n}return this.parsePropertyName(e),e.key},r.parseClassStaticBlock=function(e,t){var r;this.scope.enter(Cb|Sb|jb);var a=this.state.labels;this.state.labels=[],this.prodParam.enter(Fx);var n=t.body=[];this.parseBlockOrModuleBlockBody(n,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=a,e.body.push(this.finishNode(t,"StaticBlock")),null!=(r=t.decorators)&&r.length&&this.raise(vh.DecoratorStaticBlock,t)},r.pushClassProperty=function(e,t){!t.computed&&this.nameIsConstructor(t.key)&&this.raise(vh.ConstructorClassField,t.key),e.body.push(this.parseClassProperty(t))},r.pushClassPrivateProperty=function(e,t){var r=this.parseClassPrivateProperty(t);e.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),ox,r.key.loc.start)},r.pushClassAccessorProperty=function(e,t,r){r||t.computed||!this.nameIsConstructor(t.key)||this.raise(vh.ConstructorClassField,t.key);var a=this.parseClassAccessorProperty(t);e.body.push(a),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(a.key),ox,a.key.loc.start)},r.pushClassMethod=function(e,t,r,a,n,s){e.body.push(this.parseMethod(t,r,a,n,s,"ClassMethod",!0))},r.pushClassPrivateMethod=function(e,t,r,a){var n=this.parseMethod(t,r,a,!1,!1,"ClassPrivateMethod",!0);e.body.push(n);var s="get"===n.kind?n.static?cx:ux:"set"===n.kind?n.static?lx:px:ox;this.declareClassPrivateMethodInScope(n,s)},r.declareClassPrivateMethodInScope=function(e,t){this.classScope.declarePrivateName(this.getPrivateNameSV(e.key),t,e.key.loc.start)},r.parsePostMemberNameModifiers=function(e){},r.parseClassPrivateProperty=function(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassPrivateProperty")},r.parseClassProperty=function(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassProperty")},r.parseClassAccessorProperty=function(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassAccessorProperty")},r.parseInitializer=function(e){this.scope.enter(Cb|jb),this.expressionScope.enter(dv()),this.prodParam.enter(Fx),e.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()},r.parseClassId=function(e,t,r,a){if(void 0===a&&(a=Vb),sb(this.state.type))e.id=this.parseIdentifier(),t&&this.declareNameFromIdentifier(e.id,a);else{if(!r&&t)throw this.raise(vh.MissingClassName,this.state.startLoc);e.id=null}},r.parseClassSuper=function(e){e.superClass=this.eat(81)?this.parseExprSubscripts():null},r.parseExport=function(e,t){var r=this.parseMaybeImportPhase(e,!0),a=this.maybeParseExportDefaultSpecifier(e,r),n=!a||this.eat(12),s=n&&this.eatExportStar(e),o=s&&this.maybeParseExportNamespaceSpecifier(e),i=n&&(!o||this.eat(12)),d=a||s;if(s&&!o){if(a&&this.unexpected(),t)throw this.raise(vh.UnsupportedDecoratorExport,e);return this.parseExportFrom(e,!0),this.sawUnambiguousESM=!0,this.finishNode(e,"ExportAllDeclaration")}var c,l=this.maybeParseExportNamedSpecifiers(e);if(a&&n&&!s&&!l&&this.unexpected(null,5),o&&i&&this.unexpected(null,98),d||l){if(c=!1,t)throw this.raise(vh.UnsupportedDecoratorExport,e);this.parseExportFrom(e,d)}else c=this.maybeParseExportDeclaration(e);if(d||l||c){var u,p=e;if(this.checkExport(p,!0,!1,!!p.source),"ClassDeclaration"===(null==(u=p.declaration)?void 0:u.type))this.maybeTakeDecorators(t,p.declaration,p);else if(t)throw this.raise(vh.UnsupportedDecoratorExport,e);return this.sawUnambiguousESM=!0,this.finishNode(p,"ExportNamedDeclaration")}if(this.eat(65)){var f=e,g=this.parseExportDefaultExpression();if(f.declaration=g,"ClassDeclaration"===g.type)this.maybeTakeDecorators(t,g,f);else if(t)throw this.raise(vh.UnsupportedDecoratorExport,e);return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}this.unexpected(null,5)},r.eatExportStar=function(e){return this.eat(55)},r.maybeParseExportDefaultSpecifier=function(e,t){if(t||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",null==t?void 0:t.loc.start);var r=t||this.parseIdentifier(!0),a=this.startNodeAtNode(r);return a.exported=r,e.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],!0}return!1},r.maybeParseExportNamespaceSpecifier=function(e){if(this.isContextual(93)){var t;null!=(t=e).specifiers||(t.specifiers=[]);var r=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),r.exported=this.parseModuleExportName(),e.specifiers.push(this.finishNode(r,"ExportNamespaceSpecifier")),!0}return!1},r.maybeParseExportNamedSpecifiers=function(e){if(this.match(5)){var t,r=e;r.specifiers||(r.specifiers=[]);var a="type"===r.exportKind;return(t=r.specifiers).push.apply(t,this.parseExportSpecifiers(a)),r.source=null,this.hasPlugin("importAssertions")?r.assertions=[]:r.attributes=[],r.declaration=null,!0}return!1},r.maybeParseExportDeclaration=function(e){return!!this.shouldParseExportDeclaration()&&(e.specifiers=[],e.source=null,this.hasPlugin("importAssertions")?e.assertions=[]:e.attributes=[],e.declaration=this.parseExportDeclaration(e),!0)},r.isAsyncFunction=function(){if(!this.isContextual(95))return!1;var e=this.nextTokenInLineStart();return this.isUnparsedContextual(e,"function")},r.parseExportDefaultExpression=function(){var e=this.startNode();if(this.match(68))return this.next(),this.parseFunction(e,qv|Wv);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(e,qv|Wv|Vv);if(this.match(80))return this.parseClass(e,!0,!0);if(this.match(26))return this.hasPlugin("decorators")&&!0===this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(vh.DecoratorBeforeExport,this.state.startLoc),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(vh.UnsupportedDefaultExport,this.state.startLoc);var t=this.parseMaybeAssignAllowIn();return this.semicolon(),t},r.parseExportDeclaration=function(e){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()},r.isExportDefaultSpecifier=function(){var e=this.state.type;if(sb(e)){if(95===e&&!this.state.containsEsc||100===e)return!1;if((130===e||129===e)&&!this.state.containsEsc){var t=this.nextTokenStart(),r=this.input.charCodeAt(t);if(123===r||this.chStartsBindingIdentifier(r,t)&&!this.input.startsWith("from",t))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;var a=this.nextTokenStart(),n=this.isUnparsedContextual(a,"from");if(44===this.input.charCodeAt(a)||sb(this.state.type)&&n)return!0;if(this.match(65)&&n){var s=this.input.charCodeAt(this.nextTokenStartSince(a+4));return 34===s||39===s}return!1},r.parseExportFrom=function(e,t){this.eatContextual(98)?(e.source=this.parseImportSource(),this.checkExport(e),this.maybeParseImportAttributes(e),this.checkJSONModuleImport(e)):t&&this.unexpected(),this.semicolon()},r.shouldParseExportDeclaration=function(){var e=this.state.type;return 26===e&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))?(!0===this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(vh.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()||this.isAwaitUsing()?(this.raise(vh.UsingDeclarationExport,this.state.startLoc),!0):74===e||75===e||68===e||80===e||this.isLet()||this.isAsyncFunction()},r.checkExport=function(e,t,r,a){var n;if(t)if(r){if(this.checkDuplicateExports(e,"default"),this.hasPlugin("exportDefaultFrom")){var s,o=e.declaration;"Identifier"!==o.type||"from"!==o.name||o.end-o.start!=4||null!=(s=o.extra)&&s.parenthesized||this.raise(vh.ExportDefaultFromAsIdentifier,o)}}else if(null!=(n=e.specifiers)&&n.length)for(var i=0,d=e.specifiers;i0&&this.raise(vh.ImportReflectionHasAssertion,t[0].loc.start)}},r.checkJSONModuleImport=function(e){if(this.isJSONModuleImport(e)&&"ExportAllDeclaration"!==e.type){var t=e.specifiers;if(null!=t){var r=t.find((function(e){var t;if("ExportSpecifier"===e.type?t=e.local:"ImportSpecifier"===e.type&&(t=e.imported),void 0!==t)return"Identifier"===t.type?"default"!==t.name:"default"!==t.value}));void 0!==r&&this.raise(vh.ImportJSONBindingNotDefault,r.loc.start)}}},r.isPotentialImportPhase=function(e){return!e&&(this.isContextual(105)||this.isContextual(97)||this.isContextual(127))},r.applyImportPhase=function(e,t,r,a){t||("module"===r?(this.expectPlugin("importReflection",a),e.module=!0):this.hasPlugin("importReflection")&&(e.module=!1),"source"===r?(this.expectPlugin("sourcePhaseImports",a),e.phase="source"):"defer"===r?(this.expectPlugin("deferredImportEvaluation",a),e.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(e.phase=null))},r.parseMaybeImportPhase=function(e,t){if(!this.isPotentialImportPhase(t))return this.applyImportPhase(e,t,null),null;var r=this.startNode(),a=this.parseIdentifierName(!0),n=this.state.type;return(ob(n)?98!==n||102===this.lookaheadCharCode():12!==n)?(this.applyImportPhase(e,t,a,r.loc.start),null):(this.applyImportPhase(e,t,null),this.createIdentifier(r,a))},r.isPrecedingIdImportPhase=function(e){var t=this.state.type;return sb(t)?98!==t||102===this.lookaheadCharCode():12!==t},r.parseImport=function(e){return this.match(134)?this.parseImportSourceAndAttributes(e):this.parseImportSpecifiersAndAfter(e,this.parseMaybeImportPhase(e,!1))},r.parseImportSpecifiersAndAfter=function(e,t){e.specifiers=[];var r=!this.maybeParseDefaultImportSpecifier(e,t)||this.eat(12),a=r&&this.maybeParseStarImportSpecifier(e);return r&&!a&&this.parseNamedImportSpecifiers(e),this.expectContextual(98),this.parseImportSourceAndAttributes(e)},r.parseImportSourceAndAttributes=function(e){return null!=e.specifiers||(e.specifiers=[]),e.source=this.parseImportSource(),this.maybeParseImportAttributes(e),this.checkImportReflection(e),this.checkJSONModuleImport(e),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(e,"ImportDeclaration")},r.parseImportSource=function(){return this.match(134)||this.unexpected(),this.parseExprAtom()},r.parseImportSpecifierLocal=function(e,t,r){t.local=this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(t,r))},r.finishImportSpecifier=function(e,t,r){return void 0===r&&(r=Hb),this.checkLVal(e.local,{type:t},r),this.finishNode(e,t)},r.parseImportAttributes=function(){this.expect(5);var e=[],t=new Set;do{if(this.match(8))break;var r=this.startNode(),a=this.state.value;if(t.has(a)&&this.raise(vh.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:a}),t.add(a),this.match(134)?r.key=this.parseStringLiteral(a):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(vh.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),e.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return this.expect(8),e},r.parseModuleAttributes=function(){var e=[],t=new Set;do{var r=this.startNode();if(r.key=this.parseIdentifier(!0),"type"!==r.key.name&&this.raise(vh.ModuleAttributeDifferentFromType,r.key),t.has(r.key.name)&&this.raise(vh.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),t.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(vh.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),e.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return e},r.maybeParseImportAttributes=function(e){var t,r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&40===this.lookaheadCharCode())return;this.next(),this.hasPlugin("moduleAttributes")?(t=this.parseModuleAttributes(),this.addExtra(e,"deprecatedWithLegacySyntax",!0)):t=this.parseImportAttributes(),r=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(this.hasPlugin("deprecatedImportAssert")||this.hasPlugin("importAssertions")||this.raise(vh.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(e,"deprecatedAssertSyntax",!0),this.next(),t=this.parseImportAttributes()):t=[];!r&&this.hasPlugin("importAssertions")?e.assertions=t:e.attributes=t},r.maybeParseDefaultImportSpecifier=function(e,t){if(t){var r=this.startNodeAtNode(t);return r.local=t,e.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}return!!ob(this.state.type)&&(this.parseImportSpecifierLocal(e,this.startNode(),"ImportDefaultSpecifier"),!0)},r.maybeParseStarImportSpecifier=function(e){if(this.match(55)){var t=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(e,t,"ImportNamespaceSpecifier"),!0}return!1},r.parseNamedImportSpecifiers=function(e){var t=!0;for(this.expect(5);!this.eat(8);){if(t)t=!1;else{if(this.eat(14))throw this.raise(vh.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}var r=this.startNode(),a=this.match(134),n=this.isContextual(130);r.imported=this.parseModuleExportName();var s=this.parseImportSpecifier(r,a,"type"===e.importKind||"typeof"===e.importKind,n,void 0);e.specifiers.push(s)}},r.parseImportSpecifier=function(e,t,r,a,n){if(this.eatContextual(93))e.local=this.parseIdentifier();else{var s=e.imported;if(t)throw this.raise(vh.ImportBindingIsString,e,{importName:s.value});this.checkReservedWord(s.name,e.loc.start,!0,!0),e.local||(e.local=this.cloneIdentifier(s))}return this.finishImportSpecifier(e,"ImportSpecifier",n)},r.isThisParam=function(e){return"Identifier"===e.type&&"this"===e.name},o(t)}(Mv),Zv=function(e){function t(t,r,a){var n;t=function(e){var t={sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:null,ranges:!1,tokens:!1,createImportExpressions:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0};if(null==e)return t;if(null!=e.annexB&&!1!==e.annexB)throw new Error("The `annexB` option can only be set to `false`.");for(var r=0,a=Object.keys(t);r0?t.startIndex=t.startColumn:null==e.startColumn&&t.startIndex>0&&(t.startColumn=t.startIndex);else if((null==e.startColumn||null==e.startIndex)&&null!=e.startIndex)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if("commonjs"===t.sourceType){if(null!=e.allowAwaitOutsideFunction)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(null!=e.allowReturnOutsideFunction)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(null!=e.allowNewTargetOutsideFunction)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return t}(t),(n=e.call(this,t,r)||this).options=t,n.initializeScopes(),n.plugins=a,n.filename=t.sourceFilename,n.startIndex=t.startIndex;var s=0;return t.allowAwaitOutsideFunction&&(s|=Rh),t.allowReturnOutsideFunction&&(s|=jh),t.allowImportExportEverywhere&&(s|=Eh),t.allowSuperOutsideMethod&&(s|=Sh),t.allowUndeclaredExports&&(s|=Ph),t.allowNewTargetOutsideFunction&&(s|=wh),t.allowYieldOutsideFunction&&(s|=Th),t.ranges&&(s|=Ah),t.tokens&&(s|=kh),t.createImportExpressions&&(s|=Ch),t.createParenthesizedExpressions&&(s|=_h),t.errorRecovery&&(s|=Ih),t.attachComment&&(s|=Dh),t.annexB&&(s|=Oh),n.optionFlags=s,n}c(t,e);var r=t.prototype;return r.getScopeHandler=function(){return hx},r.parse=function(){this.enterInitialScopes();var e=this.startNode(),t=this.startNode();return this.nextToken(),e.errors=null,this.parseTopLevel(e,t),e.errors=this.state.errors,e.comments.length=this.state.commentsLen,e},o(t)}(Qv);function eR(e,t){var r;if("unambiguous"!==(null==(r=t)?void 0:r.sourceType))return rR(t,e).parse();t=Object.assign({},t);try{t.sourceType="module";var a=rR(t,e),n=a.parse();if(a.sawUnambiguousESM)return n;if(a.ambiguousScriptDifferentAst)try{return t.sourceType="script",rR(t,e).parse()}catch(e){}else n.program.sourceType="script";return n}catch(r){try{return t.sourceType="script",rR(t,e).parse()}catch(e){}throw r}}var tR=function(e){for(var t={},r=0,a=Object.keys(e);r!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g,bR.matchToToken=function(e){var t={type:"invalid",value:e[0],closed:void 0};return e[1]?(t.type="string",t.closed=!(!e[3]&&!e[4])):e[5]?t.type="comment":e[6]?(t.type="comment",t.closed=!!e[7]):e[8]?t.type="regex":e[9]?t.type="number":e[10]?t.type="name":e[11]?t.type="punctuator":e[12]&&(t.type="whitespace"),t}),bR}var vR,RR=(void K.env.BABEL_8_BREAKING,xR()),jR=new Set(["as","async","from","get","of","set"]),wR=/\r\n|[\n\r\u2028\u2029]/,ER=/^[()[\]{}]$/,SR=/^[a-z][\w-]*$/i,TR=function(e,t,r){if("name"===e.type){if(Qr(e.value)||Jr(e.value,!0)||jR.has(e.value))return"keyword";if(SR.test(e.value)&&("<"===r[t-1]||""),n.gutter(s),e.length>0?" "+e:"",l].join("")}return" "+n.gutter(s)+(e.length>0?" "+e:"")})).join("\n");return r.message&&!l&&(f=""+" ".repeat(u+1)+r.message+"\n"+f),a?n.reset(f):f}var kR=ee,CR=ae,_R=dr,IR=de,DR=kt,OR=he,NR=Ot,BR=nr,MR=ue,FR=Em,LR=Nm,UR=/^[_$A-Z0-9]+$/;function qR(e,t,r){var a=r.placeholderWhitelist,n=r.placeholderPattern,s=r.preserveComments,o=r.syntacticPlaceholders,i=function(e,t,r){var a=(t.plugins||[]).slice();!1!==r&&a.push("placeholders");t=Object.assign({allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0,allowNewTargetOutsideFunction:!0,allowSuperOutsideMethod:!0,allowYieldOutsideFunction:!0,sourceType:"module"},t,{plugins:a});try{return eR(e,t)}catch(t){var n=t.loc;throw n&&(t.message+="\n"+AR(e,{start:n}),t.code="BABEL_TEMPLATE_PARSE_ERROR"),t}}(t,r.parser,o);FR(i,{preserveComments:s}),e.validate(i);var d={syntactic:{placeholders:[],placeholderNames:new Set},legacy:{placeholders:[],placeholderNames:new Set},placeholderWhitelist:a,placeholderPattern:n,syntacticPlaceholders:o};return LR(i,GR,d),Object.assign({ast:i},d.syntactic.placeholders.length?d.syntactic:d.legacy)}function GR(e,t,r){var a,n,s=r.syntactic.placeholders.length>0;if(NR(e)){if(!1===r.syntacticPlaceholders)throw new Error("%%foo%%-style placeholders can't be used when '.syntacticPlaceholders' is false.");n=e.name.name,s=!0}else{if(s||r.syntacticPlaceholders)return;if(IR(e)||DR(e))n=e.name;else{if(!MR(e))return;n=e.value}}if(s&&(null!=r.placeholderPattern||null!=r.placeholderWhitelist))throw new Error("'.placeholderWhitelist' and '.placeholderPattern' aren't compatible with '.syntacticPlaceholders: true'");if(s||!1!==r.placeholderPattern&&(r.placeholderPattern||UR).test(n)||null!=(a=r.placeholderWhitelist)&&a.has(n)){var o,i=(t=t.slice())[t.length-1],d=i.node,c=i.key;MR(e)||NR(e,{expectedNode:"StringLiteral"})?o="string":OR(d)&&"arguments"===c||kR(d)&&"arguments"===c||_R(d)&&"params"===c?o="param":CR(d)&&!NR(e)?(o="statement",t=t.slice(0,-1)):o=BR(e)&&NR(e)?"statement":"other";var l=s?r.syntactic:r.legacy,u=l.placeholders,p=l.placeholderNames;u.push({name:n,type:o,resolve:function(e){return function(e,t){for(var r=e,a=0;a1?a-1:0),o=1;o1)throw new Error("Unexpected extra params.");return aj(ZR(e,t,rh(n,ah(s[0]))))}if(Array.isArray(t)){var i=r.get(t);return i||(i=ej(e,t,n),r.set(t,i)),aj(i(s))}if("object"==typeof t&&t){if(s.length>0)throw new Error("Unexpected extra params.");return rj(e,rh(n,ah(t)))}throw new Error("Unexpected template param "+typeof t)}),{ast:function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o1)throw new Error("Unexpected extra params.");return ZR(e,t,rh(rh(n,ah(s[0])),tj))()}if(Array.isArray(t)){var i=a.get(t);return i||(i=ej(e,t,rh(n,tj)),a.set(t,i)),i(s)()}throw new Error("Unexpected template param "+typeof t)}})}function aj(e){var t="";try{throw new Error}catch(e){e.stack&&(t=e.stack.split("\n").slice(3).join("\n"))}return function(r){try{return e(r)}catch(e){throw e.stack+="\n =============\n"+t,e}}}var nj=rj($m),sj=rj(Zm),oj=rj(Qm),ij=rj(eh),dj=rj({code:function(e){return e},validate:function(){},unwrap:function(e){return e.program}}),cj=Object.assign(nj.bind(void 0),{smart:nj,statement:sj,statements:oj,expression:ij,program:dj,ast:nj.ast}),lj=Object.freeze({__proto__:null,default:cj,expression:ij,program:dj,smart:nj,statement:sj,statements:oj});function uj(e,t,r){return Object.freeze({minVersion:e,ast:function(){return cj.program.ast(t,{preserveComments:!0})},metadata:r})}var pj={__proto__:null,OverloadYield:uj("7.18.14","function _OverloadYield(e,d){this.v=e,this.k=d}",{globals:[],locals:{_OverloadYield:["body.0.id"]},exportBindingAssignments:[],exportName:"_OverloadYield",dependencies:{},internal:!1}),applyDecoratedDescriptor:uj("7.0.0-beta.0",'function _applyDecoratedDescriptor(i,e,r,n,l){var a={};return Object.keys(n).forEach((function(i){a[i]=n[i]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce((function(r,n){return n(i,e,r)||r}),a),l&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(l):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(i,e,a),null):a}',{globals:["Object"],locals:{_applyDecoratedDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_applyDecoratedDescriptor",dependencies:{},internal:!1}),applyDecs2311:uj("7.24.0",'function applyDecs2311(e,t,n,r,o,i){var a,c,u,s,f,l,p,d=Symbol.metadata||Symbol.for("Symbol.metadata"),m=Object.defineProperty,h=Object.create,y=[h(null),h(null)],v=t.length;function g(t,n,r){return function(o,i){n&&(i=o,o=e);for(var a=0;a=0;O-=n?2:1){var T=b(h[O],"A decorator","be",!0),z=n?h[O-1]:void 0,A={},H={kind:["field","accessor","method","getter","setter","class"][o],name:r,metadata:a,addInitializer:function(e,t){if(e.v)throw new TypeError("attempted to call addInitializer after decoration was finished");b(t,"An initializer","be",!0),i.push(t)}.bind(null,A)};if(w)c=T.call(z,N,H),A.v=1,b(c,"class decorators","return")&&(N=c);else if(H.static=s,H.private=f,c=H.access={has:f?p.bind():function(e){return r in e}},j||(c.get=f?E?function(e){return d(e),P.value}:I("get",0,d):function(e){return e[r]}),E||S||(c.set=f?I("set",0,d):function(e,t){e[r]=t}),N=T.call(z,D?{get:P.get,set:P.set}:P[F],H),A.v=1,D){if("object"==typeof N&&N)(c=b(N.get,"accessor.get"))&&(P.get=c),(c=b(N.set,"accessor.set"))&&(P.set=c),(c=b(N.init,"accessor.init"))&&k.unshift(c);else if(void 0!==N)throw new TypeError("accessor decorators must return an object with get, set, or init properties or undefined")}else b(N,(l?"field":"method")+" decorators","return")&&(l?k.unshift(N):P[F]=N)}return o<2&&u.push(g(k,s,1),g(i,s,0)),l||w||(f?D?u.splice(-1,0,I("get",s),I("set",s)):u.push(E?P[F]:b.call.bind(P[F])):m(e,r,P)),N}function w(e){return m(e,d,{configurable:!0,enumerable:!0,value:a})}return void 0!==i&&(a=i[d]),a=h(null==a?null:a),f=[],l=function(e){e&&f.push(g(e))},p=function(t,r){for(var i=0;ir.length)&&(a=r.length);for(var e=0,n=Array(a);e=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}',{globals:["Symbol","Array","TypeError"],locals:{_createForOfIteratorHelper:["body.0.id"]},exportBindingAssignments:[],exportName:"_createForOfIteratorHelper",dependencies:{unsupportedIterableToArray:["body.0.body.body.1.consequent.body.0.test.left.right.right.callee"]},internal:!1}),createForOfIteratorHelperLoose:uj("7.9.0",'function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}',{globals:["Symbol","Array","TypeError"],locals:{_createForOfIteratorHelperLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_createForOfIteratorHelperLoose",dependencies:{unsupportedIterableToArray:["body.0.body.body.2.test.left.right.right.callee"]},internal:!1}),createSuper:uj("7.9.0","function _createSuper(t){var r=isNativeReflectConstruct();return function(){var e,o=getPrototypeOf(t);if(r){var s=getPrototypeOf(this).constructor;e=Reflect.construct(o,arguments,s)}else e=o.apply(this,arguments);return possibleConstructorReturn(this,e)}}",{globals:["Reflect"],locals:{_createSuper:["body.0.id"]},exportBindingAssignments:[],exportName:"_createSuper",dependencies:{getPrototypeOf:["body.0.body.body.1.argument.body.body.0.declarations.1.init.callee","body.0.body.body.1.argument.body.body.1.consequent.body.0.declarations.0.init.object.callee"],isNativeReflectConstruct:["body.0.body.body.0.declarations.0.init.callee"],possibleConstructorReturn:["body.0.body.body.1.argument.body.body.2.argument.callee"]},internal:!1}),decorate:uj("7.1.5",'function _decorate(e,r,t,i){var o=_getDecoratorsApi();if(i)for(var n=0;n=0;n--){var s=r[e.placement];s.splice(s.indexOf(e.key),1);var a=this.fromElementDescriptor(e),l=this.toElementFinisherExtras((0,o[n])(a)||a);e=l.element,this.addElementPlacement(e,r),l.finisher&&i.push(l.finisher);var c=l.extras;if(c){for(var p=0;p=0;i--){var o=this.fromClassDescriptor(e),n=this.toClassDescriptor((0,r[i])(o)||o);if(void 0!==n.finisher&&t.push(n.finisher),void 0!==n.elements){e=n.elements;for(var s=0;s1){for(var t=Array(n),f=0;f3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a \'"+o+"\' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(define(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,define(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,define(u,"constructor",GeneratorFunctionPrototype),define(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",define(GeneratorFunctionPrototype,o,"GeneratorFunction"),define(u),define(u,o,"Generator"),define(u,n,(function(){return this})),define(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}',{globals:["Symbol","Object","TypeError"],locals:{_regenerator:["body.0.id","body.0.body.body.9.argument.expressions.9.callee.left"]},exportBindingAssignments:["body.0.body.body.9.argument.expressions.9.callee"],exportName:"_regenerator",dependencies:{regeneratorDefine:["body.0.body.body.1.body.body.1.argument.expressions.0.callee","body.0.body.body.7.declarations.0.init.alternate.expressions.0.callee","body.0.body.body.8.body.body.0.argument.expressions.0.alternate.expressions.1.callee","body.0.body.body.9.argument.expressions.1.callee","body.0.body.body.9.argument.expressions.2.callee","body.0.body.body.9.argument.expressions.4.callee","body.0.body.body.9.argument.expressions.5.callee","body.0.body.body.9.argument.expressions.6.callee","body.0.body.body.9.argument.expressions.7.callee","body.0.body.body.9.argument.expressions.8.callee"]},internal:!1}),regeneratorAsync:uj("7.27.0","function _regeneratorAsync(n,e,r,t,o){var a=asyncGen(n,e,r,t,o);return a.next().then((function(n){return n.done?n.value:a.next()}))}",{globals:[],locals:{_regeneratorAsync:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorAsync",dependencies:{regeneratorAsyncGen:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),regeneratorAsyncGen:uj("7.27.0","function _regeneratorAsyncGen(r,e,t,o,n){return new regeneratorAsyncIterator(regenerator().w(r,e,t,o),n||Promise)}",{globals:["Promise"],locals:{_regeneratorAsyncGen:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorAsyncGen",dependencies:{regenerator:["body.0.body.body.0.argument.arguments.0.callee.object.callee"],regeneratorAsyncIterator:["body.0.body.body.0.argument.callee"]},internal:!1}),regeneratorAsyncIterator:uj("7.27.0",'function AsyncIterator(t,e){function n(r,o,i,f){try{var c=t[r](o),u=c.value;return u instanceof OverloadYield?e.resolve(u.v).then((function(t){n("next",t,i,f)}),(function(t){n("throw",t,i,f)})):e.resolve(u).then((function(t){c.value=t,i(c)}),(function(t){return n("throw",t,i,f)}))}catch(t){f(t)}}var r;this.next||(define(AsyncIterator.prototype),define(AsyncIterator.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),define(this,"_invoke",(function(t,o,i){function f(){return new e((function(e,r){n(t,i,e,r)}))}return r=r?r.then(f,f):f()}),!0)}',{globals:["Symbol"],locals:{AsyncIterator:["body.0.id","body.0.body.body.2.expression.expressions.0.right.expressions.0.arguments.0.object","body.0.body.body.2.expression.expressions.0.right.expressions.1.arguments.0.object"]},exportBindingAssignments:[],exportName:"AsyncIterator",dependencies:{OverloadYield:["body.0.body.body.0.body.body.0.block.body.1.argument.test.right"],regeneratorDefine:["body.0.body.body.2.expression.expressions.0.right.expressions.0.callee","body.0.body.body.2.expression.expressions.0.right.expressions.1.callee","body.0.body.body.2.expression.expressions.1.callee"]},internal:!0}),regeneratorDefine:uj("7.27.0",'function regeneratorDefine(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}regeneratorDefine=function(e,r,n,t){function o(r,n){regeneratorDefine(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))},regeneratorDefine(e,r,n,t)}',{globals:["Object"],locals:{regeneratorDefine:["body.0.id","body.0.body.body.2.expression.expressions.0.right.body.body.0.body.body.0.expression.callee","body.0.body.body.2.expression.expressions.1.callee","body.0.body.body.2.expression.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.2.expression.expressions.0"],exportName:"regeneratorDefine",dependencies:{},internal:!0}),regeneratorKeys:uj("7.27.0","function _regeneratorKeys(e){var n=Object(e),r=[];for(var t in n)r.unshift(t);return function e(){for(;r.length;)if((t=r.pop())in n)return e.value=t,e.done=!1,e;return e.done=!0,e}}",{globals:["Object"],locals:{_regeneratorKeys:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorKeys",dependencies:{},internal:!1}),regeneratorValues:uj("7.18.0",'function _regeneratorValues(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(typeof e+" is not iterable")}',{globals:["Symbol","isNaN","TypeError"],locals:{_regeneratorValues:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorValues",dependencies:{},internal:!1}),set:uj("7.0.0-beta.0",'function set(e,r,t,o){return set="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(e,r,t,o){var f,i=superPropBase(e,r);if(i){if((f=Object.getOwnPropertyDescriptor(i,r)).set)return f.set.call(o,t),!0;if(!f.writable)return!1}if(f=Object.getOwnPropertyDescriptor(o,r)){if(!f.writable)return!1;f.value=t,Object.defineProperty(o,r,f)}else defineProperty(o,r,t);return!0},set(e,r,t,o)}function _set(e,r,t,o,f){if(!set(e,r,t,o||e)&&f)throw new TypeError("failed to set property");return t}',{globals:["Reflect","Object","TypeError"],locals:{set:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.1.body.body.0.test.left.argument.callee","body.0.body.body.0.argument.expressions.0.left"],_set:["body.1.id"]},exportBindingAssignments:[],exportName:"_set",dependencies:{superPropBase:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.0.declarations.1.init.callee"],defineProperty:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.2.alternate.expression.callee"]},internal:!1}),setFunctionName:uj("7.23.6",'function setFunctionName(e,t,n){"symbol"==typeof t&&(t=(t=t.description)?"["+t+"]":"");try{Object.defineProperty(e,"name",{configurable:!0,value:n?n+" "+t:t})}catch(e){}return e}',{globals:["Object"],locals:{setFunctionName:["body.0.id"]},exportBindingAssignments:[],exportName:"setFunctionName",dependencies:{},internal:!1}),setPrototypeOf:uj("7.0.0-beta.0","function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}",{globals:["Object"],locals:{_setPrototypeOf:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_setPrototypeOf",dependencies:{},internal:!1}),skipFirstGeneratorNext:uj("7.0.0-beta.0","function _skipFirstGeneratorNext(t){return function(){var r=t.apply(this,arguments);return r.next(),r}}",{globals:[],locals:{_skipFirstGeneratorNext:["body.0.id"]},exportBindingAssignments:[],exportName:"_skipFirstGeneratorNext",dependencies:{},internal:!1}),slicedToArray:uj("7.0.0-beta.0","function _slicedToArray(r,e){return arrayWithHoles(r)||iterableToArrayLimit(r,e)||unsupportedIterableToArray(r,e)||nonIterableRest()}",{globals:[],locals:{_slicedToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_slicedToArray",dependencies:{arrayWithHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArrayLimit:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableRest:["body.0.body.body.0.argument.right.callee"]},internal:!1}),superPropBase:uj("7.0.0-beta.0","function _superPropBase(t,o){for(;!{}.hasOwnProperty.call(t,o)&&null!==(t=getPrototypeOf(t)););return t}",{globals:[],locals:{_superPropBase:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropBase",dependencies:{getPrototypeOf:["body.0.body.body.0.test.right.right.right.callee"]},internal:!1}),superPropGet:uj("7.25.0",'function _superPropGet(t,o,e,r){var p=get(getPrototypeOf(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t)}:p}',{globals:[],locals:{_superPropGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropGet",dependencies:{get:["body.0.body.body.0.declarations.0.init.callee"],getPrototypeOf:["body.0.body.body.0.declarations.0.init.arguments.0.callee"]},internal:!1}),superPropSet:uj("7.25.0","function _superPropSet(t,e,o,r,p,f){return set(getPrototypeOf(f?t.prototype:t),e,o,r,p)}",{globals:[],locals:{_superPropSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropSet",dependencies:{set:["body.0.body.body.0.argument.callee"],getPrototypeOf:["body.0.body.body.0.argument.arguments.0.callee"]},internal:!1}),taggedTemplateLiteral:uj("7.0.0-beta.0","function _taggedTemplateLiteral(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}",{globals:["Object"],locals:{_taggedTemplateLiteral:["body.0.id"]},exportBindingAssignments:[],exportName:"_taggedTemplateLiteral",dependencies:{},internal:!1}),taggedTemplateLiteralLoose:uj("7.0.0-beta.0","function _taggedTemplateLiteralLoose(e,t){return t||(t=e.slice(0)),e.raw=t,e}",{globals:[],locals:{_taggedTemplateLiteralLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_taggedTemplateLiteralLoose",dependencies:{},internal:!1}),tdz:uj("7.5.5",'function _tdzError(e){throw new ReferenceError(e+" is not defined - temporal dead zone")}',{globals:["ReferenceError"],locals:{_tdzError:["body.0.id"]},exportBindingAssignments:[],exportName:"_tdzError",dependencies:{},internal:!1}),temporalRef:uj("7.0.0-beta.0","function _temporalRef(r,e){return r===undef?err(e):r}",{globals:[],locals:{_temporalRef:["body.0.id"]},exportBindingAssignments:[],exportName:"_temporalRef",dependencies:{temporalUndefined:["body.0.body.body.0.argument.test.right"],tdz:["body.0.body.body.0.argument.consequent.callee"]},internal:!1}),temporalUndefined:uj("7.0.0-beta.0","function _temporalUndefined(){}",{globals:[],locals:{_temporalUndefined:["body.0.id"]},exportBindingAssignments:[],exportName:"_temporalUndefined",dependencies:{},internal:!1}),toArray:uj("7.0.0-beta.0","function _toArray(r){return arrayWithHoles(r)||iterableToArray(r)||unsupportedIterableToArray(r)||nonIterableRest()}",{globals:[],locals:{_toArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_toArray",dependencies:{arrayWithHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArray:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableRest:["body.0.body.body.0.argument.right.callee"]},internal:!1}),toConsumableArray:uj("7.0.0-beta.0","function _toConsumableArray(r){return arrayWithoutHoles(r)||iterableToArray(r)||unsupportedIterableToArray(r)||nonIterableSpread()}",{globals:[],locals:{_toConsumableArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_toConsumableArray",dependencies:{arrayWithoutHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArray:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableSpread:["body.0.body.body.0.argument.right.callee"]},internal:!1}),toPrimitive:uj("7.1.5",'function toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}',{globals:["Symbol","TypeError","String","Number"],locals:{toPrimitive:["body.0.id"]},exportBindingAssignments:[],exportName:"toPrimitive",dependencies:{},internal:!1}),toPropertyKey:uj("7.1.5",'function toPropertyKey(t){var i=toPrimitive(t,"string");return"symbol"==typeof i?i:i+""}',{globals:[],locals:{toPropertyKey:["body.0.id"]},exportBindingAssignments:[],exportName:"toPropertyKey",dependencies:{toPrimitive:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),toSetter:uj("7.24.0",'function _toSetter(t,e,n){e||(e=[]);var r=e.length++;return Object.defineProperty({},"_",{set:function(o){e[r]=o,t.apply(n,e)}})}',{globals:["Object"],locals:{_toSetter:["body.0.id"]},exportBindingAssignments:[],exportName:"_toSetter",dependencies:{},internal:!1}),tsRewriteRelativeImportExtensions:uj("7.27.0",'function tsRewriteRelativeImportExtensions(t,e){return"string"==typeof t&&/^\\.\\.?\\//.test(t)?t.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+)?)\\.([cm]?)ts$/i,(function(t,s,r,n,o){return s?e?".jsx":".js":!r||n&&o?r+n+"."+o.toLowerCase()+"js":t})):t}',{globals:[],locals:{tsRewriteRelativeImportExtensions:["body.0.id"]},exportBindingAssignments:[],exportName:"tsRewriteRelativeImportExtensions",dependencies:{},internal:!1}),typeof:uj("7.0.0-beta.0",'function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}',{globals:["Symbol"],locals:{_typeof:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_typeof",dependencies:{},internal:!1}),unsupportedIterableToArray:uj("7.9.0",'function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?arrayLikeToArray(r,a):void 0}}',{globals:["Array"],locals:{_unsupportedIterableToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_unsupportedIterableToArray",dependencies:{arrayLikeToArray:["body.0.body.body.0.consequent.body.0.consequent.argument.callee","body.0.body.body.0.consequent.body.2.argument.expressions.1.alternate.consequent.callee"]},internal:!1}),usingCtx:uj("7.23.9",'function _usingCtx(){var r="function"==typeof SuppressedError?SuppressedError:function(r,e){var n=Error();return n.name="SuppressedError",n.error=r,n.suppressed=e,n},e={},n=[];function using(r,e){if(null!=e){if(Object(e)!==e)throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(r)var o=e[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(void 0===o&&(o=e[Symbol.dispose||Symbol.for("Symbol.dispose")],r))var t=o;if("function"!=typeof o)throw new TypeError("Object is not disposable.");t&&(o=function(){try{t.call(e)}catch(r){return Promise.reject(r)}}),n.push({v:e,d:o,a:r})}else r&&n.push({d:e,a:r});return e}return{e:e,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var o,t=this.e,s=0;function next(){for(;o=n.pop();)try{if(!o.a&&1===s)return s=0,n.push(o),Promise.resolve().then(next);if(o.d){var r=o.d.call(o.v);if(o.a)return s|=2,Promise.resolve(r).then(next,err)}else s|=1}catch(r){return err(r)}if(1===s)return t!==e?Promise.reject(t):Promise.resolve();if(t!==e)throw t}function err(n){return t=t!==e?new r(n,t):n,next()}return next()}}}',{globals:["SuppressedError","Error","Object","TypeError","Symbol","Promise"],locals:{_usingCtx:["body.0.id"]},exportBindingAssignments:[],exportName:"_usingCtx",dependencies:{},internal:!1}),wrapAsyncGenerator:uj("7.0.0-beta.0",'function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function AsyncGenerator(e){var r,t;function resume(r,t){try{var n=e[r](t),o=n.value,u=o instanceof OverloadYield;Promise.resolve(u?o.v:o).then((function(t){if(u){var i="return"===r?"return":"next";if(!o.k||t.done)return resume(i,t);t=e[i](t).value}settle(n.done?"return":"normal",t)}),(function(e){resume("throw",e)}))}catch(e){settle("throw",e)}}function settle(e,n){switch(e){case"return":r.resolve({value:n,done:!0});break;case"throw":r.reject(n);break;default:r.resolve({value:n,done:!1})}(r=r.next)?resume(r.key,r.arg):t=null}this._invoke=function(e,n){return new Promise((function(o,u){var i={key:e,arg:n,resolve:o,reject:u,next:null};t?t=t.next=i:(r=t=i,resume(e,n))}))},"function"!=typeof e.return&&(this.return=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype.throw=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype.return=function(e){return this._invoke("return",e)};',{globals:["Promise","Symbol"],locals:{_wrapAsyncGenerator:["body.0.id"],AsyncGenerator:["body.1.id","body.0.body.body.0.argument.body.body.0.argument.callee","body.2.expression.expressions.0.left.object.object","body.2.expression.expressions.1.left.object.object","body.2.expression.expressions.2.left.object.object","body.2.expression.expressions.3.left.object.object"]},exportBindingAssignments:[],exportName:"_wrapAsyncGenerator",dependencies:{OverloadYield:["body.1.body.body.1.body.body.0.block.body.0.declarations.2.init.right"]},internal:!1}),wrapNativeSuper:uj("7.0.0-beta.0",'function _wrapNativeSuper(t){var r="function"==typeof Map?new Map:void 0;return _wrapNativeSuper=function(t){if(null===t||!isNativeFunction(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,Wrapper)}function Wrapper(){return construct(t,arguments,getPrototypeOf(this).constructor)}return Wrapper.prototype=Object.create(t.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),setPrototypeOf(Wrapper,t)},_wrapNativeSuper(t)}',{globals:["Map","TypeError","Object"],locals:{_wrapNativeSuper:["body.0.id","body.0.body.body.1.argument.expressions.1.callee","body.0.body.body.1.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.1.argument.expressions.0"],exportName:"_wrapNativeSuper",dependencies:{getPrototypeOf:["body.0.body.body.1.argument.expressions.0.right.body.body.3.body.body.0.argument.arguments.2.object.callee"],setPrototypeOf:["body.0.body.body.1.argument.expressions.0.right.body.body.4.argument.expressions.1.callee"],isNativeFunction:["body.0.body.body.1.argument.expressions.0.right.body.body.0.test.right.argument.callee"],construct:["body.0.body.body.1.argument.expressions.0.right.body.body.3.body.body.0.argument.callee"]},internal:!1}),wrapRegExp:uj("7.19.0",'function _wrapRegExp(){_wrapRegExp=function(e,r){return new BabelRegExp(e,void 0,r)};var e=RegExp.prototype,r=new WeakMap;function BabelRegExp(e,t,p){var o=RegExp(e,t);return r.set(o,p||r.get(e)),setPrototypeOf(o,BabelRegExp.prototype)}function buildGroups(e,t){var p=r.get(t);return Object.keys(p).reduce((function(r,t){var o=p[t];if("number"==typeof o)r[t]=e[o];else{for(var i=0;void 0===e[o[i]]&&i+1]+)(>|$)/g,(function(e,r,t){if(""===t)return e;var p=o[r];return Array.isArray(p)?"$"+p.join("$"):"number"==typeof p?"$"+p:""})))}if("function"==typeof p){var i=this;return e[Symbol.replace].call(this,t,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(buildGroups(e,i)),p.apply(this,e)}))}return e[Symbol.replace].call(this,t,p)},_wrapRegExp.apply(this,arguments)}',{globals:["RegExp","WeakMap","Object","Symbol","Array"],locals:{_wrapRegExp:["body.0.id","body.0.body.body.4.argument.expressions.3.callee.object","body.0.body.body.0.expression.left"]},exportBindingAssignments:["body.0.body.body.0.expression"],exportName:"_wrapRegExp",dependencies:{setPrototypeOf:["body.0.body.body.2.body.body.1.argument.expressions.1.callee"],inherits:["body.0.body.body.4.argument.expressions.0.callee"]},internal:!1}),writeOnlyError:uj("7.12.13","function _writeOnlyError(r){throw new TypeError('\"'+r+'\" is write-only')}",{globals:["TypeError"],locals:{_writeOnlyError:["body.0.id"]},exportBindingAssignments:[],exportName:"_writeOnlyError",dependencies:{},internal:!1})};Object.assign(pj,{AwaitValue:uj("7.0.0-beta.0","function _AwaitValue(t){this.wrapped=t}",{globals:[],locals:{_AwaitValue:["body.0.id"]},exportBindingAssignments:[],exportName:"_AwaitValue",dependencies:{},internal:!1}),applyDecs:uj("7.17.8",'function old_createMetadataMethodsForProperty(e,t,a,r){return{getMetadata:function(o){old_assertNotFinished(r,"getMetadata"),old_assertMetadataKey(o);var i=e[o];if(void 0!==i)if(1===t){var n=i.public;if(void 0!==n)return n[a]}else if(2===t){var l=i.private;if(void 0!==l)return l.get(a)}else if(Object.hasOwnProperty.call(i,"constructor"))return i.constructor},setMetadata:function(o,i){old_assertNotFinished(r,"setMetadata"),old_assertMetadataKey(o);var n=e[o];if(void 0===n&&(n=e[o]={}),1===t){var l=n.public;void 0===l&&(l=n.public={}),l[a]=i}else if(2===t){var s=n.priv;void 0===s&&(s=n.private=new Map),s.set(a,i)}else n.constructor=i}}}function old_convertMetadataMapToFinal(e,t){var a=e[Symbol.metadata||Symbol.for("Symbol.metadata")],r=Object.getOwnPropertySymbols(t);if(0!==r.length){for(var o=0;o=0;m--){var b;void 0!==(p=old_memberDec(h[m],r,c,l,s,o,i,n,f))&&(old_assertValidReturnValue(o,p),0===o?b=p:1===o?(b=old_getInit(p),v=p.get||f.get,y=p.set||f.set,f={get:v,set:y}):f=p,void 0!==b&&(void 0===d?d=b:"function"==typeof d?d=[d,b]:d.push(b)))}if(0===o||1===o){if(void 0===d)d=function(e,t){return t};else if("function"!=typeof d){var g=d;d=function(e,t){for(var a=t,r=0;r3,m=v>=5;if(m?(u=t,f=r,0!=(v-=5)&&(p=n=n||[])):(u=t.prototype,f=a,0!==v&&(p=i=i||[])),0!==v&&!h){var b=m?s:l,g=b.get(y)||0;if(!0===g||3===g&&4!==v||4===g&&3!==v)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+y);!g&&v>2?b.set(y,v):b.set(y,!0)}old_applyMemberDec(e,u,d,y,v,m,h,f,p)}}old_pushInitializers(e,i),old_pushInitializers(e,n)}function old_pushInitializers(e,t){t&&e.push((function(e){for(var a=0;a0){for(var o=[],i=t,n=t.name,l=r.length-1;l>=0;l--){var s={v:!1};try{var c=Object.assign({kind:"class",name:n,addInitializer:old_createAddInitializerMethod(o,s)},old_createMetadataMethodsForProperty(a,0,n,s)),d=r[l](i,c)}finally{s.v=!0}void 0!==d&&(old_assertValidReturnValue(10,d),i=d)}e.push(i,(function(){for(var e=0;e=0;v--){var g;void 0!==(f=memberDec(h[v],a,c,o,n,i,s,u))&&(assertValidReturnValue(n,f),0===n?g=f:1===n?(g=f.init,p=f.get||u.get,d=f.set||u.set,u={get:p,set:d}):u=f,void 0!==g&&(void 0===l?l=g:"function"==typeof l?l=[l,g]:l.push(g)))}if(0===n||1===n){if(void 0===l)l=function(e,t){return t};else if("function"!=typeof l){var y=l;l=function(e,t){for(var r=t,a=0;a3,h=f>=5;if(h?(l=t,0!=(f-=5)&&(u=n=n||[])):(l=t.prototype,0!==f&&(u=a=a||[])),0!==f&&!d){var v=h?s:i,g=v.get(p)||0;if(!0===g||3===g&&4!==f||4===g&&3!==f)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+p);!g&&f>2?v.set(p,f):v.set(p,!0)}applyMemberDec(e,l,c,p,f,h,d,u)}}pushInitializers(e,a),pushInitializers(e,n)}(a,e,t),function(e,t,r){if(r.length>0){for(var a=[],n=t,i=t.name,s=r.length-1;s>=0;s--){var o={v:!1};try{var c=r[s](n,{kind:"class",name:i,addInitializer:createAddInitializerMethod(a,o)})}finally{o.v=!0}void 0!==c&&(assertValidReturnValue(10,c),n=c)}e.push(n,(function(){for(var e=0;e=0;g--){var y;void 0!==(p=memberDec(v[g],n,c,s,a,i,o,f))&&(assertValidReturnValue(a,p),0===a?y=p:1===a?(y=p.init,d=p.get||f.get,h=p.set||f.set,f={get:d,set:h}):f=p,void 0!==y&&(void 0===l?l=y:"function"==typeof l?l=[l,y]:l.push(y)))}if(0===a||1===a){if(void 0===l)l=function(e,t){return t};else if("function"!=typeof l){var m=l;l=function(e,t){for(var r=t,n=0;n3,h=f>=5;if(h?(l=e,0!=(f-=5)&&(u=n=n||[])):(l=e.prototype,0!==f&&(u=r=r||[])),0!==f&&!d){var v=h?o:i,g=v.get(p)||0;if(!0===g||3===g&&4!==f||4===g&&3!==f)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+p);!g&&f>2?v.set(p,f):v.set(p,!0)}applyMemberDec(a,l,c,p,f,h,d,u)}}return pushInitializers(a,r),pushInitializers(a,n),a}function pushInitializers(e,t){t&&e.push((function(e){for(var r=0;r0){for(var r=[],n=e,a=e.name,i=t.length-1;i>=0;i--){var o={v:!1};try{var s=t[i](n,{kind:"class",name:a,addInitializer:createAddInitializerMethod(r,o)})}finally{o.v=!0}void 0!==s&&(assertValidReturnValue(10,s),n=s)}return[n,function(){for(var e=0;e=0;m--){var b;void 0!==(h=memberDec(g[m],n,u,o,a,i,s,p,c))&&(assertValidReturnValue(a,h),0===a?b=h:1===a?(b=h.init,v=h.get||p.get,y=h.set||p.set,p={get:v,set:y}):p=h,void 0!==b&&(void 0===l?l=b:"function"==typeof l?l=[l,b]:l.push(b)))}if(0===a||1===a){if(void 0===l)l=function(e,t){return t};else if("function"!=typeof l){var I=l;l=function(e,t){for(var r=t,n=0;n3,y=d>=5,g=r;if(y?(f=e,0!=(d-=5)&&(p=a=a||[]),v&&!i&&(i=function(t){return checkInRHS(t)===e}),g=i):(f=e.prototype,0!==d&&(p=n=n||[])),0!==d&&!v){var m=y?c:o,b=m.get(h)||0;if(!0===b||3===b&&4!==d||4===b&&3!==d)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+h);!b&&d>2?m.set(h,d):m.set(h,!0)}applyMemberDec(s,f,l,h,d,y,v,p,g)}}return pushInitializers(s,n),pushInitializers(s,a),s}function pushInitializers(e,t){t&&e.push((function(e){for(var r=0;r0){for(var r=[],n=e,a=e.name,i=t.length-1;i>=0;i--){var s={v:!1};try{var o=t[i](n,{kind:"class",name:a,addInitializer:createAddInitializerMethod(r,s)})}finally{s.v=!0}void 0!==o&&(assertValidReturnValue(10,o),n=o)}return[n,function(){for(var e=0;e=0;j-=r?2:1){var D=v[j],E=r?v[j-1]:void 0,I={},O={kind:["field","accessor","method","getter","setter","class"][o],name:n,metadata:a,addInitializer:function(e,t){if(e.v)throw Error("attempted to call addInitializer after decoration was finished");s(t,"An initializer","be",!0),c.push(t)}.bind(null,I)};try{if(b)(y=s(D.call(E,P,O),"class decorators","return"))&&(P=y);else{var k,F;O.static=l,O.private=f,f?2===o?k=function(e){return m(e),w.value}:(o<4&&(k=i(w,"get",m)),3!==o&&(F=i(w,"set",m))):(k=function(e){return e[n]},(o<2||4===o)&&(F=function(e,t){e[n]=t}));var N=O.access={has:f?h.bind():function(e){return n in e}};if(k&&(N.get=k),F&&(N.set=F),P=D.call(E,d?{get:w.get,set:w.set}:w[A],O),d){if("object"==typeof P&&P)(y=s(P.get,"accessor.get"))&&(w.get=y),(y=s(P.set,"accessor.set"))&&(w.set=y),(y=s(P.init,"accessor.init"))&&S.push(y);else if(void 0!==P)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0")}else s(P,(p?"field":"method")+" decorators","return")&&(p?S.push(P):w[A]=P)}}finally{I.v=!0}}return(p||d)&&u.push((function(e,t){for(var r=S.length-1;r>=0;r--)t=S[r].call(e,t);return t})),p||b||(f?d?u.push(i(w,"get"),i(w,"set")):u.push(2===o?w[A]:i.call.bind(w[A])):Object.defineProperty(e,n,w)),P}function u(e,t){return Object.defineProperty(e,Symbol.metadata||Symbol.for("Symbol.metadata"),{configurable:!0,enumerable:!0,value:t})}if(arguments.length>=6)var l=a[Symbol.metadata||Symbol.for("Symbol.metadata")];var f=Object.create(null==l?null:l),p=function(e,t,r,n){var o,a,i=[],s=function(t){return checkInRHS(t)===e},u=new Map;function l(e){e&&i.push(c.bind(null,e))}for(var f=0;f3,y=16&d,v=!!(8&d),g=0==(d&=7),b=h+"/"+v;if(!g&&!m){var w=u.get(b);if(!0===w||3===w&&4!==d||4===w&&3!==d)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+h);u.set(b,!(d>2)||d)}applyDec(v?e:e.prototype,p,y,m?"#"+h:toPropertyKey(h),d,n,v?a=a||[]:o=o||[],i,v,m,g,1===d,v&&m?s:r)}}return l(o),l(a),i}(e,t,o,f);return r.length||u(e,f),{e:p,get c(){var t=[];return r.length&&[u(applyDec(e,[r],n,e.name,5,f,t),f),c.bind(null,t,e)]}}}',{globals:["TypeError","Array","Object","Error","Symbol","Map"],locals:{applyDecs2305:["body.0.id"]},exportBindingAssignments:[],exportName:"applyDecs2305",dependencies:{checkInRHS:["body.0.body.body.6.declarations.1.init.callee.body.body.0.declarations.3.init.body.body.0.argument.left.callee"],setFunctionName:["body.0.body.body.3.body.body.2.consequent.body.2.expression.consequent.expressions.0.consequent.right.properties.0.value.callee","body.0.body.body.3.body.body.2.consequent.body.2.expression.consequent.expressions.1.right.callee"],toPropertyKey:["body.0.body.body.6.declarations.1.init.callee.body.body.2.body.body.1.consequent.body.2.expression.arguments.3.alternate.callee"]},internal:!1}),classApplyDescriptorDestructureSet:uj("7.13.10",'function _classApplyDescriptorDestructureSet(e,t){if(t.set)return"__destrObj"in t||(t.__destrObj={set value(r){t.set.call(e,r)}}),t.__destrObj;if(!t.writable)throw new TypeError("attempted to set read only private field");return t}',{globals:["TypeError"],locals:{_classApplyDescriptorDestructureSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classApplyDescriptorDestructureSet",dependencies:{},internal:!1}),classApplyDescriptorGet:uj("7.13.10","function _classApplyDescriptorGet(e,t){return t.get?t.get.call(e):t.value}",{globals:[],locals:{_classApplyDescriptorGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classApplyDescriptorGet",dependencies:{},internal:!1}),classApplyDescriptorSet:uj("7.13.10",'function _classApplyDescriptorSet(e,t,l){if(t.set)t.set.call(e,l);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=l}}',{globals:["TypeError"],locals:{_classApplyDescriptorSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classApplyDescriptorSet",dependencies:{},internal:!1}),classCheckPrivateStaticAccess:uj("7.13.10","function _classCheckPrivateStaticAccess(s,a,r){return assertClassBrand(a,s,r)}",{globals:[],locals:{_classCheckPrivateStaticAccess:["body.0.id"]},exportBindingAssignments:[],exportName:"_classCheckPrivateStaticAccess",dependencies:{assertClassBrand:["body.0.body.body.0.argument.callee"]},internal:!1}),classCheckPrivateStaticFieldDescriptor:uj("7.13.10",'function _classCheckPrivateStaticFieldDescriptor(t,e){if(void 0===t)throw new TypeError("attempted to "+e+" private static field before its declaration")}',{globals:["TypeError"],locals:{_classCheckPrivateStaticFieldDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_classCheckPrivateStaticFieldDescriptor",dependencies:{},internal:!1}),classExtractFieldDescriptor:uj("7.13.10","function _classExtractFieldDescriptor(e,t){return classPrivateFieldGet2(t,e)}",{globals:[],locals:{_classExtractFieldDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_classExtractFieldDescriptor",dependencies:{classPrivateFieldGet2:["body.0.body.body.0.argument.callee"]},internal:!1}),classPrivateFieldDestructureSet:uj("7.4.4","function _classPrivateFieldDestructureSet(e,t){var r=classPrivateFieldGet2(t,e);return classApplyDescriptorDestructureSet(e,r)}",{globals:[],locals:{_classPrivateFieldDestructureSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldDestructureSet",dependencies:{classApplyDescriptorDestructureSet:["body.0.body.body.1.argument.callee"],classPrivateFieldGet2:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),classPrivateFieldGet:uj("7.0.0-beta.0","function _classPrivateFieldGet(e,t){var r=classPrivateFieldGet2(t,e);return classApplyDescriptorGet(e,r)}",{globals:[],locals:{_classPrivateFieldGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldGet",dependencies:{classApplyDescriptorGet:["body.0.body.body.1.argument.callee"],classPrivateFieldGet2:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),classPrivateFieldSet:uj("7.0.0-beta.0","function _classPrivateFieldSet(e,t,r){var s=classPrivateFieldGet2(t,e);return classApplyDescriptorSet(e,s,r),r}",{globals:[],locals:{_classPrivateFieldSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldSet",dependencies:{classApplyDescriptorSet:["body.0.body.body.1.argument.expressions.0.callee"],classPrivateFieldGet2:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),classPrivateMethodGet:uj("7.1.6","function _classPrivateMethodGet(s,a,r){return assertClassBrand(a,s),r}",{globals:[],locals:{_classPrivateMethodGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateMethodGet",dependencies:{assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"]},internal:!1}),classPrivateMethodSet:uj("7.1.6",'function _classPrivateMethodSet(){throw new TypeError("attempted to reassign private method")}',{globals:["TypeError"],locals:{_classPrivateMethodSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateMethodSet",dependencies:{},internal:!1}),classStaticPrivateFieldDestructureSet:uj("7.13.10",'function _classStaticPrivateFieldDestructureSet(t,r,s){return assertClassBrand(r,t),classCheckPrivateStaticFieldDescriptor(s,"set"),classApplyDescriptorDestructureSet(t,s)}',{globals:[],locals:{_classStaticPrivateFieldDestructureSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateFieldDestructureSet",dependencies:{classApplyDescriptorDestructureSet:["body.0.body.body.0.argument.expressions.2.callee"],assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"],classCheckPrivateStaticFieldDescriptor:["body.0.body.body.0.argument.expressions.1.callee"]},internal:!1}),classStaticPrivateFieldSpecGet:uj("7.0.2",'function _classStaticPrivateFieldSpecGet(t,s,r){return assertClassBrand(s,t),classCheckPrivateStaticFieldDescriptor(r,"get"),classApplyDescriptorGet(t,r)}',{globals:[],locals:{_classStaticPrivateFieldSpecGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateFieldSpecGet",dependencies:{classApplyDescriptorGet:["body.0.body.body.0.argument.expressions.2.callee"],assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"],classCheckPrivateStaticFieldDescriptor:["body.0.body.body.0.argument.expressions.1.callee"]},internal:!1}),classStaticPrivateFieldSpecSet:uj("7.0.2",'function _classStaticPrivateFieldSpecSet(s,t,r,e){return assertClassBrand(t,s),classCheckPrivateStaticFieldDescriptor(r,"set"),classApplyDescriptorSet(s,r,e),e}',{globals:[],locals:{_classStaticPrivateFieldSpecSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateFieldSpecSet",dependencies:{classApplyDescriptorSet:["body.0.body.body.0.argument.expressions.2.callee"],assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"],classCheckPrivateStaticFieldDescriptor:["body.0.body.body.0.argument.expressions.1.callee"]},internal:!1}),classStaticPrivateMethodSet:uj("7.3.2",'function _classStaticPrivateMethodSet(){throw new TypeError("attempted to set read only static private field")}',{globals:["TypeError"],locals:{_classStaticPrivateMethodSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateMethodSet",dependencies:{},internal:!1}),defineEnumerableProperties:uj("7.0.0-beta.0",'function _defineEnumerableProperties(e,r){for(var t in r){var n=r[t];n.configurable=n.enumerable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,t,n)}if(Object.getOwnPropertySymbols)for(var a=Object.getOwnPropertySymbols(r),b=0;b0;)try{var o=r.pop(),p=o.d.call(o.v);if(o.a)return Promise.resolve(p).then(next,err)}catch(r){return err(r)}if(s)throw e}function err(r){return e=s?new dispose_SuppressedError(e,r):r,s=!0,next()}return next()}',{globals:["SuppressedError","Error","Object","Promise"],locals:{dispose_SuppressedError:["body.0.id","body.0.body.body.0.argument.expressions.0.alternate.expressions.1.left.object","body.0.body.body.0.argument.expressions.0.alternate.expressions.1.right.arguments.1.properties.0.value.properties.0.value","body.0.body.body.0.argument.expressions.1.callee","body.1.body.body.1.body.body.0.argument.expressions.0.right.consequent.callee","body.0.body.body.0.argument.expressions.0.consequent.left","body.0.body.body.0.argument.expressions.0.alternate.expressions.0.left"],_dispose:["body.1.id"]},exportBindingAssignments:[],exportName:"_dispose",dependencies:{},internal:!1}),objectSpread:uj("7.0.0-beta.0",'function _objectSpread(e){for(var r=1;r0;)e=e[n],n=a.shift();if(!(arguments.length>2))return e[n];e[n]=r}catch(e){throw e.message+=" (when accessing "+t+")",e}}var mj=Object.create(null);function hj(e){if(!mj[e]){var t=pj[e];if(!t)throw Object.assign(new ReferenceError("Unknown helper "+e),{code:"BABEL_HELPER_UNKNOWN",helper:e});mj[e]={minVersion:t.minVersion,build:function(e,r,a,n){var s=t.ast();return function(e,t,r,a,n,s){var o=t.locals,d=t.dependencies,c=t.exportBindingAssignments,l=t.exportName,u=new Set(a||[]);r&&u.add(r);for(var p=0,f=(Object.entries||function(e){return Object.keys(e).map((function(t){return[t,e[t]]}))})(o);p=1.5*r;return Math.round(e/r)+" "+a+(n?"s":"")}return Rj=function(i,d){d=d||{};var c=typeof i;if("string"===c&&i.length>0)return function(o){if((o=String(o)).length>100)return;var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!i)return;var d=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return d*s;case"weeks":case"week":case"w":return d*n;case"days":case"day":case"d":return d*a;case"hours":case"hour":case"hrs":case"hr":case"h":return d*r;case"minutes":case"minute":case"mins":case"min":case"m":return d*t;case"seconds":case"second":case"secs":case"sec":case"s":return d*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}(i);if("number"===c&&isFinite(i))return d.long?function(n){var s=Math.abs(n);if(s>=a)return o(n,s,a,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(i):function(n){var s=Math.abs(n);if(s>=a)return Math.round(n/a)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))},Rj}var Pj=function(e){function t(e){var a,n,s,o=null;function i(){for(var e=arguments.length,r=new Array(e),n=0;n=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(r=!1,function(){r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||function(){},e.exports=Pj(t),e.exports.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Sj,Sj.exports);var Aj=Sj.exports,kj=Mm,Cj=Um,_j=hr,Ij=tr,Dj=vr,Oj=se,Nj=ir,Bj=de,Mj=Ge,Fj=He,Lj=kt,Uj=Ct,qj=me,Gj=je,Wj=qm,Vj=Gm,Hj=nr,Kj=Km,zj=ke,Xj=qe,Jj=zm.isCompatTag;e.isExistentialTypeParam=function(){throw new Error("`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.")},e.isNumericLiteralTypeAnnotation=function(){throw new Error("`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.")};var Yj=Object.freeze({__proto__:null,isBindingIdentifier:function(){var e=this.node,t=this.parent,r=this.parentPath.parent;return Bj(e)&&kj(e,t,r)},isBlockScoped:function(){return Cj(this.node)},isExpression:function(){return this.isIdentifier()?this.isReferencedIdentifier():Ij(this.node)},isFlow:function(){var e=this.node;return!!Dj(e)||(Mj(e)?"type"===e.importKind||"typeof"===e.importKind:_j(e)?"type"===e.exportKind:!!Fj(e)&&("type"===e.importKind||"typeof"===e.importKind))},isForAwaitStatement:function(){return Xj(this.node,{await:!0})},isGenerated:function(){return!this.isUser()},isPure:function(e){return this.scope.isPure(this.node,e)},isReferenced:function(){return Wj(this.node,this.parent)},isReferencedIdentifier:function(e){var t=this.node,r=this.parent;if(!Bj(t,e)&&!Uj(r,e)){if(!Lj(t,e))return!1;if(Jj(t.name))return!1}return Wj(t,r,this.parentPath.parent)},isReferencedMemberExpression:function(){var e=this.node,t=this.parent;return qj(e)&&Wj(e,t)},isRestProperty:function(){var e;return Gj(this.node)&&(null==(e=this.parentPath)?void 0:e.isObjectPattern())},isScope:function(){return Vj(this.node,this.parent)},isSpreadProperty:function(){var e;return Gj(this.node)&&(null==(e=this.parentPath)?void 0:e.isObjectExpression())},isStatement:function(){var e=this.node,t=this.parent;if(Hj(e)){if(zj(e)){if(Nj(t,{left:e}))return!1;if(Oj(t,{init:e}))return!1}return!0}return!1},isUser:function(){return this.node&&!!this.node.loc},isVar:function(){return Kj(this.node)}}),$j=Ca,Qj=Hn,Zj=Pa,ew=ts,tw=J;function rw(e){return e in Ej}function aw(e){return null==e?void 0:e._exploded}function nw(e){if(aw(e))return e;e._exploded=!0;for(var t=0,r=Object.keys(e);t=11?t+=r-1:r>=9?t+=r-9:r>=1&&(t+=r+1),r++}while(this.hasLabel(t)||this.hasBinding(t)||this.hasGlobal(t)||this.hasReference(t));var a=this.getProgramParent();return a.references[t]=!0,a.uids[t]=!0,t},t.generateUidBasedOnNode=function(e,t){var r=[];jE(e,r);var a=r.join("$");return a=a.replace(/^_/,"")||t||"ref",this.generateUid(a.slice(0,20))},t.generateUidIdentifierBasedOnNode=function(e,t){return Iw(this.generateUidBasedOnNode(e,t))},t.isStatic=function(e){if(aE(e)||eE(e)||mE(e))return!0;if(Ww(e)){var t=this.getBinding(e.name);return t?t.constant:this.hasBinding(e.name)}return!1},t.maybeGenerateMemoised=function(e,t){if(this.isStatic(e))return null;var r=this.generateUidIdentifierBasedOnNode(e);return t?r:(this.push({id:r}),Cw(r))},t.checkBlockScopedCollisions=function(e,t,r,a){if("param"!==t&&("local"!==e.kind&&("let"===t||"let"===e.kind||"const"===e.kind||"module"===e.kind||"param"===e.kind&&"const"===t)))throw this.path.hub.buildError(a,'Duplicate declaration "'+r+'"',TypeError)},t.rename=function(e,t){var r=this.getBinding(e);r&&(t||(t=this.generateUidIdentifier(e).name),new bw(r,e,t).rename(arguments[2]))},t.dump=function(){var e="-".repeat(60);console.log(e);var t=this;do{console.log("#",t.block.type);for(var r=0,a=Object.keys(t.bindings);r0)&&this.isPure(e.body,t));if(Mw(e)){for(var o,d=i(e.body);!(o=d()).done;){var c=o.value;if(!this.isPure(c,t))return!1}return!0}if(Ow(e))return this.isPure(e.left,t)&&this.isPure(e.right,t);if(Dw(e)||gE(e)){for(var l,u=i(e.elements);!(l=u()).done;){var p=l.value;if(null!==p&&!this.isPure(p,t))return!1}return!0}if(Yw(e)||fE(e)){for(var f,g=i(e.properties);!(f=g()).done;){var y=f.value;if(!this.isPure(y,t))return!1}return!0}if(zw(e))return!(e.computed&&!this.isPure(e.key,t))&&!((null==(n=e.decorators)?void 0:n.length)>0);if($w(e))return!(e.computed&&!this.isPure(e.key,t))&&(!((null==(s=e.decorators)?void 0:s.length)>0)&&!((yE(e)||e.static)&&null!==e.value&&!this.isPure(e.value,t)));if(nE(e))return this.isPure(e.argument,t);if(rE(e)){for(var m,h=i(e.expressions);!(m=h()).done;){var b=m.value;if(!this.isPure(b,t))return!1}return!0}return tE(e)?iE(e.tag,"String.raw")&&!this.hasBinding("String",{noGlobals:!0})&&this.isPure(e.quasi,t):Kw(e)?!e.computed&&Ww(e.object)&&"Symbol"===e.object.name&&Ww(e.property)&&"for"!==e.property.name&&!this.hasBinding("Symbol",{noGlobals:!0}):Nw(e)?iE(e.callee,"Symbol.for")&&!this.hasBinding("Symbol",{noGlobals:!0})&&1===e.arguments.length&&ue(e.arguments[0]):Qw(e)},t.setData=function(e,t){return this.data[e]=t},t.getData=function(e){var t=this;do{var r=t.data[e];if(null!=r)return r}while(t=t.parent)},t.removeData=function(e){var t=this;do{null!=t.data[e]&&(t.data[e]=null)}while(t=t.parent)},t.init=function(){this.inited||(this.inited=!0,this.crawl())},t.crawl=function(){var e=this.path;wE(this),this.data=Object.create(null);var t=this;do{if(t.crawling)return;if(t.path.isProgram())break}while(t=t.parent);var r=t,a={references:[],constantViolations:[],assignments:[]};if(this.crawling=!0,EE||(EE=WO.visitors.merge([{Scope:function(e){wE(e.scope)}},TE])),"Program"!==e.type){for(var n,s=i(EE.enter);!(n=s()).done;){n.value.call(a,e,a)}var o=EE[e.type];if(o)for(var d,c=i(o.enter);!(d=c()).done;){d.value.call(a,e,a)}}e.traverse(EE,a),this.crawling=!1;for(var l,u=i(a.assignments);!(l=u()).done;){for(var p=l.value,f=p.getAssignmentIdentifiers(),g=0,y=Object.keys(f);g1&&(r+=t),"_"+r},AE.prototype.toArray=function(e,t,r){if(Ww(e)){var a=this.getBinding(e.name);if(null!=a&&a.constant&&a.path.isGenericType("Array"))return e}if(Dw(e))return e;if(Ww(e,{name:"arguments"}))return kw(dE(dE(dE(Iw("Array"),Iw("prototype")),Iw("slice")),Iw("call")),[e]);var n,s=[e];return!0===t?n="toConsumableArray":"number"==typeof t?(s.push(cE(t)),n="slicedToArray"):n="toArray",r&&(s.unshift(this.path.hub.addHelper(n)),n="maybeArrayLike"),kw(this.path.hub.addHelper(n),s)},AE.prototype.getAllBindingsOfKind=function(){for(var e=Object.create(null),t=arguments.length,r=new Array(t),a=0;a>18&63]+kE[n>>12&63]+kE[n>>6&63]+kE[63&n]);return s.join("")}function NE(e){var t;IE||DE();for(var r=e.length,a=r%3,n="",s=[],o=16383,i=0,d=r-a;id?d:i+o));return 1===a?(t=e[r-1],n+=kE[t>>2],n+=kE[t<<4&63],n+="=="):2===a&&(t=(e[r-2]<<8)+e[r-1],n+=kE[t>>10],n+=kE[t>>4&63],n+=kE[t<<2&63],n+="="),s.push(n),s.join("")}function BE(e,t,r,a,n){var s,o,i=8*n-a-1,d=(1<>1,l=-7,u=r?n-1:0,p=r?-1:1,f=e[t+u];for(u+=p,s=f&(1<<-l)-1,f>>=-l,l+=i;l>0;s=256*s+e[t+u],u+=p,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=a;l>0;o=256*o+e[t+u],u+=p,l-=8);if(0===s)s=1-c;else{if(s===d)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,a),s-=c}return(f?-1:1)*o*Math.pow(2,s-a)}function ME(e,t,r,a,n,s){var o,i,d,c=8*s-n-1,l=(1<>1,p=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:s-1,g=a?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(d=Math.pow(2,-o))<1&&(o--,d*=2),(t+=o+u>=1?p/d:p*Math.pow(2,1-u))*d>=2&&(o++,d/=2),o+u>=l?(i=0,o=l):o+u>=1?(i=(t*d-1)*Math.pow(2,n),o+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;e[r+f]=255&i,f+=g,i/=256,n-=8);for(o=o<0;e[r+f]=255&o,f+=g,o/=256,c-=8);e[r+f-g]|=128*y}var FE={}.toString,LE=Array.isArray||function(e){return"[object Array]"==FE.call(e)};function UE(){return GE.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function qE(e,t){if(UE()=UE())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+UE().toString(16)+" bytes");return 0|e}function XE(e){return!(null==e||!e._isBuffer)}function JE(e,t){if(XE(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return jS(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return wS(e).length;default:if(a)return jS(e).length;t=(""+t).toLowerCase(),a=!0}}function YE(e,t,r){var a=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return uS(this,t,r);case"utf8":case"utf-8":return iS(this,t,r);case"ascii":return cS(this,t,r);case"latin1":case"binary":return lS(this,t,r);case"base64":return oS(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return pS(this,t,r);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function $E(e,t,r){var a=e[t];e[t]=e[r],e[r]=a}function QE(e,t,r,a,n){if(0===e.length)return-1;if("string"==typeof r?(a=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=GE.from(t,a)),XE(t))return 0===t.length?-1:ZE(e,t,r,a,n);if("number"==typeof t)return t&=255,GE.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):ZE(e,[t],r,a,n);throw new TypeError("val must be string, number or Buffer")}function ZE(e,t,r,a,n){var s,o=1,i=e.length,d=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;o=2,i/=2,d/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(n){var l=-1;for(s=r;si&&(r=i-d),s=r;s>=0;s--){for(var u=!0,p=0;pn&&(a=n):a=n;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");a>s/2&&(a=s/2);for(var o=0;o>8,n=r%256,s.push(n),s.push(a);return s}(t,e.length-r),e,r,a)}function oS(e,t,r){return 0===t&&r===e.length?NE(e):NE(e.slice(t,r))}function iS(e,t,r){r=Math.min(e.length,r);for(var a=[],n=t;n239?4:c>223?3:c>191?2:1;if(n+u<=r)switch(u){case 1:c<128&&(l=c);break;case 2:128==(192&(s=e[n+1]))&&(d=(31&c)<<6|63&s)>127&&(l=d);break;case 3:s=e[n+1],o=e[n+2],128==(192&s)&&128==(192&o)&&(d=(15&c)<<12|(63&s)<<6|63&o)>2047&&(d<55296||d>57343)&&(l=d);break;case 4:s=e[n+1],o=e[n+2],i=e[n+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(d=(15&c)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&d<1114112&&(l=d)}null===l?(l=65533,u=1):l>65535&&(l-=65536,a.push(l>>>10&1023|55296),l=56320|1023&l),a.push(l),n+=u}return function(e){var t=e.length;if(t<=dS)return String.fromCharCode.apply(String,e);var r="",a=0;for(;a0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},GE.prototype.compare=function(e,t,r,a,n){if(!XE(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===a&&(a=0),void 0===n&&(n=this.length),t<0||r>e.length||a<0||n>this.length)throw new RangeError("out of range index");if(a>=n&&t>=r)return 0;if(a>=n)return-1;if(t>=r)return 1;if(this===e)return 0;for(var s=(n>>>=0)-(a>>>=0),o=(r>>>=0)-(t>>>=0),i=Math.min(s,o),d=this.slice(a,n),c=e.slice(t,r),l=0;ln)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var s=!1;;)switch(a){case"hex":return eS(this,e,t,r);case"utf8":case"utf-8":return tS(this,e,t,r);case"ascii":return rS(this,e,t,r);case"latin1":case"binary":return aS(this,e,t,r);case"base64":return nS(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sS(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),s=!0}},GE.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var dS=4096;function cS(e,t,r){var a="";r=Math.min(e.length,r);for(var n=t;na)&&(r=a);for(var n="",s=t;sr)throw new RangeError("Trying to access beyond buffer length")}function gS(e,t,r,a,n,s){if(!XE(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||te.length)throw new RangeError("Index out of range")}function yS(e,t,r,a){t<0&&(t=65535+t+1);for(var n=0,s=Math.min(e.length-r,2);n>>8*(a?n:1-n)}function mS(e,t,r,a){t<0&&(t=4294967295+t+1);for(var n=0,s=Math.min(e.length-r,4);n>>8*(a?n:3-n)&255}function hS(e,t,r,a,n,s){if(r+a>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function bS(e,t,r,a,n){return n||hS(e,0,r,4),ME(e,t,r,a,23,4),r+4}function xS(e,t,r,a,n){return n||hS(e,0,r,8),ME(e,t,r,a,52,8),r+8}GE.prototype.slice=function(e,t){var r,a=this.length;if((e=~~e)<0?(e+=a)<0&&(e=0):e>a&&(e=a),(t=void 0===t?a:~~t)<0?(t+=a)<0&&(t=0):t>a&&(t=a),t0&&(n*=256);)a+=this[e+--t]*n;return a},GE.prototype.readUInt8=function(e,t){return t||fS(e,1,this.length),this[e]},GE.prototype.readUInt16LE=function(e,t){return t||fS(e,2,this.length),this[e]|this[e+1]<<8},GE.prototype.readUInt16BE=function(e,t){return t||fS(e,2,this.length),this[e]<<8|this[e+1]},GE.prototype.readUInt32LE=function(e,t){return t||fS(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},GE.prototype.readUInt32BE=function(e,t){return t||fS(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},GE.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||fS(e,t,this.length);for(var a=this[e],n=1,s=0;++s=(n*=128)&&(a-=Math.pow(2,8*t)),a},GE.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||fS(e,t,this.length);for(var a=t,n=1,s=this[e+--a];a>0&&(n*=256);)s+=this[e+--a]*n;return s>=(n*=128)&&(s-=Math.pow(2,8*t)),s},GE.prototype.readInt8=function(e,t){return t||fS(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},GE.prototype.readInt16LE=function(e,t){t||fS(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},GE.prototype.readInt16BE=function(e,t){t||fS(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},GE.prototype.readInt32LE=function(e,t){return t||fS(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},GE.prototype.readInt32BE=function(e,t){return t||fS(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},GE.prototype.readFloatLE=function(e,t){return t||fS(e,4,this.length),BE(this,e,!0,23,4)},GE.prototype.readFloatBE=function(e,t){return t||fS(e,4,this.length),BE(this,e,!1,23,4)},GE.prototype.readDoubleLE=function(e,t){return t||fS(e,8,this.length),BE(this,e,!0,52,8)},GE.prototype.readDoubleBE=function(e,t){return t||fS(e,8,this.length),BE(this,e,!1,52,8)},GE.prototype.writeUIntLE=function(e,t,r,a){(e=+e,t|=0,r|=0,a)||gS(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,s=0;for(this[t]=255&e;++s=0&&(s*=256);)this[t+n]=e/s&255;return t+r},GE.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,1,255,0),GE.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},GE.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,2,65535,0),GE.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):yS(this,e,t,!0),t+2},GE.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,2,65535,0),GE.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):yS(this,e,t,!1),t+2},GE.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,4,4294967295,0),GE.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):mS(this,e,t,!0),t+4},GE.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,4,4294967295,0),GE.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):mS(this,e,t,!1),t+4},GE.prototype.writeIntLE=function(e,t,r,a){if(e=+e,t|=0,!a){var n=Math.pow(2,8*r-1);gS(this,e,t,r,n-1,-n)}var s=0,o=1,i=0;for(this[t]=255&e;++s>0)-i&255;return t+r},GE.prototype.writeIntBE=function(e,t,r,a){if(e=+e,t|=0,!a){var n=Math.pow(2,8*r-1);gS(this,e,t,r,n-1,-n)}var s=r-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+r},GE.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,1,127,-128),GE.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},GE.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,2,32767,-32768),GE.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):yS(this,e,t,!0),t+2},GE.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,2,32767,-32768),GE.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):yS(this,e,t,!1),t+2},GE.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,4,2147483647,-2147483648),GE.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):mS(this,e,t,!0),t+4},GE.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||gS(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),GE.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):mS(this,e,t,!1),t+4},GE.prototype.writeFloatLE=function(e,t,r){return bS(this,e,t,!0,r)},GE.prototype.writeFloatBE=function(e,t,r){return bS(this,e,t,!1,r)},GE.prototype.writeDoubleLE=function(e,t,r){return xS(this,e,t,!0,r)},GE.prototype.writeDoubleBE=function(e,t,r){return xS(this,e,t,!1,r)},GE.prototype.copy=function(e,t,r,a){if(r||(r=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a=this.length)throw new RangeError("sourceStart out of bounds");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t=0;--n)e[n+t]=this[n+r];else if(s<1e3||!GE.TYPED_ARRAY_SUPPORT)for(n=0;n>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(s=t;s55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===a){(t-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function wS(e){return function(e){var t,r,a,n,s,o;IE||DE();var i=e.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===e[i-2]?2:"="===e[i-1]?1:0,o=new _E(3*i/4-s),a=s>0?i-4:i;var d=0;for(t=0,r=0;t>16&255,o[d++]=n>>8&255,o[d++]=255&n;return 2===s?(n=CE[e.charCodeAt(t)]<<2|CE[e.charCodeAt(t+1)]>>4,o[d++]=255&n):1===s&&(n=CE[e.charCodeAt(t)]<<10|CE[e.charCodeAt(t+1)]<<4|CE[e.charCodeAt(t+2)]>>2,o[d++]=n>>8&255,o[d++]=255&n),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(vS,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function ES(e,t,r,a){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function SS(e){return null!=e&&(!!e._isBuffer||TS(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&TS(e.slice(0,0))}(e))}function TS(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}for(var PS=",".charCodeAt(0),AS=";".charCodeAt(0),kS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",CS=new Uint8Array(64),_S=new Uint8Array(128),IS=0;IS<64;IS++){var DS=kS.charCodeAt(IS);CS[IS]=DS,_S[DS]=IS}function OS(e,t){var r=0,a=0,n=0;do{var s=e.next();r|=(31&(n=_S[s]))<>>=1,o&&(r=-2147483648|-r),t+r}function NS(e,t,r){var a=t-r;a=a<0?-a<<1|1:a<<1;do{var n=31&a;(a>>>=5)>0&&(n|=32),e.write(CS[n])}while(a>0);return t}function BS(e,t){return!(e.pos>=t)&&e.peek()!==PS}var MS="undefined"!=typeof TextDecoder?new TextDecoder:void 0!==GE?{decode:function(e){return GE.from(e.buffer,e.byteOffset,e.byteLength).toString()}}:{decode:function(e){for(var t="",r=0;r0?t+MS.decode(e.subarray(0,r)):t},o(e)}(),LS=function(){function e(e){this.pos=0,this.buffer=e}var t=e.prototype;return t.next=function(){return this.buffer.charCodeAt(this.pos++)},t.peek=function(){return this.buffer.charCodeAt(this.pos)},t.indexOf=function(e){var t=this.buffer,r=this.pos,a=t.indexOf(e,r);return-1===a?t.length:a},o(e)}();function US(e){e.sort(qS)}function qS(e,t){return e[0]-t[0]}function GS(e){for(var t=new FS,r=0,a=0,n=0,s=0,o=0;o0&&t.write(AS),0!==i.length)for(var d=0,c=0;c0&&t.write(PS),d=NS(t,l[0],d),1!==l.length&&(r=NS(t,l[1],r),a=NS(t,l[2],a),n=NS(t,l[3],n),4!==l.length&&(s=NS(t,l[4],s)))}}return t.flush()}var WS=/^[\w+.-]+:\/\//,VS=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,HS=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function KS(e){return e.startsWith("/")}function zS(e){return/^[.?#]/.test(e)}function XS(e){var t=VS.exec(e);return JS(t[1],t[2]||"",t[3],t[4]||"",t[5]||"/",t[6]||"",t[7]||"")}function JS(e,t,r,a,n,s,o){return{scheme:e,user:t,host:r,port:a,path:n,query:s,hash:o,type:7}}function YS(e){if(function(e){return e.startsWith("//")}(e)){var t=XS("http:"+e);return t.scheme="",t.type=6,t}if(KS(e)){var r=XS("http://foo.com"+e);return r.scheme="",r.host="",r.type=5,r}if(function(e){return e.startsWith("file:")}(e))return function(e){var t=HS.exec(e),r=t[2];return JS("file:","",t[1]||"","",KS(r)?r:"/"+r,t[3]||"",t[4]||"")}(e);if(function(e){return WS.test(e)}(e))return XS(e);var a=XS("http://foo.com/"+e);return a.scheme="",a.host="",a.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,a}function $S(e,t){for(var r=t<=4,a=e.path.split("/"),n=1,s=0,o=!1,i=1;ia&&(a=s)}$S(r,a);var o=r.query+r.hash;switch(a){case 2:case 3:return o;case 4:var i=r.path.slice(1);return i?zS(t||e)&&!zS(i)?"./"+i+o:i+o:o||".";case 5:return r.path+o;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+o}}var ZS=0;function eT(e,t){for(var r=t;r=0&&e[a][ZS]===t;r=a--);return r}function iT(e,t,r,a){var n=r.lastKey,s=r.lastNeedle,o=r.lastIndex,i=0,d=e.length-1;if(a===n){if(t===s)return nT=-1!==o&&e[o][ZS]===t,o;t>=s?i=-1===o?0:o:d=o}return r.lastKey=a,r.lastNeedle=t,r.lastIndex=function(e,t,r,a){for(;r<=a;){var n=r+(a-r>>1),s=e[n][ZS]-t;if(0===s)return nT=!0,n;s<0?r=n+1:a=n-1}return nT=!1,r-1}(e,t,i,d)}var dT=-1,cT=1,lT=o((function(e,t){var r="string"==typeof e;if(!r&&e._decodedMemo)return e;var a=function(e){return"string"==typeof e?JSON.parse(e):e}(e),n=a.version,s=a.file,o=a.names,i=a.sourceRoot,d=a.sources,c=a.sourcesContent;this.version=n,this.file=s,this.names=o||[],this.sourceRoot=i,this.sources=d,this.sourcesContent=c,this.ignoreList=a.ignoreList||a.x_google_ignoreList||void 0;var l=function(e,t){var r=function(e){if(!e)return"";var t=e.lastIndexOf("/");return e.slice(0,t+1)}(e),a=t?t+"/":"";return function(e){return QS(a+(e||""),r)}}(t,i);this.resolvedSources=d.map(l);var u=a.mappings;if("string"==typeof u)this._encoded=u,this._decoded=void 0;else{if(!Array.isArray(u))throw a.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error("invalid source map: "+JSON.stringify(a));this._encoded=void 0,this._decoded=function(e,t){var r=eT(e,0);if(r===e.length)return e;t||(e=e.slice());for(var a=r;a=s.length)return fT(null,null,null,null);var o=s[r],i=gT(o,e._decodedMemo,r,a,n||cT);if(-1===i)return fT(null,null,null,null);var d=o[i];if(1===d.length)return fT(null,null,null,null);var c=e.names;return fT(e.resolvedSources[d[1]],d[2]+1,d[3],5===d.length?c[d[4]]:null)}function fT(e,t,r,a){return{source:e,line:t,column:r,name:a}}function gT(e,t,r,a,n){var s=iT(e,a,t,r);return nT?s=(n===dT?sT:oT)(e,a,s):n===dT&&s++,-1===s||s===e.length?-1:s}var yT=o((function(){this._indexes={__proto__:null},this.array=[]}));function mT(e,t){var r=function(e,t){return e._indexes[t]}(e,t);if(void 0!==r)return r;var a=e,n=a.array,s=a._indexes,o=n.push(t);return s[t]=o-1}var hT=0,bT=1,xT=2,vT=3,RT=4,jT=-1,wT=o((function(e){var t=void 0===e?{}:e,r=t.file,a=t.sourceRoot;this._names=new yT,this._sources=new yT,this._sourcesContent=[],this._mappings=[],this.file=r,this.sourceRoot=a,this._ignoreList=new yT}));var ET=function(e,t){return function(e,t,r){var a=r.generated,n=r.source,s=r.original,o=r.name,i=r.content;if(!n)return PT(e,t,a.line-1,a.column,null,null,null,null,null);return PT(e,t,a.line-1,a.column,n,s.line-1,s.column,o,i)}(!0,e,t)};function ST(e,t,r){var a=e,n=a._sources;a._sourcesContent[mT(n,t)]=r}function TT(e){var t=e,r=t._mappings,a=t._sources,n=t._sourcesContent,s=t._names,o=t._ignoreList;return function(e){for(var t=e.length,r=t,a=r-1;a>=0&&!(e[a].length>0);r=a,a--);r=0;r=a--){if(t>=e[a][hT])break}return r}(g,a);if(!n){if(function(e,t){if(0===t)return!0;var r=e[t-1];return 1===r.length}(g,y))return;return AT(g,y,[a])}var m=mT(u,n),h=i?mT(f,i):jT;if(m===p.length&&(p[m]=null!=d?d:null),!function(e,t,r,a,n,s){if(0===t)return!1;var o=e[t-1];return 1!==o.length&&(r===o[bT]&&a===o[xT]&&n===o[vT]&&s===(5===o.length?o[RT]:jT))}(g,y,m,s,o,h))return AT(g,y,i?[a,m,s,o,h]:[a,m,s,o])}function AT(e,t,r){for(var a=e.length;a>t;a--)e[a]=e[a-1];e[t]=r}var kT=function(){function e(e,t){var r;this._map=void 0,this._rawMappings=void 0,this._sourceFileName=void 0,this._lastGenLine=0,this._lastSourceLine=0,this._lastSourceColumn=0,this._inputMap=void 0;var a=this._map=new wT({sourceRoot:e.sourceRoot});if(this._sourceFileName=null==(r=e.sourceFileName)?void 0:r.replace(/\\/g,"/"),this._rawMappings=void 0,e.inputSourceMap){this._inputMap=new lT(e.inputSourceMap);var n=this._inputMap.resolvedSources;if(n.length)for(var s=0;s1?this._indentChar.repeat(t):this._indentChar}else this._str+=t>1?String.fromCharCode(e).repeat(t):String.fromCharCode(e);10!==e?(this._mark(r.line,r.column,r.identifierName,r.identifierNamePos,r.filename),this._position.column+=t):(this._position.line++,this._position.column=0),this._canMarkIdName&&(r.identifierName=void 0,r.identifierNamePos=void 0)},t._append=function(e,t,r){var a=e.length,n=this._position;if(this._last=e.charCodeAt(a-1),++this._appendCount>4096?(this._str,this._buf+=this._str,this._str=e,this._appendCount=0):this._str+=e,r||this._map){var s=t.column,o=t.identifierName,i=t.identifierNamePos,d=t.filename,c=t.line;null==o&&null==i||!this._canMarkIdName||(t.identifierName=void 0,t.identifierNamePos=void 0);var l=e.indexOf("\n"),u=0;for(0!==l&&this._mark(c,s,o,i,d);-1!==l;)n.line++,n.column=0,(u=l+1)=0&&10===this._queue[r].char;r--)t++;return t===e&&10===this._last?t+1:t},t.endsWithCharAndNewline=function(){var e=this._queue,t=this._queueCursor;if(0!==t){if(10!==e[t-1].char)return;return t>1?e[t-2].char:this._last}},t.hasContent=function(){return 0!==this._queueCursor||!!this._last},t.exactSource=function(e,t){if(this._map){this.source("start",e);var r=e.identifierName,a=this._sourcePosition;r&&(this._canMarkIdName=!1,a.identifierName=r),t(),r&&(this._canMarkIdName=!0,a.identifierName=void 0,a.identifierNamePos=void 0),this.source("end",e)}else t()},t.source=function(e,t){this._map&&this._normalizePosition(e,t,0)},t.sourceWithOffset=function(e,t,r){this._map&&this._normalizePosition(e,t,r)},t._normalizePosition=function(e,t,r){var a=t[e],n=this._sourcePosition;a&&(n.line=a.line,n.column=Math.max(a.column+r,0),n.filename=t.filename)},t.getCurrentColumn=function(){for(var e=this._queue,t=this._queueCursor,r=-1,a=0,n=0;n",0],["&&",1],["|",2],["^",3],["&",4],["==",5],["===",5],["!=",5],["!==",5],["<",6],[">",6],["<=",6],[">=",6],["in",6],["instanceof",6],[">>",7],["<<",7],[">>>",7],["+",8],["-",8],["*",9],["/",9],["%",9],["**",10]]);function iP(e,t){return"BinaryExpression"===t||"LogicalExpression"===t?oP.get(e.operator):"TSAsExpression"===t||"TSSatisfiesExpression"===t?oP.get("in"):void 0}function dP(e){return"TSAsExpression"===e||"TSSatisfiesExpression"===e||"TSTypeAssertion"===e}var cP=function(e,t){var r=t.type;return("ClassDeclaration"===r||"ClassExpression"===r)&&t.superClass===e},lP=function(e,t){var r=t.type;return("MemberExpression"===r||"OptionalMemberExpression"===r)&&t.object===e||("CallExpression"===r||"OptionalCallExpression"===r||"NewExpression"===r)&&t.callee===e||"TaggedTemplateExpression"===r&&t.tag===e||"TSNonNullExpression"===r};function uP(e){return Boolean(e&(AP.expressionStatement|AP.arrowBody))}function pP(e,t){var r=t.type;if("BinaryExpression"===e.type&&"**"===e.operator&&"BinaryExpression"===r&&"**"===t.operator)return t.left===e;if(cP(e,t))return!0;if(lP(e,t)||"UnaryExpression"===r||"SpreadElement"===r||"AwaitExpression"===r)return!0;var a=iP(t,r);if(null!=a){var n=iP(e,e.type);if(a===n&&"BinaryExpression"===r&&t.right===e||a>n)return!0}}function fP(e,t){var r=t.type;return"ArrayTypeAnnotation"===r||"NullableTypeAnnotation"===r||"IntersectionTypeAnnotation"===r||"UnionTypeAnnotation"===r}function gP(e,t){return("AssignmentExpression"===t.type||"AssignmentPattern"===t.type)&&t.left===e||("BinaryExpression"===t.type&&("|"===t.operator||"&"===t.operator)&&e===t.left||pP(e,t))}function yP(e,t){var r=t.type;return"TSIntersectionType"===r||"TSUnionType"===r||"TSTypeOperator"===r||"TSOptionalType"===r||"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSConditionalType"===r&&(t.checkType===e||t.extendsType===e)}function mP(e,t){var r=t.type;return"BinaryExpression"===r||"LogicalExpression"===r||"UnaryExpression"===r||"SpreadElement"===r||lP(e,t)||"AwaitExpression"===r&&nP(e)||"ConditionalExpression"===r&&e===t.test||cP(e,t)||dP(r)}function hP(e,t){return lP(e,t)||$T(t)&&"**"===t.operator&&t.left===e||cP(e,t)}function bP(e,t){var r=t.type;return!!("UnaryExpression"===r||"SpreadElement"===r||"BinaryExpression"===r||"LogicalExpression"===r||"ConditionalExpression"===r&&t.test===e||"AwaitExpression"===r||dP(r))||hP(e,t)}function xP(e,t){return QT(t)&&t.callee===e||tP(t)&&t.object===e}var vP=Object.freeze({__proto__:null,ArrowFunctionExpression:bP,AssignmentExpression:function(e,t,r){return!(!uP(r)||!rP(e.left))||bP(e,t)},AwaitExpression:mP,Binary:pP,BinaryExpression:function(e,t,r){return"in"===e.operator&&Boolean(r&AP.forInOrInitHeadAccumulate)},ClassExpression:function(e,t,r){return Boolean(r&(AP.expressionStatement|AP.exportDefault))},ConditionalExpression:bP,DoExpression:function(e,t,r){return!e.async&&Boolean(r&AP.expressionStatement)},FunctionExpression:function(e,t,r){return Boolean(r&(AP.expressionStatement|AP.exportDefault))},FunctionTypeAnnotation:function(e,t,r){var a=t.type;return"UnionTypeAnnotation"===a||"IntersectionTypeAnnotation"===a||"ArrayTypeAnnotation"===a||Boolean(r&AP.arrowFlowReturnType)},Identifier:function(e,t,r,a){var n,s=t.type;if(null!=(n=e.extra)&&n.parenthesized&&"AssignmentExpression"===s&&t.left===e){var o=t.right.type;if(("FunctionExpression"===o||"ClassExpression"===o)&&null==t.right.id)return!0}return(!a||a(e)===e.name)&&("let"===e.name?!!((tP(t,{object:e,computed:!0})||aP(t,{object:e,computed:!0,optional:!1}))&&r&(AP.expressionStatement|AP.forInitHead|AP.forInHead))||Boolean(r&AP.forOfHead):"async"===e.name&&ZT(t,{left:e,await:!1}))},IntersectionTypeAnnotation:fP,LogicalExpression:function(e,t){var r=t.type;if(dP(r))return!0;if("LogicalExpression"!==r)return!1;switch(e.operator){case"||":return"??"===t.operator||"&&"===t.operator;case"&&":return"??"===t.operator;case"??":return"??"!==t.operator}},NullableTypeAnnotation:function(e,t){return YT(t)},ObjectExpression:function(e,t,r){return uP(r)},OptionalCallExpression:xP,OptionalIndexedAccessType:function(e,t){return eP(t)&&t.objectType===e},OptionalMemberExpression:xP,SequenceExpression:function(e,t){var r=t.type;return!("SequenceExpression"===r||"ParenthesizedExpression"===r||"MemberExpression"===r&&t.property===e||"OptionalMemberExpression"===r&&t.property===e||"TemplateLiteral"===r)&&("ClassDeclaration"===r||("ForOfStatement"===r?t.right===e:"ExportDefaultDeclaration"===r||!sP(t)))},TSAsExpression:gP,TSConditionalType:function(e,t){var r=t.type;return"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r||"TSTypeOperator"===r||"TSTypeParameter"===r||(("TSIntersectionType"===r||"TSUnionType"===r)&&t.types[0]===e||"TSConditionalType"===r&&(t.checkType===e||t.extendsType===e))},TSConstructorType:yP,TSFunctionType:yP,TSInferType:function(e,t){var r=t.type;return"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r||!(!e.typeParameter.constraint||"TSIntersectionType"!==r&&"TSUnionType"!==r||t.types[0]!==e)},TSInstantiationExpression:function(e,t){var r=t.type;return("CallExpression"===r||"OptionalCallExpression"===r||"NewExpression"===r||"TSInstantiationExpression"===r)&&!!t.typeParameters},TSIntersectionType:function(e,t){var r=t.type;return"TSTypeOperator"===r||"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r},TSSatisfiesExpression:gP,TSTypeAssertion:hP,TSTypeOperator:function(e,t){var r=t.type;return"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r},TSUnionType:function(e,t){var r=t.type;return"TSIntersectionType"===r||"TSTypeOperator"===r||"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r},UnaryLike:hP,UnionTypeAnnotation:fP,UpdateExpression:function(e,t){return lP(e,t)||cP(e,t)},YieldExpression:mP}),RP=Pa,jP=Sa,wP=ee,EP=Bt,SP=me,TP=he,PP=Se,AP={normal:0,expressionStatement:1,arrowBody:2,exportDefault:4,arrowFlowReturnType:8,forInitHead:16,forInHead:32,forOfHead:64,forInOrInitHeadAccumulate:128,forInOrInitHeadAccumulatePassThroughMask:128};function kP(e){var t=new Map;function r(e,r){var a=t.get(e);t.set(e,a?function(e,t,n,s){var o;return null!=(o=a(e,t,n,s))?o:r(e,t,n,s)}:r)}for(var a=0,n=Object.keys(e);a0&&a._nodesToTokenIndexes.set(e,t)})),this._tokensCache=null}var t=e.prototype;return t.has=function(e){return this._nodesToTokenIndexes.has(e)},t.getIndexes=function(e){return this._nodesToTokenIndexes.get(e)},t.find=function(e,t){var r=this._nodesToTokenIndexes.get(e);if(r)for(var a=0;a=0;a--){var n=r[a];if(t(this._tokens[n],n))return n}return-1},t.findMatching=function(e,t,r){void 0===r&&(r=0);var a=this._nodesToTokenIndexes.get(e);if(a){var n=0,s=r;if(s>1){var o=this._nodesOccurrencesCountCache.get(e);o&&o.test===t&&o.count0&&this._nodesOccurrencesCountCache.set(e,{test:t,count:s,i:n}),i;r--}}}return null},t.matchesOriginal=function(e,t){return e.end-e.start===t.length&&(null!=e.value?e.value===t:this._source.startsWith(t,e.start))},t.startMatches=function(e,t){var r=this._nodesToTokenIndexes.get(e);if(!r)return!1;var a=this._tokens[r[0]];return a.start===e.start&&this.matchesOriginal(a,t)},t.endMatches=function(e,t){var r=this._nodesToTokenIndexes.get(e);if(!r)return!1;var a=this._tokens[r[r.length-1]];return a.end===e.end&&this.matchesOriginal(a,t)},t._getTokensIndexesOfNode=function(e){if(null==e.start||null==e.end)return[];var t=this._findTokensOfNode(e,0,this._tokens.length-1),r=t.first,a=t.last,n=r,s=MP(e);"ExportNamedDeclaration"!==e.type&&"ExportDefaultDeclaration"!==e.type||!e.declaration||"ClassDeclaration"!==e.declaration.type||s.next();for(var o,d=[],c=i(s);!(o=c()).done;){var l=o.value;if(null!=l&&(null!=l.start&&null!=l.end)){for(var u=this._findTokensOfNode(l,n,a),p=u.first,f=n;f>1;if(ethis._tokens[a].start))return a;t=a+1}}return t},t._findLastTokenOfNode=function(e,t,r){for(;t<=r;){var a=r+t>>1;if(ethis._tokens[a].end))return a;t=a+1}}return r},o(e)}();function MP(e){var t,r,a,n,s,o;return p().w((function(d){for(;;)switch(d.n){case 0:if("TemplateLiteral"!==e.type){d.n=6;break}return d.n=1,e.quasis[0];case 1:t=1;case 2:if(!(t2?hA(p):"\\x"+("00"+p).slice(-2)})),"`"==d&&(i=i.replace(/\$\{/g,"\\${")),t.isScriptContext&&(i=i.replace(/<\/(script|style)/gi,"<\\/$1").replace(/ previous live fiber + // --sibling--> deleted fiber + // + // We can't disconnect `alternate` on nodes that haven't been deleted + // yet, but we can disconnect the `sibling` and `child` pointers. + var previousFiber = fiber.alternate; + + if (previousFiber !== null) { + var detachedChild = previousFiber.child; + + if (detachedChild !== null) { + previousFiber.child = null; + + do { + var detachedSibling = detachedChild.sibling; + detachedChild.sibling = null; + detachedChild = detachedSibling; + } while (detachedChild !== null); + } + } + } + + nextEffect = fiber; + } + } + + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { + child.return = fiber; + nextEffect = child; + } else { + commitPassiveUnmountEffects_complete(); + } + } + } + + function commitPassiveUnmountEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; + + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); + commitPassiveUnmountOnFiber(fiber); + resetCurrentFiber(); + } + + var sibling = fiber.sibling; + + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + + nextEffect = fiber.return; + } + } + + function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + recordPassiveEffectDuration(finishedWork); + } else { + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + } + + break; + } + } + } + + function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { + while (nextEffect !== null) { + var fiber = nextEffect; // Deletion effects fire in parent -> child order + // TODO: Check if fiber has a PassiveStatic flag + + setCurrentFiber(fiber); + commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); + resetCurrentFiber(); + var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we + // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) + + if (child !== null) { + child.return = fiber; + nextEffect = child; + } else { + commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); + } + } + } + + function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var sibling = fiber.sibling; + var returnFiber = fiber.return; + + { + // Recursively traverse the entire deleted tree and clean up fiber fields. + // This is more aggressive than ideal, and the long term goal is to only + // have to detach the deleted tree at the root. + detachFiberAfterEffects(fiber); + + if (fiber === deletedSubtreeRoot) { + nextEffect = null; + return; + } + } + + if (sibling !== null) { + sibling.return = returnFiber; + nextEffect = sibling; + return; + } + + nextEffect = returnFiber; + } + } + + function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { + switch (current.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( current.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); + recordPassiveEffectDuration(current); + } else { + commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); + } + + break; + } + } + } // TODO: Reuse reappearLayoutEffects traversal here? + + + function invokeLayoutEffectMountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListMount(Layout | HasEffect, fiber); + } catch (error) { + captureCommitPhaseError(fiber, fiber.return, error); + } + + break; + } + + case ClassComponent: + { + var instance = fiber.stateNode; + + try { + instance.componentDidMount(); + } catch (error) { + captureCommitPhaseError(fiber, fiber.return, error); + } + + break; + } + } + } + } + + function invokePassiveEffectMountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListMount(Passive$1 | HasEffect, fiber); + } catch (error) { + captureCommitPhaseError(fiber, fiber.return, error); + } + + break; + } + } + } + } + + function invokeLayoutEffectUnmountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); + } catch (error) { + captureCommitPhaseError(fiber, fiber.return, error); + } + + break; + } + + case ClassComponent: + { + var instance = fiber.stateNode; + + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } + + break; + } + } + } + } + + function invokePassiveEffectUnmountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); + } catch (error) { + captureCommitPhaseError(fiber, fiber.return, error); + } + } + } + } + } + + var COMPONENT_TYPE = 0; + var HAS_PSEUDO_CLASS_TYPE = 1; + var ROLE_TYPE = 2; + var TEST_NAME_TYPE = 3; + var TEXT_TYPE = 4; + + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + COMPONENT_TYPE = symbolFor('selector.component'); + HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); + ROLE_TYPE = symbolFor('selector.role'); + TEST_NAME_TYPE = symbolFor('selector.test_id'); + TEXT_TYPE = symbolFor('selector.text'); + } + var commitHooks = []; + function onCommitRoot$1() { + { + commitHooks.forEach(function (commitHook) { + return commitHook(); + }); + } + } + + var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; + function isLegacyActEnvironment(fiber) { + { + // Legacy mode. We preserve the behavior of React 17's act. It assumes an + // act environment whenever `jest` is defined, but you can still turn off + // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly + // to false. + var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest + + var jestIsDefined = typeof jest !== 'undefined'; + return jestIsDefined && isReactActEnvironmentGlobal !== false; + } + } + function isConcurrentActEnvironment() { + { + var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; + + if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { + // TODO: Include link to relevant documentation page. + error('The current testing environment is not configured to support ' + 'act(...)'); + } + + return isReactActEnvironmentGlobal; + } + } + + var ceil = Math.ceil; + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig, + ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; + var NoContext = + /* */ + 0; + var BatchedContext = + /* */ + 1; + var RenderContext = + /* */ + 2; + var CommitContext = + /* */ + 4; + var RootInProgress = 0; + var RootFatalErrored = 1; + var RootErrored = 2; + var RootSuspended = 3; + var RootSuspendedWithDelay = 4; + var RootCompleted = 5; + var RootDidNotComplete = 6; // Describes where we are in the React execution stack + + var executionContext = NoContext; // The root we're working on + + var workInProgressRoot = null; // The fiber we're working on + + var workInProgress = null; // The lanes we're rendering + + var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree + // This is a superset of the lanes we started working on at the root. The only + // case where it's different from `workInProgressRootRenderLanes` is when we + // enter a subtree that is hidden and needs to be unhidden: Suspense and + // Offscreen component. + // + // Most things in the work loop should deal with workInProgressRootRenderLanes. + // Most things in begin/complete phases should deal with subtreeRenderLanes. + + var subtreeRenderLanes = NoLanes; + var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. + + var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown + + var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's + // slightly different than `renderLanes` because `renderLanes` can change as you + // enter and exit an Offscreen tree. This value is the combination of all render + // lanes for the entire render phase. + + var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only + // includes unprocessed updates, not work in bailed out children. + + var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. + + var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). + + var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. + + var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. + // We will log them once the tree commits. + + var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train + // model where we don't commit new loading states in too quick succession. + + var globalMostRecentFallbackTime = 0; + var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering + // more and prefer CPU suspense heuristics instead. + + var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU + // suspense heuristics and opt out of rendering more content. + + var RENDER_TIMEOUT_MS = 500; + var workInProgressTransitions = null; + + function resetRenderTimer() { + workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; + } + + function getRenderTargetTime() { + return workInProgressRootRenderTargetTime; + } + var hasUncaughtError = false; + var firstUncaughtError = null; + var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; + var rootDoesHavePassiveEffects = false; + var rootWithPendingPassiveEffects = null; + var pendingPassiveEffectsLanes = NoLanes; + var pendingPassiveProfilerEffects = []; + var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates + + var NESTED_UPDATE_LIMIT = 50; + var nestedUpdateCount = 0; + var rootWithNestedUpdates = null; + var isFlushingPassiveEffects = false; + var didScheduleUpdateDuringPassiveEffects = false; + var NESTED_PASSIVE_UPDATE_LIMIT = 50; + var nestedPassiveUpdateCount = 0; + var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their + // event times as simultaneous, even if the actual clock time has advanced + // between the first and second call. + + var currentEventTime = NoTimestamp; + var currentEventTransitionLane = NoLanes; + var isRunningInsertionEffect = false; + function getWorkInProgressRoot() { + return workInProgressRoot; + } + function requestEventTime() { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + // We're inside React, so it's fine to read the actual time. + return now(); + } // We're not inside React, so we may be in the middle of a browser event. + + + if (currentEventTime !== NoTimestamp) { + // Use the same start time for all updates until we enter React again. + return currentEventTime; + } // This is the first update since React yielded. Compute a new start time. + + + currentEventTime = now(); + return currentEventTime; + } + function requestUpdateLane(fiber) { + // Special cases + var mode = fiber.mode; + + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { + // This is a render phase update. These are not officially supported. The + // old behavior is to give this the same "thread" (lanes) as + // whatever is currently rendering. So if you call `setState` on a component + // that happens later in the same render, it will flush. Ideally, we want to + // remove the special case and treat them as if they came from an + // interleaved event. Regardless, this pattern is not officially supported. + // This behavior is only a fallback. The flag only exists until we can roll + // out the setState warning, since existing code might accidentally rely on + // the current behavior. + return pickArbitraryLane(workInProgressRootRenderLanes); + } + + var isTransition = requestCurrentTransition() !== NoTransition; + + if (isTransition) { + if ( ReactCurrentBatchConfig$3.transition !== null) { + var transition = ReactCurrentBatchConfig$3.transition; + + if (!transition._updatedFibers) { + transition._updatedFibers = new Set(); + } + + transition._updatedFibers.add(fiber); + } // The algorithm for assigning an update to a lane should be stable for all + // updates at the same priority within the same event. To do this, the + // inputs to the algorithm must be the same. + // + // The trick we use is to cache the first of each of these inputs within an + // event. Then reset the cached values once we can be sure the event is + // over. Our heuristic for that is whenever we enter a concurrent work loop. + + + if (currentEventTransitionLane === NoLane) { + // All transitions within the same event are assigned the same lane. + currentEventTransitionLane = claimNextTransitionLane(); + } + + return currentEventTransitionLane; + } // Updates originating inside certain React methods, like flushSync, have + // their priority set by tracking it with a context variable. + // + // The opaque type returned by the host config is internally a lane, so we can + // use that directly. + // TODO: Move this type conversion to the event priority module. + + + var updateLane = getCurrentUpdatePriority(); + + if (updateLane !== NoLane) { + return updateLane; + } // This update originated outside React. Ask the host environment for an + // appropriate priority, based on the type of event. + // + // The opaque type returned by the host config is internally a lane, so we can + // use that directly. + // TODO: Move this type conversion to the event priority module. + + + var eventLane = getCurrentEventPriority(); + return eventLane; + } + + function requestRetryLane(fiber) { + // This is a fork of `requestUpdateLane` designed specifically for Suspense + // "retries" — a special update that attempts to flip a Suspense boundary + // from its placeholder state to its primary/resolved state. + // Special cases + var mode = fiber.mode; + + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } + + return claimNextRetryLane(); + } + + function scheduleUpdateOnFiber(root, fiber, lane, eventTime) { + checkForNestedUpdates(); + + { + if (isRunningInsertionEffect) { + error('useInsertionEffect must not schedule updates.'); + } + } + + { + if (isFlushingPassiveEffects) { + didScheduleUpdateDuringPassiveEffects = true; + } + } // Mark that the root has a pending update. + + + markRootUpdated(root, lane, eventTime); + + if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { + // This update was dispatched during the render phase. This is a mistake + // if the update originates from user space (with the exception of local + // hook updates, which are handled differently and don't reach this + // function), but there are some internal React features that use this as + // an implementation detail, like selective hydration. + warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase + } else { + // This is a normal update, scheduled from outside the render phase. For + // example, during an input event. + { + if (isDevToolsPresent) { + addFiberToLanesMap(root, fiber, lane); + } + } + + warnIfUpdatesNotWrappedWithActDEV(fiber); + + if (root === workInProgressRoot) { + // Received an update to a tree that's in the middle of rendering. Mark + // that there was an interleaved update work on this root. Unless the + // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render + // phase update. In that case, we don't treat render phase updates as if + // they were interleaved, for backwards compat reasons. + if ( (executionContext & RenderContext) === NoContext) { + workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); + } + + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: Make sure this doesn't override pings that happen while we've + // already started rendering. + markRootSuspended$1(root, workInProgressRootRenderLanes); + } + } + + ensureRootIsScheduled(root, eventTime); + + if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !( ReactCurrentActQueue$1.isBatchingLegacy)) { + // Flush the synchronous work now, unless we're already working or inside + // a batch. This is intentionally inside scheduleUpdateOnFiber instead of + // scheduleCallbackForFiber to preserve the ability to schedule a callback + // without immediately flushing it. We only do this for user-initiated + // updates, to preserve historical behavior of legacy mode. + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function scheduleInitialHydrationOnRoot(root, lane, eventTime) { + // This is a special fork of scheduleUpdateOnFiber that is only used to + // schedule the initial hydration of a root that has just been created. Most + // of the stuff in scheduleUpdateOnFiber can be skipped. + // + // The main reason for this separate path, though, is to distinguish the + // initial children from subsequent updates. In fully client-rendered roots + // (createRoot instead of hydrateRoot), all top-level renders are modeled as + // updates, but hydration roots are special because the initial render must + // match what was rendered on the server. + var current = root.current; + current.lanes = lane; + markRootUpdated(root, lane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + function isUnsafeClassRenderPhaseUpdate(fiber) { + // Check if this is a render phase update. Only called by class components, + // which special (deprecated) behavior for UNSAFE_componentWillReceive props. + return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We + // decided not to enable it. + (executionContext & RenderContext) !== NoContext + ); + } // Use this function to schedule a task for a root. There's only one task per + // root; if a task was already scheduled, we'll check to make sure the priority + // of the existing task is the same as the priority of the next level that the + // root has work on. This function is called on every update, and right before + // exiting a task. + + function ensureRootIsScheduled(root, currentTime) { + var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as + // expired so we know to work on those next. + + markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. + + var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); + + if (nextLanes === NoLanes) { + // Special case: There's nothing to work on. + if (existingCallbackNode !== null) { + cancelCallback$1(existingCallbackNode); + } + + root.callbackNode = null; + root.callbackPriority = NoLane; + return; + } // We use the highest priority lane to represent the priority of the callback. + + + var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. + + var existingCallbackPriority = root.callbackPriority; + + if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a + // Scheduler task, rather than an `act` task, cancel it and re-scheduled + // on the `act` queue. + !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { + { + // If we're going to re-use an existing task, it needs to exist. + // Assume that discrete update microtasks are non-cancellable and null. + // TODO: Temporary until we confirm this warning is not fired. + if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { + error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); + } + } // The priority hasn't changed. We can reuse the existing task. Exit. + + + return; + } + + if (existingCallbackNode != null) { + // Cancel the existing callback. We'll schedule a new one below. + cancelCallback$1(existingCallbackNode); + } // Schedule a new callback. + + + var newCallbackNode; + + if (newCallbackPriority === SyncLane) { + // Special case: Sync React callbacks are scheduled on a special + // internal queue + if (root.tag === LegacyRoot) { + if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { + ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; + } + + scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else { + scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } + + { + // Flush the queue in a microtask. + if ( ReactCurrentActQueue$1.current !== null) { + // Inside `act`, use our internal `act` queue so that these get flushed + // at the end of the current scope even when using the sync version + // of `act`. + ReactCurrentActQueue$1.current.push(flushSyncCallbacks); + } else { + scheduleMicrotask(function () { + // In Safari, appending an iframe forces microtasks to run. + // https://github.com/facebook/react/issues/22459 + // We don't support running callbacks in the middle of render + // or commit so we need to check against that. + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + // Note that this would still prematurely flush the callbacks + // if this happens outside render or commit phase (e.g. in an event). + flushSyncCallbacks(); + } + }); + } + } + + newCallbackNode = null; + } else { + var schedulerPriorityLevel; + + switch (lanesToEventPriority(nextLanes)) { + case DiscreteEventPriority: + schedulerPriorityLevel = ImmediatePriority; + break; + + case ContinuousEventPriority: + schedulerPriorityLevel = UserBlockingPriority; + break; + + case DefaultEventPriority: + schedulerPriorityLevel = NormalPriority; + break; + + case IdleEventPriority: + schedulerPriorityLevel = IdlePriority; + break; + + default: + schedulerPriorityLevel = NormalPriority; + break; + } + + newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); + } + + root.callbackPriority = newCallbackPriority; + root.callbackNode = newCallbackNode; + } // This is the entry point for every concurrent task, i.e. anything that + // goes through Scheduler. + + + function performConcurrentWorkOnRoot(root, didTimeout) { + { + resetNestedUpdateFlag(); + } // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. + + + currentEventTime = NoTimestamp; + currentEventTransitionLane = NoLanes; + + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } // Flush any pending passive effects before deciding which lanes to work on, + // in case they schedule additional work. + + + var originalCallbackNode = root.callbackNode; + var didFlushPassiveEffects = flushPassiveEffects(); + + if (didFlushPassiveEffects) { + // Something in the passive effect phase may have canceled the current task. + // Check if the task node for this root was changed. + if (root.callbackNode !== originalCallbackNode) { + // The current task was canceled. Exit. We don't need to call + // `ensureRootIsScheduled` because the check above implies either that + // there's a new task, or that there's no remaining work on this root. + return null; + } + } // Determine the next lanes to work on, using the fields stored + // on the root. + + + var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); + + if (lanes === NoLanes) { + // Defensive coding. This is never expected to happen. + return null; + } // We disable time-slicing in some cases: if the work has been CPU-bound + // for too long ("expired" work, to prevent starvation), or we're in + // sync-updates-by-default mode. + // TODO: We only check `didTimeout` defensively, to account for a Scheduler + // bug we're still investigating. Once the bug in Scheduler is fixed, + // we can remove this, since we track expiration ourselves. + + + var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); + var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); + + if (exitStatus !== RootInProgress) { + if (exitStatus === RootErrored) { + // If something threw an error, try rendering one more time. We'll + // render synchronously to block concurrent data mutations, and we'll + // includes all pending updates are included. If it still fails after + // the second attempt, we'll give up and commit the resulting tree. + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); + + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } + + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now()); + throw fatalError; + } + + if (exitStatus === RootDidNotComplete) { + // The render unwound without completing the tree. This happens in special + // cases where need to exit the current render without producing a + // consistent tree or committing. + // + // This should only happen during a concurrent render, not a discrete or + // synchronous update. We should have already checked for this when we + // unwound the stack. + markRootSuspended$1(root, lanes); + } else { + // The render completed. + // Check if this render may have yielded to a concurrent event, and if so, + // confirm that any newly rendered stores are consistent. + // TODO: It's possible that even a concurrent render may never have yielded + // to the main thread, if it was fast enough, or if it expired. We could + // skip the consistency check in that case, too. + var renderWasConcurrent = !includesBlockingLane(root, lanes); + var finishedWork = root.current.alternate; + + if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { + // A store was mutated in an interleaved event. Render again, + // synchronously, to block further mutations. + exitStatus = renderRootSync(root, lanes); // We need to check again if something threw + + if (exitStatus === RootErrored) { + var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); + + if (_errorRetryLanes !== NoLanes) { + lanes = _errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any + // concurrent events. + } + } + + if (exitStatus === RootFatalErrored) { + var _fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now()); + throw _fatalError; + } + } // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. + + + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + finishConcurrentRender(root, exitStatus, lanes); + } + } + + ensureRootIsScheduled(root, now()); + + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); + } + + return null; + } + + function recoverFromConcurrentError(root, errorRetryLanes) { + // If an error occurred during hydration, discard server response and fall + // back to client side render. + // Before rendering again, save the errors from the previous attempt. + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; + + if (isRootDehydrated(root)) { + // The shell failed to hydrate. Set a flag to force a client rendering + // during the next attempt. To do this, we call prepareFreshStack now + // to create the root work-in-progress fiber. This is a bit weird in terms + // of factoring, because it relies on renderRootSync not calling + // prepareFreshStack again in the call below, which happens because the + // root and lanes haven't changed. + // + // TODO: I think what we should do is set ForceClientRender inside + // throwException, like we do for nested Suspense boundaries. The reason + // it's here instead is so we can switch to the synchronous work loop, too. + // Something to consider for a future refactor. + var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); + rootWorkInProgress.flags |= ForceClientRender; + + { + errorHydratingContainer(root.containerInfo); + } + } + + var exitStatus = renderRootSync(root, errorRetryLanes); + + if (exitStatus !== RootErrored) { + // Successfully finished rendering on retry + // The errors from the failed first attempt have been recovered. Add + // them to the collection of recoverable errors. We'll log them in the + // commit phase. + var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors + // from the first attempt, to preserve the causal sequence. + + if (errorsFromSecondAttempt !== null) { + queueRecoverableErrors(errorsFromSecondAttempt); + } + } + + return exitStatus; + } + + function queueRecoverableErrors(errors) { + if (workInProgressRootRecoverableErrors === null) { + workInProgressRootRecoverableErrors = errors; + } else { + workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); + } + } + + function finishConcurrentRender(root, exitStatus, lanes) { + switch (exitStatus) { + case RootInProgress: + case RootFatalErrored: + { + throw new Error('Root did not complete. This is a bug in React.'); + } + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough + + case RootErrored: + { + // We should have already attempted to retry this tree. If we reached + // this point, it errored again. Commit it. + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + + case RootSuspended: + { + markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. + + if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope + !shouldForceFlushFallbacksInDEV()) { + // This render only included retries, no updates. Throttle committing + // retries so that we don't show too many loading states too quickly. + var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. + + if (msUntilTimeout > 10) { + var nextLanes = getNextLanes(root, NoLanes); + + if (nextLanes !== NoLanes) { + // There's additional work on this root. + break; + } + + var suspendedLanes = root.suspendedLanes; + + if (!isSubsetOfLanes(suspendedLanes, lanes)) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + // FIXME: What if the suspended lanes are Idle? Should not restart. + var eventTime = requestEventTime(); + markRootPinged(root, suspendedLanes); + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback + // immediately, wait for more data to arrive. + + + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout); + break; + } + } // The work expired. Commit immediately. + + + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + + case RootSuspendedWithDelay: + { + markRootSuspended$1(root, lanes); + + if (includesOnlyTransitions(lanes)) { + // This is a transition, so we should exit without committing a + // placeholder and without scheduling a timeout. Delay indefinitely + // until we receive more data. + break; + } + + if (!shouldForceFlushFallbacksInDEV()) { + // This is not a transition, but we did trigger an avoided state. + // Schedule a placeholder to display after a short delay, using the Just + // Noticeable Difference. + // TODO: Is the JND optimization worth the added complexity? If this is + // the only reason we track the event time, then probably not. + // Consider removing. + var mostRecentEventTime = getMostRecentEventTime(root, lanes); + var eventTimeMs = mostRecentEventTime; + var timeElapsedMs = now() - eventTimeMs; + + var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. + + + if (_msUntilTimeout > 10) { + // Instead of committing the fallback immediately, wait for more data + // to arrive. + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout); + break; + } + } // Commit the placeholder. + + + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + + case RootCompleted: + { + // The work completed. Ready to commit. + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + + default: + { + throw new Error('Unknown root exit status.'); + } + } + } + + function isRenderConsistentWithExternalStores(finishedWork) { + // Search the rendered tree for external store reads, and check whether the + // stores were mutated in a concurrent event. Intentionally using an iterative + // loop instead of recursion so we can exit early. + var node = finishedWork; + + while (true) { + if (node.flags & StoreConsistency) { + var updateQueue = node.updateQueue; + + if (updateQueue !== null) { + var checks = updateQueue.stores; + + if (checks !== null) { + for (var i = 0; i < checks.length; i++) { + var check = checks[i]; + var getSnapshot = check.getSnapshot; + var renderedValue = check.value; + + try { + if (!objectIs(getSnapshot(), renderedValue)) { + // Found an inconsistent store. + return false; + } + } catch (error) { + // If `getSnapshot` throws, return `false`. This will schedule + // a re-render, and the error will be rethrown during render. + return false; + } + } + } + } + } + + var child = node.child; + + if (node.subtreeFlags & StoreConsistency && child !== null) { + child.return = node; + node = child; + continue; + } + + if (node === finishedWork) { + return true; + } + + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return true; + } + + node = node.return; + } + + node.sibling.return = node.return; + node = node.sibling; + } // Flow doesn't know this is unreachable, but eslint does + // eslint-disable-next-line no-unreachable + + + return true; + } + + function markRootSuspended$1(root, suspendedLanes) { + // When suspending, we should always exclude lanes that were pinged or (more + // rarely, since we try to avoid it) updated during the render phase. + // TODO: Lol maybe there's a better way to factor this besides this + // obnoxiously named function :) + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); + markRootSuspended(root, suspendedLanes); + } // This is the entry point for synchronous tasks that don't go + // through Scheduler + + + function performSyncWorkOnRoot(root) { + { + syncNestedUpdateFlag(); + } + + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } + + flushPassiveEffects(); + var lanes = getNextLanes(root, NoLanes); + + if (!includesSomeLane(lanes, SyncLane)) { + // There's no remaining sync work left. + ensureRootIsScheduled(root, now()); + return null; + } + + var exitStatus = renderRootSync(root, lanes); + + if (root.tag !== LegacyRoot && exitStatus === RootErrored) { + // If something threw an error, try rendering one more time. We'll render + // synchronously to block concurrent data mutations, and we'll includes + // all pending updates are included. If it still fails after the second + // attempt, we'll give up and commit the resulting tree. + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); + + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } + + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now()); + throw fatalError; + } + + if (exitStatus === RootDidNotComplete) { + throw new Error('Root did not complete. This is a bug in React.'); + } // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. + + + var finishedWork = root.current.alternate; + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next + // pending level. + + ensureRootIsScheduled(root, now()); + return null; + } + + function flushRoot(root, lanes) { + if (lanes !== NoLanes) { + markRootEntangled(root, mergeLanes(lanes, SyncLane)); + ensureRootIsScheduled(root, now()); + + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function batchedUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer + // most batchedUpdates-like method. + + if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !( ReactCurrentActQueue$1.isBatchingLegacy)) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function discreteUpdates(fn, a, b, c, d) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$3.transition; + + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + return fn(a, b, c, d); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + + if (executionContext === NoContext) { + resetRenderTimer(); + } + } + } // Overload the definition to the two valid signatures. + // Warning, this opts-out of checking the function body. + + // eslint-disable-next-line no-redeclare + function flushSync(fn) { + // In legacy mode, we flush pending passive effects at the beginning of the + // next event, not at the end of the previous one. + if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { + flushPassiveEffects(); + } + + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$3.transition; + var previousPriority = getCurrentUpdatePriority(); + + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + + if (fn) { + return fn(); + } else { + return undefined; + } + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. + + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + flushSyncCallbacks(); + } + } + } + function isAlreadyRendering() { + // Used by the renderer to print a warning if certain APIs are called from + // the wrong context. + return (executionContext & (RenderContext | CommitContext)) !== NoContext; + } + function pushRenderLanes(fiber, lanes) { + push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); + subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); + workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes); + } + function popRenderLanes(fiber) { + subtreeRenderLanes = subtreeRenderLanesCursor.current; + pop(subtreeRenderLanesCursor, fiber); + } + + function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = NoLanes; + var timeoutHandle = root.timeoutHandle; + + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above + + cancelTimeout(timeoutHandle); + } + + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + + while (interruptedWork !== null) { + var current = interruptedWork.alternate; + unwindInterruptedWork(current, interruptedWork); + interruptedWork = interruptedWork.return; + } + } + + workInProgressRoot = root; + var rootWorkInProgress = createWorkInProgress(root.current, null); + workInProgress = rootWorkInProgress; + workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; + workInProgressRootExitStatus = RootInProgress; + workInProgressRootFatalError = null; + workInProgressRootSkippedLanes = NoLanes; + workInProgressRootInterleavedUpdatedLanes = NoLanes; + workInProgressRootPingedLanes = NoLanes; + workInProgressRootConcurrentErrors = null; + workInProgressRootRecoverableErrors = null; + finishQueueingConcurrentUpdates(); + + { + ReactStrictModeWarnings.discardPendingWarnings(); + } + + return rootWorkInProgress; + } + + function handleError(root, thrownValue) { + do { + var erroredWork = workInProgress; + + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooksAfterThrow(); + resetCurrentFiber(); // TODO: I found and added this missing line while investigating a + // separate issue. Write a regression test using string refs. + + ReactCurrentOwner$2.current = null; + + if (erroredWork === null || erroredWork.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next + // sibling, or the parent if there are no siblings. But since the root + // has no siblings nor a parent, we set it to null. Usually this is + // handled by `completeUnitOfWork` or `unwindWork`, but since we're + // intentionally not calling those, we need set it here. + // TODO: Consider calling `unwindWork` to pop the contexts. + + workInProgress = null; + return; + } + + if (enableProfilerTimer && erroredWork.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); + } + + if (enableSchedulingProfiler) { + markComponentRenderStopped(); + + if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { + var wakeable = thrownValue; + markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); + } else { + markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); + } + } + + throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); + completeUnitOfWork(erroredWork); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; + + if (workInProgress === erroredWork && erroredWork !== null) { + // If this boundary has already errored, then we had trouble processing + // the error. Bubble it to the next boundary. + erroredWork = erroredWork.return; + workInProgress = erroredWork; + } else { + erroredWork = workInProgress; + } + + continue; + } // Return to the normal work loop. + + + return; + } while (true); + } + + function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher$2.current; + ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; + + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } + } + + function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher$2.current = prevDispatcher; + } + + function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); + } + function markSkippedUpdateLanes(lane) { + workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); + } + function renderDidSuspend() { + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootSuspended; + } + } + function renderDidSuspendDelayIfPossible() { + if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there are updates that we skipped tree that might have unblocked + // this render. + + + if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { + // Mark the current render as suspended so that we switch to working on + // the updates that were skipped. Usually we only suspend at the end of + // the render phase. + // TODO: We should probably always mark the root as suspended immediately + // (inside this function), since by suspending at the end of the render + // phase introduces a potential mistake where we suspend lanes that were + // pinged or updated while we were rendering. + markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); + } + } + function renderDidError(error) { + if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { + workInProgressRootExitStatus = RootErrored; + } + + if (workInProgressRootConcurrentErrors === null) { + workInProgressRootConcurrentErrors = [error]; + } else { + workInProgressRootConcurrentErrors.push(error); + } + } // Called during render to determine if anything has suspended. + // Returns false if we're not sure. + + function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootInProgress; + } + + function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. + + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. + // If we bailout on this work, we'll move them back (like above). + // It's important to move them now in case the work spawns more work at the same priority with different updaters. + // That way we can keep the current update and future updates separate. + + + movePendingFibersToMemoized(root, lanes); + } + } + + workInProgressTransitions = getTransitionsForLanes(); + prepareFreshStack(root, lanes); + } + + { + markRenderStarted(lanes); + } + + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); + } + + { + markRenderStopped(); + } // Set this to null to indicate there's no in-progress render. + + + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } // The work loop is an extremely hot path. Tell Closure not to inline it. + + /** @noinline */ + + + function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + performUnitOfWork(workInProgress); + } + } + + function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. + + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. + // If we bailout on this work, we'll move them back (like above). + // It's important to move them now in case the work spawns more work at the same priority with different updaters. + // That way we can keep the current update and future updates separate. + + + movePendingFibersToMemoized(root, lanes); + } + } + + workInProgressTransitions = getTransitionsForLanes(); + resetRenderTimer(); + prepareFreshStack(root, lanes); + } + + { + markRenderStarted(lanes); + } + + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + + resetContextDependencies(); + popDispatcher(prevDispatcher); + executionContext = prevExecutionContext; + + + if (workInProgress !== null) { + // Still work remaining. + { + markRenderYielded(); + } + + return RootInProgress; + } else { + // Completed the tree. + { + markRenderStopped(); + } // Set this to null to indicate there's no in-progress render. + + + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; // Return the final exit status. + + return workInProgressRootExitStatus; + } + } + /** @noinline */ + + + function workLoopConcurrent() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + performUnitOfWork(workInProgress); + } + } + + function performUnitOfWork(unitOfWork) { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current = unitOfWork.alternate; + setCurrentFiber(unitOfWork); + var next; + + if ( (unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current, unitOfWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current, unitOfWork, subtreeRenderLanes); + } + + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + + if (next === null) { + // If this doesn't spawn new work, complete the current work. + completeUnitOfWork(unitOfWork); + } else { + workInProgress = next; + } + + ReactCurrentOwner$2.current = null; + } + + function completeUnitOfWork(unitOfWork) { + // Attempt to complete the current unit of work, then move to the next + // sibling. If there are no more siblings, return to the parent fiber. + var completedWork = unitOfWork; + + do { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current = completedWork.alternate; + var returnFiber = completedWork.return; // Check if the work completed or if something threw. + + if ((completedWork.flags & Incomplete) === NoFlags) { + setCurrentFiber(completedWork); + var next = void 0; + + if ( (completedWork.mode & ProfileMode) === NoMode) { + next = completeWork(current, completedWork, subtreeRenderLanes); + } else { + startProfilerTimer(completedWork); + next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. + + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + } + + resetCurrentFiber(); + + if (next !== null) { + // Completing this fiber spawned new work. Work on that next. + workInProgress = next; + return; + } + } else { + // This fiber did not complete because something threw. Pop values off + // the stack without entering the complete phase. If this is a boundary, + // capture values if possible. + var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. + + + if (_next !== null) { + // If completing this work spawned new work, do that next. We'll come + // back here again. + // Since we're restarting, remove anything that is not a host effect + // from the effect tag. + _next.flags &= HostEffectMask; + workInProgress = _next; + return; + } + + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // Record the render duration for the fiber that errored. + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. + + var actualDuration = completedWork.actualDuration; + var child = completedWork.child; + + while (child !== null) { + actualDuration += child.actualDuration; + child = child.sibling; + } + + completedWork.actualDuration = actualDuration; + } + + if (returnFiber !== null) { + // Mark the parent fiber as incomplete and clear its subtree flags. + returnFiber.flags |= Incomplete; + returnFiber.subtreeFlags = NoFlags; + returnFiber.deletions = null; + } else { + // We've unwound all the way to the root. + workInProgressRootExitStatus = RootDidNotComplete; + workInProgress = null; + return; + } + } + + var siblingFiber = completedWork.sibling; + + if (siblingFiber !== null) { + // If there is more work to do in this returnFiber, do that next. + workInProgress = siblingFiber; + return; + } // Otherwise, return to the parent + + + completedWork = returnFiber; // Update the next thing we're working on in case something throws. + + workInProgress = completedWork; + } while (completedWork !== null); // We've reached the root. + + + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootCompleted; + } + } + + function commitRoot(root, recoverableErrors, transitions) { + // TODO: This no longer makes any sense. We already wrap the mutation and + // layout phases. Should be able to remove. + var previousUpdateLanePriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$3.transition; + + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority); + } finally { + ReactCurrentBatchConfig$3.transition = prevTransition; + setCurrentUpdatePriority(previousUpdateLanePriority); + } + + return null; + } + + function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) { + do { + // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which + // means `flushPassiveEffects` will sometimes result in additional + // passive effects. So we need to keep flushing in a loop until there are + // no more pending effects. + // TODO: Might be better if `flushPassiveEffects` did not automatically + // flush synchronous work at the end, to avoid factoring hazards like this. + flushPassiveEffects(); + } while (rootWithPendingPassiveEffects !== null); + + flushRenderPhaseStrictModeWarningsInDEV(); + + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } + + var finishedWork = root.finishedWork; + var lanes = root.finishedLanes; + + { + markCommitStarted(lanes); + } + + if (finishedWork === null) { + + { + markCommitStopped(); + } + + return null; + } else { + { + if (lanes === NoLanes) { + error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); + } + } + } + + root.finishedWork = null; + root.finishedLanes = NoLanes; + + if (finishedWork === root.current) { + throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); + } // commitRoot never returns a continuation; it always finishes synchronously. + // So we can clear these now to allow a new callback to be scheduled. + + + root.callbackNode = null; + root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first + // pending time is whatever is left on the root fiber. + + var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); + markRootFinished(root, remainingLanes); + + if (root === workInProgressRoot) { + // We can reset these now that they are finished. + workInProgressRoot = null; + workInProgress = null; + workInProgressRootRenderLanes = NoLanes; + } // If there are pending passive effects, schedule a callback to process them. + // Do this as early as possible, so it is queued before anything else that + // might get scheduled in the commit phase. (See #16714.) + // TODO: Delete all other places that schedule the passive effect callback + // They're redundant. + + + if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + // to store it in pendingPassiveTransitions until they get processed + // We need to pass this through as an argument to commitRoot + // because workInProgressTransitions might have changed between + // the previous render and commit if we throttle the commit + // with setTimeout + + pendingPassiveTransitions = transitions; + scheduleCallback$1(NormalPriority, function () { + flushPassiveEffects(); // This render triggered passive effects: release the root cache pool + // *after* passive effects fire to avoid freeing a cache pool that may + // be referenced by a node in the tree (HostRoot, Cache boundary etc) + + return null; + }); + } + } // Check if there are any effects in the whole tree. + // TODO: This is left over from the effect list implementation, where we had + // to check for the existence of `firstEffect` to satisfy Flow. I think the + // only other reason this optimization exists is because it affects profiling. + // Reconsider whether this is necessary. + + + var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + + if (subtreeHasEffects || rootHasEffect) { + var prevTransition = ReactCurrentBatchConfig$3.transition; + ReactCurrentBatchConfig$3.transition = null; + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(DiscreteEventPriority); + var prevExecutionContext = executionContext; + executionContext |= CommitContext; // Reset this to null before calling lifecycles + + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass + // of the effect list for each phase: all mutation effects come before all + // layout effects, and so on. + // The first phase a "before mutation" phase. We use this phase to read the + // state of the host tree right before we mutate it. This is where + // getSnapshotBeforeUpdate is called. + + var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork); + + { + // Mark the current commit time to be shared by all Profilers in this + // batch. This enables them to be grouped later. + recordCommitTime(); + } + + + commitMutationEffects(root, finishedWork, lanes); + + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after + // the mutation phase, so that the previous tree is still current during + // componentWillUnmount, but before the layout phase, so that the finished + // work is current during componentDidMount/Update. + + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read + + { + markLayoutEffectsStarted(lanes); + } + + commitLayoutEffects(finishedWork, root, lanes); + + { + markLayoutEffectsStopped(); + } + // opportunity to paint. + + + requestPaint(); + executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. + + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + } else { + // No effects. + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were + // no effects. + // TODO: Maybe there's a better way to report this. + + { + recordCommitTime(); + } + } + + var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; + + if (rootDoesHavePassiveEffects) { + // This commit has passive effects. Stash a reference to them. But don't + // schedule a callback until after flushing layout work. + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects = root; + pendingPassiveEffectsLanes = lanes; + } else { + + { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = null; + } + } // Read this again, since an effect might have updated it + + + remainingLanes = root.pendingLanes; // Check if there's remaining work on this root + // TODO: This is part of the `componentDidCatch` implementation. Its purpose + // is to detect whether something might have called setState inside + // `componentDidCatch`. The mechanism is known to be flawed because `setState` + // inside `componentDidCatch` is itself flawed — that's why we recommend + // `getDerivedStateFromError` instead. However, it could be improved by + // checking if remainingLanes includes Sync work, instead of whether there's + // any work remaining at all (which would also include stuff like Suspense + // retries or transitions). It's been like this for a while, though, so fixing + // it probably isn't that urgent. + + if (remainingLanes === NoLanes) { + // If there's no remaining work, we can clear the set of already failed + // error boundaries. + legacyErrorBoundariesThatAlreadyFailed = null; + } + + { + if (!rootDidHavePassiveEffects) { + commitDoubleInvokeEffectsInDEV(root.current, false); + } + } + + onCommitRoot(finishedWork.stateNode, renderPriorityLevel); + + { + if (isDevToolsPresent) { + root.memoizedUpdaters.clear(); + } + } + + { + onCommitRoot$1(); + } // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. + + + ensureRootIsScheduled(root, now()); + + if (recoverableErrors !== null) { + // There were errors during this render, but recovered from them without + // needing to surface it to the UI. We log them here. + var onRecoverableError = root.onRecoverableError; + + for (var i = 0; i < recoverableErrors.length; i++) { + var recoverableError = recoverableErrors[i]; + var componentStack = recoverableError.stack; + var digest = recoverableError.digest; + onRecoverableError(recoverableError.value, { + componentStack: componentStack, + digest: digest + }); + } + } + + if (hasUncaughtError) { + hasUncaughtError = false; + var error$1 = firstUncaughtError; + firstUncaughtError = null; + throw error$1; + } // If the passive effects are the result of a discrete render, flush them + // synchronously at the end of the current task so that the result is + // immediately observable. Otherwise, we assume that they are not + // order-dependent and do not need to be observed by external systems, so we + // can wait until after paint. + // TODO: We can optimize this by not scheduling the callback earlier. Since we + // currently schedule the callback in multiple places, will wait until those + // are consolidated. + + + if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { + flushPassiveEffects(); + } // Read this again, since a passive effect might have updated it + + + remainingLanes = root.pendingLanes; + + if (includesSomeLane(remainingLanes, SyncLane)) { + { + markNestedUpdateScheduled(); + } // Count the number of times the root synchronously re-renders without + // finishing. If there are too many, it indicates an infinite update loop. + + + if (root === rootWithNestedUpdates) { + nestedUpdateCount++; + } else { + nestedUpdateCount = 0; + rootWithNestedUpdates = root; + } + } else { + nestedUpdateCount = 0; + } // If layout work was scheduled, flush it now. + + + flushSyncCallbacks(); + + { + markCommitStopped(); + } + + return null; + } + + function flushPassiveEffects() { + // Returns whether passive effects were flushed. + // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should + // probably just combine the two functions. I believe they were only separate + // in the first place because we used to wrap it with + // `Scheduler.runWithPriority`, which accepts a function. But now we track the + // priority within React itself, so we can mutate the variable directly. + if (rootWithPendingPassiveEffects !== null) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); + var priority = lowerEventPriority(DefaultEventPriority, renderPriority); + var prevTransition = ReactCurrentBatchConfig$3.transition; + var previousPriority = getCurrentUpdatePriority(); + + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(priority); + return flushPassiveEffectsImpl(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a + } + } + + return false; + } + function enqueuePendingPassiveProfilerEffect(fiber) { + { + pendingPassiveProfilerEffects.push(fiber); + + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback$1(NormalPriority, function () { + flushPassiveEffects(); + return null; + }); + } + } + } + + function flushPassiveEffectsImpl() { + if (rootWithPendingPassiveEffects === null) { + return false; + } // Cache and clear the transitions flag + + + var transitions = pendingPassiveTransitions; + pendingPassiveTransitions = null; + var root = rootWithPendingPassiveEffects; + var lanes = pendingPassiveEffectsLanes; + rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. + // Figure out why and fix it. It's not causing any known issues (probably + // because it's only used for profiling), but it's a refactor hazard. + + pendingPassiveEffectsLanes = NoLanes; + + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Cannot flush passive effects while already rendering.'); + } + + { + isFlushingPassiveEffects = true; + didScheduleUpdateDuringPassiveEffects = false; + } + + { + markPassiveEffectsStarted(lanes); + } + + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + commitPassiveUnmountEffects(root.current); + commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects + + { + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; + + for (var i = 0; i < profilerEffects.length; i++) { + var _fiber = profilerEffects[i]; + commitPassiveEffectDurations(root, _fiber); + } + } + + { + markPassiveEffectsStopped(); + } + + { + commitDoubleInvokeEffectsInDEV(root.current, true); + } + + executionContext = prevExecutionContext; + flushSyncCallbacks(); + + { + // If additional passive effects were scheduled, increment a counter. If this + // exceeds the limit, we'll fire a warning. + if (didScheduleUpdateDuringPassiveEffects) { + if (root === rootWithPassiveNestedUpdates) { + nestedPassiveUpdateCount++; + } else { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = root; + } + } else { + nestedPassiveUpdateCount = 0; + } + + isFlushingPassiveEffects = false; + didScheduleUpdateDuringPassiveEffects = false; + } // TODO: Move to commitPassiveMountEffects + + + onPostCommitRoot(root); + + { + var stateNode = root.current.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + + return true; + } + + function isAlreadyFailedLegacyErrorBoundary(instance) { + return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); + } + function markLegacyErrorBoundaryAsFailed(instance) { + if (legacyErrorBoundariesThatAlreadyFailed === null) { + legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); + } else { + legacyErrorBoundariesThatAlreadyFailed.add(instance); + } + } + + function prepareToThrowUncaughtError(error) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error; + } + } + + var onUncaughtError = prepareToThrowUncaughtError; + + function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + var errorInfo = createCapturedValueAtFiber(error, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); + var root = enqueueUpdate(rootFiber, update, SyncLane); + var eventTime = requestEventTime(); + + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } + + function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { + { + reportUncaughtErrorInDEV(error$1); + setIsRunningInsertionEffect(false); + } + + if (sourceFiber.tag === HostRoot) { + // Error was thrown at the root. There is no parent, so the root + // itself should capture it. + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); + return; + } + + var fiber = null; + + { + fiber = nearestMountedAncestor; + } + + while (fiber !== null) { + if (fiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); + return; + } else if (fiber.tag === ClassComponent) { + var ctor = fiber.type; + var instance = fiber.stateNode; + + if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { + var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber); + var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); + var root = enqueueUpdate(fiber, update, SyncLane); + var eventTime = requestEventTime(); + + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + + return; + } + } + + fiber = fiber.return; + } + + { + // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning + // will fire for errors that are thrown by destroy functions inside deleted + // trees. What it should instead do is propagate the error to the parent of + // the deleted tree. In the meantime, do not add this warning to the + // allowlist; this is only for our internal use. + error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); + } + } + function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + + if (pingCache !== null) { + // The wakeable resolved, so we no longer need to memoize, because it will + // never be thrown again. + pingCache.delete(wakeable); + } + + var eventTime = requestEventTime(); + markRootPinged(root, pingedLanes); + warnIfSuspenseResolutionNotWrappedWithActDEV(root); + + if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { + // Received a ping at the same priority level at which we're currently + // rendering. We might want to restart this render. This should mirror + // the logic of whether or not a root suspends once it completes. + // TODO: If we're rendering sync either due to Sync, Batched or expired, + // we should probably never restart. + // If we're suspended with delay, or if it's a retry, we'll always suspend + // so we can always restart. + if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { + // Restart from the root. + prepareFreshStack(root, NoLanes); + } else { + // Even though we can't restart right now, we might get an + // opportunity later. So we mark this render as having a ping. + workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); + } + } + + ensureRootIsScheduled(root, eventTime); + } + + function retryTimedOutBoundary(boundaryFiber, retryLane) { + // The boundary fiber (a Suspense component or SuspenseList component) + // previously was rendered in its fallback state. One of the promises that + // suspended it has resolved, which means at least part of the tree was + // likely unblocked. Try rendering again, at a new lanes. + if (retryLane === NoLane) { + // TODO: Assign this to `suspenseState.retryLane`? to avoid + // unnecessary entanglement? + retryLane = requestRetryLane(boundaryFiber); + } // TODO: Special case idle priority? + + + var eventTime = requestEventTime(); + var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + + if (root !== null) { + markRootUpdated(root, retryLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } + + function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryLane = NoLane; + + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } + + retryTimedOutBoundary(boundaryFiber, retryLane); + } + function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = NoLane; // Default + + var retryCache; + + switch (boundaryFiber.tag) { + case SuspenseComponent: + retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } + + break; + + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; + break; + + default: + throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); + } + + if (retryCache !== null) { + // The wakeable resolved, so we no longer need to memoize, because it will + // never be thrown again. + retryCache.delete(wakeable); + } + + retryTimedOutBoundary(boundaryFiber, retryLane); + } // Computes the next Just Noticeable Difference (JND) boundary. + // The theory is that a person can't tell the difference between small differences in time. + // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable + // difference in the experience. However, waiting for longer might mean that we can avoid + // showing an intermediate loading state. The longer we have already waited, the harder it + // is to tell small differences in time. Therefore, the longer we've already waited, + // the longer we can wait additionally. At some point we have to give up though. + // We pick a train model where the next boundary commits at a consistent schedule. + // These particular numbers are vague estimates. We expect to adjust them based on research. + + function jnd(timeElapsed) { + return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; + } + + function checkForNestedUpdates() { + if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { + nestedUpdateCount = 0; + rootWithNestedUpdates = null; + throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); + } + + { + if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = null; + + error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); + } + } + } + + function flushRenderPhaseStrictModeWarningsInDEV() { + { + ReactStrictModeWarnings.flushLegacyContextWarning(); + + { + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); + } + } + } + + function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { + { + // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects + // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. + // Maybe not a big deal since this is DEV only behavior. + setCurrentFiber(fiber); + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); + + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); + } + + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); + + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); + } + + resetCurrentFiber(); + } + } + + function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + var current = firstChild; + var subtreeRoot = null; + + while (current !== null) { + var primarySubtreeFlag = current.subtreeFlags & fiberFlags; + + if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { + current = current.child; + } else { + if ((current.flags & fiberFlags) !== NoFlags) { + invokeEffectFn(current); + } + + if (current.sibling !== null) { + current = current.sibling; + } else { + current = subtreeRoot = current.return; + } + } + } + } + } + + var didWarnStateUpdateForNotYetMountedComponent = null; + function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { + { + if ((executionContext & RenderContext) !== NoContext) { + // We let the other warning about render phase updates deal with this one. + return; + } + + if (!(fiber.mode & ConcurrentMode)) { + return; + } + + var tag = fiber.tag; + + if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { + // Only warn for user-defined components, not internal ones like Suspense. + return; + } // We show the whole stack but dedupe on the top component's name because + // the problematic code almost always lies inside that component. + + + var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; + + if (didWarnStateUpdateForNotYetMountedComponent !== null) { + if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { + return; + } + + didWarnStateUpdateForNotYetMountedComponent.add(componentName); + } else { + didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); + } + + var previousFiber = current; + + try { + setCurrentFiber(fiber); + + error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } + var beginWork$1; + + { + var dummyFiber = null; + + beginWork$1 = function (current, unitOfWork, lanes) { + // If a component throws an error, we replay it again in a synchronously + // dispatched event, so that the debugger will treat it as an uncaught + // error See ReactErrorUtils for more information. + // Before entering the begin phase, copy the work-in-progress onto a dummy + // fiber. If beginWork throws, we'll use this to reset the state. + var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); + + try { + return beginWork(current, unitOfWork, lanes); + } catch (originalError) { + if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { + // Don't replay promises. + // Don't replay errors if we are hydrating and have already suspended or handled an error + throw originalError; + } // Keep this code in sync with handleError; any changes here must have + // corresponding changes there. + + + resetContextDependencies(); + resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. + // Unwind the failed stack frame + + unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. + + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); + + if ( unitOfWork.mode & ProfileMode) { + // Reset the profiler timer. + startProfilerTimer(unitOfWork); + } // Run beginWork again. + + + invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); + + if (hasCaughtError()) { + var replayError = clearCaughtError(); + + if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { + // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. + originalError._suppressLogging = true; + } + } // We always throw the original error in case the second render pass is not idempotent. + // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. + + + throw originalError; + } + }; + } + + var didWarnAboutUpdateInRender = false; + var didWarnAboutUpdateInRenderForAnotherComponent; + + { + didWarnAboutUpdateInRenderForAnotherComponent = new Set(); + } + + function warnAboutRenderPhaseUpdatesInDEV(fiber) { + { + if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. + + var dedupeKey = renderingComponentName; + + if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { + didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); + var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; + + error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); + } + + break; + } + + case ClassComponent: + { + if (!didWarnAboutUpdateInRender) { + error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); + + didWarnAboutUpdateInRender = true; + } + + break; + } + } + } + } + } + + function restorePendingUpdaters(root, lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + memoizedUpdaters.forEach(function (schedulingFiber) { + addFiberToLanesMap(root, schedulingFiber, lanes); + }); // This function intentionally does not clear memoized updaters. + // Those may still be relevant to the current commit + // and a future one (e.g. Suspense). + } + } + } + var fakeActCallbackNode = {}; + + function scheduleCallback$1(priorityLevel, callback) { + { + // If we're currently inside an `act` scope, bypass Scheduler and push to + // the `act` queue instead. + var actQueue = ReactCurrentActQueue$1.current; + + if (actQueue !== null) { + actQueue.push(callback); + return fakeActCallbackNode; + } else { + return scheduleCallback(priorityLevel, callback); + } + } + } + + function cancelCallback$1(callbackNode) { + if ( callbackNode === fakeActCallbackNode) { + return; + } // In production, always call Scheduler. This function will be stripped out. + + + return cancelCallback(callbackNode); + } + + function shouldForceFlushFallbacksInDEV() { + // Never force flush in production. This function should get stripped out. + return ReactCurrentActQueue$1.current !== null; + } + + function warnIfUpdatesNotWrappedWithActDEV(fiber) { + { + if (fiber.mode & ConcurrentMode) { + if (!isConcurrentActEnvironment()) { + // Not in an act environment. No need to warn. + return; + } + } else { + // Legacy mode has additional cases where we suppress a warning. + if (!isLegacyActEnvironment()) { + // Not in an act environment. No need to warn. + return; + } + + if (executionContext !== NoContext) { + // Legacy mode doesn't warn if the update is batched, i.e. + // batchedUpdates or flushSync. + return; + } + + if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { + // For backwards compatibility with pre-hooks code, legacy mode only + // warns for updates that originate from a hook. + return; + } + } + + if (ReactCurrentActQueue$1.current === null) { + var previousFiber = current; + + try { + setCurrentFiber(fiber); + + error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } + } + + function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { + { + if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { + error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); + } + } + } + + function setIsRunningInsertionEffect(isRunning) { + { + isRunningInsertionEffect = isRunning; + } + } + + /* eslint-disable react-internal/prod-error-codes */ + var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. + + var failedBoundaries = null; + var setRefreshHandler = function (handler) { + { + resolveFamily = handler; + } + }; + function resolveFunctionForHotReloading(type) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return type; + } + + var family = resolveFamily(type); + + if (family === undefined) { + return type; + } // Use the latest known implementation. + + + return family.current; + } + } + function resolveClassForHotReloading(type) { + // No implementation differences. + return resolveFunctionForHotReloading(type); + } + function resolveForwardRefForHotReloading(type) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return type; + } + + var family = resolveFamily(type); + + if (family === undefined) { + // Check if we're dealing with a real forwardRef. Don't want to crash early. + if (type !== null && type !== undefined && typeof type.render === 'function') { + // ForwardRef is special because its resolved .type is an object, + // but it's possible that we only have its inner render function in the map. + // If that inner render function is different, we'll build a new forwardRef type. + var currentRender = resolveFunctionForHotReloading(type.render); + + if (type.render !== currentRender) { + var syntheticType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: currentRender + }; + + if (type.displayName !== undefined) { + syntheticType.displayName = type.displayName; + } + + return syntheticType; + } + } + + return type; + } // Use the latest known implementation. + + + return family.current; + } + } + function isCompatibleFamilyForHotReloading(fiber, element) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return false; + } + + var prevType = fiber.elementType; + var nextType = element.type; // If we got here, we know types aren't === equal. + + var needsCompareFamilies = false; + var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; + + switch (fiber.tag) { + case ClassComponent: + { + if (typeof nextType === 'function') { + needsCompareFamilies = true; + } + + break; + } + + case FunctionComponent: + { + if (typeof nextType === 'function') { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + // We don't know the inner type yet. + // We're going to assume that the lazy inner type is stable, + // and so it is sufficient to avoid reconciling it away. + // We're not going to unwrap or actually use the new lazy type. + needsCompareFamilies = true; + } + + break; + } + + case ForwardRef: + { + if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } + + break; + } + + case MemoComponent: + case SimpleMemoComponent: + { + if ($$typeofNextType === REACT_MEMO_TYPE) { + // TODO: if it was but can no longer be simple, + // we shouldn't set this. + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } + + break; + } + + default: + return false; + } // Check if both types have a family and it's the same one. + + + if (needsCompareFamilies) { + // Note: memo() and forwardRef() we'll compare outer rather than inner type. + // This means both of them need to be registered to preserve state. + // If we unwrapped and compared the inner types for wrappers instead, + // then we would risk falsely saying two separate memo(Foo) + // calls are equivalent because they wrap the same Foo function. + var prevFamily = resolveFamily(prevType); + + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { + return true; + } + } + + return false; + } + } + function markFailedErrorBoundaryForHotReloading(fiber) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return; + } + + if (typeof WeakSet !== 'function') { + return; + } + + if (failedBoundaries === null) { + failedBoundaries = new WeakSet(); + } + + failedBoundaries.add(fiber); + } + } + var scheduleRefresh = function (root, update) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return; + } + + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; + flushPassiveEffects(); + flushSync(function () { + scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); + }); + } + }; + var scheduleRoot = function (root, element) { + { + if (root.context !== emptyContextObject) { + // Super edge case: root has a legacy _renderSubtree context + // but we don't know the parentComponent so we can't pass it. + // Just ignore. We'll delete this with _renderSubtree code path later. + return; + } + + flushPassiveEffects(); + flushSync(function () { + updateContainer(element, root, null, null); + }); + } + }; + + function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { + { + var alternate = fiber.alternate, + child = fiber.child, + sibling = fiber.sibling, + tag = fiber.tag, + type = fiber.type; + var candidateType = null; + + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; + + case ForwardRef: + candidateType = type.render; + break; + } + + if (resolveFamily === null) { + throw new Error('Expected resolveFamily to be set during hot reload.'); + } + + var needsRender = false; + var needsRemount = false; + + if (candidateType !== null) { + var family = resolveFamily(candidateType); + + if (family !== undefined) { + if (staleFamilies.has(family)) { + needsRemount = true; + } else if (updatedFamilies.has(family)) { + if (tag === ClassComponent) { + needsRemount = true; + } else { + needsRender = true; + } + } + } + } + + if (failedBoundaries !== null) { + if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { + needsRemount = true; + } + } + + if (needsRemount) { + fiber._debugNeedsRemount = true; + } + + if (needsRemount || needsRender) { + var _root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (_root !== null) { + scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp); + } + } + + if (child !== null && !needsRemount) { + scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); + } + + if (sibling !== null) { + scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); + } + } + } + + var findHostInstancesForRefresh = function (root, families) { + { + var hostInstances = new Set(); + var types = new Set(families.map(function (family) { + return family.current; + })); + findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); + return hostInstances; + } + }; + + function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { + { + var child = fiber.child, + sibling = fiber.sibling, + tag = fiber.tag, + type = fiber.type; + var candidateType = null; + + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; + + case ForwardRef: + candidateType = type.render; + break; + } + + var didMatch = false; + + if (candidateType !== null) { + if (types.has(candidateType)) { + didMatch = true; + } + } + + if (didMatch) { + // We have a match. This only drills down to the closest host components. + // There's no need to search deeper because for the purpose of giving + // visual feedback, "flashing" outermost parent rectangles is sufficient. + findHostInstancesForFiberShallowly(fiber, hostInstances); + } else { + // If there's no match, maybe there will be one further down in the child tree. + if (child !== null) { + findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); + } + } + + if (sibling !== null) { + findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); + } + } + } + + function findHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); + + if (foundHostInstances) { + return; + } // If we didn't find any host children, fallback to closest host parent. + + + var node = fiber; + + while (true) { + switch (node.tag) { + case HostComponent: + hostInstances.add(node.stateNode); + return; + + case HostPortal: + hostInstances.add(node.stateNode.containerInfo); + return; + + case HostRoot: + hostInstances.add(node.stateNode.containerInfo); + return; + } + + if (node.return === null) { + throw new Error('Expected to reach root first.'); + } + + node = node.return; + } + } + } + + function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var node = fiber; + var foundHostInstances = false; + + while (true) { + if (node.tag === HostComponent) { + // We got a match. + foundHostInstances = true; + hostInstances.add(node.stateNode); // There may still be more, so keep searching. + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + + if (node === fiber) { + return foundHostInstances; + } + + while (node.sibling === null) { + if (node.return === null || node.return === fiber) { + return foundHostInstances; + } + + node = node.return; + } + + node.sibling.return = node.return; + node = node.sibling; + } + } + + return false; + } + + var hasBadMapPolyfill; + + { + hasBadMapPolyfill = false; + + try { + var nonExtensibleObject = Object.preventExtensions({}); + /* eslint-disable no-new */ + + new Map([[nonExtensibleObject, null]]); + new Set([nonExtensibleObject]); + /* eslint-enable no-new */ + } catch (e) { + // TODO: Consider warning about bad polyfills + hasBadMapPolyfill = true; + } + } + + function FiberNode(tag, pendingProps, key, mode) { + // Instance + this.tag = tag; + this.key = key; + this.elementType = null; + this.type = null; + this.stateNode = null; // Fiber + + this.return = null; + this.child = null; + this.sibling = null; + this.index = 0; + this.ref = null; + this.pendingProps = pendingProps; + this.memoizedProps = null; + this.updateQueue = null; + this.memoizedState = null; + this.dependencies = null; + this.mode = mode; // Effects + + this.flags = NoFlags; + this.subtreeFlags = NoFlags; + this.deletions = null; + this.lanes = NoLanes; + this.childLanes = NoLanes; + this.alternate = null; + + { + // Note: The following is done to avoid a v8 performance cliff. + // + // Initializing the fields below to smis and later updating them with + // double values will cause Fibers to end up having separate shapes. + // This behavior/bug has something to do with Object.preventExtension(). + // Fortunately this only impacts DEV builds. + // Unfortunately it makes React unusably slow for some applications. + // To work around this, initialize the fields below with doubles. + // + // Learn more about this here: + // https://github.com/facebook/react/issues/14365 + // https://bugs.chromium.org/p/v8/issues/detail?id=8538 + this.actualDuration = Number.NaN; + this.actualStartTime = Number.NaN; + this.selfBaseDuration = Number.NaN; + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. + // This won't trigger the performance cliff mentioned above, + // and it simplifies other profiler code (including DevTools). + + this.actualDuration = 0; + this.actualStartTime = -1; + this.selfBaseDuration = 0; + this.treeBaseDuration = 0; + } + + { + // This isn't directly used but is handy for debugging internals: + this._debugSource = null; + this._debugOwner = null; + this._debugNeedsRemount = false; + this._debugHookTypes = null; + + if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { + Object.preventExtensions(this); + } + } + } // This is a constructor function, rather than a POJO constructor, still + // please ensure we do the following: + // 1) Nobody should add any instance methods on this. Instance methods can be + // more difficult to predict when they get optimized and they are almost + // never inlined properly in static compilers. + // 2) Nobody should rely on `instanceof Fiber` for type testing. We should + // always know when it is a fiber. + // 3) We might want to experiment with using numeric keys since they are easier + // to optimize in a non-JIT environment. + // 4) We can easily go from a constructor to a createFiber object literal if that + // is faster. + // 5) It should be easy to port this to a C struct and keep a C implementation + // compatible. + + + var createFiber = function (tag, pendingProps, key, mode) { + // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors + return new FiberNode(tag, pendingProps, key, mode); + }; + + function shouldConstruct$1(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + + function isSimpleFunctionComponent(type) { + return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; + } + function resolveLazyComponentTag(Component) { + if (typeof Component === 'function') { + return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; + } else if (Component !== undefined && Component !== null) { + var $$typeof = Component.$$typeof; + + if ($$typeof === REACT_FORWARD_REF_TYPE) { + return ForwardRef; + } + + if ($$typeof === REACT_MEMO_TYPE) { + return MemoComponent; + } + } + + return IndeterminateComponent; + } // This is used to create an alternate fiber to do work on. + + function createWorkInProgress(current, pendingProps) { + var workInProgress = current.alternate; + + if (workInProgress === null) { + // We use a double buffering pooling technique because we know that we'll + // only ever need at most two versions of a tree. We pool the "other" unused + // node that we're free to reuse. This is lazily created to avoid allocating + // extra objects for things that are never updated. It also allow us to + // reclaim the extra memory if needed. + workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); + workInProgress.elementType = current.elementType; + workInProgress.type = current.type; + workInProgress.stateNode = current.stateNode; + + { + // DEV-only fields + workInProgress._debugSource = current._debugSource; + workInProgress._debugOwner = current._debugOwner; + workInProgress._debugHookTypes = current._debugHookTypes; + } + + workInProgress.alternate = current; + current.alternate = workInProgress; + } else { + workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. + + workInProgress.type = current.type; // We already have an alternate. + // Reset the effect tag. + + workInProgress.flags = NoFlags; // The effects are no longer valid. + + workInProgress.subtreeFlags = NoFlags; + workInProgress.deletions = null; + + { + // We intentionally reset, rather than copy, actualDuration & actualStartTime. + // This prevents time from endlessly accumulating in new commits. + // This has the downside of resetting values for different priority renders, + // But works for yielding (the common case) and should support resuming. + workInProgress.actualDuration = 0; + workInProgress.actualStartTime = -1; + } + } // Reset all effects except static ones. + // Static effects are not specific to a render. + + + workInProgress.flags = current.flags & StaticMask; + workInProgress.childLanes = current.childLanes; + workInProgress.lanes = current.lanes; + workInProgress.child = current.child; + workInProgress.memoizedProps = current.memoizedProps; + workInProgress.memoizedState = current.memoizedState; + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so + // it cannot be shared with the current fiber. + + var currentDependencies = current.dependencies; + workInProgress.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; // These will be overridden during the parent's reconciliation + + workInProgress.sibling = current.sibling; + workInProgress.index = current.index; + workInProgress.ref = current.ref; + + { + workInProgress.selfBaseDuration = current.selfBaseDuration; + workInProgress.treeBaseDuration = current.treeBaseDuration; + } + + { + workInProgress._debugNeedsRemount = current._debugNeedsRemount; + + switch (workInProgress.tag) { + case IndeterminateComponent: + case FunctionComponent: + case SimpleMemoComponent: + workInProgress.type = resolveFunctionForHotReloading(current.type); + break; + + case ClassComponent: + workInProgress.type = resolveClassForHotReloading(current.type); + break; + + case ForwardRef: + workInProgress.type = resolveForwardRefForHotReloading(current.type); + break; + } + } + + return workInProgress; + } // Used to reuse a Fiber for a second pass. + + function resetWorkInProgress(workInProgress, renderLanes) { + // This resets the Fiber to what createFiber or createWorkInProgress would + // have set the values to before during the first pass. Ideally this wouldn't + // be necessary but unfortunately many code paths reads from the workInProgress + // when they should be reading from current and writing to workInProgress. + // We assume pendingProps, index, key, ref, return are still untouched to + // avoid doing another reconciliation. + // Reset the effect flags but keep any Placement tags, since that's something + // that child fiber is setting, not the reconciliation. + workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. + + var current = workInProgress.alternate; + + if (current === null) { + // Reset to createFiber's initial values. + workInProgress.childLanes = NoLanes; + workInProgress.lanes = renderLanes; + workInProgress.child = null; + workInProgress.subtreeFlags = NoFlags; + workInProgress.memoizedProps = null; + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; + workInProgress.dependencies = null; + workInProgress.stateNode = null; + + { + // Note: We don't reset the actualTime counts. It's useful to accumulate + // actual time across multiple render passes. + workInProgress.selfBaseDuration = 0; + workInProgress.treeBaseDuration = 0; + } + } else { + // Reset to the cloned values that createWorkInProgress would've. + workInProgress.childLanes = current.childLanes; + workInProgress.lanes = current.lanes; + workInProgress.child = current.child; + workInProgress.subtreeFlags = NoFlags; + workInProgress.deletions = null; + workInProgress.memoizedProps = current.memoizedProps; + workInProgress.memoizedState = current.memoizedState; + workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. + + workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so + // it cannot be shared with the current fiber. + + var currentDependencies = current.dependencies; + workInProgress.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; + + { + // Note: We don't reset the actualTime counts. It's useful to accumulate + // actual time across multiple render passes. + workInProgress.selfBaseDuration = current.selfBaseDuration; + workInProgress.treeBaseDuration = current.treeBaseDuration; + } + } + + return workInProgress; + } + function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { + var mode; + + if (tag === ConcurrentRoot) { + mode = ConcurrentMode; + + if (isStrictMode === true) { + mode |= StrictLegacyMode; + + { + mode |= StrictEffectsMode; + } + } + } else { + mode = NoMode; + } + + if ( isDevToolsPresent) { + // Always collect profile timings when DevTools are present. + // This enables DevTools to start capturing timing at any point– + // Without some nodes in the tree having empty base times. + mode |= ProfileMode; + } + + return createFiber(HostRoot, null, null, mode); + } + function createFiberFromTypeAndProps(type, // React$ElementType + key, pendingProps, owner, mode, lanes) { + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. + + var resolvedType = type; + + if (typeof type === 'function') { + if (shouldConstruct$1(type)) { + fiberTag = ClassComponent; + + { + resolvedType = resolveClassForHotReloading(resolvedType); + } + } else { + { + resolvedType = resolveFunctionForHotReloading(resolvedType); + } + } + } else if (typeof type === 'string') { + fiberTag = HostComponent; + } else { + getTag: switch (type) { + case REACT_FRAGMENT_TYPE: + return createFiberFromFragment(pendingProps.children, mode, lanes, key); + + case REACT_STRICT_MODE_TYPE: + fiberTag = Mode; + mode |= StrictLegacyMode; + + if ( (mode & ConcurrentMode) !== NoMode) { + // Strict effects should never run on legacy roots + mode |= StrictEffectsMode; + } + + break; + + case REACT_PROFILER_TYPE: + return createFiberFromProfiler(pendingProps, mode, lanes, key); + + case REACT_SUSPENSE_TYPE: + return createFiberFromSuspense(pendingProps, mode, lanes, key); + + case REACT_SUSPENSE_LIST_TYPE: + return createFiberFromSuspenseList(pendingProps, mode, lanes, key); + + case REACT_OFFSCREEN_TYPE: + return createFiberFromOffscreen(pendingProps, mode, lanes, key); + + case REACT_LEGACY_HIDDEN_TYPE: + + // eslint-disable-next-line no-fallthrough + + case REACT_SCOPE_TYPE: + + // eslint-disable-next-line no-fallthrough + + case REACT_CACHE_TYPE: + + // eslint-disable-next-line no-fallthrough + + case REACT_TRACING_MARKER_TYPE: + + // eslint-disable-next-line no-fallthrough + + case REACT_DEBUG_TRACING_MODE_TYPE: + + // eslint-disable-next-line no-fallthrough + + default: + { + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: + fiberTag = ContextProvider; + break getTag; + + case REACT_CONTEXT_TYPE: + // This is a consumer + fiberTag = ContextConsumer; + break getTag; + + case REACT_FORWARD_REF_TYPE: + fiberTag = ForwardRef; + + { + resolvedType = resolveForwardRefForHotReloading(resolvedType); + } + + break getTag; + + case REACT_MEMO_TYPE: + fiberTag = MemoComponent; + break getTag; + + case REACT_LAZY_TYPE: + fiberTag = LazyComponent; + resolvedType = null; + break getTag; + } + } + + var info = ''; + + { + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; + } + + var ownerName = owner ? getComponentNameFromFiber(owner) : null; + + if (ownerName) { + info += '\n\nCheck the render method of `' + ownerName + '`.'; + } + } + + throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); + } + } + } + + var fiber = createFiber(fiberTag, pendingProps, key, mode); + fiber.elementType = type; + fiber.type = resolvedType; + fiber.lanes = lanes; + + { + fiber._debugOwner = owner; + } + + return fiber; + } + function createFiberFromElement(element, mode, lanes) { + var owner = null; + + { + owner = element._owner; + } + + var type = element.type; + var key = element.key; + var pendingProps = element.props; + var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); + + { + fiber._debugSource = element._source; + fiber._debugOwner = element._owner; + } + + return fiber; + } + function createFiberFromFragment(elements, mode, lanes, key) { + var fiber = createFiber(Fragment, elements, key, mode); + fiber.lanes = lanes; + return fiber; + } + + function createFiberFromProfiler(pendingProps, mode, lanes, key) { + { + if (typeof pendingProps.id !== 'string') { + error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); + } + } + + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); + fiber.elementType = REACT_PROFILER_TYPE; + fiber.lanes = lanes; + + { + fiber.stateNode = { + effectDuration: 0, + passiveEffectDuration: 0 + }; + } + + return fiber; + } + + function createFiberFromSuspense(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromOffscreen(pendingProps, mode, lanes, key) { + var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); + fiber.elementType = REACT_OFFSCREEN_TYPE; + fiber.lanes = lanes; + var primaryChildInstance = { + isHidden: false + }; + fiber.stateNode = primaryChildInstance; + return fiber; + } + function createFiberFromText(content, mode, lanes) { + var fiber = createFiber(HostText, content, null, mode); + fiber.lanes = lanes; + return fiber; + } + function createFiberFromHostInstanceForDeletion() { + var fiber = createFiber(HostComponent, null, null, NoMode); + fiber.elementType = 'DELETED'; + return fiber; + } + function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; + } + function createFiberFromPortal(portal, mode, lanes) { + var pendingProps = portal.children !== null ? portal.children : []; + var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); + fiber.lanes = lanes; + fiber.stateNode = { + containerInfo: portal.containerInfo, + pendingChildren: null, + // Used by persistent updates + implementation: portal.implementation + }; + return fiber; + } // Used for stashing WIP properties to replay failed work in DEV. + + function assignFiberPropertiesInDEV(target, source) { + if (target === null) { + // This Fiber's initial properties will always be overwritten. + // We only use a Fiber to ensure the same hidden class so DEV isn't slow. + target = createFiber(IndeterminateComponent, null, null, NoMode); + } // This is intentionally written as a list of all properties. + // We tried to use Object.assign() instead but this is called in + // the hottest path, and Object.assign() was too slow: + // https://github.com/facebook/react/issues/12502 + // This code is DEV-only so size is not a concern. + + + target.tag = source.tag; + target.key = source.key; + target.elementType = source.elementType; + target.type = source.type; + target.stateNode = source.stateNode; + target.return = source.return; + target.child = source.child; + target.sibling = source.sibling; + target.index = source.index; + target.ref = source.ref; + target.pendingProps = source.pendingProps; + target.memoizedProps = source.memoizedProps; + target.updateQueue = source.updateQueue; + target.memoizedState = source.memoizedState; + target.dependencies = source.dependencies; + target.mode = source.mode; + target.flags = source.flags; + target.subtreeFlags = source.subtreeFlags; + target.deletions = source.deletions; + target.lanes = source.lanes; + target.childLanes = source.childLanes; + target.alternate = source.alternate; + + { + target.actualDuration = source.actualDuration; + target.actualStartTime = source.actualStartTime; + target.selfBaseDuration = source.selfBaseDuration; + target.treeBaseDuration = source.treeBaseDuration; + } + + target._debugSource = source._debugSource; + target._debugOwner = source._debugOwner; + target._debugNeedsRemount = source._debugNeedsRemount; + target._debugHookTypes = source._debugHookTypes; + return target; + } + + function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { + this.tag = tag; + this.containerInfo = containerInfo; + this.pendingChildren = null; + this.current = null; + this.pingCache = null; + this.finishedWork = null; + this.timeoutHandle = noTimeout; + this.context = null; + this.pendingContext = null; + this.callbackNode = null; + this.callbackPriority = NoLane; + this.eventTimes = createLaneMap(NoLanes); + this.expirationTimes = createLaneMap(NoTimestamp); + this.pendingLanes = NoLanes; + this.suspendedLanes = NoLanes; + this.pingedLanes = NoLanes; + this.expiredLanes = NoLanes; + this.mutableReadLanes = NoLanes; + this.finishedLanes = NoLanes; + this.entangledLanes = NoLanes; + this.entanglements = createLaneMap(NoLanes); + this.identifierPrefix = identifierPrefix; + this.onRecoverableError = onRecoverableError; + + { + this.mutableSourceEagerHydrationData = null; + } + + { + this.effectDuration = 0; + this.passiveEffectDuration = 0; + } + + { + this.memoizedUpdaters = new Set(); + var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; + + for (var _i = 0; _i < TotalLanes; _i++) { + pendingUpdatersLaneMap.push(new Set()); + } + } + + { + switch (tag) { + case ConcurrentRoot: + this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; + break; + + case LegacyRoot: + this._debugRootType = hydrate ? 'hydrate()' : 'render()'; + break; + } + } + } + + function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the + // host config, but because they are passed in at runtime, we have to thread + // them through the root constructor. Perhaps we should put them all into a + // single type, like a DynamicHostConfig that is defined by the renderer. + identifierPrefix, onRecoverableError, transitionCallbacks) { + var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); + // stateNode is any. + + + var uninitializedFiber = createHostRootFiber(tag, isStrictMode); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; + + { + var _initialState = { + element: initialChildren, + isDehydrated: hydrate, + cache: null, + // not enabled yet + transitions: null, + pendingSuspenseBoundaries: null + }; + uninitializedFiber.memoizedState = _initialState; + } + + initializeUpdateQueue(uninitializedFiber); + return root; + } + + var ReactVersion = '18.3.1'; + + function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. + implementation) { + var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + + { + checkKeyStringCoercion(key); + } + + return { + // This tag allow us to uniquely identify this as a React Portal + $$typeof: REACT_PORTAL_TYPE, + key: key == null ? null : '' + key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; + } + + var didWarnAboutNestedUpdates; + var didWarnAboutFindNodeInStrictMode; + + { + didWarnAboutNestedUpdates = false; + didWarnAboutFindNodeInStrictMode = {}; + } + + function getContextForSubtree(parentComponent) { + if (!parentComponent) { + return emptyContextObject; + } + + var fiber = get(parentComponent); + var parentContext = findCurrentUnmaskedContext(fiber); + + if (fiber.tag === ClassComponent) { + var Component = fiber.type; + + if (isContextProvider(Component)) { + return processChildContext(fiber, Component, parentContext); + } + } + + return parentContext; + } + + function findHostInstanceWithWarning(component, methodName) { + { + var fiber = get(component); + + if (fiber === undefined) { + if (typeof component.render === 'function') { + throw new Error('Unable to find node on an unmounted component.'); + } else { + var keys = Object.keys(component).join(','); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } + + var hostFiber = findCurrentHostFiber(fiber); + + if (hostFiber === null) { + return null; + } + + if (hostFiber.mode & StrictLegacyMode) { + var componentName = getComponentNameFromFiber(fiber) || 'Component'; + + if (!didWarnAboutFindNodeInStrictMode[componentName]) { + didWarnAboutFindNodeInStrictMode[componentName] = true; + var previousFiber = current; + + try { + setCurrentFiber(hostFiber); + + if (fiber.mode & StrictLegacyMode) { + error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); + } else { + error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); + } + } finally { + // Ideally this should reset to previous but this shouldn't be called in + // render and there's another warning for that anyway. + if (previousFiber) { + setCurrentFiber(previousFiber); + } else { + resetCurrentFiber(); + } + } + } + } + + return hostFiber.stateNode; + } + } + + function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = false; + var initialChildren = null; + return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + } + function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. + callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = true; + var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor + + root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from + // a regular update because the initial render must match was was rendered + // on the server. + // NOTE: This update intentionally doesn't have a payload. We're only using + // the update to schedule work on the root fiber (and, for legacy roots, to + // enqueue the callback if one is provided). + + var current = root.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current); + var update = createUpdate(eventTime, lane); + update.callback = callback !== undefined && callback !== null ? callback : null; + enqueueUpdate(current, update, lane); + scheduleInitialHydrationOnRoot(root, lane, eventTime); + return root; + } + function updateContainer(element, container, parentComponent, callback) { + { + onScheduleRoot(container, element); + } + + var current$1 = container.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current$1); + + { + markRenderScheduled(lane); + } + + var context = getContextForSubtree(parentComponent); + + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } + + { + if (isRendering && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; + + error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); + } + } + + var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property + // being called "element". + + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; + + if (callback !== null) { + { + if (typeof callback !== 'function') { + error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); + } + } + + update.callback = callback; + } + + var root = enqueueUpdate(current$1, update, lane); + + if (root !== null) { + scheduleUpdateOnFiber(root, current$1, lane, eventTime); + entangleTransitions(root, current$1, lane); + } + + return lane; + } + function getPublicRootInstance(container) { + var containerFiber = container.current; + + if (!containerFiber.child) { + return null; + } + + switch (containerFiber.child.tag) { + case HostComponent: + return getPublicInstance(containerFiber.child.stateNode); + + default: + return containerFiber.child.stateNode; + } + } + function attemptSynchronousHydration$1(fiber) { + switch (fiber.tag) { + case HostRoot: + { + var root = fiber.stateNode; + + if (isRootDehydrated(root)) { + // Flush the first scheduled "update". + var lanes = getHighestPriorityPendingLanes(root); + flushRoot(root, lanes); + } + + break; + } + + case SuspenseComponent: + { + flushSync(function () { + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime); + } + }); // If we're still blocked after this, we need to increase + // the priority of any promises resolving within this + // boundary so that they next attempt also has higher pri. + + var retryLane = SyncLane; + markRetryLaneIfNotHydrated(fiber, retryLane); + break; + } + } + } + + function markRetryLaneImpl(fiber, retryLane) { + var suspenseState = fiber.memoizedState; + + if (suspenseState !== null && suspenseState.dehydrated !== null) { + suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); + } + } // Increases the priority of thenables when they resolve within this boundary. + + + function markRetryLaneIfNotHydrated(fiber, retryLane) { + markRetryLaneImpl(fiber, retryLane); + var alternate = fiber.alternate; + + if (alternate) { + markRetryLaneImpl(alternate, retryLane); + } + } + function attemptContinuousHydration$1(fiber) { + if (fiber.tag !== SuspenseComponent) { + // We ignore HostRoots here because we can't increase + // their priority and they should not suspend on I/O, + // since you have to wrap anything that might suspend in + // Suspense. + return; + } + + var lane = SelectiveHydrationLane; + var root = enqueueConcurrentRenderForLane(fiber, lane); + + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + } + + markRetryLaneIfNotHydrated(fiber, lane); + } + function attemptHydrationAtCurrentPriority$1(fiber) { + if (fiber.tag !== SuspenseComponent) { + // We ignore HostRoots here because we can't increase + // their priority other than synchronously flush it. + return; + } + + var lane = requestUpdateLane(fiber); + var root = enqueueConcurrentRenderForLane(fiber, lane); + + if (root !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root, fiber, lane, eventTime); + } + + markRetryLaneIfNotHydrated(fiber, lane); + } + function findHostInstanceWithNoPortals(fiber) { + var hostFiber = findCurrentHostFiberWithNoPortals(fiber); + + if (hostFiber === null) { + return null; + } + + return hostFiber.stateNode; + } + + var shouldErrorImpl = function (fiber) { + return null; + }; + + function shouldError(fiber) { + return shouldErrorImpl(fiber); + } + + var shouldSuspendImpl = function (fiber) { + return false; + }; + + function shouldSuspend(fiber) { + return shouldSuspendImpl(fiber); + } + var overrideHookState = null; + var overrideHookStateDeletePath = null; + var overrideHookStateRenamePath = null; + var overrideProps = null; + var overridePropsDeletePath = null; + var overridePropsRenamePath = null; + var scheduleUpdate = null; + var setErrorHandler = null; + var setSuspenseHandler = null; + + { + var copyWithDeleteImpl = function (obj, path, index) { + var key = path[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + + if (index + 1 === path.length) { + if (isArray(updated)) { + updated.splice(key, 1); + } else { + delete updated[key]; + } + + return updated; + } // $FlowFixMe number or string is fine here + + + updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); + return updated; + }; + + var copyWithDelete = function (obj, path) { + return copyWithDeleteImpl(obj, path, 0); + }; + + var copyWithRenameImpl = function (obj, oldPath, newPath, index) { + var oldKey = oldPath[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + + if (index + 1 === oldPath.length) { + var newKey = newPath[index]; // $FlowFixMe number or string is fine here + + updated[newKey] = updated[oldKey]; + + if (isArray(updated)) { + updated.splice(oldKey, 1); + } else { + delete updated[oldKey]; + } + } else { + // $FlowFixMe number or string is fine here + updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here + obj[oldKey], oldPath, newPath, index + 1); + } + + return updated; + }; + + var copyWithRename = function (obj, oldPath, newPath) { + if (oldPath.length !== newPath.length) { + warn('copyWithRename() expects paths of the same length'); + + return; + } else { + for (var i = 0; i < newPath.length - 1; i++) { + if (oldPath[i] !== newPath[i]) { + warn('copyWithRename() expects paths to be the same except for the deepest key'); + + return; + } + } + } + + return copyWithRenameImpl(obj, oldPath, newPath, 0); + }; + + var copyWithSetImpl = function (obj, path, index, value) { + if (index >= path.length) { + return value; + } + + var key = path[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here + + updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); + return updated; + }; + + var copyWithSet = function (obj, path, value) { + return copyWithSetImpl(obj, path, 0, value); + }; + + var findHook = function (fiber, id) { + // For now, the "id" of stateful hooks is just the stateful hook index. + // This may change in the future with e.g. nested hooks. + var currentHook = fiber.memoizedState; + + while (currentHook !== null && id > 0) { + currentHook = currentHook.next; + id--; + } + + return currentHook; + }; // Support DevTools editable values for useState and useReducer. + + + overrideHookState = function (fiber, id, path, value) { + var hook = findHook(fiber, id); + + if (hook !== null) { + var newState = copyWithSet(hook.memoizedState, path, value); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. + + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + }; + + overrideHookStateDeletePath = function (fiber, id, path) { + var hook = findHook(fiber, id); + + if (hook !== null) { + var newState = copyWithDelete(hook.memoizedState, path); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. + + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + }; + + overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { + var hook = findHook(fiber, id); + + if (hook !== null) { + var newState = copyWithRename(hook.memoizedState, oldPath, newPath); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. + + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + } + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. + + + overrideProps = function (fiber, path, value) { + fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + + overridePropsDeletePath = function (fiber, path) { + fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); + + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + + overridePropsRenamePath = function (fiber, oldPath, newPath) { + fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); + + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + + scheduleUpdate = function (fiber) { + var root = enqueueConcurrentRenderForLane(fiber, SyncLane); + + if (root !== null) { + scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); + } + }; + + setErrorHandler = function (newShouldErrorImpl) { + shouldErrorImpl = newShouldErrorImpl; + }; + + setSuspenseHandler = function (newShouldSuspendImpl) { + shouldSuspendImpl = newShouldSuspendImpl; + }; + } + + function findHostInstanceByFiber(fiber) { + var hostFiber = findCurrentHostFiber(fiber); + + if (hostFiber === null) { + return null; + } + + return hostFiber.stateNode; + } + + function emptyFindFiberByHostInstance(instance) { + return null; + } + + function getCurrentFiberForDevTools() { + return current; + } + + function injectIntoDevTools(devToolsConfig) { + var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + return injectInternals({ + bundleType: devToolsConfig.bundleType, + version: devToolsConfig.version, + rendererPackageName: devToolsConfig.rendererPackageName, + rendererConfig: devToolsConfig.rendererConfig, + overrideHookState: overrideHookState, + overrideHookStateDeletePath: overrideHookStateDeletePath, + overrideHookStateRenamePath: overrideHookStateRenamePath, + overrideProps: overrideProps, + overridePropsDeletePath: overridePropsDeletePath, + overridePropsRenamePath: overridePropsRenamePath, + setErrorHandler: setErrorHandler, + setSuspenseHandler: setSuspenseHandler, + scheduleUpdate: scheduleUpdate, + currentDispatcherRef: ReactCurrentDispatcher, + findHostInstanceByFiber: findHostInstanceByFiber, + findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, + // React Refresh + findHostInstancesForRefresh: findHostInstancesForRefresh , + scheduleRefresh: scheduleRefresh , + scheduleRoot: scheduleRoot , + setRefreshHandler: setRefreshHandler , + // Enables DevTools to append owner stacks to error messages in DEV mode. + getCurrentFiber: getCurrentFiberForDevTools , + // Enables DevTools to detect reconciler version rather than renderer version + // which may not match for third party renderers. + reconcilerVersion: ReactVersion + }); + } + + /* global reportError */ + + var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, + // emulating an uncaught JavaScript error. + reportError : function (error) { + // In older browsers and test environments, fallback to console.error. + // eslint-disable-next-line react-internal/no-production-logging + console['error'](error); + }; + + function ReactDOMRoot(internalRoot) { + this._internalRoot = internalRoot; + } + + ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) { + var root = this._internalRoot; + + if (root === null) { + throw new Error('Cannot update an unmounted root.'); + } + + { + if (typeof arguments[1] === 'function') { + error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().'); + } else if (isValidContainer(arguments[1])) { + error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root."); + } else if (typeof arguments[1] !== 'undefined') { + error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.'); + } + + var container = root.containerInfo; + + if (container.nodeType !== COMMENT_NODE) { + var hostInstance = findHostInstanceWithNoPortals(root.current); + + if (hostInstance) { + if (hostInstance.parentNode !== container) { + error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container."); + } + } + } + } + + updateContainer(children, root, null, null); + }; + + ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () { + { + if (typeof arguments[0] === 'function') { + error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().'); + } + } + + var root = this._internalRoot; + + if (root !== null) { + this._internalRoot = null; + var container = root.containerInfo; + + { + if (isAlreadyRendering()) { + error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.'); + } + } + + flushSync(function () { + updateContainer(null, root, null, null); + }); + unmarkContainerAsRoot(container); + } + }; + + function createRoot(container, options) { + if (!isValidContainer(container)) { + throw new Error('createRoot(...): Target container is not a DOM element.'); + } + + warnIfReactDOMContainerInDEV(container); + var isStrictMode = false; + var concurrentUpdatesByDefaultOverride = false; + var identifierPrefix = ''; + var onRecoverableError = defaultOnRecoverableError; + var transitionCallbacks = null; + + if (options !== null && options !== undefined) { + { + if (options.hydrate) { + warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, ) instead.'); + } else { + if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) { + error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + ' let root = createRoot(domContainer);\n' + ' root.render();'); + } + } + } + + if (options.unstable_strictMode === true) { + isStrictMode = true; + } + + if (options.identifierPrefix !== undefined) { + identifierPrefix = options.identifierPrefix; + } + + if (options.onRecoverableError !== undefined) { + onRecoverableError = options.onRecoverableError; + } + + if (options.transitionCallbacks !== undefined) { + transitionCallbacks = options.transitionCallbacks; + } + } + + var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + markContainerAsRoot(root.current, container); + var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; + listenToAllSupportedEvents(rootContainerElement); + return new ReactDOMRoot(root); + } + + function ReactDOMHydrationRoot(internalRoot) { + this._internalRoot = internalRoot; + } + + function scheduleHydration(target) { + if (target) { + queueExplicitHydrationTarget(target); + } + } + + ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration; + function hydrateRoot(container, initialChildren, options) { + if (!isValidContainer(container)) { + throw new Error('hydrateRoot(...): Target container is not a DOM element.'); + } + + warnIfReactDOMContainerInDEV(container); + + { + if (initialChildren === undefined) { + error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, )'); + } + } // For now we reuse the whole bag of options since they contain + // the hydration callbacks. + + + var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option + + var mutableSources = options != null && options.hydratedSources || null; + var isStrictMode = false; + var concurrentUpdatesByDefaultOverride = false; + var identifierPrefix = ''; + var onRecoverableError = defaultOnRecoverableError; + + if (options !== null && options !== undefined) { + if (options.unstable_strictMode === true) { + isStrictMode = true; + } + + if (options.identifierPrefix !== undefined) { + identifierPrefix = options.identifierPrefix; + } + + if (options.onRecoverableError !== undefined) { + onRecoverableError = options.onRecoverableError; + } + } + + var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway. + + listenToAllSupportedEvents(container); + + if (mutableSources) { + for (var i = 0; i < mutableSources.length; i++) { + var mutableSource = mutableSources[i]; + registerMutableSourceForHydration(root, mutableSource); + } + } + + return new ReactDOMHydrationRoot(root); + } + function isValidContainer(node) { + return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers )); + } // TODO: Remove this function which also includes comment nodes. + // We only use it in places that are currently more relaxed. + + function isValidContainerLegacy(node) { + return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); + } + + function warnIfReactDOMContainerInDEV(container) { + { + if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') { + error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.'); + } + + if (isContainerMarkedAsRoot(container)) { + if (container._reactRootContainer) { + error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.'); + } else { + error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.'); + } + } + } + } + + var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; + var topLevelUpdateWarnings; + + { + topLevelUpdateWarnings = function (container) { + if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { + var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current); + + if (hostInstance) { + if (hostInstance.parentNode !== container) { + error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.'); + } + } + } + + var isRootRenderedBySomeReact = !!container._reactRootContainer; + var rootEl = getReactRootElementInContainer(container); + var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl)); + + if (hasNonRootReactChild && !isRootRenderedBySomeReact) { + error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.'); + } + + if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') { + error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.'); + } + }; + } + + function getReactRootElementInContainer(container) { + if (!container) { + return null; + } + + if (container.nodeType === DOCUMENT_NODE) { + return container.documentElement; + } else { + return container.firstChild; + } + } + + function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the + // legacy API. + } + + function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) { + if (isHydrationContainer) { + if (typeof callback === 'function') { + var originalCallback = callback; + + callback = function () { + var instance = getPublicRootInstance(root); + originalCallback.call(instance); + }; + } + + var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks + false, // isStrictMode + false, // concurrentUpdatesByDefaultOverride, + '', // identifierPrefix + noopOnRecoverableError); + container._reactRootContainer = root; + markContainerAsRoot(root.current, container); + var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; + listenToAllSupportedEvents(rootContainerElement); + flushSync(); + return root; + } else { + // First clear any existing content. + var rootSibling; + + while (rootSibling = container.lastChild) { + container.removeChild(rootSibling); + } + + if (typeof callback === 'function') { + var _originalCallback = callback; + + callback = function () { + var instance = getPublicRootInstance(_root); + + _originalCallback.call(instance); + }; + } + + var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks + false, // isStrictMode + false, // concurrentUpdatesByDefaultOverride, + '', // identifierPrefix + noopOnRecoverableError); + + container._reactRootContainer = _root; + markContainerAsRoot(_root.current, container); + + var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; + + listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched. + + flushSync(function () { + updateContainer(initialChildren, _root, parentComponent, callback); + }); + return _root; + } + } + + function warnOnInvalidCallback$1(callback, callerName) { + { + if (callback !== null && typeof callback !== 'function') { + error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); + } + } + } + + function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) { + { + topLevelUpdateWarnings(container); + warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render'); + } + + var maybeRoot = container._reactRootContainer; + var root; + + if (!maybeRoot) { + // Initial mount + root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate); + } else { + root = maybeRoot; + + if (typeof callback === 'function') { + var originalCallback = callback; + + callback = function () { + var instance = getPublicRootInstance(root); + originalCallback.call(instance); + }; + } // Update + + + updateContainer(children, root, parentComponent, callback); + } + + return getPublicRootInstance(root); + } + + var didWarnAboutFindDOMNode = false; + function findDOMNode(componentOrElement) { + { + if (!didWarnAboutFindDOMNode) { + didWarnAboutFindDOMNode = true; + + error('findDOMNode is deprecated and will be removed in the next major ' + 'release. Instead, add a ref directly to the element you want ' + 'to reference. Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node'); + } + + var owner = ReactCurrentOwner$3.current; + + if (owner !== null && owner.stateNode !== null) { + var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender; + + if (!warnedAboutRefsInRender) { + error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component'); + } + + owner.stateNode._warnedAboutRefsInRender = true; + } + } + + if (componentOrElement == null) { + return null; + } + + if (componentOrElement.nodeType === ELEMENT_NODE) { + return componentOrElement; + } + + { + return findHostInstanceWithWarning(componentOrElement, 'findDOMNode'); + } + } + function hydrate(element, container, callback) { + { + error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot'); + } + + if (!isValidContainerLegacy(container)) { + throw new Error('Target container is not a DOM element.'); + } + + { + var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; + + if (isModernRoot) { + error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?'); + } + } // TODO: throw or warn if we couldn't hydrate? + + + return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); + } + function render(element, container, callback) { + { + error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot'); + } + + if (!isValidContainerLegacy(container)) { + throw new Error('Target container is not a DOM element.'); + } + + { + var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; + + if (isModernRoot) { + error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?'); + } + } + + return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); + } + function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { + { + error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot'); + } + + if (!isValidContainerLegacy(containerNode)) { + throw new Error('Target container is not a DOM element.'); + } + + if (parentComponent == null || !has(parentComponent)) { + throw new Error('parentComponent must be a valid React Component'); + } + + return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback); + } + var didWarnAboutUnmountComponentAtNode = false; + function unmountComponentAtNode(container) { + { + if (!didWarnAboutUnmountComponentAtNode) { + didWarnAboutUnmountComponentAtNode = true; + + error('unmountComponentAtNode is deprecated and will be removed in the ' + 'next major release. Switch to the createRoot API. Learn ' + 'more: https://reactjs.org/link/switch-to-createroot'); + } + } + + if (!isValidContainerLegacy(container)) { + throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.'); + } + + { + var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; + + if (isModernRoot) { + error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?'); + } + } + + if (container._reactRootContainer) { + { + var rootEl = getReactRootElementInContainer(container); + var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl); + + if (renderedByDifferentReact) { + error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.'); + } + } // Unmount should not be batched. + + + flushSync(function () { + legacyRenderSubtreeIntoContainer(null, null, container, false, function () { + // $FlowFixMe This should probably use `delete container._reactRootContainer` + container._reactRootContainer = null; + unmarkContainerAsRoot(container); + }); + }); // If you call unmountComponentAtNode twice in quick succession, you'll + // get `true` twice. That's probably fine? + + return true; + } else { + { + var _rootEl = getReactRootElementInContainer(container); + + var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node. + + var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer; + + if (hasNonRootReactChild) { + error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.'); + } + } + + return false; + } + } + + setAttemptSynchronousHydration(attemptSynchronousHydration$1); + setAttemptContinuousHydration(attemptContinuousHydration$1); + setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1); + setGetCurrentUpdatePriority(getCurrentUpdatePriority); + setAttemptHydrationAtPriority(runWithPriority); + + { + if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype + Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype + Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') { + error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills'); + } + } + + setRestoreImplementation(restoreControlledState$3); + setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync); + + function createPortal$1(children, container) { + var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + if (!isValidContainer(container)) { + throw new Error('Target container is not a DOM element.'); + } // TODO: pass ReactDOM portal implementation as third argument + // $FlowFixMe The Flow type is opaque but there's no way to actually create it. + + + return createPortal(children, container, null, key); + } + + function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { + return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback); + } + + var Internals = { + usingClientEntryPoint: false, + // Keep in sync with ReactTestUtils.js. + // This is an array for better minification. + Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1] + }; + + function createRoot$1(container, options) { + { + if (!Internals.usingClientEntryPoint && !true) { + error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".'); + } + } + + return createRoot(container, options); + } + + function hydrateRoot$1(container, initialChildren, options) { + { + if (!Internals.usingClientEntryPoint && !true) { + error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".'); + } + } + + return hydrateRoot(container, initialChildren, options); + } // Overload the definition to the two valid signatures. + // Warning, this opts-out of checking the function body. + + + // eslint-disable-next-line no-redeclare + function flushSync$1(fn) { + { + if (isAlreadyRendering()) { + error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.'); + } + } + + return flushSync(fn); + } + var foundDevTools = injectIntoDevTools({ + findFiberByHostInstance: getClosestInstanceFromNode, + bundleType: 1 , + version: ReactVersion, + rendererPackageName: 'react-dom' + }); + + { + if (!foundDevTools && canUseDOM && window.top === window.self) { + // If we're in Chrome or Firefox, provide a download link if not installed. + if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { + var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://. + + if (/^(https?|file):$/.test(protocol)) { + // eslint-disable-next-line react-internal/no-production-logging + console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold'); + } + } + } + } + + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals; + exports.createPortal = createPortal$1; + exports.createRoot = createRoot$1; + exports.findDOMNode = findDOMNode; + exports.flushSync = flushSync$1; + exports.hydrate = hydrate; + exports.hydrateRoot = hydrateRoot$1; + exports.render = render; + exports.unmountComponentAtNode = unmountComponentAtNode; + exports.unstable_batchedUpdates = batchedUpdates$1; + exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer; + exports.version = ReactVersion; + +}))); diff --git a/Project/Web/wwwroot/lib/js/react.development.js b/Project/Web/wwwroot/lib/js/react.development.js new file mode 100644 index 0000000..37b38b3 --- /dev/null +++ b/Project/Web/wwwroot/lib/js/react.development.js @@ -0,0 +1,3343 @@ +/** + * @license React + * react.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.React = {})); +}(this, (function (exports) { 'use strict'; + + var ReactVersion = '18.3.1'; + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; + } + + /** + * Keeps track of the current dispatcher. + */ + var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + + /** + * Keeps track of the current batch's configuration such as how long an update + * should suspend for if it needs to. + */ + var ReactCurrentBatchConfig = { + transition: null + }; + + var ReactCurrentActQueue = { + current: null, + // Used to reproduce behavior of `batchedUpdates` in legacy mode. + isBatchingLegacy: false, + didScheduleLegacyUpdate: false + }; + + /** + * Keeps track of the current owner. + * + * The current owner is the component who should own any components that are + * currently being constructed. + */ + var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } + } + + { + ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { + { + currentExtraStackFrame = stack; + } + }; // Stack implementation injected by the current renderer. + + + ReactDebugCurrentFrame.getCurrentStack = null; + + ReactDebugCurrentFrame.getStackAddendum = function () { + var stack = ''; // Add an extra top frame while an element is being validated + + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } // Delegate to the injected renderer-specific implementation + + + var impl = ReactDebugCurrentFrame.getCurrentStack; + + if (impl) { + stack += impl() || ''; + } + + return stack; + }; + } + + // ----------------------------------------------------------------------------- + + var enableScopeAPI = false; // Experimental Create Event Handle API. + var enableCacheElement = false; + var enableTransitionTracing = false; // No known bugs, but needs performance testing + + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + // stuff. Intended to enable React core members to more easily debug scheduling + // issues in DEV builds. + + var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + + var ReactSharedInternals = { + ReactCurrentDispatcher: ReactCurrentDispatcher, + ReactCurrentBatchConfig: ReactCurrentBatchConfig, + ReactCurrentOwner: ReactCurrentOwner + }; + + { + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; + } + + // by calls to these methods by a Babel plugin. + // + // In PROD (or in packages without access to React internals), + // they are left as they are instead. + + function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } + } + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } + } + + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + + var didWarnStateUpdateForUnmountedComponent = {}; + + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; + var warningKey = componentName + "." + callerName; + + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + + error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); + + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + } + /** + * This is the abstract API for an update queue. + */ + + + var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + return false; + }, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueForceUpdate: function (publicInstance, callback, callerName) { + warnNoop(publicInstance, 'forceUpdate'); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, 'replaceState'); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ + enqueueSetState: function (publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, 'setState'); + } + }; + + var assign = Object.assign; + + var emptyObject = {}; + + { + Object.freeze(emptyObject); + } + /** + * Base class helpers for the updating state of a component. + */ + + + function Component(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + + this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the + // renderer. + + this.updater = updater || ReactNoopUpdateQueue; + } + + Component.prototype.isReactComponent = {}; + /** + * Sets a subset of the state. Always use this to mutate + * state. You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * + * When a function is provided to setState, it will be called at some point in + * the future (not synchronously). It will be called with the up to date + * component arguments (state, props, context). These values can be different + * from this.* because your function may be called after receiveProps but before + * shouldComponentUpdate, and this new state, props, and context will not yet be + * assigned to this. + * + * @param {object|function} partialState Next partial state or function to + * produce next partial state to be merged with current state. + * @param {?function} callback Called after state is updated. + * @final + * @protected + */ + + Component.prototype.setState = function (partialState, callback) { + if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) { + throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.'); + } + + this.updater.enqueueSetState(this, partialState, callback, 'setState'); + }; + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {?function} callback Called after update is complete. + * @final + * @protected + */ + + + Component.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); + }; + /** + * Deprecated APIs. These APIs used to exist on classic React classes but since + * we would like to deprecate them, we're not going to move them over to this + * modern base class. Instead, we define a getter that warns if it's accessed. + */ + + + { + var deprecatedAPIs = { + isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], + replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] + }; + + var defineDeprecationWarning = function (methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function () { + warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); + + return undefined; + } + }); + }; + + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + } + + function ComponentDummy() {} + + ComponentDummy.prototype = Component.prototype; + /** + * Convenience component with default shallow equality check for sCU. + */ + + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. + + assign(pureComponentPrototype, Component.prototype); + pureComponentPrototype.isPureReactComponent = true; + + // an immutable object with a single mutable value + function createRef() { + var refObject = { + current: null + }; + + { + Object.seal(refObject); + } + + return refObject; + } + + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + + function isArray(a) { + return isArrayImpl(a); + } + + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. + + + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } + + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber + + + function getContextName(type) { + return type.displayName || 'Context'; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; + } + + var hasOwnProperty = Object.prototype.hasOwnProperty; + + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + + { + didWarnAboutStringRefs = {}; + } + + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.ref !== undefined; + } + + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.key !== undefined; + } + + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function () { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + } + }; + + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } + + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function () { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + } + }; + + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } + + function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + /** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ + + + var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + + return element; + }; + /** + * Create and return a new ReactElement of the given type. + * See https://reactjs.org/docs/react-api.html#createelement + */ + + function createElement(type, config, children) { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; + var self = null; + var source = null; + + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } + + self = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + + + var childrenLength = arguments.length - 2; + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + + props.children = childArray; + } // Resolve default props + + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + + { + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + /** + * Clone and return a new ReactElement using element as the starting point. + * See https://reactjs.org/docs/react-api.html#cloneelement + */ + + function cloneElement(element, config, children) { + if (element === null || element === undefined) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + + var propName; // Original props are copied + + var props = assign({}, element.props); // Reserved names are extracted + + var key = element.key; + var ref = element.ref; // Self is preserved since the owner is preserved. + + var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a + // transpiler, and the original source is probably a better indicator of the + // true owner. + + var source = element._source; // Owner will be preserved, unless ref is overridden + + var owner = element._owner; + + if (config != null) { + if (hasValidRef(config)) { + // Silently steal the ref from the parent. + ref = config.ref; + owner = ReactCurrentOwner.current; + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } // Remaining properties override existing props + + + var defaultProps; + + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === undefined && defaultProps !== undefined) { + // Resolve default props + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + + + var childrenLength = arguments.length - 2; + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + + props.children = childArray; + } + + return ReactElement(element.type, key, ref, self, source, owner, props); + } + /** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ + + function isValidElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + + var SEPARATOR = '.'; + var SUBSEPARATOR = ':'; + /** + * Escape and wrap key so it is safe to use as a reactid + * + * @param {string} key to be escaped. + * @return {string} the escaped key. + */ + + function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + '=': '=0', + ':': '=2' + }; + var escapedString = key.replace(escapeRegex, function (match) { + return escaperLookup[match]; + }); + return '$' + escapedString; + } + /** + * TODO: Test that a single child and an array with one item have the same key + * pattern. + */ + + + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, '$&/'); + } + /** + * Generate a key string that identifies a element within a set. + * + * @param {*} element A element that could contain a manual key. + * @param {number} index Index that is used if a manual key is not provided. + * @return {string} + */ + + + function getElementKey(element, index) { + // Do some typechecking here since we call this blindly. We want to ensure + // that we don't block potential future ES APIs. + if (typeof element === 'object' && element !== null && element.key != null) { + // Explicit key + { + checkKeyStringCoercion(element.key); + } + + return escape('' + element.key); + } // Implicit key determined by the index in the set + + + return index.toString(36); + } + + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + + if (type === 'undefined' || type === 'boolean') { + // All of the above are perceived as null. + children = null; + } + + var invokeCallback = false; + + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case 'string': + case 'number': + invokeCallback = true; + break; + + case 'object': + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + + } + } + + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array + // so that it's consistent if the number of children grows: + + var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + + if (isArray(mappedChild)) { + var escapedChildKey = ''; + + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + '/'; + } + + mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + // The `if` statement here prevents auto-disabling of the safe + // coercion ESLint rule, so we must manually disable it below. + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + + mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number + // eslint-disable-next-line react-internal/safe-string-coercion + escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); + } + + array.push(mappedChild); + } + + return 1; + } + + var child; + var nextName; + var subtreeCount = 0; // Count of children found in the current subtree. + + var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; + + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + + if (typeof iteratorFn === 'function') { + var iterableChildren = children; + + { + // Warn about using Maps as children + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } + + didWarnAboutMaps = true; + } + } + + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === 'object') { + // eslint-disable-next-line react-internal/safe-string-coercion + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } + } + + return subtreeCount; + } + + /** + * Maps children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenmap + * + * The provided mapFunction(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} func The map function. + * @param {*} context Context for mapFunction. + * @return {object} Object containing the ordered map of results. + */ + function mapChildren(children, func, context) { + if (children == null) { + return children; + } + + var result = []; + var count = 0; + mapIntoArray(children, result, '', '', function (child) { + return func.call(context, child, count++); + }); + return result; + } + /** + * Count the number of children that are typically specified as + * `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrencount + * + * @param {?*} children Children tree container. + * @return {number} The number of children. + */ + + + function countChildren(children) { + var n = 0; + mapChildren(children, function () { + n++; // Don't return anything + }); + return n; + } + + /** + * Iterates through children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenforeach + * + * The provided forEachFunc(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} forEachFunc + * @param {*} forEachContext Context for forEachContext. + */ + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function () { + forEachFunc.apply(this, arguments); // Don't return anything. + }, forEachContext); + } + /** + * Flatten a children object (typically specified as `props.children`) and + * return an array with appropriately re-keyed children. + * + * See https://reactjs.org/docs/react-api.html#reactchildrentoarray + */ + + + function toArray(children) { + return mapChildren(children, function (child) { + return child; + }) || []; + } + /** + * Returns the first child in a collection of children and verifies that there + * is only one child in the collection. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenonly + * + * The current implementation of this function assumes that a single child gets + * passed without a wrapper, but the purpose of this helper function is to + * abstract away the particular structure of children. + * + * @param {?object} children Child collection structure. + * @return {ReactElement} The first and only `ReactElement` contained in the + * structure. + */ + + + function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error('React.Children.only expected to receive a single React element child.'); + } + + return children; + } + + function createContext(defaultValue) { + // TODO: Second argument used to be an optional `calculateChangedBits` + // function. Warn to reserve for future use? + var context = { + $$typeof: REACT_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + // Add these to use same hidden class in VM as ServerContext + _defaultValue: null, + _globalName: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + + { + // A separate object, but proxies back to the original context object for + // backwards compatibility. It has a different $$typeof, so we can properly + // warn for the incorrect usage of Context as a Consumer. + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context + }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here + + Object.defineProperties(Consumer, { + Provider: { + get: function () { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + + error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + + return context.Provider; + }, + set: function (_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function () { + return context._currentValue; + }, + set: function (_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function () { + return context._currentValue2; + }, + set: function (_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function () { + return context._threadCount; + }, + set: function (_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function () { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + + error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + + return context.Consumer; + } + }, + displayName: { + get: function () { + return context.displayName; + }, + set: function (displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName); + + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty + + context.Consumer = Consumer; + } + + { + context._currentRenderer = null; + context._currentRenderer2 = null; + } + + return context; + } + + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); // Transition to the next state. + // This might throw either because it's missing or throws. If so, we treat it + // as still uninitialized and try again next time. Which is the same as what + // happens if the ctor or any wrappers processing the ctor throws. This might + // end up fixing it if the resolution was a concurrency bug. + + thenable.then(function (moduleObject) { + if (payload._status === Pending || payload._status === Uninitialized) { + // Transition to the next state. + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject; + } + }, function (error) { + if (payload._status === Pending || payload._status === Uninitialized) { + // Transition to the next state. + var rejected = payload; + rejected._status = Rejected; + rejected._result = error; + } + }); + + if (payload._status === Uninitialized) { + // In case, we're still uninitialized, then we're waiting for the thenable + // to resolve. Set it as pending in the meantime. + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + + if (payload._status === Resolved) { + var moduleObject = payload._result; + + { + if (moduleObject === undefined) { + error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. + 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject); + } + } + + { + if (!('default' in moduleObject)) { + error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. + 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject); + } + } + + return moduleObject.default; + } else { + throw payload._result; + } + } + + function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + + { + // In production, this would just set it on the object. + var defaultProps; + var propTypes; // $FlowFixMe + + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function () { + return defaultProps; + }, + set: function (newDefaultProps) { + error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); + + defaultProps = newDefaultProps; // Match production behavior more closely: + // $FlowFixMe + + Object.defineProperty(lazyType, 'defaultProps', { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function () { + return propTypes; + }, + set: function (newPropTypes) { + error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); + + propTypes = newPropTypes; // Match production behavior more closely: + // $FlowFixMe + + Object.defineProperty(lazyType, 'propTypes', { + enumerable: true + }); + } + } + }); + } + + return lazyType; + } + + function forwardRef(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); + } else if (typeof render !== 'function') { + error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); + } + } + + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); + } + } + } + + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: render + }; + + { + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; // The inner component shouldn't inherit this display name in most cases, + // because the component may be used elsewhere. + // But it's nice for anonymous functions to inherit the name, + // so that our component-stack generation logic will display their frames. + // An anonymous function generally suggests a pattern like: + // React.forwardRef((props, ref) => {...}); + // This kind of inner function is not used elsewhere so the side effect is okay. + + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + + return elementType; + } + + var REACT_MODULE_REFERENCE; + + { + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); + } + + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; + } + + function memo(type, compare) { + { + if (!isValidElementType(type)) { + error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); + } + } + + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: compare === undefined ? null : compare + }; + + { + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; // The inner component shouldn't inherit this display name in most cases, + // because the component may be used elsewhere. + // But it's nice for anonymous functions to inherit the name, + // so that our component-stack generation logic will display their frames. + // An anonymous function generally suggests a pattern like: + // React.memo((props) => {...}); + // This kind of inner function is not used elsewhere so the side effect is okay. + + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + + return elementType; + } + + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + + { + if (dispatcher === null) { + error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } + } // Will result in a null access error if accessed outside render phase. We + // intentionally don't throw our own error because this is in a hot path. + // Also helps ensure this is inlined. + + + return dispatcher; + } + function useContext(Context) { + var dispatcher = resolveDispatcher(); + + { + // TODO: add a more generic warning for invalid values. + if (Context._context !== undefined) { + var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs + // and nobody should be using this in existing code. + + if (realContext.Consumer === Context) { + error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); + } else if (realContext.Provider === Context) { + error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); + } + } + } + + return dispatcher.useContext(Context); + } + function useState(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + } + function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); + } + function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); + } + function useId() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); + } + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + } + + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + + function disabledLog() {} + + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } + } + + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; + } + + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } + } + + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + } + + var propTypesMisspellWarningShown; + + { + propTypesMisspellWarningShown = false; + } + + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; + } + } + + return ''; + } + + function getSourceInfoErrorAddendum(source) { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + + return ''; + } + + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== undefined) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + + return ''; + } + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ + + + var ownerHasKeyUseWarning = {}; + + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + + return info; + } + /** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ + + + function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + + { + setCurrentlyValidatingElement$1(element); + + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + + setCurrentlyValidatingElement$1(null); + } + } + /** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ + + + function validateChildKeys(node, parentType) { + if (typeof node !== 'object') { + return; + } + + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + /** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ + + + function validatePropTypes(element) { + { + var type = element.type; + + if (type === null || type === undefined || typeof type === 'string') { + return; + } + + var propTypes; + + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } + } + } + /** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ + + + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + + setCurrentlyValidatingElement$1(null); + break; + } + } + + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + + setCurrentlyValidatingElement$1(null); + } + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + + var typeString; + + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + + { + error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + } + + var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + + warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); + } // Legacy hook: remove it + + + Object.defineProperty(validatedFactory, 'type', { + enumerable: false, + get: function () { + warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); + + Object.defineProperty(this, 'type', { + value: type + }); + return type; + } + }); + } + + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + + validatePropTypes(newElement); + return newElement; + } + + var enableSchedulerDebugging = false; + var enableProfiling = false; + var frameYieldMs = 5; + + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + return heap.length === 0 ? null : heap[0]; + } + function pop(heap) { + if (heap.length === 0) { + return null; + } + + var first = heap[0]; + var last = heap.pop(); + + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } + + return first; + } + + function siftUp(heap, node, i) { + var index = i; + + while (index > 0) { + var parentIndex = index - 1 >>> 1; + var parent = heap[parentIndex]; + + if (compare(parent, node) > 0) { + // The parent is larger. Swap positions. + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + // The parent is smaller. Exit. + return; + } + } + } + + function siftDown(heap, node, i) { + var index = i; + var length = heap.length; + var halfLength = length >>> 1; + + while (index < halfLength) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. + + if (compare(left, node) < 0) { + if (rightIndex < length && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (rightIndex < length && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + // Neither child is smaller. Exit. + return; + } + } + } + + function compare(a, b) { + // Compare sort index first, then task id. + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } + + // TODO: Use symbols? + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; + + function markTaskErrored(task, ms) { + } + + /* eslint-disable no-var */ + var getCurrentTime; + var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; + + if (hasPerformanceNow) { + var localPerformance = performance; + + getCurrentTime = function () { + return localPerformance.now(); + }; + } else { + var localDate = Date; + var initialTime = localDate.now(); + + getCurrentTime = function () { + return localDate.now() - initialTime; + }; + } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. + // Math.pow(2, 30) - 1 + // 0b111111111111111111111111111111 + + + var maxSigned31BitInt = 1073741823; // Times out immediately + + var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out + + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5000; + var LOW_PRIORITY_TIMEOUT = 10000; // Never times out + + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap + + var taskQueue = []; + var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. + + var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. + var currentTask = null; + var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. + + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. + + var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom + + var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; + + function advanceTimers(currentTime) { + // Check for tasks that are no longer delayed and add them to the queue. + var timer = peek(timerQueue); + + while (timer !== null) { + if (timer.callback === null) { + // Timer was cancelled. + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + // Timer fired. Transfer to the task queue. + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + // Remaining timers are pending. + return; + } + + timer = peek(timerQueue); + } + } + + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); + + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); + + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + } + } + } + + function flushWork(hasTimeRemaining, initialTime) { + + + isHostCallbackScheduled = false; + + if (isHostTimeoutScheduled) { + // We scheduled a timeout but it's no longer needed. Cancel it. + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } + + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; + + try { + if (enableProfiling) { + try { + return workLoop(hasTimeRemaining, initialTime); + } catch (error) { + if (currentTask !== null) { + var currentTime = getCurrentTime(); + markTaskErrored(currentTask, currentTime); + currentTask.isQueued = false; + } + + throw error; + } + } else { + // No catch in prod code path. + return workLoop(hasTimeRemaining, initialTime); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } + + function workLoop(hasTimeRemaining, initialTime) { + var currentTime = initialTime; + advanceTimers(currentTime); + currentTask = peek(taskQueue); + + while (currentTask !== null && !(enableSchedulerDebugging )) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + // This currentTask hasn't expired, and we've reached the deadline. + break; + } + + var callback = currentTask.callback; + + if (typeof callback === 'function') { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; + + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = getCurrentTime(); + + if (typeof continuationCallback === 'function') { + currentTask.callback = continuationCallback; + } else { + + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } + + advanceTimers(currentTime); + } else { + pop(taskQueue); + } + + currentTask = peek(taskQueue); + } // Return whether there's additional work + + + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); + + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + + return false; + } + } + + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; + + default: + priorityLevel = NormalPriority; + } + + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + + function unstable_next(eventHandler) { + var priorityLevel; + + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + // Shift down to normal priority + priorityLevel = NormalPriority; + break; + + default: + // Anything lower than normal priority should remain at the current level. + priorityLevel = currentPriorityLevel; + break; + } + + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function () { + // This is a fork of runWithPriority, inlined for performance. + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; + + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } + + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = getCurrentTime(); + var startTime; + + if (typeof options === 'object' && options !== null) { + var delay = options.delay; + + if (typeof delay === 'number' && delay > 0) { + startTime = currentTime + delay; + } else { + startTime = currentTime; + } + } else { + startTime = currentTime; + } + + var timeout; + + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; + + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; + + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; + + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; + + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } + + var expirationTime = startTime + timeout; + var newTask = { + id: taskIdCounter++, + callback: callback, + priorityLevel: priorityLevel, + startTime: startTime, + expirationTime: expirationTime, + sortIndex: -1 + }; + + if (startTime > currentTime) { + // This is a delayed task. + newTask.sortIndex = startTime; + push(timerQueue, newTask); + + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + // All tasks are delayed, and this is the task with the earliest delay. + if (isHostTimeoutScheduled) { + // Cancel an existing timeout. + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } // Schedule a timeout. + + + requestHostTimeout(handleTimeout, startTime - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + // wait until the next time we yield. + + + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + + return newTask; + } + + function unstable_pauseExecution() { + } + + function unstable_continueExecution() { + + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } + + function unstable_cancelCallback(task) { + // remove from the queue because you can't remove arbitrary nodes from an + // array based heap, only the first one.) + + + task.callback = null; + } + + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } + + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main + // thread, like user events. By default, it yields multiple times per frame. + // It does not attempt to align with frame boundaries, since most tasks don't + // need to be frame aligned; for those that do, use requestAnimationFrame. + + var frameInterval = frameYieldMs; + var startTime = -1; + + function shouldYieldToHost() { + var timeElapsed = getCurrentTime() - startTime; + + if (timeElapsed < frameInterval) { + // The main thread has only been blocked for a really short amount of time; + // smaller than a single frame. Don't yield yet. + return false; + } // The main thread has been blocked for a non-negligible amount of time. We + + + return true; + } + + function requestPaint() { + + } + + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + // Using console['error'] to evade Babel and ESLint + console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); + return; + } + + if (fps > 0) { + frameInterval = Math.floor(1000 / fps); + } else { + // reset the framerate + frameInterval = frameYieldMs; + } + } + + var performWorkUntilDeadline = function () { + if (scheduledHostCallback !== null) { + var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread + // has been blocked. + + startTime = currentTime; + var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the + // error can be observed. + // + // Intentionally not using a try-catch, since that makes some debugging + // techniques harder. Instead, if `scheduledHostCallback` errors, then + // `hasMoreWork` will remain true, and we'll continue the work loop. + + var hasMoreWork = true; + + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + // If there's more work, schedule the next message event at the end + // of the preceding one. + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } // Yielding to the browser will give it a chance to paint, so we can + }; + + var schedulePerformWorkUntilDeadline; + + if (typeof localSetImmediate === 'function') { + // Node.js and old IE. + // There's a few reasons for why we prefer setImmediate. + // + // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. + // (Even though this is a DOM fork of the Scheduler, you could get here + // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) + // https://github.com/facebook/react/issues/20756 + // + // But also, it runs earlier which is the semantic we want. + // If other browsers ever implement it, it's better to use it. + // Although both of these would be inferior to native scheduling. + schedulePerformWorkUntilDeadline = function () { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== 'undefined') { + // DOM and Worker environments. + // We prefer MessageChannel because of the 4ms setTimeout clamping. + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; + + schedulePerformWorkUntilDeadline = function () { + port.postMessage(null); + }; + } else { + // We should only fallback here in non-browser environments. + schedulePerformWorkUntilDeadline = function () { + localSetTimeout(performWorkUntilDeadline, 0); + }; + } + + function requestHostCallback(callback) { + scheduledHostCallback = callback; + + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + schedulePerformWorkUntilDeadline(); + } + } + + function requestHostTimeout(callback, ms) { + taskTimeoutID = localSetTimeout(function () { + callback(getCurrentTime()); + }, ms); + } + + function cancelHostTimeout() { + localClearTimeout(taskTimeoutID); + taskTimeoutID = -1; + } + + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; + + + + var Scheduler = /*#__PURE__*/Object.freeze({ + __proto__: null, + unstable_ImmediatePriority: ImmediatePriority, + unstable_UserBlockingPriority: UserBlockingPriority, + unstable_NormalPriority: NormalPriority, + unstable_IdlePriority: IdlePriority, + unstable_LowPriority: LowPriority, + unstable_runWithPriority: unstable_runWithPriority, + unstable_next: unstable_next, + unstable_scheduleCallback: unstable_scheduleCallback, + unstable_cancelCallback: unstable_cancelCallback, + unstable_wrapCallback: unstable_wrapCallback, + unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel, + unstable_shouldYield: shouldYieldToHost, + unstable_requestPaint: unstable_requestPaint, + unstable_continueExecution: unstable_continueExecution, + unstable_pauseExecution: unstable_pauseExecution, + unstable_getFirstCallbackNode: unstable_getFirstCallbackNode, + get unstable_now () { return getCurrentTime; }, + unstable_forceFrameRate: forceFrameRate, + unstable_Profiling: unstable_Profiling + }); + + var ReactSharedInternals$1 = { + ReactCurrentDispatcher: ReactCurrentDispatcher, + ReactCurrentOwner: ReactCurrentOwner, + ReactCurrentBatchConfig: ReactCurrentBatchConfig, + // Re-export the schedule API(s) for UMD bundles. + // This avoids introducing a dependency on a new UMD global in a minor update, + // Since that would be a breaking change (e.g. for all existing CodeSandboxes). + // This re-export is only required for UMD bundles; + // CJS bundles use the shared NPM package. + Scheduler: Scheduler + }; + + { + ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue; + ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + } + + function startTransition(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + + { + ReactCurrentBatchConfig.transition._updatedFibers = new Set(); + } + + try { + scope(); + } finally { + ReactCurrentBatchConfig.transition = prevTransition; + + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + + if (updatedFibersCount > 10) { + warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); + } + + currentTransition._updatedFibers.clear(); + } + } + } + } + + var didWarnAboutMessageChannel = false; + var enqueueTaskImpl = null; + function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + // read require off the module object to get around the bundlers. + // we don't want them to detect a require and bundle a Node polyfill. + var requireString = ('require' + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's + // version of setImmediate, bypassing fake timers if any. + + enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; + } catch (_err) { + // we're in a browser + // we can't use regular timers because they may still be faked + // so we try MessageChannel+postMessage instead + enqueueTaskImpl = function (callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + + if (typeof MessageChannel === 'undefined') { + error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.'); + } + } + } + + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(undefined); + }; + } + } + + return enqueueTaskImpl(task); + } + + var actScopeDepth = 0; + var didWarnNoAwaitAct = false; + function act(callback) { + { + // `act` calls can be nested, so we track the depth. This represents the + // number of `act` scopes on the stack. + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + + if (ReactCurrentActQueue.current === null) { + // This is the outermost `act` scope. Initialize the queue. The reconciler + // will detect the queue and use it instead of Scheduler. + ReactCurrentActQueue.current = []; + } + + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + + try { + // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only + // set to `true` while the given callback is executed, not for updates + // triggered during an async event, because this is how the legacy + // implementation of `act` behaved. + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); // Replicate behavior of original `act` implementation in legacy mode, + // which flushed updates immediately after the scope function exits, even + // if it's an async function. + + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error) { + popActScope(prevActScopeDepth); + throw error; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + + if (result !== null && typeof result === 'object' && typeof result.then === 'function') { + var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait + // for it to resolve before exiting the current scope. + + var wasAwaited = false; + var thenable = { + then: function (resolve, reject) { + wasAwaited = true; + thenableResult.then(function (returnValue) { + popActScope(prevActScopeDepth); + + if (actScopeDepth === 0) { + // We've exited the outermost act scope. Recursively flush the + // queue until there's no remaining work. + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + }, function (error) { + // The callback threw an error. + popActScope(prevActScopeDepth); + reject(error); + }); + } + }; + + { + if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') { + // eslint-disable-next-line no-undef + Promise.resolve().then(function () {}).then(function () { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + + error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);'); + } + }); + } + } + + return thenable; + } else { + var returnValue = result; // The callback is not an async function. Exit the current scope + // immediately, without awaiting. + + popActScope(prevActScopeDepth); + + if (actScopeDepth === 0) { + // Exiting the outermost act scope. Flush the queue. + var _queue = ReactCurrentActQueue.current; + + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } // Return a thenable. If the user awaits it, we'll flush again in + // case additional work was scheduled by a microtask. + + + var _thenable = { + then: function (resolve, reject) { + // Confirm we haven't re-entered another `act` scope, in case + // the user does something weird like await the thenable + // multiple times. + if (ReactCurrentActQueue.current === null) { + // Recursively flush the queue until there's no remaining work. + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + // Since we're inside a nested `act` scope, the returned thenable + // immediately resolves. The outer scope will flush the queue. + var _thenable2 = { + then: function (resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } + } + + function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. '); + } + + actScopeDepth = prevActScopeDepth; + } + } + + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function () { + if (queue.length === 0) { + // No additional work was scheduled. Finish. + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + // Keep flushing work until there's none left. + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error) { + reject(error); + } + } else { + resolve(returnValue); + } + } + } + + var isFlushing = false; + + function flushActQueue(queue) { + { + if (!isFlushing) { + // Prevent re-entrance. + isFlushing = true; + var i = 0; + + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + + do { + callback = callback(true); + } while (callback !== null); + } + + queue.length = 0; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + queue = queue.slice(i + 1); + throw error; + } finally { + isFlushing = false; + } + } + } + } + + var createElement$1 = createElementWithValidation ; + var cloneElement$1 = cloneElementWithValidation ; + var createFactory = createFactoryWithValidation ; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray: toArray, + only: onlyChild + }; + + exports.Children = Children; + exports.Component = Component; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1; + exports.act = act; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext; + exports.createElement = createElement$1; + exports.createFactory = createFactory; + exports.createRef = createRef; + exports.forwardRef = forwardRef; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.startTransition = startTransition; + exports.unstable_act = act; + exports.useCallback = useCallback; + exports.useContext = useContext; + exports.useDebugValue = useDebugValue; + exports.useDeferredValue = useDeferredValue; + exports.useEffect = useEffect; + exports.useId = useId; + exports.useImperativeHandle = useImperativeHandle; + exports.useInsertionEffect = useInsertionEffect; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo; + exports.useReducer = useReducer; + exports.useRef = useRef; + exports.useState = useState; + exports.useSyncExternalStore = useSyncExternalStore; + exports.useTransition = useTransition; + exports.version = ReactVersion; + +}))); diff --git a/Project/Web/wwwroot/lib/js/tailwind-config.js b/Project/Web/wwwroot/lib/js/tailwind-config.js new file mode 100644 index 0000000..a024d45 --- /dev/null +++ b/Project/Web/wwwroot/lib/js/tailwind-config.js @@ -0,0 +1,81 @@ +// Tailwind CSS Configuration for GroupWare React Components +// This configuration includes all custom colors and extensions used in the React components + +window.tailwind = { + config: { + theme: { + extend: { + colors: { + primary: { + 50: '#eff6ff', + 100: '#dbeafe', + 200: '#bfdbfe', + 300: '#93c5fd', + 400: '#60a5fa', + 500: '#3b82f6', + 600: '#2563eb', + 700: '#1d4ed8', + 800: '#1e40af', + 900: '#1e3a8a', + }, + success: { + 50: '#f0fdf4', + 100: '#dcfce7', + 200: '#bbf7d0', + 300: '#86efac', + 400: '#4ade80', + 500: '#22c55e', + 600: '#16a34a', + 700: '#15803d', + 800: '#166534', + 900: '#14532d', + }, + warning: { + 50: '#fffbeb', + 100: '#fef3c7', + 200: '#fde68a', + 300: '#fcd34d', + 400: '#fbbf24', + 500: '#f59e0b', + 600: '#d97706', + 700: '#b45309', + 800: '#92400e', + 900: '#78350f', + }, + danger: { + 50: '#fef2f2', + 100: '#fee2e2', + 200: '#fecaca', + 300: '#fca5a5', + 400: '#f87171', + 500: '#ef4444', + 600: '#dc2626', + 700: '#b91c1c', + 800: '#991b1b', + 900: '#7f1d1d', + } + }, + animation: { + 'fade-in': 'fadeIn 0.5s ease-in-out', + 'slide-up': 'slideUp 0.3s ease-out', + 'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite', + }, + keyframes: { + fadeIn: { + '0%': { opacity: '0' }, + '100%': { opacity: '1' }, + }, + slideUp: { + '0%': { transform: 'translateY(10px)', opacity: '0' }, + '100%': { transform: 'translateY(0)', opacity: '1' }, + } + } + } + } + } +}; + +// Apply configuration if tailwindcss is available +if (typeof tailwindcss !== 'undefined') { + tailwindcss.config = window.tailwind.config; +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/CommonApp.jsx b/Project/Web/wwwroot/react/CommonApp.jsx new file mode 100644 index 0000000..ba7fe81 --- /dev/null +++ b/Project/Web/wwwroot/react/CommonApp.jsx @@ -0,0 +1,559 @@ +// CommonApp.jsx - React Common Code Management Component for GroupWare +const { useState, useEffect, useRef } = React; + +const CommonApp = () => { + // 상태 관리 + const [groupData, setGroupData] = useState([]); + const [currentData, setCurrentData] = useState([]); + const [selectedGroupCode, setSelectedGroupCode] = useState(null); + const [selectedGroupName, setSelectedGroupName] = useState(''); + const [loading, setLoading] = useState(false); + const [showEditModal, setShowEditModal] = useState(false); + const [showDeleteModal, setShowDeleteModal] = useState(false); + const [deleteTargetIdx, setDeleteTargetIdx] = useState(null); + const [editMode, setEditMode] = useState('add'); + + // 편집 폼 데이터 + const [editData, setEditData] = useState({ + idx: '', + grp: '', + code: '', + svalue: '', + ivalue: '', + fvalue: '', + svalue2: '', + memo: '' + }); + + // 페이지 로드시 초기 데이터 로드 + useEffect(() => { + loadGroups(); + }, []); + + // API 호출 함수들 + const loadGroups = async () => { + setLoading(true); + try { + const response = await fetch('http://127.0.0.1:7979/Common/GetGroups'); + const data = await response.json(); + setGroupData(data || []); + } catch (error) { + console.error('그룹 데이터 로드 중 오류 발생:', error); + showNotification('그룹 데이터 로드 중 오류가 발생했습니다.', 'error'); + } finally { + setLoading(false); + } + }; + + const loadDataByGroup = async (grp) => { + setLoading(true); + try { + let url = 'http://127.0.0.1:7979/Common/GetList'; + if (grp) { + url += '?grp=' + encodeURIComponent(grp); + } + + const response = await fetch(url); + const data = await response.json(); + setCurrentData(data || []); + } catch (error) { + console.error('데이터 로드 중 오류 발생:', error); + showNotification('데이터 로드 중 오류가 발생했습니다.', 'error'); + } finally { + setLoading(false); + } + }; + + const saveData = async () => { + try { + const data = { + idx: parseInt(editData.idx) || 0, + grp: editData.grp, + code: editData.code, + svalue: editData.svalue, + ivalue: parseInt(editData.ivalue) || 0, + fvalue: parseFloat(editData.fvalue) || 0.0, + svalue2: editData.svalue2, + memo: editData.memo + }; + + setLoading(true); + const response = await fetch('http://127.0.0.1:7979/Common/Save', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(data) + }); + + const result = await response.json(); + + if (result.Success) { + showNotification(result.Message, 'success'); + setShowEditModal(false); + if (selectedGroupCode) { + loadDataByGroup(selectedGroupCode); + } + } else { + showNotification(result.Message, 'error'); + } + } catch (error) { + console.error('저장 중 오류 발생:', error); + showNotification('저장 중 오류가 발생했습니다.', 'error'); + } finally { + setLoading(false); + } + }; + + const deleteItem = async () => { + if (!deleteTargetIdx) return; + + try { + setLoading(true); + const response = await fetch('http://127.0.0.1:7979/Common/Delete', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ idx: deleteTargetIdx }) + }); + + const data = await response.json(); + + if (data.Success) { + showNotification(data.Message, 'success'); + setShowDeleteModal(false); + if (selectedGroupCode) { + loadDataByGroup(selectedGroupCode); + } + } else { + showNotification(data.Message, 'error'); + } + } catch (error) { + console.error('삭제 중 오류 발생:', error); + showNotification('삭제 중 오류가 발생했습니다.', 'error'); + } finally { + setLoading(false); + setDeleteTargetIdx(null); + } + }; + + // 이벤트 핸들러들 + const selectGroup = (code, name) => { + setSelectedGroupCode(code); + setSelectedGroupName(name); + loadDataByGroup(code); + }; + + const openAddModal = () => { + if (!selectedGroupCode) { + showNotification('먼저 코드그룹을 선택하세요.', 'warning'); + return; + } + + setEditMode('add'); + setEditData({ + idx: '', + grp: selectedGroupCode, + code: '', + svalue: '', + ivalue: '', + fvalue: '', + svalue2: '', + memo: '' + }); + setShowEditModal(true); + }; + + const openEditModal = (item) => { + setEditMode('edit'); + setEditData({ + idx: item.idx, + grp: item.grp || '', + code: item.code || '', + svalue: item.svalue || '', + ivalue: item.ivalue || '', + fvalue: item.fvalue || '', + svalue2: item.svalue2 || '', + memo: item.memo || '' + }); + setShowEditModal(true); + }; + + const openDeleteModal = (idx) => { + setDeleteTargetIdx(idx); + setShowDeleteModal(true); + setShowEditModal(false); + }; + + const closeModals = () => { + setShowEditModal(false); + setShowDeleteModal(false); + setDeleteTargetIdx(null); + }; + + const handleInputChange = (field, value) => { + setEditData(prev => ({ ...prev, [field]: value })); + }; + + const showNotification = (message, type = 'info') => { + // 기존 알림 제거 + const existing = document.querySelectorAll('.notification-toast'); + existing.forEach(el => el.remove()); + + const colors = { + info: 'bg-blue-500/90', + success: 'bg-green-500/90', + warning: 'bg-yellow-500/90', + error: 'bg-red-500/90' + }; + + const icons = { + info: '🔵', + success: '✅', + warning: '⚠️', + error: '❌' + }; + + const notification = document.createElement('div'); + notification.className = `notification-toast fixed top-4 right-4 ${colors[type]} backdrop-blur-sm text-white px-4 py-3 rounded-lg z-50 shadow-lg border border-white/20`; + notification.innerHTML = `
${icons[type]}${message}
`; + + document.body.appendChild(notification); + + setTimeout(() => { + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + setTimeout(() => notification.remove(), 300); + }, 3000); + }; + + // 키보드 이벤트 + useEffect(() => { + const handleKeyDown = (e) => { + if (e.key === 'Escape') { + closeModals(); + } + }; + + document.addEventListener('keydown', handleKeyDown); + return () => document.removeEventListener('keydown', handleKeyDown); + }, []); + + return ( +
+ {/* Navigation Component */} + + +
+ {/* 2열 구조 메인 컨테이너 */} +
+ {/* 좌측: 코드그룹 리스트 */} +
+
+
+

+ + + + 코드그룹 목록 +

+
+
+
+ {groupData.length === 0 ? ( +
그룹 데이터가 없습니다.
+ ) : ( + groupData.map(group => ( +
selectGroup(group.code, group.memo)} + > +
+
+ {group.code} +
+
+
{group.memo}
+
+
+
+ )) + )} +
+
+
+
+ + {/* 우측: 상세 데이터 */} +
+
+ {/* 상단 헤더 */} +
+
+

+ + + + + {selectedGroupCode ? `${selectedGroupCode} - ${selectedGroupName}` : '코드그룹을 선택하세요'} + +

+

+ 총 {currentData.length}건 +

+
+ +
+ + {/* 데이터 테이블 */} +
+ + + + + + + + + + + + + {currentData.length === 0 ? ( + + + + ) : ( + currentData.map(item => ( + openEditModal(item)} + > + + + + + + + + )) + )} + +
코드비고값(문자열)값(숫자)값(실수)값2
+ + + + {selectedGroupCode ? '데이터가 없습니다.' : '좌측에서 코드그룹을 선택하세요'} +
{item.code || '-'}{item.memo || '-'} + {item.svalue || '-'} + {item.ivalue || '0'}{item.fvalue || '0.0'}{item.svalue2 || '-'}
+
+
+
+
+ + {/* 로딩 인디케이터 */} + {loading && ( +
+
+
+ 데이터 로딩 중... +
+
+ )} +
+ + {/* 추가/편집 모달 */} + {showEditModal && ( +
+
+
+ {/* 모달 헤더 */} +
+

+ {editMode === 'add' ? '공용코드 추가' : '공용코드 편집'} +

+ +
+ + {/* 모달 내용 */} +
+
+
+ + +
+
+ + handleInputChange('code', e.target.value)} + required + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="코드를 입력하세요" + /> +
+
+ + handleInputChange('svalue', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="문자열 값" + /> +
+
+ + handleInputChange('ivalue', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="숫자 값" + /> +
+
+ + handleInputChange('fvalue', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="실수 값" + /> +
+
+ + handleInputChange('svalue2', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="추가 문자열 값" + /> +
+
+ +
+ + +
+
+ + {/* 모달 푸터 */} +
+ {editMode === 'edit' && ( + + )} +
+ + +
+
+
+
+
+ )} + + {/* 삭제 확인 모달 */} + {showDeleteModal && ( +
+
+
+
+
+
+ + + +
+
+

삭제 확인

+

이 작업은 되돌릴 수 없습니다.

+
+
+

+ 선택한 공용코드를 삭제하시겠습니까?
+ 이 작업은 되돌릴 수 없습니다. +

+
+ + +
+
+
+
+
+ )} +
+ ); +}; \ No newline at end of file diff --git a/Project/Web/wwwroot/react/CommonCode.jsx b/Project/Web/wwwroot/react/CommonCode.jsx new file mode 100644 index 0000000..a133f1c --- /dev/null +++ b/Project/Web/wwwroot/react/CommonCode.jsx @@ -0,0 +1,590 @@ +const { useState, useEffect } = React; + +function CommonCode() { + // 상태 관리 + const [currentData, setCurrentData] = useState([]); + const [groupData, setGroupData] = useState([]); + const [selectedGroupCode, setSelectedGroupCode] = useState(null); + const [selectedGroupName, setSelectedGroupName] = useState(''); + const [isLoading, setIsLoading] = useState(false); + const [showEditModal, setShowEditModal] = useState(false); + const [showDeleteModal, setShowDeleteModal] = useState(false); + const [deleteTargetIdx, setDeleteTargetIdx] = useState(null); + const [editData, setEditData] = useState({ + idx: '', + grp: '', + code: '', + svalue: '', + ivalue: '', + fvalue: '', + svalue2: '', + memo: '' + }); + const [isEditMode, setIsEditMode] = useState(false); + + // 컴포넌트 마운트 시 초기 데이터 로드 + useEffect(() => { + loadGroups(); + }, []); + + // 코드그룹 목록 로드 + const loadGroups = async () => { + setIsLoading(true); + try { + const response = await fetch('http://127.0.0.1:7979/Common/GetGroups'); + const data = await response.json(); + setGroupData(data || []); + } catch (error) { + console.error('그룹 데이터 로드 중 오류 발생:', error); + showNotification('그룹 데이터 로드 중 오류가 발생했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 그룹 선택 처리 + const selectGroup = async (code, name) => { + setSelectedGroupCode(code); + setSelectedGroupName(name); + await loadDataByGroup(code); + }; + + // 특정 그룹의 데이터 로드 + const loadDataByGroup = async (grp) => { + setIsLoading(true); + try { + let url = 'http://127.0.0.1:7979/Common/GetList'; + if (grp) { + url += '?grp=' + encodeURIComponent(grp); + } + + const response = await fetch(url); + const data = await response.json(); + setCurrentData(data || []); + } catch (error) { + console.error('데이터 로드 중 오류 발생:', error); + showNotification('데이터 로드 중 오류가 발생했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 추가 모달 표시 + const showAddModal = () => { + if (!selectedGroupCode) { + showNotification('먼저 코드그룹을 선택하세요.', 'warning'); + return; + } + + setIsEditMode(false); + setEditData({ + idx: '', + grp: selectedGroupCode, + code: '', + svalue: '', + ivalue: '', + fvalue: '', + svalue2: '', + memo: '' + }); + setShowEditModal(true); + }; + + // 편집 모달 표시 + const editItem = (idx) => { + const item = currentData.find(x => x.idx === idx); + if (!item) return; + + setIsEditMode(true); + setEditData({ + idx: item.idx, + grp: item.grp || '', + code: item.code || '', + svalue: item.svalue || '', + ivalue: item.ivalue || '', + fvalue: item.fvalue || '', + svalue2: item.svalue2 || '', + memo: item.memo || '' + }); + setShowEditModal(true); + }; + + // 데이터 저장 + const saveData = async () => { + const form = document.getElementById('editForm'); + if (!form.checkValidity()) { + form.reportValidity(); + return; + } + + const data = { + idx: parseInt(editData.idx) || 0, + grp: editData.grp, + code: editData.code, + svalue: editData.svalue, + ivalue: parseInt(editData.ivalue) || 0, + fvalue: parseFloat(editData.fvalue) || 0.0, + svalue2: editData.svalue2, + memo: editData.memo + }; + + setIsLoading(true); + try { + const response = await fetch('http://127.0.0.1:7979/Common/Save', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(data) + }); + + const result = await response.json(); + if (result.Success) { + showNotification(result.Message, 'success'); + setShowEditModal(false); + if (selectedGroupCode) { + await loadDataByGroup(selectedGroupCode); + } + } else { + showNotification(result.Message, 'error'); + } + } catch (error) { + console.error('저장 중 오류 발생:', error); + showNotification('저장 중 오류가 발생했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 삭제 확인 + const confirmDelete = async () => { + if (!deleteTargetIdx) return; + + setIsLoading(true); + try { + const response = await fetch('http://127.0.0.1:7979/Common/Delete', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ idx: deleteTargetIdx }) + }); + + const data = await response.json(); + if (data.Success) { + showNotification(data.Message, 'success'); + setShowDeleteModal(false); + setDeleteTargetIdx(null); + if (selectedGroupCode) { + await loadDataByGroup(selectedGroupCode); + } + } else { + showNotification(data.Message, 'error'); + } + } catch (error) { + console.error('삭제 중 오류 발생:', error); + showNotification('삭제 중 오류가 발생했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 삭제 요청 + const deleteCurrentItem = () => { + if (!editData.idx) { + showNotification('삭제할 항목이 없습니다.', 'warning'); + return; + } + + setDeleteTargetIdx(parseInt(editData.idx)); + setShowEditModal(false); + setShowDeleteModal(true); + }; + + // 알림 표시 함수 + const showNotification = (message, type = 'info') => { + const colors = { + info: 'bg-blue-500/90 backdrop-blur-sm', + success: 'bg-green-500/90 backdrop-blur-sm', + warning: 'bg-yellow-500/90 backdrop-blur-sm', + error: 'bg-red-500/90 backdrop-blur-sm' + }; + + const icons = { + info: ( + + + + ), + success: ( + + + + ), + warning: ( + + + + ), + error: ( + + + + ) + }; + + // React에서는 실제 DOM 조작 대신 Toast 라이브러리나 상태로 관리하는 것이 좋습니다 + // 여기서는 기존 방식을 유지하되 React 컴포넌트 스타일로 구현 + const notification = document.createElement('div'); + notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-4 py-3 rounded-lg z-50 transition-all duration-300 transform translate-x-0 opacity-100 shadow-lg border border-white/20`; + notification.innerHTML = ` +
+ ${type === 'info' ? '' : ''} + ${type === 'success' ? '' : ''} + ${type === 'warning' ? '' : ''} + ${type === 'error' ? '' : ''} + ${message} +
+ `; + + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + document.body.appendChild(notification); + + setTimeout(() => { + notification.style.transform = 'translateX(0)'; + notification.style.opacity = '1'; + }, 10); + + setTimeout(() => { + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + setTimeout(() => notification.remove(), 300); + }, 3000); + }; + + // 키보드 이벤트 핸들러 + useEffect(() => { + const handleKeyDown = (e) => { + if (e.key === 'Escape') { + setShowEditModal(false); + setShowDeleteModal(false); + } + }; + + document.addEventListener('keydown', handleKeyDown); + return () => document.removeEventListener('keydown', handleKeyDown); + }, []); + + // 입력 필드 변경 핸들러 + const handleInputChange = (field, value) => { + setEditData(prev => ({ ...prev, [field]: value })); + }; + + return ( +
+ {/* 2열 구조 메인 컨테이너 */} +
+ {/* 좌측: 코드그룹 리스트 */} +
+
+
+

+ + + + 코드그룹 목록 +

+
+
+
+ {groupData.length === 0 ? ( +
그룹 데이터가 없습니다.
+ ) : ( + groupData.map(group => ( +
selectGroup(group.code, group.memo)} + > +
+
+ {group.code} +
+
+
{group.memo}
+
+
+
+ )) + )} +
+
+
+
+ + {/* 우측: 상세 데이터 */} +
+
+ {/* 상단 헤더 */} +
+
+

+ + + + {selectedGroupCode ? `${selectedGroupCode} - ${selectedGroupName}` : '코드그룹을 선택하세요'} +

+

{currentData.length}

+
+ +
+ + {/* 데이터 테이블 */} +
+ + + + + + + + + + + + + {currentData.length === 0 ? ( + + + + ) : ( + currentData.map(item => ( + editItem(item.idx)} + > + + + + + + + + )) + )} + +
코드비고값(문자열)값(숫자)값(실수)값2
+ + + + {selectedGroupCode ? '데이터가 없습니다.' : '좌측에서 코드그룹을 선택하세요'} +
{item.code || '-'}{item.memo || '-'}{item.svalue || '-'}{item.ivalue || '0'}{item.fvalue || '0.0'}{item.svalue2 || '-'}
+
+
+
+
+ + {/* 로딩 인디케이터 */} + {isLoading && ( +
+
+
+ 데이터 로딩 중... +
+
+ )} + + {/* 추가/편집 모달 */} + {showEditModal && ( +
+
+
+ {/* 모달 헤더 */} +
+

+ {isEditMode ? '공용코드 편집' : '공용코드 추가'} +

+ +
+ + {/* 모달 내용 */} +
+
+
+ + +
+
+ + handleInputChange('code', e.target.value)} + required + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="코드를 입력하세요" + /> +
+
+ + handleInputChange('svalue', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="문자열 값" + /> +
+
+ + handleInputChange('ivalue', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="숫자 값" + /> +
+
+ + handleInputChange('fvalue', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="실수 값" + /> +
+
+ + handleInputChange('svalue2', e.target.value)} + className="w-full px-3 py-2 bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="추가 문자열 값" + /> +
+
+ +
+ + +
+
+ + {/* 모달 푸터 */} +
+ +
+ + +
+
+
+
+
+ )} + + {/* 삭제 확인 모달 */} + {showDeleteModal && ( +
+
+
+
+
+
+ + + +
+
+

삭제 확인

+

이 작업은 되돌릴 수 없습니다.

+
+
+

+ 선택한 공용코드를 삭제하시겠습니까?
+ 이 작업은 되돌릴 수 없습니다. +

+
+ + +
+
+
+
+
+ )} +
+ ); +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/CommonNavigation.jsx b/Project/Web/wwwroot/react/CommonNavigation.jsx new file mode 100644 index 0000000..2a4750f --- /dev/null +++ b/Project/Web/wwwroot/react/CommonNavigation.jsx @@ -0,0 +1,166 @@ +// CommonNavigation.jsx - React Navigation Component for GroupWare +const CommonNavigation = ({ currentPage = 'dashboard' }) => { + const [menuItems, setMenuItems] = useState([]); + const [mobileMenuOpen, setMobileMenuOpen] = useState(false); + const [currentUser, setCurrentUser] = useState('사용자'); + + // 기본 메뉴 아이템 - React 경로 사용 + const defaultMenuItems = [ + { + key: 'dashboard', + title: '대시보드', + url: '/react/dashboard', + icon: 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z M8 5a2 2 0 012-2h4a2 2 0 012 2v2H8V5z', + isVisible: true, + sortOrder: 1 + }, + { + key: 'common', + title: '공용코드', + url: '/react/common', + icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', + isVisible: true, + sortOrder: 2 + }, + { + key: 'jobreport', + title: '업무일지', + url: '/react/jobreport', + icon: 'M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2', + isVisible: true, + sortOrder: 3 + }, + { + key: 'kuntae', + title: '근태관리', + url: '/react/kuntae', + icon: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z', + isVisible: true, + sortOrder: 4 + }, + { + key: 'todo', + title: '할일관리', + url: '/react/todo', + icon: 'M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2M12 12l2 2 4-4', + isVisible: true, + sortOrder: 5 + }, + { + key: 'project', + title: '프로젝트', + url: '/react/project', + icon: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10', + isVisible: true, + sortOrder: 6 + }, + { + key: 'purchase', + title: '구매관리', + url: '/Purchase/', + icon: 'M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z', + isVisible: true, + sortOrder: 7 + }, + { + key: 'customer', + title: '고객관리', + url: '/Customer/', + icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z', + isVisible: true, + sortOrder: 8 + } + ]; + + // 메뉴 아이템 로드 - defaultMenuItems 사용 (React 경로) + useEffect(() => { + setMenuItems(defaultMenuItems); + }, []); + + // 보이는 메뉴 아이템만 정렬해서 반환 + const visibleItems = menuItems + .filter(item => item.isVisible) + .sort((a, b) => a.sortOrder - b.sortOrder); + + return ( + + ); +}; \ No newline at end of file diff --git a/Project/Web/wwwroot/react/DashboardApp.jsx b/Project/Web/wwwroot/react/DashboardApp.jsx new file mode 100644 index 0000000..c412b36 --- /dev/null +++ b/Project/Web/wwwroot/react/DashboardApp.jsx @@ -0,0 +1,669 @@ +// DashboardApp.jsx - React Dashboard Component for GroupWare +const { useState, useEffect, useRef } = React; + +function DashboardApp() { + // 상태 관리 + const [dashboardData, setDashboardData] = useState({ + presentCount: 0, + leaveCount: 0, + leaveRequestCount: 0, + purchaseCountNR: 0, + purchaseCountCR: 0 + }); + + const [isLoading, setIsLoading] = useState(true); + const [lastUpdated, setLastUpdated] = useState(''); + const [modals, setModals] = useState({ + presentUsers: false, + holidayUsers: false, + holidayRequest: false, + purchaseNR: false, + purchaseCR: false + }); + + const [modalData, setModalData] = useState({ + presentUsers: [], + holidayUsers: [], + holidayRequests: [], + purchaseNR: [], + purchaseCR: [] + }); + + const [todoList, setTodoList] = useState([]); + + // 모달 제어 함수 + const showModal = (modalName) => { + setModals(prev => ({ ...prev, [modalName]: true })); + loadModalData(modalName); + }; + + const hideModal = (modalName) => { + setModals(prev => ({ ...prev, [modalName]: false })); + }; + + // Dashboard 데이터 로드 + const loadDashboardData = async () => { + setIsLoading(true); + try { + // 실제 DashBoardController API 호출 + const [ + currentUserResponse, + leaveCountResponse, + holyRequestResponse, + purchaseWaitResponse + ] = await Promise.all([ + fetch('http://127.0.0.1:7979/DashBoard/GetCurrentUserCount'), + fetch('http://127.0.0.1:7979/DashBoard/TodayCountH'), + fetch('http://127.0.0.1:7979/DashBoard/GetHolydayRequestCount'), + fetch('http://127.0.0.1:7979/DashBoard/GetPurchaseWaitCount') + ]); + + // 현재 근무자 수 (JSON 응답) + const currentUserData = await currentUserResponse.json(); + const presentCount = currentUserData.Count || 0; + + // 휴가자 수 (텍스트 응답) + const leaveCountText = await leaveCountResponse.text(); + const leaveCount = parseInt(leaveCountText.replace(/"/g, ''), 10) || 0; + + // 휴가 요청 수 (JSON 응답) + const holyRequestData = await holyRequestResponse.json(); + const leaveRequestCount = holyRequestData.HOLY || 0; + + // 구매 대기 수 (JSON 응답) + const purchaseWaitData = await purchaseWaitResponse.json(); + const purchaseCountNR = purchaseWaitData.NR || 0; + const purchaseCountCR = purchaseWaitData.CR || 0; + + setDashboardData({ + presentCount, + leaveCount, + leaveRequestCount, + purchaseCountNR, + purchaseCountCR + }); + + setLastUpdated(new Date().toLocaleString('ko-KR')); + } catch (error) { + console.error('대시보드 데이터 로드 실패:', error); + } finally { + setIsLoading(false); + } + }; + + // 모달 데이터 로드 + const loadModalData = async (modalName) => { + try { + let endpoint = ''; + switch (modalName) { + case 'presentUsers': + endpoint = 'http://127.0.0.1:7979/DashBoard/GetPresentUserList'; + break; + case 'holidayUsers': + endpoint = 'http://127.0.0.1:7979/DashBoard/GetholyUser'; + break; + case 'holidayRequest': + endpoint = 'http://127.0.0.1:7979/DashBoard/GetholyRequestUser'; + break; + case 'purchaseNR': + endpoint = 'http://127.0.0.1:7979/DashBoard/GetPurchaseNRList'; + break; + case 'purchaseCR': + endpoint = 'http://127.0.0.1:7979/DashBoard/GetPurchaseCRList'; + break; + default: + return; + } + + const response = await fetch(endpoint); + const data = await response.json(); + + setModalData(prev => ({ + ...prev, + [modalName]: Array.isArray(data) ? data : [] + })); + } catch (error) { + console.error(`모달 데이터 로드 실패 (${modalName}):`, error); + setModalData(prev => ({ + ...prev, + [modalName]: [] + })); + } + }; + + // Todo 목록 로드 + const loadTodoList = async () => { + try { + const response = await fetch('http://127.0.0.1:7979/Todo/GetUrgentTodos'); + const data = await response.json(); + + if (data.Success && data.Data) { + setTodoList(data.Data); + } else { + setTodoList([]); + } + } catch (error) { + console.error('Todo 목록 로드 실패:', error); + setTodoList([]); + } + }; + + // 자동 새로고침 (30초마다) + useEffect(() => { + loadDashboardData(); + loadModalData('holidayUsers'); // 휴가자 목록 자동 로드 + loadTodoList(); // Todo 목록 자동 로드 + + const interval = setInterval(() => { + loadDashboardData(); + loadModalData('holidayUsers'); // 30초마다 휴가자 목록도 새로고침 + loadTodoList(); // 30초마다 Todo 목록도 새로고침 + }, 30000); // 30초 + + return () => clearInterval(interval); + }, []); + + // 통계 카드 컴포넌트 + const StatCard = ({ title, count, icon, color, onClick, isClickable = false }) => { + return ( +
+
+
+

{title}

+

+ {isLoading ? ( +

+ ) : count} +

+
+
+ {icon} +
+
+
+ ); + }; + + // 테이블 모달 컴포넌트 + const TableModal = ({ isOpen, onClose, title, headers, data, renderRow, maxWidth = 'max-w-4xl' }) => { + if (!isOpen) return null; + + return ( +
+
+
+ {/* 모달 헤더 */} +
+

+ + + + {title} +

+ +
+ + {/* 모달 내용 */} +
+ + + + {headers.map((header, index) => ( + + ))} + + + + {data.length > 0 ? ( + data.map((item, index) => renderRow(item, index)) + ) : ( + + + + )} + +
+ {header} +
+ 데이터가 없습니다. +
+
+ + {/* 모달 푸터 */} +
+

+ 총 {data.length}건 +

+ +
+
+
+
+ ); + }; + + return ( +
+
+ {/* 헤더 */} +
+

근태현황 대시보드

+

실시간 근태 및 업무 현황을 확인하세요

+ {lastUpdated && ( +

마지막 업데이트: {lastUpdated}

+ )} +
+ + {/* 새로고침 버튼 */} +
+ +
+ + {/* 통계 카드 */} +
+ showModal('presentUsers')} + color="bg-success-500" + icon={ + + + + } + /> + + showModal('holidayUsers')} + color="bg-warning-500" + icon={ + + + + } + /> + + showModal('holidayRequest')} + color="bg-primary-500" + icon={ + + + + } + /> + + showModal('purchaseNR')} + color="bg-danger-500" + icon={ + + + + } + /> + + showModal('purchaseCR')} + color="bg-purple-500" + icon={ + + + + } + /> +
+ + {/* 2칸 레이아웃: 좌측 휴가현황, 우측 할일 */} +
+ {/* 좌측: 휴가/기타 현황 */} +
+
+

+ + + + 휴가/기타 현황 +

+
+
+ + + + + + + + + + + + {modalData.holidayUsers.map((user, index) => { + // 형태에 따른 색상 결정 + const typeColorClass = (user.type === '휴가') ? 'bg-green-500/20 text-green-300' : 'bg-warning-500/20 text-warning-300'; + + // 종류에 따른 색상 결정 + let cateColorClass = 'bg-warning-500/20 text-warning-300'; // 기본값 + if (user.cate === '휴가') { + cateColorClass = 'bg-warning-500/20 text-warning-300'; // 노란색 계열 + } else if (user.cate === '파견') { + cateColorClass = 'bg-purple-500/20 text-purple-300'; // 보라색 계열 + } else { + cateColorClass = 'bg-warning-500/20 text-warning-300'; // 기타는 주황색 계열 + } + + // 기간 표시 형식 개선 + let periodText = ''; + if (user.sdate && user.edate) { + if (user.sdate === user.edate) { + periodText = user.sdate; + } else { + periodText = `${user.sdate}~${user.edate}`; + } + } else { + periodText = '-'; + } + + return ( + + + + + + + + ); + })} + {modalData.holidayUsers.length === 0 && ( + + + + )} + +
이름형태종류기간사유
{user.name || '이름 없음'} + + {user.type || 'N/A'} + + + + {user.cate || '종류 없음'} + + {periodText}{user.title || '사유 없음'}
+ 현재 휴가자가 없습니다 +
+
+
+ + {/* 우측: 할일 */} +
+
+

+ + + + + 할일 + +
+ + +
+

+
+
+
+ {todoList.length > 0 ? ( + todoList.map((todo, index) => { + const flagIcon = todo.flag ? '📌 ' : ''; + + // 상태별 클래스 + const getTodoStatusClass = (status) => { + switch(status) { + case '0': return 'bg-gray-500/20 text-gray-300'; + case '1': return 'bg-primary-500/20 text-primary-300'; + case '2': return 'bg-danger-500/20 text-danger-300'; + case '3': return 'bg-warning-500/20 text-warning-300'; + case '5': return 'bg-success-500/20 text-success-300'; + default: return 'bg-white/10 text-white/50'; + } + }; + + const getTodoStatusText = (status) => { + switch(status) { + case '0': return '대기'; + case '1': return '진행'; + case '2': return '취소'; + case '3': return '보류'; + case '5': return '완료'; + default: return '대기'; + } + }; + + const getTodoSeqnoClass = (seqno) => { + switch(seqno) { + case '0': return 'bg-gray-500/20 text-gray-300'; + case '1': return 'bg-success-500/20 text-success-300'; + case '2': return 'bg-warning-500/20 text-warning-300'; + case '3': return 'bg-danger-500/20 text-danger-300'; + default: return 'bg-white/10 text-white/50'; + } + }; + + const getTodoSeqnoText = (seqno) => { + switch(seqno) { + case '0': return '낮음'; + case '1': return '보통'; + case '2': return '높음'; + case '3': return '긴급'; + default: return '보통'; + } + }; + + const statusClass = getTodoStatusClass(todo.status); + const statusText = getTodoStatusText(todo.status); + const seqnoClass = getTodoSeqnoClass(todo.seqno); + const seqnoText = getTodoSeqnoText(todo.seqno); + + const expireText = todo.expire ? new Date(todo.expire).toLocaleDateString('ko-KR') : ''; + const isExpired = todo.expire && new Date(todo.expire) < new Date(); + const expireClass = isExpired ? 'text-danger-400' : 'text-white/60'; + + // 만료일이 지난 경우 배경을 적색계통으로 강조 + const expiredBgClass = isExpired ? 'bg-danger-600/30 border-danger-400/40 hover:bg-danger-600/40' : 'bg-white/10 hover:bg-white/15 border-white/20'; + + return ( +
alert('Todo 상세보기 기능은 준비 중입니다.')}> +
+
+ + {statusText} + + + {seqnoText} + +
+ {expireText && ( + + {expireText} + + )} +
+

+ {flagIcon}{todo.title || '제목 없음'} +

+ {todo.description && ( +

+ {todo.description} +

+ )} + {todo.request && ( +

요청자: {todo.request}

+ )} +
+ ); + }) + ) : ( +
+ + + + 급한 할일이 없습니다 +
+ )} +
+
+
+
+ + {/* 출근 대상자 모달 */} + hideModal('presentUsers')} + title="금일 출근 대상자 목록" + headers={['사번', '이름', '공정', '직급', '상태', '이메일']} + data={modalData.presentUsers} + renderRow={(user, index) => ( + + {user.id || 'N/A'} + {user.name || '이름 없음'} + {user.gname || 'N/A'} + {user.level || 'N/A'} + 출근 + {user.email || 'N/A'} + + )} + /> + + {/* 휴가 요청 모달 */} + hideModal('holidayRequest')} + title="휴가 신청 목록" + maxWidth="max-w-6xl" + headers={['사번', '이름', '항목', '일자', '요청일', '요청시간', '비고']} + data={modalData.holidayRequests} + renderRow={(request, index) => ( + + {request.uid || 'N/A'} + {request.name || '이름 없음'} + {request.cate || 'N/A'} + + {request.sdate && request.edate ? `${request.sdate} ~ ${request.edate}` : 'N/A'} + + {request.holydays || 'N/A'} + {request.holytimes || 'N/A'} + {request.HolyReason || request.remark || 'N/A'} + + )} + /> + + {/* 구매요청 NR 모달 */} + hideModal('purchaseNR')} + title="구매요청(NR) 목록" + maxWidth="max-w-7xl" + headers={['요청일', '공정', '품목', '규격', '단위', '수량', '단가', '금액']} + data={modalData.purchaseNR} + renderRow={(item, index) => ( + + {item.pdate || 'N/A'} + {item.process || 'N/A'} + {item.pumname || '품목 없음'} + {item.pumscale || 'N/A'} + {item.pumunit || 'N/A'} + {item.pumqtyreq || 'N/A'} + + {item.pumprice ? `₩${Number(item.pumprice).toLocaleString()}` : 'N/A'} + + + {item.pumamt ? `₩${Number(item.pumamt).toLocaleString()}` : 'N/A'} + + + )} + /> + + {/* 구매요청 CR 모달 */} + hideModal('purchaseCR')} + title="구매요청(CR) 목록" + maxWidth="max-w-7xl" + headers={['요청일', '공정', '품목', '규격', '단위', '수량', '단가', '금액']} + data={modalData.purchaseCR} + renderRow={(item, index) => ( + + {item.pdate || 'N/A'} + {item.process || 'N/A'} + {item.pumname || '품목 없음'} + {item.pumscale || 'N/A'} + {item.pumunit || 'N/A'} + {item.pumqtyreq || 'N/A'} + + {item.pumprice ? `₩${Number(item.pumprice).toLocaleString()}` : 'N/A'} + + + {item.pumamt ? `₩${Number(item.pumamt).toLocaleString()}` : 'N/A'} + + + )} + /> +
+
+ ); +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/DevWarning.jsx b/Project/Web/wwwroot/react/DevWarning.jsx new file mode 100644 index 0000000..bcc3104 --- /dev/null +++ b/Project/Web/wwwroot/react/DevWarning.jsx @@ -0,0 +1,21 @@ +// 개발중 경고 메시지 컴포넌트 +function DevWarning({ show = false }) { + // show props가 false이거나 없으면 아무것도 렌더링하지 않음 + if (!show) { + return null; + } + + return ( +
+
+ + + +
+

🚧 개발중인 기능입니다

+

일부 기능이 정상적으로 동작하지 않을 수 있습니다.

+
+
+
+ ); +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/JobReport.jsx b/Project/Web/wwwroot/react/JobReport.jsx new file mode 100644 index 0000000..8194153 --- /dev/null +++ b/Project/Web/wwwroot/react/JobReport.jsx @@ -0,0 +1,988 @@ +const { useState, useEffect } = React; + +function JobReport() { + // 상태 관리 + const [jobData, setJobData] = useState([]); + const [filteredData, setFilteredData] = useState([]); + const [currentPage, setCurrentPage] = useState(1); + const [pageSize, setPageSize] = useState(25); + const [sortColumn, setSortColumn] = useState('pdate'); + const [sortDirection, setSortDirection] = useState('desc'); + const [isLoading, setIsLoading] = useState(false); + const [showEditModal, setShowEditModal] = useState(false); + const [editData, setEditData] = useState({}); + const [isEditMode, setIsEditMode] = useState(false); + + // 필터 상태 + const [filters, setFilters] = useState({ + startDate: '', + endDate: '', + status: '', + type: '', + user: '', + project: '', + search: '' + }); + + // 통계 데이터 + const [statistics, setStatistics] = useState({ + totalDays: 0, + todayHours: 0, + todayProgress: 0, + totalOT: 0, + activeProjects: 0 + }); + + // 컴포넌트 마운트시 초기화 + useEffect(() => { + initializeFilters(); + loadJobData(); + loadUserList(); + }, []); + + // 필터 변경 시 데이터 필터링 + useEffect(() => { + filterData(); + }, [jobData, filters]); + + // 초기 필터 설정 (오늘부터 -2주) + const initializeFilters = () => { + const now = new Date(); + const today = now.toISOString().split('T')[0]; + const twoWeeksAgo = new Date(now.getTime() - (14 * 24 * 60 * 60 * 1000)).toISOString().split('T')[0]; + + setFilters(prev => ({ + ...prev, + startDate: twoWeeksAgo, + endDate: today + })); + }; + + // 업무일지 데이터 로드 + const loadJobData = async () => { + setIsLoading(true); + try { + let url = '/Jobreport/GetJobData'; + const params = new URLSearchParams(); + if (filters.startDate) params.append('startDate', filters.startDate); + if (filters.endDate) params.append('endDate', filters.endDate); + if (filters.user) params.append('user', filters.user); + + if (params.toString()) { + url += '?' + params.toString(); + } + + const response = await fetch(url); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: 데이터를 불러오는데 실패했습니다.`); + } + + const responseText = await response.text(); + const responseData = JSON.parse(responseText); + + if (Array.isArray(responseData)) { + setJobData(responseData); + } else if (responseData.error) { + throw new Error(responseData.error); + } else { + setJobData([]); + } + + } catch (error) { + console.error('Error loading job data:', error); + setJobData([]); + showNotification('데이터를 불러오는데 실패했습니다: ' + error.message, 'error'); + } finally { + setIsLoading(false); + } + }; + + // 사용자 목록 로드 + const loadUserList = async () => { + try { + const response = await fetch('/Jobreport/GetUsers'); + if (response.ok) { + const data = await response.json(); + // 사용자 데이터를 상태로 저장 (필요시) + } + } catch (error) { + console.error('사용자 목록 로드 중 오류:', error); + } + }; + + // 통계 업데이트 + useEffect(() => { + updateStatistics(); + }, [jobData]); + + const updateStatistics = () => { + const totalDays = new Set(jobData.map(item => item.pdate)).size; + const totalOT = jobData.reduce((sum, item) => sum + (parseFloat(item.ot) || 0), 0); + const activeProjects = new Set(jobData.filter(item => item.status === '진행중').map(item => item.projectName)).size; + + const now = new Date(); + const today = now.toISOString().split('T')[0]; + + const todayData = jobData.filter(item => { + if (!item.pdate) return false; + const itemDate = item.pdate.toString(); + if (itemDate.length >= 10) { + return itemDate.substring(0, 10) === today; + } + return false; + }); + + let todayHours = 0; + if (todayData.length > 0) { + todayHours = todayData.reduce((sum, item) => sum + (parseFloat(item.hrs) || 0), 0); + } + const todayProgress = (todayHours / 8) * 100; + + setStatistics({ + totalDays, + todayHours, + todayProgress, + totalOT, + activeProjects + }); + }; + + // 데이터 필터링 + const filterData = () => { + let filtered = jobData.filter(item => { + const statusMatch = !filters.status || item.status === filters.status; + const typeMatch = !filters.type || item.type === filters.type; + const projectMatch = !filters.project || item.projectName === filters.project; + const searchMatch = !filters.search || + (item.description && item.description.toLowerCase().includes(filters.search.toLowerCase())) || + (item.projectName && item.projectName.toLowerCase().includes(filters.search.toLowerCase())) || + (item.requestpart && item.requestpart.toLowerCase().includes(filters.search.toLowerCase())); + + return statusMatch && typeMatch && projectMatch && searchMatch; + }); + + // 정렬 + filtered.sort((a, b) => { + let aVal = a[sortColumn]; + let bVal = b[sortColumn]; + + if (sortColumn === 'pdate') { + aVal = new Date(aVal); + bVal = new Date(bVal); + } else if (['hrs', 'ot'].includes(sortColumn)) { + aVal = parseFloat(aVal) || 0; + bVal = parseFloat(bVal) || 0; + } else { + aVal = (aVal || '').toString().toLowerCase(); + bVal = (bVal || '').toString().toLowerCase(); + } + + if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1; + if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1; + return 0; + }); + + setFilteredData(filtered); + setCurrentPage(1); + }; + + // 필터 변경 핸들러 + const handleFilterChange = (field, value) => { + setFilters(prev => ({ ...prev, [field]: value })); + + // 날짜 필터 변경시 데이터 다시 로드 + if (field === 'startDate' || field === 'endDate' || field === 'user') { + setTimeout(() => loadJobData(), 100); + } + }; + + // 필터 초기화 + const clearFilters = () => { + const now = new Date(); + const today = now.toISOString().split('T')[0]; + const twoWeeksAgo = new Date(now.getTime() - (14 * 24 * 60 * 60 * 1000)).toISOString().split('T')[0]; + + setFilters({ + startDate: twoWeeksAgo, + endDate: today, + status: '', + type: '', + user: '', + project: '', + search: '' + }); + + setTimeout(() => loadJobData(), 100); + }; + + // 정렬 처리 + const handleSort = (column) => { + if (sortColumn === column) { + setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc'); + } else { + setSortColumn(column); + setSortDirection('asc'); + } + }; + + // 추가 모달 표시 + const showAddJobModal = () => { + const today = new Date().toISOString().split('T')[0]; + setIsEditMode(false); + setEditData({ + idx: '', + pdate: today, + status: '진행 중', + projectName: '', + requestpart: '', + type: '', + hrs: '8', + ot: '', + otStart: '', + otEnd: '', + description: '' + }); + setShowEditModal(true); + }; + + // 편집 모달 표시 + const showEditJobModal = async (item) => { + try { + // 상세 정보 로드 + const response = await fetch(`/Jobreport/GetJobDetail?id=${item.idx}`); + if (response.ok) { + const fullItem = await response.json(); + item = fullItem.error ? item : fullItem; + } + } catch (error) { + console.warn('Failed to load full details, using truncated data:', error); + } + + setIsEditMode(true); + setEditData({ + idx: item.idx || '', + pdate: item.pdate || '', + status: item.status || '', + projectName: item.projectName || '', + requestpart: item.requestpart || '', + type: item.type || '', + hrs: item.hrs || '', + ot: item.ot || '', + otStart: item.otStart || '', + otEnd: item.otEnd || '', + description: item.description || '' + }); + setShowEditModal(true); + }; + + // 저장 처리 + const handleSave = async (event) => { + event.preventDefault(); + + const formData = new URLSearchParams(); + Object.keys(editData).forEach(key => { + if (key !== 'idx' || editData.idx) { + formData.append(key, editData[key]); + } + }); + + try { + const url = isEditMode ? '/Jobreport/Edit' : '/Jobreport/Add'; + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: formData + }); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${isEditMode ? '수정' : '추가'}에 실패했습니다.`); + } + + setShowEditModal(false); + await loadJobData(); + showNotification(`업무일지가 성공적으로 ${isEditMode ? '수정' : '추가'}되었습니다.`, 'success'); + + } catch (error) { + console.error('Error saving job:', error); + showNotification(`업무일지 ${isEditMode ? '수정' : '추가'} 중 오류가 발생했습니다: ` + error.message, 'error'); + } + }; + + // 삭제 처리 + const handleDelete = async () => { + if (!editData.idx) { + showNotification('삭제할 수 없는 항목입니다.', 'warning'); + return; + } + + if (!window.confirm('정말로 이 업무일지를 삭제하시겠습니까?')) { + return; + } + + try { + const response = await fetch(`/Jobreport/Delete/${editData.idx}`, { + method: 'DELETE' + }); + + if (!response.ok) { + throw new Error('삭제에 실패했습니다.'); + } + + const result = await response.json(); + + if (result.success) { + setShowEditModal(false); + await loadJobData(); + showNotification('업무일지가 성공적으로 삭제되었습니다.', 'success'); + } else { + throw new Error(result.message || '삭제에 실패했습니다.'); + } + + } catch (error) { + console.error('Error deleting job:', error); + showNotification('업무일지 삭제 중 오류가 발생했습니다: ' + error.message, 'error'); + } + }; + + // 엑셀 내보내기 + const exportToExcel = () => { + if (filteredData.length === 0) { + showNotification('내보낼 데이터가 없습니다.', 'warning'); + return; + } + + const periodText = filters.startDate && filters.endDate ? `_${filters.startDate}_${filters.endDate}` : ''; + const headers = ['날짜', '상태', '프로젝트명', '요청부서', '타입', '업무내용', '근무시간', '초과근무']; + const csvContent = [ + headers.join(','), + ...filteredData.map(item => [ + formatDate(item.pdate), + item.status || '', + item.projectName || '', + item.requestpart || '', + item.type || '', + `"${(item.description || '').replace(/"/g, '""')}"`, + item.hrs || '', + item.ot || '' + ].join(',')) + ].join('\n'); + + const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' }); + const link = document.createElement('a'); + const url = URL.createObjectURL(blob); + link.setAttribute('href', url); + link.setAttribute('download', `업무일지${periodText}_${new Date().toISOString().split('T')[0]}.csv`); + link.style.visibility = 'hidden'; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }; + + // 유틸리티 함수들 + const formatDate = (dateString) => { + if (!dateString) return '-'; + const date = new Date(dateString); + return date.toLocaleDateString('ko-KR'); + }; + + const getStatusColor = (status) => { + switch (status) { + case '진행 중': return 'bg-blue-100 text-blue-800'; + case '진행 완료': return 'bg-green-100 text-green-800'; + case '대기': return 'bg-yellow-100 text-yellow-800'; + default: return 'bg-gray-100 text-gray-800'; + } + }; + + // 알림 표시 함수 + const showNotification = (message, type = 'info') => { + const colors = { + info: 'bg-blue-500/90 backdrop-blur-sm', + success: 'bg-green-500/90 backdrop-blur-sm', + warning: 'bg-yellow-500/90 backdrop-blur-sm', + error: 'bg-red-500/90 backdrop-blur-sm' + }; + + const notification = document.createElement('div'); + notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-4 py-3 rounded-lg z-50 transition-all duration-300 transform translate-x-0 opacity-100 shadow-lg border border-white/20`; + notification.innerHTML = ` +
+ ${message} +
+ `; + + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + document.body.appendChild(notification); + + setTimeout(() => { + notification.style.transform = 'translateX(0)'; + notification.style.opacity = '1'; + }, 10); + + setTimeout(() => { + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + setTimeout(() => notification.remove(), 300); + }, 3000); + }; + + // 페이지네이션 + const maxPage = Math.ceil(filteredData.length / pageSize); + const startIndex = (currentPage - 1) * pageSize; + const endIndex = startIndex + pageSize; + const pageData = filteredData.slice(startIndex, endIndex); + + // 프로젝트 목록 업데이트 + const uniqueProjects = [...new Set(jobData.map(item => item.projectName).filter(Boolean))]; + + return ( +
+ {/* 개발중 경고 메시지 */} +
+
+ + + +
+

🚧 개발중인 기능입니다

+

일부 기능이 정상적으로 동작하지 않을 수 있습니다.

+
+
+
+ + {/* 통계 카드 */} +
+
+
+
+ + + +
+
+

총 업무일수

+

{statistics.totalDays}

+
+
+
+
+
+
+ + + +
+
+

오늘 근무시간

+

+ {statistics.todayHours.toFixed(1)}h +

+

(목표 8시간의 {statistics.todayProgress.toFixed(0)}%)

+
+
+
+
+
+
+ + + +
+
+

총 초과근무

+

{statistics.totalOT.toFixed(1)}h

+
+
+
+
+
+
+ + + +
+
+

진행중 프로젝트

+

{statistics.activeProjects}

+
+
+
+
+ + {/* 필터 및 검색 */} +
+
+
+ {/* 좌측: 필터 컨트롤 */} +
+
+
+ +
+ handleFilterChange('startDate', e.target.value)} + className="flex-1 bg-white/20 border border-white/30 rounded-md px-2 py-1 text-white placeholder-white/60 focus:outline-none focus:ring-1 focus:ring-white/50 focus:border-transparent text-xs" + /> + ~ + handleFilterChange('endDate', e.target.value)} + className="flex-1 bg-white/20 border border-white/30 rounded-md px-2 py-1 text-white placeholder-white/60 focus:outline-none focus:ring-1 focus:ring-white/50 focus:border-transparent text-xs" + /> +
+
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + handleFilterChange('search', e.target.value)} + placeholder="업무 내용 검색..." + className="w-full bg-white/20 border border-white/30 rounded-md px-2 py-1 text-white placeholder-white/60 focus:outline-none focus:ring-1 focus:ring-white/50 focus:border-transparent text-xs" + /> +
+
+
+ + {/* 우측: 액션 버튼들 */} +
+ + + +
+
+
+
+ + {/* 데이터 테이블 */} +
+
+ + + + + + + + + + + + + + {isLoading ? ( + + + + ) : pageData.length === 0 ? ( + + + + ) : ( + pageData.map((item, index) => { + const hrs = parseFloat(item.hrs) || 0; + const ot = parseFloat(item.ot) || 0; + let workTimeDisplay = ''; + + if (hrs > 0) { + workTimeDisplay = hrs.toFixed(1); + if (ot > 0) { + workTimeDisplay += '+' + ot.toFixed(1); + } + } else { + workTimeDisplay = '-'; + } + + return ( + showEditJobModal(item)} + > + + + + + + + + + ); + }) + )} + +
handleSort('pdate')} + > + 날짜 + + + handleSort('status')} + > + 상태 + + + handleSort('hrs')} + > + 근무시간 + + + handleSort('projectName')} + > + 프로젝트명 + + + 업무내용 handleSort('requestpart')} + > + 요청부서 + + + handleSort('type')} + > + 타입 + + +
+
+ + + + + 데이터를 불러오는 중... +
+
+ + + +

업무일지 데이터가 없습니다.

+
+ {formatDate(item.pdate)} + + + {item.status || '-'} + + + {workTimeDisplay} + +
+ {item.projectName || '-'} +
+
+
+ {item.description || '-'} +
+
+ {item.requestpart || '-'} + + {item.type || '-'} +
+
+
+ + {/* 페이지네이션 */} +
+
+ 페이지당 행 수: + +
+
+ + {currentPage} / {maxPage} + +
+
+ + {/* 편집 모달 */} + {showEditModal && ( +
+
+
+ {/* 모달 헤더 */} +
+

+ + + + 업무일지 {isEditMode ? '편집' : '추가'} +

+ +
+ + {/* 모달 내용 */} +
+
+ {/* 좌측: 기본 정보 */} +
+
+
+ + setEditData(prev => ({...prev, pdate: e.target.value}))} + required + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+ + +
+
+ + setEditData(prev => ({...prev, requestpart: e.target.value}))} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+ + +
+
+ + setEditData(prev => ({...prev, hrs: e.target.value}))} + required + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+ + setEditData(prev => ({...prev, ot: e.target.value}))} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+ + setEditData(prev => ({...prev, otStart: e.target.value}))} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+ + setEditData(prev => ({...prev, otEnd: e.target.value}))} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+
+ + {/* 우측: 프로젝트명과 업무내용 */} +
+
+ + setEditData(prev => ({...prev, projectName: e.target.value}))} + required + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+ + +
+ +
+ {currentProjectIdx && ( + + )} +
+ + +
+
+ +
+
+
+
+ )} + + {/* 삭제 확인 모달 */} + {showDeleteModal && ( +
+
+
+
+
+ + + +

삭제 확인

+
+

선택한 프로젝트를 삭제하시겠습니까?
이 작업은 되돌릴 수 없습니다.

+
+ + +
+
+
+
+
+ )} + + {/* 로딩 인디케이터 */} + {isLoading && ( +
+
+
+ 처리 중... +
+
+ )} + + {/* 외부 클릭시 드롭다운 닫기 */} + {showColumnDropdown && ( +
setShowColumnDropdown(false)} + >
+ )} +
+ ); +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/TestApp.jsx b/Project/Web/wwwroot/react/TestApp.jsx new file mode 100644 index 0000000..98eb025 --- /dev/null +++ b/Project/Web/wwwroot/react/TestApp.jsx @@ -0,0 +1,147 @@ +// TestApp.jsx - React Test Component for GroupWare +const { useState, useEffect } = React; + +function TestApp() { + const [status, setStatus] = useState('loading'); + const [counter, setCounter] = useState(0); + const [serverTime, setServerTime] = useState(''); + const [apiTest, setApiTest] = useState({ status: 'pending', message: '' }); + + // 컴포넌트가 마운트될 때 실행 + useEffect(() => { + // React가 정상적으로 로드되었음을 표시 + setTimeout(() => { + setStatus('success'); + setServerTime(new Date().toLocaleString('ko-KR')); + }, 1000); + + // API 테스트 + testAPI(); + }, []); + + // GroupWare API 테스트 함수 + const testAPI = async () => { + try { + // Home 컨트롤러 테스트 + const response = await fetch('/Home'); + if (response.ok) { + setApiTest({ status: 'success', message: 'API 연결 성공' }); + } else { + setApiTest({ status: 'warning', message: `API 응답: ${response.status}` }); + } + } catch (error) { + setApiTest({ status: 'error', message: `API 오류: ${error.message}` }); + } + }; + + const buttonStyle = { + padding: '10px 20px', + margin: '5px', + border: 'none', + borderRadius: '5px', + cursor: 'pointer', + fontSize: '14px' + }; + + return ( +
+
+ {status === 'success' ? ( +
+

✅ React 컴포넌트가 성공적으로 로드되었습니다!

+

현재 시간: {serverTime}

+

파일 위치: /react/TestApp.jsx

+
+ ) : ( +

React 컴포넌트를 로딩 중입니다...

+ )} +
+ + {status === 'success' && ( +
+
+

📊 상태 관리 테스트

+

카운터: {counter}

+ + + +
+ +
+

🌐 GroupWare API 연결 테스트

+

상태: {apiTest.message}

+

테스트 엔드포인트: /Home

+ +
+ +
+

📋 React + OWIN 통합 테스트 체크리스트

+
    +
  • ✅ OWIN 정적 파일 서빙
  • +
  • ✅ React 라이브러리 로딩 (CDN)
  • +
  • ✅ JSX 파일 분리 및 로딩
  • +
  • ✅ JSX 컴파일 (Babel)
  • +
  • ✅ React Hooks (useState, useEffect)
  • +
  • ✅ 이벤트 핸들링
  • +
  • ✅ API 호출 (fetch)
  • +
  • ✅ 반응형 UI 업데이트
  • +
  • ✅ 컴포넌트 모듈화
  • +
+
+ +
+

🎉 통합 테스트 결과

+

GroupWare + OWIN + React 환경이 성공적으로 구성되었습니다!

+

다음 단계:

+
    +
  • React Router 추가 (SPA 라우팅)
  • +
  • 상태 관리 라이브러리 추가 (Redux/Zustand)
  • +
  • UI 컴포넌트 라이브러리 추가 (Material-UI/Ant Design)
  • +
  • 번들링 도구 설정 (Webpack/Vite)
  • +
  • TypeScript 지원 추가
  • +
+
+
+ )} +
+ ); +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/Todo.jsx b/Project/Web/wwwroot/react/Todo.jsx new file mode 100644 index 0000000..b62990c --- /dev/null +++ b/Project/Web/wwwroot/react/Todo.jsx @@ -0,0 +1,811 @@ +const { useState, useEffect } = React; + +function Todo() { + // 상태 관리 + const [todos, setTodos] = useState([]); + const [activeTodos, setActiveTodos] = useState([]); + const [completedTodos, setCompletedTodos] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [currentTab, setCurrentTab] = useState('active'); + const [currentEditId, setCurrentEditId] = useState(null); + + // 모달 상태 + const [showAddModal, setShowAddModal] = useState(false); + const [showEditModal, setShowEditModal] = useState(false); + + // 폼 상태 + const [todoForm, setTodoForm] = useState({ + title: '', + remark: '', + expire: '', + seqno: 0, + flag: false, + request: '', + status: '0' + }); + + const [editForm, setEditForm] = useState({ + idx: 0, + title: '', + remark: '', + expire: '', + seqno: 0, + flag: false, + request: '', + status: '0' + }); + + // 컴포넌트 마운트시 할일 목록 로드 + useEffect(() => { + loadTodos(); + }, []); + + // 할일 목록을 활성/완료로 분리 + useEffect(() => { + const active = todos.filter(todo => (todo.status || '0') !== '5'); + const completed = todos.filter(todo => (todo.status || '0') === '5'); + setActiveTodos(active); + setCompletedTodos(completed); + }, [todos]); + + // 할일 목록 로드 + const loadTodos = async () => { + setIsLoading(true); + try { + const response = await fetch('/Todo/GetTodos'); + const data = await response.json(); + + if (data.Success) { + setTodos(data.Data || []); + } else { + showNotification(data.Message || '할일 목록을 불러올 수 없습니다.', 'error'); + } + } catch (error) { + console.error('할일 목록 로드 중 오류:', error); + showNotification('서버 연결에 실패했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 새 할일 추가 + const addTodo = async (e) => { + e.preventDefault(); + + if (!todoForm.remark.trim()) { + showNotification('할일 내용을 입력해주세요.', 'error'); + return; + } + + setIsLoading(true); + try { + const response = await fetch('/Todo/CreateTodo', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + ...todoForm, + seqno: parseInt(todoForm.seqno), + expire: todoForm.expire || null, + request: todoForm.request || null + }) + }); + + const data = await response.json(); + + if (data.Success) { + setShowAddModal(false); + setTodoForm({ + title: '', + remark: '', + expire: '', + seqno: 0, + flag: false, + request: '', + status: '0' + }); + loadTodos(); + showNotification(data.Message || '할일이 추가되었습니다.', 'success'); + } else { + showNotification(data.Message || '할일 추가에 실패했습니다.', 'error'); + } + } catch (error) { + console.error('할일 추가 중 오류:', error); + showNotification('서버 연결에 실패했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 할일 수정 + const updateTodo = async () => { + if (!editForm.remark.trim()) { + showNotification('할일 내용을 입력해주세요.', 'error'); + return; + } + + setIsLoading(true); + try { + const response = await fetch('/Todo/UpdateTodo', { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + ...editForm, + seqno: parseInt(editForm.seqno), + expire: editForm.expire || null, + request: editForm.request || null + }) + }); + + const data = await response.json(); + + if (data.Success) { + setShowEditModal(false); + setCurrentEditId(null); + loadTodos(); + showNotification(data.Message || '할일이 수정되었습니다.', 'success'); + } else { + showNotification(data.Message || '할일 수정에 실패했습니다.', 'error'); + } + } catch (error) { + console.error('할일 수정 중 오류:', error); + showNotification('서버 연결에 실패했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 상태 업데이트 (편집 모달에서 바로 서버에 반영) + const updateTodoStatus = async (status) => { + if (!currentEditId) return; + + const formData = { + ...editForm, + status: status, + seqno: parseInt(editForm.seqno), + expire: editForm.expire || null, + request: editForm.request || null + }; + + if (!formData.remark.trim()) { + showNotification('할일 내용을 입력해주세요.', 'error'); + return; + } + + setIsLoading(true); + try { + const response = await fetch('/Todo/UpdateTodo', { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(formData) + }); + + const data = await response.json(); + + if (data.Success) { + setShowEditModal(false); + setCurrentEditId(null); + loadTodos(); + showNotification(`상태가 '${getStatusText(status)}'(으)로 변경되었습니다.`, 'success'); + } else { + showNotification(data.Message || '상태 변경에 실패했습니다.', 'error'); + } + } catch (error) { + console.error('상태 변경 중 오류:', error); + showNotification('서버 연결에 실패했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 할일 편집 모달 열기 + const editTodo = async (id) => { + setCurrentEditId(id); + setIsLoading(true); + + try { + const response = await fetch(`/Todo/GetTodo?id=${id}`); + const data = await response.json(); + + if (data.Success && data.Data) { + const todo = data.Data; + setEditForm({ + idx: todo.idx, + title: todo.title || '', + remark: todo.remark || '', + expire: todo.expire ? new Date(todo.expire).toISOString().split('T')[0] : '', + seqno: todo.seqno || 0, + flag: todo.flag || false, + request: todo.request || '', + status: todo.status || '0' + }); + setShowEditModal(true); + } else { + showNotification(data.Message || '할일 정보를 불러올 수 없습니다.', 'error'); + } + } catch (error) { + console.error('할일 조회 중 오류:', error); + showNotification('서버 연결에 실패했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 할일 삭제 + const deleteTodo = async (id) => { + if (!confirm('정말로 이 할일을 삭제하시겠습니까?')) { + return; + } + + setIsLoading(true); + try { + const response = await fetch(`/Todo/DeleteTodo?id=${id}`, { + method: 'DELETE' + }); + + const data = await response.json(); + + if (data.Success) { + loadTodos(); + showNotification(data.Message || '할일이 삭제되었습니다.', 'success'); + } else { + showNotification(data.Message || '할일 삭제에 실패했습니다.', 'error'); + } + } catch (error) { + console.error('할일 삭제 중 오류:', error); + showNotification('서버 연결에 실패했습니다.', 'error'); + } finally { + setIsLoading(false); + } + }; + + // 유틸리티 함수들 + const getStatusClass = (status) => { + switch(status) { + case '0': return 'bg-gray-500/20 text-gray-300'; + case '1': return 'bg-primary-500/20 text-primary-300'; + case '2': return 'bg-danger-500/20 text-danger-300'; + case '3': return 'bg-warning-500/20 text-warning-300'; + case '5': return 'bg-success-500/20 text-success-300'; + default: return 'bg-white/10 text-white/50'; + } + }; + + const getStatusText = (status) => { + switch(status) { + case '0': return '대기'; + case '1': return '진행'; + case '2': return '취소'; + case '3': return '보류'; + case '5': return '완료'; + default: return '대기'; + } + }; + + const getSeqnoClass = (seqno) => { + switch(seqno) { + case 1: return 'bg-primary-500/20 text-primary-300'; + case 2: return 'bg-warning-500/20 text-warning-300'; + case 3: return 'bg-danger-500/20 text-danger-300'; + default: return 'bg-white/10 text-white/50'; + } + }; + + const getSeqnoText = (seqno) => { + switch(seqno) { + case 1: return '중요'; + case 2: return '매우 중요'; + case 3: return '긴급'; + default: return '보통'; + } + }; + + const formatDate = (dateString) => { + if (!dateString) return '-'; + return new Date(dateString).toLocaleDateString('ko-KR'); + }; + + // 알림 표시 함수 + const showNotification = (message, type = 'info') => { + const colors = { + info: 'bg-blue-500/90 backdrop-blur-sm', + success: 'bg-green-500/90 backdrop-blur-sm', + warning: 'bg-yellow-500/90 backdrop-blur-sm', + error: 'bg-red-500/90 backdrop-blur-sm' + }; + + const notification = document.createElement('div'); + notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-4 py-3 rounded-lg z-50 transition-all duration-300 transform translate-x-0 opacity-100 shadow-lg border border-white/20`; + notification.innerHTML = ` +
+ ${message} +
+ `; + + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + document.body.appendChild(notification); + + setTimeout(() => { + notification.style.transform = 'translateX(0)'; + notification.style.opacity = '1'; + }, 10); + + setTimeout(() => { + notification.style.transform = 'translateX(100%)'; + notification.style.opacity = '0'; + setTimeout(() => notification.remove(), 300); + }, 3000); + }; + + // 할일 행 렌더링 + const renderTodoRow = (todo, includeOkdate = false) => { + const statusClass = getStatusClass(todo.status); + const statusText = getStatusText(todo.status); + + const flagClass = todo.flag ? 'bg-warning-500/20 text-warning-300' : 'bg-white/10 text-white/50'; + const flagText = todo.flag ? '고정' : '일반'; + + const seqnoClass = getSeqnoClass(todo.seqno); + const seqnoText = getSeqnoText(todo.seqno); + + const expireText = formatDate(todo.expire); + const isExpired = todo.expire && new Date(todo.expire) < new Date(); + const expireClass = isExpired ? 'text-danger-400' : 'text-white/80'; + + const okdateText = formatDate(todo.okdate); + const okdateClass = todo.okdate ? 'text-success-400' : 'text-white/80'; + + return ( + editTodo(todo.idx)}> + + + {statusText} + + + + + {flagText} + + + {todo.title || '제목 없음'} + {todo.remark || ''} + {todo.request || '-'} + + + {seqnoText} + + + {expireText} + {includeOkdate && {okdateText}} + e.stopPropagation()}> + + + + + ); + }; + + return ( +
+ {/* 할일 목록 */} +
+
+

+ + + + 내 할일 목록 +

+ +
+ + {/* 탭 메뉴 */} +
+
+ + +
+
+ + {/* 진행중인 할일 테이블 */} + {currentTab === 'active' && ( +
+ + + + + + + + + + + + + + + {isLoading ? ( + + + + ) : activeTodos.length === 0 ? ( + + + + ) : ( + activeTodos.map(todo => renderTodoRow(todo, false)) + )} + +
진행상태플래그제목내용요청자중요도만료일작업
+
+
+ 데이터를 불러오는 중... +
+
+ 진행중인 할일이 없습니다 +
+
+ )} + + {/* 완료된 할일 테이블 */} + {currentTab === 'completed' && ( +
+ + + + + + + + + + + + + + + + {isLoading ? ( + + + + ) : completedTodos.length === 0 ? ( + + + + ) : ( + completedTodos.map(todo => renderTodoRow(todo, true)) + )} + +
진행상태플래그제목내용요청자중요도만료일완료일작업
+
+
+ 데이터를 불러오는 중... +
+
+ 완료된 할일이 없습니다 +
+
+ )} +
+ + {/* 로딩 인디케이터 */} + {isLoading && ( +
+
+
+ 처리 중... +
+
+ )} + + {/* 새 할일 추가 모달 */} + {showAddModal && ( +
+
+
+ {/* 모달 헤더 */} +
+

+ + + + 새 할일 추가 +

+ +
+ + {/* 모달 내용 */} +
+
+
+
+ + setTodoForm({...todoForm, title: e.target.value})} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="할일 제목을 입력하세요" + /> +
+
+ + setTodoForm({...todoForm, expire: e.target.value})} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+
+ + +
+
+ + setTodoForm({...todoForm, request: e.target.value})} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="업무 요청자를 입력하세요" + /> +
+
+
+ +
+ {[ + {value: '0', label: '대기', class: 'bg-gray-500/20 text-gray-300'}, + {value: '1', label: '진행', class: 'bg-primary-500/20 text-primary-300'}, + {value: '3', label: '보류', class: 'bg-warning-500/20 text-warning-300'}, + {value: '2', label: '취소', class: 'bg-danger-500/20 text-danger-300'}, + {value: '5', label: '완료', class: 'bg-success-500/20 text-success-300'} + ].map(status => ( + + ))} +
+
+
+ + +
+
+ +
+
+
+
+ + {/* 모달 푸터 */} +
+ + +
+
+
+
+ )} + + {/* 수정 모달 */} + {showEditModal && ( +
+
+
+ {/* 모달 헤더 */} +
+

+ + + + 할일 수정 +

+ +
+ + {/* 모달 내용 */} +
+
+
+
+ + setEditForm({...editForm, title: e.target.value})} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="할일 제목을 입력하세요" + /> +
+
+ + setEditForm({...editForm, expire: e.target.value})} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + /> +
+
+
+ + +
+
+ + setEditForm({...editForm, request: e.target.value})} + className="w-full bg-white/20 backdrop-blur-sm border border-white/30 rounded-lg px-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400 transition-all" + placeholder="업무 요청자를 입력하세요" + /> +
+
+
+ +
+ {[ + {value: '0', label: '대기', class: 'bg-gray-500/20 text-gray-300'}, + {value: '1', label: '진행', class: 'bg-primary-500/20 text-primary-300'}, + {value: '3', label: '보류', class: 'bg-warning-500/20 text-warning-300'}, + {value: '2', label: '취소', class: 'bg-danger-500/20 text-danger-300'}, + {value: '5', label: '완료', class: 'bg-success-500/20 text-success-300'} + ].map(status => ( + + ))} +
+
+
+ + +
+
+ +
+
+
+
+ + {/* 모달 푸터 */} +
+ + +
+
+
+
+ )} +
+ ); +} \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-common.html b/Project/Web/wwwroot/react/react-common.html new file mode 100644 index 0000000..01f0dd2 --- /dev/null +++ b/Project/Web/wwwroot/react/react-common.html @@ -0,0 +1,270 @@ + + + + + + + + + 공용코드관리 (React) + + + + + + + + + + +
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-dashboard.html b/Project/Web/wwwroot/react/react-dashboard.html new file mode 100644 index 0000000..59e912c --- /dev/null +++ b/Project/Web/wwwroot/react/react-dashboard.html @@ -0,0 +1,297 @@ + + + + + + + + + + 근태현황 대시보드 (React) + + + + + + + +
+ +
+
+ +
+
+
+
+
+ + +
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+ + +
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+ + +
+
+

React Dashboard 컴포넌트를 로딩 중입니다...

+
+
+
+
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-jobreport.html b/Project/Web/wwwroot/react/react-jobreport.html new file mode 100644 index 0000000..2459f82 --- /dev/null +++ b/Project/Web/wwwroot/react/react-jobreport.html @@ -0,0 +1,261 @@ + + + + + + + + + 업무일지 (React) + + + + + + + + +
+
+ {/* 스켈레톤 UI */} +
+ {/* 경고 메시지 스켈레톤 */} +
+
+
+ + {/* 통계 카드 스켈레톤 */} +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + {/* 필터 스켈레톤 */} +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + {/* 테이블 스켈레톤 */} +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-jsx-test.html b/Project/Web/wwwroot/react/react-jsx-test.html new file mode 100644 index 0000000..ebfbac9 --- /dev/null +++ b/Project/Web/wwwroot/react/react-jsx-test.html @@ -0,0 +1,120 @@ + + + + + + React JSX Test - GroupWare + + + +
+
+

🚀 React JSX Integration

+

GroupWare + OWIN + React + JSX 모듈화 테스트

+
+ 기술 스택: C# WinForms + OWIN + React 18 + Babel JSX + 모듈화된 컴포넌트 +
+
+ +
+
+ React JSX 컴포넌트를 로딩 중입니다... +
+
+ +
+

환경: .NET Framework 4.6 + OWIN + React 18.2.0

+

포트: 7979 | 파일 위치: /react-jsx-test.html

+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-kuntae.html b/Project/Web/wwwroot/react/react-kuntae.html new file mode 100644 index 0000000..12e9cf1 --- /dev/null +++ b/Project/Web/wwwroot/react/react-kuntae.html @@ -0,0 +1,241 @@ + + + + + + + + + 근태관리 (React) + + + + + + + +
+
+
+ {/* 경고 메시지 스켈레톤 */} +
+
+
+ + {/* 필터 스켈레톤 */} +
+
+
+
+
+
+
+ + {/* 통계 카드 스켈레톤 */} +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + {/* 테이블 스켈레톤 */} +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-login.html b/Project/Web/wwwroot/react/react-login.html new file mode 100644 index 0000000..9319d29 --- /dev/null +++ b/Project/Web/wwwroot/react/react-login.html @@ -0,0 +1,177 @@ + + + + + + 로그인 - GroupWare (React) + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-project.html b/Project/Web/wwwroot/react/react-project.html new file mode 100644 index 0000000..cd17168 --- /dev/null +++ b/Project/Web/wwwroot/react/react-project.html @@ -0,0 +1,191 @@ + + + + + + 프로젝트 관리 - GroupWare (React) + + + + + +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-test.html b/Project/Web/wwwroot/react/react-test.html new file mode 100644 index 0000000..1c56cf1 --- /dev/null +++ b/Project/Web/wwwroot/react/react-test.html @@ -0,0 +1,197 @@ + + + + + + React Test Page - GroupWare + + + +
+
+

🚀 React Integration Test

+

GroupWare + OWIN + React 통합 테스트

+
+ +
+
+ React 컴포넌트를 로딩 중입니다... +
+
+
+ + + + + + + + + + + \ No newline at end of file diff --git a/Project/Web/wwwroot/react/react-todo.html b/Project/Web/wwwroot/react/react-todo.html new file mode 100644 index 0000000..2f1f3c4 --- /dev/null +++ b/Project/Web/wwwroot/react/react-todo.html @@ -0,0 +1,115 @@ + + + + + + + + + + 할일 관리 - GroupWare (React) + + + + + +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Sub/Console_SendMail/Console_SendMail.csproj b/Sub/Console_SendMail/Console_SendMail.csproj index 35a3f4f..bef7553 100644 --- a/Sub/Console_SendMail/Console_SendMail.csproj +++ b/Sub/Console_SendMail/Console_SendMail.csproj @@ -35,6 +35,7 @@ + @@ -49,6 +50,9 @@ True True + + Component + diff --git a/Sub/Console_SendMail/InstallService.bat b/Sub/Console_SendMail/InstallService.bat new file mode 100644 index 0000000..e42074f --- /dev/null +++ b/Sub/Console_SendMail/InstallService.bat @@ -0,0 +1,36 @@ +@echo off +echo EETGW Mail Service 설치 중... + +REM 관리자 권한 확인 +net session >nul 2>&1 +if %errorLevel% == 0 ( + echo 관리자 권한이 확인되었습니다. +) else ( + echo 이 스크립트는 관리자 권한으로 실행해야 합니다. + echo 관리자 권한으로 다시 실행해주세요. + pause + exit /b 1 +) + +REM 서비스 설치 +Console_SendMail.exe -install + +if %errorLevel% == 0 ( + echo. + echo 서비스 설치가 완료되었습니다. + echo 서비스를 시작하시겠습니까? (Y/N) + set /p choice="선택: " + if /i "%choice%"=="Y" ( + net start EETGWMailService + if %errorLevel% == 0 ( + echo 서비스가 성공적으로 시작되었습니다. + ) else ( + echo 서비스 시작에 실패했습니다. + ) + ) +) else ( + echo 서비스 설치에 실패했습니다. +) + +echo. +pause \ No newline at end of file diff --git a/Sub/Console_SendMail/MailService.cs b/Sub/Console_SendMail/MailService.cs new file mode 100644 index 0000000..37dbff1 --- /dev/null +++ b/Sub/Console_SendMail/MailService.cs @@ -0,0 +1,112 @@ +using System; +using System.ServiceProcess; +using System.Threading; +using System.Threading.Tasks; +using System.Diagnostics; + +namespace Console_SendMail +{ + public partial class MailService : ServiceBase + { + private CancellationTokenSource _cancellationTokenSource; + private Task _serviceTask; + + public MailService() + { + InitializeComponent(); + ServiceName = "EETGWMailService"; + CanStop = true; + CanPauseAndContinue = false; + AutoLog = true; + } + + protected override void OnStart(string[] args) + { + try + { + EventLog.WriteEntry(ServiceName, "메일 서비스가 시작됩니다.", EventLogEntryType.Information); + + _cancellationTokenSource = new CancellationTokenSource(); + _serviceTask = Task.Run(() => DoWork(_cancellationTokenSource.Token)); + + EventLog.WriteEntry(ServiceName, "메일 서비스가 성공적으로 시작되었습니다.", EventLogEntryType.Information); + } + catch (Exception ex) + { + EventLog.WriteEntry(ServiceName, $"서비스 시작 중 오류 발생: {ex.Message}", EventLogEntryType.Error); + throw; + } + } + + protected override void OnStop() + { + try + { + EventLog.WriteEntry(ServiceName, "메일 서비스를 중지합니다.", EventLogEntryType.Information); + + _cancellationTokenSource?.Cancel(); + + if (_serviceTask != null) + { + // 최대 30초 대기 + if (!_serviceTask.Wait(TimeSpan.FromSeconds(30))) + { + EventLog.WriteEntry(ServiceName, "서비스 중지 시간 초과", EventLogEntryType.Warning); + } + } + + EventLog.WriteEntry(ServiceName, "메일 서비스가 중지되었습니다.", EventLogEntryType.Information); + } + catch (Exception ex) + { + EventLog.WriteEntry(ServiceName, $"서비스 중지 중 오류 발생: {ex.Message}", EventLogEntryType.Error); + } + finally + { + _cancellationTokenSource?.Dispose(); + _serviceTask?.Dispose(); + } + } + + private void DoWork(CancellationToken cancellationToken) + { + // 기존 프로그램의 while 루프 로직을 여기로 이동 + EventLog.WriteEntry(ServiceName, "메일 서비스 작업을 시작합니다.", EventLogEntryType.Information); + + while (!cancellationToken.IsCancellationRequested) + { + try + { + // 기존 메일 처리 로직 실행 + Program.ExecuteMailOperations(); + + // 1초 대기 (cancellation token으로 중단 가능) + if (cancellationToken.WaitHandle.WaitOne(1000)) + { + break; // 취소 요청 시 종료 + } + } + catch (Exception ex) + { + EventLog.WriteEntry(ServiceName, $"메일 처리 중 오류 발생: {ex.Message}", EventLogEntryType.Error); + + // 오류 발생 시 5초 대기 후 재시도 + if (cancellationToken.WaitHandle.WaitOne(5000)) + { + break; + } + } + } + + EventLog.WriteEntry(ServiceName, "메일 서비스 작업이 종료되었습니다.", EventLogEntryType.Information); + } + + private void InitializeComponent() + { + // + // MailService + // + this.ServiceName = "EETGWMailService"; + } + } +} \ No newline at end of file diff --git a/Sub/Console_SendMail/Program.cs b/Sub/Console_SendMail/Program.cs index 4b88751..e95e57d 100644 --- a/Sub/Console_SendMail/Program.cs +++ b/Sub/Console_SendMail/Program.cs @@ -1,8 +1,12 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; +using System.ServiceProcess; using System.Text; +using System.Threading; using System.Threading.Tasks; +using static System.Net.Mime.MediaTypeNames; namespace Console_SendMail { @@ -62,116 +66,288 @@ namespace Console_SendMail return list_to; } - - static void Main(string[] args) { - - Console.WriteLine($"mail start ver 2508051140"); - while (true) + // 명령행 인수 처리 + if (args.Length > 0) { - - //메일대기내역전송 - var tsSendMail = DateTime.Now - ChkSendMailTime; - if (tsSendMail.TotalMilliseconds > 1000) + string command = args[0].ToLower(); + switch (command) { - try { SendMail(); } - catch { } - finally { ChkSendMailTime = DateTime.Now; } + case "-install": + case "/install": + InstallService(); + return; + case "-uninstall": + case "/uninstall": + UninstallService(); + return; + case "-console": + case "/console": + RunAsConsole(); + return; + case "-help": + case "/help": + case "/?": + ShowHelp(); + return; } - - //자동생성 메일 작성 - var tsAutoMake = DateTime.Now - ChkMakeAutoTime; - if (tsAutoMake.TotalMinutes >= 10) - { - try { MakeAutoMail(); } - catch { } - finally { ChkMakeAutoTime = DateTime.Now; } - } - - //프로젝트업데이트알림 - var tsPrjUpdateweek = DateTime.Now - ChkMakePrjUpdateWeekTime; - if (tsPrjUpdateweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) - { - - try { Mail_MakeUpdateRequireProject(); } - catch { } - finally { ChkMakePrjUpdateWeekTime = DateTime.Now; } - } - - ///스케쥴 기한 알림(주) - var tsScheDayweek = DateTime.Now - ChkMakeSchDayWeekTime; - if (tsScheDayweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) - { - - try { Mail_MakeScheduleDayWeek(); } - catch { } - finally { ChkMakeSchDayWeekTime = DateTime.Now; } - } - - - ///스케쥴 기한 알림(일) - var tsScheDay = DateTime.Now - ChkMakeSchDay; - if (tsScheDay.TotalMinutes > 30 && DateTime.Now.DayOfWeek != DayOfWeek.Saturday && - DateTime.Now.DayOfWeek != DayOfWeek.Sunday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) - { - - try { Mail_MakeScheduleDay(); } - catch { } - finally { ChkMakeSchDay = DateTime.Now; } - } - - ///스케쥴없음 - var tsNoSchedule = DateTime.Now - ChkNoSchedule; - if (tsNoSchedule.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) - { - - try { Mail_NoSchedule(); } - catch { } - finally { ChkNoSchedule = DateTime.Now; } - } - - ///업무일지(주간) - var tsjobweek = DateTime.Now - ChkJObreportWeek; - if (tsjobweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) - { - - try { Mail_JobReportWeek(); } - catch { } - finally { ChkJObreportWeek = DateTime.Now; } - } - - ///업무일지(일) - var tsjobday = DateTime.Now - ChkJobreportDay; - if (tsjobday.TotalMinutes > 15 && - DateTime.Now.DayOfWeek != DayOfWeek.Saturday && - DateTime.Now.DayOfWeek != DayOfWeek.Sunday && - DateTime.Now.DayOfWeek != DayOfWeek.Monday && - DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) - { - - try { Mail_JobReportDay(); } - catch { } - finally { ChkJobreportDay = DateTime.Now; } - } - - ///휴가신청(Remind) - 230611 - var tsTakeaRest = DateTime.Now - ChkTakeARest; - if (tsTakeaRest.TotalMinutes > 15 && - DateTime.Now.DayOfWeek != DayOfWeek.Saturday && - DateTime.Now.DayOfWeek != DayOfWeek.Sunday && - DateTime.Now.Hour >= 17) - { - - try { Mail_Take_a_rest_remind(); } - catch { } - finally { ChkTakeARest = DateTime.Now; } - } - } - Console.WriteLine("mail end"); + // 서비스로 실행 + if (Environment.UserInteractive) + { + // 대화형 모드에서는 콘솔로 실행 + RunAsConsole(); + } + else + { + // 서비스로 실행 + ServiceBase[] ServicesToRun; + ServicesToRun = new ServiceBase[] + { + new MailService() + }; + ServiceBase.Run(ServicesToRun); + } } + private static void ShowHelp() + { + Console.WriteLine("EETGW Mail Service"); + Console.WriteLine("사용법:"); + Console.WriteLine(" Console_SendMail.exe - 서비스로 실행"); + Console.WriteLine(" Console_SendMail.exe -console - 콘솔 모드로 실행"); + Console.WriteLine(" Console_SendMail.exe -install - 서비스 설치"); + Console.WriteLine(" Console_SendMail.exe -uninstall - 서비스 제거"); + Console.WriteLine(" Console_SendMail.exe -help - 도움말 표시"); + } + + private static void InstallService() + { + try + { + string servicePath = $"\"{System.Reflection.Assembly.GetExecutingAssembly().Location}\""; + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "sc.exe", + Arguments = $"create EETGWMailService binPath= \"{servicePath}\" DisplayName= \"EETGW Mail Service\" start= auto", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + if (process.ExitCode == 0) + { + Console.WriteLine("서비스가 성공적으로 설치되었습니다."); + Console.WriteLine("서비스를 시작하려면 다음 명령을 실행하세요:"); + Console.WriteLine("net start EETGWMailService"); + } + else + { + string error = process.StandardError.ReadToEnd(); + Console.WriteLine($"서비스 설치 실패: {error}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"서비스 설치 중 오류 발생: {ex.Message}"); + } + } + + private static void UninstallService() + { + try + { + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "sc.exe", + Arguments = "delete EETGWMailService", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + if (process.ExitCode == 0) + { + Console.WriteLine("서비스가 성공적으로 제거되었습니다."); + } + else + { + string error = process.StandardError.ReadToEnd(); + Console.WriteLine($"서비스 제거 실패: {error}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"서비스 제거 중 오류 발생: {ex.Message}"); + } + } + + private static void RunAsConsole() + { + // 중복실행 방지 체크 + if (!CheckSingleInstance()) + { + return; // 프로그램 종료 + } + + Console.WriteLine($"mail start ver 2508051140 (콘솔 모드)"); + Console.WriteLine("종료하려면 Ctrl+C를 누르세요."); + + // Ctrl+C 핸들러 설정 + Console.CancelKeyPress += (sender, e) => + { + Console.WriteLine("\n메일 서비스를 종료합니다..."); + e.Cancel = false; + }; + + try + { + while (true) + { + ExecuteMailOperations(); + Thread.Sleep(1000); // 1초 대기 + } + } + catch (Exception ex) + { + Console.WriteLine($"오류 발생: {ex.Message}"); + } + finally + { + Console.WriteLine("mail end"); + } + } + + /// + /// 메일 관련 작업들을 실행하는 메서드 (서비스와 콘솔에서 공통 사용) + /// + public static void ExecuteMailOperations() + { + //메일대기내역전송 + var tsSendMail = DateTime.Now - ChkSendMailTime; + if (tsSendMail.TotalMilliseconds > 1000) + { + try { SendMail(); } + catch { } + finally { ChkSendMailTime = DateTime.Now; } + } + + //자동생성 메일 작성 + var tsAutoMake = DateTime.Now - ChkMakeAutoTime; + if (tsAutoMake.TotalMinutes >= 10) + { + try { MakeAutoMail(); } + catch { } + finally { ChkMakeAutoTime = DateTime.Now; } + } + + //프로젝트업데이트알림 + var tsPrjUpdateweek = DateTime.Now - ChkMakePrjUpdateWeekTime; + if (tsPrjUpdateweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) + { + try { Mail_MakeUpdateRequireProject(); } + catch { } + finally { ChkMakePrjUpdateWeekTime = DateTime.Now; } + } + + ///스케쥴 기한 알림(주) + var tsScheDayweek = DateTime.Now - ChkMakeSchDayWeekTime; + if (tsScheDayweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) + { + try { Mail_MakeScheduleDayWeek(); } + catch { } + finally { ChkMakeSchDayWeekTime = DateTime.Now; } + } + + ///스케쥴 기한 알림(일) + var tsScheDay = DateTime.Now - ChkMakeSchDay; + if (tsScheDay.TotalMinutes > 30 && DateTime.Now.DayOfWeek != DayOfWeek.Saturday && + DateTime.Now.DayOfWeek != DayOfWeek.Sunday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) + { + try { Mail_MakeScheduleDay(); } + catch { } + finally { ChkMakeSchDay = DateTime.Now; } + } + + ///스케쥴없음 + var tsNoSchedule = DateTime.Now - ChkNoSchedule; + if (tsNoSchedule.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18) + { + try { Mail_NoSchedule(); } + catch { } + finally { ChkNoSchedule = DateTime.Now; } + } + + ///업무일지(주간) + var tsjobweek = DateTime.Now - ChkJObreportWeek; + if (tsjobweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) + { + try { Mail_JobReportWeek(); } + catch { } + finally { ChkJObreportWeek = DateTime.Now; } + } + + ///업무일지(일) + var tsjobday = DateTime.Now - ChkJobreportDay; + if (tsjobday.TotalMinutes > 15 && + DateTime.Now.DayOfWeek != DayOfWeek.Saturday && + DateTime.Now.DayOfWeek != DayOfWeek.Sunday && + DateTime.Now.DayOfWeek != DayOfWeek.Monday && + DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) + { + try { Mail_JobReportDay(); } + catch { } + finally { ChkJobreportDay = DateTime.Now; } + } + + ///휴가신청(Remind) - 230611 + var tsTakeaRest = DateTime.Now - ChkTakeARest; + if (tsTakeaRest.TotalMinutes > 15 && + DateTime.Now.DayOfWeek != DayOfWeek.Saturday && + DateTime.Now.DayOfWeek != DayOfWeek.Sunday && + DateTime.Now.Hour >= 17) + { + try { Mail_Take_a_rest_remind(); } + catch { } + finally { ChkTakeARest = DateTime.Now; } + } + } + + /// + /// 중복실행 방지 체크 + /// + /// 단일 인스턴스인 경우 true, 중복실행인 경우 false + static bool CheckSingleInstance() + { + string processName = Process.GetCurrentProcess().ProcessName; + Process[] processes = Process.GetProcessesByName(processName); + + if (processes.Length > 1) + { + // 중복실행 감지 + string message = $"⚠️ 프로그램이 이미 실행 중입니다!\n\n" + + "동시에 여러 개의 프로그램을 실행할 수 없습니다.\n\n" + + "해결방법을 선택하세요:"; + + Console.WriteLine(message); + // 현재 실행을 취소 + return false; + + } + + return true; // 단일 인스턴스 + } } } diff --git a/Sub/Console_SendMail/RunConsole.bat b/Sub/Console_SendMail/RunConsole.bat new file mode 100644 index 0000000..ffe3a2b --- /dev/null +++ b/Sub/Console_SendMail/RunConsole.bat @@ -0,0 +1,7 @@ +@echo off +echo EETGW Mail Service - 콘솔 모드로 실행 + +REM 콘솔 모드로 실행 +Console_SendMail.exe -console + +pause \ No newline at end of file diff --git a/Sub/Console_SendMail/UninstallService.bat b/Sub/Console_SendMail/UninstallService.bat new file mode 100644 index 0000000..a9dd751 --- /dev/null +++ b/Sub/Console_SendMail/UninstallService.bat @@ -0,0 +1,34 @@ +@echo off +echo EETGW Mail Service 제거 중... + +REM 관리자 권한 확인 +net session >nul 2>&1 +if %errorLevel% == 0 ( + echo 관리자 권한이 확인되었습니다. +) else ( + echo 이 스크립트는 관리자 권한으로 실행해야 합니다. + echo 관리자 권한으로 다시 실행해주세요. + pause + exit /b 1 +) + +REM 서비스 중지 +echo 서비스를 중지합니다... +net stop EETGWMailService 2>nul +if %errorLevel% == 0 ( + echo 서비스가 중지되었습니다. +) else ( + echo 서비스가 실행 중이 아니거나 중지에 실패했습니다. +) + +REM 서비스 제거 +Console_SendMail.exe -uninstall + +if %errorLevel% == 0 ( + echo 서비스 제거가 완료되었습니다. +) else ( + echo 서비스 제거에 실패했습니다. +) + +echo. +pause \ No newline at end of file