momentic 2.138.2 → 2.138.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="56954989-257d-5a8f-8880-8804bf12978d")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="066a2024-d456-59be-9d76-b49981e0d2b0")}catch(e){}}();
4
4
  import * as Mo from 'fs';
5
5
  import Mo__default, { statSync, mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, renameSync, readdir, readdirSync, createReadStream, rmSync } from 'fs';
6
6
  import * as w from 'zod';
@@ -161,7 +161,7 @@ ${this.decisions.map(t=>t.toString()).join(`
161
161
  `).map((o,r)=>r>0?`${n}${o}`:o).join(`
162
162
  `)}logWithLevelHelper(t,n,...o){if(t<this.minLogLevel)return;let r=this.forcedStream??(t>=40?"stderr":"stdout"),i=(...d)=>r==="stderr"?console.error(...d):console.log(...d),s;Array.isArray(o[0])?(s=o[0],o=o.slice(1)):typeof o[0]=="object"&&!(o[0]instanceof Error)&&Object.entries(o[0]).length&&(s={...o[0],...this.logBindings},o=o.slice(1));let a=Qs.level===0,l=a&&t===50?"Error:":a&&t===40?"Warning:":"",c=[];if(l&&c.push(l),c.push(...o),i(n(...c)),s&&!Array.isArray(s)){let d=Object.entries(s);for(let[u,p]of d){let m=p;if(p instanceof Error){m=p.message,i(n(` ${u}:`,m)),i(n(" stack:",p.stack));let g=Object.entries(p).filter(([f])=>f!=="message"&&f!=="stack");for(let[f,b]of g){if(b instanceof Error){i(n(` ${u}.${f}:`,b.message)),b.stack&&i(n(` ${u}.${f}.stack:`,b.stack));continue}if(typeof b=="object"&&b!==null){let T=this.indentMultiline(Xs(b,void 0,2)," ");i(n(` ${u}.${f}:`,T));continue}i(n(` ${u}.${f}:`,b));}}else typeof p=="object"?(m=Xs(p,void 0,2),m=this.indentMultiline(m),i(n(` ${u}:`,m))):i(n(` ${u}:`,m));}}else if(s)for(let d of s){let u=d;typeof d=="object"&&(u=Xs(d,void 0,2),u=u.split(`
163
163
  `).map((p,m)=>m>0?` ${p}`:p).join(`
164
- `)),i(" ",n(u));}}setMinLevel(t){typeof t=="string"?this.minLogLevel=bf[t]:this.minLogLevel=t;}setOutputStream(t){this.forcedStream=t;}log(...t){this.logWithLevel(30,Qs.reset,...t);}info(...t){this.logWithLevel(30,Qs.white,...t);}debug(...t){this.logWithLevel(20,Qs.dim,...t);}warn(...t){this.logWithLevel(40,Qs.yellow,...t);}error(...t){this.logWithLevel(50,Qs.red,...t);}success(...t){this.logWithLevel(30,Qs.green,...t);}dimmed(...t){this.logWithLevel(30,Qs.dim,...t);}underline(...t){this.logWithLevel(30,Qs.underline,...t);}bold(...t){this.logWithLevel(30,Qs.bold,...t);}grey(...t){this.logWithLevel(30,Qs.grey,...t);}child(t){let n=new e(this.minLogLevel,{...this.logBindings,...t});return n.forcedStream=this.forcedStream,n}async flush(){}bindings(){return this.logBindings}},R=zx._internalSingleton(),br={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>br,flush:async()=>{},bindings:()=>({})},$T={},qx=({logger:e,logKey:t,maxCount:n,intervalMs:o},r,i,...s)=>{let a=$T[t];a?clearTimeout(a.timer):(a={count:0,totalCount:0},$T[t]=a),a.totalCount++,a.count<n&&(a.count++,e.debug(r,i,...s)),a.timer=setTimeout(()=>{let l=$T[t];l?.totalCount!==l?.count&&e.debug({logKey:t,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${t}`),delete $T[t];},o);};var GU=1e4,jU=1,vm=Ql.extend({browserType:z.enum(za).optional(),slowMoMs:z.number().optional().refine(e=>e===void 0||e<=GU&&e>=-1,{message:`Slow motion must be between 0 and ${GU} milliseconds`}),basicAuthorization:z.object({username:z.string().optional(),password:z.string().optional()}).optional(),geolocation:z.object({latitude:z.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:z.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:z.boolean().optional(),locale:z.string().optional(),timezone:z.enum(NT).optional(),colorScheme:z.enum(["light","dark"]).optional()}),$U=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],Kx=z.object({useMemory:z.boolean().optional(),failureRecovery:z.boolean().optional().describe("undefined means inherit org settings")}),Yx=Kx.extend({disableAICaching:z.boolean().optional(),failureRecoveryInstructions:z.string().optional()}),Dae=z.object({viewport:Jl.optional()}),_i=Dae.extend(Yx.shape).extend(vm.shape),VT=z.object({cron:z.string().refine(e=>isValidCron(e),{error:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:z.boolean().default(false),env:z.string().optional(),timeZone:z.string().default("America/Los_Angeles"),jobKey:z.string().optional()}),zT=z.object({onSuccess:z.boolean().default(false),failureMessage:z.string().optional(),onFailure:z.boolean().default(true),successMessage:z.string().optional()}),Fae=z.object({name:z.string(),required:z.boolean().optional(),defaultValue:z.string().describe("this is not optional because we need a value when the editor is first loaded")}),VU=Fae.array(),Bae=z.object({name:z.string(),value:z.string()}),WT=Bae.array(),zU=z.object({name:z.string(),default:z.boolean().optional(),fixtures:SU.array().optional()});var qa=Kx.extend({agentConfig:z.record(z.string(),z.string()).optional(),aiFailureAnalysis:z.boolean().optional(),classification:C0.optional(),triage:E0.optional(),healing:pT.optional(),explore:Sf.optional(),select:IU.optional()}),Uae=z.object({cliOnly:z.boolean().optional(),neverShowUsageBanner:z.boolean().optional(),hideInternalTraceInfo:z.boolean().optional(),bypassUsageLimits:z.boolean().optional()}),Jx=z.object({fakerConstantSeed:z.boolean().optional(),isolateCachesByEnvironment:z.boolean().optional()}),Hae=z.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),Gae=z.enum(["ios","android","web"]),jae=z.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),$ae=z.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","other"]),Vae=z.object({helpIntents:z.array(Hae).optional(),helpIntentOtherText:z.string().optional(),deviceTypeIntent:Gae.optional(),currentTestingTool:jae.optional(),heardAboutSource:$ae.optional()}),zae=z.object({discovery:Vae.optional(),needsToCompleteOnboarding:z.boolean().optional(),wizardCompletedAt:z.iso.datetime().optional()}),wm=z.object({ai:qa.optional(),githubAppInstallationId:z.number().nullish(),githubAppSummaryMessageEnabled:z.boolean().nullish(),githubReleaseAppInstallationId:z.number().nullish(),gitlabAppAccessToken:z.string().nullish(),gitlabAppBaseUrl:z.string().nullish(),browser:kx.optional(),internal:Uae.optional(),advanced:Jx.optional(),onboarding:zae.optional()});function WU(e){try{return wm.parse(e)}catch{return R.warn("Cloud settings contain values this version of the CLI does not support. Please upgrade. Falling back to defaults."),wm.parse({})}}z.object({globalOverrides:z.record(z.string(),z.string()).optional(),agentConfig:z.record(z.string(),z.string()).optional()});z.record(z.string(),z.string()).nullish();var Zs=(n=>(n.CANNOT_FIX_TEST="CANNOT_FIX_TEST",n.FIXED="FIXED",n))(Zs||{}),qU=z.object({index:z.int().nonnegative(),section:wx,step:_t}),Wae=z.object({additions:qU.array(),deletions:qU.array()}),Qx=z.object({subAgentStatus:z.enum(Zs).default("CANNOT_FIX_TEST"),rootCause:z.string(),solution:z.string(),verificationNotes:z.string().optional().default(""),diffs:Wae.optional(),pullRequestUrl:z.string().optional(),branchUrl:z.string().optional()}),KU=Qx.optional().catch(void 0);var Pi={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Gt=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(Gt||{});var Tf=(r=>(r.NOT_ATTEMPTED="NOT_ATTEMPTED",r.PERM_HEAL_SUCCEEDED="PERM_HEAL_SUCCEEDED",r.PERM_HEAL_FAILED="PERM_HEAL_FAILED",r.PERM_HEAL_ON_SUCCESS_FAILED="PERM_HEAL_ON_SUCCESS_FAILED",r))(Tf||{});var Xx=z.enum(Tf).default("NOT_ATTEMPTED"),qT=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(qT||{});var qae=z.object({attempts:z.int().nonnegative()}),On=z.string().pipe(z.coerce.date()).or(z.date()),ea=z.object({id:z.string(),runKey:z.string(),organizationId:z.string(),executionType:Rm.optional().default("WEB"),createdAt:On,createdBy:z.string(),flake:z.boolean().nullish(),scheduledAt:On.or(z.null()),startedAt:On.or(z.null()),updatedAt:On.nullish(),finishedAt:On.or(z.null()),resolvedBaseUrl:z.string().nullish(),environmentName:z.string().nullish(),gitBranchName:z.string().nullish(),gitMainBranch:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),labels:z.array(z.string()).optional(),gitOriginUrl:z.string().nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),gitCommitTimestamp:On.nullish(),gitCommitMessage:z.string().nullish(),schemaVersion:z.string().nullish(),cliVersion:z.string().nullish(),section:z.enum(qT).nullish(),status:z.enum(Gt),healStatus:Xx,healDetails:KU.nullish(),trigger:z.enum(Pi),attempts:z.number(),runAttempts:z.array(z.object({id:z.string(),status:z.enum(Gt),startedAt:On.or(z.null()),finishedAt:On.or(z.null())})).optional(),videos:z.array(z.string()).optional(),failureReason:z.string().nullish(),failureDetails:w0.nullish(),failureRecoveryDetails:qae.nullish(),pipelineId:z.string().nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),quarantined:z.boolean().nullish().default(false),quarantinedReason:z.string().nullish(),localTestId:z.string().nullish(),testId:z.string().nullish(),testName:z.string().nullish(),description:z.string().nullish(),directory:z.string().nullish(),test:z.object({name:z.string(),id:z.string()}).nullish().default(null),suiteId:z.string().nullish(),aiSettings:qa.nullish(),stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish()}),Kae={id:true,status:true,healStatus:true,healDetails:true,testName:true,localTestId:true,testId:true,test:{select:{name:true,id:true}},finishedAt:true,failureReason:true,failureDetails:true},KT=ea.pick({...Kae,test:true}),Zx=ea.omit({failureReason:true,failureDetails:true,test:true}),e_=ea.extend({stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),test:z.object({name:z.string(),id:z.string(),description:z.string().nullish(),baseUrl:z.string().nullish(),advanced:_i.nullish()}).nullish()}).extend(Ux.shape),YU=e=>e.includes("PASSED")&&e.includes("FAILED");var JU=z.enum(["error","warning","passing"]);var QU=z.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]);var XU=z.object({kind:QU,detail:z.string().min(1).max(280)}),Eu=z.object({riskLevel:z.string(),headline:z.string().min(1).max(200).describe("One-sentence summary of what happened in this run. Plain text, no markdown."),overview:z.string().min(1).max(280).optional().describe("One plain-text sentence giving the bottom line of the run. No markdown."),summaryMarkdown:z.string().min(1).max(4e3).describe("Markdown body. Several short paragraphs or a tight list. No emojis, no top-level heading. Max 5 sentences."),recommendedAction:XU.optional()}),ZU=Eu.extend({riskLevel:JU.describe("Traffic-light validation signal. Use passing when validation is trustworthy with no real concern, warning when review or follow-up is needed, and error when the evidence shows the PR may hide or cause a product regression or another material concern that requires review."),headline:z.string().min(1).max(60).describe("Short, factual, title-case status of the validation signal, 6 words max, no punctuation. Describe the outcome only - never name the process or mode (no 'dry run', 'auto-heal', 'triage', 'pending'); those are shown separately. Examples: 'Review Required', 'Sign In Failing Across 5 Tests', 'All Tests Passed'."),overview:z.string().min(1).max(280).describe("The bottom-line verdict in one plain sentence: what the Momentic validation means for user-visible behavior and how trustworthy the signal is. This is the conclusion only, not the evidence. No markdown, headings, lists, or emojis. Do not prescribe a merge decision (use recommendedAction)."),summaryMarkdown:z.string().min(1).max(1e3).describe("The supporting evidence behind the overview, in GitHub-flavored markdown: a few short sentences or a tight list with the specific tests, errors, and signals that justify the verdict. Must carry information the overview does not - never paraphrase or restate the overview. Do not prescribe a merge decision or restate repair mechanics. Max 4 sentences. No emojis or top-level heading."),recommendedAction:XU.extend({kind:QU.describe("The kind of action a reviewer should take. safe_to_merge = signal is trustworthy and can be merged as-is; confirm_intended_change = a product or UI change was detected (or a heal relaxed an expectation) and a human must confirm it is intentional; investigate_regression = evidence points to a real product bug or regression to investigate before merging; fix_test = a broken or stale test or test setup needs repair; resolve_infra = an infrastructure or environment problem needs resolving and a re-run; review_coverage = quarantine has materially reduced coverage that should be reviewed."),detail:z.string().min(1).max(280).describe("One plain-text sentence naming the specific next step (e.g. 'Confirm the new success-indicator color is an intended design change'). No markdown.")}).describe("The single most important next step a reviewer should take. Omit entirely when the signal is clean and there is genuinely nothing to do.").optional()});var eH=z.object({id:z.string(),status:z.enum(Gt),trigger:z.enum(Pi),createdAt:On,startedAt:On.nullish(),finishedAt:On.nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitTimestamp:On.nullish(),gitBranchName:z.string().nullish(),gitOriginUrl:z.string().nullish(),gitCommitMessage:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),pipelineId:z.string().nullish(),ciProvider:z.string().nullish(),cliVersion:z.string().nullish(),labels:z.string().array().optional(),healRiskSummary:Eu.optional(),localSuiteName:z.string().optional(),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:z.object({status:z.enum(Gt),environmentName:z.string().nullish()}).array()}),tH=eH.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:KT.array()}),nH=eH.extend({runs:ea.array()});var Jae=z.object({type:z.literal("TARGETING"),name:z.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:pU.array(),pageState:z.string().optional(),targetSource:z.enum(xa).optional(),targetUpdateTime:z.string().optional()}),Qae=z.object({type:z.literal("AI_LOCATION"),matched:z.boolean(),pageState:z.string().optional(),ragUsed:z.boolean().optional(),thoughts:z.string().optional()}),Xae=z.object({type:z.literal("ASSERTION"),relevantElementsSerialized:z.string().array().optional(),pageState:z.string().optional(),ragUsed:z.boolean().optional()}),oH=z.discriminatedUnion("type",[Jae,Qae,Xae]);var Zae=z.object({id:z.string(),name:z.string()});Zae.extend(z.object({createdAt:On,createdBy:z.string(),schedule:VT,notification:zT,environment:z.object({name:z.string()}).nullish(),beforeTests:z.object({id:z.string()}).array().nullish(),afterTests:z.object({id:z.string()}).array().nullish()}).shape);var rH=z.object({id:z.guid(),orgId:z.string(),createdAt:On,startedAt:On.or(z.null()),finishedAt:On.or(z.null()),status:z.enum(Gt),trigger:z.enum(Pi),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:ea.array()});rH.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var iH=rH.extend({runs:KT.array()});function sH({beforeStatus:e,mainStatus:t,afterStatus:n}){return e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":"PASSED"}function aH(e,t){return e.some(r=>t?.onlyQuarantined?r.status==="FAILED":!r.quarantined&&r.status==="FAILED")?"FAILED":e.some(r=>r.status==="CANCELLED")?"CANCELLED":"PASSED"}function lH(e){switch(e){case "PASSED":return "SUCCESS";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":case "PENDING":case "RETRYING":case "WAITING_FOR_USER":return "RUNNING"}}var t_=z.object({content:z.string(),ids:z.string().array(),tokenLength:z.number()}),ele=z.object({chunks:t_.array()});z.object({ids:z.string().array(),score:z.number(),tokenLength:z.number()});ele.extend({description:z.string().describe("Input to pass to RAG engine"),tokenLimit:z.number()});var cH=z.object({ids:z.number().array()}),dH=z.object({indices:z.number().array()});var vo=z.object({disableCache:z.boolean().optional(),useMemory:z.boolean().optional(),clientMode:z.enum(["interactive","runner"]).optional(),loggerTags:z.record(z.string(),z.string()).optional(),langfuseSessionId:z.string().optional(),agentConfigVersion:z.string().optional(),cacheBustReason:z.enum(Fg).optional()});vo.extend({chunks:t_.array(),description:z.string().describe("Input to pass to AI"),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),softTokenLimit:z.number(),mediumTokenLimit:z.number().optional(),hardTokenLimit:z.number(),callId:z.string().optional()});var tle=z.object({screenshotBase64AfterCommand:z.string(),urlAfterCommand:z.string(),serializedCommand:z.string(),elementInteracted:z.string().optional(),thoughts:z.string().optional()}),uH=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),source:uU.optional().catch(void 0),isTieBreakerCall:z.boolean().optional(),memory:z.discriminatedUnion("type",[Hs,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),firstPassModelResults:PT.array().optional(),knowledgeBaseSection:z.string().optional()}),pH=z.object({target:z.string().or(z.number()),browserState:z.string().optional(),screenshot:z.string().optional(),boundingBox:z.object({x:z.number(),y:z.number(),height:z.number(),width:z.number()}).optional()}),mH=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),hH=z.object({goal:z.string(),emulatorState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),n_=z.union([z.literal("NEGATED_CHECK"),z.literal("CONDITIONAL_CHECK")]),gH=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),url:z.string(),contextChoice:ax.optional(),memory:z.discriminatedUnion("type",[hu,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),source:n_.optional(),recoveryHint:z.string().optional(),knowledgeBaseSection:z.string().optional()}),fH=z.object({command:zc}),o_=z.object({goal:z.string(),browserState:z.string(),startingScreenshot:z.string().optional(),screenshot:z.string(),url:z.string(),history:tle.array(),actionHint:z.string().optional(),lastError:z.string().optional()}),yH=z.object({results:BT.array(),errorMessage:z.string(),errorStack:z.string().optional()}),SH=z.object({results:BT.array(),goal:z.string(),errorMessage:z.string()}),bH=z.object({failedResults:BT.array(),nextStepsSerialized:z.string().array(),currentUrl:z.string(),currentPageState:z.string(),currentScreenshot:z.string(),customInstructions:z.string().optional(),testDescription:z.string().optional()});z.object({description:z.string(),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),excerpt:z.string()});var TH=z.object({type:z.string(),browserContext:z.string(),currentStep:z.string(),screenshot:z.string()}),AH=z.object({description:z.string(),browserState:z.string().optional(),screenshot:z.string()}),nle=z.enum(["locator","assertion"]);z.object({completionType:nle,currentGoal:z.string(),pastGoal:z.string().optional(),currentScreenshot:z.string(),pastScreenshot:z.string(),pastResult:z.union([z.boolean(),z.number()])});z.object({goal:z.string()});var EH=z.object({keywords:z.array(z.string())});var YT=(i=>(i.LOCATOR="locator",i.ASSERTION="assertion",i.VISUAL_ASSERTION="visual-assertion",i.TEXT_EXTRACTION="text-extraction",i.FAILURE_RECOVERY="failure-recovery",i))(YT||{}),ole=["locator","assertion","visual-assertion","text-extraction","failure-recovery"];z.enum(YT);var rle=new Set(ole);function ile(e){return rle.has(e)}var sle=z.enum(["v1","v2","v3","v4"]),ale=z.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1");z.union([sle,ale,z.string().describe("for people with special configurations")]);var xm={locator:"v4",assertion:"v4","visual-assertion":"v4","text-extraction":"v3","failure-recovery":"v2"};var lle={locator:{v4:["v4.2","v4.1","v4.0"],v3:["v3.3","v3.2","v3.1","v3.0"],v2:["v2.2","v2.1","v2.0"],v1:["v1.0"]},assertion:{v4:["v4.1","v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.3","v2.2","v2.1","v2.0"],v1:["v1.0"]},"visual-assertion":{v4:["v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.0"],v1:["v1.0"]},"text-extraction":{v3:["v3.0"],v2:["v2.0"],v1:["v1.0"]},"failure-recovery":{v2:["v2.1","v2.0"],v1:["v1.0"]}},CH=(s=>(s.ANDROID_LOCATOR="android-locator",s.IOS_LOCATOR="ios-locator",s.ANDROID_ASSERTION="android-assertion",s.IOS_ASSERTION="ios-assertion",s.ANDROID_TEXT_EXTRACTION="android-text-extraction",s.IOS_TEXT_EXTRACTION="ios-text-extraction",s))(CH||{});z.enum(CH);function RH(e){for(let[t,n]of Object.entries(e)){if(!ile(t))continue;let o=lle[t];if(!o)continue;let r=new Set;for(let[i,s]of Object.entries(o)){r.add(i);for(let a of s)r.add(a);}if(!r.has(n)){let i=[...r].sort();throw new Y("UserConfigurationError",`Invalid agent config: "${n}" is not a valid version for "${t}". Valid versions: ${i.join(", ")}`)}}}var Xl=w__default.object({id:w__default.guid(),envKey:w__default.string().optional(),skipped:w__default.boolean().optional(),retries:w__default.number().optional()});var Cu=(r=>(r.PRESET="MOBILE_PRESET_STEP",r.MODULE="MOBILE_MODULE_STEP",r.AI_ACTION="MOBILE_AI_ACTION_STEP",r.CONDITIONAL="MOBILE_CONDITIONAL_STEP",r))(Cu||{});var _m=Xl.extend({type:w__default.literal("MOBILE_CONDITIONAL_STEP")});var Tr=z.object({id:z.string(),name:ET,baseUrl:CT,description:z.string().optional().nullish(),schemaVersion:z.string(),advanced:_i,retries:z.number().optional().nullish(),envs:z.array(zU).nullish(),parameters:VU.nullish(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional().catch([])}),vH=z.enum(["INHERIT","ENABLED","DISABLED"]);var dle=_i.extend({failureRecovery:vH.optional(),useMemory:vH.optional()});Tr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true}).extend({advanced:dle});Tr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true});var ule=z.object({labels:z.array(z.string()).optional(),outputs:WT.nullish()}),Wn=Tr.extend(ule.shape),ple=z.object({createdAt:z.coerce.date(),updatedAt:z.coerce.date(),updatedBy:z.string().nullable(),schedule:VT,notification:zT,createdBy:z.string(),organizationId:z.string(),folderId:z.string().nullable().optional()}),mle=Tr.extend(ple.shape);mle.extend(Jc.shape);var r_=Tr.extend(Jc.shape);Tr.extend(Wl.shape);var hle="test",gle="module",fle="mobile-test",yle="mobile-module",Sle="test/v2",ble="module/v2",Tle="mobile-test/v2",Ale="mobile-module/v2";var we=(l=>(l.TEST=`momentic/${hle}`,l.MODULE=`momentic/${gle}`,l.TEST_V2=`momentic/${Sle}`,l.MODULE_V2=`momentic/${ble}`,l.MOBILE_TEST=`momentic/${fle}`,l.MOBILE_MODULE=`momentic/${yle}`,l.MOBILE_TEST_V2=`momentic/${Tle}`,l.MOBILE_MODULE_V2=`momentic/${Ale}`,l))(we||{});Tr.merge(Wl);var Ele=Rn.extend({steps:z.array(z.record(z.string(),z.unknown().optional())),schemaVersion:z.string()}),Cf=Ele.extend({fileType:z.literal(we.MODULE)});z.object({test:z.string().describe("YAML for the test, including metadata and steps"),modules:z.record(z.string(),z.string()).describe("Map of module name to YAML for the module")});function JT(e){if(e===void 0)return "__undefined__";if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(JT);let t={};for(let[n,o]of Object.entries(e))t[n]=JT(o);return t}var Cle=/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/,wH=36,Ln=z.union([z.guid().max(wH,"V2 IDs must be 36 characters or fewer"),z.string().max(wH,"V2 IDs must be 36 characters or fewer").regex(Cle,"V2 IDs must be lowercase kebab-case with at least three words, e.g. silver-river-lantern")],{error:"ID must be a UUID or lowercase kebab-case with at least three words, e.g. silver-river-lantern (36 characters max)"});var QT=w.discriminatedUnion("type",[w.object({type:w.literal("SCREEN")}),w.object({type:w.literal("OPEN_APP")}),w.object({type:w.literal("OPEN_WEBVIEW")})]),Zl=w.object({type:w.literal("description"),description:w.string()}),s_=w.object({type:w.literal("CUSTOM_COORDINATES"),startX:w.number().describe("Starting X coordinate in pixels"),startY:w.number().describe("Starting Y coordinate in pixels"),deltaPixels:w.number().describe("Number of pixels to scroll in the specified direction")}),XT=w.discriminatedUnion("type",[...QT.options,w.object({type:w.literal("CUSTOM"),target:Zl}),s_]);function Rle(e){return e.toLowerCase().replaceAll("_"," ")}function a_(e){switch(e.type){case "CUSTOM":return e.target.description;case "CUSTOM_COORDINATES":return `custom coordinates (x: ${e.startX}, y: ${e.startY}, delta: ${e.deltaPixels}px)`;case "SCREEN":case "OPEN_APP":case "OPEN_WEBVIEW":return Rle(e.type);default:{throw new Error("Unreachable")}}}var vle=w.object({type:w.literal("coordinates"),xPercent:w.number(),yPercent:w.number()}),wle=w.object({type:w.literal("absolute_percent"),x:w.number(),y:w.number()}),Pm=w.discriminatedUnion("type",[Zl,vle,wle]);var Ile=w.object({x1:w.number(),y1:w.number(),x2:w.number(),y2:w.number(),tolerance:w.nativeEnum(li),preciseTolerance:w.boolean().optional()}),xle=w.object({width:w.number(),height:w.number(),tolerance:w.nativeEnum(li),preciseTolerance:w.boolean().optional()}),l_=w.object({requiredText:w.string().optional(),requiredAttributes:w.record(w.string(),w.string()).optional(),requiredBounds:w.boolean().optional(),position:Ile.optional(),shape:xle.optional()}),IH=w.object({xPath:w.string(),requirements:l_.optional()}),_le=w.object({type:w.literal("CUSTOM"),target:Zl,cache:w.lazy(()=>xH).optional()}),Ple=w.object({pixelDelta:w.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:w.union([QT,_le,s_]),direction:w.enum(["up","down"])}),xH=w.object({type:w.literal("NATIVE"),bounds:w.number().array().optional(),resolvedDescription:w.string().optional(),xPath:w.string().optional(),elementOnlySerializedXml:w.string().optional(),scrollDetails:Ple.optional(),requirements:l_.optional(),requiredRelatedElements:IH.array().optional(),memory:Hs.optional()}),Mle=w.object({type:w.literal("WEBVIEW"),resolvedDescription:w.string().optional(),xPath:w.string().optional(),browserCache:_a.optional(),memory:Hs.optional()}),ZT=w.union([xH,Mle]);var Ole=w.object({left:w.number(),top:w.number(),right:w.number(),bottom:w.number()});w.object({newViewportBounds:Ole});var Nle=w.object({type:w.literal("CUSTOM"),target:Zl,cache:w.lazy(()=>OH).optional()}),_H=w.object({pixelDelta:w.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:w.union([QT,Nle,s_]),direction:w.enum(["up","down"])}),PH=(n=>(n.Native="native",n.Appium="appium",n))(PH||{}),c_=w.tuple([w.number(),w.number(),w.number(),w.number()]),MH=IH.extend({bounds:c_.optional(),browserCache:_a.optional()}),OH=w.object({type:w.literal("NATIVE"),bounds:c_.optional(),resolvedDescription:w.string().optional(),sourceTree:w.nativeEnum(PH).optional(),xPath:w.string().optional(),elementOnlySerializedXml:w.string().optional(),scrollDetails:_H.optional(),requirements:l_.optional(),requiredRelatedElements:MH.array().optional(),memory:Hs.optional()}),Lle=w.object({type:w.literal("WEBVIEW"),bounds:c_.optional(),resolvedDescription:w.string().optional(),xPath:w.string().optional(),scrollDetails:_H.optional(),browserCache:_a.optional(),requiredRelatedElements:MH.array().optional(),memory:Hs.optional()}),eA=w.discriminatedUnion("type",[OH,Lle]);var Wt=(E=>(E.AI_CHECK="AI_CHECK",E.AI_EXTRACT="AI_EXTRACT",E.TAP="TAP",E.TYPE="TYPE",E.PRESS="PRESS",E.PRESS_KEYBOARD="PRESS_KEYBOARD",E.OPEN_APP="OPEN_APP",E.KILL_APP="KILL_APP",E.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",E.SWIPE="SWIPE",E.SCROLL_TO="SCROLL_TO",E.SCREEN_CHECK="SCREEN_CHECK",E.ELEMENT_CHECK="ELEMENT_CHECK",E.DRAG_AND_DROP="DRAG_AND_DROP",E.JAVASCRIPT="JAVASCRIPT",E.REQUEST="REQUEST",E.WAIT="WAIT",E.ADD_FILE="ADD_FILE",E.INSTALL_APP="INSTALL_APP",E.UNINSTALL_APP="UNINSTALL_APP",E.TOGGLE_SETTINGS="TOGGLE_SETTINGS",E.ROTATE_ORIENTATION="ROTATE_ORIENTATION",E.ADB_COMMAND="ADB_COMMAND",E.APPIUM_EXECUTE="APPIUM_EXECUTE",E.STATE="STATE",E))(Wt||{}),ze=w__default.object({id:w__default.guid(),disableCache:w__default.boolean().optional()}),Mm=w__default.object({updatedAt:w__default.coerce.date().optional(),updatedAtLoggerTags:w__default.record(w__default.string(),w__default.string()).optional()}),ms=Mm.extend({target:ZT}),tA=Mm.extend({fromTarget:ZT,toTarget:ZT}),Ya=Mm.extend({target:eA}),NH=Mm.extend({fromTarget:eA,toTarget:eA}),ec=e=>{switch(e.type){case "description":return e.description;case "coordinates":return `${Math.round(e.xPercent*100)}%, ${Math.round(e.yPercent*100)}%`;case "absolute_percent":return `x: ${e.x}%, y: ${e.y}%`}};var LH=ze.extend({type:w__default.literal("ADB_COMMAND"),command:w__default.string(),jsonArgs:w__default.string().optional()});var kle=w__default.string().trim(),DH=ze.extend({type:w__default.literal("INSTALL_APP"),uri:kle});var FH=ze.extend({type:w__default.literal("OPEN_NOTIFICATION_DRAWER")});var nA=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(nA||{}),UH=ze.extend({type:w__default.literal("TOGGLE_SETTINGS"),settingsType:w__default.nativeEnum(nA)});var GH=ze.extend({type:w__default.literal("UNINSTALL_APP"),packageName:w__default.string()});var oA=ze.extend({type:w__default.literal("APPIUM_EXECUTE"),command:w__default.string(),jsonArgs:w__default.string().optional()});var jH=ze.extend({type:w__default.literal("ADD_FILE"),file:w__default.string(),storageLocation:w__default.string()});var tc=ze.extend({type:w__default.literal("AI_CHECK"),assertion:w__default.string(),timeoutSecs:w__default.number().optional(),cache:Mm.extend({memory:hu.optional()}).optional()});var $H=ze.extend({type:w__default.literal("AI_EXTRACT"),goal:w__default.string(),schema:w__default.string().optional()});var Om=ze.extend({type:w__default.literal("JAVASCRIPT"),code:w__default.string(),timeout:w__default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var VH=ze.extend({type:w__default.literal("KILL_APP")});var rA=(n=>(n.HOME="HOME",n.POWER="POWER",n))(rA||{}),f_=(s=>(s.BACK="BACK",s.APP_SWITCHER="APP_SWITCHER",s.SEARCH="SEARCH",s.VOLUME_UP="VOLUME_UP",s.VOLUME_DOWN="VOLUME_DOWN",s.VOLUME_MUTE="VOLUME_MUTE",s))(f_||{}),iA=ze.extend({type:w__default.literal("PRESS"),key:w__default.nativeEnum(rA),longPress:w__default.boolean().optional()}),zH=iA.extend({key:w__default.nativeEnum(f_).or(w__default.nativeEnum(rA))}),WH=iA;var qH=ze.extend({type:w__default.literal("REQUEST")}).merge(Gg);var YH=(n=>(n.PORTRAIT="PORTRAIT",n.LANDSCAPE="LANDSCAPE",n))(YH||{}),JH=ze.extend({type:w__default.literal("ROTATE_ORIENTATION"),orientation:w__default.nativeEnum(YH)});var Ule=w__default.object({type:w__default.literal("CONTENT"),negated:w__default.boolean().optional(),value:w__default.string()}),Lm=ze.extend({type:w__default.literal("SCREEN_CHECK"),assertion:Ule,timeout:w__default.number().int().min(0).max(om).optional().describe("max seconds to wait for the assertion to be true")});var QH=ze.extend({type:w__default.literal("STATE")});var ZH=ze.extend({type:w__default.literal("WAIT"),timeoutSecs:w__default.number()});var vf=w__default.discriminatedUnion("type",[QH,tc,$H,Om,ZH,qH,JH,Lm,jH,VH]);w__default.discriminatedUnion("type",[...vf.options,iA]);var S_=ze.extend({type:w__default.literal("DRAG_AND_DROP"),fromTarget:Zl,toTarget:Zl,hoverDuration:w__default.number().optional(),dragDuration:w__default.number().optional()}),wf=S_.extend({cache:tA.optional()}),If=S_.extend({cache:NH.optional()});var b_=ze.extend({type:w__default.literal("ELEMENT_CHECK"),target:Pm,assertion:tT,timeout:w__default.number().int().min(0).max(om).optional().describe("max seconds to wait for the assertion to be true")}),Ru=b_.extend({cache:ms.optional()}),vu=b_.extend({cache:Ya.optional()});var sA=(n=>(n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(sA||{}),T_=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(T_||{}),nG=ze.extend({type:w__default.literal("PRESS_KEYBOARD"),key:w__default.nativeEnum(sA)}),oG=ze.extend({type:w__default.literal("PRESS_KEYBOARD"),key:w__default.nativeEnum(T_).or(w__default.nativeEnum(sA))});var rG=ze.extend({type:w__default.literal("OPEN_APP"),packageName:w__default.string(),activityName:w__default.string().optional(),intentExtras:w__default.string().optional()}),iG=ze.extend({type:w__default.literal("OPEN_APP"),packageName:w__default.string(),intentExtras:w__default.string().optional()});var A_=ze.extend({type:w__default.literal("SCROLL_TO"),target:Zl,direction:w__default.enum(["down","up"]),scrollableElement:XT,scrollStepPercent:w__default.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.9 (90%)."),maxScrollAttempts:w__default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),_f=A_.extend({cache:ms.optional()}),Pf=A_.extend({cache:Ya.optional()});var E_=ze.extend({type:w__default.literal("SWIPE"),direction:w__default.enum(["up","down","left","right"]),scrollableElement:XT,viewportPercent:w__default.number().optional(),durationMs:w__default.number().optional(),relativePosition:Zb.optional()}),Mf=E_.extend({cache:ms.optional()}),Of=E_.extend({cache:Ya.optional()});var C_=ze.extend({type:w__default.literal("TAP"),target:Pm,longPress:w__default.boolean().optional(),longPressDurationMs:w__default.number().optional(),iterations:w__default.number().optional(),tapDelayMs:w__default.number().optional(),relativePosition:Zb.optional(),doubleTap:w__default.boolean().optional(),doubleTapDelayMs:w__default.number().optional()}),Nf=C_.extend({cache:ms.optional()}),Lf=C_.extend({cache:Ya.optional()});var R_=ze.extend({type:w__default.literal("TYPE"),target:Pm.optional(),keyPressDelayMs:w__default.number().optional(),text:w__default.string(),clearContent:w__default.boolean().optional(),forceClearContent:w__default.boolean().optional()});var Df=R_.extend({cache:ms.optional()}),Ff=R_.extend({cache:Ya.optional()});var Bf=w__default.discriminatedUnion("type",[...vf.options,Nf,Df,zH,oG,GH,DH,LH,oA,wf,FH,_f,Mf,UH,Ru,rG]);var Uf=w__default.discriminatedUnion("type",[...vf.options,Lf,Ff,WH,nG,iG,Of,If,Pf,vu,oA]);var lG=w__default.union([w__default.string(),w__default.record(w__default.string(),w__default.unknown().optional())]),cA=Xl.extend({type:w__default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:w__default.number().optional()}),td=cA.extend({command:Bf}),nd=cA.extend({command:Uf}),km=w__default.object({moduleId:w__default.string(),inputs:w__default.record(w__default.string(),w__default.string()).optional()}),Hf=Xl.merge(km.extend({type:w__default.literal("MOBILE_MODULE_STEP")}));km.extend({steps:w__default.lazy(()=>Ja.array())});km.extend({steps:w__default.lazy(()=>nc.array())});var v_=(n=>(n.V2="2",n.V3="3",n))(v_||{});var w_=w__default.nativeEnum(v_),Vle=Ia.extend({platform:w__default.literal("ANDROID"),resolvedGoal:w__default.string(),steps:w__default.lazy(()=>td.array()),autoGeneratedPostcondition:w__default.string().optional()}),zle=Ia.extend({platform:w__default.literal("IOS"),resolvedGoal:w__default.string(),steps:w__default.lazy(()=>nd.array()),autoGeneratedPostcondition:w__default.string().optional()}),I_=w__default.discriminatedUnion("platform",[Vle,zle]),od=Xl.extend({type:w__default.literal("MOBILE_AI_ACTION_STEP"),text:w__default.string(),version:w_.optional(),cache:I_.optional(),precondition:w__default.string().optional(),postcondition:w__default.string().optional()});var qle=w__default.discriminatedUnion("type",[tc,Lm,Ru,Om]),x_=cA.extend({command:qle}),Kle=w__default.discriminatedUnion("type",[tc,Lm,vu,Om]),__=cA.extend({command:Kle}),Yle=w__default.object({assertion:x_,steps:w__default.lazy(()=>Ja.array())}),Jle=w__default.object({assertion:__,steps:w__default.lazy(()=>nc.array())}),Qle=_m.extend({blocks:w__default.lazy(()=>Yle.array()),elseSteps:w__default.lazy(()=>Ja.array()).optional()}),Xle=_m.extend({blocks:w__default.lazy(()=>Jle.array()),elseSteps:w__default.lazy(()=>nc.array()).optional()}),Ja=w__default.discriminatedUnion("type",[td,Hf,od,Qle]),nc=w__default.discriminatedUnion("type",[nd,Hf,od,Xle]);w__default.union([Ja.array(),nc.array()]);var P_=w__default.object({parameterNames:w__default.string().array(),defaultParameters:w__default.record(w__default.string(),w__default.string()).optional(),parameterEnums:w__default.record(w__default.string(),w__default.string().array()).optional()}),dA=w__default.object({moduleId:Ln,name:w__default.string(),description:w__default.string().nullish(),platform:w__default.nativeEnum(Js).optional().default("ANDROID"),parameters:P_.optional(),enabled:w__default.boolean().nullish(),schemaVersion:w__default.string()}),M_=dA.omit({name:true}),Zle=M_.extend({steps:lG.array()});w__default.object({fileType:w__default.literal(we.MOBILE_MODULE)}).merge(Zle);var cG=dA.omit({platform:true,schemaVersion:true});({ANDROID:cG.extend({platform:w__default.literal("ANDROID"),steps:Ja.array()}),IOS:cG.extend({platform:w__default.literal("IOS"),steps:nc.array()})});var Dm=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(Dm||{}),dG=w__default.object({description:w__default.string().optional(),name:w__default.string().describe("name of the module"),parameters:P_.optional()}),uG=km.merge(dG).extend({platform:w__default.literal("ANDROID"),get steps(){return na.array()}}),pG=km.merge(dG).extend({platform:w__default.literal("IOS"),get steps(){return oa.array()}});w__default.discriminatedUnion("platform",[uG,pG]);var O_=Xl.merge(uG).extend({type:w__default.literal("RESOLVED_MOBILE_MODULE")}),N_=Xl.merge(pG).extend({type:w__default.literal("RESOLVED_MOBILE_MODULE")});w__default.discriminatedUnion("platform",[O_,N_]);var ece=w__default.object({assertion:x_,get steps(){return na.array()}}),L_=_m.extend({get blocks(){return ece.array()},get elseSteps(){return na.array().optional()}}),tce=w__default.object({assertion:__,get steps(){return oa.array()}}),k_=_m.extend({get blocks(){return tce.array()},get elseSteps(){return oa.array().optional()}}),na=w__default.discriminatedUnion("type",[O_,td,od,L_]),oa=w__default.discriminatedUnion("type",[N_,nd,od,k_]);function mG(e){return Object.values(Dm).includes(e)||Object.values(Cu).includes(e)}var hG=(i=>(i.PRECONDITION="PRECONDITION",i.REPLAY="REPLAY",i.GENERATE="GENERATE",i.AUTOHEAL="AUTOHEAL",i.POSTCONDITION="POSTCONDITION",i))(hG||{}),gG=z.enum(["pending","running","success","failed"]),fG=z.object({type:z.literal("THOUGHT"),text:z.string(),blockId:z.string().optional()}),yG=z.object({type:z.literal("TOOL_CALL"),toolName:z.string()}),SG=z.object({type:z.literal("PHASE"),phase:z.nativeEnum(hG),failureMessage:z.string().optional()}),nce=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:na,status:gG,message:z.string().optional(),afterSnapshotId:z.string().optional()}),oce=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:oa,status:gG,message:z.string().optional(),afterSnapshotId:z.string().optional()}),bG=z.object({type:z.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z.string()}),rce=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:td.array(),resolvedGoal:z.string()}),ice=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:nd.array(),resolvedGoal:z.string()}),TG=z.discriminatedUnion("type",[fG,yG,SG,nce,rce,bG]),AG=z.discriminatedUnion("type",[fG,yG,SG,oce,ice,bG]);var Qa=w__default.object({message:w__default.string().optional(),startTime:w__default.number(),endTime:w__default.number(),status:w__default.nativeEnum(Mt),trace:w__default.unknown().optional().optional(),beforeSnapshot:w__default.string().optional(),afterSnapshot:w__default.string().optional(),data:w__default.unknown().optional().optional().describe("output data from the step"),aiSuggested:w__default.boolean().optional(),beforeTestContext:Em.optional(),afterTestContext:Em.optional()}),EG=Qa.merge(td).extend({previousAttempts:w__default.lazy(()=>Oi.array()).optional()}),sce=Qa.merge(Hf).extend({steps:w__default.lazy(()=>Oi.array()),name:w__default.string().optional(),previousAttempts:w__default.lazy(()=>Oi.array()).optional()}),ace=Qa.merge(od).extend({steps:w__default.lazy(()=>Oi.array()),previousAttempts:w__default.lazy(()=>Oi.array()).optional(),failureRecoveryReason:w__default.string().optional(),trajectory:TG.array().optional()}),lce=Qa.merge(L_).extend({assertionResult:EG.optional(),steps:w__default.lazy(()=>Oi.array()),previousAttempts:w__default.lazy(()=>Oi.array()).optional()}),Oi=w__default.discriminatedUnion("type",[EG,sce,ace,lce]),CG=Qa.merge(nd).extend({previousAttempts:w__default.lazy(()=>Ni.array()).optional()}),cce=Qa.merge(Hf).extend({steps:w__default.lazy(()=>Ni.array()),name:w__default.string().optional(),previousAttempts:w__default.lazy(()=>Ni.array()).optional()}),dce=Qa.merge(od).extend({steps:w__default.lazy(()=>Ni.array()),previousAttempts:w__default.lazy(()=>Ni.array()).optional(),failureRecoveryReason:w__default.string().optional(),trajectory:AG.array().optional()}),uce=Qa.merge(k_).extend({assertionResult:CG.optional(),steps:w__default.lazy(()=>Ni.array()),previousAttempts:w__default.lazy(()=>Ni.array()).optional()}),Ni=w__default.discriminatedUnion("type",[CG,cce,dce,uce]);var pce=Qa.extend({index:w__default.number().optional(),userFacingStepReference:w__default.string().optional(),description:w__default.string()}),RG=pce.extend({beforeScreenshot:w__default.string().optional(),afterScreenshot:w__default.string().optional()});var vG=z.object({attributesRequired:z.array(z.string()).optional(),textRequired:z.boolean().optional(),boundsRequired:z.boolean().optional(),positionSpecificity:z.enum(li).optional(),shapeSpecificity:z.enum(li).optional()}),mce=z.object({id:z.number(),requirements:vG}).array();z.object({thoughts:z.string(),id:z.number(),updatedMemory:kg.optional(),inWebview:z.boolean().optional(),requirements:vG.optional(),additionalElements:mce.optional()});var hce=z.literal("SCROLL_TO"),wG=z.object({description:z.string(),screenXml:z.string(),screenshot:z.string(),source:hce.optional(),memory:z.discriminatedUnion("type",[Hs,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()}),IG=z.object({assertion:z.string(),screenXml:z.string(),screenshot:z.string(),memory:z.discriminatedUnion("type",[hu,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()});z.object({thoughts:z.string(),result:z.boolean(),relevantElements:z.array(z.number()).optional(),updatedMemory:Dg.optional()});var xG=z.object({failedResults:RG.array(),nextStepsSerialized:z.string().array(),currentScreenXml:z.string(),currentScreenshot:z.string(),customInstructions:z.string().optional(),testDescription:z.string()}),_G=(o=>(o.LEGITIMATE="LEGITIMATE",o.RECOVERABLE="RECOVERABLE",o.INELIGIBLE="INELIGIBLE",o))(_G||{});z.object({thoughts:z.string(),scenario:z.enum(_G),instructions:z.string().nullish(),reasonSummary:z.string().nullish()});z.looseObject({type:z.literal("response.create")});var PG=z.union([z.looseObject({response:z.looseObject({id:z.string()}),sequence_number:z.number(),type:z.literal("response.completed")}),z.looseObject({code:z.string().nullable(),message:z.string(),sequence_number:z.number(),type:z.literal("error")})]);var MG="ui_states.jsonl";z.object({stepId:z.string(),parentStepIdChain:z.array(z.string()),fingerprintHash:z.string(),minhash:z.array(z.number().int()),canonicalUrl:z.string(),capturedAt:z.number().describe("Unix timestamp in milliseconds")});var Fm=(s=>(s.TestRun="test-run",s.MobileTestRun="mobile-test-run",s.CreditsUsed="credits-used",s.CreditsUsedV2="credits-used-v2",s.StepsExecuted="steps-executed",s.LLMTokensUsed="llm-tokens-used",s))(Fm||{}),gce=3;function fce(e){return e==="MODULE"||e==="CONDITIONAL"||e==="SECTION"||e==="RESOLVED_MODULE"}function OG(e){if(!fce(e))switch(e){case "PRESET_ACTION":return 0;case "AI_ACTION":return 3;case "AI_ACTION_DYNAMIC":return 5;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}function NG(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return gce;case "CAPTCHA":return 3;case "CLICK":case "TYPE":case "SELECT_OPTION":case "HOVER":case "ELEMENT_CHECK":case "FOCUS":case "BLUR":case "SCROLL_DOWN":case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_UP":case "MOUSE_DRAG":return e.useSelector||!e.target||e.target.type!=="description"?0:1;case "DRAG":return e.useSelector?0:1;case "VISUAL_DIFF":case "TAB":case "JAVASCRIPT":case "NAVIGATE":case "WAIT":case "SUCCESS":case "AUTH_LOAD":case "AUTH_SAVE":case "COOKIE":case "DIALOG":case "FILE_UPLOAD":case "GO_BACK":case "GO_FORWARD":case "LOCAL_STORAGE":case "NEW_TAB":case "CLOSE_TAB":case "PAGE_CHECK":case "PRESS":case "KEY_DOWN":case "KEY_UP":case "COPY":case "PASTE":case "REFRESH":case "REQUEST":case "GRAPHQL_REQUEST":case "WAIT_FOR_URL":case "REGISTER_REQUEST_LISTENER":case "AWAIT_LISTENER":case "RECORD_REQUESTS":case "GET_RECORDED_REQUESTS":case "SET_HEADER":case "MOCK_ROUTE":case "REMOVE_ROUTE_MOCK":case "OFFLINE_MODE":return 0;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}var D_=z.object({name:z.string(),value:z.string(),url:z.string().optional(),domain:z.string().optional(),path:z.string().optional(),expires:z.number().default(Date.now()/1e3+60*60*24*365),httpOnly:z.boolean().optional(),secure:z.boolean().default(true),sameSite:z.union([z.literal("Strict"),z.literal("Lax"),z.literal("None")]).default("None")});function uA(e,t){let n=[],o=splitCookiesString(e);for(let r of o){let i=parseString(r,{decodeValues:false});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let s;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")s="Strict";else if(d==="lax")s="Lax";else if(d==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=false),!i.path&&i.domain&&(i.path="/"),!i.domain&&t&&(i.domain=t);let a=D_.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:s});n.push(a);let l=[a.name,...Object.keys(a)].map(d=>d.toLowerCase()),c=r.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,p]=d.split("=");if(!u||!p)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||n.push({...a,name:u,value:p});}}return n}var bce=z.object({origin:z.string(),localStorage:z.array(z.object({name:z.string(),value:z.string()})),sessionStorage:z.array(z.object({name:z.string(),value:z.string()})).optional()}),Tce=z.object({entries:z.record(z.string(),z.array(z.tuple([z.unknown().optional(),z.unknown().optional()]))),version:z.number().optional()}),pA=z.object({cookies:D_.array().optional(),origins:bce.array().optional(),idb:z.record(z.string(),Tce).optional().describe("key is db name")});function LG(e,t){let n=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(o=>{let r=D_.safeParse({name:o.key,...o});if(!r.success)return;let i=r.data;!i.domain&&!i.url&&(i.domain=t),n.push(i);}),n}var ui={type:true,cache:true},kG=[tc.pick(ui),Ru.pick(ui),Nf.pick(ui),Df.pick(ui),Mf.pick(ui),_f.pick(ui),wf.pick(ui)],F_=w__default.discriminatedUnion("type",kG),DG=[tc.pick(ui),vu.pick(ui),Lf.pick(ui),Ff.pick(ui),Of.pick(ui),If.pick(ui),Pf.pick(ui)],B_=w__default.discriminatedUnion("type",DG);Object.values(Wt).filter(e=>kG.some(t=>t.shape.type.safeParse(e).success));Object.values(Wt).filter(e=>DG.some(t=>t.shape.type.safeParse(e).success));var U_=w__default.object({type:w__default.literal("MOBILE_AI_ACTION_STEP"),cache:I_}),mA=w__default.union([F_,U_]),hA=w__default.union([B_,U_]);var H_=(s=>(s.US_EAST_1="us-east1",s.US_EAST_2="us-east2",s.US_WEST_1="us-west1",s.US_WEST_2="us-west2",s.EU_NORTH_1="eu-north1",s.AS_SOUTH_1="as-south1",s))(H_||{}),G_=(o=>(o.US="us",o.EU="eu",o.AS="as",o))(G_||{}),FG=(t=>(t.LOCAL="local",t))(FG||{}),j_=w__default.nativeEnum(H_).or(w__default.nativeEnum(G_)),$_=w__default.nativeEnum(H_).or(w__default.nativeEnum(G_)).or(w__default.nativeEnum(FG)),Ece="closest";$_.or(w__default.literal(Ece));var jf=(n=>(n.ANDROID_14="14",n.ANDROID_15="15",n))(jf||{});var V_=(t=>(t.IOS_26="26",t))(V_||{});w.custom().refine(e=>e&&e.length>0).refine(e=>e&&e[0]instanceof File,{message:"Please upload a valid file."});var wo=e=>w.preprocess(t=>t==null?void 0:Array.isArray(t)?t:[t],w.array(e).optional()),Hm=w.string().transform(e=>{let t=e.trim();return t.length===0?void 0:t}).optional();var Cce=w__default.object({disableMomenticAccessibilityTree:w__default.boolean().optional(),autoGrantPermissions:w__default.boolean().optional(),disableXmlSnapshots:w__default.boolean().optional().describe("Skip collecting XML snapshots during test runs. This can speed up test runs, but will cause the run viewer to show less information."),browserSettings:vm.optional()}),Rce="avdId",vce="iosDeviceType",wce="iosVersion",z_=Cce.extend({region:$_.optional().describe("Do you want local or Limbar? Default behavior is Limbar (remote emulators)"),remoteEmulatorSettings:w__default.object({androidVersion:w__default.nativeEnum(jf).optional()}).optional(),localEmulatorSettings:w__default.object({[Rce]:Hm,[vce]:Hm,[wce]:Hm}).optional(),geolocation:w__default.object({latitude:w__default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:w__default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:w__default.boolean().optional().describe("wait for stability before every targeting action")}),$f=w__default.object({retries:w__default.number().optional().describe("number of retries to run"),defaultChannel:w__default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:w__default.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:w__default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:Hm.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:Hm.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:z_.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:Yx.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),BG=w__default.object({id:Ln,description:w__default.string(),schemaVersion:w__default.string(),settings:$f.optional(),disabled:w__default.boolean().optional(),labels:w__default.array(w__default.string()).optional()}),Gm=BG.extend({platform:w__default.literal("ANDROID").optional().default("ANDROID")}),jm=BG.extend({platform:w__default.literal("IOS")}),UG=w__default.discriminatedUnion("platform",[Gm,jm]),HG=w__default.object({fileType:w__default.literal(we.MOBILE_TEST)}),GG=HG.merge(Gm),jG=HG.merge(jm);w__default.discriminatedUnion("platform",[GG,jG]);var $G=Gm.merge(w__default.object({steps:w__default.array(Ja)})),VG=jm.merge(w__default.object({steps:w__default.array(nc)}));w__default.discriminatedUnion("platform",[$G,VG]);var Ice=GG.merge($G),xce=jG.merge(VG);w__default.discriminatedUnion("platform",[Ice,xce]);w__default.object({name:w__default.string(),steps:w__default.array(Ja).optional(),settings:$f.optional()});var zG=Gm.extend({steps:na.array(),beforeSteps:na.array().optional(),afterSteps:na.array().optional()}),WG=jm.extend({steps:oa.array(),beforeSteps:oa.array().optional(),afterSteps:oa.array().optional()});w__default.discriminatedUnion("platform",[zG,WG]);var _ce=zG.extend({name:w__default.string()}),Pce=WG.extend({name:w__default.string()});w__default.discriminatedUnion("platform",[_ce,Pce]);var er=w__default.object({startTime:w__default.number(),endTime:w__default.number().optional(),durationMs:w__default.number().optional(),error:w__default.string().optional(),result:w__default.unknown().optional().optional(),attributes:w__default.record(w__default.string(),w__default.unknown().optional()),subSpans:w__default.lazy(()=>qce.array())});var W_=er.extend({type:w__default.literal("SECTION"),name:w__default.string()}),Mce=er.extend({type:w__default.literal("GET_PAGE_STATE")}),Oce=er.extend({type:w__default.literal("GET_PAGE_SCREENSHOT")}),Nce=er.extend({type:w__default.literal("SMART_WAITING")}),Lce=er.extend({type:w__default.literal("SCROLL_ELEMENT_INTO_VIEW")}),kce=er.extend({type:w__default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:w__default.string().optional(),result:w__default.object({id:w__default.number(),thoughts:w__default.string(),citations:Ao.array().optional()}).optional()}),Dce=er.extend({type:w__default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:w__default.string().optional(),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({thoughts:w__default.string(),result:w__default.boolean(),citations:Ao.array().optional()}).optional()}),Fce=er.extend({type:w__default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:w__default.string().optional(),browserStateSnapshotId:w__default.string().optional(),result:w__default.object({thoughts:w__default.string().optional(),result:w__default.unknown().optional().optional()}).optional()}),Bce=er.extend({type:w__default.literal("ELEMENT_ASSERTION"),name:w__default.string(),result:w__default.object({success:w__default.boolean(),message:w__default.string().optional()}).optional()}),Uce=er.extend({type:w__default.literal("BROWSER_INTERACTION"),name:w__default.string(),coordinates:w__default.object({x:w__default.number(),y:w__default.number()}).optional(),value:w__default.string().optional(),selector:w__default.string().optional()}),Hce=er.extend({type:w__default.literal("CACHE_RESOLUTION"),resolutionMethod:w__default.string().optional(),cacheMissReason:w__default.nativeEnum(Yp).optional(),targetSource:w__default.string().optional(),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({serializedElement:w__default.string()}).optional()}),Gce=er.extend({type:w__default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({serializedElement:w__default.string()}).optional()}),jce=er.extend({type:w__default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({outcome:w__default.string(),logs:w__default.string().array().optional(),serializedElement:w__default.string().optional(),relativeClickPoint:w__default.object({x:w__default.number(),y:w__default.number()}).optional(),force:w__default.boolean().optional()}).optional()}),$ce=er.extend({type:w__default.literal("WAIT_FOR_STABILITY")}),Vce=er.extend({type:w__default.literal("GENERIC"),name:w__default.string()}),zce=er.extend({type:w__default.literal("PAGE_ASSERTION"),name:w__default.string(),result:w__default.object({success:w__default.boolean(),message:w__default.string().optional()}).optional()}),Wce=er.extend({type:w__default.literal("AUTO_FOLLOW_NEW_TABS"),result:w__default.object({followed:w__default.boolean()}).optional()});function qG(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var qce=w__default.discriminatedUnion("type",[W_,Mce,Oce,Nce,Lce,kce,Dce,Fce,Bce,Uce,Gce,Hce,jce,$ce,zce,Vce,Wce]);z.object({testId:z.string(),sessionId:z.string()});var KG=z.object({uploadUrl:z.string(),id:z.string()});new Set(Object.values(Cn));var on={AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of a conditional check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",BLUR:"Remove focus from an element on the page.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",CLOSE_TAB:"Close a specified open tab or current tab if none specified.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock."};z.string().refine(e=>Hh.valid(e),{error:"must be a valid semver string"});function Vf(e){if(e!==void 0)return e===true||e==="true"||e==="1"}function YG(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var gA=55555,fA="momentic-code-eval.js";z.object({body:z.string(),to:z.string(),from:z.string()});z.object({from:z.string().optional(),to:z.string(),timeout:z.number().optional(),beforeDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional()});z.object({timeoutMs:z.number().nonnegative().optional()}).optional();z.object({phoneNumber:z.string(),leaseToken:z.string()});var Jce=z.union([z.string(),z.date()]).transform(e=>e instanceof Date?e:new Date(e)),JG=z.object({phoneNumber:z.string(),expiresAt:Jce,leaseToken:z.string()});z.object({to:z.email(),from:z.string(),subject:z.string(),body:z.string(),html:z.string().optional()});z.object({inbox:z.string().transform(e=>e.toLowerCase()),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),timeout:z.number().optional(),trimWhitespace:z.boolean().optional()});z.object({inbox:z.string(),limit:z.number().optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),trimWhitespace:z.boolean().optional()});var QG=z.object({email:z.string(),prefix:z.string(),expiresAt:z.coerce.date()}),yA=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(yA||{}),XG=z.object({body:z.string().nullish(),status:z.number().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}),Qce=z.object({url:z.string(),options:z.object({method:z.string(),body:z.string().nullish(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),Xce=z.object({body:z.string().nullish(),options:z.object({status:z.number(),statusText:z.string().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),ZG=z.object({result:z.unknown().optional(),variableUpdates:z.record(z.string(),z.unknown().optional()).optional(),persistentVariableUpdates:z.record(z.string(),z.unknown().optional()).optional(),error:z.string().optional(),success:z.boolean()});z.object({id:z.string().optional(),orgId:z.string(),momenticLambdaAuthHash:z.string(),code:z.string(),fragment:z.boolean(),state:z.object({env:z.record(z.string(),z.unknown().optional()),request:Qce,response:Xce,additionalBindings:z.record(z.string(),z.unknown().optional()).optional()}),timeoutMs:z.number().optional(),disallowVariableUpdates:z.boolean().optional(),responseSerialization:z.enum(yA).optional()});var id=9e4;var Zce=w.object({url:w.string(),lineNumber:w.number(),columnNumber:w.number()}),ej=w.object({timestamp:w.number(),text:w.string(),type:w.string(),tabIndex:w.number(),args:w.unknown().optional().array().optional(),url:w.string().optional(),location:Zce.optional()}),tj=ej.array(),q_=tj.array();var zf=class{async getConsoleLogsForRunAttempt(t,n,o){}async getNetworkLogsForRunAttempt(t,n,o){}async getHtmlSnapshot(t,n){}async getA11yTreeSnapshot(t,n){}async getScreenshot(t,n){}async storeConsoleLogsForRunAttempt(t,n,o,r){}async storeNetworkLogsForRunAttempt(t,n,o,r){}listVideoAssetPaths(){return []}close(){}async storeScreenshot(t,n,o){}async storeOnDemandScreenshotById(t,n,o,r){}async storeHtmlSnapshot(t,n,o){}};var ede=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),tde=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),nde=z.object({onContentLoad:z.number().optional(),onLoad:z.number().optional(),comment:z.string().optional()}),Wf=z.object({startedDateTime:z.string(),id:z.string(),title:z.string().optional(),pageTimings:nde,comment:z.string().optional()}),ode=z.array(Wf),rde=z.object({name:z.string(),value:z.string(),path:z.string().optional(),domain:z.string().optional(),expires:z.string().optional(),httpOnly:z.boolean().optional(),secure:z.boolean().optional(),comment:z.string().optional()}),oj=z.array(rde),ide=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),rj=z.array(ide),sde=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),ade=z.array(sde),lde=z.object({name:z.string(),value:z.string().optional(),fileName:z.string().optional(),contentType:z.string().optional(),comment:z.string().optional()}),cde=z.array(lde),dde=z.object({mimeType:z.string(),params:cde,text:z.string(),comment:z.string().optional(),_redactedReason:z.string().optional()}),ude=z.object({method:z.string(),url:z.string(),httpVersion:z.string().optional(),cookies:oj,headers:rj,queryString:ade,postData:dde.optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional()}),pde=z.object({size:z.number().optional(),compression:z.number().optional(),mimeType:z.string().optional(),text:z.string().optional(),encoding:z.string().optional(),comment:z.string().optional(),_redactedReason:z.string().optional()}),mde=z.object({status:z.number(),statusText:z.string(),httpVersion:z.string().optional(),cookies:oj,headers:rj,content:pde,redirectURL:z.string().optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional(),_mocked:z.boolean().optional()}),nj=z.object({expires:z.string().optional(),lastAccess:z.string(),eTag:z.string(),hitCount:z.number(),comment:z.string().optional()}),hde=z.object({beforeRequest:nj.optional(),afterRequest:nj.optional(),comment:z.string().optional()}),gde=z.object({blocked:z.number().optional(),dns:z.number().optional(),connect:z.number().optional(),send:z.number(),wait:z.number(),receive:z.number(),ssl:z.number().optional(),comment:z.string().optional()}),qf=z.object({pageref:z.string().optional(),startedDateTime:z.string(),time:z.number().optional(),request:ude,response:mde.optional(),cache:hde.optional(),timings:gde,serverIPAddress:z.string().optional(),connection:z.string().optional(),comment:z.string().optional(),_resourceType:z.string().optional()}),fde=z.array(qf),yde=z.object({version:z.string().default("1.1"),creator:ede.optional(),browser:tde.optional(),pages:ode.optional(),entries:fde,comment:z.string().optional()});z.object({log:yde});z.record(z.string(),Wf);z.record(z.string(),qf);function K_(e,t){return {log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(e).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime()),entries:Object.values(t).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime())}}}var Y_=(h=>(h.DisableClickhouseCaches="disable_clickhouse_caches",h.ShowZeroOpacityElements="show_zero_opacity_elements",h.VisualActions="visual_actions",h.RagV2="rag_v2",h.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",h.GlobalLocatorRedirect="global_locator_redirect",h.FakerConstantSeed="faker_constant_seed",h.AutoExpandIframes="auto_expand_iframes",h.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",h.PerformanceInsights="performance_insights",h.ShowKnowledgeBase="show_knowledge_base",h.AppGraphBackend="app_graph_backend",h.AppGraphUI="app_graph_ui",h.WebEditorV3="web_editor_v3",h))(Y_||{});var sd=z.union([z.string(),z.number(),z.boolean(),z.null(),z.record(z.string(),z.lazy(()=>sd)),z.array(z.lazy(()=>sd))]),Kf=class{flags;payloads;constructor(t,n){this.flags=t,this.payloads=n;}isBooleanFlagEnabled(t){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="true"?true:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="false"?false:this.flags[t]===true}getAllFlags(){let t=cloneDeep(this.flags);return Object.entries(t).forEach(([n,o])=>{typeof o=="boolean"&&Object.values(Y_).includes(n)&&(t[n]=this.isBooleanFlagEnabled(n));}),t}getFlagPayload(t){let n=this.payloads[t];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}};var Yf={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},ij=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var sj=z.discriminatedUnion("operation",[z.object({operation:z.literal("upsert"),path:z.string().min(1),content:z.string()}),z.object({operation:z.literal("delete"),path:z.string().min(1)})]),Tde=z.object({githubLogin:z.string().optional(),email:z.string().optional()}),Ade=z.object({baseSha:z.string().min(1),headSha:z.string().min(1)}),Ede=z.object({baseBranch:z.string().min(1).max(255),baseCommitSha:z.string().min(1),headBranch:z.string().min(1).max(255).optional(),branchPrefix:z.string().min(1).max(255).optional(),idempotencyKey:z.string().min(1).optional()}),Cde=z.object({commitMessage:z.string().min(1),title:z.string().min(1),body:z.string(),reviewers:z.array(z.string().min(1)).optional(),draft:z.boolean().optional()});Ede.extend(Cde.shape).extend({changes:z.array(sj).min(1),coAuthorRange:Ade.optional()}).superRefine((e,t)=>{e.headBranch||(!e.branchPrefix||!e.idempotencyKey)&&t.addIssue({code:"custom",message:"branchPrefix and idempotencyKey are required when headBranch is omitted",path:["idempotencyKey"]});});var aj=z.object({pullRequestUrl:z.url(),pullRequestNumber:z.number(),headBranch:z.string(),commitSha:z.string(),created:z.boolean(),authors:z.array(Tde).optional()});z.object({branch:z.string().min(1).max(255),commitMessage:z.string().min(1),changes:z.array(sj).min(1)});var lj=z.object({branch:z.string(),commitSha:z.string(),committed:z.boolean()}),cj=z.object({issueNumber:z.number(),htmlUrl:z.url(),headBranch:z.string().min(1),baseBranch:z.string().min(1),latestCommitSha:z.string().min(1),title:z.string().optional(),body:z.string().optional()}),Rde=z.object({path:z.string().min(1),status:z.string().min(1),additions:z.number(),deletions:z.number(),previousPath:z.string().optional(),patch:z.string().optional()}),vde=z.object({sha:z.string().min(1),author:z.string().optional(),email:z.string().optional(),date:z.string().optional(),message:z.string()}),dj=z.object({mergeBaseSha:z.string().min(1),totalCommits:z.number(),commits:z.array(vde),files:z.array(Rde)}),uj=z.object({content:z.string().nullable()}),pj=z.object({name:z.string().min(1),protected:z.boolean()}),mj=z.object({iid:z.number(),webUrl:z.url(),sourceBranch:z.string().min(1),targetBranch:z.string().min(1),latestCommitSha:z.string().min(1)}),wde=z.object({name:z.string(),path:z.string(),body:z.string()}),hj=z.object({template:wde});function Io(e){let[t,n,...o]=e.split("/");if(!(!t||!n||o.length>0))return {owner:t,repo:n}}function gj(e){let t=Io(e);if(t)return t;throw new dt(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var Ide=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,xde=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function SA(e){return e.match(xde)?.[1]}function fj(e){let t=[];for(let n of e.matchAll(Ide)){let o=n[1]?.trim();o&&t.push({email:o,githubLogin:SA(o)});}return t}function _de(e){return (e.githubLogin??(e.email?SA(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function yj(e){return e.filter(t=>!_de(t))}var bA=z.enum(["TERMINOLOGY","AGENT_RULE","FLOW"]),Jf=z.enum(["CANDIDATE","ACTIVE","PENDING_CONFLICT","REJECTED","ARCHIVED"]),J_=z.enum(["MANUAL","CRAWLER","SYSTEM","GENERATED","IMPORTED"]),Pde=z.enum(["PENDING","INDEXING","INDEXED","FAILED"]);var Q_=z.enum(["locator","assertion","visual-assertion","text-extraction","failure-recovery","result-classification","ai-action"]),Qf=z.object({canonicalTerm:z.string().min(1),definition:z.string().min(1),examples:z.array(z.string().min(1)).default([])}),Mde=z.object({agentSubtype:Q_,instruction:z.string().min(1)}),Xf=z.object({intent:z.string().min(1),steps:z.string().min(1),successState:z.string().min(1)}),TA=z.discriminatedUnion("type",[z.object({type:z.literal("TERMINOLOGY"),data:Qf}),z.object({type:z.literal("AGENT_RULE"),data:Mde}),z.object({type:z.literal("FLOW"),data:Xf})]);var Sj=z.discriminatedUnion("source",[z.object({source:z.literal("MANUAL"),userId:z.string().nullable()}),z.object({source:z.literal("CRAWLER"),url:z.url().nullable(),crawlerJobId:z.string().nullable(),snippet:z.string().nullable()}),z.object({source:z.literal("GENERATED"),generatorJobId:z.string().nullable(),agentName:z.string().nullable(),rationale:z.string().nullable(),metadata:z.record(z.string(),z.string()).optional()}),z.object({source:z.literal("SYSTEM"),rule:z.string().nullable()}),z.object({source:z.literal("IMPORTED"),importerSource:z.string().nullable(),externalId:z.string().nullable()})]),X_=z.object({id:z.string(),organizationId:z.string(),appId:z.string().nullable(),testId:z.string().nullable(),environmentId:z.string().nullable(),type:bA,status:Jf,source:J_,trust:z.int().min(0).max(100),title:z.string(),body:z.string(),data:TA,provenance:Sj,contentHash:z.string(),indexingState:Pde,indexedVersion:z.int().nullable(),currentVersion:z.int(),retrievalCount:z.int(),lastRetrievedAt:z.iso.datetime().nullable(),createdByUserId:z.string().nullable(),updatedByUserId:z.string().nullable(),createdAt:z.iso.datetime(),updatedAt:z.iso.datetime()});z.object({id:z.string(),itemId:z.string(),organizationId:z.string(),version:z.int(),title:z.string(),body:z.string(),data:TA,status:Jf,trust:z.int().min(0).max(100),changedByUserId:z.string().nullable(),changedBySystem:z.string().nullable(),changeNote:z.string().nullable(),changedAt:z.iso.datetime()});var Ode=z.object({appId:z.string().nullable().optional(),testId:z.string().nullable().optional(),environmentId:z.string().nullable().optional()});Ode.extend({type:bA,status:Jf.optional(),source:J_,trust:z.int().min(0).max(100).optional(),title:z.string().min(1).max(500),data:TA,provenance:Sj});z.object({title:z.string().min(1).max(500).optional(),data:TA.optional(),status:Jf.optional(),trust:z.int().min(0).max(100).optional(),appId:z.string().nullable().optional(),testId:z.string().nullable().optional(),environmentId:z.string().nullable().optional(),changeNote:z.string().nullable().optional()}).refine(e=>Object.entries(e).some(([t,n])=>t!=="changeNote"&&n!==void 0),{error:"at least one updatable field is required"});z.object({appId:z.string().nullable().optional(),type:wo(bA),status:wo(Jf),source:wo(J_),agentSubtype:wo(Q_),testId:z.string().optional(),environmentId:z.string().optional(),search:z.string().optional(),page:z.coerce.number().int().min(1).prefault(1),pageSize:z.coerce.number().int().min(1).max(200).prefault(50)});var bj=z.enum(["active-only","active-plus-candidates","review"]);z.object({query:z.string().min(1),appId:z.string().nullable().optional(),types:bA.array().min(1).max(3).optional(),agentSubtype:Q_.optional(),testId:z.string().nullable().optional(),environmentId:z.string().nullable().optional(),mode:bj.default("active-only"),limit:z.int().min(1).max(50).default(10),clientName:z.string().min(1).max(100),scoreMultiplier:z.number().positive().max(100).default(1)});var Nde=z.object({combined:z.number(),lexical:z.number().nullable(),vector:z.number().nullable()}),Lde=z.object({item:X_,rank:z.int().min(1),score:Nde,topChunkIndex:z.int().nullable()}),Tj=z.object({hits:z.array(Lde),mode:bj});var Z_=w__default.object({platformSep:w__default.string(),fullPathSegments:w__default.string().array(),relativePathSegments:w__default.string().array(),relativePath:w__default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:w__default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:w__default.coerce.date(),createdAt:w__default.coerce.date()});var kde=z.array(Z_.extend({id:z.string(),name:z.string(),description:z.string().optional(),labels:z.string().array().optional()})),Dde=Z_.extend({id:z.string(),name:z.string(),description:z.string().optional(),content:AT}),Fde=z.array(Dde);z.object({tests:kde,modules:Fde,labels:z.string().array()});z.string().array();var Aj=z.object({pathSegments:z.string().array()});r_.merge(Wn);var Ej=z.object({schemaVersion:z.string(),stepLists:Jc}),Cj=Wn.partial().merge(Tr.pick({id:true})),Zf="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",eP={name:z.string().min(1).max(255).describe(Zf),description:z.string().optional(),baseUrl:z.url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:z.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:z.enum(za).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Jl.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:z.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder. Paths are relative to the project root.")},Rj=z.object(eP);r_.extend(z.object({relativeFilePath:z.string().describe("relative to project root")}).shape);var vj=z.object({name:z.string()});z.object({relativeFilePath:z.string()});var wj=z.object({name:z.string(),sourceModuleContent:AT});z.object({relativeFilePath:z.string()});var Ij=z.object({name:z.string(),description:z.string(),enabled:z.boolean(),steps:z.lazy(()=>Yt.array()),testFilePath:z.string().describe("relative to the project root"),folderPath:z.string().optional().describe("user selected folder path")}),xj=z.object({name:z.string(),description:z.string(),enabled:z.boolean()}).partial(),_j=z.object({folderPath:z.string()}),Pj=z.object({folderPath:z.string()});z.array(TU);var Mj=z.object({defaultEnv:z.string().optional().describe("name of the default env, or undefined to unset")}),Oj=z.object({configFilePath:z.string().describe("full path on disk")});z.string().array();z.object({message:z.string(),newRelativeTestPath:z.string().optional()});var tP=z.object({name:z.string(),absolutePath:z.string(),relativePath:z.string(),pathSegments:z.array(z.string()),isDirectory:z.boolean(),size:z.number(),createdAt:z.coerce.date(),modifiedAt:z.coerce.date(),accessedAt:z.coerce.date()}),Nj=z.object({pathSegments:z.array(z.string())});z.object({absolutePath:z.string(),pathSegments:z.array(z.string()),contents:z.array(tP)});var Lj=z.object({sourceDirectoryPath:z.string().optional(),value:z.string(),allowedExtensions:z.array(z.string()).optional()}),Bde=z.object({name:z.string(),value:z.string(),isDirectory:z.boolean()});z.object({suggestions:z.array(Bde)});var kj=z.object({pathSegments:z.array(z.string())}),Dj=z.object({pathSegments:z.array(z.string()),newPathSegments:z.array(z.string())}),Fj=z.object({pathSegments:z.array(z.string()),recursive:z.boolean().optional()});z.object({success:z.boolean(),message:z.string(),pathSegments:z.array(z.string()).optional()});z.object({gitBranch:z.string(),fileMtime:z.coerce.date(),gitCommitSha:z.string()});var Bj=typeof process<"u"&&true&&true,AA=58889;var Uj=z.object({id:z.string(),createdAt:z.coerce.date(),createdBy:z.string(),organizationId:z.string(),name:z.string(),description:z.string().nullish(),enabled:z.boolean(),schemaVersion:z.string().describe("Schema version for steps"),parameters:z.string().array().nullish().describe("Parameter list"),parameterEnums:z.record(z.string(),z.string().array()).nullish(),defaultParameters:z.record(z.string(),z.string()).nullish(),defaultCacheKey:z.string().nullish(),defaultCacheTtl:z.number().nullish(),defaultCacheAllInvocations:z.boolean().nullish(),autoAuth:z.boolean().nullish(),defaultRetries:z.int().min(0).nullish(),advanced:Rx.nullish()});Uj.extend({steps:z.lazy(()=>_t.array())});var Hj=5*60*1e3,EA=Rn.extend(Uj.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var Ude="org_01HMJTX4GT1KG94KZRCT8MZ6YB",Hde="org_01HMSCJQBCCG51M2ZF65YC5B8W",Gde="org_01JPR6MGFQSHF3W234R3XJDPMB",jde=[Ude,Hde,Gde];function Gj(e){return jde.includes(e)}var jj=(o=>(o.AZURE="AZURE",o.KERNEL="KERNEL",o.BROWSERBASE="BROWSERBASE",o))(jj||{}),nP=z.enum(jj);z.object({azureRegion:z.string().optional(),azureWorkspaceId:z.string().optional()});z.object({});var $de=z.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z.object({region:$de.optional()});var oP=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(oP||{});var Vde=z.object({type:z.literal("DESCRIPTION_UPDATE"),thoughts:z.string()}),CA=z.discriminatedUnion("type",[Vde]),zde=z.object({testId:z.string(),name:z.string(),orgId:z.string(),runId:z.string(),steps:Yt.array(),purpose:z.enum(oP),details:CA.or(CA.array()).optional()});zde.pick({name:true,orgId:true});var Wde=z.object({id:z.string(),name:z.string().nullish(),createdAt:z.string().pipe(z.coerce.date()).or(z.date()),organizationId:z.string(),schemaVersion:z.string(),runId:z.string().nullish(),purpose:z.enum(oP),details:CA.or(CA.array()).optional(),applied:z.boolean().nullish(),appliedAt:z.coerce.date().nullish()}),$j=Wde.extend({steps:Yt.array()});var Vj=z.enum(["v1","v2"]);var Kde=z.enum(["element","content","attribute","tag_name","style"]),RA=z.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...MB,...PB].forEach(e=>{if(!RA.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var rP={element:{aliasPrefix:"",assertionType:"ELEMENT_EXISTENCE",requiresName:false},content:{aliasPrefix:"Content",assertionType:"ELEMENT_CONTENT",requiresName:false},attribute:{aliasPrefix:"Attribute",assertionType:"ELEMENT_ATTRIBUTE",requiresName:true},tag_name:{aliasPrefix:"Name",assertionType:"ELEMENT_NAME",requiresName:false},style:{aliasPrefix:"Style",assertionType:"ELEMENT_STYLE",requiresName:true}},qj={exists:{positiveAliasSuffix:"Exists",negativeAliasSuffix:"DoesNotExist",elementCondition:"EXISTS",contentOperation:"EXISTS"},visible:{positiveAliasSuffix:"Visible",negativeAliasSuffix:"NotVisible",elementCondition:"VISIBLE"},enabled:{positiveAliasSuffix:"Enabled",negativeAliasSuffix:"NotEnabled",elementCondition:"ENABLED"},editable:{positiveAliasSuffix:"Editable",negativeAliasSuffix:"NotEditable",elementCondition:"EDITABLE"},focused:{positiveAliasSuffix:"Focused",negativeAliasSuffix:"NotFocused",elementCondition:"FOCUSED"},contains:{positiveAliasSuffix:"Contains",negativeAliasSuffix:"DoesNotContain",contentOperation:"CONTAINS"},equals:{positiveAliasSuffix:"Equals",negativeAliasSuffix:"DoesNotEqual",contentOperation:"EQUALS"},starts_with:{positiveAliasSuffix:"StartsWith",negativeAliasSuffix:"DoesNotStartWith",contentOperation:"STARTS_WITH"}},Kj={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function zj(e){return {alias:iP(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:rP[e.subject].assertionType,requiresName:rP[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function iP(e){let t=rP[e.subject],n=qj[e.condition];if(!Yj(e.subject,e.condition))throw new Error(`Unsupported element check alias for subject '${e.subject}' and condition '${e.condition}'.`);let o=e.negated?n.negativeAliasSuffix:n.positiveAliasSuffix;return `checkElement${t.aliasPrefix}${o}`}function Yj(e,t){let n=qj[t],o=n.elementCondition,r=n.contentOperation;return e==="element"?o!==void 0:r!==void 0}var Yde=Kde.options.flatMap(e=>RA.options.flatMap(t=>Yj(e,t)?[zj({subject:e,condition:t,negated:false}),zj({subject:e,condition:t,negated:true})]:[])),Jj=new Map(Yde.map(e=>[e.alias,e]));var Jde=z.enum(Na),Qde=z.enum(vi);function qr(e){return Jj.get(e)}function Xj(e){let t=Kj[e.type],n=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return iP({subject:t,condition:Xde(n),negated:e.negated})}function Zj(e){return Jde.parse(e.toUpperCase())}function ey(e){return Qde.parse(e.toUpperCase())}function Xde(e){return RA.parse(e.toLowerCase())}var Ke={saveAs:z.string().optional(),retries:z.number().optional(),skipped:z.boolean().optional(),comment:z.string().optional()};z.object(Ke);var vA=Object.keys(Ke);function Ge(e){return z.union([z.strictObject({[e.key]:e.simplified}),z.strictObject({[e.key]:e.detailed})])}function Tn(e){return z.strictObject({[e.key]:e.detailed})}var e$='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Vm=z.union([Pa,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,e$)],{error:e$});z.union([z.string(),Pa]);var Di={css:z.string().optional(),coords:Vm.optional(),x:z.union([z.number(),z.string()]).optional(),y:z.union([z.number(),z.string()]).optional()},aP={on:z.string().optional(),...Di},Fi={...Ke,useSelector:z.boolean().optional(),force:z.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional()},ty={...Fi,offset:Vm.optional()};function Kr({schema:e,descriptionKey:t,required:n=true}){return e.superRefine((o,r)=>{let s=[t in o?Object.entries(o).find(([a])=>a===t)?.[1]:void 0,"css"in o?o.css:void 0,"coords"in o?o.coords:void 0,"x"in o||"y"in o?true:void 0].filter(a=>a!==void 0).length;n&&s!==1&&r.addIssue({code:"custom",message:`Use exactly one target: ${t}, css, coords, or x/y.`}),!n&&s>1&&r.addIssue({code:"custom",message:`Use at most one target: ${t}, css, coords, or x/y.`}),("x"in o||"y"in o)&&(!("x"in o)||o.x===void 0||!("y"in o)||o.y===void 0)&&r.addIssue({code:"custom",message:"x and y must be provided together."});})}var Zde=Kr({descriptionKey:"on",schema:z.strictObject({...aP,...ty,times:z.int().min(1).optional(),rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),eue=Kr({descriptionKey:"on",schema:z.strictObject({...aP,...ty,rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),tue=Kr({descriptionKey:"on",schema:z.strictObject({...aP,...ty,times:z.int().min(1).optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),t$=Ge({key:"click",simplified:z.string(),detailed:Zde}),n$=Ge({key:"doubleClick",simplified:z.string(),detailed:eue}),o$=Ge({key:"rightClick",simplified:z.string(),detailed:tue}),nue=Kr({descriptionKey:"into",required:false,schema:z.strictObject({text:z.string(),into:z.string().optional(),...Di,...ty,pressEnter:z.boolean().optional(),clear:z.union([z.literal("inputs"),z.literal("always"),z.literal("never"),z.boolean()]).optional(),delay:z.number().optional()})}),r$=Ge({key:"type",simplified:z.string(),detailed:nue}),i$=Tn({key:"select",detailed:Kr({descriptionKey:"from",schema:z.strictObject({from:z.string().optional(),...Di,label:z.string().optional(),value:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),...Fi})}).superRefine((e,t)=>{[e.label,e.value,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"select requires exactly one of label, value, or index"});})}),s$=Ge({key:"hover",simplified:z.string(),detailed:Kr({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Di,...ty})})}),a$=Tn({key:"blur",detailed:Kr({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Di,...Fi})})}),l$=Ge({key:"focus",simplified:z.string(),detailed:Kr({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Di,...Fi})})}),c$=Tn({key:"dragAndDrop",detailed:z.strictObject({from:z.string().optional(),to:z.string().optional(),fromCss:z.string().optional(),toCss:z.string().optional(),fromCoords:Vm.optional(),toCoords:Vm.optional(),fromX:z.union([z.number(),z.string()]).optional(),fromY:z.union([z.number(),z.string()]).optional(),toX:z.union([z.number(),z.string()]).optional(),toY:z.union([z.number(),z.string()]).optional(),steps:z.number().optional(),hover:z.number().optional(),...Fi}).superRefine((e,t)=>{let n=[e.from,e.fromCss,e.fromCoords,e.fromX!==void 0||e.fromY!==void 0?true:void 0].filter(r=>r!==void 0).length,o=[e.to,e.toCss,e.toCoords,e.toX!==void 0||e.toY!==void 0?true:void 0].filter(r=>r!==void 0).length;n!==1&&t.addIssue({code:"custom",message:"Use exactly one from target."}),o!==1&&t.addIssue({code:"custom",message:"Use exactly one to target."}),(e.fromX!==void 0||e.fromY!==void 0)&&(e.fromX===void 0||e.fromY===void 0)&&t.addIssue({code:"custom",message:"fromX and fromY must be provided together."}),(e.toX!==void 0||e.toY!==void 0)&&(e.toX===void 0||e.toY===void 0)&&t.addIssue({code:"custom",message:"toX and toY must be provided together."});})}),d$=z.union([z.strictObject({mouseDrag:Vm}),z.strictObject({mouseDrag:Kr({descriptionKey:"from",required:false,schema:z.strictObject({from:z.string().optional(),...Di,delta:Vm,steps:z.number().optional(),...Fi})})})]),u$=Ge({key:"press",simplified:z.string(),detailed:z.strictObject({key:z.string(),repeat:z.number().optional(),delay:z.number().optional(),convertMeta:z.boolean().optional(),...Ke})}),p$=Ge({key:"keyDown",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Ke})}),m$=Ge({key:"keyUp",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Ke})}),h$=Ge({key:"navigate",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:z.number().optional(),...Ke})}),g$=Ge({key:"newTab",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:z.number().optional(),...Ke})}),f$=Ge({key:"switchTab",simplified:z.union([z.number(),z.string()]),detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"switchTab requires exactly one of substring, regex, or index"});})}),y$=Tn({key:"closeTab",detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length<=1||t.addIssue({code:"custom",message:"closeTab accepts at most one of substring, regex, or index"});})}),S$=Tn({key:"goBack",detailed:z.strictObject(Ke)}),b$=Tn({key:"goForward",detailed:z.strictObject(Ke)}),T$=Tn({key:"refresh",detailed:z.strictObject({timeout:z.number().optional(),...Ke})}),wA=z.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),A$=Ge({key:"scrollUp",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),E$=Ge({key:"scrollDown",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),C$=Ge({key:"scrollLeft",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),R$=Ge({key:"scrollRight",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),v$=Ge({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...Ke})}),oue=Ge({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Ke})}),rue=Ge({key:"assertVisually",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Ke})}),IA=oue,xA=rue,w$=Ge({key:"checkPageContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Ke})}),I$=Ge({key:"checkPageDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Ke})}),lP=z.union([w$,I$]),iue=z.record(z.string(),z.unknown().optional()),_A=iue.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qr(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=Kr({descriptionKey:"element",schema:z.looseObject({element:z.string().optional(),...Di,...Fi,timeout:z.number().optional(),name:z.string().optional(),value:z.string().optional()})}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),x$=Ge({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:sd.optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),...Ke})}),_$=Ge({key:"cookie",simplified:z.string(),detailed:z.strictObject({value:z.string(),...Ke})}),P$=Tn({key:"localStorage",detailed:z.strictObject({key:z.string(),value:z.string(),...Ke})}),M$=Ge({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:jl.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:sd.optional(),contentType:z.enum(La).optional(),timeout:z.number().optional(),...Ke})}),O$=Tn({key:"graphqlRequest",detailed:z.strictObject({url:z.string(),query:z.string(),variables:sd.optional(),headers:z.record(z.string(),z.string()).optional(),timeout:z.number().optional(),...Ke})}),PA=Ge({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),environment:z.enum(["node","browser","NODE","BROWSER"]).optional(),fragment:z.boolean().optional(),timeout:z.number().optional(),...Ke})}),zm={substring:z.string().optional(),glob:z.string().optional(),regex:z.string().optional(),domain:z.string().optional()};function sue(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Wm(e){let t=sue(e.payload);if(e.required&&t!==1||!e.required&&t>1){e.ctx.addIssue({code:"custom",message:e.required?"requires exactly one of substring, glob, regex, or domain":"requires at most one of substring, glob, regex, or domain"});return}!e.required&&t===0&&e.payload.method&&e.ctx.addIssue({code:"custom",message:"method requires a URL matcher"});}var N$=Tn({key:"header",detailed:z.strictObject({name:z.string(),value:z.string(),...zm,method:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:false});})}),L$=Tn({key:"mock",detailed:z.strictObject({...zm,method:z.string().optional(),responseGenerator:z.string(),fetchOriginalResponse:z.boolean().optional(),key:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),k$=Ge({key:"removeRouteMock",simplified:z.string(),detailed:z.strictObject({key:z.string(),...Ke})}),D$=Ge({key:"waitForUrl",simplified:z.string(),detailed:z.strictObject({...zm,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),F$=Ge({key:"waitForUrlNotToMatch",simplified:z.string(),detailed:z.strictObject({...zm,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),aue=z.union([D$,F$]),B$=Ge({key:"dialog",simplified:z.enum(["ACCEPT","DISMISS"]),detailed:z.strictObject({action:z.enum(["ACCEPT","DISMISS"]),...Ke})}),U$=Ge({key:"fileUpload",simplified:z.string(),detailed:z.strictObject({path:z.string(),name:z.string().optional(),...Ke})}),H$=Ge({key:"copy",simplified:z.union([z.string(),z.boolean(),z.null()]),detailed:z.strictObject({value:z.union([z.string(),z.boolean(),z.null()]),...Ke})}),G$=Tn({key:"paste",detailed:z.strictObject(Ke)}),j$=Tn({key:"captcha",detailed:z.strictObject({...Fi})}),lue=z.strictObject({data:z.union([z.string(),Us]),width:z.number(),height:z.number()}),$$=Ge({key:"visualDiff",simplified:z.string(),detailed:Kr({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Di,threshold:z.number().optional(),screenshot:lue.optional(),...Fi})})}),V$=Tn({key:"offline",detailed:z.strictObject(Ke)}),z$=Tn({key:"online",detailed:z.strictObject(Ke)}),W$=Tn({key:"registerRequestListener",detailed:z.strictObject({...zm,key:z.string(),method:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),q$=Ge({key:"awaitListener",simplified:z.string(),detailed:z.strictObject({key:z.string(),timeout:z.number().optional(),...Ke})}),K$=Tn({key:"recordRequests",detailed:z.strictObject({...zm,key:z.string(),method:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),Y$=Ge({key:"getRecordedRequests",simplified:z.string(),detailed:z.strictObject({key:z.string(),...Ke})}),J$=Ge({key:"authLoad",simplified:z.string(),detailed:z.strictObject({path:z.string(),...Ke})}),Q$=Ge({key:"authSave",simplified:z.string(),detailed:z.strictObject({path:z.string().optional(),...Ke})});z.union([t$,n$,o$,f$,y$,r$,i$,s$,a$,l$,c$,d$,u$,p$,m$,h$,g$,S$,b$,T$,A$,E$,C$,R$,v$,IA,xA,lP,x$,_$,P$,M$,O$,PA,N$,L$,k$,aue,B$,U$,H$,G$,j$,$$,V$,z$,W$,q$,K$,Y$,J$,Q$,_A]);var X$=new Map([["click",t$],["doubleClick",n$],["rightClick",o$],["switchTab",f$],["closeTab",y$],["type",r$],["select",i$],["hover",s$],["blur",a$],["focus",l$],["dragAndDrop",c$],["mouseDrag",d$],["press",u$],["keyDown",p$],["keyUp",m$],["navigate",h$],["newTab",g$],["goBack",S$],["goForward",b$],["refresh",T$],["scrollUp",A$],["scrollDown",E$],["scrollLeft",C$],["scrollRight",R$],["wait",v$],["assert",IA],["assertVisually",xA],["checkPageContains",w$],["checkPageDoesNotContain",I$],["extract",x$],["cookie",_$],["localStorage",P$],["request",M$],["graphqlRequest",O$],["javascript",PA],["header",N$],["mock",L$],["removeRouteMock",k$],["waitForUrl",D$],["waitForUrlNotToMatch",F$],["dialog",B$],["fileUpload",U$],["copy",H$],["paste",G$],["captcha",j$],["visualDiff",$$],["offline",V$],["online",z$],["registerRequestListener",W$],["awaitListener",q$],["recordRequests",K$],["getRecordedRequests",Y$],["authLoad",J$],["authSave",Q$]]),Z$=Object.freeze([...X$.keys()]),Za=z.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"Steps must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"Steps must have exactly one action key."});return}let r=X$.get(o)??(qr(o)?_A:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported step type '${o}'.`});return}let i=r.safeParse(e);if(!i.success){let s=cue(i.error.issues,o);s.length>0&&eV(t,s);}});function cue(e,t){return due(e).filter(n=>!uue(n,t))}function eV(e,t){for(let n of t){if(n.code==="invalid_union"){eV(e,cP(n));continue}e.addIssue({...n});}}function due(e){let t=[];for(let n of e){if(n.code==="invalid_union"){t.push(...cP(n));continue}t.push(n);}return t}function uue(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function cP(e){let t=e.errors[0]??[],n=sP(t);for(let o of e.errors.slice(1)){let r=sP(o);r>n&&(t=o,n=r);}return t}function sP(e){return e.reduce((t,n)=>{let o=n.code==="invalid_union"?sP(cP(n)):0;return t+n.path.length+o},0)}var tV=z.strictObject({string:z.string()}),pue=z.strictObject({javascript:z.string()}),nV=z.union([tV,pue]),mue=z.union([z.strictObject({name:z.string(),required:z.boolean().optional(),default:tV.optional()}),z.strictObject({name:z.string(),required:z.boolean().optional(),defaultValue:z.string()})]),oV=mue.array(),hue=z.strictObject({name:z.string(),default:nV.optional(),enum:z.array(z.string()).optional()}),rV=hue.array(),ny=z.union([nV,z.string()]),iV=z.record(z.string(),ny);var gue=z.preprocess(e=>typeof e=="number"?String(e):e,dx),MA=z.looseObject({goal:z.string(),version:gue.optional(),...Ke}),fue=z.union([z.strictObject({act:z.string()}),z.strictObject({act:MA})]),dP=z.looseObject({path:z.string(),inputs:z.record(z.string(),ny).optional(),...Ke}),yue=z.union([z.strictObject({module:z.string()}),z.strictObject({module:dP})]),qm=z.union([IA,xA,lP,PA,_A]),Sue=new Set(["then",...vA]),bue=z.looseObject({then:z.lazy(()=>el.array()),...Ke}).superRefine((e,t)=>{Object.entries(e).filter(([o,r])=>!Sue.has(o)&&qm.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),Tue=z.strictObject({if:bue}),el=z.lazy(()=>z.union([wA,fue,yue,Tue,Za]));z.object({before:el.array().optional(),steps:el.array(),after:el.array().optional()});var Aue=z.union([Jl,z.string().refine(e=>{let t=e.match(/^\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*$/);if(!t)return false;let[,n,o]=t;return Jl.safeParse({width:Number(n),height:Number(o)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),Eue=_i.omit({viewport:true}).extend({viewport:Aue.optional()}),uP=z.object({id:Ln,version:z.string(),url:CT.optional(),description:z.string().optional(),retries:z.number().optional(),defaultEnv:z.string().optional(),parameters:oV.optional(),outputs:WT.optional(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional()}).extend(Eue.shape),ld=z.looseObject({fileType:z.literal(we.TEST_V2)}).extend(uP.shape).extend({before:el.array().optional(),steps:el.array(),after:el.array().optional()});var Cue=z.array(z.string()),Rue=z.union([z.string(),z.record(z.string(),z.unknown().optional())]),OA=Rn.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:Ln,version:z.string(),name:z.string().optional(),parameters:z.union([rV,Cue]).optional(),defaultParameters:z.record(z.string(),z.string()).optional(),parameterEnums:z.record(z.string(),z.array(z.string())).optional()}),pP=z.looseObject(OA.extend({fileType:z.literal(we.MODULE_V2),steps:Rue.array().optional()}).shape).superRefine(aV),NA=z.looseObject(OA.extend({fileType:z.literal(we.MODULE_V2),steps:el.array().optional()}).shape).superRefine(aV);function sV(e){return e.steps??[]}function aV(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var mP=(n=>(n.TEST="TEST",n.MODULE="MODULE",n))(mP||{}),vue=z.enum(mP),lV=z.object({orgId:z.string(),entityType:vue,entityId:z.string()}),hP=lV.extend({entityType:z.literal("TEST"),stepLists:Gs}),gP=lV.extend({entityType:z.literal("MODULE"),steps:_t.array()});z.discriminatedUnion("entityType",[hP,gP]);var cV=(o=>(o.WEB="web",o.ANDROID="android",o.IOS="ios",o))(cV||{}),fP=z.nativeEnum(cV);var dV=z.object({entity_type:z.string(),value:z.string()}),uV=Yg(dV),pV=dV.extend({cache_key:z.string()});function ry({entityType:e,entityId:t}){return `${e}:${t}`}var Pu=z.string();var mV='Coordinates must be "x, y" pixel values, e.g. "100, 200"',yV=z.union([Pa,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,mV)],{error:mV}),hV='Percent must be a number or a percent string, e.g. 90 or "90%"',SV=z.union([z.number(),z.string().regex(/^-?\d+(?:\.\d+)?%$/,hV)],{error:hV}).transform(e=>typeof e=="number"?e:Number(e.slice(0,-1))).pipe(z.number().min(0,{message:"Percent must be >= 0"}).max(100,{message:"Percent must be <= 100"})),wue=z.strictObject({x:z.number(),y:z.number(),delta:z.number()}),bV=z.union([z.string(),wue]),gn={...Ke,DANGEROUS_FORCE_DYNAMIC:z.boolean().optional()},Iue=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],xue=["enter","backspace","close_keyboard"],gV=["airplane_mode","data","wifi","location"],fV=["portrait","landscape"],_ue=z.strictObject({on:Pu.optional(),longPress:z.boolean().optional(),longPressDuration:z.number().optional(),iterations:z.number().optional(),tapDelay:z.number().optional(),offset:yV.optional(),...gn}),TV=Ge({key:"tap",simplified:Pu,detailed:_ue}),Pue=z.strictObject({text:z.string(),into:Pu.optional(),clearContent:z.boolean().optional(),forceClearContent:z.boolean().optional(),keyPressDelay:z.number().optional(),...gn}),AV=Ge({key:"type",simplified:z.string(),detailed:Pue}),EV=z.enum(Iue),Mue=z.strictObject({key:EV,longPress:z.boolean().optional(),...gn}),CV=Ge({key:"press",simplified:EV,detailed:Mue}),RV=z.enum(xue),Oue=z.strictObject({key:RV,...gn}),vV=Ge({key:"pressKey",simplified:RV,detailed:Oue}),Nue=z.strictObject({package:z.string(),activity:z.string().optional(),intentExtras:z.string().optional(),...gn}),wV=Ge({key:"openApp",simplified:z.string(),detailed:Nue}),IV=Tn({key:"killApp",detailed:z.strictObject(gn)}),xV=Tn({key:"openNotifications",detailed:z.strictObject(gn)}),_V=z.enum(["up","down","left","right"]),Lue=z.strictObject({direction:_V,in:bV.optional(),viewportPercent:SV.optional(),duration:z.number().optional(),offset:yV.optional(),...gn}),PV=Ge({key:"swipe",simplified:_V,detailed:Lue}),kue=z.enum(["up","down"]),Due=z.strictObject({on:Pu,direction:kue.optional(),in:bV.optional(),scrollStepPercent:SV.optional(),maxScrollAttempts:z.number().optional(),...gn}),MV=Ge({key:"scrollTo",simplified:z.string(),detailed:Due}),yP=Ge({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),...gn})}),OV=Ge({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:sd.optional(),...gn})}),NV=Ge({key:"checkScreenContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...gn})}),LV=Ge({key:"checkScreenDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...gn})}),kV=z.union([NV,LV]),Fue=z.record(z.string(),z.unknown().optional()),SP=Fue.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qr(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=z.looseObject({on:Pu.optional(),timeout:z.number().optional(),name:z.string().optional(),value:z.string().optional(),...gn}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}i.data.on===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a target via 'on'`,path:[r.alias,"on"]}),r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),Bue=z.strictObject({from:Pu,to:Pu,hoverDuration:z.number().optional(),dragDuration:z.number().optional(),...gn}),DV=Tn({key:"dragAndDrop",detailed:Bue}),bP=Ge({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),timeout:z.number().optional(),...gn})}),FV=Ge({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:jl.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:z.string().optional(),bodyType:z.nativeEnum(La).optional(),timeout:z.number().optional(),...gn})}),BV=Ge({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...gn})}),UV=Tn({key:"addFile",detailed:z.strictObject({path:z.string(),location:z.string(),...gn})}),HV=Ge({key:"installApp",simplified:z.string(),detailed:z.strictObject({path:z.string(),...gn})}),GV=Ge({key:"uninstallApp",simplified:z.string(),detailed:z.strictObject({package:z.string(),...gn})}),jV=Ge({key:"toggleSettings",simplified:z.enum(gV),detailed:z.strictObject({setting:z.enum(gV),...gn})}),$V=Ge({key:"rotate",simplified:z.enum(fV),detailed:z.strictObject({orientation:z.enum(fV),...gn})}),VV=Ge({key:"adb",simplified:z.string(),detailed:z.strictObject({command:z.string(),args:z.string().optional(),...gn})}),zV=Tn({key:"appium",detailed:z.strictObject({script:z.string(),args:z.string().optional(),...gn})}),WV=Tn({key:"debugState",detailed:z.strictObject(gn)}),qV=z.enum(["killApp","openNotifications","debugState"]);z.union([TV,AV,CV,vV,wV,IV,xV,PV,MV,yP,OV,kV,DV,bP,FV,BV,UV,HV,GV,jV,$V,VV,zV,WV,SP]);var KV=new Map([["tap",TV],["type",AV],["press",CV],["pressKey",vV],["openApp",wV],["killApp",IV],["openNotifications",xV],["swipe",PV],["scrollTo",MV],["assert",yP],["extract",OV],["checkScreenContains",NV],["checkScreenDoesNotContain",LV],["dragAndDrop",DV],["javascript",bP],["request",FV],["wait",BV],["addFile",UV],["installApp",HV],["uninstallApp",GV],["toggleSettings",jV],["rotate",$V],["adb",VV],["appium",zV],["debugState",WV]]);Object.freeze([...KV.keys()]);var YV=z.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"v2 mobile commands must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"v2 mobile commands must have exactly one action key."});return}let r=KV.get(o)??(qr(o)?SP:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported v2 mobile command '${o}'.`});return}let i=r.safeParse(e);if(!i.success)for(let s of i.error.issues)t.addIssue({...s});}),JV=z.union([yP,kV,bP,SP]);var Uue=z.preprocess(e=>typeof e=="number"?String(e):e,w_),Hue=z.looseObject({goal:z.string(),version:Uue.optional(),precondition:z.string().optional(),postcondition:z.string().optional(),...Ke}),Gue=z.union([z.strictObject({act:z.string()}),z.strictObject({act:Hue})]),jue=z.looseObject({path:z.string(),inputs:z.record(z.string(),ny).optional(),...Ke}),$ue=z.union([z.strictObject({module:z.string()}),z.strictObject({module:jue})]),Vue=new Set(["then",...vA]),zue=z.looseObject({then:z.lazy(()=>tl.array()),...Ke}).superRefine((e,t)=>{if("else"in e){t.addIssue({code:"custom",message:"v2 mobile conditionals do not support 'else'. Use a separate step instead.",path:["else"]});return}Object.entries(e).filter(([o,r])=>!Vue.has(o)&&JV.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),Wue=z.strictObject({if:zue}),tl=z.lazy(()=>z.union([qV,Gue,$ue,Wue,YV]));z.object({before:tl.array().optional(),steps:tl.array(),after:tl.array().optional()});var TP=["android","ios"],que=z.literal("android"),Kue=z.literal("ios");z.enum(TP);function LA(e){if(typeof e!="object"||e===null)return e;let t=e;if(typeof t.platform!="string")return e;let n=t.platform.toLowerCase();return n===t.platform?e:{...t,platform:n}}var QV=Gm.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string(),platform:que,...$f.shape}),XV=jm.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string(),platform:Kue,...$f.shape}),Yue=z.discriminatedUnion("platform",[QV,XV]),ZV=z.preprocess(LA,Yue),ez={before:tl.array().optional(),steps:tl.array(),after:tl.array().optional()},tz=z.looseObject({fileType:z.literal(we.MOBILE_TEST_V2)}).extend(QV.shape).extend(ez);z.preprocess(LA,tz);var nz=z.looseObject({fileType:z.literal(we.MOBILE_TEST_V2)}).extend(XV.shape).extend(ez);z.preprocess(LA,nz);var Jue=z.discriminatedUnion("platform",[tz,nz]);z.preprocess(LA,Jue);var Que=z.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z.enum(TP).optional().default("android")),kA=dA.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:Ln,name:z.string().optional(),version:z.string(),platform:Que});z.looseObject(kA.extend({fileType:z.literal(we.MOBILE_MODULE_V2),steps:z.array(z.record(z.string(),z.unknown().optional())).optional()}).shape);z.looseObject(kA.extend({fileType:z.literal(we.MOBILE_MODULE_V2),steps:tl.array().optional()}).shape);var DA="x-momentic-cli-version",rz="x-momentic-client-mode",iz="x-momentic-cli-type",sz="x-momentic-logger-tags",Xue="x-momentic-main-branch-name",Zue="x-momentic-branch-name",epe="x-momentic-commit-timestamp",tpe="x-momentic-last-commit-on-main",npe="x-momentic-last-commit-on-main-timestamp",ope="x-momentic-merged-branch-name",az="x-momentic-session-id";w.object({error:w.boolean(),reason:w.string(),message:w.string()});vo.merge(o_);var lz=rT;vo.merge(o_);vo.merge(gH).extend({useConsensus:w.boolean().optional(),attemptNumber:w.number().optional()});var AP=_B;vo.merge(fH);var cz=oU;vo.merge(uH);var dz=PT;vo.merge(CB);vo.merge(pH);var uz=eU;vo.merge(mH);vo.merge(hH);vo.merge(TH);vo.merge(AH);w.object({testPaths:w.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:w.string().optional(),all:w.boolean().optional(),urlOverride:w.string().optional(),customHeaders:w.record(w.string(),w.string()).optional(),testInputMatrix:w.record(w.string(),w.string()).array().optional()});var pz=w.object({queuedTests:w.unknown().optional().array(),runIds:w.guid().array(),runGroupId:w.string().optional()});w.string().array();w.union([w.object({paths:w.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:w.boolean().describe("run all tests").optional()}),w.object({path:w.string().describe("deprecated; present for backcompat")})]);var rpe=w.object({tests:w.record(w.string().describe("Test name (keys correspond to entries in `tests`)"),w.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:w.record(w.string().describe("Module name (keys correspond to entries in `modules`)"),w.string().describe("Slash-separated folder name path that the module lives in."))}),mz=w.object({tests:w.record(w.string().describe("Test name"),w.string().describe("Test YAML")),modules:w.record(w.string().describe("Module name"),w.string().describe("Module YAML")),folderPaths:rpe.optional().describe("Optional map from exported entity name to its slash-separated cloud folder path. Used by the CLI to recreate folder structure on disk.")}),ipe=w.object({test:w.string().describe("test YAML"),modules:w.record(w.string().describe("moduleId"),w.string().describe("module YAML"))});ipe.array();w.object({testId:w.string(),schemaVersion:w.string()}).merge(Wl);function FA(e){let{gitMainBranch:t,gitBranchName:n,gitCommitTimestamp:o,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,s={};return t&&(s[Xue]=encodeURIComponent(t)),n&&(s[Zue]=encodeURIComponent(n)),o&&(s[epe]=o.toISOString()),r&&(s[tpe]=encodeURIComponent(r)),i&&(s[npe]=i.toISOString()),e.mergedGitBranchName&&(s[ope]=encodeURIComponent(e.mergedGitBranchName)),s}w.object({entries:w.array(f0)});w.object({platform:fP.optional(),entries:w.array(uV)});w.object({testId:w.string(),environment:w.string().optional(),platform:fP.optional()});w.object({testId:w.string(),key:w.string(),environment:w.string().optional()});function hz(e){return w.record(w.string(),w.unknown().optional()).transform(t=>{let n={};for(let[o,r]of Object.entries(t)){let i=e.safeParse(r);i.success&&(n[o]=i.data);}return n})}var gz=hz(y0),fz=pV.array();function oz(e){return hz(Jg(e))}var yz={ANDROID:e=>oz(mA).parse(e),IOS:e=>oz(hA).parse(e)},spe=w.object({id:w.string(),completionType:w.string(),description:w.string().optional(),thoughts:w.string(),result:w.string(),sessionType:w.string(),timeCreated:w.string().optional(),citations:w.array(Ao).optional()}),ape=w.object({id:w.string(),assertion:w.string().optional(),result:w.string(),thoughts:w.string(),sessionType:w.string(),timeCreated:w.string().optional(),citations:w.array(Ao).optional()});w.object({completionType:w.string(),traceIds:w.string().array()});var EP=w.union([spe,ape]).array(),Sz=w.object({trigger:w.nativeEnum(Pi),status:w.nativeEnum(Gt),startedAt:w.coerce.date().optional(),gitCommitSha:w.string().optional(),gitCommitShaShort:w.string().optional(),gitCommitTimestamp:w.coerce.date().optional(),gitBranchName:w.string().optional(),gitOriginUrl:w.string().optional(),gitCommitMessage:w.string().optional(),gitCommitAuthorName:w.string().optional(),githubRepository:w.string().optional(),gitlabProjectPath:w.string().optional(),pipelineId:w.string().optional(),cliVersion:w.string().optional()});w.object({id:w.string()});var bz=w.object({status:w.nativeEnum(Gt),updatedAt:w.coerce.date().optional(),finishedAt:w.coerce.date().optional()});w.object({summary:Eu,githubRepository:w.string().optional(),gitBranchName:w.string().optional()});var Tz=w.object({stepsSnapshot:w.array(w.record(w.string(),w.unknown().optional())).optional(),beforeStepsSnapshot:w.array(w.record(w.string(),w.unknown().optional())).optional(),afterStepsSnapshot:w.array(w.record(w.string(),w.unknown().optional())).optional(),runGroupId:w.string().optional(),testId:w.string(),testName:w.string(),resolvedBaseUrl:w.string().optional(),environmentName:w.string().optional(),labels:w.array(w.string()).optional(),cliVersion:w.string().optional(),trigger:w.nativeEnum(Pi),schemaVersion:w.string().optional(),section:w.nativeEnum(qT).optional(),resolvedInputs:w.record(w.string(),w.string()).optional(),quarantined:w.boolean().optional().default(false),quarantinedReason:w.string().optional(),aiSettings:qa.optional()});w.object({id:w.string()});var lpe=e_.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),Az=lpe.array(),Ez=e_.pick({startedAt:true,finishedAt:true,updatedAt:true,results:true,beforeResults:true,afterResults:true,status:true,healStatus:true,healDetails:true,failureDetails:true,failureReason:true,failureRecoveryDetails:true,resolvedBaseUrl:true,environmentName:true,labels:true,cliVersion:true,resolvedInputs:true,attempts:true,flake:true,aiSettings:true}).partial();w.object({id:w.string()});var Cz=w.object({run:ea.omit({runAttempts:true}),attemptZipUrls:w.array(w.string().url().nullish())}),Rz=w.object({status:w.nativeEnum(Gt),finishedAt:w.coerce.date().optional(),schemaVersion:w.string().optional().default("1.0.19"),results:w.record(w.string(),w.unknown().optional()).array().optional(),beforeResults:w.record(w.string(),w.unknown().optional()).array().optional(),afterResults:w.record(w.string(),w.unknown().optional()).array().optional()});w.object({screenshot:w.string(),contentType:w.enum(["image/jpeg","image/png"]).optional()});w.object({id:w.string(),screenshot:w.string(),contentType:w.enum(["image/jpeg","image/png"])});var vz=w.object({key:w.string()}),wz=w.object({orgId:w.string(),userId:w.string(),email:w.string().optional(),name:w.string().optional(),pylonEmailHash:w.string().optional(),selfServe:w.boolean().optional()}),Iz=w.object({blocked:w.boolean()}),xz=w.array(bU);w.record(w.string(),w.union([w.string(),w.boolean()]));w.object({workosAccessToken:w.string().min(1),organizationId:w.string().optional(),clientName:w.string().min(1).max(80).optional()});var _z=w.object({apiKey:w.string(),apiKeyName:w.string(),organizationId:w.string(),user:w.object({id:w.string(),email:w.string().optional()}),selfServe:w.boolean().optional()}),Pz=w.object({error:w.literal("multiple_organizations"),organizations:w.array(w.object({id:w.string(),name:w.string()}))}),cpe=["web","ios","android"];w.object({platforms:w.array(w.enum(cpe)),packageManager:w.enum(["npm","pnpm","yarn","bun"]),wizardVersion:w.string().min(1).max(40),cliVersions:w.object({momentic:w.string().max(40).optional(),momenticMobile:w.string().max(40).optional()}).optional(),firstRunIds:w.array(w.guid()).max(10).optional()});w.object({ok:w.literal(true)});w.object({paths:w.string().array(),env:w.string().optional(),urlOverride:w.string().optional(),customHeaders:w.record(w.string(),w.string()).optional()});var Mz=w.object({suiteRunIds:w.string().array(),runGroupIds:w.string().array()});w.object({suiteRunIds:w.string().array()});iH.array();w.object({runGroupIds:w.string().array()});var CP=w.object({uploadUrl:w.string()});vo.merge(yH);vo.merge(bH);vo.merge(SH);var dpe=w.object({testId:w.string().optional().default(""),testName:w.string().optional().default(""),suiteId:w.string().optional().default(""),suiteName:w.string().optional().default(""),isInteractive:w.boolean().optional().default(false),creditsUsed:w.number().optional(),stepsExecuted:w.number().optional(),tokensUsed:w.number().optional()}),upe=w.object({transactionId:w.string(),timestamp:w.string(),event:w.nativeEnum(Fm),properties:dpe});upe.array();var Oz=$j.omit({steps:true}).extend({steps:w.array(w.record(w.string(),w.unknown().optional())).describe("unparsed ResolvedStep[]")});w.object({limit:w.number().min(1).max(10).optional(),page:w.number().min(1).optional(),start:On.optional(),end:On.optional(),gitBranchName:w.string().optional(),status:w.nativeEnum(Gt).optional()});var Nz=Zx.array(),ppe=w.object({testId:Ln.optional(),gitBranchName:w.string().optional(),status:w.nativeEnum(Gt).optional(),label:w.string().array().optional(),limit:w.number().min(1).max(100).optional(),page:w.number().min(1).optional(),start:On.optional(),end:On.optional(),quarantined:w.boolean().optional(),recovered:w.boolean().optional()});ppe.extend({orgId:w.string().optional(),testId:wo(Ln),status:wo(w.nativeEnum(Gt)),gitBranchName:wo(w.string()),label:wo(w.string()),testName:w.string().optional(),trigger:wo(w.nativeEnum(Pi)),executionType:wo(Rm),cliVersion:wo(w.string()),githubRepository:wo(w.string()),gitlabProjectPath:wo(w.string()),environment:wo(w.string()),directory:wo(w.string()),failureCategory:wo(w.string()),exclude:wo(w.string()),healed:w.boolean().optional()});var Lz=w.object({runs:Zx.array(),page:w.number(),pageSize:w.number(),pageCount:w.number()});w.object({applied:w.boolean().optional(),appliedAt:w.coerce.date().optional()});var kz=CP.extend({id:w.string()});w.object({runGroupId:w.guid().optional(),persist:w.boolean().optional()});var Dz=w.object({runGroupId:w.guid()}),Fz=w.object({quarantined:w.object({testId:Ln,quarantinedAt:w.coerce.date(),quarantinedBy:w.string().optional(),quarantinedReason:w.string()}).array()}),Bz=w.object({gitLocalUsername:w.string().optional(),gitLocalEmail:w.string().optional(),gitLocalName:w.string().optional()});w.object({testId:Ln,testName:w.string().optional(),reason:w.string()}).merge(Bz);w.object({testName:w.string().optional(),reason:w.string().optional()}).merge(Bz);vo.merge(wG);vo.merge(IG);vo.merge(xG);w.object({apkToInstall:w.object({channel:w.string(),tag:w.string().optional()}).optional(),hostname:w.string().optional(),region:j_.optional(),osVersion:w.nativeEnum(jf).optional(),sessionId:w.string().optional()});var Uz=w.object({name:w.string(),apiUrl:w.string(),webRtcUrl:w.string(),adbUrl:w.string(),token:w.string(),apkDownloadUrl:w.string().optional(),playwrightServerUrl:w.string().optional(),region:w.string().optional(),resolvedTag:w.string().optional()});w.object({appToInstall:w.object({channel:w.string(),tag:w.string().optional()}).optional(),hostname:w.string().optional(),region:j_.optional(),osVersion:w.nativeEnum(V_).optional(),sessionId:w.string().optional(),installAppOnClient:w.boolean().optional()});var Hz=w.object({id:w.string(),apiUrl:w.string(),webRtcUrl:w.string(),wdaUrl:w.string(),token:w.string(),appDownloadUrl:w.string().optional(),appMd5:w.string().optional(),region:w.string().optional(),resolvedTag:w.string().optional()});w.object({channel:w.string().trim().min(1,"channel must be a non-empty string"),tag:w.string().trim().min(1,"tag must be a non-empty string"),md5:w.string()});var Gz=w.object({id:w.string(),uploadUrl:w.string().optional(),downloadUrl:w.string(),md5:w.string().optional()}),mpe=w.object({channel:w.string(),tag:w.string(),md5:w.string(),platform:w.nativeEnum(Js).default("ANDROID"),createdAt:w.number().describe("Unix timestamp in milliseconds")}),jz=w.object({assets:w.array(mpe)}),$z=w.object({downloadUrl:w.string()}),RP=(n=>(n.PLAYWRIGHT="PLAYWRIGHT",n.CDP="CDP",n))(RP||{}),hpe=w.nativeEnum(RP);w.object({runId:w.guid().optional(),attemptedProviders:w.array(nP).optional()});var Vz=w.object({wsEndpoint:w.string(),accessToken:w.string().optional(),endpointType:hpe.optional(),provider:nP.optional()});z.object({repositoriesIndexed:z.boolean(),indexingInProgress:z.boolean(),indexesOutdated:z.boolean()});var zz=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(zz||{}),Wz=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(Wz||{});z.object({name:z.string(),status:z.enum(zz),conclusion:z.enum(Wz).nullable()});var iy=z.object({sha:z.string(),message:z.string(),author:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()}),committer:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()})}),vP=z.object({mergedBranch:z.string().optional()});var qz=z.object({orgId:z.string(),cacheKeys:z.string().array()});z.object({keyParams:qz,clientMetadata:z.string(),lockAcquisitionTimeoutMs:z.number().optional()});var Kz=z.object({acquired:z.boolean(),acquiredByMetadata:z.string(),keyPrefix:z.string()});z.object({keyPrefix:z.string(),result:z.string(),ttlMs:z.number()});z.union([z.object({keyPrefix:z.string()}),qz]);var gpe=z.object({remainingTtlMs:z.number(),value:z.string().nullish()});z.object({results:z.record(z.string(),gpe),activeLocks:z.string().array()});var Yz=0,Jz=5*60*1e3;function Qz(){return new Date(Date.now()-2592e6)}function Km(e){if(e.startsWith("https://api"))return e.replace("https://api","https://app");if(e.startsWith("http://localhost:8000"))return e.replace("http://localhost:8000","http://localhost:3000");throw new Error(`Unknown Momentic app server URL pattern: ${e}`)}var fpe=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()),hash:z.string()}),Xz=z.record(z.string(),z.unknown().optional());z.object({newSvgs:z.array(fpe),metadata:Xz.optional()});var ype=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()).nullish(),hash:z.string(),description:z.string().nullish(),metadata:Xz.nullish()}),Zz=z.record(z.string().describe("icon hash"),ype);function e1(e){let t;try{t=JSON.parse(e);}catch(n){return `The schema is not valid JSON. ${n}`}try{validator(t);}catch(n){return `The schema is not a valid JSON schema. ${n}`}}var t1=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,n])=>t.trim()&&n.trim())));};var BA=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function bpe(e){return e.map(t=>({...t,environment:void 0}))}function wP(e,t){return t?e:bpe(e)}var xP="browser-crash-dump.zip",IP=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new sy}},sy=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new IP}flushResults(t){}};var Ze="metadata.json",tr="assets",wn="runs",Tpe=z.object({step:Yt,status:z.enum(Mt),startedAt:z.coerce.date(),finishedAt:z.coerce.date().optional(),healMetadata:z.object({healType:z.enum(hf).or(z.literal("AI")),healedAt:z.coerce.date()}).optional(),beforeSnapshotId:z.guid().optional(),afterSnapshotId:z.guid().optional(),message:z.string().optional()}),Ape=Tpe.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});Ape.extend({step:z.unknown().optional()});var _P=z.object({avdId:z.string().optional(),channel:z.string().optional(),tag:z.string().optional(),region:z.string().optional()}),o1="1.0.0",r1=Rz.extend({id:z.guid().optional(),startedAt:z.coerce.date(),runAttemptSchemaVersion:z.string().optional(),schemaVersion:z.string().optional().default("1.0.19"),results:z.record(z.string(),z.unknown().optional()).array().optional(),beforeResults:z.record(z.string(),z.unknown().optional()).array().optional(),afterResults:z.record(z.string(),z.unknown().optional()).array().optional(),assetDetails:_P.optional(),viewport:Jl.optional(),activeVideos:z.array(z.object({videoName:z.string(),timestamp:z.coerce.date()})).optional()}),ay=r1.extend({assetDetails:_P.optional(),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});r1.extend(Hx.shape);var i1=ay.extend(Hx.shape),Epe=z.object({results:z.array(Oi),beforeResults:z.array(Oi).optional(),afterResults:z.array(Oi).optional()});ay.extend(Epe.shape);var Cpe=z.object({results:z.array(Ni),beforeResults:z.array(Ni).optional(),afterResults:z.array(Ni).optional()});ay.extend(Cpe.shape);var s1=Ez.merge(Tz).extend({executionType:Rm.optional().default("WEB"),testId:Ln,testDescription:z.string().optional(),directory:z.string().optional(),runGroupId:z.guid(),status:z.enum(Gt),healStatus:Xx,startedAt:z.coerce.date(),schemaVersion:z.string().nullish(),attempts:z.number(),failureRecoveryDetails:z.object({attempts:z.number()}).optional(),aiSettings:qa.optional(),avgCpuUsage:z.number().optional(),avgMemoryUsage:z.number().optional()}),Rpe=s1.extend(_P.shape),Mu=s1.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});Rpe.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var n1=z.object({mode:z.enum(["SELECTED","RUN_ALL","RUN_NONE","SHADOW"]),baseRef:z.string().nullable(),headSha:z.string(),planId:z.string().nullable(),totalCandidates:z.number().int().nonnegative(),selectedCount:z.number().int().nonnegative(),anchorSegmentIds:z.array(z.string()),userSummary:z.string(),toolCallCount:z.number().int().nonnegative(),selectedTests:z.array(z.object({testId:z.string(),name:z.string(),testPath:z.string().nullable(),relevanceLabel:z.enum(["high","medium","low"]),rationale:z.string()})),forcedTests:z.array(z.object({name:z.string(),testPath:z.string(),status:z.enum(["A","M","R","C","T"])})).optional().default([]),runAllReason:z.string().nullable()}),vpe=Sz.merge(bz).extend({id:z.guid().optional(),startedAt:z.coerce.date(),cliVersion:z.string(),labels:z.string().array().optional().default([]),suiteName:z.string().optional(),ciProvider:z.string().optional(),gitMainBranch:z.string().optional(),ai:qa.optional(),browser:Ql.optional(),aiSelect:z.union([n1.transform(e=>[e]),z.array(n1)]).optional()}),fs=vpe.extend({healRiskSummary:Eu.optional(),updatedAt:z.coerce.date().optional().transform(e=>e??new Date),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var wpe=new Set(["AWAIT_LISTENER","REGISTER_REQUEST_LISTENER","GET_RECORDED_REQUESTS","MOCK_ROUTE","REMOVE_ROUTE_MOCK","SCROLL_DOWN","SCROLL_UP","SCROLL_LEFT","SCROLL_RIGHT","VISUAL_DIFF","WAIT","SET_HEADER","OFFLINE_MODE"]),Ipe=new Set(["MODULE","RESOLVED_MODULE"]);function UA(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function HA(e){return Ipe.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!wpe.has(e.command.type)}function a1(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return R.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var l1="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",GA="https://us-west.metrics.momentic.ai",jA="c60c6a0f-60da-41a7-a61b-07969a0aa303",ic=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;var kpe=new Set(["exit","quit"]),u1=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})();async function xo(e){return ic||u1?true:(await R.flush(),await new Promise(n=>setTimeout(n,100)),await confirm({message:e}))}async function PP(e){let t=dirname(e);return a1(t)?existsSync(e)?xo(`File '${c1(e)}' already exists. Overwrite existing content?`):true:await xo(`Directory '${c1(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function c1(e){return e.replace(/(\s+)/g,"\\$1")}async function p1(e,t){return ic||u1?t:(await input({message:e,default:t})).trim()||t}async function m1(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){R.info("");return}throw t}if(!kpe.has(e.toLowerCase()))return e}var Ym=new Map,g1="Log throttle exceeded",Wpe=100,qpe=5e3,Kpe=Hpe(global.fetch,{retries:2,retryOn:function(e,t,n){return !!(t!==null||n&&n.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}}),Ype="https://ingest.us.signoz.cloud:443/logs/json",MP=class{constructor(t,n){this.flushIntervalMs=t;this.maxBatchSize=n;}records=[];flushTimer;push(t){if(this.records.push(t),this.records.length>=this.maxBatchSize){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flush();return}this.scheduleFlush();}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush();},this.flushIntervalMs));}async flush(){if(this.records.length===0)return;let t=this.records;this.records=[];try{let n=await Kpe(Ype,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":l1},body:Xs(t),signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch{}}},OP=class e{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=false;lastWindowStart=Date.now();flushIntervalMs;maxBatchSize;buffer;constructor({bindings:t,hostname:n,disableConsoleLogs:o,flushIntervalMs:r,maxBatchSize:i,buffer:s}){this.hostname=n??sc.hostname(),this.disableConsoleLogs=o,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=s??new MP(this.flushIntervalMs,this.maxBatchSize);let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=h1(a);}child(t){return new e({bindings:{...this.bindingAttributes,...t},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize,buffer:this.buffer})}async flush(){await this.buffer.flush(),this.disableConsoleLogs||this.consoleLogger.flush();}shouldAllowLog(t){if(t===g1)return true;let n=Date.now();return n-this.lastWindowStart>qpe&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,g1),this.droppedLogsInWindow=false,this.lastWindowStart=n),this.logsInCurrentWindow<Wpe?(this.logsInCurrentWindow++,true):(this.droppedLogsInWindow=true,false)}log(t,n,o,...r){try{this.logHelper(t,n,o,...r);}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`);}}logHelper(t,n,o,...r){if(bf[t]<this.minLevelValue||!this.shouldAllowLog(o))return;typeof n=="string"&&!o&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=Vpe.err(n.err));let i={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...r.length>0?{args:r}:{}},s={host:this.hostname,env:this.bindingAttributes.env},a=Jpe();this.disableConsoleLogs||this.consoleLogger[t]({...i,...a??{}},o,...r);let l={timestamp:Math.round(Date.now()*1e6),...a??{},severity_text:t.toUpperCase(),resources:s,attributes:{},body:UU({message:o||"",...i})};this.buffer.push(l);}setApp(t){let n=this.bindingAttributes.app;this.bindingAttributes.app=t,Ym.set("app",this),Ym.delete(n);}debug(t,n,...o){this.log("debug",t,n,...o);}info(t,n,...o){this.log("info",t,n,...o);}warn(t,n,...o){this.log("warn",t,n,...o);}error(t,n,...o){this.log("error",t,n,...o);}bindings(){return this.bindingAttributes}addBinding(t,n){this.bindingAttributes[t]=n;}setMinLevel(t){typeof t=="number"?(this.minLevelValue=t,this.consoleLogger.level=HU[t]):(this.minLevelValue=bf[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},Jm=({app:e,hostname:t,disableConsoleLogs:n})=>(Ym.has(e)||Ym.set(e,new OP({bindings:{app:e},hostname:t,disableConsoleLogs:n})),Ym.get(e));function Jpe(){let e=trace.getSpan(context.active());if(!e)return;let t=e.spanContext();if(isSpanContextValid(t))return {trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}async function $A(){await Promise.all([...Ym.values()].map(e=>e.flush()));}var cd=class extends Error{constructor(t){super(t),this.name="TimeoutError";}};var f1=e=>{let t=e.reason===void 0?new DOMException("This operation was aborted.","AbortError"):e.reason;return t instanceof Error?t:new DOMException(t,"AbortError")};function Re(e,t){let{milliseconds:n,fallback:o,message:r,customTimers:i={setTimeout,clearTimeout}}=t,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);return new Promise((a,l)=>{let c;if(t.signal){let{signal:p}=t;if(p.aborted)return l(f1(p));c=()=>l(f1(p)),p.addEventListener("abort",c,{once:true});}let d=()=>{if(t.signal&&t.signal.removeEventListener("abort",c),o)try{a(o());}catch(p){l(p);}else {typeof e.cancel=="function"&&Promise.resolve().then(()=>e.cancel()).catch(()=>{});let p=r instanceof Error?r:new cd(r??`Promise timed out after ${n}ms`);l(p);}};n<1/0&&(s=i.setTimeout(d,n));let u=()=>{i.clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",c);};Promise.resolve(e).then(p=>{u(),a(p);}).catch(p=>{u(),l(p);});})}var VA="organization";function zA(e){let t=new PostHog(e.writeKey,{host:e.host,...e.flushImmediately?{flushAt:1,flushInterval:0}:{}}),n=e.platform,o=(l,c,d)=>{let{type:u,...p}=l;t.capture({distinctId:c??d??randomUUID(),event:u,...d&&{groups:{[VA]:d}},properties:{platform:n,user_id:c??void 0,org_id:d??void 0,...p,organizationId:d??void 0,...c==null&&{$process_person_profile:false}}});},r=({orgId:l,properties:c})=>{t.groupIdentify({groupType:VA,groupKey:l,properties:c});},i=({userId:l,properties:c})=>{Object.values(c).some(u=>u!=null&&u!=="")&&t.identify({distinctId:l,properties:c});},s=()=>t.shutdown();if(e.identity==="stashed"){let l=null;return {shutdownAnalytics:s,groupIdentifyOrg:r,setAnalyticsIdentity:d=>{l=d,e.onIdentify?.(d),i({userId:d.userId,properties:{email:d.email,...d.selfServe!==void 0?{self_serve:d.selfServe}:{}}});},captureEvent:d=>o(d,l?.userId??null,l?.orgId??null)}}return {shutdownAnalytics:s,groupIdentifyOrg:r,identifyUser:i,captureEvent:(l,{userId:c,orgId:d})=>o(l,c,d),captureBillingEvent:(l,{userId:c,orgId:d})=>o(l,c,d)}}async function y1(e,t,n){let o,r=0,i=3,s,a;for(;r<i;)try{let l=await Re(e.getAllFlagsAndPayloads(n??t,{personProperties:{organizationId:t},groups:{[VA]:t}}),{milliseconds:5e3});s=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){o=l,r++,await new Promise(c=>setTimeout(c,100*r));}if(s&&a)return {flags:s,payloads:a};throw o}var WA=class e extends Kf{constructor(n,o,r,i,s){super(i,s);this.client=n;this.orgId=o;this.userId=r;}static async init(n,o){let r=new PostHog("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://p.momentic.ai"}),{flags:i,payloads:s}=await y1(r,n,o);return new e(r,n,o,i,s)}async refresh(){let{flags:n,payloads:o}=await y1(this.client,this.orgId,this.userId);this.flags=n,this.payloads=o;}};var nme=2e3,Ou=e=>Number.parseInt(e,10),LP=e=>readFileSync(e,"utf8").trim(),Qm=e=>Ou(LP(e)),S1,qA,ly={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function A1(){return {...ly}}var YA=sc.platform(),ome=sc.cpus().map(e=>({model:e.model,speed:e.speed})).reduce((e,t)=>(e[t.model]={speed:t.speed},e.totalCores=(e.totalCores??0)+1,e),{});function NP(e=Date.now()){let t=sc.cpus(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;return n.total=n.user+n.nice+n.sys+n.idle+n.irq,n}function E1(e,t){let n={user:t.user-e.user,nice:t.nice-e.nice,sys:t.sys-e.sys,idle:t.idle-e.idle,irq:t.irq-e.irq,total:t.total-e.total};return n.total<=0?null:{measurementTime:t.measurementTime,intervalMs:t.measurementTime-e.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100}}function rme(){let e=NP();return ()=>{let t=NP(),n=E1(e,t);return e=t,n}}function b1(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return Ou(t[1])}catch{}try{let e=Qm("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function ime(){try{let t=LP("/sys/fs/cgroup/cpu.max").split(" "),n=t[0],o=t[1];return !n||!o||n==="max"?null:Ou(n)/Ou(o)}catch{}try{let e=Qm("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=Qm("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function sme(){if(YA!=="linux")return null;let e=b1();if(e===null)return null;let t=ime()??sc.cpus().length,n=e,o=Date.now();return ()=>{let r=b1();if(r===null)return null;let i=Date.now(),s=i-o;if(s<=0)return null;let a=r-n,l=s*1e3,c=Math.max(0,Math.min(100,a/l/t*100));return n=r,o=i,{measurementTime:i,intervalMs:s,user:c,nice:0,sys:0,idle:Math.max(0,100-c),irq:0,total:c}}}function ame(){let e=process.cpuUsage(),t=process.hrtime.bigint();return ()=>{let n=process.cpuUsage(),o=process.hrtime.bigint(),r=Number(o-t)/1e6,i=n.user-e.user,s=n.system-e.system;if(e=n,t=o,r<=0)return null;let a=Math.max(sc.cpus().length,1),l=c=>Math.max(0,c/1e3/r*100/a);return {total:l(i+s),user:l(i),sys:l(s),intervalMs:r}}}function C1({intervalMs:e=nme,maxSamples:t=1e4,keepSamples:n=true,onSample:o}={}){let r=[],i=sme()??rme(),s=ame(),a=()=>{let d=Date.now(),u=w1(),p=process.memoryUsage(),m=i(),h=s(),g={timestamp:d,system:{cpu:m,memory:{total:u.totalMemory,free:u.freeMemory,freePercentage:u.freePercentage}},process:{cpu:h,memory:{rss:p.rss,heapTotal:p.heapTotal,heapUsed:p.heapUsed,external:p.external,arrayBuffers:p.arrayBuffers}}};o?.(g),n&&(r.push(g),r.length>t&&r.shift());};a();let l=setInterval(a,e),c=d=>({samples:n?[...r]:[]});return {stop:()=>(clearInterval(l),c()),getSeries:()=>c()}}var KA=e=>{try{let t={},n=!1,o=w1(),r=cme();ly.samples++,o.freePercentage<.05&&(Object.assign(t,process.memoryUsage()),n=!0,ly.lowMemorySamples++),r&&r?.total>80&&(n=!0,ly.highCpuSamples++);let i=tme.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(n=!0,ly.highHeapSamples++),n?e.warn({memory:o,cpu:r,heapStats:i,...t},"Critical resource usage metrics detected"):e.debug({memory:o,cpu:r},"Got machine resource usage metrics");}catch{}},R1=e=>{KA(e),setTimeout(()=>KA(e),5e3);};function v1(e){return KA(e),{interval:setInterval(()=>KA(e),2e4),cpuMetadata:ome,platform:YA}}function lme(){if(YA!=="linux")return null;try{let e=LP("/sys/fs/cgroup/memory.max"),t=Qm("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let n=Ou(e);if(isNaN(n))return null;let o=Math.max(0,n-t);return {totalMemory:n,freeMemory:o,freePercentage:o/n}}catch{}try{let e=Qm("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=Qm("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let n=sc.totalmem();if(e>=n)return null;let o=Math.max(0,e-t);return {totalMemory:e,freeMemory:o,freePercentage:o/e}}catch{return null}}function w1(){let e=lme();if(e)return e;let t=sc.totalmem(),n=YA==="darwin"?dme():(()=>{let r=sc.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),o=n.availableMemory/t;return {totalMemory:t,freeMemory:n.availableMemory,freePercentage:o}}function cme(){let e=NP();if(!qA)return qA=e,null;let t=E1(qA,e);return qA=e,t?(S1=t,S1):null}function dme(){try{let e=execSync("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),n=e.match(/page size of (\d+) bytes/)?.[1],o=n?Ou(n):4096,r=d=>{let p=e.match(new RegExp(`${d}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Ou(p):0},i=r("Pages free"),s=r("Pages inactive"),a=r("Pages speculative"),l=i*o,c=(s+a)*o;return {availableMemory:l+c,rawFreeMemory:l,cachedMemory:c}}catch{let e=sc.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Xm=false,JA,cy,dy,_1=[];function QA(){return Xm}function P1(e){_1.push(e);}async function Ame(){for(let e of _1)try{await e();}catch{}}function Eme(){return QA()&&trace.getSpan(context.active())!==void 0}function Cme(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${GA}/v1/traces`,headers:{"x-momentic-metrics-api-key":jA}})}function Rme(e){let t="production",n=v4$1(),o=Cme(),r=new NodeTracerProvider({resource:new Resource({[SEMRESATTRS_SERVICE_NAME]:e,[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:t,[SEMRESATTRS_SERVICE_INSTANCE_ID]:n})});return r.addSpanProcessor(new BatchSpanProcessor(o)),r}function vme(e){return !e&&!JA?trace.getTracer("momentic-serverless"):dy?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function Nu(e){if(!(!e.enabled||Xm))try{JA=e.serviceName;let t=Rme(e.serviceName);dy=t,cy=new AsyncLocalStorageContextManager,t.register({contextManager:cy.enable()}),Xm=!0;}catch{Xm=false,JA=void 0,dy=void 0,cy=void 0;}}async function XA(){if(Xm)try{await Ame(),await dy?.shutdown();}catch{}finally{try{cy?.disable();}catch{}Xm=false,JA=void 0,cy=void 0,dy=void 0;}}async function it(e){if(!QA()||!e.root&&!Eme())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await vme(e.serviceName).startActiveSpan(e.name,{attributes:t,kind:e.kind??SpanKind.CLIENT},async n=>{try{let o=await e.fn(n);return n.setStatus({code:SpanStatusCode.OK}),o}catch(o){throw n.setStatus({code:SpanStatusCode.ERROR,message:o instanceof Error?o.message.slice(0,300):void 0}),o instanceof Error&&n.recordException(o),o}finally{n.end();}})}var uy=class{increment(t,n,o){}gauge(t,n){}distribution(t,n,o){}async flush(){}async recordDuration(t){return await DP(t)}};async function DP({fn:e,name:t,timeoutMs:n,trace:o}){let r=o?()=>it({name:o.name,attributes:o.attributes,fn:e}):e,i=Promise.resolve(r());return n===void 0?await i:await Re(i,{milliseconds:n,message:`Timed out after ${n}ms recording duration for ${t}`})}function wme(e){if(!e||e.length===0)return {};let t={};for(let n of e){let o=n.indexOf(":");if(o>-1){let r=n.slice(0,o).trim(),i=n.slice(o+1).trim();r&&(t[r]=i);continue}t[n]=true;}return t}function FP(e,t){let n=wme(e);return !t||Object.keys(t).length===0?n:{...t,...n}}function Dme(){return new OTLPMetricExporter({url:`${GA}/v1/metrics`,headers:{"x-momentic-metrics-api-key":jA},temporalityPreference:AggregationTemporalityPreference.DELTA})}var Fme=[new View({instrumentName:"test_event_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],false)}),new View({instrumentName:"test_step_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],false)}),new View({instrumentName:"test_mobile_step_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],false)}),new View({instrumentName:"web_agent_action_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([5,10,25,50,100,250,500,1e3,2e3,5e3],false)})],nE=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(t){let n=this.counterCache.get(t);if(n)return n;let o=this.meter.createCounter(t);return this.counterCache.set(t,o),o}getHistogram(t){let n=this.histogramCache.get(t);if(n)return n;let o=this.meter.createHistogram(t);return this.histogramCache.set(t,o),o}ensureObservableGauge(t){let n=this.observableGaugeCache.get(t);if(n)return n;let o=this.meter.createObservableGauge(t);return o.addCallback(r=>{let i=this.gaugeValues.get(t);i!==void 0&&r.observe(i,this.globalAttributes);}),this.observableGaugeCache.set(t,o),o}constructor(t){this.globalAttributes={...t.globalAttributes??{}};let n=typeof process<"u"?"production":"unknown",o=new Resource({[SEMRESATTRS_SERVICE_NAME]:t.serviceName,[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:n,[SEMRESATTRS_SERVICE_INSTANCE_ID]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1()}),r=Dme(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:o,readers:[i],views:Fme}),metrics.setGlobalMeterProvider(this.provider),this.meter=metrics.getMeter("momentic-serverless");}increment(t,n,o){try{let r=FP(o,this.globalAttributes);this.getCounter(t).add(typeof n=="number"?n:1,r);}catch{}}gauge(t,n){try{this.ensureObservableGauge(t),this.gaugeValues.set(t,n);}catch{}}distribution(t,n,o){try{let r=FP(o,this.globalAttributes);this.getHistogram(t).record(n,r);}catch{}}async flush(){try{await this.provider.forceFlush();}catch{}}async recordDuration(t){let{name:n,tags:o}=t,r=Date.now();try{return await DP(t)}finally{this.distribution(n,Date.now()-r,o);}}};var gt=new uy;function O1(e){if(!e.disabled)try{gt=new nE(e);}catch{gt=new uy;}}var BP;function N1(e){BP=e;}function dd(e){bT(e,_e)||BP&&BP(e);}function W1(){return globalThis.crypto}function jP(e){let t=W1(),n=new Uint8Array(e);if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(n),n;for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);return n}function pd(){let e=W1();if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=jP(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return `${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function $P(e){let t=globalThis.Buffer;if(t)return t.from(e).toString("base64");let n="";for(let a=0;a<e.length;a++)n+=String.fromCharCode(e[a]);let o=globalThis.btoa;if(typeof o=="function")return o(n);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="",s=0;for(;s<n.length;){let a=n.charCodeAt(s++)&255,l=s<n.length?n.charCodeAt(s++)&255:NaN,c=s<n.length?n.charCodeAt(s++)&255:NaN,d=a>>2,u=(a&3)<<4|(Number.isNaN(l)?0:l>>4),p=Number.isNaN(l)?64:(l&15)<<2|(Number.isNaN(c)?0:c>>6),m=Number.isNaN(c)?64:c&63;i+=r.charAt(d),i+=r.charAt(u),i+=p===64?"=":r.charAt(p),i+=m===64?"=":r.charAt(m);}return i}function Ume(e){return new Promise(t=>setTimeout(t,e))}function my(e){if(e)return e.endsWith("/")?e:`${e}/`}function Hme(e){var t;let n=(t=e.get("Retry-After"))!=null?t:e.get("retry-after");if(!n)return;let o=Number(n);if(n.trim()!==""&&!Number.isNaN(o))return o*1e3;let r=new Date(n).getTime();if(!Number.isNaN(r)){let i=r-Date.now();return i>0?i:0}}function Gme(e,t){if(t&&typeof t=="object"&&t!==null&&"retryAfterMs"in t){let r=t.retryAfterMs;if(typeof r=="number")return Math.max(0,r)}if(e<=1)return 0;let n=500,o=Math.pow(2,e-2);return n*o}async function jme(e,t,n){let o=n.sdkName?`[raindrop-ai/${n.sdkName}]`:"[raindrop-ai/core]",r;for(let i=1;i<=n.maxAttempts;i++){if(i>1){let s=Gme(i,r);n.debug&&console.warn(`${o} ${t} retry ${i}/${n.maxAttempts} in ${s}ms`),s>0&&await Ume(s);}else n.debug&&console.log(`${o} ${t} attempt ${i}/${n.maxAttempts}`);try{return await e()}catch(s){if(r=s,n.debug){let a=s instanceof Error?s.message:String(s);console.warn(`${o} ${t} attempt ${i} failed: ${a}${i===n.maxAttempts?" (no more retries)":""}`);}if(r&&typeof r=="object"&&"retryable"in r&&!r.retryable||i===n.maxAttempts)break}}throw r instanceof Error?r:new Error(String(r))}async function ku(e,t,n,o){let r=`POST ${e}`;await jme(async()=>{let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)});if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`HTTP ${i.status} ${i.statusText}${s?`: ${s}`:""}`),l=Hme(i.headers);throw typeof l=="number"&&(a.retryAfterMs=l),a.retryable=i.status===429||i.status>=500,a}},r,o);}var L1={UNSET:0,ERROR:2};function k1(e){let t=e?e.traceIdB64:$P(jP(16)),n=$P(jP(8));return {traceIdB64:t,spanIdB64:n,parentSpanIdB64:e?e.spanIdB64:void 0}}function hy(){return Date.now().toString()+"000000"}function D1(e){return String(Math.floor(e))+"000000"}function G(e,t){if(t!==void 0)return {key:e,value:{stringValue:t}}}function We(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{intValue:String(Math.trunc(t))}}}function Zm(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{doubleValue:t}}}function $me(e,t){if(t!==void 0)return {key:e,value:{boolValue:t}}}function ac(e,t){if(!(!t||t.length===0))return {key:e,value:{arrayValue:{values:t.filter(n=>typeof n=="string").map(n=>({stringValue:n}))}}}}function UP(e){let t=e.attributes.filter(o=>o!==void 0),n={traceId:e.ids.traceIdB64,spanId:e.ids.spanIdB64,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano};return e.ids.parentSpanIdB64&&(n.parentSpanId=e.ids.parentSpanIdB64),t.length&&(n.attributes=t),e.status&&(n.status=e.status),n}function F1(e,t="raindrop.core",n="0.0.0"){return {resourceSpans:[{resource:{attributes:[{key:"service.name",value:{stringValue:t}}]},scopeSpans:[{scope:{name:t,version:n},spans:e}]}]}}var Vme="RAINDROP_LOCAL_DEBUGGER",zme="RAINDROP_WORKSHOP",B1="http://localhost:5899/v1/";function JP(e){var t;try{let n=(t=globalThis?.process)==null?void 0:t.env;if(n&&typeof n[e]=="string"&&n[e].length>0)return n[e]}catch{}}function Wme(){let e=JP(zme);if(e===void 0)return;let t=e.trim();if(t.length!==0){if(/^https?:\/\//i.test(t))return {url:t};if(/^(1|true|yes|on)$/i.test(t))return "enable";if(/^(0|false|no|off)$/i.test(t))return "disable"}}function qme(e){return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e.endsWith(".localhost")):false}function Kme(){try{let e=globalThis?.location;if(e&&typeof e.hostname=="string"&&e.hostname.length>0)return e.hostname}catch{}}function Yme(){return !!(qme(Kme())||JP("NODE_ENV")==="development")}function Fu(e){var t,n,o;if(e===null)return null;if(typeof e=="string"&&e.length>0)return (t=my(e))!=null?t:null;let r=JP(Vme);if(r)return (n=my(r))!=null?n:null;let i=Wme();return i==="disable"?null:i==="enable"?B1:i&&"url"in i?(o=my(i.url))!=null?o:null:Yme()?B1:null}function cE(e){return Fu(e)!==null}function Jme(e,t={}){var n;let o=Fu(t.baseUrl);o&&ku(`${o}traces`,e,{},{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function Qme(e,t={}){var n;let o=Fu(t.baseUrl);if(!o)return;let r=t.writeKey?{Authorization:`Bearer ${t.writeKey}`}:{};ku(`${o}events/track_partial`,e,r,{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function ud(e,t={}){var n,o;let r=Fu(t.baseUrl);r&&ku(`${r}live`,{...e,type:e.type,timestamp:(n=e.timestamp)!=null?n:Date.now()},{},{maxAttempts:1,debug:(o=t.debug)!=null?o:false,sdkName:t.sdkName}).catch(()=>{});}function Xme(e,t){var n,o,r,i;let s={...e,...t};return (e.properties||t.properties)&&(s.properties={...(n=e.properties)!=null?n:{},...(o=t.properties)!=null?o:{}}),(e.attachments||t.attachments)&&(s.attachments=[...(r=e.attachments)!=null?r:[],...(i=t.attachments)!=null?i:[]]),s}var Zme=class{constructor(e){this.buffers=new Map,this.sticky=new Map,this.timers=new Map,this.inFlight=new Set;var t,n,o,r,i,s,a,l;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=my(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.partialFlushMs=(o=e.partialFlushMs)!=null?o:1e3,this.sdkName=(r=e.sdkName)!=null?r:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.defaultEventName=(i=e.defaultEventName)!=null?i:"ai_generation",this.localDebuggerUrl=(s=Fu(e.localDebuggerUrl))!=null?s:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);let c=typeof process<"u"&&typeof process.version=="string";this.context={library:{name:(a=e.libraryName)!=null?a:"@raindrop-ai/core",version:(l=e.libraryVersion)!=null?l:"0.0.0"},metadata:{jsRuntime:c?"node":"web",...c?{nodeVersion:process.version}:{}}};}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}async patch(e,t){var n,o,r,i,s,a,l,c,d,u,p;if(!this.enabled||!e||!e.trim())return;this.debug&&console.log(`${this.prefix} queue patch`,{eventId:e,userId:t.userId,convoId:t.convoId,eventName:t.eventName,hasInput:typeof t.input=="string"&&t.input.length>0,hasOutput:typeof t.output=="string"&&t.output.length>0,attachments:(o=(n=t.attachments)==null?void 0:n.length)!=null?o:0,isPending:t.isPending});let m=(r=this.sticky.get(e))!=null?r:{},h=(i=this.buffers.get(e))!=null?i:{},g=Xme(h,t);g.isPending=(l=(a=(s=t.isPending)!=null?s:h.isPending)!=null?a:m.isPending)!=null?l:true,this.buffers.set(e,g),this.sticky.set(e,{userId:(c=g.userId)!=null?c:m.userId,convoId:(d=g.convoId)!=null?d:m.convoId,eventName:(u=g.eventName)!=null?u:m.eventName,isPending:(p=g.isPending)!=null?p:m.isPending});let f=this.timers.get(e);if(f&&clearTimeout(f),g.isPending===false){await this.flushOne(e);return}let b=setTimeout(()=>{this.flushOne(e).catch(()=>{});},this.partialFlushMs);this.timers.set(e,b);}async finish(e,t){await this.patch(e,{...t,isPending:false});}async flush(){if(!this.enabled)return;let e=[...this.buffers.keys()];await Promise.all(e.map(t=>this.flushOne(t))),await Promise.all([...this.inFlight].map(t=>t.catch(()=>{})));}async shutdown(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),await this.flush();}async trackSignal(e){var t,n;if(!this.enabled)return;let o=[{event_id:e.eventId,signal_name:e.name,signal_type:(t=e.type)!=null?t:"default",timestamp:e.timestamp,sentiment:e.sentiment,attachment_id:e.attachmentId,properties:{...(n=e.properties)!=null?n:{},...e.comment?{comment:e.comment}:{},...e.after?{after:e.after}:{}}}];if(!this.writeKey)return;let r=`${this.baseUrl}signals/track`;try{await ku(r,o,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`${this.prefix} failed to send signal (dropping): ${s}`);}}async identify(e){if(!this.enabled)return;let n=(Array.isArray(e)?e:[e]).filter(r=>!r?.userId||!r.userId.trim()?(this.debug&&console.warn(`${this.prefix} skipping identify: missing userId`),false):true).map(r=>{var i;return {user_id:r.userId,traits:(i=r.traits)!=null?i:{}}});if(!this.writeKey||n.length===0)return;let o=`${this.baseUrl}users/identify`;try{await ku(o,n,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send identify (dropping): ${i}`);}}async flushOne(e){var t,n,o,r,i,s,a,l,c,d,u,p,m;if(!this.enabled)return;let h=this.timers.get(e);h&&(clearTimeout(h),this.timers.delete(e));let g=this.buffers.get(e);if(this.buffers.delete(e),!g)return;let f=(t=this.sticky.get(e))!=null?t:{},b=(o=(n=g.eventName)!=null?n:f.eventName)!=null?o:this.defaultEventName,T=(r=g.userId)!=null?r:f.userId;if(!T){this.debug&&console.warn(`${this.prefix} skipping track_partial for ${e}: missing userId`),this.sticky.delete(e);return}let{wizardSession:A,...C}=(i=g.properties)!=null?i:{},v=(s=g.convoId)!=null?s:f.convoId,I=(l=(a=g.isPending)!=null?a:f.isPending)!=null?l:true,_={event_id:e,user_id:T,event:b,timestamp:(c=g.timestamp)!=null?c:new Date().toISOString(),ai_data:{input:g.input,output:g.output,model:g.model,convo_id:v},properties:{...C,...A?{"raindrop.wizardSession":A}:{},$context:this.context},attachments:g.attachments,is_pending:I},x=`${this.baseUrl}events/track_partial`;if(this.debug&&console.log(`${this.prefix} sending track_partial`,{eventId:e,eventName:b,userId:T,convoId:v,isPending:I,inputPreview:typeof g.input=="string"?g.input.slice(0,120):void 0,outputPreview:typeof g.output=="string"?g.output.slice(0,120):void 0,attachments:(u=(d=g.attachments)==null?void 0:d.length)!=null?u:0,attachmentKinds:(m=(p=g.attachments)==null?void 0:p.map(O=>({type:O.type,role:O.role,name:O.name,valuePreview:O.value.slice(0,60)})))!=null?m:[],endpoint:x}),this.localDebuggerUrl&&Qme(_,{baseUrl:this.localDebuggerUrl,writeKey:this.writeKey,debug:this.debug,sdkName:this.sdkName}),!this.writeKey){I||this.sticky.delete(e);return}let E=ku(x,_,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(E);try{try{await E,this.debug&&console.log(`${this.prefix} sent track_partial ${e} (${b})`);}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`${this.prefix} failed to send track_partial (dropping): ${N}`);}}finally{this.inFlight.delete(E);}I||this.sticky.delete(e);}},q1=["apikey","apisecret","apitoken","secretaccesskey","sessiontoken","privatekey","privatekeyid","clientsecret","accesstoken","refreshtoken","oauthtoken","bearertoken","authorization","password","passphrase"],K1="[REDACTED]";function Y1(e){return e.toLowerCase().replace(/[-_.]/g,"")}function J1(e,t){var n,o;let r=ehe((n=t?.secretKeyNames)!=null?n:q1),i=(o=t?.placeholder)!=null?o:K1,s=new WeakSet,a=l=>{if(l===null||typeof l!="object")return l;if(s.has(l))return "[CIRCULAR]";if(s.add(l),Array.isArray(l))return l.map(d=>a(d));let c={};for(let[d,u]of Object.entries(l))r.has(Y1(d))?c[d]=i:c[d]=a(u);return c};return a(e)}function ehe(e){let t=new Set;for(let n of e)t.add(Y1(n));return t}var Q1=["ai.request.providerOptions","ai.response.providerMetadata"];function X1(e){let t=e.attributes;if(!t||t.length===0)return e;let n;for(let o=0;o<t.length;o++){let r=t[o],i=Z1(r.key,r.value);i!==void 0&&(n||(n=t.slice()),n[o]={key:r.key,value:i});}return n?{...e,attributes:n}:e}var the=new Set(Q1);function Z1(e,t){if(!the.has(e))return;let n=t.stringValue;if(typeof n!="string"||n.length===0)return;let o;try{o=JSON.parse(n);}catch{return}let r=J1(o),i;try{i=JSON.stringify(r);}catch{return}if(i!==n)return {stringValue:i}}var nhe=class{constructor(e){this.queue=[],this.inFlight=new Set;var t,n,o,r,i,s,a,l,c;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=my(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.debugSpans=e.debugSpans===true,this.flushIntervalMs=(o=e.flushIntervalMs)!=null?o:1e3,this.maxBatchSize=(r=e.maxBatchSize)!=null?r:50,this.maxQueueSize=(i=e.maxQueueSize)!=null?i:5e3,this.sdkName=(s=e.sdkName)!=null?s:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.serviceName=(a=e.serviceName)!=null?a:"raindrop.core",this.serviceVersion=(l=e.serviceVersion)!=null?l:"0.0.0",this.localDebuggerUrl=(c=Fu(e.localDebuggerUrl))!=null?c:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`),this.transformSpanHook=e.transformSpan,this.disableDefaultRedaction=e.disableDefaultRedaction===true;}redactSpan(e){let t=e;if(this.transformSpanHook)try{let n=this.transformSpanHook(t);if(n===null)return null;n!==void 0&&(t=n);}catch(n){if(this.debug){let o=n instanceof Error?n.message:String(n);console.warn(`${this.prefix} transformSpan hook threw: ${o}`);}return null}return this.disableDefaultRedaction||(t=X1(t)),t}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}startSpan(e){var t,n;let o=k1(e.parent),r=(t=e.startTimeUnixNano)!=null?t:hy(),i=[G("ai.telemetry.metadata.raindrop.eventId",e.eventId),G("ai.operationId",e.operationId)];(n=e.attributes)!=null&&n.length&&i.push(...e.attributes);let s={ids:o,name:e.name,startTimeUnixNano:r,attributes:i};return this.mirrorToLocalDebugger(UP({ids:s.ids,name:s.name,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:s.startTimeUnixNano,attributes:s.attributes,status:{code:L1.UNSET}})),s}mirrorToLocalDebugger(e){if(!this.localDebuggerUrl)return;let t=this.redactSpan(e);if(t===null)return;let n=F1([t],this.serviceName,this.serviceVersion);Jme(n,{baseUrl:this.localDebuggerUrl,debug:false,sdkName:this.sdkName});}endSpan(e,t){var n,o;if(e.endTimeUnixNano)return;e.endTimeUnixNano=(n=t?.endTimeUnixNano)!=null?n:hy(),(o=t?.attributes)!=null&&o.length&&e.attributes.push(...t.attributes);let r=t?.status;if(!r&&t?.error!==void 0){let s=t.error instanceof Error?t.error.message:String(t.error);r={code:L1.ERROR,message:s};}let i=UP({ids:e.ids,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:e.attributes,status:r});this.enqueue(i),this.mirrorToLocalDebugger(i);}createSpan(e){var t;let n=k1(e.parent),o=[G("ai.telemetry.metadata.raindrop.eventId",e.eventId)];(t=e.attributes)!=null&&t.length&&o.push(...e.attributes);let r=UP({ids:n,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:o,status:e.status});this.enqueue(r),this.mirrorToLocalDebugger(r);}enqueue(e){if(!this.enabled)return;if(this.debugSpans){let n=o=>o?o.slice(-8):"none";console.log(`${this.prefix}[span] name=${e.name} trace=${n(e.traceId)} span=${n(e.spanId)} parent=${n(e.parentSpanId)}`);}let t=this.redactSpan(e);if(t!==null){if(this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(t),this.queue.length>=this.maxBatchSize){this.flush().catch(()=>{});return}this.timer||(this.timer=setTimeout(()=>{this.timer=void 0,this.flush().catch(()=>{});},this.flushIntervalMs));}}async flush(){if(this.enabled)for(this.timer&&(clearTimeout(this.timer),this.timer=void 0);this.queue.length>0;){let e=this.queue.splice(0,this.maxBatchSize);if(!this.writeKey)continue;let t=F1(e,this.serviceName,this.serviceVersion),n=`${this.baseUrl}traces`;this.debug&&console.log(`${this.prefix} sending traces batch`,{spans:e.length,endpoint:n});let o=ku(n,t,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(o);try{try{await o,this.debug&&console.log(`${this.prefix} sent ${e.length} spans`);}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send ${e.length} spans: ${i}`);}}finally{this.inFlight.delete(o);}}}async shutdown(){this.timer&&(clearTimeout(this.timer),this.timer=void 0),await this.flush(),await Promise.all([...this.inFlight].map(e=>e.catch(()=>{})));}},ohe={};function U1(){return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE}var rhe=class{constructor(){this._stack=[];}isEmpty(){return this._stack.length===0}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},ihe=class{},she=class extends ihe{constructor(){super(),this._fallback=null;let e=U1();if(e){this._storage=new e;return}this._fallback=new rhe,this._storage=this._fallback;}maybeAdoptAsyncLocalStorage(){if(!this._fallback||!this._fallback.isEmpty())return;let e=U1();e&&(this._storage=new e,this._fallback=null);}isReady(){return true}getParentSpanIds(){this.maybeAdoptAsyncLocalStorage();let e=this._storage.getStore();if(!(!e||e===ohe))return {traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId}}runInContext(e,t){return this.maybeAdoptAsyncLocalStorage(),this._storage.run(e,t)}getCurrentSpan(){return this.maybeAdoptAsyncLocalStorage(),this._storage.getStore()}},HP=null;function md(){return HP||(HP=globalThis.RAINDROP_CONTEXT_MANAGER?new globalThis.RAINDROP_CONTEXT_MANAGER:new she),HP}function eW(e,t){return md().runInContext(e,t)}async function Du(){return md().getParentSpanIds()}async function gy(e,t){let n=md(),o={traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId};return n.runInContext(o,t)}async function*ahe(e,t){let n;for(;;){let o=await eW(e,async()=>{try{return await t.next(n)}catch(r){return {value:void 0,done:true,error:r}}});if("error"in o&&o.error!==void 0)throw o.error;if(o.done)return o.value;n=yield o.value;}}globalThis.RAINDROP_ASYNC_LOCAL_STORAGE=AsyncLocalStorage;function pe(e){return typeof e=="object"&&e!==null}function Ar(e){return typeof e=="function"}function H1(e){var t;if(!e||typeof e!="object")return false;if(((t=e.constructor)==null?void 0:t.name)==="Module")return true;try{let o=Object.keys(e);if(o.length===0)return !1;let r=Object.getOwnPropertyDescriptor(e,o[0]);if(!r)return !1;let i="writable"in r?r.writable:!0;return !r.configurable&&!i}catch{return false}}function aE(e){try{return JSON.stringify(e)}catch{return}}function tt(e){try{return JSON.stringify(e,(t,n)=>n instanceof Uint8Array?$P(n):n)}catch{return}}function hE(e){if(typeof e=="string"){let r=e.indexOf("/");return r>0&&r<e.length-1?{provider:e.slice(0,r),modelId:e.slice(r+1)}:{modelId:e}}if(!pe(e))return {};let t=typeof e.provider=="string"?e.provider:void 0,n;if(typeof e.modelId=="string"?n=e.modelId:typeof e.model=="string"&&(n=e.model),!n)return {provider:t};let o=n.indexOf("/");return !t&&o>0&&o<n.length-1?{provider:n.slice(0,o),modelId:n.slice(o+1)}:{provider:t,modelId:n}}function QP(e){if(!pe(e))return;let t=e.text;return typeof t=="string"?t:void 0}function lhe(e){var t;if(!pe(e))return;let n=e.object;if(n!==void 0)return (t=aE(n))!=null?t:String(n)}function che(e){if(typeof e!="function")return false;let t=e.prototype;return pe(t)?typeof t.generate=="function"&&typeof t.stream=="function":false}function XP(e){if(!pe(e))return;let t=e.model;if(typeof t=="string"&&t.length)return t;let n=e.response;if(pe(n)){let o=n.modelId;if(typeof o=="string"&&o.length)return o}}function fy(e){if(pe(e)){if(typeof e.finishReason=="string")return e.finishReason;if(pe(e.finishReason)&&typeof e.finishReason.unified=="string")return e.finishReason.unified}}function G1(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return typeof btoa=="function"?btoa(t):""}function lE(e,t){if(e instanceof URL)return e.toString();if(typeof e=="string")return e.startsWith("data:")||e.startsWith("http://")||e.startsWith("https://")?e:`data:${t};base64,${e}`;if(e instanceof Uint8Array){let n=G1(e);return n?`data:${t};base64,${n}`:void 0}if(e instanceof ArrayBuffer){let n=G1(new Uint8Array(e));return n?`data:${t};base64,${n}`:void 0}}function tW(e){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return `[binary:${e.byteLength} bytes]`;if(e instanceof ArrayBuffer)return `[binary:${e.byteLength} bytes]`}function j1(e){if(typeof e.mediaType=="string")return e.mediaType;if(typeof e.mimeType=="string")return e.mimeType;let t=e.file;if(pe(t)){if(typeof t.mediaType=="string")return t.mediaType;if(typeof t.mimeType=="string")return t.mimeType}}function dhe(e){if(typeof e.filename=="string")return e.filename;if(typeof e.name=="string")return e.name;let t=e.file;if(pe(t)){if(typeof t.filename=="string")return t.filename;if(typeof t.name=="string")return t.name}}function uhe(e){if("data"in e)return e.data;let t=e.file;if(pe(t)){if("file_data"in t)return t.file_data;if("data"in t)return t.data}}function phe(e,t){var n,o,r;let i=e.type;if(typeof i=="string"){if(i==="image"){let s=(n=j1(e))!=null?n:"image/png",a=lE(e.image,s);return a?{type:"image",role:t,value:a}:void 0}if(i==="image_url"){let s=e.image_url,a=pe(s)?s.url:s,l=lE(a,"image/png");return l?{type:"image",role:t,value:l}:void 0}if(i==="file"){let s=j1(e),a=uhe(e),l=s?.startsWith("image/")===true,c=l&&s?lE(a,s):tW(a);if(!c)return;let d=(r=(o=dhe(e))!=null?o:s)!=null?r:"file";return {type:l?"image":"text",role:t,name:d,value:c}}}}function VP(e,t){if(!Array.isArray(e))return;let n=[];for(let o of e){if(!pe(o))continue;let r=phe(o,t);r&&n.push(r);}return n.length?n:void 0}function mhe(e){var t,n,o,r;let i=typeof e.mediaType=="string"?e.mediaType:typeof e.mimeType=="string"?e.mimeType:void 0,s=(r=(o=(n=(t=e.base64Data)!=null?t:e.base64)!=null?n:e.uint8ArrayData)!=null?o:e.uint8Array)!=null?r:e.data,a=i?.startsWith("image/")===true,l=a&&i?lE(s,i):tW(s);if(!l)return;let c=typeof e.filename=="string"?e.filename:typeof e.name=="string"?e.name:i??"file";return {type:a?"image":"text",role:"output",name:c,value:l}}async function hhe(e){let t=e;if(t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function")try{t=await t;}catch{return}if(!Array.isArray(t))return;let n=[];for(let o of t){if(!pe(o))continue;let r=mhe(o);r&&n.push(r);}return n.length?n:void 0}function nW(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t="";for(let n of e)!pe(n)||n.type!=="text"||typeof n.text!="string"||(t+=n.text);return t.length?t:void 0}function ZP(e){let t=e.messages;if(Array.isArray(t))return t;let n=e.prompt;if(Array.isArray(n))return n}function oW(e){let t=ZP(e);if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(pe(o)&&o.role==="user")return o}}function eM(e){var t;if(pe(e))return VP((t=oW(e))==null?void 0:t.content,"input")}async function tM(e){if(!pe(e))return;let t=await hhe(e.files);if(t?.length)return t;let n=gE(e);for(let o=n.length-1;o>=0;o--){let r=n[o];if(!(!pe(r)||r.role!=="assistant"))return VP(r.content,"output")}return VP(e.content,"output")}function nM(e){var t,n;if(!pe(e))return;let o=(t=oW(e))==null?void 0:t.content;if(o===void 0)return;let r=nW(o);return r!==void 0?r:(n=tt(o))!=null?n:String(o)}function oM(e){var t;if(!pe(e))return;let n=e.prompt;if(typeof n=="string")return n;let o=ZP(e);if(Array.isArray(o)&&o.length>0){let i=o[o.length-1];if(pe(i)){let s=i.content,a=nW(s);if(a!==void 0)return a;let l=aE(s);if(l)return l}return (t=aE(o))!=null?t:void 0}let r=e.input;return typeof r=="string"?r:aE(e)}function rM(e){if(!pe(e))return [];let t=[];typeof e.system=="string"&&e.system&&t.push({role:"system",content:e.system});let n=ZP(e);if(Array.isArray(n)){for(let o of n)pe(o)&&typeof o.role=="string"&&t.push(o);return t}return typeof e.prompt=="string"&&e.prompt&&t.push({role:"user",content:e.prompt}),t}function gE(e){if(!pe(e))return [];let t=e.response;if(pe(t)&&Array.isArray(t.messages))return t.messages.filter(o=>pe(o)&&typeof o.role=="string"&&"content"in o).map(o=>o);let n=e.steps;if(Array.isArray(n)&&n.length>0){let o=n[n.length-1];if(pe(o)&&pe(o.response)){let r=o.response.messages;if(Array.isArray(r))return r.filter(i=>pe(i)&&typeof i.role=="string"&&"content"in i).map(i=>i)}}return []}function dE(e){if(typeof e.toolCallId=="string"&&e.toolCallId.length>0)return `id:${e.toolCallId}`;if(typeof e.toolName=="string"&&e.toolName.length>0){let t=tt(e.input);return t!==void 0?`name:${e.toolName}|input:${t}`:`name:${e.toolName}`}}function ghe(e,t){return e.isError===true||e.type==="tool-error"?true:pe(t)&&typeof t.type=="string"?t.type.startsWith("error")||t.type==="execution-denied":false}function fhe(e){if(typeof e=="string"&&e.length>0)return e;if(pe(e)){if(typeof e.value=="string"&&e.value.length>0)return e.value;if(typeof e.reason=="string"&&e.reason.length>0)return e.reason;if(typeof e.message=="string"&&e.message.length>0)return e.message}return tt(e)}function yhe(e){if(!pe(e))return [];let t=e.content;return Array.isArray(t)?t.filter(pe):pe(t)?[t]:[]}function She(e){return "input"in e?e.input:"args"in e?e.args:void 0}function iM(e){let t=e.toolCallId;return typeof t=="string"&&t.length>0?t:void 0}function bhe(e){return "output"in e?e.output:"result"in e?e.result:e.error}function The(e,t,n){var o;if(!t)return;let r=(o=e.get(t))!=null?o:[];r.includes(n)||(r.push(n),e.set(t,r));}function Ahe(e,t){if(!t)return;let n=e.get(t);if(!n||n.length===0)return;let o=n.shift();if(o!==void 0)return n.length===0&&e.delete(t),o}function Ehe(e){var t,n,o,r;let{spans:i,pendingKeysByToolName:s,part:a}=e,l=iM(a),c=typeof a.toolName=="string"?a.toolName:void 0,d=She(a),u=dE({toolCallId:l,toolName:c,input:d});if(!u)return;let p=l==null?dE({toolCallId:void 0,toolName:c,input:void 0}):void 0,m=p&&p!==u?i.get(p):void 0,h=(t=i.get(u))!=null?t:m;i.set(u,{key:u,toolCallId:(n=h?.toolCallId)!=null?n:l,toolName:(o=h?.toolName)!=null?o:c,input:(r=h?.input)!=null?r:d,result:h?.result,status:h?.status,errorMessage:h?.errorMessage}),p&&p!==u&&i.delete(p),!l&&h?.result===void 0&&The(s,c,u);}function Che(e){var t,n,o;let{spans:r,pendingKeysByToolName:i,part:s}=e,a=iM(s),l=typeof s.toolName=="string"?s.toolName:void 0,c=bhe(s),d=dE({toolCallId:a,toolName:l,input:void 0}),u=a!=null?d:(t=Ahe(i,l))!=null?t:d;if(!u)return;let p=r.get(u),m=ghe(s,c);r.set(u,{key:u,toolCallId:(n=p?.toolCallId)!=null?n:a,toolName:(o=p?.toolName)!=null?o:l,input:p?.input,result:c,status:m?"ERROR":"OK",errorMessage:m?fhe(c):void 0});}function rW(e){let t=new Map,n=new Map;for(let o of e)for(let r of yhe(o)){if(r.type==="tool-call"){Ehe({spans:t,pendingKeysByToolName:n,part:r});continue}(r.type==="tool-result"||r.type==="tool-error")&&Che({spans:t,pendingKeysByToolName:n,part:r});}return [...t.values()]}function Rhe(e){if(!Array.isArray(e))return;let t="";for(let n of e)pe(n)&&n.type==="text"&&typeof n.text=="string"&&(t+=n.text);return t.length?t:void 0}function vhe(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!pe(n)||n.type!=="tool-call")continue;let o=iM(n),r=typeof n.toolName=="string"?n.toolName:void 0;(o||r)&&t.push({toolCallId:o,toolName:r,input:n.input});}return t.length?t:void 0}function th(e){if(!pe(e))return;let t=e.experimental_telemetry;if(pe(t))return {functionId:typeof t.functionId=="string"?t.functionId:void 0,isEnabled:typeof t.isEnabled=="boolean"?t.isEnabled:void 0,recordInputs:typeof t.recordInputs=="boolean"?t.recordInputs:void 0,recordOutputs:typeof t.recordOutputs=="boolean"?t.recordOutputs:void 0,metadata:pe(t.metadata)?t.metadata:void 0}}function ys(e,t){return {operationName:`${e}${t?` ${t}`:""}`,resourceName:t}}function iW(e,t){if(t==null)return;if(typeof t=="string")return G(e,t);if(typeof t=="number")return Number.isInteger(t)?We(e,t):Zm(e,t);if(typeof t=="boolean")return $me(e,t);if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return ac(e,t);let n=tt(t);return n?G(e,n):void 0}function fE(e){return e?Object.entries(e).filter(([t])=>!t.startsWith("raindrop.internal.")).map(([t,n])=>iW(`ai.telemetry.metadata.${t==="raindrop.userId"?"raindrop.ai.userId":t}`,n)):[]}function sM(e){return pe(e)?Object.entries(e).filter(([,t])=>typeof t=="string").map(([t,n])=>G(`ai.request.headers.${t}`,n)):[]}function aM(e){if(!pe(e))return [];let t=[],n=["maxRetries","timeout","maxOutputTokens","temperature","topP","topK","presencePenalty","frequencyPenalty","seed","stopSequences"];for(let o of n){if(!(o in e))continue;let r=e[o];o==="stopSequences"&&Array.isArray(r)&&r.every(i=>typeof i=="string")?t.push(ac(`ai.settings.${o}`,r)):o==="timeout"&&typeof r=="number"?t.push(We(`ai.settings.${o}`,r)):t.push(iW(`ai.settings.${o}`,r));}return t}function sW(e){return pe(e)?[Zm("gen_ai.request.frequency_penalty",typeof e.frequencyPenalty=="number"?e.frequencyPenalty:void 0),We("gen_ai.request.max_tokens",typeof e.maxOutputTokens=="number"?e.maxOutputTokens:void 0),Zm("gen_ai.request.presence_penalty",typeof e.presencePenalty=="number"?e.presencePenalty:void 0),...Array.isArray(e.stopSequences)&&e.stopSequences.every(t=>typeof t=="string")?[ac("gen_ai.request.stop_sequences",e.stopSequences)]:[],Zm("gen_ai.request.temperature",typeof e.temperature=="number"?e.temperature:void 0),We("gen_ai.request.top_k",typeof e.topK=="number"?e.topK:void 0),Zm("gen_ai.request.top_p",typeof e.topP=="number"?e.topP:void 0)]:[]}function aW(e){if(!pe(e)||!pe(e.providerOptions))return;let t=tt(e.providerOptions);return t?G("ai.request.providerOptions",t):void 0}var whe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},oE=null;function lW(){if(oE)return oE;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return oE=e?new e:new whe,oE}function lM(){return lW().getStore()}function zP(e,t){return lW().run(e,t)}function cW(e){var t;if(e.length===0)return;let n=e[0];if(!pe(n))return;let o=pe(n.metadata)?n.metadata:void 0,r=pe(n.telemetry)?n.telemetry.metadata:void 0,i=pe(r)?r:void 0,s=th(n),a=s?.metadata&&typeof s.metadata=="object"?s.metadata:void 0,l=(t=o??i)!=null?t:a;if(!l)return;let c={rawMetadata:l},d=l["raindrop.userId"];typeof d=="string"&&d&&(c.userId=d);let u=l["raindrop.eventId"];typeof u=="string"&&u&&(c.eventId=u);let p=l["raindrop.internal.eventIdGenerated"];(p===true||p==="true"||p==="1")&&(c.eventIdGenerated=true);let m=l["raindrop.convoId"];typeof m=="string"&&m&&(c.convoId=m);let h=l["raindrop.eventName"];typeof h=="string"&&h&&(c.eventName=h);let g=l["raindrop.properties"];if(typeof g=="string")try{let f=JSON.parse(g);f&&typeof f=="object"&&(c.properties=f);}catch{}else g&&typeof g=="object"&&(c.properties=g);return c}var Ihe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},rE=null;function cM(){if(rE)return rE;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return rE=e?new e:new Ihe,rE}function WP(){return cM().getStore()}function qP(e){var t;let n=cM();(t=n.enterWith)==null||t.call(n,e);}function dW(){var e;let t=cM();(e=t.enterWith)==null||e.call(t,void 0);}var dM=class{constructor(e){this.callStates=new Map,this.priorParentContexts=new Map,this.onStart=t=>{var n,o,r,i,s;if(t.isEnabled===false)return;let a=t.operationId==="ai.embed"||t.operationId==="ai.embedMany",l=t.recordInputs!==false,c=t.recordOutputs!==false,d=t.functionId,u=t.metadata,p=lM(),m=u??p?.rawMetadata,h=this.extractRaindropMetadata(m),g=md().getParentSpanIds(),f=m?.["raindrop.internal.eventIdGenerated"]==="true"||m?.["raindrop.internal.eventIdGenerated"]===true||p?.eventIdGenerated===true,b=h.eventId&&!f?h.eventId:void 0,T=(i=(r=(o=b??((n=this.defaultContext)==null?void 0:n.eventId))!=null?o:g?.eventId)!=null?r:h.eventId)!=null?i:pd(),A=g&&g.eventId===T?{traceIdB64:g.traceIdB64,spanIdB64:g.spanIdB64}:void 0,{operationName:C,resourceName:v}=ys(t.operationId,d),I=!a&&this.subagentWrapping?WP():void 0,_=!a&&this.subagentWrapping&&I===void 0&&typeof m?.["ash.subagent.name"]=="string"?m["ash.subagent.name"]:void 0,x=(s=I?.toolName)!=null?s:_,E,O;if(x&&this.sendTraces){let H=I?[G("raindrop.parent.callId",I.parentCallId),G("raindrop.parent.toolCallId",I.toolCallId),G("raindrop.parent.toolName",I.toolName)]:[];E=this.traceShipper.startSpan({name:x,parent:A,eventId:T,operationId:"ai.toolCall",attributes:[G("operation.name","ai.toolCall"),G("resource.name",x),G("raindrop.span.kind","tool_call"),G("ai.toolCall.name",x),G("raindrop.subagent.name",x),G("raindrop.agent.role","subagent"),...H]});let U=this.spanParentRef(E),$=this.traceShipper.startSpan({name:"agent.subagent",parent:U,eventId:T,operationId:"agent.subagent",attributes:[G("operation.name","agent.subagent"),G("raindrop.span.kind","llm_call"),G("raindrop.subagent.name",x)]});this.traceShipper.endSpan($),O=U;}let N;if(this.sendTraces){let H=!a&&l?[G("ai.prompt",tt({system:t.system,prompt:t.prompt,messages:t.messages}))]:[],U=a&&l?t.operationId==="ai.embedMany"?[G("ai.values",tt(t.value))]:[G("ai.value",tt(t.value))]:[];N=this.traceShipper.startSpan({name:t.operationId,parent:O??A,eventId:T,operationId:t.operationId,attributes:[G("operation.name",C),G("resource.name",v),G("ai.telemetry.functionId",d),G("ai.model.provider",t.provider),G("ai.model.id",t.modelId),...fE(m?Object.fromEntries(Object.entries(m).filter(([$])=>$!=="raindrop.eventId"&&$!=="raindrop.internal.eventIdGenerated")):void 0),...H,...U]});}this.callStates.set(t.callId,{operationId:t.operationId,eventId:T,rootSpan:N,rootParent:N?this.spanParentRef(N):O??A,stepSpan:void 0,stepParent:void 0,toolSpans:new Map,embedSpans:new Map,parentContextToolCallIds:new Set,recordInputs:l,recordOutputs:c,functionId:d,metadata:m,accumulatedText:"",inputText:a?void 0:this.extractInputText(t),toolCallCount:0,subagentName:x,subagentToolCallSpan:E});},this.onStepStart=t=>{let n=this.getState(t.callId);if(!n?.rootSpan||!n.rootParent)return;let r=n.operationId==="ai.streamText"||n.operationId==="ai.streamObject"?`${n.operationId}.doStream`:`${n.operationId}.doGenerate`,{operationName:i,resourceName:s}=ys(r,n.functionId),a=[];n.recordInputs&&(t.promptMessages&&a.push(G("ai.prompt.messages",tt(t.promptMessages))),t.stepTools&&a.push(ac("ai.prompt.tools",t.stepTools.map(c=>JSON.stringify(c)))),t.stepToolChoice!=null&&a.push(G("ai.prompt.toolChoice",JSON.stringify(t.stepToolChoice))));let l=this.traceShipper.startSpan({name:r,parent:n.rootParent,eventId:n.eventId,operationId:r,attributes:[G("operation.name",i),G("resource.name",s),G("ai.telemetry.functionId",n.functionId),G("ai.model.provider",t.provider),G("ai.model.id",t.modelId),G("gen_ai.system",t.provider),G("gen_ai.request.model",t.modelId),...a]});n.stepSpan=l,n.stepParent=this.spanParentRef(l);},this.onToolExecutionStart=t=>this.toolExecutionStart(t),this.onToolExecutionEnd=t=>this.toolExecutionEnd(t),this.onToolCallStart=t=>this.toolExecutionStart(t),this.onToolCallFinish=t=>this.toolExecutionEnd(t),this.onLanguageModelCallStart=t=>{},this.onLanguageModelCallEnd=t=>{},this.onChunk=t=>{var n,o,r,i,s;let a=(o=t.callId)!=null?o:(n=t.chunk)==null?void 0:n.callId;if(!a)return;let l=this.getState(a);if(!l)return;let c=t.chunk;if(!(!c||typeof c!="object")){if(c.type==="text-delta"){let d=(r=c.textDelta)!=null?r:c.delta;typeof d=="string"&&(l.accumulatedText+=d,this.emitLive(l,"text_delta",d));}else if(c.type==="reasoning"||c.type==="reasoning-delta"){let d=(s=(i=c.textDelta)!=null?i:c.text)!=null?s:c.delta;typeof d=="string"&&this.emitLive(l,"reasoning_delta",d);}}},this.onStepFinish=t=>{var n,o,r,i,s,a,l,c,d;let u=this.getState(t.callId);if(!u?.stepSpan)return;let p=[];if(u.recordOutputs&&(p.push(G("ai.response.finishReason",t.finishReason),G("ai.response.text",(n=t.text)!=null?n:void 0),G("ai.response.id",(o=t.response)==null?void 0:o.id),G("ai.response.model",(r=t.response)==null?void 0:r.modelId),G("ai.response.timestamp",((i=t.response)==null?void 0:i.timestamp)instanceof Date?t.response.timestamp.toISOString():(s=t.response)==null?void 0:s.timestamp),G("ai.response.providerMetadata",t.providerMetadata?tt(t.providerMetadata):void 0)),((a=t.toolCalls)==null?void 0:a.length)>0&&p.push(G("ai.response.toolCalls",JSON.stringify(t.toolCalls.map(h=>({toolCallId:h.toolCallId,toolName:h.toolName,input:h.input}))))),((l=t.reasoning)==null?void 0:l.length)>0)){let h=t.reasoning.filter(g=>"text"in g).map(g=>g.text).join(`
164
+ `)),i(" ",n(u));}}setMinLevel(t){typeof t=="string"?this.minLogLevel=bf[t]:this.minLogLevel=t;}setOutputStream(t){this.forcedStream=t;}log(...t){this.logWithLevel(30,Qs.reset,...t);}info(...t){this.logWithLevel(30,Qs.white,...t);}debug(...t){this.logWithLevel(20,Qs.dim,...t);}warn(...t){this.logWithLevel(40,Qs.yellow,...t);}error(...t){this.logWithLevel(50,Qs.red,...t);}success(...t){this.logWithLevel(30,Qs.green,...t);}dimmed(...t){this.logWithLevel(30,Qs.dim,...t);}underline(...t){this.logWithLevel(30,Qs.underline,...t);}bold(...t){this.logWithLevel(30,Qs.bold,...t);}grey(...t){this.logWithLevel(30,Qs.grey,...t);}child(t){let n=new e(this.minLogLevel,{...this.logBindings,...t});return n.forcedStream=this.forcedStream,n}async flush(){}bindings(){return this.logBindings}},R=zx._internalSingleton(),br={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>br,flush:async()=>{},bindings:()=>({})},$T={},qx=({logger:e,logKey:t,maxCount:n,intervalMs:o},r,i,...s)=>{let a=$T[t];a?clearTimeout(a.timer):(a={count:0,totalCount:0},$T[t]=a),a.totalCount++,a.count<n&&(a.count++,e.debug(r,i,...s)),a.timer=setTimeout(()=>{let l=$T[t];l?.totalCount!==l?.count&&e.debug({logKey:t,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${t}`),delete $T[t];},o);};var GU=1e4,jU=1,vm=Ql.extend({browserType:z.enum(za).optional(),slowMoMs:z.number().optional().refine(e=>e===void 0||e<=GU&&e>=-1,{message:`Slow motion must be between 0 and ${GU} milliseconds`}),basicAuthorization:z.object({username:z.string().optional(),password:z.string().optional()}).optional(),geolocation:z.object({latitude:z.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:z.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:z.boolean().optional(),locale:z.string().optional(),timezone:z.enum(NT).optional(),colorScheme:z.enum(["light","dark"]).optional()}),$U=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],Kx=z.object({useMemory:z.boolean().optional(),failureRecovery:z.boolean().optional().describe("undefined means inherit org settings")}),Yx=Kx.extend({disableAICaching:z.boolean().optional(),failureRecoveryInstructions:z.string().optional()}),Dae=z.object({viewport:Jl.optional()}),_i=Dae.extend(Yx.shape).extend(vm.shape),VT=z.object({cron:z.string().refine(e=>isValidCron(e),{error:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:z.boolean().default(false),env:z.string().optional(),timeZone:z.string().default("America/Los_Angeles"),jobKey:z.string().optional()}),zT=z.object({onSuccess:z.boolean().default(false),failureMessage:z.string().optional(),onFailure:z.boolean().default(true),successMessage:z.string().optional()}),Fae=z.object({name:z.string(),required:z.boolean().optional(),defaultValue:z.string().describe("this is not optional because we need a value when the editor is first loaded")}),VU=Fae.array(),Bae=z.object({name:z.string(),value:z.string()}),WT=Bae.array(),zU=z.object({name:z.string(),default:z.boolean().optional(),fixtures:SU.array().optional()});var qa=Kx.extend({agentConfig:z.record(z.string(),z.string()).optional(),aiFailureAnalysis:z.boolean().optional(),classification:C0.optional(),triage:E0.optional(),healing:pT.optional(),explore:Sf.optional(),select:IU.optional()}),Uae=z.object({cliOnly:z.boolean().optional(),neverShowUsageBanner:z.boolean().optional(),hideInternalTraceInfo:z.boolean().optional(),bypassUsageLimits:z.boolean().optional()}),Jx=z.object({fakerConstantSeed:z.boolean().optional(),isolateCachesByEnvironment:z.boolean().optional()}),Hae=z.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),Gae=z.enum(["ios","android","web"]),jae=z.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),$ae=z.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","other"]),Vae=z.object({helpIntents:z.array(Hae).optional(),helpIntentOtherText:z.string().optional(),deviceTypeIntent:Gae.optional(),currentTestingTool:jae.optional(),heardAboutSource:$ae.optional()}),zae=z.object({discovery:Vae.optional(),needsToCompleteOnboarding:z.boolean().optional(),wizardCompletedAt:z.iso.datetime().optional()}),wm=z.object({ai:qa.optional(),githubAppInstallationId:z.number().nullish(),githubAppSummaryMessageEnabled:z.boolean().nullish(),githubReleaseAppInstallationId:z.number().nullish(),gitlabAppAccessToken:z.string().nullish(),gitlabAppBaseUrl:z.string().nullish(),browser:kx.optional(),internal:Uae.optional(),advanced:Jx.optional(),onboarding:zae.optional()});function WU(e){try{return wm.parse(e)}catch{return R.warn("Cloud settings contain values this version of the CLI does not support. Please upgrade. Falling back to defaults."),wm.parse({})}}z.object({globalOverrides:z.record(z.string(),z.string()).optional(),agentConfig:z.record(z.string(),z.string()).optional()});z.record(z.string(),z.string()).nullish();var Zs=(n=>(n.CANNOT_FIX_TEST="CANNOT_FIX_TEST",n.FIXED="FIXED",n))(Zs||{}),qU=z.object({index:z.int().nonnegative(),section:wx,step:_t}),Wae=z.object({additions:qU.array(),deletions:qU.array()}),Qx=z.object({subAgentStatus:z.enum(Zs).default("CANNOT_FIX_TEST"),rootCause:z.string(),solution:z.string(),verificationNotes:z.string().optional().default(""),diffs:Wae.optional(),pullRequestUrl:z.string().optional(),branchUrl:z.string().optional()}),KU=Qx.optional().catch(void 0);var Pi={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Gt=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(Gt||{});var Tf=(r=>(r.NOT_ATTEMPTED="NOT_ATTEMPTED",r.PERM_HEAL_SUCCEEDED="PERM_HEAL_SUCCEEDED",r.PERM_HEAL_FAILED="PERM_HEAL_FAILED",r.PERM_HEAL_ON_SUCCESS_FAILED="PERM_HEAL_ON_SUCCESS_FAILED",r))(Tf||{});var Xx=z.enum(Tf).default("NOT_ATTEMPTED"),qT=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(qT||{});var qae=z.object({attempts:z.int().nonnegative()}),On=z.string().pipe(z.coerce.date()).or(z.date()),ea=z.object({id:z.string(),runKey:z.string(),organizationId:z.string(),executionType:Rm.optional().default("WEB"),createdAt:On,createdBy:z.string(),flake:z.boolean().nullish(),scheduledAt:On.or(z.null()),startedAt:On.or(z.null()),updatedAt:On.nullish(),finishedAt:On.or(z.null()),resolvedBaseUrl:z.string().nullish(),environmentName:z.string().nullish(),gitBranchName:z.string().nullish(),gitMainBranch:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),labels:z.array(z.string()).optional(),gitOriginUrl:z.string().nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),gitCommitTimestamp:On.nullish(),gitCommitMessage:z.string().nullish(),schemaVersion:z.string().nullish(),cliVersion:z.string().nullish(),section:z.enum(qT).nullish(),status:z.enum(Gt),healStatus:Xx,healDetails:KU.nullish(),trigger:z.enum(Pi),attempts:z.number(),runAttempts:z.array(z.object({id:z.string(),status:z.enum(Gt),startedAt:On.or(z.null()),finishedAt:On.or(z.null())})).optional(),videos:z.array(z.string()).optional(),failureReason:z.string().nullish(),failureDetails:w0.nullish(),failureRecoveryDetails:qae.nullish(),pipelineId:z.string().nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),quarantined:z.boolean().nullish().default(false),quarantinedReason:z.string().nullish(),localTestId:z.string().nullish(),testId:z.string().nullish(),testName:z.string().nullish(),description:z.string().nullish(),directory:z.string().nullish(),test:z.object({name:z.string(),id:z.string()}).nullish().default(null),suiteId:z.string().nullish(),aiSettings:qa.nullish(),stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish()}),Kae={id:true,status:true,healStatus:true,healDetails:true,testName:true,localTestId:true,testId:true,test:{select:{name:true,id:true}},finishedAt:true,failureReason:true,failureDetails:true},KT=ea.pick({...Kae,test:true}),Zx=ea.omit({failureReason:true,failureDetails:true,test:true}),e_=ea.extend({stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),test:z.object({name:z.string(),id:z.string(),description:z.string().nullish(),baseUrl:z.string().nullish(),advanced:_i.nullish()}).nullish()}).extend(Ux.shape),YU=e=>e.includes("PASSED")&&e.includes("FAILED");var JU=z.enum(["error","warning","passing"]);var QU=z.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]);var XU=z.object({kind:QU,detail:z.string().min(1).max(280)}),Eu=z.object({riskLevel:z.string(),headline:z.string().min(1).max(200).describe("One-sentence summary of what happened in this run. Plain text, no markdown."),overview:z.string().min(1).max(280).optional().describe("One plain-text sentence giving the bottom line of the run. No markdown."),summaryMarkdown:z.string().min(1).max(4e3).describe("Markdown body. Several short paragraphs or a tight list. No emojis, no top-level heading. Max 5 sentences."),recommendedAction:XU.optional()}),ZU=Eu.extend({riskLevel:JU.describe("Traffic-light validation signal. Use passing when validation is trustworthy with no real concern, warning when review or follow-up is needed, and error when the evidence shows the PR may hide or cause a product regression or another material concern that requires review."),headline:z.string().min(1).max(60).describe("Short, factual, title-case status of the validation signal, 6 words max, no punctuation. Describe the outcome only - never name the process or mode (no 'dry run', 'auto-heal', 'triage', 'pending'); those are shown separately. Examples: 'Review Required', 'Sign In Failing Across 5 Tests', 'All Tests Passed'."),overview:z.string().min(1).max(280).describe("The bottom-line verdict in one plain sentence: what the Momentic validation means for user-visible behavior and how trustworthy the signal is. This is the conclusion only, not the evidence. No markdown, headings, lists, or emojis. Do not prescribe a merge decision (use recommendedAction)."),summaryMarkdown:z.string().min(1).max(1e3).describe("The supporting evidence behind the overview, in GitHub-flavored markdown: a few short sentences or a tight list with the specific tests, errors, and signals that justify the verdict. Must carry information the overview does not - never paraphrase or restate the overview. Do not prescribe a merge decision or restate repair mechanics. Max 4 sentences. No emojis or top-level heading."),recommendedAction:XU.extend({kind:QU.describe("The kind of action a reviewer should take. safe_to_merge = signal is trustworthy and can be merged as-is; confirm_intended_change = a product or UI change was detected (or a heal relaxed an expectation) and a human must confirm it is intentional; investigate_regression = evidence points to a real product bug or regression to investigate before merging; fix_test = a broken or stale test or test setup needs repair; resolve_infra = an infrastructure or environment problem needs resolving and a re-run; review_coverage = quarantine has materially reduced coverage that should be reviewed."),detail:z.string().min(1).max(280).describe("One plain-text sentence naming the specific next step (e.g. 'Confirm the new success-indicator color is an intended design change'). No markdown.")}).describe("The single most important next step a reviewer should take. Omit entirely when the signal is clean and there is genuinely nothing to do.").optional()});var eH=z.object({id:z.string(),status:z.enum(Gt),trigger:z.enum(Pi),createdAt:On,startedAt:On.nullish(),finishedAt:On.nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitTimestamp:On.nullish(),gitBranchName:z.string().nullish(),gitOriginUrl:z.string().nullish(),gitCommitMessage:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),pipelineId:z.string().nullish(),ciProvider:z.string().nullish(),cliVersion:z.string().nullish(),labels:z.string().array().optional(),healRiskSummary:Eu.optional(),localSuiteName:z.string().optional(),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:z.object({status:z.enum(Gt),environmentName:z.string().nullish()}).array()}),tH=eH.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:KT.array()}),nH=eH.extend({runs:ea.array()});var Jae=z.object({type:z.literal("TARGETING"),name:z.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:pU.array(),pageState:z.string().optional(),targetSource:z.enum(xa).optional(),targetUpdateTime:z.string().optional()}),Qae=z.object({type:z.literal("AI_LOCATION"),matched:z.boolean(),pageState:z.string().optional(),ragUsed:z.boolean().optional(),thoughts:z.string().optional()}),Xae=z.object({type:z.literal("ASSERTION"),relevantElementsSerialized:z.string().array().optional(),pageState:z.string().optional(),ragUsed:z.boolean().optional()}),oH=z.discriminatedUnion("type",[Jae,Qae,Xae]);var Zae=z.object({id:z.string(),name:z.string()});Zae.extend(z.object({createdAt:On,createdBy:z.string(),schedule:VT,notification:zT,environment:z.object({name:z.string()}).nullish(),beforeTests:z.object({id:z.string()}).array().nullish(),afterTests:z.object({id:z.string()}).array().nullish()}).shape);var rH=z.object({id:z.guid(),orgId:z.string(),createdAt:On,startedAt:On.or(z.null()),finishedAt:On.or(z.null()),status:z.enum(Gt),trigger:z.enum(Pi),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:ea.array()});rH.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var iH=rH.extend({runs:KT.array()});function sH({beforeStatus:e,mainStatus:t,afterStatus:n}){return e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":"PASSED"}function aH(e,t){return e.some(r=>t?.onlyQuarantined?r.status==="FAILED":!r.quarantined&&r.status==="FAILED")?"FAILED":e.some(r=>r.status==="CANCELLED")?"CANCELLED":"PASSED"}function lH(e){switch(e){case "PASSED":return "SUCCESS";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":case "PENDING":case "RETRYING":case "WAITING_FOR_USER":return "RUNNING"}}var t_=z.object({content:z.string(),ids:z.string().array(),tokenLength:z.number()}),ele=z.object({chunks:t_.array()});z.object({ids:z.string().array(),score:z.number(),tokenLength:z.number()});ele.extend({description:z.string().describe("Input to pass to RAG engine"),tokenLimit:z.number()});var cH=z.object({ids:z.number().array()}),dH=z.object({indices:z.number().array()});var vo=z.object({disableCache:z.boolean().optional(),useMemory:z.boolean().optional(),clientMode:z.enum(["interactive","runner"]).optional(),loggerTags:z.record(z.string(),z.string()).optional(),langfuseSessionId:z.string().optional(),agentConfigVersion:z.string().optional(),cacheBustReason:z.enum(Fg).optional()});vo.extend({chunks:t_.array(),description:z.string().describe("Input to pass to AI"),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),softTokenLimit:z.number(),mediumTokenLimit:z.number().optional(),hardTokenLimit:z.number(),callId:z.string().optional()});var tle=z.object({screenshotBase64AfterCommand:z.string(),urlAfterCommand:z.string(),serializedCommand:z.string(),elementInteracted:z.string().optional(),thoughts:z.string().optional()}),uH=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),source:uU.optional().catch(void 0),isTieBreakerCall:z.boolean().optional(),memory:z.discriminatedUnion("type",[Hs,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),firstPassModelResults:PT.array().optional(),knowledgeBaseSection:z.string().optional()}),pH=z.object({target:z.string().or(z.number()),browserState:z.string().optional(),screenshot:z.string().optional(),boundingBox:z.object({x:z.number(),y:z.number(),height:z.number(),width:z.number()}).optional()}),mH=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),hH=z.object({goal:z.string(),emulatorState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),n_=z.union([z.literal("NEGATED_CHECK"),z.literal("CONDITIONAL_CHECK")]),gH=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),url:z.string(),contextChoice:ax.optional(),memory:z.discriminatedUnion("type",[hu,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),source:n_.optional(),recoveryHint:z.string().optional(),knowledgeBaseSection:z.string().optional()}),fH=z.object({command:zc}),o_=z.object({goal:z.string(),browserState:z.string(),startingScreenshot:z.string().optional(),screenshot:z.string(),url:z.string(),history:tle.array(),actionHint:z.string().optional(),lastError:z.string().optional()}),yH=z.object({results:BT.array(),errorMessage:z.string(),errorStack:z.string().optional()}),SH=z.object({results:BT.array(),goal:z.string(),errorMessage:z.string()}),bH=z.object({failedResults:BT.array(),nextStepsSerialized:z.string().array(),currentUrl:z.string(),currentPageState:z.string(),currentScreenshot:z.string(),customInstructions:z.string().optional(),testDescription:z.string().optional()});z.object({description:z.string(),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),excerpt:z.string()});var TH=z.object({type:z.string(),browserContext:z.string(),currentStep:z.string(),screenshot:z.string()}),AH=z.object({description:z.string(),browserState:z.string().optional(),screenshot:z.string()}),nle=z.enum(["locator","assertion"]);z.object({completionType:nle,currentGoal:z.string(),pastGoal:z.string().optional(),currentScreenshot:z.string(),pastScreenshot:z.string(),pastResult:z.union([z.boolean(),z.number()])});z.object({goal:z.string()});var EH=z.object({keywords:z.array(z.string())});var YT=(i=>(i.LOCATOR="locator",i.ASSERTION="assertion",i.VISUAL_ASSERTION="visual-assertion",i.TEXT_EXTRACTION="text-extraction",i.FAILURE_RECOVERY="failure-recovery",i))(YT||{}),ole=["locator","assertion","visual-assertion","text-extraction","failure-recovery"];z.enum(YT);var rle=new Set(ole);function ile(e){return rle.has(e)}var sle=z.enum(["v1","v2","v3","v4"]),ale=z.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1");z.union([sle,ale,z.string().describe("for people with special configurations")]);var xm={locator:"v4",assertion:"v4","visual-assertion":"v4","text-extraction":"v3","failure-recovery":"v2"};var lle={locator:{v4:["v4.2","v4.1","v4.0"],v3:["v3.3","v3.2","v3.1","v3.0"],v2:["v2.2","v2.1","v2.0"],v1:["v1.0"]},assertion:{v4:["v4.1","v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.3","v2.2","v2.1","v2.0"],v1:["v1.0"]},"visual-assertion":{v4:["v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.0"],v1:["v1.0"]},"text-extraction":{v3:["v3.0"],v2:["v2.0"],v1:["v1.0"]},"failure-recovery":{v2:["v2.1","v2.0"],v1:["v1.0"]}},CH=(s=>(s.ANDROID_LOCATOR="android-locator",s.IOS_LOCATOR="ios-locator",s.ANDROID_ASSERTION="android-assertion",s.IOS_ASSERTION="ios-assertion",s.ANDROID_TEXT_EXTRACTION="android-text-extraction",s.IOS_TEXT_EXTRACTION="ios-text-extraction",s))(CH||{});z.enum(CH);function RH(e){for(let[t,n]of Object.entries(e)){if(!ile(t))continue;let o=lle[t];if(!o)continue;let r=new Set;for(let[i,s]of Object.entries(o)){r.add(i);for(let a of s)r.add(a);}if(!r.has(n)){let i=[...r].sort();throw new Y("UserConfigurationError",`Invalid agent config: "${n}" is not a valid version for "${t}". Valid versions: ${i.join(", ")}`)}}}var Xl=w__default.object({id:w__default.guid(),envKey:w__default.string().optional(),skipped:w__default.boolean().optional(),retries:w__default.number().optional()});var Cu=(r=>(r.PRESET="MOBILE_PRESET_STEP",r.MODULE="MOBILE_MODULE_STEP",r.AI_ACTION="MOBILE_AI_ACTION_STEP",r.CONDITIONAL="MOBILE_CONDITIONAL_STEP",r))(Cu||{});var _m=Xl.extend({type:w__default.literal("MOBILE_CONDITIONAL_STEP")});var Tr=z.object({id:z.string(),name:ET,baseUrl:CT,description:z.string().optional().nullish(),schemaVersion:z.string(),advanced:_i,retries:z.number().optional().nullish(),envs:z.array(zU).nullish(),parameters:VU.nullish(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional().catch([])}),vH=z.enum(["INHERIT","ENABLED","DISABLED"]);var dle=_i.extend({failureRecovery:vH.optional(),useMemory:vH.optional()});Tr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true}).extend({advanced:dle});Tr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true});var ule=z.object({labels:z.array(z.string()).optional(),outputs:WT.nullish()}),Wn=Tr.extend(ule.shape),ple=z.object({createdAt:z.coerce.date(),updatedAt:z.coerce.date(),updatedBy:z.string().nullable(),schedule:VT,notification:zT,createdBy:z.string(),organizationId:z.string(),folderId:z.string().nullable().optional()}),mle=Tr.extend(ple.shape);mle.extend(Jc.shape);var r_=Tr.extend(Jc.shape);Tr.extend(Wl.shape);var hle="test",gle="module",fle="mobile-test",yle="mobile-module",Sle="test/v2",ble="module/v2",Tle="mobile-test/v2",Ale="mobile-module/v2";var we=(l=>(l.TEST=`momentic/${hle}`,l.MODULE=`momentic/${gle}`,l.TEST_V2=`momentic/${Sle}`,l.MODULE_V2=`momentic/${ble}`,l.MOBILE_TEST=`momentic/${fle}`,l.MOBILE_MODULE=`momentic/${yle}`,l.MOBILE_TEST_V2=`momentic/${Tle}`,l.MOBILE_MODULE_V2=`momentic/${Ale}`,l))(we||{});Tr.merge(Wl);var Ele=Rn.extend({steps:z.array(z.record(z.string(),z.unknown().optional())),schemaVersion:z.string()}),Cf=Ele.extend({fileType:z.literal(we.MODULE)});z.object({test:z.string().describe("YAML for the test, including metadata and steps"),modules:z.record(z.string(),z.string()).describe("Map of module name to YAML for the module")});function JT(e){if(e===void 0)return "__undefined__";if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(JT);let t={};for(let[n,o]of Object.entries(e))t[n]=JT(o);return t}var Cle=/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/,wH=36,Ln=z.union([z.guid().max(wH,"V2 IDs must be 36 characters or fewer"),z.string().max(wH,"V2 IDs must be 36 characters or fewer").regex(Cle,"V2 IDs must be lowercase kebab-case with at least three words, e.g. silver-river-lantern")],{error:"ID must be a UUID or lowercase kebab-case with at least three words, e.g. silver-river-lantern (36 characters max)"});var QT=w.discriminatedUnion("type",[w.object({type:w.literal("SCREEN")}),w.object({type:w.literal("OPEN_APP")}),w.object({type:w.literal("OPEN_WEBVIEW")})]),Zl=w.object({type:w.literal("description"),description:w.string()}),s_=w.object({type:w.literal("CUSTOM_COORDINATES"),startX:w.number().describe("Starting X coordinate in pixels"),startY:w.number().describe("Starting Y coordinate in pixels"),deltaPixels:w.number().describe("Number of pixels to scroll in the specified direction")}),XT=w.discriminatedUnion("type",[...QT.options,w.object({type:w.literal("CUSTOM"),target:Zl}),s_]);function Rle(e){return e.toLowerCase().replaceAll("_"," ")}function a_(e){switch(e.type){case "CUSTOM":return e.target.description;case "CUSTOM_COORDINATES":return `custom coordinates (x: ${e.startX}, y: ${e.startY}, delta: ${e.deltaPixels}px)`;case "SCREEN":case "OPEN_APP":case "OPEN_WEBVIEW":return Rle(e.type);default:{throw new Error("Unreachable")}}}var vle=w.object({type:w.literal("coordinates"),xPercent:w.number(),yPercent:w.number()}),wle=w.object({type:w.literal("absolute_percent"),x:w.number(),y:w.number()}),Pm=w.discriminatedUnion("type",[Zl,vle,wle]);var Ile=w.object({x1:w.number(),y1:w.number(),x2:w.number(),y2:w.number(),tolerance:w.nativeEnum(li),preciseTolerance:w.boolean().optional()}),xle=w.object({width:w.number(),height:w.number(),tolerance:w.nativeEnum(li),preciseTolerance:w.boolean().optional()}),l_=w.object({requiredText:w.string().optional(),requiredAttributes:w.record(w.string(),w.string()).optional(),requiredBounds:w.boolean().optional(),position:Ile.optional(),shape:xle.optional()}),IH=w.object({xPath:w.string(),requirements:l_.optional()}),_le=w.object({type:w.literal("CUSTOM"),target:Zl,cache:w.lazy(()=>xH).optional()}),Ple=w.object({pixelDelta:w.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:w.union([QT,_le,s_]),direction:w.enum(["up","down"])}),xH=w.object({type:w.literal("NATIVE"),bounds:w.number().array().optional(),resolvedDescription:w.string().optional(),xPath:w.string().optional(),elementOnlySerializedXml:w.string().optional(),scrollDetails:Ple.optional(),requirements:l_.optional(),requiredRelatedElements:IH.array().optional(),memory:Hs.optional()}),Mle=w.object({type:w.literal("WEBVIEW"),resolvedDescription:w.string().optional(),xPath:w.string().optional(),browserCache:_a.optional(),memory:Hs.optional()}),ZT=w.union([xH,Mle]);var Ole=w.object({left:w.number(),top:w.number(),right:w.number(),bottom:w.number()});w.object({newViewportBounds:Ole});var Nle=w.object({type:w.literal("CUSTOM"),target:Zl,cache:w.lazy(()=>OH).optional()}),_H=w.object({pixelDelta:w.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:w.union([QT,Nle,s_]),direction:w.enum(["up","down"])}),PH=(n=>(n.Native="native",n.Appium="appium",n))(PH||{}),c_=w.tuple([w.number(),w.number(),w.number(),w.number()]),MH=IH.extend({bounds:c_.optional(),browserCache:_a.optional()}),OH=w.object({type:w.literal("NATIVE"),bounds:c_.optional(),resolvedDescription:w.string().optional(),sourceTree:w.nativeEnum(PH).optional(),xPath:w.string().optional(),elementOnlySerializedXml:w.string().optional(),scrollDetails:_H.optional(),requirements:l_.optional(),requiredRelatedElements:MH.array().optional(),memory:Hs.optional()}),Lle=w.object({type:w.literal("WEBVIEW"),bounds:c_.optional(),resolvedDescription:w.string().optional(),xPath:w.string().optional(),scrollDetails:_H.optional(),browserCache:_a.optional(),requiredRelatedElements:MH.array().optional(),memory:Hs.optional()}),eA=w.discriminatedUnion("type",[OH,Lle]);var Wt=(E=>(E.AI_CHECK="AI_CHECK",E.AI_EXTRACT="AI_EXTRACT",E.TAP="TAP",E.TYPE="TYPE",E.PRESS="PRESS",E.PRESS_KEYBOARD="PRESS_KEYBOARD",E.OPEN_APP="OPEN_APP",E.KILL_APP="KILL_APP",E.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",E.SWIPE="SWIPE",E.SCROLL_TO="SCROLL_TO",E.SCREEN_CHECK="SCREEN_CHECK",E.ELEMENT_CHECK="ELEMENT_CHECK",E.DRAG_AND_DROP="DRAG_AND_DROP",E.JAVASCRIPT="JAVASCRIPT",E.REQUEST="REQUEST",E.WAIT="WAIT",E.ADD_FILE="ADD_FILE",E.INSTALL_APP="INSTALL_APP",E.UNINSTALL_APP="UNINSTALL_APP",E.TOGGLE_SETTINGS="TOGGLE_SETTINGS",E.ROTATE_ORIENTATION="ROTATE_ORIENTATION",E.ADB_COMMAND="ADB_COMMAND",E.APPIUM_EXECUTE="APPIUM_EXECUTE",E.STATE="STATE",E))(Wt||{}),ze=w__default.object({id:w__default.guid(),disableCache:w__default.boolean().optional()}),Mm=w__default.object({updatedAt:w__default.coerce.date().optional(),updatedAtLoggerTags:w__default.record(w__default.string(),w__default.string()).optional()}),ms=Mm.extend({target:ZT}),tA=Mm.extend({fromTarget:ZT,toTarget:ZT}),Ya=Mm.extend({target:eA}),NH=Mm.extend({fromTarget:eA,toTarget:eA}),ec=e=>{switch(e.type){case "description":return e.description;case "coordinates":return `${Math.round(e.xPercent*100)}%, ${Math.round(e.yPercent*100)}%`;case "absolute_percent":return `x: ${e.x}%, y: ${e.y}%`}};var LH=ze.extend({type:w__default.literal("ADB_COMMAND"),command:w__default.string(),jsonArgs:w__default.string().optional()});var kle=w__default.string().trim(),DH=ze.extend({type:w__default.literal("INSTALL_APP"),uri:kle});var FH=ze.extend({type:w__default.literal("OPEN_NOTIFICATION_DRAWER")});var nA=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(nA||{}),UH=ze.extend({type:w__default.literal("TOGGLE_SETTINGS"),settingsType:w__default.nativeEnum(nA)});var GH=ze.extend({type:w__default.literal("UNINSTALL_APP"),packageName:w__default.string()});var oA=ze.extend({type:w__default.literal("APPIUM_EXECUTE"),command:w__default.string(),jsonArgs:w__default.string().optional()});var jH=ze.extend({type:w__default.literal("ADD_FILE"),file:w__default.string(),storageLocation:w__default.string()});var tc=ze.extend({type:w__default.literal("AI_CHECK"),assertion:w__default.string(),timeoutSecs:w__default.number().optional(),cache:Mm.extend({memory:hu.optional()}).optional()});var $H=ze.extend({type:w__default.literal("AI_EXTRACT"),goal:w__default.string(),schema:w__default.string().optional()});var Om=ze.extend({type:w__default.literal("JAVASCRIPT"),code:w__default.string(),timeout:w__default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var VH=ze.extend({type:w__default.literal("KILL_APP")});var rA=(n=>(n.HOME="HOME",n.POWER="POWER",n))(rA||{}),f_=(s=>(s.BACK="BACK",s.APP_SWITCHER="APP_SWITCHER",s.SEARCH="SEARCH",s.VOLUME_UP="VOLUME_UP",s.VOLUME_DOWN="VOLUME_DOWN",s.VOLUME_MUTE="VOLUME_MUTE",s))(f_||{}),iA=ze.extend({type:w__default.literal("PRESS"),key:w__default.nativeEnum(rA),longPress:w__default.boolean().optional()}),zH=iA.extend({key:w__default.nativeEnum(f_).or(w__default.nativeEnum(rA))}),WH=iA;var qH=ze.extend({type:w__default.literal("REQUEST")}).merge(Gg);var YH=(n=>(n.PORTRAIT="PORTRAIT",n.LANDSCAPE="LANDSCAPE",n))(YH||{}),JH=ze.extend({type:w__default.literal("ROTATE_ORIENTATION"),orientation:w__default.nativeEnum(YH)});var Ule=w__default.object({type:w__default.literal("CONTENT"),negated:w__default.boolean().optional(),value:w__default.string()}),Lm=ze.extend({type:w__default.literal("SCREEN_CHECK"),assertion:Ule,timeout:w__default.number().int().min(0).max(om).optional().describe("max seconds to wait for the assertion to be true")});var QH=ze.extend({type:w__default.literal("STATE")});var ZH=ze.extend({type:w__default.literal("WAIT"),timeoutSecs:w__default.number()});var vf=w__default.discriminatedUnion("type",[QH,tc,$H,Om,ZH,qH,JH,Lm,jH,VH]);w__default.discriminatedUnion("type",[...vf.options,iA]);var S_=ze.extend({type:w__default.literal("DRAG_AND_DROP"),fromTarget:Zl,toTarget:Zl,hoverDuration:w__default.number().optional(),dragDuration:w__default.number().optional()}),wf=S_.extend({cache:tA.optional()}),If=S_.extend({cache:NH.optional()});var b_=ze.extend({type:w__default.literal("ELEMENT_CHECK"),target:Pm,assertion:tT,timeout:w__default.number().int().min(0).max(om).optional().describe("max seconds to wait for the assertion to be true")}),Ru=b_.extend({cache:ms.optional()}),vu=b_.extend({cache:Ya.optional()});var sA=(n=>(n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(sA||{}),T_=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(T_||{}),nG=ze.extend({type:w__default.literal("PRESS_KEYBOARD"),key:w__default.nativeEnum(sA)}),oG=ze.extend({type:w__default.literal("PRESS_KEYBOARD"),key:w__default.nativeEnum(T_).or(w__default.nativeEnum(sA))});var rG=ze.extend({type:w__default.literal("OPEN_APP"),packageName:w__default.string(),activityName:w__default.string().optional(),intentExtras:w__default.string().optional()}),iG=ze.extend({type:w__default.literal("OPEN_APP"),packageName:w__default.string(),intentExtras:w__default.string().optional()});var A_=ze.extend({type:w__default.literal("SCROLL_TO"),target:Zl,direction:w__default.enum(["down","up"]),scrollableElement:XT,scrollStepPercent:w__default.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.9 (90%)."),maxScrollAttempts:w__default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),_f=A_.extend({cache:ms.optional()}),Pf=A_.extend({cache:Ya.optional()});var E_=ze.extend({type:w__default.literal("SWIPE"),direction:w__default.enum(["up","down","left","right"]),scrollableElement:XT,viewportPercent:w__default.number().optional(),durationMs:w__default.number().optional(),relativePosition:Zb.optional()}),Mf=E_.extend({cache:ms.optional()}),Of=E_.extend({cache:Ya.optional()});var C_=ze.extend({type:w__default.literal("TAP"),target:Pm,longPress:w__default.boolean().optional(),longPressDurationMs:w__default.number().optional(),iterations:w__default.number().optional(),tapDelayMs:w__default.number().optional(),relativePosition:Zb.optional(),doubleTap:w__default.boolean().optional(),doubleTapDelayMs:w__default.number().optional()}),Nf=C_.extend({cache:ms.optional()}),Lf=C_.extend({cache:Ya.optional()});var R_=ze.extend({type:w__default.literal("TYPE"),target:Pm.optional(),keyPressDelayMs:w__default.number().optional(),text:w__default.string(),clearContent:w__default.boolean().optional(),forceClearContent:w__default.boolean().optional()});var Df=R_.extend({cache:ms.optional()}),Ff=R_.extend({cache:Ya.optional()});var Bf=w__default.discriminatedUnion("type",[...vf.options,Nf,Df,zH,oG,GH,DH,LH,oA,wf,FH,_f,Mf,UH,Ru,rG]);var Uf=w__default.discriminatedUnion("type",[...vf.options,Lf,Ff,WH,nG,iG,Of,If,Pf,vu,oA]);var lG=w__default.union([w__default.string(),w__default.record(w__default.string(),w__default.unknown().optional())]),cA=Xl.extend({type:w__default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:w__default.number().optional()}),td=cA.extend({command:Bf}),nd=cA.extend({command:Uf}),km=w__default.object({moduleId:w__default.string(),inputs:w__default.record(w__default.string(),w__default.string()).optional()}),Hf=Xl.merge(km.extend({type:w__default.literal("MOBILE_MODULE_STEP")}));km.extend({steps:w__default.lazy(()=>Ja.array())});km.extend({steps:w__default.lazy(()=>nc.array())});var v_=(n=>(n.V2="2",n.V3="3",n))(v_||{});var w_=w__default.nativeEnum(v_),Vle=Ia.extend({platform:w__default.literal("ANDROID"),resolvedGoal:w__default.string(),steps:w__default.lazy(()=>td.array()),autoGeneratedPostcondition:w__default.string().optional()}),zle=Ia.extend({platform:w__default.literal("IOS"),resolvedGoal:w__default.string(),steps:w__default.lazy(()=>nd.array()),autoGeneratedPostcondition:w__default.string().optional()}),I_=w__default.discriminatedUnion("platform",[Vle,zle]),od=Xl.extend({type:w__default.literal("MOBILE_AI_ACTION_STEP"),text:w__default.string(),version:w_.optional(),cache:I_.optional(),precondition:w__default.string().optional(),postcondition:w__default.string().optional()});var qle=w__default.discriminatedUnion("type",[tc,Lm,Ru,Om]),x_=cA.extend({command:qle}),Kle=w__default.discriminatedUnion("type",[tc,Lm,vu,Om]),__=cA.extend({command:Kle}),Yle=w__default.object({assertion:x_,steps:w__default.lazy(()=>Ja.array())}),Jle=w__default.object({assertion:__,steps:w__default.lazy(()=>nc.array())}),Qle=_m.extend({blocks:w__default.lazy(()=>Yle.array()),elseSteps:w__default.lazy(()=>Ja.array()).optional()}),Xle=_m.extend({blocks:w__default.lazy(()=>Jle.array()),elseSteps:w__default.lazy(()=>nc.array()).optional()}),Ja=w__default.discriminatedUnion("type",[td,Hf,od,Qle]),nc=w__default.discriminatedUnion("type",[nd,Hf,od,Xle]);w__default.union([Ja.array(),nc.array()]);var P_=w__default.object({parameterNames:w__default.string().array(),defaultParameters:w__default.record(w__default.string(),w__default.string()).optional(),parameterEnums:w__default.record(w__default.string(),w__default.string().array()).optional()}),dA=w__default.object({moduleId:Ln,name:w__default.string(),description:w__default.string().nullish(),platform:w__default.nativeEnum(Js).optional().default("ANDROID"),parameters:P_.optional(),enabled:w__default.boolean().nullish(),schemaVersion:w__default.string()}),M_=dA.omit({name:true}),Zle=M_.extend({steps:lG.array()});w__default.object({fileType:w__default.literal(we.MOBILE_MODULE)}).merge(Zle);var cG=dA.omit({platform:true,schemaVersion:true});({ANDROID:cG.extend({platform:w__default.literal("ANDROID"),steps:Ja.array()}),IOS:cG.extend({platform:w__default.literal("IOS"),steps:nc.array()})});var Dm=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(Dm||{}),dG=w__default.object({description:w__default.string().optional(),name:w__default.string().describe("name of the module"),parameters:P_.optional()}),uG=km.merge(dG).extend({platform:w__default.literal("ANDROID"),get steps(){return na.array()}}),pG=km.merge(dG).extend({platform:w__default.literal("IOS"),get steps(){return oa.array()}});w__default.discriminatedUnion("platform",[uG,pG]);var O_=Xl.merge(uG).extend({type:w__default.literal("RESOLVED_MOBILE_MODULE")}),N_=Xl.merge(pG).extend({type:w__default.literal("RESOLVED_MOBILE_MODULE")});w__default.discriminatedUnion("platform",[O_,N_]);var ece=w__default.object({assertion:x_,get steps(){return na.array()}}),L_=_m.extend({get blocks(){return ece.array()},get elseSteps(){return na.array().optional()}}),tce=w__default.object({assertion:__,get steps(){return oa.array()}}),k_=_m.extend({get blocks(){return tce.array()},get elseSteps(){return oa.array().optional()}}),na=w__default.discriminatedUnion("type",[O_,td,od,L_]),oa=w__default.discriminatedUnion("type",[N_,nd,od,k_]);function mG(e){return Object.values(Dm).includes(e)||Object.values(Cu).includes(e)}var hG=(i=>(i.PRECONDITION="PRECONDITION",i.REPLAY="REPLAY",i.GENERATE="GENERATE",i.AUTOHEAL="AUTOHEAL",i.POSTCONDITION="POSTCONDITION",i))(hG||{}),gG=z.enum(["pending","running","success","failed"]),fG=z.object({type:z.literal("THOUGHT"),text:z.string(),blockId:z.string().optional()}),yG=z.object({type:z.literal("TOOL_CALL"),toolName:z.string()}),SG=z.object({type:z.literal("PHASE"),phase:z.nativeEnum(hG),failureMessage:z.string().optional()}),nce=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:na,status:gG,message:z.string().optional(),afterSnapshotId:z.string().optional()}),oce=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:oa,status:gG,message:z.string().optional(),afterSnapshotId:z.string().optional()}),bG=z.object({type:z.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z.string()}),rce=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:td.array(),resolvedGoal:z.string()}),ice=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:nd.array(),resolvedGoal:z.string()}),TG=z.discriminatedUnion("type",[fG,yG,SG,nce,rce,bG]),AG=z.discriminatedUnion("type",[fG,yG,SG,oce,ice,bG]);var Qa=w__default.object({message:w__default.string().optional(),startTime:w__default.number(),endTime:w__default.number(),status:w__default.nativeEnum(Mt),trace:w__default.unknown().optional().optional(),beforeSnapshot:w__default.string().optional(),afterSnapshot:w__default.string().optional(),data:w__default.unknown().optional().optional().describe("output data from the step"),aiSuggested:w__default.boolean().optional(),beforeTestContext:Em.optional(),afterTestContext:Em.optional()}),EG=Qa.merge(td).extend({previousAttempts:w__default.lazy(()=>Oi.array()).optional()}),sce=Qa.merge(Hf).extend({steps:w__default.lazy(()=>Oi.array()),name:w__default.string().optional(),previousAttempts:w__default.lazy(()=>Oi.array()).optional()}),ace=Qa.merge(od).extend({steps:w__default.lazy(()=>Oi.array()),previousAttempts:w__default.lazy(()=>Oi.array()).optional(),failureRecoveryReason:w__default.string().optional(),trajectory:TG.array().optional()}),lce=Qa.merge(L_).extend({assertionResult:EG.optional(),steps:w__default.lazy(()=>Oi.array()),previousAttempts:w__default.lazy(()=>Oi.array()).optional()}),Oi=w__default.discriminatedUnion("type",[EG,sce,ace,lce]),CG=Qa.merge(nd).extend({previousAttempts:w__default.lazy(()=>Ni.array()).optional()}),cce=Qa.merge(Hf).extend({steps:w__default.lazy(()=>Ni.array()),name:w__default.string().optional(),previousAttempts:w__default.lazy(()=>Ni.array()).optional()}),dce=Qa.merge(od).extend({steps:w__default.lazy(()=>Ni.array()),previousAttempts:w__default.lazy(()=>Ni.array()).optional(),failureRecoveryReason:w__default.string().optional(),trajectory:AG.array().optional()}),uce=Qa.merge(k_).extend({assertionResult:CG.optional(),steps:w__default.lazy(()=>Ni.array()),previousAttempts:w__default.lazy(()=>Ni.array()).optional()}),Ni=w__default.discriminatedUnion("type",[CG,cce,dce,uce]);var pce=Qa.extend({index:w__default.number().optional(),userFacingStepReference:w__default.string().optional(),description:w__default.string()}),RG=pce.extend({beforeScreenshot:w__default.string().optional(),afterScreenshot:w__default.string().optional()});var vG=z.object({attributesRequired:z.array(z.string()).optional(),textRequired:z.boolean().optional(),boundsRequired:z.boolean().optional(),positionSpecificity:z.enum(li).optional(),shapeSpecificity:z.enum(li).optional()}),mce=z.object({id:z.number(),requirements:vG}).array();z.object({thoughts:z.string(),id:z.number(),updatedMemory:kg.optional(),inWebview:z.boolean().optional(),requirements:vG.optional(),additionalElements:mce.optional()});var hce=z.literal("SCROLL_TO"),wG=z.object({description:z.string(),screenXml:z.string(),screenshot:z.string(),source:hce.optional(),memory:z.discriminatedUnion("type",[Hs,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()}),IG=z.object({assertion:z.string(),screenXml:z.string(),screenshot:z.string(),memory:z.discriminatedUnion("type",[hu,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()});z.object({thoughts:z.string(),result:z.boolean(),relevantElements:z.array(z.number()).optional(),updatedMemory:Dg.optional()});var xG=z.object({failedResults:RG.array(),nextStepsSerialized:z.string().array(),currentScreenXml:z.string(),currentScreenshot:z.string(),customInstructions:z.string().optional(),testDescription:z.string()}),_G=(o=>(o.LEGITIMATE="LEGITIMATE",o.RECOVERABLE="RECOVERABLE",o.INELIGIBLE="INELIGIBLE",o))(_G||{});z.object({thoughts:z.string(),scenario:z.enum(_G),instructions:z.string().nullish(),reasonSummary:z.string().nullish()});z.looseObject({type:z.literal("response.create")});var PG=z.union([z.looseObject({response:z.looseObject({id:z.string()}),sequence_number:z.number(),type:z.literal("response.completed")}),z.looseObject({code:z.string().nullable(),message:z.string(),sequence_number:z.number(),type:z.literal("error")})]);var MG="ui_states.jsonl";z.object({stepId:z.string(),parentStepIdChain:z.array(z.string()),fingerprintHash:z.string(),minhash:z.array(z.number().int()),canonicalUrl:z.string(),capturedAt:z.number().describe("Unix timestamp in milliseconds")});var Fm=(s=>(s.TestRun="test-run",s.MobileTestRun="mobile-test-run",s.CreditsUsed="credits-used",s.CreditsUsedV2="credits-used-v2",s.StepsExecuted="steps-executed",s.LLMTokensUsed="llm-tokens-used",s))(Fm||{}),gce=3;function fce(e){return e==="MODULE"||e==="CONDITIONAL"||e==="SECTION"||e==="RESOLVED_MODULE"}function OG(e){if(!fce(e))switch(e){case "PRESET_ACTION":return 0;case "AI_ACTION":return 3;case "AI_ACTION_DYNAMIC":return 5;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}function NG(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return gce;case "CAPTCHA":return 3;case "CLICK":case "TYPE":case "SELECT_OPTION":case "HOVER":case "ELEMENT_CHECK":case "FOCUS":case "BLUR":case "SCROLL_DOWN":case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_UP":case "MOUSE_DRAG":return e.useSelector||!e.target||e.target.type!=="description"?0:1;case "DRAG":return e.useSelector?0:1;case "VISUAL_DIFF":case "TAB":case "JAVASCRIPT":case "NAVIGATE":case "WAIT":case "SUCCESS":case "AUTH_LOAD":case "AUTH_SAVE":case "COOKIE":case "DIALOG":case "FILE_UPLOAD":case "GO_BACK":case "GO_FORWARD":case "LOCAL_STORAGE":case "NEW_TAB":case "CLOSE_TAB":case "PAGE_CHECK":case "PRESS":case "KEY_DOWN":case "KEY_UP":case "COPY":case "PASTE":case "REFRESH":case "REQUEST":case "GRAPHQL_REQUEST":case "WAIT_FOR_URL":case "REGISTER_REQUEST_LISTENER":case "AWAIT_LISTENER":case "RECORD_REQUESTS":case "GET_RECORDED_REQUESTS":case "SET_HEADER":case "MOCK_ROUTE":case "REMOVE_ROUTE_MOCK":case "OFFLINE_MODE":return 0;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}var D_=z.object({name:z.string(),value:z.string(),url:z.string().optional(),domain:z.string().optional(),path:z.string().optional(),expires:z.number().default(Date.now()/1e3+60*60*24*365),httpOnly:z.boolean().optional(),secure:z.boolean().default(true),sameSite:z.union([z.literal("Strict"),z.literal("Lax"),z.literal("None")]).default("None")});function uA(e,t){let n=[],o=splitCookiesString(e);for(let r of o){let i=parseString(r,{decodeValues:false});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let s;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")s="Strict";else if(d==="lax")s="Lax";else if(d==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=false),!i.path&&i.domain&&(i.path="/"),!i.domain&&t&&(i.domain=t);let a=D_.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:s});n.push(a);let l=[a.name,...Object.keys(a)].map(d=>d.toLowerCase()),c=r.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,p]=d.split("=");if(!u||!p)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||n.push({...a,name:u,value:p});}}return n}var bce=z.object({origin:z.string(),localStorage:z.array(z.object({name:z.string(),value:z.string()})),sessionStorage:z.array(z.object({name:z.string(),value:z.string()})).optional()}),Tce=z.object({entries:z.record(z.string(),z.array(z.tuple([z.unknown().optional(),z.unknown().optional()]))),version:z.number().optional()}),pA=z.object({cookies:D_.array().optional(),origins:bce.array().optional(),idb:z.record(z.string(),Tce).optional().describe("key is db name")});function LG(e,t){let n=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(o=>{let r=D_.safeParse({name:o.key,...o});if(!r.success)return;let i=r.data;!i.domain&&!i.url&&(i.domain=t),n.push(i);}),n}var ui={type:true,cache:true},kG=[tc.pick(ui),Ru.pick(ui),Nf.pick(ui),Df.pick(ui),Mf.pick(ui),_f.pick(ui),wf.pick(ui)],F_=w__default.discriminatedUnion("type",kG),DG=[tc.pick(ui),vu.pick(ui),Lf.pick(ui),Ff.pick(ui),Of.pick(ui),If.pick(ui),Pf.pick(ui)],B_=w__default.discriminatedUnion("type",DG);Object.values(Wt).filter(e=>kG.some(t=>t.shape.type.safeParse(e).success));Object.values(Wt).filter(e=>DG.some(t=>t.shape.type.safeParse(e).success));var U_=w__default.object({type:w__default.literal("MOBILE_AI_ACTION_STEP"),cache:I_}),mA=w__default.union([F_,U_]),hA=w__default.union([B_,U_]);var H_=(s=>(s.US_EAST_1="us-east1",s.US_EAST_2="us-east2",s.US_WEST_1="us-west1",s.US_WEST_2="us-west2",s.EU_NORTH_1="eu-north1",s.AS_SOUTH_1="as-south1",s))(H_||{}),G_=(o=>(o.US="us",o.EU="eu",o.AS="as",o))(G_||{}),FG=(t=>(t.LOCAL="local",t))(FG||{}),j_=w__default.nativeEnum(H_).or(w__default.nativeEnum(G_)),$_=w__default.nativeEnum(H_).or(w__default.nativeEnum(G_)).or(w__default.nativeEnum(FG)),Ece="closest";$_.or(w__default.literal(Ece));var jf=(n=>(n.ANDROID_14="14",n.ANDROID_15="15",n))(jf||{});var V_=(t=>(t.IOS_26="26",t))(V_||{});w.custom().refine(e=>e&&e.length>0).refine(e=>e&&e[0]instanceof File,{message:"Please upload a valid file."});var wo=e=>w.preprocess(t=>t==null?void 0:Array.isArray(t)?t:[t],w.array(e).optional()),Hm=w.string().transform(e=>{let t=e.trim();return t.length===0?void 0:t}).optional();var Cce=w__default.object({disableMomenticAccessibilityTree:w__default.boolean().optional(),autoGrantPermissions:w__default.boolean().optional(),disableXmlSnapshots:w__default.boolean().optional().describe("Skip collecting XML snapshots during test runs. This can speed up test runs, but will cause the run viewer to show less information."),browserSettings:vm.optional()}),Rce="avdId",vce="iosDeviceType",wce="iosVersion",z_=Cce.extend({region:$_.optional().describe("Do you want local or Limbar? Default behavior is Limbar (remote emulators)"),remoteEmulatorSettings:w__default.object({androidVersion:w__default.nativeEnum(jf).optional()}).optional(),localEmulatorSettings:w__default.object({[Rce]:Hm,[vce]:Hm,[wce]:Hm}).optional(),geolocation:w__default.object({latitude:w__default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:w__default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:w__default.boolean().optional().describe("wait for stability before every targeting action")}),$f=w__default.object({retries:w__default.number().optional().describe("number of retries to run"),defaultChannel:w__default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:w__default.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:w__default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:Hm.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:Hm.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:z_.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:Yx.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),BG=w__default.object({id:Ln,description:w__default.string(),schemaVersion:w__default.string(),settings:$f.optional(),disabled:w__default.boolean().optional(),labels:w__default.array(w__default.string()).optional()}),Gm=BG.extend({platform:w__default.literal("ANDROID").optional().default("ANDROID")}),jm=BG.extend({platform:w__default.literal("IOS")}),UG=w__default.discriminatedUnion("platform",[Gm,jm]),HG=w__default.object({fileType:w__default.literal(we.MOBILE_TEST)}),GG=HG.merge(Gm),jG=HG.merge(jm);w__default.discriminatedUnion("platform",[GG,jG]);var $G=Gm.merge(w__default.object({steps:w__default.array(Ja)})),VG=jm.merge(w__default.object({steps:w__default.array(nc)}));w__default.discriminatedUnion("platform",[$G,VG]);var Ice=GG.merge($G),xce=jG.merge(VG);w__default.discriminatedUnion("platform",[Ice,xce]);w__default.object({name:w__default.string(),steps:w__default.array(Ja).optional(),settings:$f.optional()});var zG=Gm.extend({steps:na.array(),beforeSteps:na.array().optional(),afterSteps:na.array().optional()}),WG=jm.extend({steps:oa.array(),beforeSteps:oa.array().optional(),afterSteps:oa.array().optional()});w__default.discriminatedUnion("platform",[zG,WG]);var _ce=zG.extend({name:w__default.string()}),Pce=WG.extend({name:w__default.string()});w__default.discriminatedUnion("platform",[_ce,Pce]);var er=w__default.object({startTime:w__default.number(),endTime:w__default.number().optional(),durationMs:w__default.number().optional(),error:w__default.string().optional(),result:w__default.unknown().optional().optional(),attributes:w__default.record(w__default.string(),w__default.unknown().optional()),subSpans:w__default.lazy(()=>qce.array())});var W_=er.extend({type:w__default.literal("SECTION"),name:w__default.string()}),Mce=er.extend({type:w__default.literal("GET_PAGE_STATE")}),Oce=er.extend({type:w__default.literal("GET_PAGE_SCREENSHOT")}),Nce=er.extend({type:w__default.literal("SMART_WAITING")}),Lce=er.extend({type:w__default.literal("SCROLL_ELEMENT_INTO_VIEW")}),kce=er.extend({type:w__default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:w__default.string().optional(),result:w__default.object({id:w__default.number(),thoughts:w__default.string(),citations:Ao.array().optional()}).optional()}),Dce=er.extend({type:w__default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:w__default.string().optional(),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({thoughts:w__default.string(),result:w__default.boolean(),citations:Ao.array().optional()}).optional()}),Fce=er.extend({type:w__default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:w__default.string().optional(),browserStateSnapshotId:w__default.string().optional(),result:w__default.object({thoughts:w__default.string().optional(),result:w__default.unknown().optional().optional()}).optional()}),Bce=er.extend({type:w__default.literal("ELEMENT_ASSERTION"),name:w__default.string(),result:w__default.object({success:w__default.boolean(),message:w__default.string().optional()}).optional()}),Uce=er.extend({type:w__default.literal("BROWSER_INTERACTION"),name:w__default.string(),coordinates:w__default.object({x:w__default.number(),y:w__default.number()}).optional(),value:w__default.string().optional(),selector:w__default.string().optional()}),Hce=er.extend({type:w__default.literal("CACHE_RESOLUTION"),resolutionMethod:w__default.string().optional(),cacheMissReason:w__default.nativeEnum(Yp).optional(),targetSource:w__default.string().optional(),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({serializedElement:w__default.string()}).optional()}),Gce=er.extend({type:w__default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({serializedElement:w__default.string()}).optional()}),jce=er.extend({type:w__default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:w__default.string().optional(),result:w__default.object({outcome:w__default.string(),logs:w__default.string().array().optional(),serializedElement:w__default.string().optional(),relativeClickPoint:w__default.object({x:w__default.number(),y:w__default.number()}).optional(),force:w__default.boolean().optional()}).optional()}),$ce=er.extend({type:w__default.literal("WAIT_FOR_STABILITY")}),Vce=er.extend({type:w__default.literal("GENERIC"),name:w__default.string()}),zce=er.extend({type:w__default.literal("PAGE_ASSERTION"),name:w__default.string(),result:w__default.object({success:w__default.boolean(),message:w__default.string().optional()}).optional()}),Wce=er.extend({type:w__default.literal("AUTO_FOLLOW_NEW_TABS"),result:w__default.object({followed:w__default.boolean()}).optional()});function qG(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var qce=w__default.discriminatedUnion("type",[W_,Mce,Oce,Nce,Lce,kce,Dce,Fce,Bce,Uce,Gce,Hce,jce,$ce,zce,Vce,Wce]);z.object({testId:z.string(),sessionId:z.string()});var KG=z.object({uploadUrl:z.string(),id:z.string()});new Set(Object.values(Cn));var on={AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of a conditional check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",BLUR:"Remove focus from an element on the page.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",CLOSE_TAB:"Close a specified open tab or current tab if none specified.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock."};z.string().refine(e=>Hh.valid(e),{error:"must be a valid semver string"});function Vf(e){if(e!==void 0)return e===true||e==="true"||e==="1"}function YG(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var gA=55555,fA="momentic-code-eval.js";z.object({body:z.string(),to:z.string(),from:z.string()});z.object({from:z.string().optional(),to:z.string(),timeout:z.number().optional(),beforeDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional()});z.object({timeoutMs:z.number().nonnegative().optional()}).optional();z.object({phoneNumber:z.string(),leaseToken:z.string()});var Jce=z.union([z.string(),z.date()]).transform(e=>e instanceof Date?e:new Date(e)),JG=z.object({phoneNumber:z.string(),expiresAt:Jce,leaseToken:z.string()});z.object({to:z.email(),from:z.string(),subject:z.string(),body:z.string(),html:z.string().optional()});z.object({inbox:z.string().transform(e=>e.toLowerCase()),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),timeout:z.number().optional(),trimWhitespace:z.boolean().optional()});z.object({inbox:z.string(),limit:z.number().optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),trimWhitespace:z.boolean().optional()});var QG=z.object({email:z.string(),prefix:z.string(),expiresAt:z.coerce.date()}),yA=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(yA||{}),XG=z.object({body:z.string().nullish(),status:z.number().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}),Qce=z.object({url:z.string(),options:z.object({method:z.string(),body:z.string().nullish(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),Xce=z.object({body:z.string().nullish(),options:z.object({status:z.number(),statusText:z.string().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),ZG=z.object({result:z.unknown().optional(),variableUpdates:z.record(z.string(),z.unknown().optional()).optional(),persistentVariableUpdates:z.record(z.string(),z.unknown().optional()).optional(),error:z.string().optional(),success:z.boolean()});z.object({id:z.string().optional(),orgId:z.string(),momenticLambdaAuthHash:z.string(),code:z.string(),fragment:z.boolean(),state:z.object({env:z.record(z.string(),z.unknown().optional()),request:Qce,response:Xce,additionalBindings:z.record(z.string(),z.unknown().optional()).optional()}),timeoutMs:z.number().optional(),disallowVariableUpdates:z.boolean().optional(),responseSerialization:z.enum(yA).optional()});var id=9e4;var Zce=w.object({url:w.string(),lineNumber:w.number(),columnNumber:w.number()}),ej=w.object({timestamp:w.number(),text:w.string(),type:w.string(),tabIndex:w.number(),args:w.unknown().optional().array().optional(),url:w.string().optional(),location:Zce.optional()}),tj=ej.array(),q_=tj.array();var zf=class{async getConsoleLogsForRunAttempt(t,n,o){}async getNetworkLogsForRunAttempt(t,n,o){}async getHtmlSnapshot(t,n){}async getA11yTreeSnapshot(t,n){}async getScreenshot(t,n){}async storeConsoleLogsForRunAttempt(t,n,o,r){}async storeNetworkLogsForRunAttempt(t,n,o,r){}listVideoAssetPaths(){return []}close(){}async storeScreenshot(t,n,o){}async storeOnDemandScreenshotById(t,n,o,r){}async storeHtmlSnapshot(t,n,o){}};var ede=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),tde=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),nde=z.object({onContentLoad:z.number().optional(),onLoad:z.number().optional(),comment:z.string().optional()}),Wf=z.object({startedDateTime:z.string(),id:z.string(),title:z.string().optional(),pageTimings:nde,comment:z.string().optional()}),ode=z.array(Wf),rde=z.object({name:z.string(),value:z.string(),path:z.string().optional(),domain:z.string().optional(),expires:z.string().optional(),httpOnly:z.boolean().optional(),secure:z.boolean().optional(),comment:z.string().optional()}),oj=z.array(rde),ide=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),rj=z.array(ide),sde=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),ade=z.array(sde),lde=z.object({name:z.string(),value:z.string().optional(),fileName:z.string().optional(),contentType:z.string().optional(),comment:z.string().optional()}),cde=z.array(lde),dde=z.object({mimeType:z.string(),params:cde,text:z.string(),comment:z.string().optional(),_redactedReason:z.string().optional()}),ude=z.object({method:z.string(),url:z.string(),httpVersion:z.string().optional(),cookies:oj,headers:rj,queryString:ade,postData:dde.optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional()}),pde=z.object({size:z.number().optional(),compression:z.number().optional(),mimeType:z.string().optional(),text:z.string().optional(),encoding:z.string().optional(),comment:z.string().optional(),_redactedReason:z.string().optional()}),mde=z.object({status:z.number(),statusText:z.string(),httpVersion:z.string().optional(),cookies:oj,headers:rj,content:pde,redirectURL:z.string().optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional(),_mocked:z.boolean().optional()}),nj=z.object({expires:z.string().optional(),lastAccess:z.string(),eTag:z.string(),hitCount:z.number(),comment:z.string().optional()}),hde=z.object({beforeRequest:nj.optional(),afterRequest:nj.optional(),comment:z.string().optional()}),gde=z.object({blocked:z.number().optional(),dns:z.number().optional(),connect:z.number().optional(),send:z.number(),wait:z.number(),receive:z.number(),ssl:z.number().optional(),comment:z.string().optional()}),qf=z.object({pageref:z.string().optional(),startedDateTime:z.string(),time:z.number().optional(),request:ude,response:mde.optional(),cache:hde.optional(),timings:gde,serverIPAddress:z.string().optional(),connection:z.string().optional(),comment:z.string().optional(),_resourceType:z.string().optional()}),fde=z.array(qf),yde=z.object({version:z.string().default("1.1"),creator:ede.optional(),browser:tde.optional(),pages:ode.optional(),entries:fde,comment:z.string().optional()});z.object({log:yde});z.record(z.string(),Wf);z.record(z.string(),qf);function K_(e,t){return {log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(e).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime()),entries:Object.values(t).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime())}}}var Y_=(b=>(b.DisableClickhouseCaches="disable_clickhouse_caches",b.ShowZeroOpacityElements="show_zero_opacity_elements",b.VisualActions="visual_actions",b.RagV2="rag_v2",b.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",b.GlobalLocatorRedirect="global_locator_redirect",b.FakerConstantSeed="faker_constant_seed",b.AutoExpandIframes="auto_expand_iframes",b.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",b.PerformanceInsights="performance_insights",b.ShowKnowledgeBase="show_knowledge_base",b.AppGraphBackend="app_graph_backend",b.AppGraphUI="app_graph_ui",b.WebEditorV3="web_editor_v3",b.ClassificationUI="classification_ui",b.HealingUI="healing_ui",b.ExploreUI="explore_ui",b))(Y_||{});var sd=z.union([z.string(),z.number(),z.boolean(),z.null(),z.record(z.string(),z.lazy(()=>sd)),z.array(z.lazy(()=>sd))]),Kf=class{flags;payloads;constructor(t,n){this.flags=t,this.payloads=n;}isBooleanFlagEnabled(t){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="true"?true:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="false"?false:this.flags[t]===true}getAllFlags(){let t=cloneDeep(this.flags);return Object.entries(t).forEach(([n,o])=>{typeof o=="boolean"&&Object.values(Y_).includes(n)&&(t[n]=this.isBooleanFlagEnabled(n));}),t}getFlagPayload(t){let n=this.payloads[t];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}};var Yf={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},ij=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var sj=z.discriminatedUnion("operation",[z.object({operation:z.literal("upsert"),path:z.string().min(1),content:z.string()}),z.object({operation:z.literal("delete"),path:z.string().min(1)})]),Tde=z.object({githubLogin:z.string().optional(),email:z.string().optional()}),Ade=z.object({baseSha:z.string().min(1),headSha:z.string().min(1)}),Ede=z.object({baseBranch:z.string().min(1).max(255),baseCommitSha:z.string().min(1),headBranch:z.string().min(1).max(255).optional(),branchPrefix:z.string().min(1).max(255).optional(),idempotencyKey:z.string().min(1).optional()}),Cde=z.object({commitMessage:z.string().min(1),title:z.string().min(1),body:z.string(),reviewers:z.array(z.string().min(1)).optional(),draft:z.boolean().optional()});Ede.extend(Cde.shape).extend({changes:z.array(sj).min(1),coAuthorRange:Ade.optional()}).superRefine((e,t)=>{e.headBranch||(!e.branchPrefix||!e.idempotencyKey)&&t.addIssue({code:"custom",message:"branchPrefix and idempotencyKey are required when headBranch is omitted",path:["idempotencyKey"]});});var aj=z.object({pullRequestUrl:z.url(),pullRequestNumber:z.number(),headBranch:z.string(),commitSha:z.string(),created:z.boolean(),authors:z.array(Tde).optional()});z.object({branch:z.string().min(1).max(255),commitMessage:z.string().min(1),changes:z.array(sj).min(1)});var lj=z.object({branch:z.string(),commitSha:z.string(),committed:z.boolean()}),cj=z.object({issueNumber:z.number(),htmlUrl:z.url(),headBranch:z.string().min(1),baseBranch:z.string().min(1),latestCommitSha:z.string().min(1),title:z.string().optional(),body:z.string().optional()}),Rde=z.object({path:z.string().min(1),status:z.string().min(1),additions:z.number(),deletions:z.number(),previousPath:z.string().optional(),patch:z.string().optional()}),vde=z.object({sha:z.string().min(1),author:z.string().optional(),email:z.string().optional(),date:z.string().optional(),message:z.string()}),dj=z.object({mergeBaseSha:z.string().min(1),totalCommits:z.number(),commits:z.array(vde),files:z.array(Rde)}),uj=z.object({content:z.string().nullable()}),pj=z.object({name:z.string().min(1),protected:z.boolean()}),mj=z.object({iid:z.number(),webUrl:z.url(),sourceBranch:z.string().min(1),targetBranch:z.string().min(1),latestCommitSha:z.string().min(1)}),wde=z.object({name:z.string(),path:z.string(),body:z.string()}),hj=z.object({template:wde});function Io(e){let[t,n,...o]=e.split("/");if(!(!t||!n||o.length>0))return {owner:t,repo:n}}function gj(e){let t=Io(e);if(t)return t;throw new dt(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var Ide=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,xde=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function SA(e){return e.match(xde)?.[1]}function fj(e){let t=[];for(let n of e.matchAll(Ide)){let o=n[1]?.trim();o&&t.push({email:o,githubLogin:SA(o)});}return t}function _de(e){return (e.githubLogin??(e.email?SA(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function yj(e){return e.filter(t=>!_de(t))}var bA=z.enum(["TERMINOLOGY","AGENT_RULE","FLOW"]),Jf=z.enum(["CANDIDATE","ACTIVE","PENDING_CONFLICT","REJECTED","ARCHIVED"]),J_=z.enum(["MANUAL","CRAWLER","SYSTEM","GENERATED","IMPORTED"]),Pde=z.enum(["PENDING","INDEXING","INDEXED","FAILED"]);var Q_=z.enum(["locator","assertion","visual-assertion","text-extraction","failure-recovery","result-classification","ai-action"]),Qf=z.object({canonicalTerm:z.string().min(1),definition:z.string().min(1),examples:z.array(z.string().min(1)).default([])}),Mde=z.object({agentSubtype:Q_,instruction:z.string().min(1)}),Xf=z.object({intent:z.string().min(1),steps:z.string().min(1),successState:z.string().min(1)}),TA=z.discriminatedUnion("type",[z.object({type:z.literal("TERMINOLOGY"),data:Qf}),z.object({type:z.literal("AGENT_RULE"),data:Mde}),z.object({type:z.literal("FLOW"),data:Xf})]);var Sj=z.discriminatedUnion("source",[z.object({source:z.literal("MANUAL"),userId:z.string().nullable()}),z.object({source:z.literal("CRAWLER"),url:z.url().nullable(),crawlerJobId:z.string().nullable(),snippet:z.string().nullable()}),z.object({source:z.literal("GENERATED"),generatorJobId:z.string().nullable(),agentName:z.string().nullable(),rationale:z.string().nullable(),metadata:z.record(z.string(),z.string()).optional()}),z.object({source:z.literal("SYSTEM"),rule:z.string().nullable()}),z.object({source:z.literal("IMPORTED"),importerSource:z.string().nullable(),externalId:z.string().nullable()})]),X_=z.object({id:z.string(),organizationId:z.string(),appId:z.string().nullable(),testId:z.string().nullable(),environmentId:z.string().nullable(),type:bA,status:Jf,source:J_,trust:z.int().min(0).max(100),title:z.string(),body:z.string(),data:TA,provenance:Sj,contentHash:z.string(),indexingState:Pde,indexedVersion:z.int().nullable(),currentVersion:z.int(),retrievalCount:z.int(),lastRetrievedAt:z.iso.datetime().nullable(),createdByUserId:z.string().nullable(),updatedByUserId:z.string().nullable(),createdAt:z.iso.datetime(),updatedAt:z.iso.datetime()});z.object({id:z.string(),itemId:z.string(),organizationId:z.string(),version:z.int(),title:z.string(),body:z.string(),data:TA,status:Jf,trust:z.int().min(0).max(100),changedByUserId:z.string().nullable(),changedBySystem:z.string().nullable(),changeNote:z.string().nullable(),changedAt:z.iso.datetime()});var Ode=z.object({appId:z.string().nullable().optional(),testId:z.string().nullable().optional(),environmentId:z.string().nullable().optional()});Ode.extend({type:bA,status:Jf.optional(),source:J_,trust:z.int().min(0).max(100).optional(),title:z.string().min(1).max(500),data:TA,provenance:Sj});z.object({title:z.string().min(1).max(500).optional(),data:TA.optional(),status:Jf.optional(),trust:z.int().min(0).max(100).optional(),appId:z.string().nullable().optional(),testId:z.string().nullable().optional(),environmentId:z.string().nullable().optional(),changeNote:z.string().nullable().optional()}).refine(e=>Object.entries(e).some(([t,n])=>t!=="changeNote"&&n!==void 0),{error:"at least one updatable field is required"});z.object({appId:z.string().nullable().optional(),type:wo(bA),status:wo(Jf),source:wo(J_),agentSubtype:wo(Q_),testId:z.string().optional(),environmentId:z.string().optional(),search:z.string().optional(),page:z.coerce.number().int().min(1).prefault(1),pageSize:z.coerce.number().int().min(1).max(200).prefault(50)});var bj=z.enum(["active-only","active-plus-candidates","review"]);z.object({query:z.string().min(1),appId:z.string().nullable().optional(),types:bA.array().min(1).max(3).optional(),agentSubtype:Q_.optional(),testId:z.string().nullable().optional(),environmentId:z.string().nullable().optional(),mode:bj.default("active-only"),limit:z.int().min(1).max(50).default(10),clientName:z.string().min(1).max(100),scoreMultiplier:z.number().positive().max(100).default(1)});var Nde=z.object({combined:z.number(),lexical:z.number().nullable(),vector:z.number().nullable()}),Lde=z.object({item:X_,rank:z.int().min(1),score:Nde,topChunkIndex:z.int().nullable()}),Tj=z.object({hits:z.array(Lde),mode:bj});var Z_=w__default.object({platformSep:w__default.string(),fullPathSegments:w__default.string().array(),relativePathSegments:w__default.string().array(),relativePath:w__default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:w__default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:w__default.coerce.date(),createdAt:w__default.coerce.date()});var kde=z.array(Z_.extend({id:z.string(),name:z.string(),description:z.string().optional(),labels:z.string().array().optional()})),Dde=Z_.extend({id:z.string(),name:z.string(),description:z.string().optional(),content:AT}),Fde=z.array(Dde);z.object({tests:kde,modules:Fde,labels:z.string().array()});z.string().array();var Aj=z.object({pathSegments:z.string().array()});r_.merge(Wn);var Ej=z.object({schemaVersion:z.string(),stepLists:Jc}),Cj=Wn.partial().merge(Tr.pick({id:true})),Zf="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",eP={name:z.string().min(1).max(255).describe(Zf),description:z.string().optional(),baseUrl:z.url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:z.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:z.enum(za).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Jl.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:z.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder. Paths are relative to the project root.")},Rj=z.object(eP);r_.extend(z.object({relativeFilePath:z.string().describe("relative to project root")}).shape);var vj=z.object({name:z.string()});z.object({relativeFilePath:z.string()});var wj=z.object({name:z.string(),sourceModuleContent:AT});z.object({relativeFilePath:z.string()});var Ij=z.object({name:z.string(),description:z.string(),enabled:z.boolean(),steps:z.lazy(()=>Yt.array()),testFilePath:z.string().describe("relative to the project root"),folderPath:z.string().optional().describe("user selected folder path")}),xj=z.object({name:z.string(),description:z.string(),enabled:z.boolean()}).partial(),_j=z.object({folderPath:z.string()}),Pj=z.object({folderPath:z.string()});z.array(TU);var Mj=z.object({defaultEnv:z.string().optional().describe("name of the default env, or undefined to unset")}),Oj=z.object({configFilePath:z.string().describe("full path on disk")});z.string().array();z.object({message:z.string(),newRelativeTestPath:z.string().optional()});var tP=z.object({name:z.string(),absolutePath:z.string(),relativePath:z.string(),pathSegments:z.array(z.string()),isDirectory:z.boolean(),size:z.number(),createdAt:z.coerce.date(),modifiedAt:z.coerce.date(),accessedAt:z.coerce.date()}),Nj=z.object({pathSegments:z.array(z.string())});z.object({absolutePath:z.string(),pathSegments:z.array(z.string()),contents:z.array(tP)});var Lj=z.object({sourceDirectoryPath:z.string().optional(),value:z.string(),allowedExtensions:z.array(z.string()).optional()}),Bde=z.object({name:z.string(),value:z.string(),isDirectory:z.boolean()});z.object({suggestions:z.array(Bde)});var kj=z.object({pathSegments:z.array(z.string())}),Dj=z.object({pathSegments:z.array(z.string()),newPathSegments:z.array(z.string())}),Fj=z.object({pathSegments:z.array(z.string()),recursive:z.boolean().optional()});z.object({success:z.boolean(),message:z.string(),pathSegments:z.array(z.string()).optional()});z.object({gitBranch:z.string(),fileMtime:z.coerce.date(),gitCommitSha:z.string()});var Bj=typeof process<"u"&&true&&true,AA=58889;var Uj=z.object({id:z.string(),createdAt:z.coerce.date(),createdBy:z.string(),organizationId:z.string(),name:z.string(),description:z.string().nullish(),enabled:z.boolean(),schemaVersion:z.string().describe("Schema version for steps"),parameters:z.string().array().nullish().describe("Parameter list"),parameterEnums:z.record(z.string(),z.string().array()).nullish(),defaultParameters:z.record(z.string(),z.string()).nullish(),defaultCacheKey:z.string().nullish(),defaultCacheTtl:z.number().nullish(),defaultCacheAllInvocations:z.boolean().nullish(),autoAuth:z.boolean().nullish(),defaultRetries:z.int().min(0).nullish(),advanced:Rx.nullish()});Uj.extend({steps:z.lazy(()=>_t.array())});var Hj=5*60*1e3,EA=Rn.extend(Uj.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var Ude="org_01HMJTX4GT1KG94KZRCT8MZ6YB",Hde="org_01HMSCJQBCCG51M2ZF65YC5B8W",Gde="org_01JPR6MGFQSHF3W234R3XJDPMB",jde=[Ude,Hde,Gde];function Gj(e){return jde.includes(e)}var jj=(o=>(o.AZURE="AZURE",o.KERNEL="KERNEL",o.BROWSERBASE="BROWSERBASE",o))(jj||{}),nP=z.enum(jj);z.object({azureRegion:z.string().optional(),azureWorkspaceId:z.string().optional()});z.object({});var $de=z.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z.object({region:$de.optional()});var oP=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(oP||{});var Vde=z.object({type:z.literal("DESCRIPTION_UPDATE"),thoughts:z.string()}),CA=z.discriminatedUnion("type",[Vde]),zde=z.object({testId:z.string(),name:z.string(),orgId:z.string(),runId:z.string(),steps:Yt.array(),purpose:z.enum(oP),details:CA.or(CA.array()).optional()});zde.pick({name:true,orgId:true});var Wde=z.object({id:z.string(),name:z.string().nullish(),createdAt:z.string().pipe(z.coerce.date()).or(z.date()),organizationId:z.string(),schemaVersion:z.string(),runId:z.string().nullish(),purpose:z.enum(oP),details:CA.or(CA.array()).optional(),applied:z.boolean().nullish(),appliedAt:z.coerce.date().nullish()}),$j=Wde.extend({steps:Yt.array()});var Vj=z.enum(["v1","v2"]);var Kde=z.enum(["element","content","attribute","tag_name","style"]),RA=z.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...MB,...PB].forEach(e=>{if(!RA.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var rP={element:{aliasPrefix:"",assertionType:"ELEMENT_EXISTENCE",requiresName:false},content:{aliasPrefix:"Content",assertionType:"ELEMENT_CONTENT",requiresName:false},attribute:{aliasPrefix:"Attribute",assertionType:"ELEMENT_ATTRIBUTE",requiresName:true},tag_name:{aliasPrefix:"Name",assertionType:"ELEMENT_NAME",requiresName:false},style:{aliasPrefix:"Style",assertionType:"ELEMENT_STYLE",requiresName:true}},qj={exists:{positiveAliasSuffix:"Exists",negativeAliasSuffix:"DoesNotExist",elementCondition:"EXISTS",contentOperation:"EXISTS"},visible:{positiveAliasSuffix:"Visible",negativeAliasSuffix:"NotVisible",elementCondition:"VISIBLE"},enabled:{positiveAliasSuffix:"Enabled",negativeAliasSuffix:"NotEnabled",elementCondition:"ENABLED"},editable:{positiveAliasSuffix:"Editable",negativeAliasSuffix:"NotEditable",elementCondition:"EDITABLE"},focused:{positiveAliasSuffix:"Focused",negativeAliasSuffix:"NotFocused",elementCondition:"FOCUSED"},contains:{positiveAliasSuffix:"Contains",negativeAliasSuffix:"DoesNotContain",contentOperation:"CONTAINS"},equals:{positiveAliasSuffix:"Equals",negativeAliasSuffix:"DoesNotEqual",contentOperation:"EQUALS"},starts_with:{positiveAliasSuffix:"StartsWith",negativeAliasSuffix:"DoesNotStartWith",contentOperation:"STARTS_WITH"}},Kj={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function zj(e){return {alias:iP(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:rP[e.subject].assertionType,requiresName:rP[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function iP(e){let t=rP[e.subject],n=qj[e.condition];if(!Yj(e.subject,e.condition))throw new Error(`Unsupported element check alias for subject '${e.subject}' and condition '${e.condition}'.`);let o=e.negated?n.negativeAliasSuffix:n.positiveAliasSuffix;return `checkElement${t.aliasPrefix}${o}`}function Yj(e,t){let n=qj[t],o=n.elementCondition,r=n.contentOperation;return e==="element"?o!==void 0:r!==void 0}var Yde=Kde.options.flatMap(e=>RA.options.flatMap(t=>Yj(e,t)?[zj({subject:e,condition:t,negated:false}),zj({subject:e,condition:t,negated:true})]:[])),Jj=new Map(Yde.map(e=>[e.alias,e]));var Jde=z.enum(Na),Qde=z.enum(vi);function qr(e){return Jj.get(e)}function Xj(e){let t=Kj[e.type],n=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return iP({subject:t,condition:Xde(n),negated:e.negated})}function Zj(e){return Jde.parse(e.toUpperCase())}function ey(e){return Qde.parse(e.toUpperCase())}function Xde(e){return RA.parse(e.toLowerCase())}var Ke={saveAs:z.string().optional(),retries:z.number().optional(),skipped:z.boolean().optional(),comment:z.string().optional()};z.object(Ke);var vA=Object.keys(Ke);function Ge(e){return z.union([z.strictObject({[e.key]:e.simplified}),z.strictObject({[e.key]:e.detailed})])}function Tn(e){return z.strictObject({[e.key]:e.detailed})}var e$='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Vm=z.union([Pa,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,e$)],{error:e$});z.union([z.string(),Pa]);var Di={css:z.string().optional(),coords:Vm.optional(),x:z.union([z.number(),z.string()]).optional(),y:z.union([z.number(),z.string()]).optional()},aP={on:z.string().optional(),...Di},Fi={...Ke,useSelector:z.boolean().optional(),force:z.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional()},ty={...Fi,offset:Vm.optional()};function Kr({schema:e,descriptionKey:t,required:n=true}){return e.superRefine((o,r)=>{let s=[t in o?Object.entries(o).find(([a])=>a===t)?.[1]:void 0,"css"in o?o.css:void 0,"coords"in o?o.coords:void 0,"x"in o||"y"in o?true:void 0].filter(a=>a!==void 0).length;n&&s!==1&&r.addIssue({code:"custom",message:`Use exactly one target: ${t}, css, coords, or x/y.`}),!n&&s>1&&r.addIssue({code:"custom",message:`Use at most one target: ${t}, css, coords, or x/y.`}),("x"in o||"y"in o)&&(!("x"in o)||o.x===void 0||!("y"in o)||o.y===void 0)&&r.addIssue({code:"custom",message:"x and y must be provided together."});})}var Zde=Kr({descriptionKey:"on",schema:z.strictObject({...aP,...ty,times:z.int().min(1).optional(),rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),eue=Kr({descriptionKey:"on",schema:z.strictObject({...aP,...ty,rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),tue=Kr({descriptionKey:"on",schema:z.strictObject({...aP,...ty,times:z.int().min(1).optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),t$=Ge({key:"click",simplified:z.string(),detailed:Zde}),n$=Ge({key:"doubleClick",simplified:z.string(),detailed:eue}),o$=Ge({key:"rightClick",simplified:z.string(),detailed:tue}),nue=Kr({descriptionKey:"into",required:false,schema:z.strictObject({text:z.string(),into:z.string().optional(),...Di,...ty,pressEnter:z.boolean().optional(),clear:z.union([z.literal("inputs"),z.literal("always"),z.literal("never"),z.boolean()]).optional(),delay:z.number().optional()})}),r$=Ge({key:"type",simplified:z.string(),detailed:nue}),i$=Tn({key:"select",detailed:Kr({descriptionKey:"from",schema:z.strictObject({from:z.string().optional(),...Di,label:z.string().optional(),value:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),...Fi})}).superRefine((e,t)=>{[e.label,e.value,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"select requires exactly one of label, value, or index"});})}),s$=Ge({key:"hover",simplified:z.string(),detailed:Kr({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Di,...ty})})}),a$=Tn({key:"blur",detailed:Kr({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Di,...Fi})})}),l$=Ge({key:"focus",simplified:z.string(),detailed:Kr({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Di,...Fi})})}),c$=Tn({key:"dragAndDrop",detailed:z.strictObject({from:z.string().optional(),to:z.string().optional(),fromCss:z.string().optional(),toCss:z.string().optional(),fromCoords:Vm.optional(),toCoords:Vm.optional(),fromX:z.union([z.number(),z.string()]).optional(),fromY:z.union([z.number(),z.string()]).optional(),toX:z.union([z.number(),z.string()]).optional(),toY:z.union([z.number(),z.string()]).optional(),steps:z.number().optional(),hover:z.number().optional(),...Fi}).superRefine((e,t)=>{let n=[e.from,e.fromCss,e.fromCoords,e.fromX!==void 0||e.fromY!==void 0?true:void 0].filter(r=>r!==void 0).length,o=[e.to,e.toCss,e.toCoords,e.toX!==void 0||e.toY!==void 0?true:void 0].filter(r=>r!==void 0).length;n!==1&&t.addIssue({code:"custom",message:"Use exactly one from target."}),o!==1&&t.addIssue({code:"custom",message:"Use exactly one to target."}),(e.fromX!==void 0||e.fromY!==void 0)&&(e.fromX===void 0||e.fromY===void 0)&&t.addIssue({code:"custom",message:"fromX and fromY must be provided together."}),(e.toX!==void 0||e.toY!==void 0)&&(e.toX===void 0||e.toY===void 0)&&t.addIssue({code:"custom",message:"toX and toY must be provided together."});})}),d$=z.union([z.strictObject({mouseDrag:Vm}),z.strictObject({mouseDrag:Kr({descriptionKey:"from",required:false,schema:z.strictObject({from:z.string().optional(),...Di,delta:Vm,steps:z.number().optional(),...Fi})})})]),u$=Ge({key:"press",simplified:z.string(),detailed:z.strictObject({key:z.string(),repeat:z.number().optional(),delay:z.number().optional(),convertMeta:z.boolean().optional(),...Ke})}),p$=Ge({key:"keyDown",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Ke})}),m$=Ge({key:"keyUp",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Ke})}),h$=Ge({key:"navigate",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:z.number().optional(),...Ke})}),g$=Ge({key:"newTab",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:z.number().optional(),...Ke})}),f$=Ge({key:"switchTab",simplified:z.union([z.number(),z.string()]),detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"switchTab requires exactly one of substring, regex, or index"});})}),y$=Tn({key:"closeTab",detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length<=1||t.addIssue({code:"custom",message:"closeTab accepts at most one of substring, regex, or index"});})}),S$=Tn({key:"goBack",detailed:z.strictObject(Ke)}),b$=Tn({key:"goForward",detailed:z.strictObject(Ke)}),T$=Tn({key:"refresh",detailed:z.strictObject({timeout:z.number().optional(),...Ke})}),wA=z.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),A$=Ge({key:"scrollUp",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),E$=Ge({key:"scrollDown",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),C$=Ge({key:"scrollLeft",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),R$=Ge({key:"scrollRight",simplified:z.number().nonnegative(),detailed:Kr({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Di,...Fi})})}),v$=Ge({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...Ke})}),oue=Ge({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Ke})}),rue=Ge({key:"assertVisually",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Ke})}),IA=oue,xA=rue,w$=Ge({key:"checkPageContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Ke})}),I$=Ge({key:"checkPageDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Ke})}),lP=z.union([w$,I$]),iue=z.record(z.string(),z.unknown().optional()),_A=iue.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qr(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=Kr({descriptionKey:"element",schema:z.looseObject({element:z.string().optional(),...Di,...Fi,timeout:z.number().optional(),name:z.string().optional(),value:z.string().optional()})}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),x$=Ge({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:sd.optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),...Ke})}),_$=Ge({key:"cookie",simplified:z.string(),detailed:z.strictObject({value:z.string(),...Ke})}),P$=Tn({key:"localStorage",detailed:z.strictObject({key:z.string(),value:z.string(),...Ke})}),M$=Ge({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:jl.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:sd.optional(),contentType:z.enum(La).optional(),timeout:z.number().optional(),...Ke})}),O$=Tn({key:"graphqlRequest",detailed:z.strictObject({url:z.string(),query:z.string(),variables:sd.optional(),headers:z.record(z.string(),z.string()).optional(),timeout:z.number().optional(),...Ke})}),PA=Ge({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),environment:z.enum(["node","browser","NODE","BROWSER"]).optional(),fragment:z.boolean().optional(),timeout:z.number().optional(),...Ke})}),zm={substring:z.string().optional(),glob:z.string().optional(),regex:z.string().optional(),domain:z.string().optional()};function sue(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Wm(e){let t=sue(e.payload);if(e.required&&t!==1||!e.required&&t>1){e.ctx.addIssue({code:"custom",message:e.required?"requires exactly one of substring, glob, regex, or domain":"requires at most one of substring, glob, regex, or domain"});return}!e.required&&t===0&&e.payload.method&&e.ctx.addIssue({code:"custom",message:"method requires a URL matcher"});}var N$=Tn({key:"header",detailed:z.strictObject({name:z.string(),value:z.string(),...zm,method:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:false});})}),L$=Tn({key:"mock",detailed:z.strictObject({...zm,method:z.string().optional(),responseGenerator:z.string(),fetchOriginalResponse:z.boolean().optional(),key:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),k$=Ge({key:"removeRouteMock",simplified:z.string(),detailed:z.strictObject({key:z.string(),...Ke})}),D$=Ge({key:"waitForUrl",simplified:z.string(),detailed:z.strictObject({...zm,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),F$=Ge({key:"waitForUrlNotToMatch",simplified:z.string(),detailed:z.strictObject({...zm,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),aue=z.union([D$,F$]),B$=Ge({key:"dialog",simplified:z.enum(["ACCEPT","DISMISS"]),detailed:z.strictObject({action:z.enum(["ACCEPT","DISMISS"]),...Ke})}),U$=Ge({key:"fileUpload",simplified:z.string(),detailed:z.strictObject({path:z.string(),name:z.string().optional(),...Ke})}),H$=Ge({key:"copy",simplified:z.union([z.string(),z.boolean(),z.null()]),detailed:z.strictObject({value:z.union([z.string(),z.boolean(),z.null()]),...Ke})}),G$=Tn({key:"paste",detailed:z.strictObject(Ke)}),j$=Tn({key:"captcha",detailed:z.strictObject({...Fi})}),lue=z.strictObject({data:z.union([z.string(),Us]),width:z.number(),height:z.number()}),$$=Ge({key:"visualDiff",simplified:z.string(),detailed:Kr({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Di,threshold:z.number().optional(),screenshot:lue.optional(),...Fi})})}),V$=Tn({key:"offline",detailed:z.strictObject(Ke)}),z$=Tn({key:"online",detailed:z.strictObject(Ke)}),W$=Tn({key:"registerRequestListener",detailed:z.strictObject({...zm,key:z.string(),method:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),q$=Ge({key:"awaitListener",simplified:z.string(),detailed:z.strictObject({key:z.string(),timeout:z.number().optional(),...Ke})}),K$=Tn({key:"recordRequests",detailed:z.strictObject({...zm,key:z.string(),method:z.string().optional(),...Ke}).superRefine((e,t)=>{Wm({payload:e,ctx:t,required:true});})}),Y$=Ge({key:"getRecordedRequests",simplified:z.string(),detailed:z.strictObject({key:z.string(),...Ke})}),J$=Ge({key:"authLoad",simplified:z.string(),detailed:z.strictObject({path:z.string(),...Ke})}),Q$=Ge({key:"authSave",simplified:z.string(),detailed:z.strictObject({path:z.string().optional(),...Ke})});z.union([t$,n$,o$,f$,y$,r$,i$,s$,a$,l$,c$,d$,u$,p$,m$,h$,g$,S$,b$,T$,A$,E$,C$,R$,v$,IA,xA,lP,x$,_$,P$,M$,O$,PA,N$,L$,k$,aue,B$,U$,H$,G$,j$,$$,V$,z$,W$,q$,K$,Y$,J$,Q$,_A]);var X$=new Map([["click",t$],["doubleClick",n$],["rightClick",o$],["switchTab",f$],["closeTab",y$],["type",r$],["select",i$],["hover",s$],["blur",a$],["focus",l$],["dragAndDrop",c$],["mouseDrag",d$],["press",u$],["keyDown",p$],["keyUp",m$],["navigate",h$],["newTab",g$],["goBack",S$],["goForward",b$],["refresh",T$],["scrollUp",A$],["scrollDown",E$],["scrollLeft",C$],["scrollRight",R$],["wait",v$],["assert",IA],["assertVisually",xA],["checkPageContains",w$],["checkPageDoesNotContain",I$],["extract",x$],["cookie",_$],["localStorage",P$],["request",M$],["graphqlRequest",O$],["javascript",PA],["header",N$],["mock",L$],["removeRouteMock",k$],["waitForUrl",D$],["waitForUrlNotToMatch",F$],["dialog",B$],["fileUpload",U$],["copy",H$],["paste",G$],["captcha",j$],["visualDiff",$$],["offline",V$],["online",z$],["registerRequestListener",W$],["awaitListener",q$],["recordRequests",K$],["getRecordedRequests",Y$],["authLoad",J$],["authSave",Q$]]),Z$=Object.freeze([...X$.keys()]),Za=z.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"Steps must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"Steps must have exactly one action key."});return}let r=X$.get(o)??(qr(o)?_A:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported step type '${o}'.`});return}let i=r.safeParse(e);if(!i.success){let s=cue(i.error.issues,o);s.length>0&&eV(t,s);}});function cue(e,t){return due(e).filter(n=>!uue(n,t))}function eV(e,t){for(let n of t){if(n.code==="invalid_union"){eV(e,cP(n));continue}e.addIssue({...n});}}function due(e){let t=[];for(let n of e){if(n.code==="invalid_union"){t.push(...cP(n));continue}t.push(n);}return t}function uue(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function cP(e){let t=e.errors[0]??[],n=sP(t);for(let o of e.errors.slice(1)){let r=sP(o);r>n&&(t=o,n=r);}return t}function sP(e){return e.reduce((t,n)=>{let o=n.code==="invalid_union"?sP(cP(n)):0;return t+n.path.length+o},0)}var tV=z.strictObject({string:z.string()}),pue=z.strictObject({javascript:z.string()}),nV=z.union([tV,pue]),mue=z.union([z.strictObject({name:z.string(),required:z.boolean().optional(),default:tV.optional()}),z.strictObject({name:z.string(),required:z.boolean().optional(),defaultValue:z.string()})]),oV=mue.array(),hue=z.strictObject({name:z.string(),default:nV.optional(),enum:z.array(z.string()).optional()}),rV=hue.array(),ny=z.union([nV,z.string()]),iV=z.record(z.string(),ny);var gue=z.preprocess(e=>typeof e=="number"?String(e):e,dx),MA=z.looseObject({goal:z.string(),version:gue.optional(),...Ke}),fue=z.union([z.strictObject({act:z.string()}),z.strictObject({act:MA})]),dP=z.looseObject({path:z.string(),inputs:z.record(z.string(),ny).optional(),...Ke}),yue=z.union([z.strictObject({module:z.string()}),z.strictObject({module:dP})]),qm=z.union([IA,xA,lP,PA,_A]),Sue=new Set(["then",...vA]),bue=z.looseObject({then:z.lazy(()=>el.array()),...Ke}).superRefine((e,t)=>{Object.entries(e).filter(([o,r])=>!Sue.has(o)&&qm.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),Tue=z.strictObject({if:bue}),el=z.lazy(()=>z.union([wA,fue,yue,Tue,Za]));z.object({before:el.array().optional(),steps:el.array(),after:el.array().optional()});var Aue=z.union([Jl,z.string().refine(e=>{let t=e.match(/^\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*$/);if(!t)return false;let[,n,o]=t;return Jl.safeParse({width:Number(n),height:Number(o)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),Eue=_i.omit({viewport:true}).extend({viewport:Aue.optional()}),uP=z.object({id:Ln,version:z.string(),url:CT.optional(),description:z.string().optional(),retries:z.number().optional(),defaultEnv:z.string().optional(),parameters:oV.optional(),outputs:WT.optional(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional()}).extend(Eue.shape),ld=z.looseObject({fileType:z.literal(we.TEST_V2)}).extend(uP.shape).extend({before:el.array().optional(),steps:el.array(),after:el.array().optional()});var Cue=z.array(z.string()),Rue=z.union([z.string(),z.record(z.string(),z.unknown().optional())]),OA=Rn.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:Ln,version:z.string(),name:z.string().optional(),parameters:z.union([rV,Cue]).optional(),defaultParameters:z.record(z.string(),z.string()).optional(),parameterEnums:z.record(z.string(),z.array(z.string())).optional()}),pP=z.looseObject(OA.extend({fileType:z.literal(we.MODULE_V2),steps:Rue.array().optional()}).shape).superRefine(aV),NA=z.looseObject(OA.extend({fileType:z.literal(we.MODULE_V2),steps:el.array().optional()}).shape).superRefine(aV);function sV(e){return e.steps??[]}function aV(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var mP=(n=>(n.TEST="TEST",n.MODULE="MODULE",n))(mP||{}),vue=z.enum(mP),lV=z.object({orgId:z.string(),entityType:vue,entityId:z.string()}),hP=lV.extend({entityType:z.literal("TEST"),stepLists:Gs}),gP=lV.extend({entityType:z.literal("MODULE"),steps:_t.array()});z.discriminatedUnion("entityType",[hP,gP]);var cV=(o=>(o.WEB="web",o.ANDROID="android",o.IOS="ios",o))(cV||{}),fP=z.nativeEnum(cV);var dV=z.object({entity_type:z.string(),value:z.string()}),uV=Yg(dV),pV=dV.extend({cache_key:z.string()});function ry({entityType:e,entityId:t}){return `${e}:${t}`}var Pu=z.string();var mV='Coordinates must be "x, y" pixel values, e.g. "100, 200"',yV=z.union([Pa,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,mV)],{error:mV}),hV='Percent must be a number or a percent string, e.g. 90 or "90%"',SV=z.union([z.number(),z.string().regex(/^-?\d+(?:\.\d+)?%$/,hV)],{error:hV}).transform(e=>typeof e=="number"?e:Number(e.slice(0,-1))).pipe(z.number().min(0,{message:"Percent must be >= 0"}).max(100,{message:"Percent must be <= 100"})),wue=z.strictObject({x:z.number(),y:z.number(),delta:z.number()}),bV=z.union([z.string(),wue]),gn={...Ke,DANGEROUS_FORCE_DYNAMIC:z.boolean().optional()},Iue=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],xue=["enter","backspace","close_keyboard"],gV=["airplane_mode","data","wifi","location"],fV=["portrait","landscape"],_ue=z.strictObject({on:Pu.optional(),longPress:z.boolean().optional(),longPressDuration:z.number().optional(),iterations:z.number().optional(),tapDelay:z.number().optional(),offset:yV.optional(),...gn}),TV=Ge({key:"tap",simplified:Pu,detailed:_ue}),Pue=z.strictObject({text:z.string(),into:Pu.optional(),clearContent:z.boolean().optional(),forceClearContent:z.boolean().optional(),keyPressDelay:z.number().optional(),...gn}),AV=Ge({key:"type",simplified:z.string(),detailed:Pue}),EV=z.enum(Iue),Mue=z.strictObject({key:EV,longPress:z.boolean().optional(),...gn}),CV=Ge({key:"press",simplified:EV,detailed:Mue}),RV=z.enum(xue),Oue=z.strictObject({key:RV,...gn}),vV=Ge({key:"pressKey",simplified:RV,detailed:Oue}),Nue=z.strictObject({package:z.string(),activity:z.string().optional(),intentExtras:z.string().optional(),...gn}),wV=Ge({key:"openApp",simplified:z.string(),detailed:Nue}),IV=Tn({key:"killApp",detailed:z.strictObject(gn)}),xV=Tn({key:"openNotifications",detailed:z.strictObject(gn)}),_V=z.enum(["up","down","left","right"]),Lue=z.strictObject({direction:_V,in:bV.optional(),viewportPercent:SV.optional(),duration:z.number().optional(),offset:yV.optional(),...gn}),PV=Ge({key:"swipe",simplified:_V,detailed:Lue}),kue=z.enum(["up","down"]),Due=z.strictObject({on:Pu,direction:kue.optional(),in:bV.optional(),scrollStepPercent:SV.optional(),maxScrollAttempts:z.number().optional(),...gn}),MV=Ge({key:"scrollTo",simplified:z.string(),detailed:Due}),yP=Ge({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),...gn})}),OV=Ge({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:sd.optional(),...gn})}),NV=Ge({key:"checkScreenContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...gn})}),LV=Ge({key:"checkScreenDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...gn})}),kV=z.union([NV,LV]),Fue=z.record(z.string(),z.unknown().optional()),SP=Fue.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qr(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=z.looseObject({on:Pu.optional(),timeout:z.number().optional(),name:z.string().optional(),value:z.string().optional(),...gn}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}i.data.on===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a target via 'on'`,path:[r.alias,"on"]}),r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),Bue=z.strictObject({from:Pu,to:Pu,hoverDuration:z.number().optional(),dragDuration:z.number().optional(),...gn}),DV=Tn({key:"dragAndDrop",detailed:Bue}),bP=Ge({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),timeout:z.number().optional(),...gn})}),FV=Ge({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:jl.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:z.string().optional(),bodyType:z.nativeEnum(La).optional(),timeout:z.number().optional(),...gn})}),BV=Ge({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...gn})}),UV=Tn({key:"addFile",detailed:z.strictObject({path:z.string(),location:z.string(),...gn})}),HV=Ge({key:"installApp",simplified:z.string(),detailed:z.strictObject({path:z.string(),...gn})}),GV=Ge({key:"uninstallApp",simplified:z.string(),detailed:z.strictObject({package:z.string(),...gn})}),jV=Ge({key:"toggleSettings",simplified:z.enum(gV),detailed:z.strictObject({setting:z.enum(gV),...gn})}),$V=Ge({key:"rotate",simplified:z.enum(fV),detailed:z.strictObject({orientation:z.enum(fV),...gn})}),VV=Ge({key:"adb",simplified:z.string(),detailed:z.strictObject({command:z.string(),args:z.string().optional(),...gn})}),zV=Tn({key:"appium",detailed:z.strictObject({script:z.string(),args:z.string().optional(),...gn})}),WV=Tn({key:"debugState",detailed:z.strictObject(gn)}),qV=z.enum(["killApp","openNotifications","debugState"]);z.union([TV,AV,CV,vV,wV,IV,xV,PV,MV,yP,OV,kV,DV,bP,FV,BV,UV,HV,GV,jV,$V,VV,zV,WV,SP]);var KV=new Map([["tap",TV],["type",AV],["press",CV],["pressKey",vV],["openApp",wV],["killApp",IV],["openNotifications",xV],["swipe",PV],["scrollTo",MV],["assert",yP],["extract",OV],["checkScreenContains",NV],["checkScreenDoesNotContain",LV],["dragAndDrop",DV],["javascript",bP],["request",FV],["wait",BV],["addFile",UV],["installApp",HV],["uninstallApp",GV],["toggleSettings",jV],["rotate",$V],["adb",VV],["appium",zV],["debugState",WV]]);Object.freeze([...KV.keys()]);var YV=z.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"v2 mobile commands must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"v2 mobile commands must have exactly one action key."});return}let r=KV.get(o)??(qr(o)?SP:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported v2 mobile command '${o}'.`});return}let i=r.safeParse(e);if(!i.success)for(let s of i.error.issues)t.addIssue({...s});}),JV=z.union([yP,kV,bP,SP]);var Uue=z.preprocess(e=>typeof e=="number"?String(e):e,w_),Hue=z.looseObject({goal:z.string(),version:Uue.optional(),precondition:z.string().optional(),postcondition:z.string().optional(),...Ke}),Gue=z.union([z.strictObject({act:z.string()}),z.strictObject({act:Hue})]),jue=z.looseObject({path:z.string(),inputs:z.record(z.string(),ny).optional(),...Ke}),$ue=z.union([z.strictObject({module:z.string()}),z.strictObject({module:jue})]),Vue=new Set(["then",...vA]),zue=z.looseObject({then:z.lazy(()=>tl.array()),...Ke}).superRefine((e,t)=>{if("else"in e){t.addIssue({code:"custom",message:"v2 mobile conditionals do not support 'else'. Use a separate step instead.",path:["else"]});return}Object.entries(e).filter(([o,r])=>!Vue.has(o)&&JV.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),Wue=z.strictObject({if:zue}),tl=z.lazy(()=>z.union([qV,Gue,$ue,Wue,YV]));z.object({before:tl.array().optional(),steps:tl.array(),after:tl.array().optional()});var TP=["android","ios"],que=z.literal("android"),Kue=z.literal("ios");z.enum(TP);function LA(e){if(typeof e!="object"||e===null)return e;let t=e;if(typeof t.platform!="string")return e;let n=t.platform.toLowerCase();return n===t.platform?e:{...t,platform:n}}var QV=Gm.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string(),platform:que,...$f.shape}),XV=jm.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string(),platform:Kue,...$f.shape}),Yue=z.discriminatedUnion("platform",[QV,XV]),ZV=z.preprocess(LA,Yue),ez={before:tl.array().optional(),steps:tl.array(),after:tl.array().optional()},tz=z.looseObject({fileType:z.literal(we.MOBILE_TEST_V2)}).extend(QV.shape).extend(ez);z.preprocess(LA,tz);var nz=z.looseObject({fileType:z.literal(we.MOBILE_TEST_V2)}).extend(XV.shape).extend(ez);z.preprocess(LA,nz);var Jue=z.discriminatedUnion("platform",[tz,nz]);z.preprocess(LA,Jue);var Que=z.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z.enum(TP).optional().default("android")),kA=dA.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:Ln,name:z.string().optional(),version:z.string(),platform:Que});z.looseObject(kA.extend({fileType:z.literal(we.MOBILE_MODULE_V2),steps:z.array(z.record(z.string(),z.unknown().optional())).optional()}).shape);z.looseObject(kA.extend({fileType:z.literal(we.MOBILE_MODULE_V2),steps:tl.array().optional()}).shape);var DA="x-momentic-cli-version",rz="x-momentic-client-mode",iz="x-momentic-cli-type",sz="x-momentic-logger-tags",Xue="x-momentic-main-branch-name",Zue="x-momentic-branch-name",epe="x-momentic-commit-timestamp",tpe="x-momentic-last-commit-on-main",npe="x-momentic-last-commit-on-main-timestamp",ope="x-momentic-merged-branch-name",az="x-momentic-session-id";w.object({error:w.boolean(),reason:w.string(),message:w.string()});vo.merge(o_);var lz=rT;vo.merge(o_);vo.merge(gH).extend({useConsensus:w.boolean().optional(),attemptNumber:w.number().optional()});var AP=_B;vo.merge(fH);var cz=oU;vo.merge(uH);var dz=PT;vo.merge(CB);vo.merge(pH);var uz=eU;vo.merge(mH);vo.merge(hH);vo.merge(TH);vo.merge(AH);w.object({testPaths:w.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:w.string().optional(),all:w.boolean().optional(),urlOverride:w.string().optional(),customHeaders:w.record(w.string(),w.string()).optional(),testInputMatrix:w.record(w.string(),w.string()).array().optional()});var pz=w.object({queuedTests:w.unknown().optional().array(),runIds:w.guid().array(),runGroupId:w.string().optional()});w.string().array();w.union([w.object({paths:w.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:w.boolean().describe("run all tests").optional()}),w.object({path:w.string().describe("deprecated; present for backcompat")})]);var rpe=w.object({tests:w.record(w.string().describe("Test name (keys correspond to entries in `tests`)"),w.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:w.record(w.string().describe("Module name (keys correspond to entries in `modules`)"),w.string().describe("Slash-separated folder name path that the module lives in."))}),mz=w.object({tests:w.record(w.string().describe("Test name"),w.string().describe("Test YAML")),modules:w.record(w.string().describe("Module name"),w.string().describe("Module YAML")),folderPaths:rpe.optional().describe("Optional map from exported entity name to its slash-separated cloud folder path. Used by the CLI to recreate folder structure on disk.")}),ipe=w.object({test:w.string().describe("test YAML"),modules:w.record(w.string().describe("moduleId"),w.string().describe("module YAML"))});ipe.array();w.object({testId:w.string(),schemaVersion:w.string()}).merge(Wl);function FA(e){let{gitMainBranch:t,gitBranchName:n,gitCommitTimestamp:o,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,s={};return t&&(s[Xue]=encodeURIComponent(t)),n&&(s[Zue]=encodeURIComponent(n)),o&&(s[epe]=o.toISOString()),r&&(s[tpe]=encodeURIComponent(r)),i&&(s[npe]=i.toISOString()),e.mergedGitBranchName&&(s[ope]=encodeURIComponent(e.mergedGitBranchName)),s}w.object({entries:w.array(f0)});w.object({platform:fP.optional(),entries:w.array(uV)});w.object({testId:w.string(),environment:w.string().optional(),platform:fP.optional()});w.object({testId:w.string(),key:w.string(),environment:w.string().optional()});function hz(e){return w.record(w.string(),w.unknown().optional()).transform(t=>{let n={};for(let[o,r]of Object.entries(t)){let i=e.safeParse(r);i.success&&(n[o]=i.data);}return n})}var gz=hz(y0),fz=pV.array();function oz(e){return hz(Jg(e))}var yz={ANDROID:e=>oz(mA).parse(e),IOS:e=>oz(hA).parse(e)},spe=w.object({id:w.string(),completionType:w.string(),description:w.string().optional(),thoughts:w.string(),result:w.string(),sessionType:w.string(),timeCreated:w.string().optional(),citations:w.array(Ao).optional()}),ape=w.object({id:w.string(),assertion:w.string().optional(),result:w.string(),thoughts:w.string(),sessionType:w.string(),timeCreated:w.string().optional(),citations:w.array(Ao).optional()});w.object({completionType:w.string(),traceIds:w.string().array()});var EP=w.union([spe,ape]).array(),Sz=w.object({trigger:w.nativeEnum(Pi),status:w.nativeEnum(Gt),startedAt:w.coerce.date().optional(),gitCommitSha:w.string().optional(),gitCommitShaShort:w.string().optional(),gitCommitTimestamp:w.coerce.date().optional(),gitBranchName:w.string().optional(),gitOriginUrl:w.string().optional(),gitCommitMessage:w.string().optional(),gitCommitAuthorName:w.string().optional(),githubRepository:w.string().optional(),gitlabProjectPath:w.string().optional(),pipelineId:w.string().optional(),cliVersion:w.string().optional()});w.object({id:w.string()});var bz=w.object({status:w.nativeEnum(Gt),updatedAt:w.coerce.date().optional(),finishedAt:w.coerce.date().optional()});w.object({summary:Eu,githubRepository:w.string().optional(),gitBranchName:w.string().optional()});var Tz=w.object({stepsSnapshot:w.array(w.record(w.string(),w.unknown().optional())).optional(),beforeStepsSnapshot:w.array(w.record(w.string(),w.unknown().optional())).optional(),afterStepsSnapshot:w.array(w.record(w.string(),w.unknown().optional())).optional(),runGroupId:w.string().optional(),testId:w.string(),testName:w.string(),resolvedBaseUrl:w.string().optional(),environmentName:w.string().optional(),labels:w.array(w.string()).optional(),cliVersion:w.string().optional(),trigger:w.nativeEnum(Pi),schemaVersion:w.string().optional(),section:w.nativeEnum(qT).optional(),resolvedInputs:w.record(w.string(),w.string()).optional(),quarantined:w.boolean().optional().default(false),quarantinedReason:w.string().optional(),aiSettings:qa.optional()});w.object({id:w.string()});var lpe=e_.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),Az=lpe.array(),Ez=e_.pick({startedAt:true,finishedAt:true,updatedAt:true,results:true,beforeResults:true,afterResults:true,status:true,healStatus:true,healDetails:true,failureDetails:true,failureReason:true,failureRecoveryDetails:true,resolvedBaseUrl:true,environmentName:true,labels:true,cliVersion:true,resolvedInputs:true,attempts:true,flake:true,aiSettings:true}).partial();w.object({id:w.string()});var Cz=w.object({run:ea.omit({runAttempts:true}),attemptZipUrls:w.array(w.string().url().nullish())}),Rz=w.object({status:w.nativeEnum(Gt),finishedAt:w.coerce.date().optional(),schemaVersion:w.string().optional().default("1.0.19"),results:w.record(w.string(),w.unknown().optional()).array().optional(),beforeResults:w.record(w.string(),w.unknown().optional()).array().optional(),afterResults:w.record(w.string(),w.unknown().optional()).array().optional()});w.object({screenshot:w.string(),contentType:w.enum(["image/jpeg","image/png"]).optional()});w.object({id:w.string(),screenshot:w.string(),contentType:w.enum(["image/jpeg","image/png"])});var vz=w.object({key:w.string()}),wz=w.object({orgId:w.string(),userId:w.string(),email:w.string().optional(),name:w.string().optional(),pylonEmailHash:w.string().optional(),selfServe:w.boolean().optional()}),Iz=w.object({blocked:w.boolean()}),xz=w.array(bU);w.record(w.string(),w.union([w.string(),w.boolean()]));w.object({workosAccessToken:w.string().min(1),organizationId:w.string().optional(),clientName:w.string().min(1).max(80).optional()});var _z=w.object({apiKey:w.string(),apiKeyName:w.string(),organizationId:w.string(),user:w.object({id:w.string(),email:w.string().optional()}),selfServe:w.boolean().optional()}),Pz=w.object({error:w.literal("multiple_organizations"),organizations:w.array(w.object({id:w.string(),name:w.string()}))}),cpe=["web","ios","android"];w.object({platforms:w.array(w.enum(cpe)),packageManager:w.enum(["npm","pnpm","yarn","bun"]),wizardVersion:w.string().min(1).max(40),cliVersions:w.object({momentic:w.string().max(40).optional(),momenticMobile:w.string().max(40).optional()}).optional(),firstRunIds:w.array(w.guid()).max(10).optional()});w.object({ok:w.literal(true)});w.object({paths:w.string().array(),env:w.string().optional(),urlOverride:w.string().optional(),customHeaders:w.record(w.string(),w.string()).optional()});var Mz=w.object({suiteRunIds:w.string().array(),runGroupIds:w.string().array()});w.object({suiteRunIds:w.string().array()});iH.array();w.object({runGroupIds:w.string().array()});var CP=w.object({uploadUrl:w.string()});vo.merge(yH);vo.merge(bH);vo.merge(SH);var dpe=w.object({testId:w.string().optional().default(""),testName:w.string().optional().default(""),suiteId:w.string().optional().default(""),suiteName:w.string().optional().default(""),isInteractive:w.boolean().optional().default(false),creditsUsed:w.number().optional(),stepsExecuted:w.number().optional(),tokensUsed:w.number().optional()}),upe=w.object({transactionId:w.string(),timestamp:w.string(),event:w.nativeEnum(Fm),properties:dpe});upe.array();var Oz=$j.omit({steps:true}).extend({steps:w.array(w.record(w.string(),w.unknown().optional())).describe("unparsed ResolvedStep[]")});w.object({limit:w.number().min(1).max(10).optional(),page:w.number().min(1).optional(),start:On.optional(),end:On.optional(),gitBranchName:w.string().optional(),status:w.nativeEnum(Gt).optional()});var Nz=Zx.array(),ppe=w.object({testId:Ln.optional(),gitBranchName:w.string().optional(),status:w.nativeEnum(Gt).optional(),label:w.string().array().optional(),limit:w.number().min(1).max(100).optional(),page:w.number().min(1).optional(),start:On.optional(),end:On.optional(),quarantined:w.boolean().optional(),recovered:w.boolean().optional()});ppe.extend({orgId:w.string().optional(),testId:wo(Ln),status:wo(w.nativeEnum(Gt)),gitBranchName:wo(w.string()),label:wo(w.string()),testName:w.string().optional(),trigger:wo(w.nativeEnum(Pi)),executionType:wo(Rm),cliVersion:wo(w.string()),githubRepository:wo(w.string()),gitlabProjectPath:wo(w.string()),environment:wo(w.string()),directory:wo(w.string()),failureCategory:wo(w.string()),exclude:wo(w.string()),healed:w.boolean().optional()});var Lz=w.object({runs:Zx.array(),page:w.number(),pageSize:w.number(),pageCount:w.number()});w.object({applied:w.boolean().optional(),appliedAt:w.coerce.date().optional()});var kz=CP.extend({id:w.string()});w.object({runGroupId:w.guid().optional(),persist:w.boolean().optional()});var Dz=w.object({runGroupId:w.guid()}),Fz=w.object({quarantined:w.object({testId:Ln,quarantinedAt:w.coerce.date(),quarantinedBy:w.string().optional(),quarantinedReason:w.string()}).array()}),Bz=w.object({gitLocalUsername:w.string().optional(),gitLocalEmail:w.string().optional(),gitLocalName:w.string().optional()});w.object({testId:Ln,testName:w.string().optional(),reason:w.string()}).merge(Bz);w.object({testName:w.string().optional(),reason:w.string().optional()}).merge(Bz);vo.merge(wG);vo.merge(IG);vo.merge(xG);w.object({apkToInstall:w.object({channel:w.string(),tag:w.string().optional()}).optional(),hostname:w.string().optional(),region:j_.optional(),osVersion:w.nativeEnum(jf).optional(),sessionId:w.string().optional()});var Uz=w.object({name:w.string(),apiUrl:w.string(),webRtcUrl:w.string(),adbUrl:w.string(),token:w.string(),apkDownloadUrl:w.string().optional(),playwrightServerUrl:w.string().optional(),region:w.string().optional(),resolvedTag:w.string().optional()});w.object({appToInstall:w.object({channel:w.string(),tag:w.string().optional()}).optional(),hostname:w.string().optional(),region:j_.optional(),osVersion:w.nativeEnum(V_).optional(),sessionId:w.string().optional(),installAppOnClient:w.boolean().optional()});var Hz=w.object({id:w.string(),apiUrl:w.string(),webRtcUrl:w.string(),wdaUrl:w.string(),token:w.string(),appDownloadUrl:w.string().optional(),appMd5:w.string().optional(),region:w.string().optional(),resolvedTag:w.string().optional()});w.object({channel:w.string().trim().min(1,"channel must be a non-empty string"),tag:w.string().trim().min(1,"tag must be a non-empty string"),md5:w.string()});var Gz=w.object({id:w.string(),uploadUrl:w.string().optional(),downloadUrl:w.string(),md5:w.string().optional()}),mpe=w.object({channel:w.string(),tag:w.string(),md5:w.string(),platform:w.nativeEnum(Js).default("ANDROID"),createdAt:w.number().describe("Unix timestamp in milliseconds")}),jz=w.object({assets:w.array(mpe)}),$z=w.object({downloadUrl:w.string()}),RP=(n=>(n.PLAYWRIGHT="PLAYWRIGHT",n.CDP="CDP",n))(RP||{}),hpe=w.nativeEnum(RP);w.object({runId:w.guid().optional(),attemptedProviders:w.array(nP).optional()});var Vz=w.object({wsEndpoint:w.string(),accessToken:w.string().optional(),endpointType:hpe.optional(),provider:nP.optional()});z.object({repositoriesIndexed:z.boolean(),indexingInProgress:z.boolean(),indexesOutdated:z.boolean()});var zz=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(zz||{}),Wz=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(Wz||{});z.object({name:z.string(),status:z.enum(zz),conclusion:z.enum(Wz).nullable()});var iy=z.object({sha:z.string(),message:z.string(),author:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()}),committer:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()})}),vP=z.object({mergedBranch:z.string().optional()});var qz=z.object({orgId:z.string(),cacheKeys:z.string().array()});z.object({keyParams:qz,clientMetadata:z.string(),lockAcquisitionTimeoutMs:z.number().optional()});var Kz=z.object({acquired:z.boolean(),acquiredByMetadata:z.string(),keyPrefix:z.string()});z.object({keyPrefix:z.string(),result:z.string(),ttlMs:z.number()});z.union([z.object({keyPrefix:z.string()}),qz]);var gpe=z.object({remainingTtlMs:z.number(),value:z.string().nullish()});z.object({results:z.record(z.string(),gpe),activeLocks:z.string().array()});var Yz=0,Jz=5*60*1e3;function Qz(){return new Date(Date.now()-2592e6)}function Km(e){if(e.startsWith("https://api"))return e.replace("https://api","https://app");if(e.startsWith("http://localhost:8000"))return e.replace("http://localhost:8000","http://localhost:3000");throw new Error(`Unknown Momentic app server URL pattern: ${e}`)}var fpe=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()),hash:z.string()}),Xz=z.record(z.string(),z.unknown().optional());z.object({newSvgs:z.array(fpe),metadata:Xz.optional()});var ype=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()).nullish(),hash:z.string(),description:z.string().nullish(),metadata:Xz.nullish()}),Zz=z.record(z.string().describe("icon hash"),ype);function e1(e){let t;try{t=JSON.parse(e);}catch(n){return `The schema is not valid JSON. ${n}`}try{validator(t);}catch(n){return `The schema is not a valid JSON schema. ${n}`}}var t1=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,n])=>t.trim()&&n.trim())));};var BA=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function bpe(e){return e.map(t=>({...t,environment:void 0}))}function wP(e,t){return t?e:bpe(e)}var xP="browser-crash-dump.zip",IP=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new sy}},sy=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new IP}flushResults(t){}};var Ze="metadata.json",tr="assets",wn="runs",Tpe=z.object({step:Yt,status:z.enum(Mt),startedAt:z.coerce.date(),finishedAt:z.coerce.date().optional(),healMetadata:z.object({healType:z.enum(hf).or(z.literal("AI")),healedAt:z.coerce.date()}).optional(),beforeSnapshotId:z.guid().optional(),afterSnapshotId:z.guid().optional(),message:z.string().optional()}),Ape=Tpe.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});Ape.extend({step:z.unknown().optional()});var _P=z.object({avdId:z.string().optional(),channel:z.string().optional(),tag:z.string().optional(),region:z.string().optional()}),o1="1.0.0",r1=Rz.extend({id:z.guid().optional(),startedAt:z.coerce.date(),runAttemptSchemaVersion:z.string().optional(),schemaVersion:z.string().optional().default("1.0.19"),results:z.record(z.string(),z.unknown().optional()).array().optional(),beforeResults:z.record(z.string(),z.unknown().optional()).array().optional(),afterResults:z.record(z.string(),z.unknown().optional()).array().optional(),assetDetails:_P.optional(),viewport:Jl.optional(),activeVideos:z.array(z.object({videoName:z.string(),timestamp:z.coerce.date()})).optional()}),ay=r1.extend({assetDetails:_P.optional(),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});r1.extend(Hx.shape);var i1=ay.extend(Hx.shape),Epe=z.object({results:z.array(Oi),beforeResults:z.array(Oi).optional(),afterResults:z.array(Oi).optional()});ay.extend(Epe.shape);var Cpe=z.object({results:z.array(Ni),beforeResults:z.array(Ni).optional(),afterResults:z.array(Ni).optional()});ay.extend(Cpe.shape);var s1=Ez.merge(Tz).extend({executionType:Rm.optional().default("WEB"),testId:Ln,testDescription:z.string().optional(),directory:z.string().optional(),runGroupId:z.guid(),status:z.enum(Gt),healStatus:Xx,startedAt:z.coerce.date(),schemaVersion:z.string().nullish(),attempts:z.number(),failureRecoveryDetails:z.object({attempts:z.number()}).optional(),aiSettings:qa.optional(),avgCpuUsage:z.number().optional(),avgMemoryUsage:z.number().optional()}),Rpe=s1.extend(_P.shape),Mu=s1.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});Rpe.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var n1=z.object({mode:z.enum(["SELECTED","RUN_ALL","RUN_NONE","SHADOW"]),baseRef:z.string().nullable(),headSha:z.string(),planId:z.string().nullable(),totalCandidates:z.number().int().nonnegative(),selectedCount:z.number().int().nonnegative(),anchorSegmentIds:z.array(z.string()),userSummary:z.string(),toolCallCount:z.number().int().nonnegative(),selectedTests:z.array(z.object({testId:z.string(),name:z.string(),testPath:z.string().nullable(),relevanceLabel:z.enum(["high","medium","low"]),rationale:z.string()})),forcedTests:z.array(z.object({name:z.string(),testPath:z.string(),status:z.enum(["A","M","R","C","T"])})).optional().default([]),runAllReason:z.string().nullable()}),vpe=Sz.merge(bz).extend({id:z.guid().optional(),startedAt:z.coerce.date(),cliVersion:z.string(),labels:z.string().array().optional().default([]),suiteName:z.string().optional(),ciProvider:z.string().optional(),gitMainBranch:z.string().optional(),ai:qa.optional(),browser:Ql.optional(),aiSelect:z.union([n1.transform(e=>[e]),z.array(n1)]).optional()}),fs=vpe.extend({healRiskSummary:Eu.optional(),updatedAt:z.coerce.date().optional().transform(e=>e??new Date),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var wpe=new Set(["AWAIT_LISTENER","REGISTER_REQUEST_LISTENER","GET_RECORDED_REQUESTS","MOCK_ROUTE","REMOVE_ROUTE_MOCK","SCROLL_DOWN","SCROLL_UP","SCROLL_LEFT","SCROLL_RIGHT","VISUAL_DIFF","WAIT","SET_HEADER","OFFLINE_MODE"]),Ipe=new Set(["MODULE","RESOLVED_MODULE"]);function UA(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function HA(e){return Ipe.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!wpe.has(e.command.type)}function a1(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return R.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var l1="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",GA="https://us-west.metrics.momentic.ai",jA="c60c6a0f-60da-41a7-a61b-07969a0aa303",ic=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;var kpe=new Set(["exit","quit"]),u1=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})();async function xo(e){return ic||u1?true:(await R.flush(),await new Promise(n=>setTimeout(n,100)),await confirm({message:e}))}async function PP(e){let t=dirname(e);return a1(t)?existsSync(e)?xo(`File '${c1(e)}' already exists. Overwrite existing content?`):true:await xo(`Directory '${c1(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function c1(e){return e.replace(/(\s+)/g,"\\$1")}async function p1(e,t){return ic||u1?t:(await input({message:e,default:t})).trim()||t}async function m1(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){R.info("");return}throw t}if(!kpe.has(e.toLowerCase()))return e}var Ym=new Map,g1="Log throttle exceeded",Wpe=100,qpe=5e3,Kpe=Hpe(global.fetch,{retries:2,retryOn:function(e,t,n){return !!(t!==null||n&&n.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}}),Ype="https://ingest.us.signoz.cloud:443/logs/json",MP=class{constructor(t,n){this.flushIntervalMs=t;this.maxBatchSize=n;}records=[];flushTimer;push(t){if(this.records.push(t),this.records.length>=this.maxBatchSize){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flush();return}this.scheduleFlush();}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush();},this.flushIntervalMs));}async flush(){if(this.records.length===0)return;let t=this.records;this.records=[];try{let n=await Kpe(Ype,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":l1},body:Xs(t),signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch{}}},OP=class e{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=false;lastWindowStart=Date.now();flushIntervalMs;maxBatchSize;buffer;constructor({bindings:t,hostname:n,disableConsoleLogs:o,flushIntervalMs:r,maxBatchSize:i,buffer:s}){this.hostname=n??sc.hostname(),this.disableConsoleLogs=o,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=s??new MP(this.flushIntervalMs,this.maxBatchSize);let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=h1(a);}child(t){return new e({bindings:{...this.bindingAttributes,...t},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize,buffer:this.buffer})}async flush(){await this.buffer.flush(),this.disableConsoleLogs||this.consoleLogger.flush();}shouldAllowLog(t){if(t===g1)return true;let n=Date.now();return n-this.lastWindowStart>qpe&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,g1),this.droppedLogsInWindow=false,this.lastWindowStart=n),this.logsInCurrentWindow<Wpe?(this.logsInCurrentWindow++,true):(this.droppedLogsInWindow=true,false)}log(t,n,o,...r){try{this.logHelper(t,n,o,...r);}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`);}}logHelper(t,n,o,...r){if(bf[t]<this.minLevelValue||!this.shouldAllowLog(o))return;typeof n=="string"&&!o&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=Vpe.err(n.err));let i={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...r.length>0?{args:r}:{}},s={host:this.hostname,env:this.bindingAttributes.env},a=Jpe();this.disableConsoleLogs||this.consoleLogger[t]({...i,...a??{}},o,...r);let l={timestamp:Math.round(Date.now()*1e6),...a??{},severity_text:t.toUpperCase(),resources:s,attributes:{},body:UU({message:o||"",...i})};this.buffer.push(l);}setApp(t){let n=this.bindingAttributes.app;this.bindingAttributes.app=t,Ym.set("app",this),Ym.delete(n);}debug(t,n,...o){this.log("debug",t,n,...o);}info(t,n,...o){this.log("info",t,n,...o);}warn(t,n,...o){this.log("warn",t,n,...o);}error(t,n,...o){this.log("error",t,n,...o);}bindings(){return this.bindingAttributes}addBinding(t,n){this.bindingAttributes[t]=n;}setMinLevel(t){typeof t=="number"?(this.minLevelValue=t,this.consoleLogger.level=HU[t]):(this.minLevelValue=bf[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},Jm=({app:e,hostname:t,disableConsoleLogs:n})=>(Ym.has(e)||Ym.set(e,new OP({bindings:{app:e},hostname:t,disableConsoleLogs:n})),Ym.get(e));function Jpe(){let e=trace.getSpan(context.active());if(!e)return;let t=e.spanContext();if(isSpanContextValid(t))return {trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}async function $A(){await Promise.all([...Ym.values()].map(e=>e.flush()));}var cd=class extends Error{constructor(t){super(t),this.name="TimeoutError";}};var f1=e=>{let t=e.reason===void 0?new DOMException("This operation was aborted.","AbortError"):e.reason;return t instanceof Error?t:new DOMException(t,"AbortError")};function Re(e,t){let{milliseconds:n,fallback:o,message:r,customTimers:i={setTimeout,clearTimeout}}=t,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);return new Promise((a,l)=>{let c;if(t.signal){let{signal:p}=t;if(p.aborted)return l(f1(p));c=()=>l(f1(p)),p.addEventListener("abort",c,{once:true});}let d=()=>{if(t.signal&&t.signal.removeEventListener("abort",c),o)try{a(o());}catch(p){l(p);}else {typeof e.cancel=="function"&&Promise.resolve().then(()=>e.cancel()).catch(()=>{});let p=r instanceof Error?r:new cd(r??`Promise timed out after ${n}ms`);l(p);}};n<1/0&&(s=i.setTimeout(d,n));let u=()=>{i.clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",c);};Promise.resolve(e).then(p=>{u(),a(p);}).catch(p=>{u(),l(p);});})}var VA="organization";function zA(e){let t=new PostHog(e.writeKey,{host:e.host,...e.flushImmediately?{flushAt:1,flushInterval:0}:{}}),n=e.platform,o=(l,c,d)=>{let{type:u,...p}=l;t.capture({distinctId:c??d??randomUUID(),event:u,...d&&{groups:{[VA]:d}},properties:{platform:n,user_id:c??void 0,org_id:d??void 0,...p,organizationId:d??void 0,...c==null&&{$process_person_profile:false}}});},r=({orgId:l,properties:c})=>{t.groupIdentify({groupType:VA,groupKey:l,properties:c});},i=({userId:l,properties:c})=>{Object.values(c).some(u=>u!=null&&u!=="")&&t.identify({distinctId:l,properties:c});},s=()=>t.shutdown();if(e.identity==="stashed"){let l=null;return {shutdownAnalytics:s,groupIdentifyOrg:r,setAnalyticsIdentity:d=>{l=d,e.onIdentify?.(d),i({userId:d.userId,properties:{email:d.email,...d.selfServe!==void 0?{self_serve:d.selfServe}:{}}});},captureEvent:d=>o(d,l?.userId??null,l?.orgId??null)}}return {shutdownAnalytics:s,groupIdentifyOrg:r,identifyUser:i,captureEvent:(l,{userId:c,orgId:d})=>o(l,c,d),captureBillingEvent:(l,{userId:c,orgId:d})=>o(l,c,d)}}async function y1(e,t,n){let o,r=0,i=3,s,a;for(;r<i;)try{let l=await Re(e.getAllFlagsAndPayloads(n??t,{personProperties:{organizationId:t},groups:{[VA]:t}}),{milliseconds:5e3});s=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){o=l,r++,await new Promise(c=>setTimeout(c,100*r));}if(s&&a)return {flags:s,payloads:a};throw o}var WA=class e extends Kf{constructor(n,o,r,i,s){super(i,s);this.client=n;this.orgId=o;this.userId=r;}static async init(n,o){let r=new PostHog("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://p.momentic.ai"}),{flags:i,payloads:s}=await y1(r,n,o);return new e(r,n,o,i,s)}async refresh(){let{flags:n,payloads:o}=await y1(this.client,this.orgId,this.userId);this.flags=n,this.payloads=o;}};var nme=2e3,Ou=e=>Number.parseInt(e,10),LP=e=>readFileSync(e,"utf8").trim(),Qm=e=>Ou(LP(e)),S1,qA,ly={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function A1(){return {...ly}}var YA=sc.platform(),ome=sc.cpus().map(e=>({model:e.model,speed:e.speed})).reduce((e,t)=>(e[t.model]={speed:t.speed},e.totalCores=(e.totalCores??0)+1,e),{});function NP(e=Date.now()){let t=sc.cpus(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;return n.total=n.user+n.nice+n.sys+n.idle+n.irq,n}function E1(e,t){let n={user:t.user-e.user,nice:t.nice-e.nice,sys:t.sys-e.sys,idle:t.idle-e.idle,irq:t.irq-e.irq,total:t.total-e.total};return n.total<=0?null:{measurementTime:t.measurementTime,intervalMs:t.measurementTime-e.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100}}function rme(){let e=NP();return ()=>{let t=NP(),n=E1(e,t);return e=t,n}}function b1(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return Ou(t[1])}catch{}try{let e=Qm("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function ime(){try{let t=LP("/sys/fs/cgroup/cpu.max").split(" "),n=t[0],o=t[1];return !n||!o||n==="max"?null:Ou(n)/Ou(o)}catch{}try{let e=Qm("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=Qm("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function sme(){if(YA!=="linux")return null;let e=b1();if(e===null)return null;let t=ime()??sc.cpus().length,n=e,o=Date.now();return ()=>{let r=b1();if(r===null)return null;let i=Date.now(),s=i-o;if(s<=0)return null;let a=r-n,l=s*1e3,c=Math.max(0,Math.min(100,a/l/t*100));return n=r,o=i,{measurementTime:i,intervalMs:s,user:c,nice:0,sys:0,idle:Math.max(0,100-c),irq:0,total:c}}}function ame(){let e=process.cpuUsage(),t=process.hrtime.bigint();return ()=>{let n=process.cpuUsage(),o=process.hrtime.bigint(),r=Number(o-t)/1e6,i=n.user-e.user,s=n.system-e.system;if(e=n,t=o,r<=0)return null;let a=Math.max(sc.cpus().length,1),l=c=>Math.max(0,c/1e3/r*100/a);return {total:l(i+s),user:l(i),sys:l(s),intervalMs:r}}}function C1({intervalMs:e=nme,maxSamples:t=1e4,keepSamples:n=true,onSample:o}={}){let r=[],i=sme()??rme(),s=ame(),a=()=>{let d=Date.now(),u=w1(),p=process.memoryUsage(),m=i(),h=s(),g={timestamp:d,system:{cpu:m,memory:{total:u.totalMemory,free:u.freeMemory,freePercentage:u.freePercentage}},process:{cpu:h,memory:{rss:p.rss,heapTotal:p.heapTotal,heapUsed:p.heapUsed,external:p.external,arrayBuffers:p.arrayBuffers}}};o?.(g),n&&(r.push(g),r.length>t&&r.shift());};a();let l=setInterval(a,e),c=d=>({samples:n?[...r]:[]});return {stop:()=>(clearInterval(l),c()),getSeries:()=>c()}}var KA=e=>{try{let t={},n=!1,o=w1(),r=cme();ly.samples++,o.freePercentage<.05&&(Object.assign(t,process.memoryUsage()),n=!0,ly.lowMemorySamples++),r&&r?.total>80&&(n=!0,ly.highCpuSamples++);let i=tme.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(n=!0,ly.highHeapSamples++),n?e.warn({memory:o,cpu:r,heapStats:i,...t},"Critical resource usage metrics detected"):e.debug({memory:o,cpu:r},"Got machine resource usage metrics");}catch{}},R1=e=>{KA(e),setTimeout(()=>KA(e),5e3);};function v1(e){return KA(e),{interval:setInterval(()=>KA(e),2e4),cpuMetadata:ome,platform:YA}}function lme(){if(YA!=="linux")return null;try{let e=LP("/sys/fs/cgroup/memory.max"),t=Qm("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let n=Ou(e);if(isNaN(n))return null;let o=Math.max(0,n-t);return {totalMemory:n,freeMemory:o,freePercentage:o/n}}catch{}try{let e=Qm("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=Qm("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let n=sc.totalmem();if(e>=n)return null;let o=Math.max(0,e-t);return {totalMemory:e,freeMemory:o,freePercentage:o/e}}catch{return null}}function w1(){let e=lme();if(e)return e;let t=sc.totalmem(),n=YA==="darwin"?dme():(()=>{let r=sc.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),o=n.availableMemory/t;return {totalMemory:t,freeMemory:n.availableMemory,freePercentage:o}}function cme(){let e=NP();if(!qA)return qA=e,null;let t=E1(qA,e);return qA=e,t?(S1=t,S1):null}function dme(){try{let e=execSync("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),n=e.match(/page size of (\d+) bytes/)?.[1],o=n?Ou(n):4096,r=d=>{let p=e.match(new RegExp(`${d}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Ou(p):0},i=r("Pages free"),s=r("Pages inactive"),a=r("Pages speculative"),l=i*o,c=(s+a)*o;return {availableMemory:l+c,rawFreeMemory:l,cachedMemory:c}}catch{let e=sc.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Xm=false,JA,cy,dy,_1=[];function QA(){return Xm}function P1(e){_1.push(e);}async function Ame(){for(let e of _1)try{await e();}catch{}}function Eme(){return QA()&&trace.getSpan(context.active())!==void 0}function Cme(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${GA}/v1/traces`,headers:{"x-momentic-metrics-api-key":jA}})}function Rme(e){let t="production",n=v4$1(),o=Cme(),r=new NodeTracerProvider({resource:new Resource({[SEMRESATTRS_SERVICE_NAME]:e,[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:t,[SEMRESATTRS_SERVICE_INSTANCE_ID]:n})});return r.addSpanProcessor(new BatchSpanProcessor(o)),r}function vme(e){return !e&&!JA?trace.getTracer("momentic-serverless"):dy?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function Nu(e){if(!(!e.enabled||Xm))try{JA=e.serviceName;let t=Rme(e.serviceName);dy=t,cy=new AsyncLocalStorageContextManager,t.register({contextManager:cy.enable()}),Xm=!0;}catch{Xm=false,JA=void 0,dy=void 0,cy=void 0;}}async function XA(){if(Xm)try{await Ame(),await dy?.shutdown();}catch{}finally{try{cy?.disable();}catch{}Xm=false,JA=void 0,cy=void 0,dy=void 0;}}async function it(e){if(!QA()||!e.root&&!Eme())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await vme(e.serviceName).startActiveSpan(e.name,{attributes:t,kind:e.kind??SpanKind.CLIENT},async n=>{try{let o=await e.fn(n);return n.setStatus({code:SpanStatusCode.OK}),o}catch(o){throw n.setStatus({code:SpanStatusCode.ERROR,message:o instanceof Error?o.message.slice(0,300):void 0}),o instanceof Error&&n.recordException(o),o}finally{n.end();}})}var uy=class{increment(t,n,o){}gauge(t,n){}distribution(t,n,o){}async flush(){}async recordDuration(t){return await DP(t)}};async function DP({fn:e,name:t,timeoutMs:n,trace:o}){let r=o?()=>it({name:o.name,attributes:o.attributes,fn:e}):e,i=Promise.resolve(r());return n===void 0?await i:await Re(i,{milliseconds:n,message:`Timed out after ${n}ms recording duration for ${t}`})}function wme(e){if(!e||e.length===0)return {};let t={};for(let n of e){let o=n.indexOf(":");if(o>-1){let r=n.slice(0,o).trim(),i=n.slice(o+1).trim();r&&(t[r]=i);continue}t[n]=true;}return t}function FP(e,t){let n=wme(e);return !t||Object.keys(t).length===0?n:{...t,...n}}function Dme(){return new OTLPMetricExporter({url:`${GA}/v1/metrics`,headers:{"x-momentic-metrics-api-key":jA},temporalityPreference:AggregationTemporalityPreference.DELTA})}var Fme=[new View({instrumentName:"test_event_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],false)}),new View({instrumentName:"test_step_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],false)}),new View({instrumentName:"test_mobile_step_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],false)}),new View({instrumentName:"web_agent_action_duration",instrumentType:InstrumentType.HISTOGRAM,aggregation:new ExplicitBucketHistogramAggregation([5,10,25,50,100,250,500,1e3,2e3,5e3],false)})],nE=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(t){let n=this.counterCache.get(t);if(n)return n;let o=this.meter.createCounter(t);return this.counterCache.set(t,o),o}getHistogram(t){let n=this.histogramCache.get(t);if(n)return n;let o=this.meter.createHistogram(t);return this.histogramCache.set(t,o),o}ensureObservableGauge(t){let n=this.observableGaugeCache.get(t);if(n)return n;let o=this.meter.createObservableGauge(t);return o.addCallback(r=>{let i=this.gaugeValues.get(t);i!==void 0&&r.observe(i,this.globalAttributes);}),this.observableGaugeCache.set(t,o),o}constructor(t){this.globalAttributes={...t.globalAttributes??{}};let n=typeof process<"u"?"production":"unknown",o=new Resource({[SEMRESATTRS_SERVICE_NAME]:t.serviceName,[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:n,[SEMRESATTRS_SERVICE_INSTANCE_ID]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1()}),r=Dme(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:o,readers:[i],views:Fme}),metrics.setGlobalMeterProvider(this.provider),this.meter=metrics.getMeter("momentic-serverless");}increment(t,n,o){try{let r=FP(o,this.globalAttributes);this.getCounter(t).add(typeof n=="number"?n:1,r);}catch{}}gauge(t,n){try{this.ensureObservableGauge(t),this.gaugeValues.set(t,n);}catch{}}distribution(t,n,o){try{let r=FP(o,this.globalAttributes);this.getHistogram(t).record(n,r);}catch{}}async flush(){try{await this.provider.forceFlush();}catch{}}async recordDuration(t){let{name:n,tags:o}=t,r=Date.now();try{return await DP(t)}finally{this.distribution(n,Date.now()-r,o);}}};var gt=new uy;function O1(e){if(!e.disabled)try{gt=new nE(e);}catch{gt=new uy;}}var BP;function N1(e){BP=e;}function dd(e){bT(e,_e)||BP&&BP(e);}function W1(){return globalThis.crypto}function jP(e){let t=W1(),n=new Uint8Array(e);if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(n),n;for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);return n}function pd(){let e=W1();if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=jP(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return `${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function $P(e){let t=globalThis.Buffer;if(t)return t.from(e).toString("base64");let n="";for(let a=0;a<e.length;a++)n+=String.fromCharCode(e[a]);let o=globalThis.btoa;if(typeof o=="function")return o(n);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="",s=0;for(;s<n.length;){let a=n.charCodeAt(s++)&255,l=s<n.length?n.charCodeAt(s++)&255:NaN,c=s<n.length?n.charCodeAt(s++)&255:NaN,d=a>>2,u=(a&3)<<4|(Number.isNaN(l)?0:l>>4),p=Number.isNaN(l)?64:(l&15)<<2|(Number.isNaN(c)?0:c>>6),m=Number.isNaN(c)?64:c&63;i+=r.charAt(d),i+=r.charAt(u),i+=p===64?"=":r.charAt(p),i+=m===64?"=":r.charAt(m);}return i}function Ume(e){return new Promise(t=>setTimeout(t,e))}function my(e){if(e)return e.endsWith("/")?e:`${e}/`}function Hme(e){var t;let n=(t=e.get("Retry-After"))!=null?t:e.get("retry-after");if(!n)return;let o=Number(n);if(n.trim()!==""&&!Number.isNaN(o))return o*1e3;let r=new Date(n).getTime();if(!Number.isNaN(r)){let i=r-Date.now();return i>0?i:0}}function Gme(e,t){if(t&&typeof t=="object"&&t!==null&&"retryAfterMs"in t){let r=t.retryAfterMs;if(typeof r=="number")return Math.max(0,r)}if(e<=1)return 0;let n=500,o=Math.pow(2,e-2);return n*o}async function jme(e,t,n){let o=n.sdkName?`[raindrop-ai/${n.sdkName}]`:"[raindrop-ai/core]",r;for(let i=1;i<=n.maxAttempts;i++){if(i>1){let s=Gme(i,r);n.debug&&console.warn(`${o} ${t} retry ${i}/${n.maxAttempts} in ${s}ms`),s>0&&await Ume(s);}else n.debug&&console.log(`${o} ${t} attempt ${i}/${n.maxAttempts}`);try{return await e()}catch(s){if(r=s,n.debug){let a=s instanceof Error?s.message:String(s);console.warn(`${o} ${t} attempt ${i} failed: ${a}${i===n.maxAttempts?" (no more retries)":""}`);}if(r&&typeof r=="object"&&"retryable"in r&&!r.retryable||i===n.maxAttempts)break}}throw r instanceof Error?r:new Error(String(r))}async function ku(e,t,n,o){let r=`POST ${e}`;await jme(async()=>{let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)});if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`HTTP ${i.status} ${i.statusText}${s?`: ${s}`:""}`),l=Hme(i.headers);throw typeof l=="number"&&(a.retryAfterMs=l),a.retryable=i.status===429||i.status>=500,a}},r,o);}var L1={UNSET:0,ERROR:2};function k1(e){let t=e?e.traceIdB64:$P(jP(16)),n=$P(jP(8));return {traceIdB64:t,spanIdB64:n,parentSpanIdB64:e?e.spanIdB64:void 0}}function hy(){return Date.now().toString()+"000000"}function D1(e){return String(Math.floor(e))+"000000"}function G(e,t){if(t!==void 0)return {key:e,value:{stringValue:t}}}function We(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{intValue:String(Math.trunc(t))}}}function Zm(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{doubleValue:t}}}function $me(e,t){if(t!==void 0)return {key:e,value:{boolValue:t}}}function ac(e,t){if(!(!t||t.length===0))return {key:e,value:{arrayValue:{values:t.filter(n=>typeof n=="string").map(n=>({stringValue:n}))}}}}function UP(e){let t=e.attributes.filter(o=>o!==void 0),n={traceId:e.ids.traceIdB64,spanId:e.ids.spanIdB64,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano};return e.ids.parentSpanIdB64&&(n.parentSpanId=e.ids.parentSpanIdB64),t.length&&(n.attributes=t),e.status&&(n.status=e.status),n}function F1(e,t="raindrop.core",n="0.0.0"){return {resourceSpans:[{resource:{attributes:[{key:"service.name",value:{stringValue:t}}]},scopeSpans:[{scope:{name:t,version:n},spans:e}]}]}}var Vme="RAINDROP_LOCAL_DEBUGGER",zme="RAINDROP_WORKSHOP",B1="http://localhost:5899/v1/";function JP(e){var t;try{let n=(t=globalThis?.process)==null?void 0:t.env;if(n&&typeof n[e]=="string"&&n[e].length>0)return n[e]}catch{}}function Wme(){let e=JP(zme);if(e===void 0)return;let t=e.trim();if(t.length!==0){if(/^https?:\/\//i.test(t))return {url:t};if(/^(1|true|yes|on)$/i.test(t))return "enable";if(/^(0|false|no|off)$/i.test(t))return "disable"}}function qme(e){return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e.endsWith(".localhost")):false}function Kme(){try{let e=globalThis?.location;if(e&&typeof e.hostname=="string"&&e.hostname.length>0)return e.hostname}catch{}}function Yme(){return !!(qme(Kme())||JP("NODE_ENV")==="development")}function Fu(e){var t,n,o;if(e===null)return null;if(typeof e=="string"&&e.length>0)return (t=my(e))!=null?t:null;let r=JP(Vme);if(r)return (n=my(r))!=null?n:null;let i=Wme();return i==="disable"?null:i==="enable"?B1:i&&"url"in i?(o=my(i.url))!=null?o:null:Yme()?B1:null}function cE(e){return Fu(e)!==null}function Jme(e,t={}){var n;let o=Fu(t.baseUrl);o&&ku(`${o}traces`,e,{},{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function Qme(e,t={}){var n;let o=Fu(t.baseUrl);if(!o)return;let r=t.writeKey?{Authorization:`Bearer ${t.writeKey}`}:{};ku(`${o}events/track_partial`,e,r,{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function ud(e,t={}){var n,o;let r=Fu(t.baseUrl);r&&ku(`${r}live`,{...e,type:e.type,timestamp:(n=e.timestamp)!=null?n:Date.now()},{},{maxAttempts:1,debug:(o=t.debug)!=null?o:false,sdkName:t.sdkName}).catch(()=>{});}function Xme(e,t){var n,o,r,i;let s={...e,...t};return (e.properties||t.properties)&&(s.properties={...(n=e.properties)!=null?n:{},...(o=t.properties)!=null?o:{}}),(e.attachments||t.attachments)&&(s.attachments=[...(r=e.attachments)!=null?r:[],...(i=t.attachments)!=null?i:[]]),s}var Zme=class{constructor(e){this.buffers=new Map,this.sticky=new Map,this.timers=new Map,this.inFlight=new Set;var t,n,o,r,i,s,a,l;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=my(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.partialFlushMs=(o=e.partialFlushMs)!=null?o:1e3,this.sdkName=(r=e.sdkName)!=null?r:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.defaultEventName=(i=e.defaultEventName)!=null?i:"ai_generation",this.localDebuggerUrl=(s=Fu(e.localDebuggerUrl))!=null?s:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);let c=typeof process<"u"&&typeof process.version=="string";this.context={library:{name:(a=e.libraryName)!=null?a:"@raindrop-ai/core",version:(l=e.libraryVersion)!=null?l:"0.0.0"},metadata:{jsRuntime:c?"node":"web",...c?{nodeVersion:process.version}:{}}};}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}async patch(e,t){var n,o,r,i,s,a,l,c,d,u,p;if(!this.enabled||!e||!e.trim())return;this.debug&&console.log(`${this.prefix} queue patch`,{eventId:e,userId:t.userId,convoId:t.convoId,eventName:t.eventName,hasInput:typeof t.input=="string"&&t.input.length>0,hasOutput:typeof t.output=="string"&&t.output.length>0,attachments:(o=(n=t.attachments)==null?void 0:n.length)!=null?o:0,isPending:t.isPending});let m=(r=this.sticky.get(e))!=null?r:{},h=(i=this.buffers.get(e))!=null?i:{},g=Xme(h,t);g.isPending=(l=(a=(s=t.isPending)!=null?s:h.isPending)!=null?a:m.isPending)!=null?l:true,this.buffers.set(e,g),this.sticky.set(e,{userId:(c=g.userId)!=null?c:m.userId,convoId:(d=g.convoId)!=null?d:m.convoId,eventName:(u=g.eventName)!=null?u:m.eventName,isPending:(p=g.isPending)!=null?p:m.isPending});let f=this.timers.get(e);if(f&&clearTimeout(f),g.isPending===false){await this.flushOne(e);return}let b=setTimeout(()=>{this.flushOne(e).catch(()=>{});},this.partialFlushMs);this.timers.set(e,b);}async finish(e,t){await this.patch(e,{...t,isPending:false});}async flush(){if(!this.enabled)return;let e=[...this.buffers.keys()];await Promise.all(e.map(t=>this.flushOne(t))),await Promise.all([...this.inFlight].map(t=>t.catch(()=>{})));}async shutdown(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),await this.flush();}async trackSignal(e){var t,n;if(!this.enabled)return;let o=[{event_id:e.eventId,signal_name:e.name,signal_type:(t=e.type)!=null?t:"default",timestamp:e.timestamp,sentiment:e.sentiment,attachment_id:e.attachmentId,properties:{...(n=e.properties)!=null?n:{},...e.comment?{comment:e.comment}:{},...e.after?{after:e.after}:{}}}];if(!this.writeKey)return;let r=`${this.baseUrl}signals/track`;try{await ku(r,o,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`${this.prefix} failed to send signal (dropping): ${s}`);}}async identify(e){if(!this.enabled)return;let n=(Array.isArray(e)?e:[e]).filter(r=>!r?.userId||!r.userId.trim()?(this.debug&&console.warn(`${this.prefix} skipping identify: missing userId`),false):true).map(r=>{var i;return {user_id:r.userId,traits:(i=r.traits)!=null?i:{}}});if(!this.writeKey||n.length===0)return;let o=`${this.baseUrl}users/identify`;try{await ku(o,n,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send identify (dropping): ${i}`);}}async flushOne(e){var t,n,o,r,i,s,a,l,c,d,u,p,m;if(!this.enabled)return;let h=this.timers.get(e);h&&(clearTimeout(h),this.timers.delete(e));let g=this.buffers.get(e);if(this.buffers.delete(e),!g)return;let f=(t=this.sticky.get(e))!=null?t:{},b=(o=(n=g.eventName)!=null?n:f.eventName)!=null?o:this.defaultEventName,T=(r=g.userId)!=null?r:f.userId;if(!T){this.debug&&console.warn(`${this.prefix} skipping track_partial for ${e}: missing userId`),this.sticky.delete(e);return}let{wizardSession:A,...C}=(i=g.properties)!=null?i:{},v=(s=g.convoId)!=null?s:f.convoId,I=(l=(a=g.isPending)!=null?a:f.isPending)!=null?l:true,_={event_id:e,user_id:T,event:b,timestamp:(c=g.timestamp)!=null?c:new Date().toISOString(),ai_data:{input:g.input,output:g.output,model:g.model,convo_id:v},properties:{...C,...A?{"raindrop.wizardSession":A}:{},$context:this.context},attachments:g.attachments,is_pending:I},x=`${this.baseUrl}events/track_partial`;if(this.debug&&console.log(`${this.prefix} sending track_partial`,{eventId:e,eventName:b,userId:T,convoId:v,isPending:I,inputPreview:typeof g.input=="string"?g.input.slice(0,120):void 0,outputPreview:typeof g.output=="string"?g.output.slice(0,120):void 0,attachments:(u=(d=g.attachments)==null?void 0:d.length)!=null?u:0,attachmentKinds:(m=(p=g.attachments)==null?void 0:p.map(O=>({type:O.type,role:O.role,name:O.name,valuePreview:O.value.slice(0,60)})))!=null?m:[],endpoint:x}),this.localDebuggerUrl&&Qme(_,{baseUrl:this.localDebuggerUrl,writeKey:this.writeKey,debug:this.debug,sdkName:this.sdkName}),!this.writeKey){I||this.sticky.delete(e);return}let E=ku(x,_,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(E);try{try{await E,this.debug&&console.log(`${this.prefix} sent track_partial ${e} (${b})`);}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`${this.prefix} failed to send track_partial (dropping): ${N}`);}}finally{this.inFlight.delete(E);}I||this.sticky.delete(e);}},q1=["apikey","apisecret","apitoken","secretaccesskey","sessiontoken","privatekey","privatekeyid","clientsecret","accesstoken","refreshtoken","oauthtoken","bearertoken","authorization","password","passphrase"],K1="[REDACTED]";function Y1(e){return e.toLowerCase().replace(/[-_.]/g,"")}function J1(e,t){var n,o;let r=ehe((n=t?.secretKeyNames)!=null?n:q1),i=(o=t?.placeholder)!=null?o:K1,s=new WeakSet,a=l=>{if(l===null||typeof l!="object")return l;if(s.has(l))return "[CIRCULAR]";if(s.add(l),Array.isArray(l))return l.map(d=>a(d));let c={};for(let[d,u]of Object.entries(l))r.has(Y1(d))?c[d]=i:c[d]=a(u);return c};return a(e)}function ehe(e){let t=new Set;for(let n of e)t.add(Y1(n));return t}var Q1=["ai.request.providerOptions","ai.response.providerMetadata"];function X1(e){let t=e.attributes;if(!t||t.length===0)return e;let n;for(let o=0;o<t.length;o++){let r=t[o],i=Z1(r.key,r.value);i!==void 0&&(n||(n=t.slice()),n[o]={key:r.key,value:i});}return n?{...e,attributes:n}:e}var the=new Set(Q1);function Z1(e,t){if(!the.has(e))return;let n=t.stringValue;if(typeof n!="string"||n.length===0)return;let o;try{o=JSON.parse(n);}catch{return}let r=J1(o),i;try{i=JSON.stringify(r);}catch{return}if(i!==n)return {stringValue:i}}var nhe=class{constructor(e){this.queue=[],this.inFlight=new Set;var t,n,o,r,i,s,a,l,c;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=my(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.debugSpans=e.debugSpans===true,this.flushIntervalMs=(o=e.flushIntervalMs)!=null?o:1e3,this.maxBatchSize=(r=e.maxBatchSize)!=null?r:50,this.maxQueueSize=(i=e.maxQueueSize)!=null?i:5e3,this.sdkName=(s=e.sdkName)!=null?s:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.serviceName=(a=e.serviceName)!=null?a:"raindrop.core",this.serviceVersion=(l=e.serviceVersion)!=null?l:"0.0.0",this.localDebuggerUrl=(c=Fu(e.localDebuggerUrl))!=null?c:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`),this.transformSpanHook=e.transformSpan,this.disableDefaultRedaction=e.disableDefaultRedaction===true;}redactSpan(e){let t=e;if(this.transformSpanHook)try{let n=this.transformSpanHook(t);if(n===null)return null;n!==void 0&&(t=n);}catch(n){if(this.debug){let o=n instanceof Error?n.message:String(n);console.warn(`${this.prefix} transformSpan hook threw: ${o}`);}return null}return this.disableDefaultRedaction||(t=X1(t)),t}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}startSpan(e){var t,n;let o=k1(e.parent),r=(t=e.startTimeUnixNano)!=null?t:hy(),i=[G("ai.telemetry.metadata.raindrop.eventId",e.eventId),G("ai.operationId",e.operationId)];(n=e.attributes)!=null&&n.length&&i.push(...e.attributes);let s={ids:o,name:e.name,startTimeUnixNano:r,attributes:i};return this.mirrorToLocalDebugger(UP({ids:s.ids,name:s.name,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:s.startTimeUnixNano,attributes:s.attributes,status:{code:L1.UNSET}})),s}mirrorToLocalDebugger(e){if(!this.localDebuggerUrl)return;let t=this.redactSpan(e);if(t===null)return;let n=F1([t],this.serviceName,this.serviceVersion);Jme(n,{baseUrl:this.localDebuggerUrl,debug:false,sdkName:this.sdkName});}endSpan(e,t){var n,o;if(e.endTimeUnixNano)return;e.endTimeUnixNano=(n=t?.endTimeUnixNano)!=null?n:hy(),(o=t?.attributes)!=null&&o.length&&e.attributes.push(...t.attributes);let r=t?.status;if(!r&&t?.error!==void 0){let s=t.error instanceof Error?t.error.message:String(t.error);r={code:L1.ERROR,message:s};}let i=UP({ids:e.ids,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:e.attributes,status:r});this.enqueue(i),this.mirrorToLocalDebugger(i);}createSpan(e){var t;let n=k1(e.parent),o=[G("ai.telemetry.metadata.raindrop.eventId",e.eventId)];(t=e.attributes)!=null&&t.length&&o.push(...e.attributes);let r=UP({ids:n,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:o,status:e.status});this.enqueue(r),this.mirrorToLocalDebugger(r);}enqueue(e){if(!this.enabled)return;if(this.debugSpans){let n=o=>o?o.slice(-8):"none";console.log(`${this.prefix}[span] name=${e.name} trace=${n(e.traceId)} span=${n(e.spanId)} parent=${n(e.parentSpanId)}`);}let t=this.redactSpan(e);if(t!==null){if(this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(t),this.queue.length>=this.maxBatchSize){this.flush().catch(()=>{});return}this.timer||(this.timer=setTimeout(()=>{this.timer=void 0,this.flush().catch(()=>{});},this.flushIntervalMs));}}async flush(){if(this.enabled)for(this.timer&&(clearTimeout(this.timer),this.timer=void 0);this.queue.length>0;){let e=this.queue.splice(0,this.maxBatchSize);if(!this.writeKey)continue;let t=F1(e,this.serviceName,this.serviceVersion),n=`${this.baseUrl}traces`;this.debug&&console.log(`${this.prefix} sending traces batch`,{spans:e.length,endpoint:n});let o=ku(n,t,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(o);try{try{await o,this.debug&&console.log(`${this.prefix} sent ${e.length} spans`);}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send ${e.length} spans: ${i}`);}}finally{this.inFlight.delete(o);}}}async shutdown(){this.timer&&(clearTimeout(this.timer),this.timer=void 0),await this.flush(),await Promise.all([...this.inFlight].map(e=>e.catch(()=>{})));}},ohe={};function U1(){return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE}var rhe=class{constructor(){this._stack=[];}isEmpty(){return this._stack.length===0}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},ihe=class{},she=class extends ihe{constructor(){super(),this._fallback=null;let e=U1();if(e){this._storage=new e;return}this._fallback=new rhe,this._storage=this._fallback;}maybeAdoptAsyncLocalStorage(){if(!this._fallback||!this._fallback.isEmpty())return;let e=U1();e&&(this._storage=new e,this._fallback=null);}isReady(){return true}getParentSpanIds(){this.maybeAdoptAsyncLocalStorage();let e=this._storage.getStore();if(!(!e||e===ohe))return {traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId}}runInContext(e,t){return this.maybeAdoptAsyncLocalStorage(),this._storage.run(e,t)}getCurrentSpan(){return this.maybeAdoptAsyncLocalStorage(),this._storage.getStore()}},HP=null;function md(){return HP||(HP=globalThis.RAINDROP_CONTEXT_MANAGER?new globalThis.RAINDROP_CONTEXT_MANAGER:new she),HP}function eW(e,t){return md().runInContext(e,t)}async function Du(){return md().getParentSpanIds()}async function gy(e,t){let n=md(),o={traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId};return n.runInContext(o,t)}async function*ahe(e,t){let n;for(;;){let o=await eW(e,async()=>{try{return await t.next(n)}catch(r){return {value:void 0,done:true,error:r}}});if("error"in o&&o.error!==void 0)throw o.error;if(o.done)return o.value;n=yield o.value;}}globalThis.RAINDROP_ASYNC_LOCAL_STORAGE=AsyncLocalStorage;function pe(e){return typeof e=="object"&&e!==null}function Ar(e){return typeof e=="function"}function H1(e){var t;if(!e||typeof e!="object")return false;if(((t=e.constructor)==null?void 0:t.name)==="Module")return true;try{let o=Object.keys(e);if(o.length===0)return !1;let r=Object.getOwnPropertyDescriptor(e,o[0]);if(!r)return !1;let i="writable"in r?r.writable:!0;return !r.configurable&&!i}catch{return false}}function aE(e){try{return JSON.stringify(e)}catch{return}}function tt(e){try{return JSON.stringify(e,(t,n)=>n instanceof Uint8Array?$P(n):n)}catch{return}}function hE(e){if(typeof e=="string"){let r=e.indexOf("/");return r>0&&r<e.length-1?{provider:e.slice(0,r),modelId:e.slice(r+1)}:{modelId:e}}if(!pe(e))return {};let t=typeof e.provider=="string"?e.provider:void 0,n;if(typeof e.modelId=="string"?n=e.modelId:typeof e.model=="string"&&(n=e.model),!n)return {provider:t};let o=n.indexOf("/");return !t&&o>0&&o<n.length-1?{provider:n.slice(0,o),modelId:n.slice(o+1)}:{provider:t,modelId:n}}function QP(e){if(!pe(e))return;let t=e.text;return typeof t=="string"?t:void 0}function lhe(e){var t;if(!pe(e))return;let n=e.object;if(n!==void 0)return (t=aE(n))!=null?t:String(n)}function che(e){if(typeof e!="function")return false;let t=e.prototype;return pe(t)?typeof t.generate=="function"&&typeof t.stream=="function":false}function XP(e){if(!pe(e))return;let t=e.model;if(typeof t=="string"&&t.length)return t;let n=e.response;if(pe(n)){let o=n.modelId;if(typeof o=="string"&&o.length)return o}}function fy(e){if(pe(e)){if(typeof e.finishReason=="string")return e.finishReason;if(pe(e.finishReason)&&typeof e.finishReason.unified=="string")return e.finishReason.unified}}function G1(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return typeof btoa=="function"?btoa(t):""}function lE(e,t){if(e instanceof URL)return e.toString();if(typeof e=="string")return e.startsWith("data:")||e.startsWith("http://")||e.startsWith("https://")?e:`data:${t};base64,${e}`;if(e instanceof Uint8Array){let n=G1(e);return n?`data:${t};base64,${n}`:void 0}if(e instanceof ArrayBuffer){let n=G1(new Uint8Array(e));return n?`data:${t};base64,${n}`:void 0}}function tW(e){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return `[binary:${e.byteLength} bytes]`;if(e instanceof ArrayBuffer)return `[binary:${e.byteLength} bytes]`}function j1(e){if(typeof e.mediaType=="string")return e.mediaType;if(typeof e.mimeType=="string")return e.mimeType;let t=e.file;if(pe(t)){if(typeof t.mediaType=="string")return t.mediaType;if(typeof t.mimeType=="string")return t.mimeType}}function dhe(e){if(typeof e.filename=="string")return e.filename;if(typeof e.name=="string")return e.name;let t=e.file;if(pe(t)){if(typeof t.filename=="string")return t.filename;if(typeof t.name=="string")return t.name}}function uhe(e){if("data"in e)return e.data;let t=e.file;if(pe(t)){if("file_data"in t)return t.file_data;if("data"in t)return t.data}}function phe(e,t){var n,o,r;let i=e.type;if(typeof i=="string"){if(i==="image"){let s=(n=j1(e))!=null?n:"image/png",a=lE(e.image,s);return a?{type:"image",role:t,value:a}:void 0}if(i==="image_url"){let s=e.image_url,a=pe(s)?s.url:s,l=lE(a,"image/png");return l?{type:"image",role:t,value:l}:void 0}if(i==="file"){let s=j1(e),a=uhe(e),l=s?.startsWith("image/")===true,c=l&&s?lE(a,s):tW(a);if(!c)return;let d=(r=(o=dhe(e))!=null?o:s)!=null?r:"file";return {type:l?"image":"text",role:t,name:d,value:c}}}}function VP(e,t){if(!Array.isArray(e))return;let n=[];for(let o of e){if(!pe(o))continue;let r=phe(o,t);r&&n.push(r);}return n.length?n:void 0}function mhe(e){var t,n,o,r;let i=typeof e.mediaType=="string"?e.mediaType:typeof e.mimeType=="string"?e.mimeType:void 0,s=(r=(o=(n=(t=e.base64Data)!=null?t:e.base64)!=null?n:e.uint8ArrayData)!=null?o:e.uint8Array)!=null?r:e.data,a=i?.startsWith("image/")===true,l=a&&i?lE(s,i):tW(s);if(!l)return;let c=typeof e.filename=="string"?e.filename:typeof e.name=="string"?e.name:i??"file";return {type:a?"image":"text",role:"output",name:c,value:l}}async function hhe(e){let t=e;if(t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function")try{t=await t;}catch{return}if(!Array.isArray(t))return;let n=[];for(let o of t){if(!pe(o))continue;let r=mhe(o);r&&n.push(r);}return n.length?n:void 0}function nW(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t="";for(let n of e)!pe(n)||n.type!=="text"||typeof n.text!="string"||(t+=n.text);return t.length?t:void 0}function ZP(e){let t=e.messages;if(Array.isArray(t))return t;let n=e.prompt;if(Array.isArray(n))return n}function oW(e){let t=ZP(e);if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(pe(o)&&o.role==="user")return o}}function eM(e){var t;if(pe(e))return VP((t=oW(e))==null?void 0:t.content,"input")}async function tM(e){if(!pe(e))return;let t=await hhe(e.files);if(t?.length)return t;let n=gE(e);for(let o=n.length-1;o>=0;o--){let r=n[o];if(!(!pe(r)||r.role!=="assistant"))return VP(r.content,"output")}return VP(e.content,"output")}function nM(e){var t,n;if(!pe(e))return;let o=(t=oW(e))==null?void 0:t.content;if(o===void 0)return;let r=nW(o);return r!==void 0?r:(n=tt(o))!=null?n:String(o)}function oM(e){var t;if(!pe(e))return;let n=e.prompt;if(typeof n=="string")return n;let o=ZP(e);if(Array.isArray(o)&&o.length>0){let i=o[o.length-1];if(pe(i)){let s=i.content,a=nW(s);if(a!==void 0)return a;let l=aE(s);if(l)return l}return (t=aE(o))!=null?t:void 0}let r=e.input;return typeof r=="string"?r:aE(e)}function rM(e){if(!pe(e))return [];let t=[];typeof e.system=="string"&&e.system&&t.push({role:"system",content:e.system});let n=ZP(e);if(Array.isArray(n)){for(let o of n)pe(o)&&typeof o.role=="string"&&t.push(o);return t}return typeof e.prompt=="string"&&e.prompt&&t.push({role:"user",content:e.prompt}),t}function gE(e){if(!pe(e))return [];let t=e.response;if(pe(t)&&Array.isArray(t.messages))return t.messages.filter(o=>pe(o)&&typeof o.role=="string"&&"content"in o).map(o=>o);let n=e.steps;if(Array.isArray(n)&&n.length>0){let o=n[n.length-1];if(pe(o)&&pe(o.response)){let r=o.response.messages;if(Array.isArray(r))return r.filter(i=>pe(i)&&typeof i.role=="string"&&"content"in i).map(i=>i)}}return []}function dE(e){if(typeof e.toolCallId=="string"&&e.toolCallId.length>0)return `id:${e.toolCallId}`;if(typeof e.toolName=="string"&&e.toolName.length>0){let t=tt(e.input);return t!==void 0?`name:${e.toolName}|input:${t}`:`name:${e.toolName}`}}function ghe(e,t){return e.isError===true||e.type==="tool-error"?true:pe(t)&&typeof t.type=="string"?t.type.startsWith("error")||t.type==="execution-denied":false}function fhe(e){if(typeof e=="string"&&e.length>0)return e;if(pe(e)){if(typeof e.value=="string"&&e.value.length>0)return e.value;if(typeof e.reason=="string"&&e.reason.length>0)return e.reason;if(typeof e.message=="string"&&e.message.length>0)return e.message}return tt(e)}function yhe(e){if(!pe(e))return [];let t=e.content;return Array.isArray(t)?t.filter(pe):pe(t)?[t]:[]}function She(e){return "input"in e?e.input:"args"in e?e.args:void 0}function iM(e){let t=e.toolCallId;return typeof t=="string"&&t.length>0?t:void 0}function bhe(e){return "output"in e?e.output:"result"in e?e.result:e.error}function The(e,t,n){var o;if(!t)return;let r=(o=e.get(t))!=null?o:[];r.includes(n)||(r.push(n),e.set(t,r));}function Ahe(e,t){if(!t)return;let n=e.get(t);if(!n||n.length===0)return;let o=n.shift();if(o!==void 0)return n.length===0&&e.delete(t),o}function Ehe(e){var t,n,o,r;let{spans:i,pendingKeysByToolName:s,part:a}=e,l=iM(a),c=typeof a.toolName=="string"?a.toolName:void 0,d=She(a),u=dE({toolCallId:l,toolName:c,input:d});if(!u)return;let p=l==null?dE({toolCallId:void 0,toolName:c,input:void 0}):void 0,m=p&&p!==u?i.get(p):void 0,h=(t=i.get(u))!=null?t:m;i.set(u,{key:u,toolCallId:(n=h?.toolCallId)!=null?n:l,toolName:(o=h?.toolName)!=null?o:c,input:(r=h?.input)!=null?r:d,result:h?.result,status:h?.status,errorMessage:h?.errorMessage}),p&&p!==u&&i.delete(p),!l&&h?.result===void 0&&The(s,c,u);}function Che(e){var t,n,o;let{spans:r,pendingKeysByToolName:i,part:s}=e,a=iM(s),l=typeof s.toolName=="string"?s.toolName:void 0,c=bhe(s),d=dE({toolCallId:a,toolName:l,input:void 0}),u=a!=null?d:(t=Ahe(i,l))!=null?t:d;if(!u)return;let p=r.get(u),m=ghe(s,c);r.set(u,{key:u,toolCallId:(n=p?.toolCallId)!=null?n:a,toolName:(o=p?.toolName)!=null?o:l,input:p?.input,result:c,status:m?"ERROR":"OK",errorMessage:m?fhe(c):void 0});}function rW(e){let t=new Map,n=new Map;for(let o of e)for(let r of yhe(o)){if(r.type==="tool-call"){Ehe({spans:t,pendingKeysByToolName:n,part:r});continue}(r.type==="tool-result"||r.type==="tool-error")&&Che({spans:t,pendingKeysByToolName:n,part:r});}return [...t.values()]}function Rhe(e){if(!Array.isArray(e))return;let t="";for(let n of e)pe(n)&&n.type==="text"&&typeof n.text=="string"&&(t+=n.text);return t.length?t:void 0}function vhe(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!pe(n)||n.type!=="tool-call")continue;let o=iM(n),r=typeof n.toolName=="string"?n.toolName:void 0;(o||r)&&t.push({toolCallId:o,toolName:r,input:n.input});}return t.length?t:void 0}function th(e){if(!pe(e))return;let t=e.experimental_telemetry;if(pe(t))return {functionId:typeof t.functionId=="string"?t.functionId:void 0,isEnabled:typeof t.isEnabled=="boolean"?t.isEnabled:void 0,recordInputs:typeof t.recordInputs=="boolean"?t.recordInputs:void 0,recordOutputs:typeof t.recordOutputs=="boolean"?t.recordOutputs:void 0,metadata:pe(t.metadata)?t.metadata:void 0}}function ys(e,t){return {operationName:`${e}${t?` ${t}`:""}`,resourceName:t}}function iW(e,t){if(t==null)return;if(typeof t=="string")return G(e,t);if(typeof t=="number")return Number.isInteger(t)?We(e,t):Zm(e,t);if(typeof t=="boolean")return $me(e,t);if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return ac(e,t);let n=tt(t);return n?G(e,n):void 0}function fE(e){return e?Object.entries(e).filter(([t])=>!t.startsWith("raindrop.internal.")).map(([t,n])=>iW(`ai.telemetry.metadata.${t==="raindrop.userId"?"raindrop.ai.userId":t}`,n)):[]}function sM(e){return pe(e)?Object.entries(e).filter(([,t])=>typeof t=="string").map(([t,n])=>G(`ai.request.headers.${t}`,n)):[]}function aM(e){if(!pe(e))return [];let t=[],n=["maxRetries","timeout","maxOutputTokens","temperature","topP","topK","presencePenalty","frequencyPenalty","seed","stopSequences"];for(let o of n){if(!(o in e))continue;let r=e[o];o==="stopSequences"&&Array.isArray(r)&&r.every(i=>typeof i=="string")?t.push(ac(`ai.settings.${o}`,r)):o==="timeout"&&typeof r=="number"?t.push(We(`ai.settings.${o}`,r)):t.push(iW(`ai.settings.${o}`,r));}return t}function sW(e){return pe(e)?[Zm("gen_ai.request.frequency_penalty",typeof e.frequencyPenalty=="number"?e.frequencyPenalty:void 0),We("gen_ai.request.max_tokens",typeof e.maxOutputTokens=="number"?e.maxOutputTokens:void 0),Zm("gen_ai.request.presence_penalty",typeof e.presencePenalty=="number"?e.presencePenalty:void 0),...Array.isArray(e.stopSequences)&&e.stopSequences.every(t=>typeof t=="string")?[ac("gen_ai.request.stop_sequences",e.stopSequences)]:[],Zm("gen_ai.request.temperature",typeof e.temperature=="number"?e.temperature:void 0),We("gen_ai.request.top_k",typeof e.topK=="number"?e.topK:void 0),Zm("gen_ai.request.top_p",typeof e.topP=="number"?e.topP:void 0)]:[]}function aW(e){if(!pe(e)||!pe(e.providerOptions))return;let t=tt(e.providerOptions);return t?G("ai.request.providerOptions",t):void 0}var whe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},oE=null;function lW(){if(oE)return oE;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return oE=e?new e:new whe,oE}function lM(){return lW().getStore()}function zP(e,t){return lW().run(e,t)}function cW(e){var t;if(e.length===0)return;let n=e[0];if(!pe(n))return;let o=pe(n.metadata)?n.metadata:void 0,r=pe(n.telemetry)?n.telemetry.metadata:void 0,i=pe(r)?r:void 0,s=th(n),a=s?.metadata&&typeof s.metadata=="object"?s.metadata:void 0,l=(t=o??i)!=null?t:a;if(!l)return;let c={rawMetadata:l},d=l["raindrop.userId"];typeof d=="string"&&d&&(c.userId=d);let u=l["raindrop.eventId"];typeof u=="string"&&u&&(c.eventId=u);let p=l["raindrop.internal.eventIdGenerated"];(p===true||p==="true"||p==="1")&&(c.eventIdGenerated=true);let m=l["raindrop.convoId"];typeof m=="string"&&m&&(c.convoId=m);let h=l["raindrop.eventName"];typeof h=="string"&&h&&(c.eventName=h);let g=l["raindrop.properties"];if(typeof g=="string")try{let f=JSON.parse(g);f&&typeof f=="object"&&(c.properties=f);}catch{}else g&&typeof g=="object"&&(c.properties=g);return c}var Ihe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},rE=null;function cM(){if(rE)return rE;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return rE=e?new e:new Ihe,rE}function WP(){return cM().getStore()}function qP(e){var t;let n=cM();(t=n.enterWith)==null||t.call(n,e);}function dW(){var e;let t=cM();(e=t.enterWith)==null||e.call(t,void 0);}var dM=class{constructor(e){this.callStates=new Map,this.priorParentContexts=new Map,this.onStart=t=>{var n,o,r,i,s;if(t.isEnabled===false)return;let a=t.operationId==="ai.embed"||t.operationId==="ai.embedMany",l=t.recordInputs!==false,c=t.recordOutputs!==false,d=t.functionId,u=t.metadata,p=lM(),m=u??p?.rawMetadata,h=this.extractRaindropMetadata(m),g=md().getParentSpanIds(),f=m?.["raindrop.internal.eventIdGenerated"]==="true"||m?.["raindrop.internal.eventIdGenerated"]===true||p?.eventIdGenerated===true,b=h.eventId&&!f?h.eventId:void 0,T=(i=(r=(o=b??((n=this.defaultContext)==null?void 0:n.eventId))!=null?o:g?.eventId)!=null?r:h.eventId)!=null?i:pd(),A=g&&g.eventId===T?{traceIdB64:g.traceIdB64,spanIdB64:g.spanIdB64}:void 0,{operationName:C,resourceName:v}=ys(t.operationId,d),I=!a&&this.subagentWrapping?WP():void 0,_=!a&&this.subagentWrapping&&I===void 0&&typeof m?.["ash.subagent.name"]=="string"?m["ash.subagent.name"]:void 0,x=(s=I?.toolName)!=null?s:_,E,O;if(x&&this.sendTraces){let H=I?[G("raindrop.parent.callId",I.parentCallId),G("raindrop.parent.toolCallId",I.toolCallId),G("raindrop.parent.toolName",I.toolName)]:[];E=this.traceShipper.startSpan({name:x,parent:A,eventId:T,operationId:"ai.toolCall",attributes:[G("operation.name","ai.toolCall"),G("resource.name",x),G("raindrop.span.kind","tool_call"),G("ai.toolCall.name",x),G("raindrop.subagent.name",x),G("raindrop.agent.role","subagent"),...H]});let U=this.spanParentRef(E),$=this.traceShipper.startSpan({name:"agent.subagent",parent:U,eventId:T,operationId:"agent.subagent",attributes:[G("operation.name","agent.subagent"),G("raindrop.span.kind","llm_call"),G("raindrop.subagent.name",x)]});this.traceShipper.endSpan($),O=U;}let N;if(this.sendTraces){let H=!a&&l?[G("ai.prompt",tt({system:t.system,prompt:t.prompt,messages:t.messages}))]:[],U=a&&l?t.operationId==="ai.embedMany"?[G("ai.values",tt(t.value))]:[G("ai.value",tt(t.value))]:[];N=this.traceShipper.startSpan({name:t.operationId,parent:O??A,eventId:T,operationId:t.operationId,attributes:[G("operation.name",C),G("resource.name",v),G("ai.telemetry.functionId",d),G("ai.model.provider",t.provider),G("ai.model.id",t.modelId),...fE(m?Object.fromEntries(Object.entries(m).filter(([$])=>$!=="raindrop.eventId"&&$!=="raindrop.internal.eventIdGenerated")):void 0),...H,...U]});}this.callStates.set(t.callId,{operationId:t.operationId,eventId:T,rootSpan:N,rootParent:N?this.spanParentRef(N):O??A,stepSpan:void 0,stepParent:void 0,toolSpans:new Map,embedSpans:new Map,parentContextToolCallIds:new Set,recordInputs:l,recordOutputs:c,functionId:d,metadata:m,accumulatedText:"",inputText:a?void 0:this.extractInputText(t),toolCallCount:0,subagentName:x,subagentToolCallSpan:E});},this.onStepStart=t=>{let n=this.getState(t.callId);if(!n?.rootSpan||!n.rootParent)return;let r=n.operationId==="ai.streamText"||n.operationId==="ai.streamObject"?`${n.operationId}.doStream`:`${n.operationId}.doGenerate`,{operationName:i,resourceName:s}=ys(r,n.functionId),a=[];n.recordInputs&&(t.promptMessages&&a.push(G("ai.prompt.messages",tt(t.promptMessages))),t.stepTools&&a.push(ac("ai.prompt.tools",t.stepTools.map(c=>JSON.stringify(c)))),t.stepToolChoice!=null&&a.push(G("ai.prompt.toolChoice",JSON.stringify(t.stepToolChoice))));let l=this.traceShipper.startSpan({name:r,parent:n.rootParent,eventId:n.eventId,operationId:r,attributes:[G("operation.name",i),G("resource.name",s),G("ai.telemetry.functionId",n.functionId),G("ai.model.provider",t.provider),G("ai.model.id",t.modelId),G("gen_ai.system",t.provider),G("gen_ai.request.model",t.modelId),...a]});n.stepSpan=l,n.stepParent=this.spanParentRef(l);},this.onToolExecutionStart=t=>this.toolExecutionStart(t),this.onToolExecutionEnd=t=>this.toolExecutionEnd(t),this.onToolCallStart=t=>this.toolExecutionStart(t),this.onToolCallFinish=t=>this.toolExecutionEnd(t),this.onLanguageModelCallStart=t=>{},this.onLanguageModelCallEnd=t=>{},this.onChunk=t=>{var n,o,r,i,s;let a=(o=t.callId)!=null?o:(n=t.chunk)==null?void 0:n.callId;if(!a)return;let l=this.getState(a);if(!l)return;let c=t.chunk;if(!(!c||typeof c!="object")){if(c.type==="text-delta"){let d=(r=c.textDelta)!=null?r:c.delta;typeof d=="string"&&(l.accumulatedText+=d,this.emitLive(l,"text_delta",d));}else if(c.type==="reasoning"||c.type==="reasoning-delta"){let d=(s=(i=c.textDelta)!=null?i:c.text)!=null?s:c.delta;typeof d=="string"&&this.emitLive(l,"reasoning_delta",d);}}},this.onStepFinish=t=>{var n,o,r,i,s,a,l,c,d;let u=this.getState(t.callId);if(!u?.stepSpan)return;let p=[];if(u.recordOutputs&&(p.push(G("ai.response.finishReason",t.finishReason),G("ai.response.text",(n=t.text)!=null?n:void 0),G("ai.response.id",(o=t.response)==null?void 0:o.id),G("ai.response.model",(r=t.response)==null?void 0:r.modelId),G("ai.response.timestamp",((i=t.response)==null?void 0:i.timestamp)instanceof Date?t.response.timestamp.toISOString():(s=t.response)==null?void 0:s.timestamp),G("ai.response.providerMetadata",t.providerMetadata?tt(t.providerMetadata):void 0)),((a=t.toolCalls)==null?void 0:a.length)>0&&p.push(G("ai.response.toolCalls",JSON.stringify(t.toolCalls.map(h=>({toolCallId:h.toolCallId,toolName:h.toolName,input:h.input}))))),((l=t.reasoning)==null?void 0:l.length)>0)){let h=t.reasoning.filter(g=>"text"in g).map(g=>g.text).join(`
165
165
  `);h&&p.push(G("ai.response.reasoning",h));}p.push(ac("gen_ai.response.finish_reasons",[t.finishReason]),G("gen_ai.response.id",(c=t.response)==null?void 0:c.id),G("gen_ai.response.model",(d=t.response)==null?void 0:d.modelId));let m=t.usage;m&&p.push(We("ai.usage.inputTokens",m.inputTokens),We("ai.usage.outputTokens",m.outputTokens),We("ai.usage.totalTokens",m.totalTokens),We("ai.usage.reasoningTokens",m.reasoningTokens),We("ai.usage.cachedInputTokens",m.cachedInputTokens),We("gen_ai.usage.input_tokens",m.inputTokens),We("gen_ai.usage.output_tokens",m.outputTokens)),this.emitProviderExecutedToolSpans(t,u),this.traceShipper.endSpan(u.stepSpan,{attributes:p}),u.stepSpan=void 0,u.stepParent=void 0;},this.onEmbedStart=t=>{let n=this.getState(t.callId);if(!n?.rootSpan||!n.rootParent)return;let{operationName:o,resourceName:r}=ys(t.operationId,n.functionId),i=n.recordInputs?[G("ai.values",tt(t.values))]:[],s=this.traceShipper.startSpan({name:t.operationId,parent:n.rootParent,eventId:n.eventId,operationId:t.operationId,attributes:[G("operation.name",o),G("resource.name",r),G("ai.telemetry.functionId",n.functionId),...i]});n.embedSpans.set(t.embedCallId,s);},this.onEmbedFinish=t=>{var n;let o=this.getState(t.callId);if(!o)return;let r=o.embedSpans.get(t.embedCallId);if(!r)return;let i=[];o.recordOutputs&&i.push(G("ai.embeddings",tt(t.embeddings))),((n=t.usage)==null?void 0:n.tokens)!=null&&i.push(We("ai.usage.tokens",t.usage.tokens)),this.traceShipper.endSpan(r,{attributes:i}),o.embedSpans.delete(t.embedCallId);},this.onEmbedEnd=t=>this.onEmbedFinish(t),this.onFinish=t=>{let n=this.getState(t.callId);if(!n)return;n.operationId==="ai.embed"||n.operationId==="ai.embedMany"?this.finishEmbed(t,n):this.finishGenerate(t,n),n.subagentToolCallSpan&&this.traceShipper.endSpan(n.subagentToolCallSpan),this.cleanup(t.callId);},this.onEnd=t=>this.onFinish(t),this.onError=t=>{var n;let o=t;if(!o?.callId)return;let r=this.getState(o.callId);if(!r)return;let i=(n=o.error)!=null?n:t;r.stepSpan&&this.traceShipper.endSpan(r.stepSpan,{error:i});for(let s of r.embedSpans.values())this.traceShipper.endSpan(s,{error:i});r.embedSpans.clear();for(let s of r.parentContextToolCallIds)this.priorParentContexts.delete(s);r.parentContextToolCallIds.clear();for(let s of r.toolSpans.values())this.traceShipper.endSpan(s,{error:i});r.toolSpans.clear(),r.rootSpan&&this.traceShipper.endSpan(r.rootSpan,{error:i}),r.subagentToolCallSpan&&this.traceShipper.endSpan(r.subagentToolCallSpan,{error:i}),this.cleanup(o.callId);},this.executeTool=async({callId:t,toolCallId:n,execute:o})=>{let r=this.getState(t),i=r?.toolSpans.get(n);return i?gy({traceIdB64:i.ids.traceIdB64,spanIdB64:i.ids.spanIdB64,eventId:r.eventId},()=>o()):o()},this.traceShipper=e.traceShipper,this.eventShipper=e.eventShipper,this.sendTraces=e.sendTraces!==false,this.sendEvents=e.sendEvents!==false,this.subagentWrapping=e.subagentWrapping!==false,this.debug=e.debug===true,this.defaultContext=e.context;}getState(e){return this.callStates.get(e)}cleanup(e){this.callStates.delete(e);}spanParentRef(e){return {traceIdB64:e.ids.traceIdB64,spanIdB64:e.ids.spanIdB64}}emitLive(e,t,n,o){var r,i,s,a,l,c;if(!cE()||!e.rootSpan)return;let d=this.extractRaindropMetadata(e.metadata);ud({traceId:e.rootSpan.ids.traceIdB64,type:t,content:n,metadata:{userId:(i=d.userId)!=null?i:(r=this.defaultContext)==null?void 0:r.userId,convoId:(a=d.convoId)!=null?a:(s=this.defaultContext)==null?void 0:s.convoId,eventName:(c=d.eventName)!=null?c:(l=this.defaultContext)==null?void 0:l.eventName,eventId:e.eventId,...o}});}extractRaindropMetadata(e){if(!e)return {};let t={},n=e["raindrop.userId"];typeof n=="string"&&n&&(t.userId=n);let o=e["raindrop.eventId"];typeof o=="string"&&o&&(t.eventId=o);let r=e["raindrop.convoId"];typeof r=="string"&&r&&(t.convoId=r);let i=e["raindrop.eventName"];typeof i=="string"&&i&&(t.eventName=i);let s=e["raindrop.properties"];if(typeof s=="string")try{t.properties=JSON.parse(s);}catch{}else s&&typeof s=="object"&&(t.properties=s);return t}extractInputText(e){if(typeof e.prompt=="string")return e.prompt;if(Array.isArray(e.messages))for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(n?.role==="user"){if(typeof n.content=="string")return n.content;if(Array.isArray(n.content)){let o=n.content.find(r=>r?.type==="text"&&typeof r.text=="string");if(o)return o.text}}}}toolExecutionStart(e){let{toolCall:t}=e,n=WP();this.priorParentContexts.set(t.toolCallId,n??null),qP({parentCallId:e.callId,toolCallId:t.toolCallId,toolName:t.toolName});let o=this.getState(e.callId);if(o?.parentContextToolCallIds.add(t.toolCallId),!o?.stepParent)return;let{operationName:r,resourceName:i}=ys("ai.toolCall",o.functionId),s=o.recordInputs?[G("ai.toolCall.args",tt(t.input))]:[],a=this.traceShipper.startSpan({name:"ai.toolCall",parent:o.stepParent,eventId:o.eventId,operationId:"ai.toolCall",attributes:[G("operation.name",r),G("resource.name",i),G("ai.telemetry.functionId",o.functionId),G("ai.toolCall.name",t.toolName),G("ai.toolCall.id",t.toolCallId),...s]});o.toolSpans.set(t.toolCallId,a),this.emitLive(o,"tool_start",t.toolName,{args:t.input});}toolExecutionEnd(e){var t;let n=(t=e.toolCall)==null?void 0:t.toolCallId;if(n&&this.priorParentContexts.has(n)){let i=this.priorParentContexts.get(n);this.priorParentContexts.delete(n),i?qP(i):dW();}let o=this.getState(e.callId);if(!o)return;let r=o.toolSpans.get(e.toolCall.toolCallId);if(r){if(o.toolCallCount+=1,e.success){let i=o.recordOutputs?[G("ai.toolCall.result",tt(e.output))]:[];this.traceShipper.endSpan(r,{attributes:i});}else this.traceShipper.endSpan(r,{error:e.error});this.emitLive(o,"tool_result",e.toolCall.toolName),o.toolSpans.delete(e.toolCall.toolCallId);}}emitProviderExecutedToolSpans(e,t){if(!t.stepParent)return;let n=Array.isArray(e.content)?e.content:[],o=n.filter(i=>i?.type==="tool-call"&&i.providerExecuted===true);if(o.length===0)return;let r=new Map;for(let i of n)(i?.type==="tool-result"||i?.type==="tool-error")&&typeof i.toolCallId=="string"&&r.set(i.toolCallId,i);for(let i of o){let{operationName:s,resourceName:a}=ys("ai.toolCall",t.functionId),l=t.recordInputs?[G("ai.toolCall.args",tt(i.input))]:[],c=this.traceShipper.startSpan({name:"ai.toolCall",parent:t.stepParent,eventId:t.eventId,operationId:"ai.toolCall",attributes:[G("operation.name",s),G("resource.name",a),G("ai.telemetry.functionId",t.functionId),G("ai.toolCall.name",i.toolName),G("ai.toolCall.id",i.toolCallId),G("ai.toolCall.providerExecuted","true"),...l]});t.toolCallCount+=1,this.emitLive(t,"tool_start",i.toolName,{args:i.input});let d=r.get(i.toolCallId);if(d?.type==="tool-error")this.traceShipper.endSpan(c,{error:d.error});else {let u=t.recordOutputs&&d&&"output"in d?[G("ai.toolCall.result",tt(d.output))]:[];this.traceShipper.endSpan(c,{attributes:u});}this.emitLive(t,"tool_result",i.toolName);}}finishGenerate(e,t){var n,o,r,i,s,a,l,c,d,u,p,m,h,g;if(t.rootSpan){let b=[];if(t.recordOutputs&&(b.push(G("ai.response.finishReason",e.finishReason),G("ai.response.text",(n=e.text)!=null?n:void 0),G("ai.response.providerMetadata",e.providerMetadata?tt(e.providerMetadata):void 0)),((o=e.toolCalls)==null?void 0:o.length)>0&&b.push(G("ai.response.toolCalls",JSON.stringify(e.toolCalls.map(A=>({toolCallId:A.toolCallId,toolName:A.toolName,input:A.input}))))),((r=e.reasoning)==null?void 0:r.length)>0)){let A=e.reasoning.filter(C=>"text"in C).map(C=>C.text).join(`
166
166
  `);A&&b.push(G("ai.response.reasoning",A));}let T=(i=e.totalUsage)!=null?i:e.usage;T&&b.push(We("ai.usage.inputTokens",T.inputTokens),We("ai.usage.outputTokens",T.outputTokens),We("ai.usage.totalTokens",T.totalTokens),We("ai.usage.reasoningTokens",T.reasoningTokens),We("ai.usage.cachedInputTokens",T.cachedInputTokens)),b.push(We("ai.toolCall.count",t.toolCallCount)),this.traceShipper.endSpan(t.rootSpan,{attributes:b});}let f=t.subagentName!==void 0&&t.subagentToolCallSpan!==void 0;if(this.sendEvents&&!f){let b=this.extractRaindropMetadata(t.metadata),T=(a=b.userId)!=null?a:(s=this.defaultContext)==null?void 0:s.userId;if(T){let A=(d=(c=b.eventName)!=null?c:(l=this.defaultContext)==null?void 0:l.eventName)!=null?d:t.operationId,C=(u=e.text)!=null?u:t.accumulatedText||void 0,v=t.inputText,I=(p=e.response)==null?void 0:p.modelId,_={...(m=this.defaultContext)==null?void 0:m.properties,...b.properties},x=(g=b.convoId)!=null?g:(h=this.defaultContext)==null?void 0:h.convoId;this.eventShipper.patch(t.eventId,{eventName:A,userId:T,convoId:x,input:v,output:C,model:I,properties:Object.keys(_).length>0?_:void 0,isPending:false}).catch(E=>{this.debug&&console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${E instanceof Error?E.message:E}`);});}}}finishEmbed(e,t){var n;if(!t.rootSpan)return;let o=[],r=t.operationId==="ai.embedMany";t.recordOutputs&&(r?o.push(G("ai.embeddings",tt(e.embedding))):o.push(G("ai.embedding",tt(e.embedding)))),((n=e.usage)==null?void 0:n.tokens)!=null&&o.push(We("ai.usage.tokens",e.usage.tokens)),this.traceShipper.endSpan(t.rootSpan,{attributes:o});}},xhe="__raindrop_report",$1={missing_context:{description:"You cannot complete the task because critical information, credentials, or access is missing and the user cannot provide it. Do NOT report this for normal clarifying questions \u2014 only when you are blocked.",sentiment:"NEGATIVE"},repeatedly_broken_tool:{description:"A tool has failed or not returned the expected response on multiple distinct attempts in this conversation, preventing task completion. A single tool error is NOT enough \u2014 the tool must be persistently broken or aberrantly behaving across retries.",sentiment:"NEGATIVE"},capability_gap:{description:"The task requires a tool, permission, or capability that you do not have. For example, the user asks you to perform an action but no suitable tool exists, or you lack the necessary access. Do NOT report this if you simply need more information from the user \u2014 only when the gap is in your own capabilities.",sentiment:"NEGATIVE"},complete_task_failure:{description:"You were unable to accomplish what the user asked despite making genuine attempts. This might be things like, you genuinely do not have the capabilities the user is asking for. You have tried but run into a persistent bug in the environment etc. This is NOT a refusal or policy block \u2014 you tried and failed to deliver the result.",sentiment:"NEGATIVE"}},_he="You have a diagnostic tool for flagging serious failures for developer review. Only call this when you hit a significant, unrecoverable problem \u2014 not for minor hiccups or routine clarifications. If you can still help the user, do that instead of calling this tool. This tool is invisible to the user \u2014 never mention it or its output.";function eh(e){return typeof e!="string"?void 0:e.trim()||void 0}function Phe(e){if(!e)return $1;let t=Object.entries(e).map(([n,o])=>{var r;let i=n.trim();if(!i||!o||typeof o!="object")return;let s=(r=o.description)==null?void 0:r.trim();if(!s)return;let a=o.sentiment;return [i,{description:s,...a==="POSITIVE"||a==="NEGATIVE"?{sentiment:a}:{}}]}).filter(n=>n!==void 0);return t.length===0?$1:Object.fromEntries(t)}function uW(e){var t,n;let o=Phe(e.signals),r=Object.keys(o),i={},s={};for(let p of r){let m=o[p];m&&(i[p]=m.description,s[p]=m.sentiment);}let a=((t=e.guidance)==null?void 0:t.trim())||"",l=((n=e.toolName)==null?void 0:n.trim())||xhe,c=r.map(p=>{let m=s[p],h=m?` [${m.toLowerCase()}]`:"";return `- ${p}: ${i[p]}${h}`}).join(`
167
167
  `),d=a?`
@@ -193,11 +193,11 @@ Categories:
193
193
  `);if(n<1||n>o.length)return;let r=Math.max(1,n-PW),i=Math.min(o.length,n+PW),s=String(i).length,a=[];for(let l=r;l<=i;l++){let c=l===n?Sge:yge;a.push(`${c}${String(l).padStart(s)} | ${o[l-1]??""}`);}return a.join(`
194
194
  `)}var NW="\r",LW="\x1B[1A",kW="\x1B[J",Ege="\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F",Cge="|/-\\",Rge="#0891b2",vge={pass:{glyph:"\u2713",ascii:"v",paint:Qs.green},fail:{glyph:"\u2718",ascii:"x",paint:Qs.red},skip:{glyph:"\u2212",ascii:"-",paint:Qs.dim},cancel:{glyph:"\u2298",ascii:"o",paint:Qs.yellow},retry:{glyph:"\u21BB",ascii:"~",paint:Qs.yellow}};function Go(e){let t=e.colorLevel>0&&e.isTTY,n=(o,r)=>t?r(o):o;return {unicode:e.unicode,color:t,bold:o=>n(o,Qs.bold),dim:o=>n(o,Qs.gray),code:o=>n(o,Qs.hex(Rge)),spinner:o=>{let r=e.unicode?Ege:Cge,i=(o%r.length+r.length)%r.length;return n(r.charAt(i),Qs.cyan)},statusGlyph:o=>{let r=vge[o],i=e.unicode?r.glyph:r.ascii;return t?r.paint(i):i},separator:e.unicode?" \xB7 ":" | "}}function DW(e,t=""){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-t.length,20),r=[];for(let i of e.split(`
195
195
  `)){let s="";for(let a of i.split(" ")){if(!s.length){s=a;continue}let l=`${s} ${a}`;if(l.length<=o){s=l;continue}r.push(t+s),s=a;}r.push(t+s);}return r.join(`
196
- `)}var Ige={PASS:{glyph:"pass",isTerminal:true},FAIL:{glyph:"fail",isTerminal:true},SKIP:{glyph:"skip",isTerminal:true},CANCEL:{glyph:"cancel",isTerminal:true},RETRY:{glyph:"retry",isTerminal:false}},xge={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function FW(e,t,n=0){let o=xge[e];if(!o)return;let r=Go(t);if(o==="RUNNING")return {badge:r.spinner(n),isTerminal:false};let{glyph:i,isTerminal:s}=Ige[o];return {badge:r.statusGlyph(i),isTerminal:s}}function cc(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function TE({parallel:e,remoteBrowser:t}){let n=cpus$1().length;if(t){if(e<=n*4)return;let o=Math.max(1,n*4-2);R.warn(`Running ${e} workers on a ${n}-core machine with a remote browser. We recommend at most ~${o} workers ((cores \xD7 4) \u2212 2) to avoid local saturation.`);return}n>=e*2||R.warn(`Running ${e} workers on a ${n}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function BW(){let e=A1(),t=[];e.lowMemorySamples>0&&t.push(`memory low ${e.lowMemorySamples}x`),e.highCpuSamples>0&&t.push(`CPU saturated ${e.highCpuSamples}x`),e.highHeapSamples>0&&t.push(`heap near limit ${e.highHeapSamples}x`),t.length!==0&&(R.log(""),R.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var ve=Jm({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"2.138.2"});var Pge=5,Bu=" ";async function AE({getResults:e,checkDone:t,name:n,timeoutMs:o=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<o;){let s;i>Pge&&(R.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{s=await e(),i=0;}catch(c){i++,ve.warn({err:c},"Failed to fetch run status; retrying."),R.warn({err:c},"Failed to fetch run status; retrying."),await new Promise(d=>setTimeout(d,1500*i));continue}if(t(s))return s;let l=Math.max(1e4,Math.floor(o/100));await new Promise(c=>setTimeout(c,l));}R.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(o/1e3)}s).`),process.exit(1);}function UW(e){let t={passed:[],failed:[],cancelled:[],quarantinedPassed:[],quarantinedFailed:[]};for(let n of e)switch(n.status){case "PASSED":(n.quarantined?t.quarantinedPassed:t.passed).push(n);break;case "FAILED":(n.quarantined?t.quarantinedFailed:t.failed).push(n);break;case "CANCELLED":t.cancelled.push(n);break}return t}function _M(e){let t=UW(e),n=t.failed.filter(r=>r.failureDetails?.classification?.action==="heal"),o=t.failed.filter(r=>r.failureDetails?.classification?.action==="warn");return {passed:t.passed.length,failed:t.failed.length,cancelled:t.cancelled.length,quarantinedPassed:t.quarantinedPassed.length,quarantinedFailed:t.quarantinedFailed.length,healElectedFailures:n.length,warnElectedFailures:o.length}}function nh(e,{onlyQuarantined:t=false,overrideExitCode:n=false}={}){let o=n?e.healElectedFailures+e.warnElectedFailures:0,r=e.failed-o,i=t?e.quarantinedFailed:0;return r+i>0||e.cancelled>0}function PM({results:e,startTime:t,getPath:n,getUrl:o,printFailureBody:r,getCancellationReason:i,recoveredCount:s,skippedCount:a,videoRecordingActive:l}){let{passed:c,failed:d,cancelled:u,quarantinedPassed:p,quarantinedFailed:m}=UW(e),h=Xt(),g=h.unicode?"\u2500":"-",f=process.stdout?.columns||80,b=(T,A,C,v)=>{let I=` ${A+1}) ${n(T)} `,_=Math.max(3,f-I.length-2);R.log(""),R.log(C(`${I}${g.repeat(_)}`)),R.log(""),v();let x=o(T);x&&(R.log(""),R.log(`${Bu}${cc(x,h)}`));};xW(()=>{d.forEach((x,E)=>{b(x,E,Qs.red.bold,()=>r?.(x));}),u.forEach((x,E)=>{b(x,d.length+E,Qs.yellow.bold,()=>{let O=i?.(x)??"Cancelled";R.log(`${Bu}${Qs.yellow.bold(O)}`);});});let T=(x,E,O)=>{x.length!==0&&(R.log(""),R.log(` ${O(`${x.length} ${E}`)}`),x.forEach(N=>{R.dimmed(`${Bu}${n(N)}`);}));};T(d,"failed",Qs.red.bold),T(m,"failed",x=>Qs.red.bold(`${x} (quarantined)`)),T(u,"cancelled",Qs.yellow.bold),a&&(R.log(""),R.log(` ${Qs.yellow.bold(`${a} skipped`)}`));let A=c.length+p.length,C=Math.max(1,Math.round((Date.now()-t)/1e3)),v=[];p.length>0&&v.push(`${p.length} quarantined`),s&&s>0&&v.push(`${s} recovered`);let I=v.length>0?` (${v.join(", ")})`:"",_=Mge(e,h,l);R.log(""),R.log(` ${Qs.green.bold(`${A} passed${I} (${C}s)`)}${_}`),BW();});}function EE(e){return PM(e),_M(e.results)}function Mge(e,t,n=false){let o=e.length;if(o===0)return "";let r=e.filter(a=>a.usedRemoteBrowser).length;return r===0?"":`${t.unicode?" \xB7 ":" | "}${r}/${o} ran on remote browser${n?" (video saved async)":""}`}function CE(e){if(!e.failureDetails||!e.failureReason)return;let t=Fa({failureReason:e.failureReason,classification:e.failureDetails.classification,manualClassification:e.failureDetails.manualClassification}),n=t.title??e.failureReason,o=e.failureDetails.classification?.rootCause??t.description??t.title??e.failureReason;R.log(`${Bu}${Qs.red.bold(n)}`),o&&o!==n&&(R.log(""),R.log(DW(o,Bu)));let r=MW({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});r&&(R.log(""),R.log(r));let i=e.failureDetails.classification?.citations;if(i&&i.length>0){R.log(""),R.log(`${Bu}${Qs.bold("Sources:")}`);for(let s of i)R.log(`${Bu} [${s.refId}] ${s.title}`);}}var oh=" ".repeat(6);var Oge=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let r=Object.getOwnPropertyDescriptor(e,n),i=Object.getOwnPropertyDescriptor(t,n);!Nge(r,i)&&o||Object.defineProperty(e,n,i);},Nge=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Lge=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n);},kge=(e,t)=>`/* Wrapped ${e}*/
196
+ `)}var Ige={PASS:{glyph:"pass",isTerminal:true},FAIL:{glyph:"fail",isTerminal:true},SKIP:{glyph:"skip",isTerminal:true},CANCEL:{glyph:"cancel",isTerminal:true},RETRY:{glyph:"retry",isTerminal:false}},xge={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function FW(e,t,n=0){let o=xge[e];if(!o)return;let r=Go(t);if(o==="RUNNING")return {badge:r.spinner(n),isTerminal:false};let{glyph:i,isTerminal:s}=Ige[o];return {badge:r.statusGlyph(i),isTerminal:s}}function cc(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function TE({parallel:e,remoteBrowser:t}){let n=cpus$1().length;if(t){if(e<=n*4)return;let o=Math.max(1,n*4-2);R.warn(`Running ${e} workers on a ${n}-core machine with a remote browser. We recommend at most ~${o} workers ((cores \xD7 4) \u2212 2) to avoid local saturation.`);return}n>=e*2||R.warn(`Running ${e} workers on a ${n}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function BW(){let e=A1(),t=[];e.lowMemorySamples>0&&t.push(`memory low ${e.lowMemorySamples}x`),e.highCpuSamples>0&&t.push(`CPU saturated ${e.highCpuSamples}x`),e.highHeapSamples>0&&t.push(`heap near limit ${e.highHeapSamples}x`),t.length!==0&&(R.log(""),R.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var ve=Jm({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"2.138.3"});var Pge=5,Bu=" ";async function AE({getResults:e,checkDone:t,name:n,timeoutMs:o=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<o;){let s;i>Pge&&(R.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{s=await e(),i=0;}catch(c){i++,ve.warn({err:c},"Failed to fetch run status; retrying."),R.warn({err:c},"Failed to fetch run status; retrying."),await new Promise(d=>setTimeout(d,1500*i));continue}if(t(s))return s;let l=Math.max(1e4,Math.floor(o/100));await new Promise(c=>setTimeout(c,l));}R.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(o/1e3)}s).`),process.exit(1);}function UW(e){let t={passed:[],failed:[],cancelled:[],quarantinedPassed:[],quarantinedFailed:[]};for(let n of e)switch(n.status){case "PASSED":(n.quarantined?t.quarantinedPassed:t.passed).push(n);break;case "FAILED":(n.quarantined?t.quarantinedFailed:t.failed).push(n);break;case "CANCELLED":t.cancelled.push(n);break}return t}function _M(e){let t=UW(e),n=t.failed.filter(r=>r.failureDetails?.classification?.action==="heal"),o=t.failed.filter(r=>r.failureDetails?.classification?.action==="warn");return {passed:t.passed.length,failed:t.failed.length,cancelled:t.cancelled.length,quarantinedPassed:t.quarantinedPassed.length,quarantinedFailed:t.quarantinedFailed.length,healElectedFailures:n.length,warnElectedFailures:o.length}}function nh(e,{onlyQuarantined:t=false,overrideExitCode:n=false}={}){let o=n?e.healElectedFailures+e.warnElectedFailures:0,r=e.failed-o,i=t?e.quarantinedFailed:0;return r+i>0||e.cancelled>0}function PM({results:e,startTime:t,getPath:n,getUrl:o,printFailureBody:r,getCancellationReason:i,recoveredCount:s,skippedCount:a,videoRecordingActive:l}){let{passed:c,failed:d,cancelled:u,quarantinedPassed:p,quarantinedFailed:m}=UW(e),h=Xt(),g=h.unicode?"\u2500":"-",f=process.stdout?.columns||80,b=(T,A,C,v)=>{let I=` ${A+1}) ${n(T)} `,_=Math.max(3,f-I.length-2);R.log(""),R.log(C(`${I}${g.repeat(_)}`)),R.log(""),v();let x=o(T);x&&(R.log(""),R.log(`${Bu}${cc(x,h)}`));};xW(()=>{d.forEach((x,E)=>{b(x,E,Qs.red.bold,()=>r?.(x));}),u.forEach((x,E)=>{b(x,d.length+E,Qs.yellow.bold,()=>{let O=i?.(x)??"Cancelled";R.log(`${Bu}${Qs.yellow.bold(O)}`);});});let T=(x,E,O)=>{x.length!==0&&(R.log(""),R.log(` ${O(`${x.length} ${E}`)}`),x.forEach(N=>{R.dimmed(`${Bu}${n(N)}`);}));};T(d,"failed",Qs.red.bold),T(m,"failed",x=>Qs.red.bold(`${x} (quarantined)`)),T(u,"cancelled",Qs.yellow.bold),a&&(R.log(""),R.log(` ${Qs.yellow.bold(`${a} skipped`)}`));let A=c.length+p.length,C=Math.max(1,Math.round((Date.now()-t)/1e3)),v=[];p.length>0&&v.push(`${p.length} quarantined`),s&&s>0&&v.push(`${s} recovered`);let I=v.length>0?` (${v.join(", ")})`:"",_=Mge(e,h,l);R.log(""),R.log(` ${Qs.green.bold(`${A} passed${I} (${C}s)`)}${_}`),BW();});}function EE(e){return PM(e),_M(e.results)}function Mge(e,t,n=false){let o=e.length;if(o===0)return "";let r=e.filter(a=>a.usedRemoteBrowser).length;return r===0?"":`${t.unicode?" \xB7 ":" | "}${r}/${o} ran on remote browser${n?" (video saved async)":""}`}function CE(e){if(!e.failureDetails||!e.failureReason)return;let t=Fa({failureReason:e.failureReason,classification:e.failureDetails.classification,manualClassification:e.failureDetails.manualClassification}),n=t.title??e.failureReason,o=e.failureDetails.classification?.rootCause??t.description??t.title??e.failureReason;R.log(`${Bu}${Qs.red.bold(n)}`),o&&o!==n&&(R.log(""),R.log(DW(o,Bu)));let r=MW({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});r&&(R.log(""),R.log(r));let i=e.failureDetails.classification?.citations;if(i&&i.length>0){R.log(""),R.log(`${Bu}${Qs.bold("Sources:")}`);for(let s of i)R.log(`${Bu} [${s.refId}] ${s.title}`);}}var oh=" ".repeat(6);var Oge=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let r=Object.getOwnPropertyDescriptor(e,n),i=Object.getOwnPropertyDescriptor(t,n);!Nge(r,i)&&o||Object.defineProperty(e,n,i);},Nge=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Lge=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n);},kge=(e,t)=>`/* Wrapped ${e}*/
197
197
  ${t}`,Dge=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Fge=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Bge=(e,t,n)=>{let o=n===""?"":`with ${n.trim()}() `,r=kge.bind(null,o,t.toString());Object.defineProperty(r,"name",Fge);let{writable:i,enumerable:s,configurable:a}=Dge;Object.defineProperty(e,"toString",{value:r,writable:i,enumerable:s,configurable:a});};function MM(e,t,{ignoreNonConfigurable:n=false}={}){let{name:o}=e;for(let r of Reflect.ownKeys(t))Oge(e,t,r,n);return Lge(e,t),Bge(e,t,o),e}var RE=new WeakMap,HW=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0,r=e.displayName||e.name||"<anonymous>",i=function(...s){if(RE.set(i,++o),o===1)n=e.apply(this,s),e=void 0;else if(t.throw===true)throw new Error(`Function \`${r}\` can only be called once`);return n};return MM(i,e),RE.set(i,o),i};HW.callCount=e=>{if(!RE.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return RE.get(e)};var GW=HW;var Uu=[];Uu.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Uu.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Uu.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var vE=e=>!!e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function",OM=Symbol.for("signal-exit emitter"),NM=globalThis,Uge=Object.defineProperty.bind(Object),LM=class{emitted={afterExit:false,exit:false};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(NM[OM])return NM[OM];Uge(NM,OM,{value:this,writable:false,enumerable:false,configurable:false});}on(t,n){this.listeners[t].push(n);}removeListener(t,n){let o=this.listeners[t],r=o.indexOf(n);r!==-1&&(r===0&&o.length===1?o.length=0:o.splice(r,1));}emit(t,n,o){if(this.emitted[t])return false;this.emitted[t]=true;let r=false;for(let i of this.listeners[t])r=i(n,o)===true||r;return t==="exit"&&(r=this.emit("afterExit",n,o)||r),r}},wE=class{},Hge=e=>({onExit(t,n){return e.onExit(t,n)},load(){return e.load()},unload(){return e.unload()}}),kM=class extends wE{onExit(){return ()=>{}}load(){}unload(){}},DM=class extends wE{#s=FM.platform==="win32"?"SIGINT":"SIGHUP";#n=new LM;#e;#r;#p;#t={};#i=false;constructor(t){super(),this.#e=t,this.#t={};for(let n of Uu)this.#t[n]=()=>{let o=this.#e.listeners(n),{count:r}=this.#n,i=t;if(typeof i.__signal_exit_emitter__=="object"&&typeof i.__signal_exit_emitter__.count=="number"&&(r+=i.__signal_exit_emitter__.count),o.length===r){this.unload();let s=this.#n.emit("exit",null,n),a=n==="SIGHUP"?this.#s:n;s||t.kill(t.pid,a);}};this.#p=t.reallyExit,this.#r=t.emit;}onExit(t,n){if(!vE(this.#e))return ()=>{};this.#i===false&&this.load();let o=n?.alwaysLast?"afterExit":"exit";return this.#n.on(o,t),()=>{this.#n.removeListener(o,t),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload();}}load(){if(!this.#i){this.#i=true,this.#n.count+=1;for(let t of Uu)try{let n=this.#t[t];n&&this.#e.on(t,n);}catch{}this.#e.emit=(t,...n)=>this.#m(t,...n),this.#e.reallyExit=t=>this.#o(t);}}unload(){this.#i&&(this.#i=false,Uu.forEach(t=>{let n=this.#t[t];if(!n)throw new Error("Listener not defined for signal: "+t);try{this.#e.removeListener(t,n);}catch{}}),this.#e.emit=this.#r,this.#e.reallyExit=this.#p,this.#n.count-=1);}#o(t){return vE(this.#e)?(this.#e.exitCode=t||0,this.#n.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(t,...n){let o=this.#r;if(t==="exit"&&vE(this.#e)){typeof n[0]=="number"&&(this.#e.exitCode=n[0]);let r=o.call(this.#e,t,...n);return this.#n.emit("exit",this.#e.exitCode,null),r}else return o.call(this.#e,t,...n)}},FM=globalThis.process,{onExit:jW}=Hge(vE(FM)?new DM(FM):new kM);var $W=ra.stderr.isTTY?ra.stderr:ra.stdout.isTTY?ra.stdout:void 0,Gge=$W?GW(()=>{jW(()=>{$W.write("\x1B[?25h");},{alwaysLast:true});}):()=>{},VW=Gge;var xE=false,rh={};rh.show=(e=ra.stderr)=>{e.isTTY&&(xE=false,e.write("\x1B[?25h"));};rh.hide=(e=ra.stderr)=>{e.isTTY&&(VW(),xE=true,e.write("\x1B[?25l"));};rh.toggle=(e,t)=>{e!==void 0&&(xE=e),xE?rh.show(t):rh.hide(t);};var BM=rh;var Ty=nx(UM());function HM(){return ra.platform!=="win32"?ra.env.TERM!=="linux":!!ra.env.CI||!!ra.env.WT_SESSION||!!ra.env.TERMINUS_SUBLIME||ra.env.ConEmuTask==="{cmd::Cmder}"||ra.env.TERM_PROGRAM==="Terminus-Sublime"||ra.env.TERM_PROGRAM==="vscode"||ra.env.TERM==="xterm-256color"||ra.env.TERM==="alacritty"||ra.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var $ge={info:Qs.blue("\u2139"),success:Qs.green("\u2714"),warning:Qs.yellow("\u26A0"),error:Qs.red("\u2716")},Vge={info:Qs.blue("i"),success:Qs.green("\u221A"),warning:Qs.yellow("\u203C"),error:Qs.red("\xD7")},zge=HM()?$ge:Vge,by=zge;function GM({onlyFirst:e=false}={}){let t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}var Wge=GM();function jM(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Wge,"")}function $M({stream:e=process.stdout}={}){return !!(e&&e.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function VM(){let{env:e}=ra,{TERM:t,TERM_PROGRAM:n}=e;return ra.platform!=="win32"?t!=="linux":!!e.WT_SESSION||!!e.TERMINUS_SUBLIME||e.ConEmuTask==="{cmd::Cmder}"||n==="Terminus-Sublime"||n==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var qge=3,zM=class{#s=0;start(){this.#s++,this.#s===1&&this.#n();}stop(){if(this.#s<=0)throw new Error("`stop` called more times than `start`");this.#s--,this.#s===0&&this.#e();}#n(){ra.platform==="win32"||!ra.stdin.isTTY||(ra.stdin.setRawMode(true),ra.stdin.on("data",this.#r),ra.stdin.resume());}#e(){ra.stdin.isTTY&&(ra.stdin.off("data",this.#r),ra.stdin.pause(),ra.stdin.setRawMode(false));}#r(t){t[0]===qge&&ra.emit("SIGINT");}},Kge=new zM,WM=Kge;nx(UM());var qM=class{#s=0;#n=false;#e=0;#r=-1;#p=0;#t;#i;#o;#m;#g;#c;#d;#u;#f;#a;#l;color;constructor(t){typeof t=="string"&&(t={text:t}),this.#t={color:"cyan",stream:ra.stderr,discardStdin:true,hideCursor:true,...t},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#o=this.#t.stream,this.#c=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:$M({stream:this.#o}),this.#d=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:false,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,ra.env.NODE_ENV==="test"&&(this._stream=this.#o,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#s},set(n){this.#s=n;}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#r}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}));}get indent(){return this.#u}set indent(t=0){if(!(t>=0&&Number.isInteger(t)))throw new Error("The `indent` option must be an integer from 0 and up");this.#u=t,this.#h();}get interval(){return this.#g??this.#i.interval??100}get spinner(){return this.#i}set spinner(t){if(this.#r=-1,this.#g=void 0,typeof t=="object"){if(t.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#i=t;}else if(!VM())this.#i=Ty.default.line;else if(t===void 0)this.#i=Ty.default.dots;else if(t!=="default"&&Ty.default[t])this.#i=Ty.default[t];else throw new Error(`There is no built-in spinner named '${t}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#f}set text(t=""){this.#f=t,this.#h();}get prefixText(){return this.#a}set prefixText(t=""){this.#a=t,this.#h();}get suffixText(){return this.#l}set suffixText(t=""){this.#l=t,this.#h();}get isSpinning(){return this.#m!==void 0}#y(t=this.#a,n=" "){return typeof t=="string"&&t!==""?t+n:typeof t=="function"?t()+n:""}#S(t=this.#l,n=" "){return typeof t=="string"&&t!==""?n+t:typeof t=="function"?n+t():""}#h(){let t=this.#o.columns??80,n=this.#y(this.#a,"-"),o=this.#S(this.#l,"-"),r=" ".repeat(this.#u)+n+"--"+this.#f+"--"+o;this.#e=0;for(let i of jM(r).split(`
198
198
  `))this.#e+=Math.max(1,Math.ceil(N3(i,{countAnsiEscapeCodes:true})/t));}get isEnabled(){return this.#c&&!this.#d}set isEnabled(t){if(typeof t!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#c=t;}get isSilent(){return this.#d}set isSilent(t){if(typeof t!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#d=t;}frame(){let t=Date.now();(this.#r===-1||t-this.#p>=this.interval)&&(this.#r=++this.#r%this.#i.frames.length,this.#p=t);let{frames:n}=this.#i,o=n[this.#r];this.color&&(o=Qs[this.color](o));let r=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",i=typeof this.text=="string"?" "+this.text:"",s=typeof this.#l=="string"&&this.#l!==""?" "+this.#l:"";return r+o+i+s}clear(){if(!this.#c||!this.#o.isTTY)return this;this.#o.cursorTo(0);for(let t=0;t<this.#s;t++)t>0&&this.#o.moveCursor(0,-1),this.#o.clearLine(1);return (this.#u||this.lastIndent!==this.#u)&&this.#o.cursorTo(this.#u),this.lastIndent=this.#u,this.#s=0,this}render(){return this.#d?this:(this.clear(),this.#o.write(this.frame()),this.#s=this.#e,this)}start(t){return t&&(this.text=t),this.#d?this:this.#c?this.isSpinning?this:(this.#t.hideCursor&&BM.hide(this.#o),this.#t.discardStdin&&ra.stdin.isTTY&&(this.#n=true,WM.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#o.write(`- ${this.text}
199
199
  `),this)}stop(){return this.#c?(clearInterval(this.#m),this.#m=void 0,this.#r=0,this.clear(),this.#t.hideCursor&&BM.show(this.#o),this.#t.discardStdin&&ra.stdin.isTTY&&this.#n&&(WM.stop(),this.#n=false),this):this}succeed(t){return this.stopAndPersist({symbol:by.success,text:t})}fail(t){return this.stopAndPersist({symbol:by.error,text:t})}warn(t){return this.stopAndPersist({symbol:by.warning,text:t})}info(t){return this.stopAndPersist({symbol:by.info,text:t})}stopAndPersist(t={}){if(this.#d)return this;let n=t.prefixText??this.#a,o=this.#y(n," "),r=t.symbol??" ",i=t.text??this.text,a=typeof i=="string"?(r?" ":"")+i:"",l=t.suffixText??this.#l,c=this.#S(l," "),d=o+r+a+c+`
200
- `;return this.stop(),this.#o.write(d),this}};function Ay(e){return new qM(e)}async function Jr(e,t){let{text:n,screen:o}=e;if(!o.isTTY)return t();let r=Ay({text:n,stream:process.stdout,discardStdin:false}).start();try{let i=await t();return r.stop(),i}catch(i){throw r.fail(),i}}var QW=En__default.join(tmpdir(),"momenticBrowserInstallation");var OE=["chrome","chromium","chrome-for-testing","ffmpeg"],NE=OE.filter(e=>e!=="ffmpeg"),rfe={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"};function XW(e){switch(e){case "chromium":return "Chromium";case "chrome":return "Google Chrome";case "chrome-for-testing":return "Chrome for Testing";default:throw new InvalidArgumentError$2(`Allowed choices are ${NE.join(", ")}.`)}}var ZW={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function LE(e){if(e==="Org Default")return false;let t=ZW[rfe[e]],n=registry.findExecutable(t);return !n||n.installType==="none"?false:KM(n)}function KM(e){let t=e.executablePath();return Mo__default.existsSync(t)}function ife(e,t){let n=ZW[e],o=registry.findExecutable(n);if(!o||o.installType==="none")throw new Error(`Requested install of unknown browser type ${e}`);if(!(!t&&KM(o)))return o}async function sfe({browser:e,force:t,screen:n}){let o=ife(e,t);if(!o){R.dimmed(`Browser '${e}' is already installed.`);return}try{await Jr({text:`Installing browser '${e}'\u2026`,screen:n},async()=>{await registry.installDeps([o],!1),await registry.install([o],!1);}),R.success(`Installed browser '${e}'`);}catch(r){if(!Q(r).includes("Lock file is already being held"))throw r;let i=5*60*1e3,s=Date.now();await Jr({text:`Waiting for another process to finish installing '${e}'\u2026`,screen:n},async()=>{for(;Date.now()-s<i&&!KM(o);)await new Promise(a=>setTimeout(a,5e3));}),R.success(`Installed browser '${e}'`);}}async function afe(e){if(platform()==="win32")try{await Jr({text:"Installing Windows dependencies for Playwright\u2026",screen:e},async()=>{await program.parseAsync(["","","install","winldd"]);}),R.success("Installed Windows dependencies");}catch(t){ve.warn({err:t},"Failed to install Windows dependencies"),R.warn(`Failed to install Windows dependencies: ${Q(t)}. Continuing with browser installation.`);}}async function e2({rawBrowsers:e,force:t=false,all:n=false}){let o=Xt();await afe(o);let r=n?OE:Array.from(new Set(e));try{await JW.lock(QW,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}});}catch(s){ve.warn({err:s},"Failed to acquire browser install lock"),R.warn(`Could not acquire the browser install lock within 5 minutes: ${Q(s)}. Continuing without installation.`);return}let i;try{for(let s of r)try{await sfe({browser:s,force:t,screen:o});}catch(a){i=yu(a),ve.error({err:a,browser:s},"Failed to install browser"),R.error(`Failed to install the ${s} browser: ${Q(a)}.`);}}finally{await JW.unlock(QW,{realpath:false});}if(i)throw i}async function kE(e,t,n=30){for(let o=0;o<n;o+=1){let r=e+o;if(await cfe(r))return r}R.error(`Could not find an available port for ${t} starting from ${e} after ${n} attempts.`),process.exit(1);}async function cfe(e){return new Promise(t=>{let n=createServer$1();n.once("error",o=>{if(("code"in o?o.code:void 0)==="EADDRINUSE"){t(false);return}R.warn({err:o},"Unexpected error checking for open ports; continuing."),n.close(),t(true);}),n.once("listening",()=>{n.close(()=>{t(true);});}),n.listen(e);})}function t2(e){pfe(e),mfe();}function pfe(e){dfe((t,n)=>{console.warn(`Detected the NodeJS event loop was blocked for ${t.toFixed(0)}ms. This can cause the CLI to hang.`);let o=n.join(`
200
+ `;return this.stop(),this.#o.write(d),this}};function Ay(e){return new qM(e)}async function Jr(e,t){let{text:n,screen:o}=e;if(!o.isTTY)return t();let r=Ay({text:n,stream:process.stdout,discardStdin:false}).start();try{let i=await t();return r.stop(),i}catch(i){throw r.fail(),i}}var QW=En__default.join(tmpdir(),"momenticBrowserInstallation");var OE=["chrome","chromium","chrome-for-testing","ffmpeg"],NE=OE.filter(e=>e!=="ffmpeg"),rfe={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"};function XW(e){switch(e){case "chromium":return "Chromium";case "chrome":return "Google Chrome";case "chrome-for-testing":return "Chrome for Testing";default:throw new InvalidArgumentError$2(`Allowed choices are ${NE.join(", ")}.`)}}var ZW={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function LE(e){if(e==="Org Default")return false;let t=ZW[rfe[e]],n=registry.findExecutable(t);return !n||n.installType==="none"?false:KM(n)}function KM(e){let t=e.executablePath();return Mo__default.existsSync(t)}function ife(e){let t=ZW[e],n=registry.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${e}`);return n}async function sfe({browser:e,force:t,screen:n}){let o=ife(e),r=!t&&KM(o);try{await Jr({text:r?`Verifying browser '${e}'\u2026`:`Installing browser '${e}'\u2026`,screen:n},async()=>{r||await registry.installDeps([o],!1),await registry.install([o],t);}),r?R.dimmed(`Browser '${e}' is already installed.`):R.success(`Installed browser '${e}'`);}catch(i){if(!Q(i).includes("Lock file is already being held"))throw i;let s=5*60*1e3,a=Date.now();await Jr({text:`Waiting for another process to finish installing '${e}'\u2026`,screen:n},async()=>{for(;Date.now()-a<s&&!KM(o);)await new Promise(l=>setTimeout(l,5e3));}),r?R.dimmed(`Browser '${e}' is already installed.`):R.success(`Installed browser '${e}'`);}}async function afe(e){if(platform()==="win32")try{await Jr({text:"Installing Windows dependencies for Playwright\u2026",screen:e},async()=>{await program.parseAsync(["","","install","winldd"]);}),R.success("Installed Windows dependencies");}catch(t){ve.warn({err:t},"Failed to install Windows dependencies"),R.warn(`Failed to install Windows dependencies: ${Q(t)}. Continuing with browser installation.`);}}async function e2({rawBrowsers:e,force:t=false,all:n=false}){let o=Xt();await afe(o);let r=n?OE:Array.from(new Set(e));try{await JW.lock(QW,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}});}catch(s){ve.warn({err:s},"Failed to acquire browser install lock"),R.warn(`Could not acquire the browser install lock within 5 minutes: ${Q(s)}. Continuing without installation.`);return}let i;try{for(let s of r)try{await sfe({browser:s,force:t,screen:o});}catch(a){i=yu(a),ve.error({err:a,browser:s},"Failed to install browser"),R.error(`Failed to install the ${s} browser: ${Q(a)}.`);}}finally{await JW.unlock(QW,{realpath:false});}if(i)throw i}async function kE(e,t,n=30){for(let o=0;o<n;o+=1){let r=e+o;if(await cfe(r))return r}R.error(`Could not find an available port for ${t} starting from ${e} after ${n} attempts.`),process.exit(1);}async function cfe(e){return new Promise(t=>{let n=createServer$1();n.once("error",o=>{if(("code"in o?o.code:void 0)==="EADDRINUSE"){t(false);return}R.warn({err:o},"Unexpected error checking for open ports; continuing."),n.close(),t(true);}),n.once("listening",()=>{n.close(()=>{t(true);});}),n.listen(e);})}function t2(e){pfe(e),mfe();}function pfe(e){dfe((t,n)=>{console.warn(`Detected the NodeJS event loop was blocked for ${t.toFixed(0)}ms. This can cause the CLI to hang.`);let o=n.join(`
201
201
  `);console.warn(o),e.warn({stack:o,time:t},"NodeJS event loop blocked");},{threshold:1e3,trimFalsePositives:true});}function mfe(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let e=process._getActiveHandles();console.log("Active handles:",e.map(t=>t.constructor?.name));}ufe(),setImmediate(()=>{setTimeout(()=>{process.exit(1);},2e3).unref();});});}function n2(e){let t=e?.shardIndex??1,n=e?.shardCount??1;if(t<1)throw new Error("Shard index must be greater than 0.");if(n<1)throw new Error("Shard count must be greater than 0.");if(t>n)throw new Error("Shard index cannot be greater than shard count")}function hfe(e,t,n,o){if(n>e.length&&(R.warn(`Shard count ${n} is greater than the number of tests ${e.length}! Some workers won't have any tests to run.`),t>n))return [];let r=Math.floor((t-1)*(e.length/n)),i=Math.floor(t*(e.length/n));return (o?[...e].sort((a,l)=>o(a).localeCompare(o(l))):[...e].sort()).slice(r,i)}function o2(e){let{items:t,shardIndex:n,shardCount:o,sortKey:r}=e;return o>1?hfe(t,n,o,r):t}function Ey({disableCache:e,saveCache:t,regenerateCache:n,bustOldestCachePercentage:o}){if(e&&n)throw new Error("--disable-cache and --regenerate-cache cannot be used together.");if(e&&t)throw new Error("--disable-cache and --save-cache cannot be used together.");return {regenerateCache:n??false,alwaysSaveCache:t??false,noCache:e??false,bustOldestCachePercentage:o}}function ffe(e){let t=e[0],n=e[1];return (t==="before"||t==="steps"||t==="after")&&typeof n=="number"?{stepList:t,stepIndex:n,field:e.slice(2).map(String).join(".")}:typeof t=="number"?{stepList:void 0,stepIndex:t,field:e.slice(1).map(String).join(".")}:{stepList:void 0,stepIndex:void 0,field:e.map(String).join(".")}}function FE(e,t,n){for(let o of e){let{stepList:r,stepIndex:i,field:s}=ffe(o.path);n.push({file:t,stepList:r,stepIndex:i,field:s,issue:o.message,nodePath:o.path});}}function ih(e,t,n){return e instanceof lm?(FE(e.zodIssues,t,n),true):false}function sh({parsingErrors:e,parsingErrorDetails:t,failedTestFilePaths:n,failedModuleFilePaths:o,rootDir:r}){if(R.log(""),R.error(`Found ${e} file${e===1?"":"s"} with validation errors that must be fixed manually.`),t.length>0){let i=new Map;for(let s of t){let a=i.get(s.file)??[];a.push(s),i.set(s.file,a);}for(let[s,a]of i)R.log(""),R.log(` ${Qs.underline(s)}`),Sfe({file:s,errors:a,rootDir:r});R.log("");return}r2("test",n),r2("module",o);}function yfe({stepList:e,stepIndex:t,field:n}){if(t===void 0)return n||"(file)";let o=`${e??"steps"}[${t}]`;return n?`${o}.${n}`:o}function Sfe({file:e,errors:t,rootDir:n}){let o=n!==void 0?bE(En__default.resolve(n,e)):void 0,r=t.map(a=>({error:a,position:o&&a.nodePath?OW(o,a.nodePath):void 0})),i=Math.max(0,...r.map(({position:a})=>a?`${a.line}:${a.col}`.length:0));bfe(r).forEach(({startOffset:a,errors:l},c)=>{c>0&&R.log("");for(let{error:d,position:u}of l){let p=u?Qs.dim(`${u.line}:${u.col}`.padStart(i)):" ".repeat(i);R.log(` ${p} ${Qs.red("error")} ${d.issue} ${Qs.dim(yfe(d))}`);}if(a!==void 0&&o){let d=IM(o,a);d&&(R.log(""),R.log(d));}});}function bfe(e){let t=[],n=new Map;for(let o of e){let r=o.position?.startOffset;if(r===void 0){t.push({errors:[o]});continue}let i=n.get(r);if(i){i.push(o);continue}let s=[o];n.set(r,s),t.push({startOffset:r,errors:s});}return t}function r2(e,t){if(!(!t||t.size===0)){R.dimmed(` Failed ${e} files:`);for(let n of t)R.dimmed(`${oh}- ${n}`);}}var YM=[],i2=false,Tfe=once(async({reason:e,logger:t,exitCode:n})=>{t.info({reason:e,exitCode:n},"Exiting process"),YM.push(async()=>$A(),async()=>gt.flush(),async()=>XA()),await Re(Promise.allSettled(YM.toReversed().map(o=>o(e,t))),{milliseconds:5e3,fallback:()=>{}}),process.exit(n);}),gd=once((e,t)=>{let n=({exitCode:o,logger:r,reason:i})=>{if(i2){r.info({reason:i},"Shutdown already in progress; ignoring signal");return}i2=true,Tfe({reason:i,logger:r,exitCode:o});};process.on("SIGINT",()=>n({reason:"SIGINT",logger:e,exitCode:0})),process.on("SIGTERM",()=>n({reason:"SIGTERM",logger:e,exitCode:0})),t&&(process.on("uncaughtException",o=>{e.error({err:o},"Uncaught exception, shutting down"),n({reason:"uncaughtException",logger:e,exitCode:1});}),process.on("unhandledRejection",o=>{e.error({reason:o},"Unhandled rejection, shutting down"),n({reason:"unhandledRejection",logger:e,exitCode:1});}));});function dc(e){YM.push(e);}function a2(e){return e instanceof Error?"code"in e&&e.code==="EPIPE"?true:e.message.includes("EPIPE"):false}function l2(e){return e instanceof Error?e.name==="AbortError":false}function c2(e){return e instanceof Error?e.message.includes("Target page, context or browser has been closed"):false}function d2(e){return !(e instanceof Error)||!e.stack?false:e.stack.includes(fA)}var Efe=[".mp4",".mov",".webm"];function p2(e,t){if(t)try{let n=Mo__default.readdirSync(t);for(let o of n)Efe.some(i=>o.endsWith(i))&&(Mo__default.unlinkSync(En__default.join(t,o)),e.info({file:o},"Deleted video artifact for passing test"));}catch(n){e.warn({err:n},"Failed to delete video artifacts for passing test");}}var Hu=3.1783027;function Cfe(e){let t=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);!(o>=48&&o<=57)&&!(o>=65&&o<=90)&&!(o>=97&&o<=122)&&t++;}return t}function nt(e){return Math.ceil(JM(e)/Hu)}function JM(e){let t=0;if(typeof e=="string"){let n=e;n=n.replaceAll(`
202
202
  `,""),n=n.replaceAll(" ","");let o=Cfe(n);return n.length-o+Hu*o}if(typeof e>"u"||e===null)return 0;if(typeof e=="number")return String(e).length;if(Array.isArray(e))return e.forEach(n=>{t+=JM(n);}),t;if(typeof e=="object"){let n=e;return n.type==="image"||n.type==="image-data"||(n.type==="media"||n.type==="file"||n.type==="file-data")&&"data"in n&&"mediaType"in n&&typeof n.mediaType=="string"&&n.mediaType.startsWith("image/")?1600*Hu:(Object.keys(n).forEach(o=>{t+=String(o).length,o==="image_url"?(n[o]??{}).detail==="high"?t+=1105*Hu:t+=85*Hu:o==="source"&&typeof n[o]=="object"&&n[o]?.type==="base64"?t+=1600*Hu:t+=JM(n[o]);}),t)}if(typeof e=="boolean")return e?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof e}': ${e}`)}var Cy=class{diff(t,n,o={}){let r;typeof o=="function"?(r=o,o={}):"callback"in o&&(r=o.callback);let i=this.castInput(t,o),s=this.castInput(n,o),a=this.removeEmpty(this.tokenize(i,o)),l=this.removeEmpty(this.tokenize(s,o));return this.diffWithOptionsObj(a,l,o,r)}diffWithOptionsObj(t,n,o,r){var i;let s=T=>{if(T=this.postProcess(T,o),r){setTimeout(function(){r(T);},0);return}else return T},a=n.length,l=t.length,c=1,d=a+l;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));let u=(i=o.timeout)!==null&&i!==void 0?i:1/0,p=Date.now()+u,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],n,t,0,o);if(m[0].oldPos+1>=l&&h+1>=a)return s(this.buildValues(m[0].lastComponent,n,t));let g=-1/0,f=1/0,b=()=>{for(let T=Math.max(g,-c);T<=Math.min(f,c);T+=2){let A,C=m[T-1],v=m[T+1];C&&(m[T-1]=void 0);let I=false;if(v){let x=v.oldPos-T;I=v&&0<=x&&x<a;}let _=C&&C.oldPos+1<l;if(!I&&!_){m[T]=void 0;continue}if(!_||I&&C.oldPos<v.oldPos?A=this.addToPath(v,true,false,0,o):A=this.addToPath(C,false,true,1,o),h=this.extractCommon(A,n,t,T,o),A.oldPos+1>=l&&h+1>=a)return s(this.buildValues(A.lastComponent,n,t))||true;m[T]=A,A.oldPos+1>=l&&(f=Math.min(f,T-1)),h+1>=a&&(g=Math.max(g,T+1));}c++;};if(r)(function T(){setTimeout(function(){if(c>d||Date.now()>p)return r(void 0);b()||T();},0);})();else for(;c<=d&&Date.now()<=p;){let T=b();if(T)return T}}addToPath(t,n,o,r,i){let s=t.lastComponent;return s&&!i.oneChangePerToken&&s.added===n&&s.removed===o?{oldPos:t.oldPos+r,lastComponent:{count:s.count+1,added:n,removed:o,previousComponent:s.previousComponent}}:{oldPos:t.oldPos+r,lastComponent:{count:1,added:n,removed:o,previousComponent:s}}}extractCommon(t,n,o,r,i){let s=n.length,a=o.length,l=t.oldPos,c=l-r,d=0;for(;c+1<s&&l+1<a&&this.equals(o[l+1],n[c+1],i);)c++,l++,d++,i.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:false,removed:false});return d&&!i.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:false,removed:false}),t.oldPos=l,c}equals(t,n,o){return o.comparator?o.comparator(t,n):t===n||!!o.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let o=0;o<t.length;o++)t[o]&&n.push(t[o]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return false}buildValues(t,n,o){let r=[],i;for(;t;)r.push(t),i=t.previousComponent,delete t.previousComponent,t=i;r.reverse();let s=r.length,a=0,l=0,c=0;for(;a<s;a++){let d=r[a];if(d.removed)d.value=this.join(o.slice(c,c+d.count)),c+=d.count;else {if(!d.added&&this.useLongestToken){let u=n.slice(l,l+d.count);u=u.map(function(p,m){let h=o[c+m];return h.length>p.length?h:p}),d.value=this.join(u);}else d.value=this.join(n.slice(l,l+d.count));l+=d.count,d.added||(c+=d.count);}}return r}};var QM=class extends Cy{constructor(){super(...arguments),this.tokenize=Rfe;}equals(t,n,o){return o.ignoreWhitespace?((!o.newlineIsToken||!t.includes(`
203
203
  `))&&(t=t.trim()),(!o.newlineIsToken||!n.includes(`
@@ -248,7 +248,7 @@ ${u}`,{cause:d})}i=qy({testV2:l,testName:En__default.basename(e,".test.yaml")});
248
248
  ${z.prettifyError(s)}`:`: ${Q(s)}`;R.warn(`Project config at ${e} does not match the required schema${a}`);return}let o=deletedDiff(t,n),r=FY(o,"");r.length>0&&R.warn(`Momentic config file at ${e} contains unrecognized keys: ${r.join(", ")}. These keys will be ignored.`);let i=Zbe(n);return tTe(t)&&i.push("ai.classification.categories"),i.length>0&&R.warn(`Momentic config file at ${e} sets cloud-managed AI settings (${i.join(", ")}) that are configured in the Momentic dashboard and ignored locally. Remove them from this file.`),n}function nTe(e){let t=DY(e,"workspace configuration");if(t!==void 0)try{return Wbe.parse(t)}catch(n){R.warn(`Possible Momentic workspace configuration file at ${e} does not adhere to the required schema: ${Q(n)}`);return}}function oTe(){let e=[],t=cwd(),n=En__default.parse(t).root,o=15,r=0;for(;r<o;){r++;let i=En__default.basename(t);if(jO.includes(i))return R.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),e;for(let s of readdirSync(t))if(s.endsWith(pl)){let a=En__default.join(t,s),l=ZO(a);l&&e.push({configFilePath:a,config:l,rootDir:dirname(a)});}if(e.length)return e;if(t=En__default.dirname(t),t===n)break}return e}async function an(e={}){let{configFilePath:t,nameFilter:n,skipExitOnError:o}=e,r=await eN(t,o);if(n&&(r=r.filter(i=>i.config.name===n)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
249
249
  ${r.map(i=>i.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return R.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}async function rTe(e){let t=nTe(e);if(!t||!t.projects||!t.projects.length)return;let n=t.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${pl}`)),o=AbortSignal.timeout(2e3),r;try{r=await gc(n,{cwd:cwd(),maxDepth:Jy,ignore:[],nodir:!0,signal:o});}catch(s){throw R.error({err:s},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${Xy} is misconfigured.`),s}let i=[];for(let s of r){let a=En__default.join(cwd(),s),l=ZO(a);l&&i.push({configFilePath:a,config:l,rootDir:dirname(a)});}return i}async function eN(e,t){if(e){e=En__default.resolve(e);let o=ZO(e);return o?[{config:o,configFilePath:e,rootDir:En__default.dirname(e)}]:(console.error(`No valid Momentic project file found at ${e}.`),t||process.exit(1),[])}if(existsSync(Xy)){let o=await rTe(Xy);if(o)return o}return oTe()}function Sc(e,t){let n=Sy.stringify(e);writeFileSync(t,n);}async function aa({project:e,apiClient:t,classificationOverrides:n}){let{classification:o,healing:r,explore:i}=(await t.getOrgSettings()).ai??{},s=sTe({flags:n,config:e.config.ai?.classification,cloudConfig:o}),a=iTe({config:e.config.ai?.triage,cloudConfig:r}),l={...e.config.ai};return delete l.healing,delete l.triage,{...e,config:{...e.config,ai:{...l,classification:s,triage:a,explore:i}}}}function iTe({config:e,cloudConfig:t}){if(!(!e&&!t))return {onHealFail:e?.onHealFail??t?.onFail??mx,onHealSuccess:e?.onHealSuccess??t?.onSuccess??hx,exitCodeOnHeal:e?.exitCodeOnHeal,remoteBrowser:e?.remoteBrowser}}function sTe({flags:e,config:t,cloudConfig:n}){if(!(!t&&!n))return {enabled:t?.enabled??n?.enabled??false,overrideExitCode:e?.overrideExitCode??t?.overrideExitCode??n?.overrideExitCode??R0,categories:n?.categories??Ur}}var BY="golden/visual-diff",UY="reports",la="test-results";var aTe=z.object({width:z.number(),height:z.number()}),Ph=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(t,n,o){let r=En__default.join(t.rootDir,t.config.goldenFileDir??BY);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=o,this.apiClient=n;}async prepareGoldenScreenshotForComparison(t,n,o){if(a0(n.screenshot?.data))return {buffer:(await this.apiClient.fetchOnDemandScreenshot(n.screenshot.data.id)).data,width:n.screenshot.width,height:n.screenshot.height};if(n.screenshot?.data?.startsWith("https://")){let s=await fetch(n.screenshot.data);return {buffer:Buffer.from(await s.arrayBuffer()),width:n.screenshot.width,height:n.screenshot.height}}let r=n.screenshot?.data;r||(r=En__default.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let i=`${r}.metadata.json`;if(this.regenerateGoldenFiles)return Mo__default.mkdirSync(En__default.dirname(r),{recursive:true}),Mo__default.writeFileSync(r,o.buffer),Mo__default.writeFileSync(i,JSON.stringify({width:o.width,height:o.height})),{buffer:Buffer.from(o.buffer),width:o.width,height:o.height};if(Mo__default.existsSync(r)){let s=Mo__default.readFileSync(r),a=aTe.parse(JSON.parse(Mo__default.readFileSync(i,"utf-8")));return {buffer:s,width:a.width,height:a.height}}else throw new Y("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${r}`)}};var HY=3e3,Jt=Zy(),dTe=promisify(execFile);async function rN(e,t){try{return await Zy(e).revparse(t)}catch(n){if($Y(n))return;throw n}}async function tp(e){return rN(e,["--show-toplevel"])}async function GY(e){return rN(e,["HEAD"])}async function jY(e){return rN(e,["--abbrev-ref","HEAD"])}async function UC({cwd:e,base:t,head:n,logger:o}){try{let r=(await Zy(e).raw(["merge-base",t,n])).trim();if(r.length>0)return r;o.warn({base:t,head:n},"git merge-base returned empty");}catch(r){o.warn({err:r,base:t,head:n},"git merge-base failed");}}function iN(){return process.env.GITHUB_BASE_REF||process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH||process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME||void 0}async function eS({client:e,repository:t,base:n,head:o,logger:r}){let i=Io(t);if(i)try{let s=await e.compareCommitsFromGithub({owner:i.owner,repo:i.repo,base:n,head:o});return s.commits.length===0?void 0:s}catch(s){r.warn({err:s,repository:t,base:n,head:o},"remote commit compare failed");return}}async function Es(e){let{logger:t,operation:n,fn:o,context:r}=e,i=Date.now();try{return await o()}finally{let s=Date.now()-i;s>HY&&!process.env.CI&&t.warn({operation:n,durationMs:s,thresholdMs:HY,...r??{}},"[timing] slow git metadata operation");}}function ml(e){if(e)try{let t=new Date(e);return isNaN(t.getTime())?void 0:t}catch{return}}async function uTe(e){let t=await Zt(e,Jt.raw(["config","--list"])),n={};if(!t)return n;for(let o of t.split(`
250
250
  `)){let r=o.indexOf("=");if(r===-1)continue;let i=o.slice(0,r),s=o.slice(r+1).trim();n[i]=s;}return n}async function pTe(e,t,n){try{let r=n["github.user"]||void 0;if(r)return r}catch{}let o;try{if(t?.startsWith("http://")||t?.startsWith("https://"))o=new URL(t).host;else if(t?.startsWith("git@")){let r=t.indexOf("@"),i=t.indexOf(":",r+1);r!==-1&&i!==-1&&(o=t.slice(r+1,i));}}catch{}if(o=o?.toLowerCase(),!!o&&t?.startsWith("git@")&&o.includes("github"))try{let{stdout:r,stderr:i}=await dTe("ssh",["-T","-o","BatchMode=yes",`git@${o}`],{timeout:5e3}),a=`${r??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(a?.[1])return a[1]}catch{return}}async function mTe(e,t,n){let o=t?.includes("github.com"),r=t?.includes("gitlab.com");try{if(o)return pTe(e,t,n);if(r)return}catch{}}function tS(e){if(e.startsWith("git@")){let t=e.split(":");if(t.length===2){let n=t[1].replace(".git","").split("/");if(n.length===2){let o=n[0],r=n[1];return `${o}/${r}`}}}else if(e.startsWith("http")||e.startsWith("https")){let n=new URL(e).pathname.split("/").filter(Boolean);if(n.length>=2){let o=n[0],r=n[1].replace(".git","");return `${o}/${r}`}}}function $Y(e){if(!(e instanceof Error))return false;let t=e.message;return t.includes("not a git repository")||t.includes("ENOENT")||t.includes("detected dubious ownership")}async function Zt(e,t){try{return (await t).trim()}catch(n){if($Y(n))return;e.error({err:n},"Failed to run git command");return}}async function Wi(e,t){if(e)try{return (await Zy(t).revparse([e]))?.trim()||void 0}catch{return}}async function nS(e){let t=await Wi(e);return t||await Wi(`origin/${e}`)}function hTe(){if(process.env.GITHUB_ACTION)return "GithubActions";if(process.env.GITLAB_CI)return "GitlabCI";if(process.env.CIRCLECI)return "CircleCI";if(process.env.BUILDKITE)return "Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return "AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return "GCPCloudBuild";if(process.env.BITRISE_BUILD_SLUG)return "Bitrise";if(process.env.MOMENTIC_GIT_OVERRIDE)return "Custom"}async function gTe(e){let[t,n,o]=await Promise.all([Zt(e,Jt.show(["--no-patch","--format=%ci"])),Zt(e,Jt.show(["-s","--pretty=%B"])),Zt(e,Jt.show(["-s","--pretty=%an"]))]),r=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return {ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:t?ml(t):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:r,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function fTe(e){let[t,n,o]=await Promise.all([Zt(e,Jt.listRemote(["--get-url","origin"])),Zt(e,Jt.show(["-s","--pretty=%B"])),Zt(e,Jt.show(["-s","--pretty=%an"]))]);return {ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?ml(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:t,gitCommitMessage:n,gitCommitAuthorName:o,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function yTe(e){let[t,n,o,r]=await Promise.all([Zt(e,Jt.show(["--no-patch","--format=%ci"])),Zt(e,Jt.listRemote(["--get-url","origin"])),Zt(e,Jt.show(["-s","--pretty=%B"])),Zt(e,Jt.show(["-s","--pretty=%an"]))]),s=process.env.CIRCLE_REPOSITORY_URL?.trim()||void 0||n||void 0,a=s?.includes("github.com")??false,l=s?.includes("gitlab.com")??false,c=s?tS(s):void 0;return {ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:t?ml(t):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:s,gitCommitMessage:o,gitCommitAuthorName:r,githubRepository:a?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function STe(e){let[t,n,o]=await Promise.all([Zt(e,Jt.show(["--no-patch","--format=%ci"])),Zt(e,Jt.show(["-s","--pretty=%B"])),Zt(e,Jt.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,i=r?.includes("github.com"),s=r?.includes("gitlab.com"),a=r?tS(r):void 0;return {ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:t?ml(t):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:r,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?a:void 0,gitlabProjectPath:s?a:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function bTe(e){let[t,n,o]=await Promise.all([Zt(e,Jt.show(["--no-patch","--format=%ci"])),Zt(e,Jt.show(["-s","--pretty=%B"])),Zt(e,Jt.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],i=r?.includes("github.com"),s=r?.includes("gitlab.com"),a=r?tS(r):void 0;return {ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:t?ml(t):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:r,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?a:void 0,gitlabProjectPath:s?a:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function TTe(e,t,n){let[o,r,i,s,a,l,c,d,u]=await Promise.all([Zt(e,Jt.revparse(["HEAD"])),Zt(e,Jt.revparse(["--short","HEAD"])),Zt(e,Jt.revparse(["--abbrev-ref","HEAD"])),Zt(e,Jt.listRemote(["--get-url","origin"])),Zt(e,Jt.show(["--no-patch","--format=%ci"])),Zt(e,Jt.show(["-s","--pretty=%B"])),Zt(e,Jt.show(["-s","--pretty=%an"])),t?Zt(e,Jt.raw(["merge-base","--fork-point",t])):Promise.resolve(void 0),uTe(e)]),p=d||(t?await Zt(e,Jt.raw(["merge-base",t,"HEAD"])):void 0),m=p?await Zt(e,Jt.show(["--no-patch","--format=%ci",p])):void 0,h=s?.includes("github.com"),g=s?.includes("gitlab.com"),f=s?tS(s):void 0,b=u["user.email"]||void 0,T=u["user.name"]||void 0,A=u["user.username"]||void 0,C=u["github.user"]||void 0,_=(n?.includeHostingUsername??true?await mTe(e,s,u):void 0)??A??C??void 0;return {ciProvider:"none",gitCommitSha:o,gitCommitShaShort:r,gitBranchName:i,gitOriginUrl:s,gitCommitTimestamp:a?ml(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:_,gitLocalEmail:b,gitLocalName:T,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?ml(m):void 0,githubRepository:h?f:void 0,gitlabProjectPath:g?f:void 0,pipelineId:void 0}}async function ATe(e){let[t,n]=await Promise.all([Zt(e,Jt.show(["--no-patch","--format=%ci"])),Zt(e,Jt.show(["-s","--pretty=%an"]))]),o=process.env.GIT_REPOSITORY_URL,r=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?tS(o):void 0;return {ciProvider:"Bitrise",gitCommitSha:process.env.BITRISE_GIT_COMMIT,gitCommitShaShort:process.env.BITRISE_GIT_COMMIT?.slice(0,6),gitCommitTimestamp:t?ml(t):void 0,gitBranchName:process.env.BITRISE_GIT_BRANCH,gitOriginUrl:o,gitCommitMessage:process.env.BITRISE_GIT_MESSAGE,gitCommitAuthorName:n,githubRepository:r?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BITRISE_APP_SLUG}:${process.env.BITRISE_BUILD_SLUG}`}}async function ETe(){let e=process.env._HEAD_REPO_URL;return {ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:e?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:e?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}function CTe(){return {ciProvider:"Custom",gitCommitSha:process.env.GIT_COMMIT_SHA,gitCommitShaShort:process.env.GIT_COMMIT_SHA_SHORT??process.env.GIT_COMMIT_SHA?.slice(0,6),gitCommitTimestamp:ml(process.env.GIT_COMMIT_TIMESTAMP),gitBranchName:process.env.GIT_BRANCH_NAME,gitOriginUrl:process.env.GIT_ORIGIN_URL,gitCommitAuthorName:process.env.GIT_COMMIT_AUTHOR_NAME,gitCommitMessage:process.env.GIT_COMMIT_MESSAGE,lastCommitOnMainSha:process.env.LAST_COMMIT_ON_MAIN_SHA,lastCommitOnMainTimestamp:ml(process.env.LAST_COMMIT_ON_MAIN_TIMESTAMP),mergedGitBranchName:process.env.MERGED_GIT_BRANCH_NAME,githubRepository:process.env.GITHUB_REPOSITORY,gitlabProjectPath:process.env.GITLAB_PROJECT_PATH,gitLocalUsername:process.env.GIT_USERNAME,gitLocalEmail:process.env.GIT_EMAIL,gitLocalName:process.env.GIT_NAME}}async function RTe(e){let t=[...e.config.gitProtectedBranches??[]];return e.config.gitMainBranch&&t.push(e.config.gitMainBranch),{gitMainBranch:e.config.gitMainBranch,gitProtectedBranches:t}}async function Cs(e,t,n){let o=hTe();if(!o)return TTe(e,t,n);switch(o){case "GithubActions":return gTe(e);case "GitlabCI":return fTe(e);case "CircleCI":return yTe(e);case "Buildkite":return STe(e);case "AzureDevOps":return bTe(e);case "GCPCloudBuild":return ETe();case "Bitrise":return ATe(e);case "Custom":return CTe()}}async function vTe(e,t,n,o){let r=o,i=o.gitCommitSha;if(!i)return r;let s=o.gitMainBranch;if(s&&(!r.lastCommitOnMainSha||!r.lastCommitOnMainTimestamp))try{let a=await Es({logger:e,operation:"getRemoteMetadataFromGitlab.getMergeBaseCommitFromGitlab",fn:()=>t.getMergeBaseCommitFromGitlab(n,s,i),context:{projectPath:n,mainBranch:s}});r={...r,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date};}catch(a){e.warn({err:a},"Failed to get merge base commit from Gitlab");}if(!r.gitCommitTimestamp||!r.gitCommitAuthorName||!r.gitCommitMessage||!r.gitCommitAuthorName)try{let a=await Es({logger:e,operation:"getRemoteMetadataFromGitlab.getCommitFromGitlab",fn:()=>t.getCommitFromGitlab(n,i),context:{projectPath:n,gitCommitSha:i}});a&&(r={...r,gitCommitTimestamp:r.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:r.gitCommitAuthorName??a.author.name,gitCommitMessage:r.gitCommitMessage??a.message});}catch(a){e.warn({err:a},"Failed to get commit from Gitlab");}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!r.mergedGitBranchName){let a=o.gitBranchName;try{let l=await Es({logger:e,operation:"getRemoteMetadataFromGitlab.getMergedBranchFromGitlab",fn:()=>t.getMergedBranchFromGitlab(n,a,i),context:{projectPath:n,branchName:a,gitCommitSha:i}});l.mergedBranch&&(r={...r,mergedGitBranchName:l.mergedBranch});}catch(l){e.warn({err:l},"Failed to get merged branch from Gitlab");}}return r}async function wTe(e,t,n,o,r){let i=r,s=r.gitCommitSha;if(!s)return i;let a=r.gitMainBranch;if(a&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let l=await Es({logger:e,operation:"getRemoteMetadataFromGitHub.getMergeBaseCommitFromGithub",fn:()=>t.getMergeBaseCommitFromGithub(n,o,a,s),context:{owner:n,repo:o,mainBranch:a}});i={...i,lastCommitOnMainSha:l.sha,lastCommitOnMainTimestamp:l.committer.date};}catch(l){e.warn({err:l},"Failed to get merge base commit from GitHub");}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let l=await Es({logger:e,operation:"getRemoteMetadataFromGitHub.getCommitFromGithub",fn:()=>t.getCommitFromGithub(n,o,s),context:{owner:n,repo:o,gitCommitSha:s}});l&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??l.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??l.author.name,gitCommitMessage:i.gitCommitMessage??l.message});}catch(l){e.warn({err:l},"Failed to get commit from GitHub");}if(r.gitBranchName&&r.gitBranchName===r.gitMainBranch&&!i.mergedGitBranchName){let l=r.gitBranchName;try{let c=await Es({logger:e,operation:"getRemoteMetadataFromGitHub.getMergedBranchFromGithub",fn:()=>t.getMergedBranchFromGithub(n,o,l,s),context:{owner:n,repo:o,branchName:l,gitCommitSha:s}});c.mergedBranch&&(i={...i,mergedGitBranchName:c.mergedBranch});}catch(c){e.warn({err:c},"Failed to get merged branch from GitHub");}}return i}async function ITe(e,t,n){try{if(n.githubRepository){let{owner:o,repo:r}=gj(n.githubRepository);return await Es({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>wTe(e,t,o,r,n),context:{githubRepository:n.githubRepository}})}else if(n.gitlabProjectPath){let o=n.gitlabProjectPath;return await Es({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>vTe(e,t,o,n),context:{gitlabProjectPath:o}})}}catch(o){e.warn({err:o},"Failed to get remote git metadata");}return n}async function xTe(e,t,n,o){let r={},i={gitMainBranch:n.config.gitMainBranch};return Es({logger:e,operation:"getGitMetadata.total",fn:async()=>{let[s,a]=await Promise.all([Es({logger:e,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>RTe(n),context:{projectConfigPath:n.configFilePath}}),Es({logger:e,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let d=await Cs(e,n.config.gitMainBranch,o);return i.ciProvider=d.ciProvider,d},context:i})]),l={...s,...a};r.gitBranchName=l.gitBranchName,r.githubRepository=l.githubRepository,r.gitlabProjectPath=l.gitlabProjectPath,(!l.lastCommitOnMainSha||!l.lastCommitOnMainTimestamp)&&l.gitBranchName===s.gitMainBranch&&(l.lastCommitOnMainSha=l.gitCommitSha,l.lastCommitOnMainTimestamp=l.gitCommitTimestamp);let c=await Es({logger:e,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>ITe(e,t,l),context:{githubRepository:l.githubRepository,gitlabProjectPath:l.gitlabProjectPath,gitBranchName:l.gitBranchName}});return {...s,...a,...c}},context:r})}async function VY(e){try{let t=await Zy(e).remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function zY(){try{return (await Jt.revparse(["--is-inside-work-tree"])).trim()==="true"}catch{return false}}var oN=new Map;async function _Te(e,t,n){let o,r;try{[o,r]=await Promise.all([Zt(e,Jt.raw(["symbolic-ref","--short","-q","HEAD"]).then(a=>a.trim())),Zt(e,Jt.revparse(["--verify","HEAD"]).then(a=>a.trim()))]);}catch{return}if(!o||!r)return;let i=`${t.configFilePath}:${t.config.gitMainBranch}:${t.config.gitProtectedBranches?.join(",")}`,s=`${n?.includeHostingUsername}`;return `${o}:${r}:${i}:${s}`}async function Rr(e,t,n,o){let r=await _Te(e,n,o);if(r&&oN.has(r))return e.debug("Using cached git metadata"),oN.get(r);let i=await xTe(e,t,n,o);return r&&oN.set(r,i),i}var MTe=1024*1024;async function GC({cwd:e,baseRef:t="HEAD"}){let n=Zy(await VC(e)),[o,r]=await Promise.all([n.diff(["--name-only","--diff-filter=ACDMRTUXB",t,"--"]),n.raw(["ls-files","--others","--exclude-standard"])]);return OTe(sN([...WY(o),...WY(r)]))}function OTe(e){return e.filter(KY)}function KY(e){let t=np.basename(e);return e.endsWith(".test.yaml")||e.endsWith(".module.yaml")||t===pl||t===Xy}async function jC({cwd:e,paths:t,maxFileSizeBytes:n=MTe}){let o=await VC(e),r=[];for(let i of sN(t)){let s=NTe({repoRoot:o,relativePath:i});if(!KY(i))throw new Error(`Pull request path is not a Momentic file: ${i}`);let a=await promises.stat(s).catch(()=>{});if(!a){r.push({operation:"delete",path:i});continue}if(!a.isFile())throw new Error(`Cannot create pull request change for non-file path: ${i}`);if(a.size>n)throw new Error(`Cannot create pull request change for oversized file: ${i}`);let l=await promises.readFile(s,"utf8");if(l.includes("\0"))throw new Error(`Cannot create pull request change for binary file: ${i}`);r.push({operation:"upsert",path:i,content:l});}return r}async function $C({cwd:e,paths:t,baseRef:n="HEAD",maxFileSizeBytes:o}){let r=await VC(e),i=sN(t??await GC({cwd:r,baseRef:n}));if(i.length===0)return "";let a=(await jC({cwd:r,paths:i,maxFileSizeBytes:o})).filter(c=>c.operation==="upsert").map(c=>c.path),l=await promises.mkdtemp(np.join(PTe.tmpdir(),"momentic-git-patch-"));try{let c=Zy(r).env("GIT_INDEX_FILE",np.join(l,"index"));return await c.raw(["read-tree",n]),a.length>0&&await c.raw(["add","--intent-to-add","--",...a]),await c.raw(["diff","--binary","--",...i])}finally{await promises.rm(l,{recursive:true,force:true});}}async function YY({cwd:e,paths:t,baseBranch:n,baseCommitSha:o,headBranch:r,branchPrefix:i,idempotencyKey:s,commitMessage:a,title:l,body:c,reviewers:d,draft:u,coAuthorRange:p,maxFileSizeBytes:m}){let h=await VC(e),g=await jC({cwd:h,paths:t??await GC({cwd:h,baseRef:o}),maxFileSizeBytes:m}),f=n??await jY(h);if(!f)throw new _e(`Cannot determine base branch because git is not usable in '${h}'.`);let b=o??await GY(h);if(!b)throw new _e(`Cannot determine base commit SHA because git is not usable in '${h}'.`);return {baseBranch:f,baseCommitSha:b,headBranch:r,branchPrefix:i,idempotencyKey:s,commitMessage:a,title:l,body:c,changes:g,reviewers:d,draft:u,coAuthorRange:p}}function WY(e){return e?e.split(`
251
- `).filter(t=>t.length>0):[]}function sN(e){return [...new Set(e)]}async function VC(e){let t=await tp(e);if(!t)throw new _e(`Cannot find a git repository at '${e}'. Install git and run this from inside a git worktree.`);return t}function NTe({repoRoot:e,relativePath:t}){if(!t||np.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let n=np.resolve(e),o=np.resolve(n,t);if(o!==n&&!o.startsWith(`${n}${np.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var JY=new Set([".DS_Store","__MACOSX"]),QY={status:(e,t)=>{if(e.status===t.status)return e.status;if(e.status==="FAILED"||t.status==="FAILED")return "FAILED";if(e.status==="CANCELLED"||t.status==="CANCELLED")return "CANCELLED";if(e.status==="RETRYING"||t.status==="RETRYING")return "RETRYING";if(e.status==="RUNNING"||t.status==="RUNNING")return "RUNNING";if(e.status==="PENDING"||t.status==="PENDING")return "PENDING";throw new Error(`Invalid run status merge: ${e.status} and ${t.status}`)},startedAt:(e,t)=>e.startedAt<t.startedAt?e.startedAt:t.startedAt,updatedAt:(e,t)=>e.updatedAt>t.updatedAt?e.updatedAt:t.updatedAt,finishedAt:(e,t)=>!e.finishedAt||!t.finishedAt?new Date:e.finishedAt>t.finishedAt?e.finishedAt:t.finishedAt,gitCommitTimestamp:(e,t)=>{if(!(!e&&!t)){if(!e.gitCommitTimestamp||!t.gitCommitTimestamp||e.gitCommitTimestamp.getTime()!==t.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${e.gitCommitTimestamp} and ${t.gitCommitTimestamp}`);return e.gitCommitTimestamp}},pipelineId:(e,t)=>e.pipelineId===t.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:e.startedAt<t.startedAt?t.pipelineId:e.pipelineId,labels:(e,t)=>{let n=new Set([...e.labels??[],...t.labels??[]]);return Array.from(n)},ai:(e,t)=>e.ai??t.ai,browser:(e,t)=>e.browser??t.browser,aiSelect:(e,t)=>{let n=[...e.aiSelect??[],...t.aiSelect??[]];return n.length>0?n:void 0},healRiskSummary:()=>{}};function kTe(e,t,n){if(QY[n]){let i=QY[n];return i(e,t)}let o=e[n],r=t[n];if(o===void 0)return r;if(r===void 0)return o;if(o!==r)throw new Error(`Metadata values for key "${n}" do not match: "${o}" vs "${r}"`);return o}var aN=class extends Error{constructor(t,n){let o=`${t} contains invalid Momentic results: ${n}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(o),this.name="InvalidMomenticResultsPathError";}};function XY(e,t){try{let n=En__default.join(t,Ze);return fs.parse(JSON.parse(Mo__default.readFileSync(n,"utf-8")))}catch{throw new aN(e,t)}}function ZY(e,t,n){let o=randomUUID(),r=e.child({runGroupId:o});Mo__default.rmSync(t,{recursive:true,force:true});let i=Mo__default.readdirSync(n).filter(l=>!JY.has(l)).map(l=>En__default.join(n,l));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);Mo__default.mkdirSync(t,{recursive:true});let s={...XY(n,i[0]),id:o,healRiskSummary:void 0,aiSelect:void 0};for(let l of i){let c=En__default.join(l,wn);if(!Mo__default.existsSync(c))continue;let d=XY(n,l);r.info({oldRunGroupId:d.id},"Merging run groups");for(let p in d){if(p==="id")continue;let m=p;s[m]=kTe(s,d,m);}let u=Mo__default.readdirSync(c);for(let p of u){if(JY.has(p))continue;let m=En__default.join(c,p),h=En__default.join(t,wn,p);Mo__default.cpSync(m,h,{recursive:true});}}let a=En__default.join(t,Ze);Mo__default.writeFileSync(a,JSON.stringify(s,null,2));}var fe="v1",lN="cli",op="2.138.2";var DTe=9e4,FTe=3,BTe=1500,UTe=15e3,Fn=class extends Error{status;rawError;constructor(t,n,o,r={}){super(o,r),this.status=t,this.rawError=n;}},cN=class extends _e{constructor(t,n={}){super(t,n),this.name="PlanLimitExceededError";}};async function HTe(e){return e.text().then(t=>{try{return JSON.parse(t).error}catch{return t}})}var dN=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(){let t={"Content-Type":"application/json"};return (t[DA]=op),(t[iz]=lN),t}async sendRequest(t,n){let{retries:o=FTe,requestTimeoutMs:r=DTe,initialRetryDelayMs:i=BTe,maxRetryDelayMs:s=UTe,onFailedRequest:a}=n,l=o,c=o,d,u={path:t,baseUrl:this.baseUrl,method:n.method};for(;l>0;)try{return l--,await this.sendSingleRequestWithOTEL(t,n,r)}catch(p){d=p;try{a?.(d);}catch{}if(p instanceof Fn&&p.status>=400&&p.status<500)throw p.status===402?new cN(p.rawError,{cause:p}):p;if(p instanceof Error&&p.name==="AbortError"&&(d=new cd),l===0)throw d;let m=c-l,h=Math.min(i*Math.pow(2,m-1),s);await new Promise(g=>setTimeout(g,h));}throw this.logger.warn({...u,err:d},"Got fatal error response from Momentic server"),d}async sendSingleRequestWithOTEL(t,n,o){let r=GTe(t);return it({name:`cli.api.${n.method.toLowerCase()}.${r}`,serviceName:"api-server",attributes:{"http.request.method":n.method,"url.path":r},fn:i=>this.sendSingleRequestHelper(t,n,o,s=>{i?.setAttribute("http.response.status_code",s);})})}async sendSingleRequestHelper(t,n,o,r){let i={path:t,baseUrl:this.baseUrl,method:n.method},s=new AbortController,a=setTimeout(()=>s.abort(),o),l=()=>s.abort();n.signal&&n.signal.addEventListener("abort",l,{once:true});let c=Date.now(),d={...this.getHeaders(),...n.extraHeaders};try{let u=await fetch(`${this.baseUrl}${t}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:d,signal:s.signal});if(r?.(u.status),!u.ok){let h=await HTe(u);throw new Fn(u.status,h,`Request to ${n.method} ${t} failed with status ${u.status}: ${h}`)}let p;if(u.status===204)p={};else if(n.responseType==="buffer"){let h=await u.arrayBuffer();p=Buffer.from(h);}else {let h=await u.text();try{p=JSON.parse(h);}catch{p=h;}}this.logger&&n.logResponse===!0&&p&&this.logger.debug({result:p,status:u.status,durationMs:Date.now()-c,...i},"Got response from Momentic server");let m=n.responseHeadersObject;return m&&u.headers.forEach((h,g)=>{m[g.toLowerCase()]=h;}),p}finally{clearTimeout(a),n.signal&&n.signal.removeEventListener("abort",l);}}};function GTe(e){return (e.split("?")[0]??e).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,":id")}var gi=class extends dN{apiKey;mode;constructor(t){super(t),this.apiKey=t.apiKey,this.mode=t.mode;}getHeaders(){return {...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[rz]:this.mode??""}}};var zC=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line;}};function uN(e){}function eJ(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=uN,onError:n=uN,onRetry:o=uN,onComment:r}=e,i="",s=true,a,l="",c="";function d(g){let f=s?g.replace(/^\xEF\xBB\xBF/,""):g,[b,T]=jTe(`${i}${f}`);for(let A of b)u(A);i=T,s=false;}function u(g){if(g===""){m();return}if(g.startsWith(":")){r&&r(g.slice(g.startsWith(": ")?2:1));return}let f=g.indexOf(":");if(f!==-1){let b=g.slice(0,f),T=g[f+1]===" "?2:1,A=g.slice(f+T);p(b,A,g);return}p(g,"",g);}function p(g,f,b){switch(g){case "event":c=f;break;case "data":l=`${l}${f}
251
+ `).filter(t=>t.length>0):[]}function sN(e){return [...new Set(e)]}async function VC(e){let t=await tp(e);if(!t)throw new _e(`Cannot find a git repository at '${e}'. Install git and run this from inside a git worktree.`);return t}function NTe({repoRoot:e,relativePath:t}){if(!t||np.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let n=np.resolve(e),o=np.resolve(n,t);if(o!==n&&!o.startsWith(`${n}${np.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var JY=new Set([".DS_Store","__MACOSX"]),QY={status:(e,t)=>{if(e.status===t.status)return e.status;if(e.status==="FAILED"||t.status==="FAILED")return "FAILED";if(e.status==="CANCELLED"||t.status==="CANCELLED")return "CANCELLED";if(e.status==="RETRYING"||t.status==="RETRYING")return "RETRYING";if(e.status==="RUNNING"||t.status==="RUNNING")return "RUNNING";if(e.status==="PENDING"||t.status==="PENDING")return "PENDING";throw new Error(`Invalid run status merge: ${e.status} and ${t.status}`)},startedAt:(e,t)=>e.startedAt<t.startedAt?e.startedAt:t.startedAt,updatedAt:(e,t)=>e.updatedAt>t.updatedAt?e.updatedAt:t.updatedAt,finishedAt:(e,t)=>!e.finishedAt||!t.finishedAt?new Date:e.finishedAt>t.finishedAt?e.finishedAt:t.finishedAt,gitCommitTimestamp:(e,t)=>{if(!(!e&&!t)){if(!e.gitCommitTimestamp||!t.gitCommitTimestamp||e.gitCommitTimestamp.getTime()!==t.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${e.gitCommitTimestamp} and ${t.gitCommitTimestamp}`);return e.gitCommitTimestamp}},pipelineId:(e,t)=>e.pipelineId===t.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:e.startedAt<t.startedAt?t.pipelineId:e.pipelineId,labels:(e,t)=>{let n=new Set([...e.labels??[],...t.labels??[]]);return Array.from(n)},ai:(e,t)=>e.ai??t.ai,browser:(e,t)=>e.browser??t.browser,aiSelect:(e,t)=>{let n=[...e.aiSelect??[],...t.aiSelect??[]];return n.length>0?n:void 0},healRiskSummary:()=>{}};function kTe(e,t,n){if(QY[n]){let i=QY[n];return i(e,t)}let o=e[n],r=t[n];if(o===void 0)return r;if(r===void 0)return o;if(o!==r)throw new Error(`Metadata values for key "${n}" do not match: "${o}" vs "${r}"`);return o}var aN=class extends Error{constructor(t,n){let o=`${t} contains invalid Momentic results: ${n}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(o),this.name="InvalidMomenticResultsPathError";}};function XY(e,t){try{let n=En__default.join(t,Ze);return fs.parse(JSON.parse(Mo__default.readFileSync(n,"utf-8")))}catch{throw new aN(e,t)}}function ZY(e,t,n){let o=randomUUID(),r=e.child({runGroupId:o});Mo__default.rmSync(t,{recursive:true,force:true});let i=Mo__default.readdirSync(n).filter(l=>!JY.has(l)).map(l=>En__default.join(n,l));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);Mo__default.mkdirSync(t,{recursive:true});let s={...XY(n,i[0]),id:o,healRiskSummary:void 0,aiSelect:void 0};for(let l of i){let c=En__default.join(l,wn);if(!Mo__default.existsSync(c))continue;let d=XY(n,l);r.info({oldRunGroupId:d.id},"Merging run groups");for(let p in d){if(p==="id")continue;let m=p;s[m]=kTe(s,d,m);}let u=Mo__default.readdirSync(c);for(let p of u){if(JY.has(p))continue;let m=En__default.join(c,p),h=En__default.join(t,wn,p);Mo__default.cpSync(m,h,{recursive:true});}}let a=En__default.join(t,Ze);Mo__default.writeFileSync(a,JSON.stringify(s,null,2));}var fe="v1",lN="cli",op="2.138.3";var DTe=9e4,FTe=3,BTe=1500,UTe=15e3,Fn=class extends Error{status;rawError;constructor(t,n,o,r={}){super(o,r),this.status=t,this.rawError=n;}},cN=class extends _e{constructor(t,n={}){super(t,n),this.name="PlanLimitExceededError";}};async function HTe(e){return e.text().then(t=>{try{return JSON.parse(t).error}catch{return t}})}var dN=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(){let t={"Content-Type":"application/json"};return (t[DA]=op),(t[iz]=lN),t}async sendRequest(t,n){let{retries:o=FTe,requestTimeoutMs:r=DTe,initialRetryDelayMs:i=BTe,maxRetryDelayMs:s=UTe,onFailedRequest:a}=n,l=o,c=o,d,u={path:t,baseUrl:this.baseUrl,method:n.method};for(;l>0;)try{return l--,await this.sendSingleRequestWithOTEL(t,n,r)}catch(p){d=p;try{a?.(d);}catch{}if(p instanceof Fn&&p.status>=400&&p.status<500)throw p.status===402?new cN(p.rawError,{cause:p}):p;if(p instanceof Error&&p.name==="AbortError"&&(d=new cd),l===0)throw d;let m=c-l,h=Math.min(i*Math.pow(2,m-1),s);await new Promise(g=>setTimeout(g,h));}throw this.logger.warn({...u,err:d},"Got fatal error response from Momentic server"),d}async sendSingleRequestWithOTEL(t,n,o){let r=GTe(t);return it({name:`cli.api.${n.method.toLowerCase()}.${r}`,serviceName:"api-server",attributes:{"http.request.method":n.method,"url.path":r},fn:i=>this.sendSingleRequestHelper(t,n,o,s=>{i?.setAttribute("http.response.status_code",s);})})}async sendSingleRequestHelper(t,n,o,r){let i={path:t,baseUrl:this.baseUrl,method:n.method},s=new AbortController,a=setTimeout(()=>s.abort(),o),l=()=>s.abort();n.signal&&n.signal.addEventListener("abort",l,{once:true});let c=Date.now(),d={...this.getHeaders(),...n.extraHeaders};try{let u=await fetch(`${this.baseUrl}${t}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:d,signal:s.signal});if(r?.(u.status),!u.ok){let h=await HTe(u);throw new Fn(u.status,h,`Request to ${n.method} ${t} failed with status ${u.status}: ${h}`)}let p;if(u.status===204)p={};else if(n.responseType==="buffer"){let h=await u.arrayBuffer();p=Buffer.from(h);}else {let h=await u.text();try{p=JSON.parse(h);}catch{p=h;}}this.logger&&n.logResponse===!0&&p&&this.logger.debug({result:p,status:u.status,durationMs:Date.now()-c,...i},"Got response from Momentic server");let m=n.responseHeadersObject;return m&&u.headers.forEach((h,g)=>{m[g.toLowerCase()]=h;}),p}finally{clearTimeout(a),n.signal&&n.signal.removeEventListener("abort",l);}}};function GTe(e){return (e.split("?")[0]??e).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,":id")}var gi=class extends dN{apiKey;mode;constructor(t){super(t),this.apiKey=t.apiKey,this.mode=t.mode;}getHeaders(){return {...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[rz]:this.mode??""}}};var zC=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line;}};function uN(e){}function eJ(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=uN,onError:n=uN,onRetry:o=uN,onComment:r}=e,i="",s=true,a,l="",c="";function d(g){let f=s?g.replace(/^\xEF\xBB\xBF/,""):g,[b,T]=jTe(`${i}${f}`);for(let A of b)u(A);i=T,s=false;}function u(g){if(g===""){m();return}if(g.startsWith(":")){r&&r(g.slice(g.startsWith(": ")?2:1));return}let f=g.indexOf(":");if(f!==-1){let b=g.slice(0,f),T=g[f+1]===" "?2:1,A=g.slice(f+T);p(b,A,g);return}p(g,"",g);}function p(g,f,b){switch(g){case "event":c=f;break;case "data":l=`${l}${f}
252
252
  `;break;case "id":a=f.includes("\0")?void 0:f;break;case "retry":/^\d+$/.test(f)?o(parseInt(f,10)):n(new zC(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:b}));break;default:n(new zC(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:f,line:b}));break}}function m(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
253
253
  `)?l.slice(0,-1):l}),a=void 0,l="",c="";}function h(g={}){i&&g.consume&&u(i),s=true,a=void 0,l="",c="",i="";}return {feed:d,reset:h}}function jTe(e){let t=[],n="",o=0;for(;o<e.length;){let r=e.indexOf("\r",o),i=e.indexOf(`
254
254
  `,o),s=-1;if(r!==-1&&i!==-1?s=Math.min(r,i):r!==-1?s=r:i!==-1&&(s=i),s===-1){n=e.slice(o);break}else {let a=e.slice(o,s);t.push(a),o=s+1,e[o-1]==="\r"&&e[o]===`
@@ -270,7 +270,7 @@ ${t}:`]}}function OJ({id:e,model:t,created:n}){return {id:e??void 0,modelId:t??v
270
270
 
271
271
  `,QCe=1e4,ZJ=w__default.object({stream:w__default.boolean().optional(),type:w__default.literal("response.create").optional()}).passthrough(),XCe=ZJ.extend({stream:w__default.literal(true)});function e3(e={}){let t=new HN(e);return async(n,o)=>{if(!tRe(n,o))return fetch(n,o);let r=await ZCe(o?.body);if(!r)return fetch(n,o);let i=XCe.safeParse(r);return i.success?t.fetch({httpUrl:t3(n),init:o,request:i.data}):fetch(n,o)}}var HN=class{constructor(t){this.options=t;}websocket;openPromise;latestResponseId;previousFullInput;pendingRequest;async fetch({httpUrl:t,init:n,request:o}){if(this.pendingRequest)return fetch(t,n);let r=await this.open({httpUrl:t,init:n}),i=new ReadableStream({start:s=>{let a={controller:s,fullRequest:o,sentContinuation:false,startedStreaming:false,retryingFullContext:false};this.pendingRequest=a,this.sendRequest({websocket:r,pendingRequest:a});},cancel:()=>{this.websocket?.close(),this.websocket=void 0,this.openPromise=void 0,this.latestResponseId=void 0,this.previousFullInput=void 0,this.pendingRequest=void 0;}});return new Response(i,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform"}})}async open({httpUrl:t,init:n}){return this.websocket?.readyState===UN.OPEN?this.websocket:this.openPromise?this.openPromise:(this.openPromise=new Promise((o,r)=>{let i=new UN(nRe(t),{headers:oRe(n?.headers)}),s=setTimeout(()=>{i.terminate(),r(new Error("Timed out opening OpenAI responses websocket"));},QCe);i.once("open",()=>{clearTimeout(s),this.websocket=i,this.openPromise=void 0,o(i);}),i.once("error",a=>{clearTimeout(s),this.resetConnection(),r(a);}),i.on("close",()=>{this.resetConnection();}),i.on("message",a=>{this.handleMessage(a);});}),this.openPromise)}sendRequest({websocket:t,pendingRequest:n}){let o=this.buildPayload(n.fullRequest);n.sentContinuation=!!o.previous_response_id,t.send(JSON.stringify(o));}buildPayload(t){let{background:n,stream:o,...r}=t,i={...r,type:"response.create"};sRe({payload:i,compactThreshold:this.options.compactThreshold});let s=Array.isArray(t.input)?t.input:void 0,a=this.latestResponseId&&s&&this.previousFullInput?rRe({currentInput:s,previousInput:this.previousFullInput}):void 0;return a&&a.length>0?(i.input=a,i.previous_response_id=this.latestResponseId,i):(delete i.previous_response_id,i)}handleMessage(t){let n=this.pendingRequest;if(!n)return;let o=lRe(t),r;try{r=JSON.parse(o);}catch(a){n.controller.error(a),this.pendingRequest=void 0,this.websocket?.close();return}let i=PG.safeParse(r),s=i.success?i.data:void 0;if(aRe(s)&&n.sentContinuation&&!n.startedStreaming&&!n.retryingFullContext&&this.websocket?.readyState===UN.OPEN){this.latestResponseId=void 0,this.previousFullInput=void 0,n.retryingFullContext=true,n.sentContinuation=false;let a=this.buildPayload(n.fullRequest);delete a.previous_response_id,this.websocket.send(JSON.stringify(a));return}if(n.startedStreaming=true,n.controller.enqueue(cRe(o)),s?.type==="response.completed"){this.latestResponseId=s.response.id,this.previousFullInput=Array.isArray(n.fullRequest.input)?n.fullRequest.input:void 0,this.closePendingRequest();return}s?.type==="error"&&(this.latestResponseId=void 0,this.previousFullInput=void 0,this.closePendingRequest());}closePendingRequest(){let t=this.pendingRequest;t&&(t.controller.enqueue(new TextEncoder().encode(JCe)),t.controller.close(),this.pendingRequest=void 0);}resetConnection(){this.websocket=void 0,this.openPromise=void 0,this.latestResponseId=void 0,this.previousFullInput=void 0;let t=this.pendingRequest;t&&(t.controller.error(new Error("OpenAI responses websocket connection closed")),this.pendingRequest=void 0);}};async function ZCe(e){let t=await eRe(e);if(!t)return;let n=ZJ.safeParse(JSON.parse(t));return n.success?n.data:void 0}async function eRe(e){if(typeof e=="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof Blob)return e.text();if(e instanceof ArrayBuffer)return new TextDecoder().decode(e);if(ArrayBuffer.isView(e))return new TextDecoder().decode(e)}function tRe(e,t){return (t?.method??(e instanceof Request?e.method:"GET")).toUpperCase()==="POST"&&t3(e).endsWith("/responses")}function t3(e){return e instanceof Request?e.url:e.toString()}function nRe(e){let t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function oRe(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((n,o)=>{t[o]=n;}),t}return Array.isArray(e)?Object.fromEntries(e):e}function rRe({currentInput:e,previousInput:t}){let n=0;for(;n<e.length&&n<t.length&&JSON.stringify(e[n])===JSON.stringify(t[n]);)n+=1;if(!(n<t.length))return e.slice(n).filter(iRe)}function iRe(e){return "role"in e&&e.role==="assistant"?false:"type"in e?e.type==="item_reference"||e.type==="reasoning"?false:e.type!=="function_call"&&e.type!=="custom_tool_call"&&e.type!=="local_shell_call":true}function sRe({payload:e,compactThreshold:t}){t&&(e.context_management=[{type:"compaction",compact_threshold:t}]);}function aRe(e){return e?.type==="error"&&e.code==="previous_response_not_found"}function lRe(e){return typeof e=="string"?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):Array.isArray(e)?Buffer.concat(e).toString("utf8"):e.toString("utf8")}function cRe(e){return new TextEncoder().encode(`data: ${e}
272
272
 
273
- `)}var uRe="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD",pRe=2e5;function nR(e){let{apiKey:t,sessionId:n,loggerTags:o}=e,r={Authorization:`Bearer ${t}`,[DA]:op,...n&&{[az]:n}};return o&&(r[sz]=JSON.stringify(o)),r}var n3="bedrock/",o3="azure/",r3=e=>t=>{let n=nR(e),o=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(n3)?o=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(n3.length))}`:t.startsWith(o3)&&(o=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(o3.length))}`),createAnthropic({baseURL:o,headers:n,apiKey:e.apiKey})(t)},i3=e=>t=>{let n=nR(e),o=e.useOpenAIResponsesWebSocket??false,r=o?e.openAIResponsesWebSocketCompactThreshold??mRe(process.env[uRe])??pRe:void 0;return sS({baseURL:`${e.baseUrl}/v1/llm/provider/openai/${t}`,headers:n,apiKey:e.apiKey,fetch:o?e3({compactThreshold:r}):void 0})(t)},s3=e=>t=>{let n=nR(e);return sS({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:n,apiKey:e.apiKey})(t)},a3=e=>t=>{let n=nR(e);return sS({baseURL:`${e.baseUrl}/v1/llm/provider/azure/${t}`,headers:n,apiKey:e.apiKey})(t)};function mRe(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}var sr=class extends gi{agentConfig;constructor(t,n){let o={...xm,...t};RH(o),super(n),this.agentConfig=o;}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(t,n){let o={...t,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/recommend-chunks-ai`,{method:"POST",body:o,signal:n.abortSignal});return dH.parse(r)}async rankChunksWithRag(t,n){let o=await this.sendRequest(`/${fe}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:op,...t},signal:n.abortSignal});return cH.parse(o)}async getScreenshotFromS3(t){let n=await this.sendRequest(`/${fe}/s3/visual-diff-screenshot`,{method:"POST",body:{url:t}});return z.string().parse(n)}async getElementLocation(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,cacheBustReason:n.cacheBustReason,agentConfigVersion:this.agentConfig?.locator},r=await this.sendRequest(`/${fe}/web-agent/locate-element`,{method:"POST",body:o,signal:n.abortSignal});return dz.parse(r)}async getAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},r=await this.sendRequest(`/${fe}/web-agent/assertion`,{method:"POST",body:o,signal:n.abortSignal});return AP.parse(r)}async getLintStepResult(t,n){let o={...t,disableCache:!!n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/lint/step`,{method:"POST",body:o,signal:n.abortSignal});return cz.parse(r)}async getVisualAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},r=await this.sendRequest(`/${fe}/web-agent/visual-assertion`,{method:"POST",body:o,signal:n.abortSignal});return AP.parse(r)}async getAiActionCommand(t,n){let o=await this.sendRequest(`/${fe}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return lz.parse(o)}async getMultiturnAiActionCommand(t,n){return await this.sendRequest(`/${fe}/web-agent/ai-action/next-command`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(t,n){let o=await this.sendRequest(`/${fe}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Ox.parse(o)}async getReverseMappedDescription(t,n){let o=await this.sendRequest(`/${fe}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return uz.parse(o)}async getTextExtraction(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`/${fe}/web-agent/text-extraction`,{method:"POST",body:o,signal:n.abortSignal});return Mx.parse(r)}async getPageSummary(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/page-summary`,{method:"POST",body:o,signal:n.abortSignal});return cU.parse(r)}async getSmartWaitingDecision(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/smart-waiting`,{method:"POST",body:o,signal:n.abortSignal});return dU.parse(r)}async getTestResultClassification(t,n){let o=await this.sendRequest(`/${fe}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return mT.parse(o)}async getExtractedKeywords(t,n){let o=await this.sendRequest(`/${fe}/web-agent/extract-keywords`,{method:"POST",body:t,signal:n.abortSignal});return EH.parse(o)}async getAutohealingProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return rU.parse(o)}async getFailureRecoveryProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return aU.parse(o)}async getFailureRecoveryPlan(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:n.abortSignal});return sU.parse(o)}async getIframeRegex(t,n){let o=await this.sendRequest(`/${fe}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return RB.parse(o)}getAnthropicModelFactory(t){let{sessionId:n,logger:o,streamType:r}=t;return r3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n})}getAnthropicBedrockModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`bedrock/${o}`)}getAnthropicFoundryModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`azure/${o}`)}getOpenAIModelFactory(t){let{sessionId:n,logger:o,streamType:r,useOpenAIResponsesWebSocket:i}=t;return i3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n,useOpenAIResponsesWebSocket:i})}getXAIModelFactory(t){let{sessionId:n,logger:o,streamType:r}=t;return s3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n})}getAzureOpenAIModelFactory(t){let{sessionId:n,logger:o,streamType:r}=t;return a3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n})}};var Dt=class extends gi{constructor(t){super({...t,mode:void 0});}getAppUrl(){return Km(this.baseUrl)}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${fe}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(n){throw n instanceof Fn?n.status>=400&&n.status<500?new Error(n.rawError,{cause:n}):new Error(`Momentic server error (HTTP ${n.status}). Please try again in a moment.`,{cause:n}):new Error(`Could not reach Momentic server at ${this.baseUrl}. Check your network connection. If you're on a restricted network (VPN, firewall, or proxy), you may need to whitelist Momentic's servers: https://momentic.ai/docs/environment/authentication#ip-whitelist`,{cause:n})}return wz.parse(t)}async getQuotaStatus(){let t=await this.sendRequest(`/${fe}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Iz.parse(t)}async createRemoteBrowserConnection(t){let n=await this.sendRequest(`/${fe}/browsers/connection`,{method:"POST",body:{...t?.runId?{runId:t.runId}:{},...t?.attemptedProviders?{attemptedProviders:t.attemptedProviders}:{}},retries:3,requestTimeoutMs:1e4});return Vz.parse(n)}async bulkGetRunStatus(t){let n=await this.sendRequest(`/${fe}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Az.parse(n)}async getRunExport(t){let n=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Cz.parse(n)}async saveRunClassification(t,n){await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let n=await this.sendRequest(`/${fe}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return mz.parse(n)}async updateStepCaches(t,n){await this.sendRequest(`/${fe}/cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,n){await this.sendRequest(`/${fe}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gz.parse(o)}async getSnapshotCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/snapshot-cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return fz.parse(o)}async deleteStepCacheEntry(t,n){await this.sendRequest(`/${fe}/cache/entry`,{method:"DELETE",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let n=await this.sendRequest(`/${fe}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return EP.parse(n)}cacheRouteForPlatform(t){switch(t){case "ANDROID":return "android-cache";case "IOS":return "ios-cache"}}async deleteMobileStepCacheEntry({platform:t,body:n,headers:o}){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:n,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,n){let o=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return EP.parse(o)}async updateMobileStepCaches(t){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t.platform)}`,{method:"PATCH",body:t.body,extraHeaders:t.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getMobileStepCacheForTest({platform:t,body:n,headers:o}){let r=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:n,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return yz[t](r)}async queueTests(t){let n=await this.sendRequest(`/${fe}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return pz.parse(n)}async uploadScreenshot(t){let n=await this.sendRequest(`/${fe}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return vz.parse(n)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${fe}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${fe}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let n={};return {data:await this.sendRequest(`/${fe}/on-demand-screenshots/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:n}),contentType:n["content-type"]??"image/jpeg"}}async getAllEnvironments(){let t=await this.sendRequest(`/${fe}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return xz.parse(t)}async acquireCacheLock(t,n){let o=await this.sendRequest(`/${fe}/result-cache/lock`,{method:"POST",body:t,signal:n,retries:3,requestTimeoutMs:3e4});return Kz.parse(o)}async releaseCacheLock(t){await this.sendRequest(`/${fe}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${fe}/result-cache/entry`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(t){let n=await this.sendRequest(`/${fe}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Mz.parse(n)}async bulkGetRunGroupStatus(t){let n={runGroupIds:t},o=await this.sendRequest(`/${fe}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return tH.array().parse(o)}async getRunGroupWithRuns(t){try{let n=await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return nH.parse(n)}catch(n){if(n instanceof Fn&&n.status===404)return null;throw n}}async updateGithubPRHealRiskSummary(t,n){await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}/github-pr-heal-risk-summary`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadProposedSteps(t,n){try{await this.sendRequest(`/${fe}/test-fragments/`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});}catch(o){n.error({err:o},"Failed to upload proposed steps");}}async reportBillableEvents(t,n){try{await this.sendRequest(`/${fe}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4});}catch(o){t.error({err:o},"Failed to report billable event");}}async fetchTestFragment(t){let n=await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Oz.parse(n)}async patchTestFragment(t,n){await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,n){let o=await this.sendRequest(`/${fe}/results/tests/${t}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Nz.parse(o)}async listRuns(t){let n=await this.sendRequest(`/${fe}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Lz.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${fe}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return kz.parse(t)}async startProcessingResultsUpload(t,n){let o=await this.sendRequest(`/${fe}/results/uploads/${t}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Dz.parse(o)}async fetchIconKnowledgeBase(t){try{let n=await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Zz.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,n){try{await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});}catch(o){n.error({err:o},"Failed to save new icons to icon knowledge base");}}async retrieveKnowledgeBase({query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l,retries:c,signal:d},u){try{let p=await this.sendRequest(`/${fe}/knowledge-base/retrieve`,{method:"POST",body:{query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l},retries:c??3,requestTimeoutMs:5e3,signal:d});return Tj.parse(p)}catch(p){return u.warn({err:p},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let n=await this.sendRequest(`/${fe}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return X_.parse(n)}async getMergeBaseCommitFromGithub(t,n,o,r){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return iy.parse(s)}async compareCommitsFromGithub({owner:t,repo:n,base:o,head:r}){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/compare?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return dj.parse(s)}async getGithubFileContent({owner:t,repo:n,path:o,ref:r}){let i=new URLSearchParams;i.set("path",o),i.set("ref",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return uj.parse(s).content??void 0}async getGithubBranchMetadata(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/branch-metadata?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return pj.parse(i)}async createGithubPullRequest(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return aj.parse(r)}async createGithubCommit(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return lj.parse(r)}async getGithubPullRequestTemplate(t,n){try{let o=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return hj.parse(o).template}catch(o){if(o instanceof Fn&&o.status===404)return;throw o}}async getGithubPullRequestForBranch(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i;try{i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof Fn&&s.status===404)return;throw s}return cj.parse(i)}async getCommitFromGithub(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return iy.parse(r)}async getMergedBranchFromGithub(t,n,o,r){let i=encodeURIComponent(o),s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return vP.parse(s)}async getMergeBaseCommitFromGitlab(t,n,o){let r=new URLSearchParams;r.set("base",n),r.set("head",o);let i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return iy.parse(s)}async getGitlabMergeRequestForBranch(t,n){let o=new URLSearchParams;o.set("branch",n);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${fe}/git/gitlab/${r}/merge-requests?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof Fn&&s.status===404)return;throw s}return mj.parse(i)}async getCommitFromGitlab(t,n){let o=encodeURIComponent(t),r=await this.sendRequest(`/${fe}/git/gitlab/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return iy.parse(r)}async getMergedBranchFromGitlab(t,n,o){let r=encodeURIComponent(n),i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/${r}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return vP.parse(s)}async getAgentConfig(){let t=await this.sendRequest(`/${fe}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return z.record(z.string(),z.string()).parse(t)}async getOrgSettings(){try{let t=await this.sendRequest(`/${fe}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return WU(t)}catch(t){if(t instanceof Fn&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),wm.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${fe}/quarantine`,{method:"GET"});return Fz.parse(t)}async sendExploreSlackNotification(t){await this.sendRequest(`/${fe}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine`,{method:"POST",body:{testId:t.id,testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}async unquarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine/${t.id}`,{method:"DELETE",body:{testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}platformRoute(t){switch(t){case "ANDROID":return "android";case "IOS":return "ios"}}async createAndroidEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/android`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Uz.parse(n)}async extendEmulatorTtl(t,n){try{await this.sendRequest(`/${fe}/limbar/${this.platformRoute(t)}/${n}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3});}catch{}}async generateAssetUploadUrl({channel:t,tag:n,md5:o,platform:r}){let i={channel:t,tag:n,md5:o},s=await this.sendRequest(`/${fe}/limbar/${this.platformRoute(r)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:true});return Gz.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(`/${fe}/limbar/android/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(`/${fe}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jz.parse(t)}async getLimbarAssetDownloadUrl(t,n,o){let r=await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return $z.parse(r)}async deleteAsset(t,n,o){await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/ios`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Hz.parse(n)}async deleteIosEmulator(t){await this.sendRequest(`/${fe}/limbar/ios/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let n=await this.sendRequest(`/${fe}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return KG.parse(n)}async generateMcpSessionTraceUploadUrl(t){let n=await this.sendRequest(`/${fe}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return CP.parse(n)}};async function Lh(e){let t=process.versions.node,n=parseInt(t.split(".")[0]);(isNaN(n)||n<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${t}`);let o=await e.client.getAuthInfo();return R.debug("Got auth info from API"),o}var Od=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,n){await this.apiClient.reportBillableEvents(t,n);}};var Nd=class extends gi{generator;constructor(t,n){super(t),this.generator=n;}async runTemplateMatching(t,n={}){let o=await this.sendRequest(`/${fe}/web-agent/template-matching`,{method:"POST",body:t,signal:n?.signal});return vB.parse(o)}async constructIframeRegex(t,n={}){return this.generator.getIframeRegex(t,{abortSignal:n.signal,loggerTags:n.loggerTags})}};var kh=class{constructor(t,n){this.client=t;this.orgId=n;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return Km(t)}async acquireCacheLock(t,n){return this.client.acquireCacheLock(t,n)}async createOnDemandScreenshot(t,n,o){let{apiServerUrl:r}=await this.client.uploadOnDemandScreenshot({id:t,screenshot:n.toString("base64"),contentType:o});return {apiServerUrl:r,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${t}`,universalHandle:{id:t,contentType:o}}}async fetchOnDemandScreenshot(t){return this.client.fetchOnDemandScreenshot(t.id)}async releaseCacheLock(t){return this.client.releaseCacheLock(t)}async deleteCacheResult(t){return this.client.deleteCacheResult(t)}async setCacheResult(t){return this.client.setCacheResult(t)}async getCacheResult(t){return this.client.getCacheResult(t)}fetchIconKnowledgeBase(t){return this.client.fetchIconKnowledgeBase(t)}saveNewIcons(t,n){return this.client.saveNewIcons(t,n)}};var Tc="v1",yRe=2e3,l3="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",Ld=class{httpClient;fakerInstance;supportsLease;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this),lease:this.leasePhoneNumber.bind(this),release:this.releasePhoneNumber.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this),create:this.createEmail.bind(this)};activeLeases=new Map;constructor(t){this.httpClient=t.httpClient,this.supportsLease=t.supportsLease??true,t.fakerSeed&&(this.fakerInstance=new Faker({locale:en$1}),this.fakerInstance.seed(t.fakerSeed));}async sendSms(t){return this.httpClient.sendRequest(`/${Tc}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${Tc}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):n})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(l3);let n=await this.httpClient.sendRequest(`/${Tc}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof Fn?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),o=JG.parse(n);return this.activeLeases.set(o.phoneNumber,{leaseToken:o.leaseToken}),o}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(l3);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${Tc}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to release phone number: ${n.message}`)})}async dispose(){let t=[...this.activeLeases.entries()];this.activeLeases.clear(),await Promise.allSettled(t.map(([n,{leaseToken:o}])=>Re(this.httpClient.sendRequest(`/${Tc}/tools/sms/release`,{method:"POST",body:{phoneNumber:n,leaseToken:o}}),{milliseconds:yRe,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${Tc}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${Tc}/tools/email/fetchAll`,{method:"POST",body:t}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${Tc}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${Tc}/tools/email/create`,{method:"POST",body:{}}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to create email inbox: ${n.message}`)});return QG.parse(t)}};function c3(e,t,n){return fetch(e,{method:"PUT",body:n,headers:{"Content-Type":t}})}var oR=class{constructor(t){this.client=t;}async uploadResultsArchive(t){let{runGroupId:n,archive:o,persist:r}=t,{uploadUrl:i,id:s}=await this.client.generateTestResultsUploadUrl(),a=await c3(i,"application/zip",o);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:l}=await this.client.startProcessingResultsUpload(s,{runGroupId:n,persist:r});return l}};function ap({logger:e,orgId:t,client:n,gitMetadata:o,regenerateCache:r,alwaysSaveCache:i,noCache:s,isolateCachesByEnvironment:a=false,bustOldestCachePercentage:l}){return s?new BA:new jN(e,t,n,o,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:a})}var jN=class{constructor(t,n,o,r,i){this.orgId=n;this.client=o;let{regenerateCache:s,alwaysSaveCache:a,bustOldestCachePercentage:l,isolateCachesByEnvironment:c}=i,{gitBranchName:d,gitProtectedBranches:u}=r;t.info({options:i,gitBranchName:d,gitProtectedBranches:u},"Cache storage initialization options"),this.cacheHeaders=FA(r),this.isolateCachesByEnvironment=c,this.readCaches=!s;let p=d&&u.includes(d);a||!p?this.writeCaches=true:this.writeCaches=false,p||(this.bustOldestCachePercentage=l);}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:wP(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save step cache entries");}}async saveSnapshotCacheEntries({entries:t,logger:n}){if(t.length!==0){if(!this.writeCaches){n.debug("Skipping snapshot cache storage because branch is protected");return}try{await this.client.updateSnapshotCaches({entries:wP(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save snapshot cache entries");}}}async deleteStepCacheEntry({logger:t,testId:n,key:o,environment:r}){try{await this.client.deleteStepCacheEntry({testId:n,key:o,environment:this.isolateCachesByEnvironment?r:void 0},this.cacheHeaders);}catch(i){t.error({err:i},"Failed to delete step cache entry");}}async resolveStepCacheEntries(t){if(!this.readCaches){t.logger.debug("Skipping cache resolution because of regenerate flag");return}let n=t.useSnapshotIdentityCache?await this.tryRestoreStepIdsFromSnapshot(t):void 0,{steps:o,beforeSteps:r,afterSteps:i}=t.stepLists,s=await this.client.getStepCacheForTest({testId:t.testId,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);if(this.bustOldestCachePercentage!==void 0){let u=Object.entries(s).map(([h,g])=>({key:h,time:g.value.cache?.updatedAt?.getTime()??0}));u.sort((h,g)=>h.time-g.time);let p=u.length,m=Math.max(1,Math.floor(p*this.bustOldestCachePercentage/100));u.slice(0,m).forEach(({key:h})=>{delete s[h];}),t.logger.info({nCachesToBust:m,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:p},"Busted oldest caches");}let a={totalSteps:0,cacheKeysHit:[],cacheKeysMissed:[],uniqueKeysHit:[],cacheMissSamples:[]};for(let u of [o,r,i]){if(!u)continue;let p=ju({steps:u,stepCacheEntries:s,logger:t.logger});a.totalSteps+=p.totalSteps,a.cacheKeysHit.push(...p.cacheKeysHit),a.cacheKeysMissed.push(...p.cacheKeysMissed),a.uniqueKeysHit.push(...p.uniqueKeysHit),a.cacheMissSamples.push(...p.cacheMissSamples);}n&&bRe({cacheResolutionStats:a,logger:t.logger,restoredIdentity:n,schemaVersion:t.schemaVersion,testId:t.testId});let l=["platform:web","source:local",`fileFormat:${t.useSnapshotIdentityCache?"v2":"v1"}`,`snapshotIdentityCache:${t.useSnapshotIdentityCache}`,`orgId:${this.orgId}`,"cliVersion:2.138.2"];if(gt.increment("step_cache_resolution",a.cacheKeysHit.length,[...l,"outcome:hit"]),gt.increment("step_cache_resolution",a.cacheKeysMissed.length,[...l,"outcome:miss"]),gt.increment("step_cache_resolution",a.totalSteps,[...l,"outcome:total"]),!this.writeCaches){t.logger.debug("Skipping cache last used at update because branch is protected");return}let{cachesToSave:c,snapshotCachesToSave:d}=await An({stepLists:t.stepLists,useSnapshotIdentityCache:t.useSnapshotIdentityCache,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});t.useSnapshotIdentityCache&&this.saveSnapshotCacheEntries({entries:d,logger:t.logger}),this.saveStepCacheEntries({entries:c,logger:t.logger});}async tryRestoreStepIdsFromSnapshot(t){try{return await this.restoreStepIdsFromSnapshot(t)}catch(n){t.logger.warn({err:n,testId:t.testId},"Failed to restore step ids from snapshot cache; proceeding without identity cache"),gt.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:2.138.2","outcome:identity_restore_error"]);return}}async restoreStepIdsFromSnapshot(t){let{logger:n,testId:o}=t,r=await this.client.getSnapshotCacheForTest({testId:o,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders),i=hC({entries:r,orgId:this.orgId,testId:o,logger:n}),s=mC({currentStepLists:t.stepLists,previousSnapshot:i.testSnapshot,previousModuleSnapshots:i.moduleSnapshots,generateUuid:randomUUID});return t.stepLists.steps.splice(0,t.stepLists.steps.length,...s.stepLists.steps),t.stepLists.beforeSteps=s.stepLists.beforeSteps,t.stepLists.afterSteps=s.stepLists.afterSteps,n.debug({snapshotEntries:r.length,testSnapshotHit:!!i.testSnapshot,moduleSnapshots:Array.from(i.moduleSnapshots.keys()),mintedSteps:s.stats.mintedSteps,stats:s.stats,moduleRestoreResults:s.moduleRestoreResults.map(({moduleId:a,snapshotHit:l,stats:c})=>({moduleId:a,snapshotHit:l,stats:c}))},"Restored step ids from snapshot cache"),s}};function bRe({cacheResolutionStats:e,logger:t,restoredIdentity:n,schemaVersion:o,testId:r}){let i=e.cacheKeysHit.length,s=e.cacheKeysMissed.length,a=i+s,l=a>0?Math.round(s/a*1e3)/10:0,c=n.stats.matchedSteps+n.stats.mintedSteps,d=c>0?Math.round(n.stats.mintedSteps/c*1e3)/10:0,u=n.moduleRestoreResults.filter(({snapshotHit:g,stats:f})=>!g||f.mintedSteps>0||f.bustedConditionals>0).slice(0,10).map(({moduleId:g,snapshotHit:f,stats:b})=>({moduleId:g,snapshotHit:f,stats:b})),p=n.stats.mintedSteps>=5&&d>=25,m=p||n.stats.bustedConditionals>0||u.some(({stats:g})=>g.mintedSteps>=5||g.bustedConditionals>0),h={cacheHits:i,cacheMissRate:l,cacheMisses:s,cacheMissSamples:e.cacheMissSamples.slice(0,10),hasHighMintRate:p,identityMintRate:d,moduleIdentityIssueCount:u.length,moduleIdentityIssues:u,schemaVersion:o,snapshotIdentityCache:true,stepIdentityStats:n.stats,testId:r,totalCacheableSteps:e.totalSteps};if(!m){t.debug(h,"V2 cache resolution completed");return}t.warn(h,"V2 cache resolution degraded");}function TRe(e){let t=new d3,n=En__default.join(e,Ze),o=fs.parse(JSON.parse(Mo__default.readFileSync(n,"utf-8")));t.addLocalFile(n);for(let r of Mo__default.readdirSync(En__default.join(e,wn))){if(!r.endsWith(".zip"))continue;let i=r.replace(/\.zip$/,""),s=new d3(En__default.join(e,wn,r));for(let a of s.getEntries())a.isDirectory||t.addFile(En__default.join(wn,i,a.entryName),a.getData());}return {runGroupId:o.id,buffer:t.toBuffer()}}async function aS(e){let{client:t,resultsPath:n,persist:o}=e;if(!Mo__default.existsSync(n))return {success:false,error:"results path does not exist"};let r=new oR(t);try{let{runGroupId:i,buffer:s}=TRe(n),a=await r.uploadResultsArchive({runGroupId:i,archive:s,persist:o});return {success:!0,runGroupUrl:`${t.getAppUrl()}/run-groups/${a}`}}catch(i){return {success:false,error:Q(i)}}}var lS=class e{constructor(t){this.filePath=t;Mo__default.rmSync(this.filePath,{recursive:true,force:true}),Mo__default.mkdirSync(this.filePath,{recursive:true});}children=[];streams=[];close(){for(let t of this.children)t.close();for(let t of this.streams)t.end();}cd(t){let n=new e(En__default.join(this.filePath,t));return this.children.push(n),n}cwd(){return this.filePath}mkdir(t){Mo__default.mkdirSync(En__default.join(this.filePath,t),{recursive:true});}readFile(t){let n=En__default.join(this.filePath,t);if(Mo__default.existsSync(n))return Mo__default.readFileSync(n)}storeFile(t){let{name:n,contents:o}=t,r=En__default.join(this.filePath,n);try{Mo__default.mkdirSync(En__default.dirname(r),{recursive:!0}),Mo__default.writeFileSync(r,o);}catch{}}createFileStream(t){let n=En__default.join(this.filePath,t),o=Mo__default.createWriteStream(n);return this.streams.push(o),o}createRunArchive(t,n){let o=new VN(En__default.join(this.filePath,wn),t,n);return this.children.push(o),o}},VN=class{children=[];tempPath;finalPath;logger;closed=false;constructor(t,n,o){this.tempPath=En__default.join(t,`temp-storage-${n}`),this.finalPath=En__default.join(t,`${n}.zip`),this.logger=o,Mo__default.rmSync(this.tempPath,{recursive:true,force:true}),Mo__default.rmSync(this.finalPath,{recursive:true,force:true}),Mo__default.mkdirSync(this.tempPath,{recursive:true});}readFile(t){let n=En__default.join(this.tempPath,t);if(Mo__default.existsSync(n))return Mo__default.readFileSync(n)}mkdir(t){Mo__default.mkdirSync(En__default.join(this.tempPath,t),{recursive:true});}cd(t){let n=new lS(En__default.join(this.tempPath,t));return this.children.push(n),n}cwd(){return this.tempPath}storeFile(t){if(this.closed)return;let{name:n,contents:o}=t,r=En__default.join(this.tempPath,n);Mo__default.mkdirSync(En__default.dirname(r),{recursive:true}),Mo__default.writeFileSync(r,o);}close(){if(!this.closed){this.closed=true;for(let t of this.children)t.close();try{let t=new d3;t.addLocalFolder(this.tempPath,void 0,o=>o!==".DS_Store");let n=t.toBuffer();Mo__default.writeFileSync(this.finalPath,n),Mo__default.rmSync(this.tempPath,{recursive:!0,force:!0});}catch(t){this.logger.warn({err:t,finalPath:this.finalPath,tempPath:this.tempPath},"Failed to archive run artifacts; leaving raw files on disk");}}}};function h3(e){try{return Mo__default.existsSync(e)?JSON.parse(Mo__default.readFileSync(e,"utf-8")):void 0}catch{return}}function u3(e){return Mo__default.existsSync(e)?Mo__default.readFileSync(e,"utf-8").split(`
273
+ `)}var uRe="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD",pRe=2e5;function nR(e){let{apiKey:t,sessionId:n,loggerTags:o}=e,r={Authorization:`Bearer ${t}`,[DA]:op,...n&&{[az]:n}};return o&&(r[sz]=JSON.stringify(o)),r}var n3="bedrock/",o3="azure/",r3=e=>t=>{let n=nR(e),o=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(n3)?o=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(n3.length))}`:t.startsWith(o3)&&(o=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(o3.length))}`),createAnthropic({baseURL:o,headers:n,apiKey:e.apiKey})(t)},i3=e=>t=>{let n=nR(e),o=e.useOpenAIResponsesWebSocket??false,r=o?e.openAIResponsesWebSocketCompactThreshold??mRe(process.env[uRe])??pRe:void 0;return sS({baseURL:`${e.baseUrl}/v1/llm/provider/openai/${t}`,headers:n,apiKey:e.apiKey,fetch:o?e3({compactThreshold:r}):void 0})(t)},s3=e=>t=>{let n=nR(e);return sS({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:n,apiKey:e.apiKey})(t)},a3=e=>t=>{let n=nR(e);return sS({baseURL:`${e.baseUrl}/v1/llm/provider/azure/${t}`,headers:n,apiKey:e.apiKey})(t)};function mRe(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}var sr=class extends gi{agentConfig;constructor(t,n){let o={...xm,...t};RH(o),super(n),this.agentConfig=o;}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(t,n){let o={...t,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/recommend-chunks-ai`,{method:"POST",body:o,signal:n.abortSignal});return dH.parse(r)}async rankChunksWithRag(t,n){let o=await this.sendRequest(`/${fe}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:op,...t},signal:n.abortSignal});return cH.parse(o)}async getScreenshotFromS3(t){let n=await this.sendRequest(`/${fe}/s3/visual-diff-screenshot`,{method:"POST",body:{url:t}});return z.string().parse(n)}async getElementLocation(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,cacheBustReason:n.cacheBustReason,agentConfigVersion:this.agentConfig?.locator},r=await this.sendRequest(`/${fe}/web-agent/locate-element`,{method:"POST",body:o,signal:n.abortSignal});return dz.parse(r)}async getAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},r=await this.sendRequest(`/${fe}/web-agent/assertion`,{method:"POST",body:o,signal:n.abortSignal});return AP.parse(r)}async getLintStepResult(t,n){let o={...t,disableCache:!!n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/lint/step`,{method:"POST",body:o,signal:n.abortSignal});return cz.parse(r)}async getVisualAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},r=await this.sendRequest(`/${fe}/web-agent/visual-assertion`,{method:"POST",body:o,signal:n.abortSignal});return AP.parse(r)}async getAiActionCommand(t,n){let o=await this.sendRequest(`/${fe}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return lz.parse(o)}async getMultiturnAiActionCommand(t,n){return await this.sendRequest(`/${fe}/web-agent/ai-action/next-command`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(t,n){let o=await this.sendRequest(`/${fe}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Ox.parse(o)}async getReverseMappedDescription(t,n){let o=await this.sendRequest(`/${fe}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return uz.parse(o)}async getTextExtraction(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`/${fe}/web-agent/text-extraction`,{method:"POST",body:o,signal:n.abortSignal});return Mx.parse(r)}async getPageSummary(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/page-summary`,{method:"POST",body:o,signal:n.abortSignal});return cU.parse(r)}async getSmartWaitingDecision(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/smart-waiting`,{method:"POST",body:o,signal:n.abortSignal});return dU.parse(r)}async getTestResultClassification(t,n){let o=await this.sendRequest(`/${fe}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return mT.parse(o)}async getExtractedKeywords(t,n){let o=await this.sendRequest(`/${fe}/web-agent/extract-keywords`,{method:"POST",body:t,signal:n.abortSignal});return EH.parse(o)}async getAutohealingProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return rU.parse(o)}async getFailureRecoveryProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return aU.parse(o)}async getFailureRecoveryPlan(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:n.abortSignal});return sU.parse(o)}async getIframeRegex(t,n){let o=await this.sendRequest(`/${fe}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return RB.parse(o)}getAnthropicModelFactory(t){let{sessionId:n,logger:o,streamType:r}=t;return r3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n})}getAnthropicBedrockModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`bedrock/${o}`)}getAnthropicFoundryModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`azure/${o}`)}getOpenAIModelFactory(t){let{sessionId:n,logger:o,streamType:r,useOpenAIResponsesWebSocket:i}=t;return i3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n,useOpenAIResponsesWebSocket:i})}getXAIModelFactory(t){let{sessionId:n,logger:o,streamType:r}=t;return s3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n})}getAzureOpenAIModelFactory(t){let{sessionId:n,logger:o,streamType:r}=t;return a3({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...vt(o),promptType:r},sessionId:n})}};var Dt=class extends gi{constructor(t){super({...t,mode:void 0});}getAppUrl(){return Km(this.baseUrl)}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${fe}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(n){throw n instanceof Fn?n.status>=400&&n.status<500?new Error(n.rawError,{cause:n}):new Error(`Momentic server error (HTTP ${n.status}). Please try again in a moment.`,{cause:n}):new Error(`Could not reach Momentic server at ${this.baseUrl}. Check your network connection. If you're on a restricted network (VPN, firewall, or proxy), you may need to whitelist Momentic's servers: https://momentic.ai/docs/environment/authentication#ip-whitelist`,{cause:n})}return wz.parse(t)}async getQuotaStatus(){let t=await this.sendRequest(`/${fe}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Iz.parse(t)}async createRemoteBrowserConnection(t){let n=await this.sendRequest(`/${fe}/browsers/connection`,{method:"POST",body:{...t?.runId?{runId:t.runId}:{},...t?.attemptedProviders?{attemptedProviders:t.attemptedProviders}:{}},retries:3,requestTimeoutMs:1e4});return Vz.parse(n)}async bulkGetRunStatus(t){let n=await this.sendRequest(`/${fe}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Az.parse(n)}async getRunExport(t){let n=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Cz.parse(n)}async saveRunClassification(t,n){await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let n=await this.sendRequest(`/${fe}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return mz.parse(n)}async updateStepCaches(t,n){await this.sendRequest(`/${fe}/cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,n){await this.sendRequest(`/${fe}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gz.parse(o)}async getSnapshotCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/snapshot-cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return fz.parse(o)}async deleteStepCacheEntry(t,n){await this.sendRequest(`/${fe}/cache/entry`,{method:"DELETE",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let n=await this.sendRequest(`/${fe}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return EP.parse(n)}cacheRouteForPlatform(t){switch(t){case "ANDROID":return "android-cache";case "IOS":return "ios-cache"}}async deleteMobileStepCacheEntry({platform:t,body:n,headers:o}){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:n,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,n){let o=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return EP.parse(o)}async updateMobileStepCaches(t){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t.platform)}`,{method:"PATCH",body:t.body,extraHeaders:t.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getMobileStepCacheForTest({platform:t,body:n,headers:o}){let r=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:n,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return yz[t](r)}async queueTests(t){let n=await this.sendRequest(`/${fe}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return pz.parse(n)}async uploadScreenshot(t){let n=await this.sendRequest(`/${fe}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return vz.parse(n)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${fe}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${fe}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let n={};return {data:await this.sendRequest(`/${fe}/on-demand-screenshots/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:n}),contentType:n["content-type"]??"image/jpeg"}}async getAllEnvironments(){let t=await this.sendRequest(`/${fe}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return xz.parse(t)}async acquireCacheLock(t,n){let o=await this.sendRequest(`/${fe}/result-cache/lock`,{method:"POST",body:t,signal:n,retries:3,requestTimeoutMs:3e4});return Kz.parse(o)}async releaseCacheLock(t){await this.sendRequest(`/${fe}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${fe}/result-cache/entry`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(t){let n=await this.sendRequest(`/${fe}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Mz.parse(n)}async bulkGetRunGroupStatus(t){let n={runGroupIds:t},o=await this.sendRequest(`/${fe}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return tH.array().parse(o)}async getRunGroupWithRuns(t){try{let n=await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return nH.parse(n)}catch(n){if(n instanceof Fn&&n.status===404)return null;throw n}}async updateGithubPRHealRiskSummary(t,n){await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}/github-pr-heal-risk-summary`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadProposedSteps(t,n){try{await this.sendRequest(`/${fe}/test-fragments/`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});}catch(o){n.error({err:o},"Failed to upload proposed steps");}}async reportBillableEvents(t,n){try{await this.sendRequest(`/${fe}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4});}catch(o){t.error({err:o},"Failed to report billable event");}}async fetchTestFragment(t){let n=await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Oz.parse(n)}async patchTestFragment(t,n){await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,n){let o=await this.sendRequest(`/${fe}/results/tests/${t}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Nz.parse(o)}async listRuns(t){let n=await this.sendRequest(`/${fe}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Lz.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${fe}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return kz.parse(t)}async startProcessingResultsUpload(t,n){let o=await this.sendRequest(`/${fe}/results/uploads/${t}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Dz.parse(o)}async fetchIconKnowledgeBase(t){try{let n=await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Zz.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,n){try{await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});}catch(o){n.error({err:o},"Failed to save new icons to icon knowledge base");}}async retrieveKnowledgeBase({query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l,retries:c,signal:d},u){try{let p=await this.sendRequest(`/${fe}/knowledge-base/retrieve`,{method:"POST",body:{query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l},retries:c??3,requestTimeoutMs:5e3,signal:d});return Tj.parse(p)}catch(p){return u.warn({err:p},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let n=await this.sendRequest(`/${fe}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return X_.parse(n)}async getMergeBaseCommitFromGithub(t,n,o,r){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return iy.parse(s)}async compareCommitsFromGithub({owner:t,repo:n,base:o,head:r}){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/compare?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return dj.parse(s)}async getGithubFileContent({owner:t,repo:n,path:o,ref:r}){let i=new URLSearchParams;i.set("path",o),i.set("ref",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return uj.parse(s).content??void 0}async getGithubBranchMetadata(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/branch-metadata?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return pj.parse(i)}async createGithubPullRequest(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return aj.parse(r)}async createGithubCommit(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return lj.parse(r)}async getGithubPullRequestTemplate(t,n){try{let o=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return hj.parse(o).template}catch(o){if(o instanceof Fn&&o.status===404)return;throw o}}async getGithubPullRequestForBranch(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i;try{i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof Fn&&s.status===404)return;throw s}return cj.parse(i)}async getCommitFromGithub(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return iy.parse(r)}async getMergedBranchFromGithub(t,n,o,r){let i=encodeURIComponent(o),s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return vP.parse(s)}async getMergeBaseCommitFromGitlab(t,n,o){let r=new URLSearchParams;r.set("base",n),r.set("head",o);let i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return iy.parse(s)}async getGitlabMergeRequestForBranch(t,n){let o=new URLSearchParams;o.set("branch",n);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${fe}/git/gitlab/${r}/merge-requests?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof Fn&&s.status===404)return;throw s}return mj.parse(i)}async getCommitFromGitlab(t,n){let o=encodeURIComponent(t),r=await this.sendRequest(`/${fe}/git/gitlab/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return iy.parse(r)}async getMergedBranchFromGitlab(t,n,o){let r=encodeURIComponent(n),i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/${r}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return vP.parse(s)}async getAgentConfig(){let t=await this.sendRequest(`/${fe}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return z.record(z.string(),z.string()).parse(t)}async getOrgSettings(){try{let t=await this.sendRequest(`/${fe}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return WU(t)}catch(t){if(t instanceof Fn&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),wm.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${fe}/quarantine`,{method:"GET"});return Fz.parse(t)}async sendExploreSlackNotification(t){await this.sendRequest(`/${fe}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine`,{method:"POST",body:{testId:t.id,testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}async unquarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine/${t.id}`,{method:"DELETE",body:{testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}platformRoute(t){switch(t){case "ANDROID":return "android";case "IOS":return "ios"}}async createAndroidEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/android`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Uz.parse(n)}async extendEmulatorTtl(t,n){try{await this.sendRequest(`/${fe}/limbar/${this.platformRoute(t)}/${n}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3});}catch{}}async generateAssetUploadUrl({channel:t,tag:n,md5:o,platform:r}){let i={channel:t,tag:n,md5:o},s=await this.sendRequest(`/${fe}/limbar/${this.platformRoute(r)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:true});return Gz.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(`/${fe}/limbar/android/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(`/${fe}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jz.parse(t)}async getLimbarAssetDownloadUrl(t,n,o){let r=await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return $z.parse(r)}async deleteAsset(t,n,o){await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/ios`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Hz.parse(n)}async deleteIosEmulator(t){await this.sendRequest(`/${fe}/limbar/ios/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let n=await this.sendRequest(`/${fe}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return KG.parse(n)}async generateMcpSessionTraceUploadUrl(t){let n=await this.sendRequest(`/${fe}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return CP.parse(n)}};async function Lh(e){let t=process.versions.node,n=parseInt(t.split(".")[0]);(isNaN(n)||n<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${t}`);let o=await e.client.getAuthInfo();return R.debug("Got auth info from API"),o}var Od=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,n){await this.apiClient.reportBillableEvents(t,n);}};var Nd=class extends gi{generator;constructor(t,n){super(t),this.generator=n;}async runTemplateMatching(t,n={}){let o=await this.sendRequest(`/${fe}/web-agent/template-matching`,{method:"POST",body:t,signal:n?.signal});return vB.parse(o)}async constructIframeRegex(t,n={}){return this.generator.getIframeRegex(t,{abortSignal:n.signal,loggerTags:n.loggerTags})}};var kh=class{constructor(t,n){this.client=t;this.orgId=n;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return Km(t)}async acquireCacheLock(t,n){return this.client.acquireCacheLock(t,n)}async createOnDemandScreenshot(t,n,o){let{apiServerUrl:r}=await this.client.uploadOnDemandScreenshot({id:t,screenshot:n.toString("base64"),contentType:o});return {apiServerUrl:r,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${t}`,universalHandle:{id:t,contentType:o}}}async fetchOnDemandScreenshot(t){return this.client.fetchOnDemandScreenshot(t.id)}async releaseCacheLock(t){return this.client.releaseCacheLock(t)}async deleteCacheResult(t){return this.client.deleteCacheResult(t)}async setCacheResult(t){return this.client.setCacheResult(t)}async getCacheResult(t){return this.client.getCacheResult(t)}fetchIconKnowledgeBase(t){return this.client.fetchIconKnowledgeBase(t)}saveNewIcons(t,n){return this.client.saveNewIcons(t,n)}};var Tc="v1",yRe=2e3,l3="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",Ld=class{httpClient;fakerInstance;supportsLease;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this),lease:this.leasePhoneNumber.bind(this),release:this.releasePhoneNumber.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this),create:this.createEmail.bind(this)};activeLeases=new Map;constructor(t){this.httpClient=t.httpClient,this.supportsLease=t.supportsLease??true,t.fakerSeed&&(this.fakerInstance=new Faker({locale:en$1}),this.fakerInstance.seed(t.fakerSeed));}async sendSms(t){return this.httpClient.sendRequest(`/${Tc}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${Tc}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):n})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(l3);let n=await this.httpClient.sendRequest(`/${Tc}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof Fn?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),o=JG.parse(n);return this.activeLeases.set(o.phoneNumber,{leaseToken:o.leaseToken}),o}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(l3);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${Tc}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to release phone number: ${n.message}`)})}async dispose(){let t=[...this.activeLeases.entries()];this.activeLeases.clear(),await Promise.allSettled(t.map(([n,{leaseToken:o}])=>Re(this.httpClient.sendRequest(`/${Tc}/tools/sms/release`,{method:"POST",body:{phoneNumber:n,leaseToken:o}}),{milliseconds:yRe,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${Tc}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${Tc}/tools/email/fetchAll`,{method:"POST",body:t}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${Tc}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${Tc}/tools/email/create`,{method:"POST",body:{}}).catch(n=>{throw n instanceof Fn?new Error(n.rawError):new Error(`Failed to create email inbox: ${n.message}`)});return QG.parse(t)}};function c3(e,t,n){return fetch(e,{method:"PUT",body:n,headers:{"Content-Type":t}})}var oR=class{constructor(t){this.client=t;}async uploadResultsArchive(t){let{runGroupId:n,archive:o,persist:r}=t,{uploadUrl:i,id:s}=await this.client.generateTestResultsUploadUrl(),a=await c3(i,"application/zip",o);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:l}=await this.client.startProcessingResultsUpload(s,{runGroupId:n,persist:r});return l}};function ap({logger:e,orgId:t,client:n,gitMetadata:o,regenerateCache:r,alwaysSaveCache:i,noCache:s,isolateCachesByEnvironment:a=false,bustOldestCachePercentage:l}){return s?new BA:new jN(e,t,n,o,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:a})}var jN=class{constructor(t,n,o,r,i){this.orgId=n;this.client=o;let{regenerateCache:s,alwaysSaveCache:a,bustOldestCachePercentage:l,isolateCachesByEnvironment:c}=i,{gitBranchName:d,gitProtectedBranches:u}=r;t.info({options:i,gitBranchName:d,gitProtectedBranches:u},"Cache storage initialization options"),this.cacheHeaders=FA(r),this.isolateCachesByEnvironment=c,this.readCaches=!s;let p=d&&u.includes(d);a||!p?this.writeCaches=true:this.writeCaches=false,p||(this.bustOldestCachePercentage=l);}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:wP(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save step cache entries");}}async saveSnapshotCacheEntries({entries:t,logger:n}){if(t.length!==0){if(!this.writeCaches){n.debug("Skipping snapshot cache storage because branch is protected");return}try{await this.client.updateSnapshotCaches({entries:wP(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save snapshot cache entries");}}}async deleteStepCacheEntry({logger:t,testId:n,key:o,environment:r}){try{await this.client.deleteStepCacheEntry({testId:n,key:o,environment:this.isolateCachesByEnvironment?r:void 0},this.cacheHeaders);}catch(i){t.error({err:i},"Failed to delete step cache entry");}}async resolveStepCacheEntries(t){if(!this.readCaches){t.logger.debug("Skipping cache resolution because of regenerate flag");return}let n=t.useSnapshotIdentityCache?await this.tryRestoreStepIdsFromSnapshot(t):void 0,{steps:o,beforeSteps:r,afterSteps:i}=t.stepLists,s=await this.client.getStepCacheForTest({testId:t.testId,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);if(this.bustOldestCachePercentage!==void 0){let u=Object.entries(s).map(([h,g])=>({key:h,time:g.value.cache?.updatedAt?.getTime()??0}));u.sort((h,g)=>h.time-g.time);let p=u.length,m=Math.max(1,Math.floor(p*this.bustOldestCachePercentage/100));u.slice(0,m).forEach(({key:h})=>{delete s[h];}),t.logger.info({nCachesToBust:m,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:p},"Busted oldest caches");}let a={totalSteps:0,cacheKeysHit:[],cacheKeysMissed:[],uniqueKeysHit:[],cacheMissSamples:[]};for(let u of [o,r,i]){if(!u)continue;let p=ju({steps:u,stepCacheEntries:s,logger:t.logger});a.totalSteps+=p.totalSteps,a.cacheKeysHit.push(...p.cacheKeysHit),a.cacheKeysMissed.push(...p.cacheKeysMissed),a.uniqueKeysHit.push(...p.uniqueKeysHit),a.cacheMissSamples.push(...p.cacheMissSamples);}n&&bRe({cacheResolutionStats:a,logger:t.logger,restoredIdentity:n,schemaVersion:t.schemaVersion,testId:t.testId});let l=["platform:web","source:local",`fileFormat:${t.useSnapshotIdentityCache?"v2":"v1"}`,`snapshotIdentityCache:${t.useSnapshotIdentityCache}`,`orgId:${this.orgId}`,"cliVersion:2.138.3"];if(gt.increment("step_cache_resolution",a.cacheKeysHit.length,[...l,"outcome:hit"]),gt.increment("step_cache_resolution",a.cacheKeysMissed.length,[...l,"outcome:miss"]),gt.increment("step_cache_resolution",a.totalSteps,[...l,"outcome:total"]),!this.writeCaches){t.logger.debug("Skipping cache last used at update because branch is protected");return}let{cachesToSave:c,snapshotCachesToSave:d}=await An({stepLists:t.stepLists,useSnapshotIdentityCache:t.useSnapshotIdentityCache,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});t.useSnapshotIdentityCache&&this.saveSnapshotCacheEntries({entries:d,logger:t.logger}),this.saveStepCacheEntries({entries:c,logger:t.logger});}async tryRestoreStepIdsFromSnapshot(t){try{return await this.restoreStepIdsFromSnapshot(t)}catch(n){t.logger.warn({err:n,testId:t.testId},"Failed to restore step ids from snapshot cache; proceeding without identity cache"),gt.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:2.138.3","outcome:identity_restore_error"]);return}}async restoreStepIdsFromSnapshot(t){let{logger:n,testId:o}=t,r=await this.client.getSnapshotCacheForTest({testId:o,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders),i=hC({entries:r,orgId:this.orgId,testId:o,logger:n}),s=mC({currentStepLists:t.stepLists,previousSnapshot:i.testSnapshot,previousModuleSnapshots:i.moduleSnapshots,generateUuid:randomUUID});return t.stepLists.steps.splice(0,t.stepLists.steps.length,...s.stepLists.steps),t.stepLists.beforeSteps=s.stepLists.beforeSteps,t.stepLists.afterSteps=s.stepLists.afterSteps,n.debug({snapshotEntries:r.length,testSnapshotHit:!!i.testSnapshot,moduleSnapshots:Array.from(i.moduleSnapshots.keys()),mintedSteps:s.stats.mintedSteps,stats:s.stats,moduleRestoreResults:s.moduleRestoreResults.map(({moduleId:a,snapshotHit:l,stats:c})=>({moduleId:a,snapshotHit:l,stats:c}))},"Restored step ids from snapshot cache"),s}};function bRe({cacheResolutionStats:e,logger:t,restoredIdentity:n,schemaVersion:o,testId:r}){let i=e.cacheKeysHit.length,s=e.cacheKeysMissed.length,a=i+s,l=a>0?Math.round(s/a*1e3)/10:0,c=n.stats.matchedSteps+n.stats.mintedSteps,d=c>0?Math.round(n.stats.mintedSteps/c*1e3)/10:0,u=n.moduleRestoreResults.filter(({snapshotHit:g,stats:f})=>!g||f.mintedSteps>0||f.bustedConditionals>0).slice(0,10).map(({moduleId:g,snapshotHit:f,stats:b})=>({moduleId:g,snapshotHit:f,stats:b})),p=n.stats.mintedSteps>=5&&d>=25,m=p||n.stats.bustedConditionals>0||u.some(({stats:g})=>g.mintedSteps>=5||g.bustedConditionals>0),h={cacheHits:i,cacheMissRate:l,cacheMisses:s,cacheMissSamples:e.cacheMissSamples.slice(0,10),hasHighMintRate:p,identityMintRate:d,moduleIdentityIssueCount:u.length,moduleIdentityIssues:u,schemaVersion:o,snapshotIdentityCache:true,stepIdentityStats:n.stats,testId:r,totalCacheableSteps:e.totalSteps};if(!m){t.debug(h,"V2 cache resolution completed");return}t.warn(h,"V2 cache resolution degraded");}function TRe(e){let t=new d3,n=En__default.join(e,Ze),o=fs.parse(JSON.parse(Mo__default.readFileSync(n,"utf-8")));t.addLocalFile(n);for(let r of Mo__default.readdirSync(En__default.join(e,wn))){if(!r.endsWith(".zip"))continue;let i=r.replace(/\.zip$/,""),s=new d3(En__default.join(e,wn,r));for(let a of s.getEntries())a.isDirectory||t.addFile(En__default.join(wn,i,a.entryName),a.getData());}return {runGroupId:o.id,buffer:t.toBuffer()}}async function aS(e){let{client:t,resultsPath:n,persist:o}=e;if(!Mo__default.existsSync(n))return {success:false,error:"results path does not exist"};let r=new oR(t);try{let{runGroupId:i,buffer:s}=TRe(n),a=await r.uploadResultsArchive({runGroupId:i,archive:s,persist:o});return {success:!0,runGroupUrl:`${t.getAppUrl()}/run-groups/${a}`}}catch(i){return {success:false,error:Q(i)}}}var lS=class e{constructor(t){this.filePath=t;Mo__default.rmSync(this.filePath,{recursive:true,force:true}),Mo__default.mkdirSync(this.filePath,{recursive:true});}children=[];streams=[];close(){for(let t of this.children)t.close();for(let t of this.streams)t.end();}cd(t){let n=new e(En__default.join(this.filePath,t));return this.children.push(n),n}cwd(){return this.filePath}mkdir(t){Mo__default.mkdirSync(En__default.join(this.filePath,t),{recursive:true});}readFile(t){let n=En__default.join(this.filePath,t);if(Mo__default.existsSync(n))return Mo__default.readFileSync(n)}storeFile(t){let{name:n,contents:o}=t,r=En__default.join(this.filePath,n);try{Mo__default.mkdirSync(En__default.dirname(r),{recursive:!0}),Mo__default.writeFileSync(r,o);}catch{}}createFileStream(t){let n=En__default.join(this.filePath,t),o=Mo__default.createWriteStream(n);return this.streams.push(o),o}createRunArchive(t,n){let o=new VN(En__default.join(this.filePath,wn),t,n);return this.children.push(o),o}},VN=class{children=[];tempPath;finalPath;logger;closed=false;constructor(t,n,o){this.tempPath=En__default.join(t,`temp-storage-${n}`),this.finalPath=En__default.join(t,`${n}.zip`),this.logger=o,Mo__default.rmSync(this.tempPath,{recursive:true,force:true}),Mo__default.rmSync(this.finalPath,{recursive:true,force:true}),Mo__default.mkdirSync(this.tempPath,{recursive:true});}readFile(t){let n=En__default.join(this.tempPath,t);if(Mo__default.existsSync(n))return Mo__default.readFileSync(n)}mkdir(t){Mo__default.mkdirSync(En__default.join(this.tempPath,t),{recursive:true});}cd(t){let n=new lS(En__default.join(this.tempPath,t));return this.children.push(n),n}cwd(){return this.tempPath}storeFile(t){if(this.closed)return;let{name:n,contents:o}=t,r=En__default.join(this.tempPath,n);Mo__default.mkdirSync(En__default.dirname(r),{recursive:true}),Mo__default.writeFileSync(r,o);}close(){if(!this.closed){this.closed=true;for(let t of this.children)t.close();try{let t=new d3;t.addLocalFolder(this.tempPath,void 0,o=>o!==".DS_Store");let n=t.toBuffer();Mo__default.writeFileSync(this.finalPath,n),Mo__default.rmSync(this.tempPath,{recursive:!0,force:!0});}catch(t){this.logger.warn({err:t,finalPath:this.finalPath,tempPath:this.tempPath},"Failed to archive run artifacts; leaving raw files on disk");}}}};function h3(e){try{return Mo__default.existsSync(e)?JSON.parse(Mo__default.readFileSync(e,"utf-8")):void 0}catch{return}}function u3(e){return Mo__default.existsSync(e)?Mo__default.readFileSync(e,"utf-8").split(`
274
274
  `).map(n=>n.trim()).filter(n=>n.length>0):[]}function RRe(e,t){let n=e.attemptIdToAttemptNumber.get(t);if(n)return En__default.join(e.inflatedPath,"attempts",n);let o=En__default.join(e.inflatedPath,"attempts");if(!Mo__default.existsSync(o))return;let r=Mo__default.readdirSync(o,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of r){let s=En__default.join(o,i,Ze),a=h3(s);if(typeof a!="object"||a===null)continue;let l=a.id;if(typeof l=="string"&&l===t)return e.attemptIdToAttemptNumber.set(t,i),En__default.join(o,i)}}function p3(e,t,n){let o=En__default.join(e,"attempts");if(!Mo__default.existsSync(o))return;let r=Mo__default.readdirSync(o,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of r){let s=En__default.join(o,i,"assets",`${t}.${n}`);if(Mo__default.existsSync(s))return s}}var iR=class{constructor(t,n,o){this.outputDir=t;this.runId=n;this.runAttemptId=o;this.runsDir=En__default.join(t,wn),this.zipPath=En__default.join(this.runsDir,`${n}.zip`);}inflatedByRunId=new Map;zipPath;runsDir;ensureInflatedRun(t){let n=this.inflatedByRunId.get(t);if(n)return n;if(t!==this.runId||!Mo__default.existsSync(this.zipPath))return;let o=En__default.join(this.runsDir,`temp-unzipped-${t}-${randomUUID()}`);Mo__default.mkdirSync(o,{recursive:true}),new d3(this.zipPath).extractAllTo(o,true);let i={runId:t,zipPath:this.zipPath,inflatedPath:o,attemptIdToAttemptNumber:new Map};return this.inflatedByRunId.set(t,i),i}close(){for(let t of this.inflatedByRunId.values())Mo__default.rmSync(t.inflatedPath,{recursive:true,force:true});this.inflatedByRunId.clear();}getAttemptDir(){let t=this.ensureInflatedRun(this.runId);if(t)return RRe(t,this.runAttemptId)}listVideoAssetPaths(){let t=this.getAttemptDir();if(!t)return [];let n=En__default.join(t,"assets");return Mo__default.existsSync(n)?Mo__default.readdirSync(n,{withFileTypes:true}).filter(r=>r.isFile()).map(r=>En__default.join(n,r.name)).filter(r=>{let i=En__default.extname(r).toLowerCase();return i===".webm"||i===".mp4"}):[]}readAttemptAssetText(t,n){let o=this.getAttemptDir();if(!o)return;let r=En__default.join(o,"assets",`${t}.${n}`);if(Mo__default.existsSync(r))try{return Mo__default.readFileSync(r,"utf-8")}catch{return}}async getConsoleLogsForRunAttempt(t,n,o){if(n!==this.runId||o!==this.runAttemptId)return;let r=this.getAttemptDir();if(!r)return;let i=h3(En__default.join(r,"console.json")),s=q_.safeParse(i);return s.success?s.data:void 0}async getNetworkLogsForRunAttempt(t,n,o){if(n!==this.runId||o!==this.runAttemptId)return;let r=this.getAttemptDir();if(!r)return;let i=En__default.join(r,"assets","har-pages.log"),s=En__default.join(r,"assets","har-entries.log"),a={};for(let d of u3(i)){let u=Wf.safeParse(m3(d));u.success&&(a[u.data.id]=u.data);}let l={},c=u3(s);for(let d=0;d<c.length;d++){let u=c[d],p=qf.safeParse(m3(u));if(!p.success)continue;let m=`${p.data.startedDateTime}-${d}`;l[m]=p.data;}if(Object.keys(l).length!==0)return K_(a,l)}async getHtmlSnapshot(t,n){let o=this.readAttemptAssetText(n,"html");if(o)return o;let r=this.ensureInflatedRun(this.runId);if(!r)return;let i=p3(r.inflatedPath,n,"html");if(i)try{return Mo__default.readFileSync(i,"utf-8")}catch{return}}async getA11yTreeSnapshot(t,n){let o=this.readAttemptAssetText(n,"xml");if(o)return o;let r=this.ensureInflatedRun(this.runId);if(!r)return;let i=p3(r.inflatedPath,n,"xml");if(i)try{return Mo__default.readFileSync(i,"utf-8")}catch{return}}async getScreenshot(t,n){if(!this.ensureInflatedRun(this.runId))return;let r=this.getAttemptDir();if(r)for(let i of ["png","jpeg"])try{return Mo__default.readFileSync(En__default.join(r,"assets",`${n}.${i}`))}catch{continue}}};function m3(e){try{return JSON.parse(e)}catch{return}}function g3(e,t){let n=vRe(e);return n==="EACCES"||n==="EPERM"?{status:403,body:{error:`Permission denied: ${t}`}}:n==="ENOENT"?{status:404,body:{error:`Not found: ${t}`}}:n==="ENOTDIR"?{status:400,body:{error:`Not a directory: ${t}`}}:n==="EISDIR"?{status:400,body:{error:`Is a directory: ${t}`}}:n==="EEXIST"?{status:409,body:{error:`Already exists: ${t}`}}:n==="ENOTEMPTY"?{status:409,body:{error:`Directory is not empty: ${t}`}}:{status:500,body:{error:`${t}: ${Q(e)}`}}}function vRe(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}function sR({test:e,envNameOverride:t,urlOverride:n,resolveEnv:o}){let r=t??wRe(e),i,s={};if(r){try{i=o(r);}catch(l){let c=`Failed to resolve environment ${r} for test ${e.name}: ${Q(l)}`;throw l instanceof _e?new _e(c,{cause:l}):new Error(c,{cause:l})}s=i.variables;}let a=e.baseUrl;if(n)a=n;else if(!a){let l=s[Bo];typeof l=="string"&&(a=l);}if(!a)throw new Error(`Cannot run test with no base URL and no ${Bo} variable defined in its environment`);return {envName:r,resolvedEnv:i,environmentVariables:s,baseUrl:a}}function wRe(e){for(let t of e.envs??[])if(t.default)return t.name}async function cS(e,t,n,o,r=st){let i=o??await je(e,false,r),s=i[n],a=IRe(s,t);if(t.id){if(a.length===0)throw new dt(`No ${n} found with id '${t.id}' in project '${e.rootDir}'.`);return aR(a,i)}if(t.name){if(a.length===0)throw new dt(`No ${n} found with exact name '${t.name}' in project '${e.rootDir}'.`);if(a.length>1){let l=a.map(c=>({id:c.id,path:c.relativePath}));throw new dt([`Multiple ${n} found with exact name '${t.name}'. Please disambiguate by id or path.`,JSON.stringify(l,null,2)].join(`
275
275
  `))}return aR(a,i)}if(t.path){let l=t.path;if(a.length===0)throw new dt(`No ${n} found at path '${l}'. Provide an absolute path or a path relative to '${e.rootDir}'.`);if(a.length>1){let c=a.filter(u=>u.fullFilePath===l||u.relativePath===l||u.fullFilePath.endsWith(`/${l}`)||u.relativePath.endsWith(`/${l}`));if(c.length===1)return aR(c,i);let d=a.map(u=>({id:u.id,path:u.fullFilePath}));throw new dt([`Multiple ${n} matched the provided path '${l}'. Please pass the absolute path.`,JSON.stringify(d,null,2)].join(`
276
276
  `))}return aR(a,i)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function aR(e,t){let n=e[0];if(!n)throw e.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return {entity:n,momenticFiles:t}}function IRe(e,t){if(t.id){let n=Object.values(e).find(o=>o.id===t.id);return n?[n]:[]}if(t.name)return Object.values(e).filter(n=>n.name===t.name);if(t.path){let n=t.path;return Object.values(e).filter(o=>o.fullFilePath.includes(n)||o.relativePath.includes(n))}throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}async function f3({cwd:e,projectName:t}){let n=En__default.join(e,pl);if(Mo__default.existsSync(n))throw new Error(`A ${pl} file already exists at ${n}. Please rename or remove it to initialize a new project.`);let o=await VY(e)??"main",r={name:t,include:wh,gitMainBranch:o,fileFormat:"v2",ai:{useMemory:true,failureRecovery:true,agentConfig:{...xm}}};return Sc(r,n),{configPath:n}}var PRe="npx skills@latest add momentic-ai/skills",MRe="https://momentic.ai/docs/integrations/mcp-server",ORe={web:["https://momentic.ai/docs/quickstart/web"],mobile:["https://momentic.ai/docs/quickstart/ios","https://momentic.ai/docs/quickstart/android"]};function y3({platform:e}){let t="npx momentic app",n=ORe[e].map(r=>Qs.underline.cyan(r)).join(Qs.dim(" \xB7 ")),o=(r,i)=>` ${Qs.dim(r.padEnd(14))}${i}`;R.log(""),R.log(Qs.bold("Next steps")),R.log(o("Editor skills",Qs.cyan(PRe))),R.log(o("Coding agent",`${Qs.dim("Momentic MCP \u2192")} ${Qs.underline.cyan(MRe)}`)),R.log(o("Local editor",Qs.cyan(t))),R.log(o("Docs",n));}var S3=["cursor","claude-code","codex","opencode","copilot"],LRe={cursor:En__default.join(".cursor","skills"),"claude-code":En__default.join(".claude","skills"),codex:En__default.join(".agents","skills"),opencode:En__default.join(".opencode","skills"),copilot:En__default.join(".github","skills")};function b3({editor:e,skillsDir:t,cwd:n=process.cwd()}){Mo__default.existsSync(t)||(R.error(`Could not find skills directory at ${t}. Is the CLI package installed correctly?`),process.exit(1));let o=Mo__default.readdirSync(t).filter(s=>s.endsWith(".md"));o.length===0&&(R.error(`No skill markdown files found in ${t}. Is the CLI package installed correctly?`),process.exit(1));let r=kRe({cwd:n}),i=En__default.join(r,LRe[e]);for(let s of o){let a=En__default.basename(s,".md"),l=En__default.join(i,a),c=Mo__default.readFileSync(En__default.join(t,s),"utf8");Mo__default.mkdirSync(l,{recursive:true}),Mo__default.writeFileSync(En__default.join(l,"SKILL.md"),c),R.success(`Installed SKILL.md at ${En__default.join(l,"SKILL.md")}.`);}}function kRe({cwd:e}){try{return execSync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||e}catch{return e}}var A3=En__default.join(sc.homedir(),".momentic"),Ac=En__default.join(A3,"auth.json"),FRe=new Set(["EPERM","EACCES","EROFS"]),BRe=z.object({workos:z.object({accessToken:z.string(),refreshToken:z.string(),expiresAt:z.number()}),user:z.object({id:z.string(),email:z.string().optional()}),organizationId:z.string(),apiKey:z.string(),apiKeyName:z.string(),serverUrl:z.string(),createdAt:z.string(),selfServe:z.boolean().optional()});function E3(){if(!Mo__default.existsSync(Ac))return null;try{let e=Mo__default.readFileSync(Ac,"utf-8"),t=BRe.safeParse(JSON.parse(e));return t.success?t.data:null}catch{return null}}function C3(e){try{Mo__default.mkdirSync(A3,{recursive:!0,mode:448}),Mo__default.writeFileSync(Ac,JSON.stringify(e,null,2),{mode:384});}catch(t){throw h2(t)&&FRe.has(t.code)?new _e(`Couldn't save your Momentic credentials to ${Ac} (${t.code}). Make sure that file and its parent directory are writable and owned by you \u2014 for example, they may have been created by a previous \`sudo\` run. Fix the permissions and try again.`,{cause:t}):t}}function R3(){return Mo__default.existsSync(Ac)?(Mo__default.unlinkSync(Ac),true):false}function lR(){return E3()?.apiKey||void 0}function cR(){return E3()?.serverUrl||void 0}var zN="client_01HM3P9MPY20QDSXAECT6PY1JF",v3="https://api.workos.com";async function w3({clientId:e}){let t=await fetch(`${v3}/user_management/authorize/device`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e}).toString()});if(!t.ok)throw new Error(`WorkOS device authorization failed (${t.status}): ${await t.text()}`);return await t.json()}async function I3({clientId:e,deviceCode:t,interval:n,expiresIn:o,onProgress:r}){let i=Date.now()+o*1e3,s=Math.max(n,1);for(;Date.now()<i;){await URe(s*1e3);let a=await fetch(`${v3}/user_management/authenticate`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t,client_id:e}).toString()});if(a.ok)return await a.json();let l=await a.json().catch(()=>({})),c=l.error??"";if(c==="authorization_pending"){r?.("polling");continue}if(c==="slow_down"){s+=5,r?.("slow_down");continue}throw c==="expired_token"?new _e("The login request expired. Please run `login` again."):c==="access_denied"?new _e("Login was denied."):new Error(`WorkOS device token exchange failed: ${l.error_description??c??a.statusText}`)}throw new _e("Timed out waiting for sign-in. Please run `login` again.")}function URe(e){return new Promise(t=>setTimeout(t,e))}async function WN({serverUrl:e,body:t}){let n=await fetch(`${e}/v1/auth/exchange-workos-token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),o=await n.text(),r;try{r=o?JSON.parse(o):void 0;}catch{}if(n.status===200){let s=_z.safeParse(r);if(s.success)return {kind:"ok",data:s.data}}if(n.status===409){let s=Pz.safeParse(r);if(s.success)return {kind:"multi_org",data:s.data}}let i=HRe(r)??o??n.statusText;return {kind:"error",status:n.status,message:i}}function HRe(e){if(e&&typeof e=="object"&&"error"in e){let{error:t}=e;if(typeof t=="string")return t}}async function _3({serverUrl:e,ui:t,openBrowser:n=true,clientName:o=sc.hostname(),coldRun:r=false}){let i=await w3({clientId:zN}),s=i.verification_uri_complete??i.verification_uri,a=r?"Create account or sign in":"Sign in",l=r?"Waiting for you to create your account or sign in...":"Waiting for you to sign in...",c=r?"Waiting for you to create your account or sign in (slowing polling)...":"Waiting for you to sign in (slowing polling)...";if(t.note(`${Qs.bold(i.user_code)}
@@ -292,7 +292,7 @@ ${l}`:a}function KN(e,t,n={}){if(e.length===0)return "";let o=Go(t),r=Math.max(n
292
292
  `);return zRe(l,{borderStyle:t.unicode?"round":"classic",borderColor:t.colorLevel>0?"yellow":void 0,padding:1,margin:{left:2},textAlignment:"center"})}var ive=40,G3=100,sve=" ",ave=/\*\*[^*]+\*\*|__[^_]+__|`[^`\n]+`/g,lve=/^\s*#{1,6}\s+/;function Fd(e,t,n={}){let o=n.dim?t.dim:a=>a,r=e.replace(lve,""),i="",s=0;for(let a of r.matchAll(ave)){a.index>s&&(i+=o(r.slice(s,a.index)));let l=a[0];i+=l.startsWith("`")?t.code(l.slice(1,-1)):t.bold(l.slice(2,-2)),s=a.index+l.length;}return s<r.length&&(i+=o(r.slice(s))),i}function Rs({label:e,text:t,screen:n,indent:o=2,labelWidth:r}){let i=t.trim();if(i.length===0)return [];let s=Go(n),a=" ".repeat(o),l=Math.max(e.length,r??e.length),c=l>0?sve:"",d=a.length+l+c.length,u=" ".repeat(d),p=n.columns>0?n.columns:G3,m=Math.max(ive-d,Math.min(G3,p)-d),h=[];for(let g of i.split(`
293
293
  `)){if(g.trim().length===0){h.push("");continue}let f=Fd(g,s,{dim:true});h.push(...Uh(f,m));}return h.map((g,f)=>f===0&&l>0?`${a}${s.dim(e.padEnd(l))}${c}${g}`:g.length===0?"":`${u}${g}`)}var cve="https://registry.npmjs.org",dve=z.object({versions:z.record(z.string(),z.unknown().optional()).optional()});async function j3({packageName:e,currentVersion:t}){let n=await Re(fetch(`${cve}/${e}`),{milliseconds:5e3});if(!n.ok)throw new Error(`Got error status code ${n.status} ${n.statusText}`);let o=await n.json(),r=dve.parse(o).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let i=Hh.major(t),s=t;for(let a of Object.keys(r))Hh.valid(a)&&Hh.prerelease(a)===null&&Hh.major(a)===i&&Hh.gt(a,s)&&(s=a);return s}function $3(e){return {checkCLIVersion:t=>uve({...e,logger:t}),getLatestCLIVersion:()=>j3({packageName:e.packageName,currentVersion:e.currentVersion})}}async function uve(e){let t=e.screen??Xt();if(!(process.env.NO_UPDATE_NOTIFIER||t.ci||!t.isTTY))try{let n=await j3({packageName:e.packageName,currentVersion:e.currentVersion});if(Hh.eq(e.currentVersion,n))return;let o=H3({currentVersion:e.currentVersion,latestVersion:n,changelogUrl:e.changelogUrl,updateCommand:e.updateCommand},t);R.log(`
294
294
  ${o}
295
- `);}catch(n){e.logger.warn({err:n},"Failed to check CLI version against npm");}}var mS=25;function V3(e){let t="v2";return {v2ProjectConfig:{...e.config,fileFormat:t},migratedFilePaths:[]}}function z3(e){let t="v1";return {legacyProjectConfig:{...e.config,fileFormat:t},migratedFilePaths:[]}}function YN({project:e,newProjectConfig:t,fileFormatLabel:n,migratedFilePaths:o}){e.config=t,Sc(e.config,e.configFilePath),o.push(e.configFilePath),R.info(`Updated ${e.configFilePath} to use ${n} file format`),t.hooks?.postSave&&(R.info(`Running post-save hook for ${o.length} migrated files`),MC([...new Set(o)],t));}async function hS(e,t,n){for(let o=0;o<e.length;o+=t)await Promise.all(e.slice(o,o+t).map(n));}function JN(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function pve(e){let t=e.ai??={},n=t.agentConfig??={},o=[];for(let[s,a]of Object.entries(xm)){let l=n[s];l!==a&&(l?.startsWith(`${a}.`)||(n[s]=a,o.push({type:s,newValue:a})));}let r=t.useMemory!==true;r&&(t.useMemory=true);let i=t.failureRecovery!==true;return i&&(t.failureRecovery=true),{upgradedAgents:o,enabledUseMemory:r,enabledFailureRecovery:i}}async function W3({project:e,dryRun:t,migrate:n}){let o=e.config.fileFormat!=="v2",r=pve(e.config);return o?{fileFormatChanged:o,aiSettings:r,migration:await n()}:(!t&&JN(r)&&Sc(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:r,migration:QN()})}function QN(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function XN({summary:e,fileFormatChanged:t,aiSettings:n,dryRun:o,testNoun:r="test",moduleNoun:i="module"}){let s=o?"Would migrate":"Migrated",a=vy(r,e.migratedTestPaths.length),l=vy(i,e.migratedModulePaths.length);R.info(`${s} ${e.migratedTestPaths.length} ${a} and ${e.migratedModulePaths.length} ${l} to v2.`),(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&R.dimmed(` Skipped ${e.alreadyV2TestCount} already-v2 ${vy(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-v2 ${vy(i,e.alreadyV2ModuleCount)}.`),t&&R.dimmed(" + fileFormat: v2");for(let c of n.upgradedAgents)R.dimmed(` + ai.agentConfig.${c.type}: ${c.newValue}`);n.enabledUseMemory&&R.dimmed(" + ai.useMemory: true"),n.enabledFailureRecovery&&R.dimmed(" + ai.failureRecovery: true");}var ZN=false,q3;try{let e=await import('@sentry/node');e.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",dist:"production",release:"cli-2.138.2",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(t,n){return a2(n?.originalException)||l2(n?.originalException)||c2(n?.originalException)||eO(n?.originalException)||bT(n?.originalException,_e)||d2(n?.originalException)?null:t}}),N1(e.captureException),q3=t=>{if(!t){e.setUser(null);return}e.setUser({id:t.userId,organizationId:t.orgId,...t.email&&{email:t.email}});},ZN=!0;}catch{}var K3=e=>q3?.(e);var hve=new BE(30,60*1e3),RR="https://api.momentic.ai",bR,Y3,Bd=e=>{RR=e;},wr=()=>RR,J3=()=>Km(RR),Ec=e=>{Y3=e;},Cc=()=>Y3,go=()=>bR;var gS,TR,Q3,X3,Z3,AR,eQ,tQ=({authInfo:e,apiKey:t,apiClient:n})=>{bR=n,gS=e.orgId,TR=e.userId,Q3=e.email,X3=e.name,Z3=e.pylonEmailHash,AR=t,eQ=e.selfServe;},fS=async({apiClient:e,apiKey:t,skipPrompts:n})=>{let o=await Lh({client:e});return tQ({authInfo:o,apiKey:t,apiClient:e}),o},vR=async e=>{if(bR&&gS&&AR)return gS;let t=new Dt({baseUrl:RR,apiKey:e,logger:R});bR=t;try{let n=await t.getAuthInfo();return tQ({authInfo:n,apiKey:e,apiClient:t}),n.orgId}catch(n){throw new Error(`Error checking API key against server: ${n}`,{cause:n})}},Bn=()=>{if(!gS)throw new Error("Your organization ID is invalid.");return gS},gl=()=>{if(!TR)throw new Error("Your user ID is invalid.");return TR},nQ=()=>TR,Gh=()=>Q3,oQ=()=>X3,rQ=()=>Z3,wR=()=>eQ,vs=()=>{if(!AR)throw new Error("Your API key is invalid.");return AR},ER,CR,fl=()=>{CR?.abort(),CR=void 0;},lp=(e,t)=>{ER=e,fl(),CR=new AbortController;let n=CR.signal,o=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=En__default.resolve(e.rootDir,r.envFile);try{if(Mo__default.lstatSync(i).isSymbolicLink())return;Mo__default.existsSync(i)&&o.push(i);}catch(s){R.warn({err:s},`Failed to check if env file ${i} exists`);}});try{gve({filesToWatch:o,revalidator:t,signal:n,project:e});}catch(r){R.error({err:r},"Failed to start config file watchers");}};async function jh({project:e,apiClient:t}){let n=o=>aa({project:o,apiClient:t});lp(await n(e),async o=>n(await an({configFilePath:o})));}var Qe=()=>{if(!ER)throw new _e("No Momentic project is currently loaded. Open or select a project before invoking this action.");return ER};function gve({filesToWatch:e,revalidator:t,signal:n,project:o}){R.debug("Starting watch on the following files:"),e.forEach(r=>{R.debug(`- ${r}`);}),e.forEach(r=>{let i=async(a,l)=>{a.mtime.getTime()!==l.mtime.getTime()&&(hve.increment("setLocalProject")&&R.warn(`A file change under the ${o.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),ER=await Promise.resolve(t(o.configFilePath)));};Mo__default.watchFile(r,{persistent:false},i);let s=()=>{Mo__default.unwatchFile(r,i),n.removeEventListener("abort",s);};n.addEventListener("abort",s);});}function ut(e){return function(...t){let n=t[t.length-1],o=e(...t);Promise.resolve(o).catch(n);}}var yve="2.138.2",cp=Jm({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:yve});(async()=>{try{let e=await Cs(cp);e.gitBranchName&&cp.addBinding("branch",e.gitBranchName);}catch{}})();var iQ=Router();iQ.get("/",async(e,t)=>{let n=Qe(),o=go();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Rr(cp,o,n),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:s,alwaysSaveCache:a}=Cc(),l=!s&&(a||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var eL=iQ;var Tve=5e3,Ave=[".js",".mjs",".cjs",".ts"];function tL(e={}){let t=Router();function n(){let u=Qe();return En__default.dirname(u.configFilePath)}function o(u){return En__default.join(n(),...u)}function r(u){let p=En__default.relative(n(),u);return p?p.split(En__default.sep):[]}function i(u,p){let m=Mo__default.statSync(u),h=r(u);return tP.parse({name:p,absolutePath:u,relativePath:h.join(En__default.sep),pathSegments:h,isDirectory:m.isDirectory(),size:m.size,createdAt:m.birthtime,modifiedAt:m.mtime,accessedAt:m.atime})}function s(u){let p=En__default.relative(n(),u);return p===""||!p.startsWith("..")&&!En__default.isAbsolute(p)}async function a(u){let p=Qe();return gc(["*"],{cwd:u,ignore:p.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(Tve)})}function l(u){let p=u.trimStart().replace(/^file:\/\//,"").replaceAll("\\","/"),m=p.lastIndexOf("/");return m===-1?{directoryText:"",filePrefix:p}:{directoryText:p.slice(0,m+1),filePrefix:p.slice(m+1)}}function c(u){return u.replaceAll("\\","/").split("/").filter(p=>p&&p!==".")}function d({sourceDirectoryPath:u,targetPath:p,isDirectory:m}){let h=En__default.relative(u,p).split(En__default.sep).join("/");return m?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",ut(async(u,p,m)=>{let h=Lj.safeParse(u.body);if(!h.success){p.status(400).json({error:`Failed to parse file-reference-suggestions body: ${h.error.message}`});return}let{sourceDirectoryPath:g="",value:f}=h.data,b=new Set((h.data.allowedExtensions??Ave).map(E=>E.toLowerCase())),T=l(f);if(T.directoryText.startsWith("/")){p.status(200).json({suggestions:[]});return}let A=En__default.resolve(n(),...c(g)),C=En__default.resolve(A,...c(T.directoryText));if(!s(A)||!s(C)){p.status(200).json({suggestions:[]});return}if(!Mo__default.existsSync(C)||!Mo__default.statSync(C).isDirectory()){p.status(200).json({suggestions:[]});return}let v;try{v=await a(C);}catch(E){if(E instanceof Error&&E.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw E}let I=v.map(E=>{let O=En__default.join(C,E);return {entryName:E,targetPath:O,isDirectory:Mo__default.statSync(O).isDirectory()}}),_=T.filePrefix.toLowerCase(),x=I.filter(E=>E.entryName.startsWith(".")||!E.entryName.toLowerCase().startsWith(_)?false:E.isDirectory?true:b.has(En__default.extname(E.entryName).toLowerCase())).sort((E,O)=>E.isDirectory!==O.isDirectory?E.isDirectory?-1:1:E.entryName.localeCompare(O.entryName)).map(E=>({name:E.entryName,isDirectory:E.isDirectory,value:d({sourceDirectoryPath:A,targetPath:E.targetPath,isDirectory:E.isDirectory})}));p.status(200).json({suggestions:x});})),t.post("/",ut(async(u,p,m)=>{let h;try{h=Nj.parse(u.body).pathSegments;}catch(C){p.status(400).json({error:`Failed to parse folder read body: ${C}`});return}let g=o(h);if(!Mo__default.existsSync(g)){p.status(404).json({error:`Path not found: ${h.join(En__default.sep)}`});return}if(!Mo__default.statSync(g).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(En__default.sep)}`});return}let b;try{b=await a(g);}catch(C){if(C instanceof Error&&C.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw C}let T=b.map(C=>{let v=En__default.join(g,C);return i(v,C)});if(e.allowedFileTypes){let C=new Set(e.allowedFileTypes);T=(await Promise.all(T.map(async v=>{if(v.isDirectory||!(v.name.endsWith(".test.yaml")||v.name.endsWith(".module.yaml")))return v;let _=await Eve(v.absolutePath);return _!==void 0&&C.has(_)?v:null}))).filter(v=>v!==null);}let A={absolutePath:g,pathSegments:h,contents:T};p.status(200).json(A);})),t.put("/",ut(async(u,p,m)=>{let h;try{h=kj.parse(u.body).pathSegments;}catch(b){p.status(400).json({error:`Failed to parse folder create body: ${b}`});return}let g=o(h);if(Mo__default.existsSync(g)){p.status(200).json({success:true,message:`Folder already exists: ${h.join(En__default.sep)}`,pathSegments:h});return}Mo__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(En__default.sep)}`,pathSegments:h};p.status(201).json(f);})),t.patch("/",ut(async(u,p,m)=>{let h,g;try{let C=Dj.parse(u.body);h=C.pathSegments,g=C.newPathSegments;}catch(C){p.status(400).json({error:`Failed to parse folder update body: ${C}`});return}let f=o(h),b=o(g);if(!Mo__default.existsSync(f)){p.status(400).json({error:`Folder not found: ${h.join(En__default.sep)}`});return}if(Mo__default.existsSync(b)){p.status(400).json({error:`Destination already exists: ${g.join(En__default.sep)}`});return}let T=En__default.dirname(b);Mo__default.existsSync(T)||Mo__default.mkdirSync(T,{recursive:true}),Mo__default.renameSync(f,b);let A={success:true,message:`Folder moved from ${h.join(En__default.sep)} to ${g.join(En__default.sep)}`,pathSegments:g};p.status(200).json(A);})),t.delete("/",ut(async(u,p,m)=>{let h,g=true;try{let A=Fj.parse(u.body);h=A.pathSegments,g=A.recursive??!0;}catch(A){p.status(400).json({error:`Failed to parse folder delete body: ${A}`});return}let f=o(h);if(!Mo__default.existsSync(f)){p.status(200).json({success:true,message:`Folder not found: ${h.join(En__default.sep)}`,pathSegments:h});return}if(!Mo__default.statSync(f).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(En__default.sep)}`});return}try{if(g)Mo__default.rmSync(f,{recursive:!0,force:!0});else {if(Mo__default.readdirSync(f).length>0){p.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}Mo__default.rmdirSync(f);}}catch(A){let{status:C,body:v}=g3(A,`delete folder ${h.join("/")}`);p.status(C).json(v);return}let T={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};p.status(200).json(T);})),t}async function Eve(e){try{let t=await Mo__default.promises.open(e,"r");try{let n=Buffer.alloc(4096),{bytesRead:o}=await t.read(n,0,n.length,0);return n.toString("utf-8",0,o).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await t.close();}}catch{}}var sQ=Router();sQ.get("/",async(e,t)=>{let n=Qe(),o=go();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Rr(cp,o,n);t.status(200).json(r);});var nL=sQ;var Rve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async()=>{t.info({sessionId:o},"Cancel event received");let r=n.getSession(o);if(!r)throw new Error("No active session found");try{r.controller.setClosed();}catch{}}},aQ={event:"cancel",createHandler:Rve};var vve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{testId:o,sessionId:r}=e;return async(i,s)=>{let{stepId:a,environment:l}=i;t.info({testId:o,stepId:a},"Clearing AI action cache");try{let c=n.getSession(r);if(!c)throw new Error("No active session found");await c.cacheStorage.deleteStepCacheEntry({logger:t,testId:o,key:a,environment:l}),s({ok:!0});}catch(c){t.error({testId:o,stepId:a,err:c},"Failed to clear AI action cache"),s({ok:false,error:Q(c)});}}},lQ={event:"clearAIActionCache",createHandler:vve};var wve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let c=(await a.getBrowserState({skipWait:!0})).serialize();t.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c});}catch(l){t.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message});}}},cQ={event:"fetchA11yTree",createHandler:wve};var Ive=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let l=await a.html();i({html:l});}catch(l){t.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message});}}},dQ={event:"fetchDom",createHandler:Ive};var xve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return r=>{t.info({sessionId:o,reason:r},`Disconnect event received (${r})`),n.removeSession(o,t);}},uQ={event:"disconnect",createHandler:xve};function ws(e){let{result:t,nestedResults:n}=e;if(!e.nestedResults.length)return;let{firstMetadata:o,lastMetadata:r}=_ve(n);Pve(t,o,r);let i=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await Mve(i,t,o,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function _ve(e){let t=e[0],n;for(;;){switch(t.type){case "PRESET_ACTION":case "CONDITIONAL":n=t;break;case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "MODULE":case "SECTION":if(!t.results.length){n=t;break}t=t.results[0];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(n)break}let o=e[e.length-1],r;for(;;){switch(o.type){case "PRESET_ACTION":{r=o;break}case "AI_ACTION_DYNAMIC":case "CONDITIONAL":case "AI_ACTION":case "MODULE":case "SECTION":if(!o.results.length){r=o;break}o=o.results[o.results.length-1];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(r)break}return {firstMetadata:n,lastMetadata:r}}function Pve(e,t,n){t&&(e.beforeUrl=t.beforeUrl),n&&(e.afterUrl=n.afterUrl,e.data=n.data,n.status!=="SUCCESS"&&(e.message=n.message,e.failureClassification=n.failureClassification));}async function Mve(e,t,n,o){await Promise.allSettled(e),n&&(t.beforeSnapshot=n.beforeSnapshot),o&&(t.afterSnapshot=o.afterSnapshot);}async function pQ(e){let t;try{t=new URL(e.url).hostname;}catch{}let n=[];return e.headers.getSetCookie()?.forEach(o=>{let r=uA(o,t);n.push(...r);}),n}function Uve(e,t){if(!e&&!t)return;let n;if(e){let{url:r,options:i}=e;n=new Request(r,i);}let o;if(t){let{body:r,options:i}=t;o=new Response(r??null,i);}return {request:n,response:o}}async function Hve(e,t){switch(e){case "RAW":return t;case "RESPONSE":if(t instanceof Response){let n=[];return t.headers.forEach((r,i)=>{n.push([i,r]);}),{status:t.status,headers:n,body:await t.text()}}else throw new Error("Result is not a Response object")}}var Gve=Object.getPrototypeOf(async function(){}).constructor;async function mQ(e,t,n){let o=t.code;t.options.fragment&&(o=`return ${t.code}`),o=`${o}
295
+ `);}catch(n){e.logger.warn({err:n},"Failed to check CLI version against npm");}}var mS=25;function V3(e){let t="v2";return {v2ProjectConfig:{...e.config,fileFormat:t},migratedFilePaths:[]}}function z3(e){let t="v1";return {legacyProjectConfig:{...e.config,fileFormat:t},migratedFilePaths:[]}}function YN({project:e,newProjectConfig:t,fileFormatLabel:n,migratedFilePaths:o}){e.config=t,Sc(e.config,e.configFilePath),o.push(e.configFilePath),R.info(`Updated ${e.configFilePath} to use ${n} file format`),t.hooks?.postSave&&(R.info(`Running post-save hook for ${o.length} migrated files`),MC([...new Set(o)],t));}async function hS(e,t,n){for(let o=0;o<e.length;o+=t)await Promise.all(e.slice(o,o+t).map(n));}function JN(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function pve(e){let t=e.ai??={},n=t.agentConfig??={},o=[];for(let[s,a]of Object.entries(xm)){let l=n[s];l!==a&&(l?.startsWith(`${a}.`)||(n[s]=a,o.push({type:s,newValue:a})));}let r=t.useMemory!==true;r&&(t.useMemory=true);let i=t.failureRecovery!==true;return i&&(t.failureRecovery=true),{upgradedAgents:o,enabledUseMemory:r,enabledFailureRecovery:i}}async function W3({project:e,dryRun:t,migrate:n}){let o=e.config.fileFormat!=="v2",r=pve(e.config);return o?{fileFormatChanged:o,aiSettings:r,migration:await n()}:(!t&&JN(r)&&Sc(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:r,migration:QN()})}function QN(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function XN({summary:e,fileFormatChanged:t,aiSettings:n,dryRun:o,testNoun:r="test",moduleNoun:i="module"}){let s=o?"Would migrate":"Migrated",a=vy(r,e.migratedTestPaths.length),l=vy(i,e.migratedModulePaths.length);R.info(`${s} ${e.migratedTestPaths.length} ${a} and ${e.migratedModulePaths.length} ${l} to v2.`),(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&R.dimmed(` Skipped ${e.alreadyV2TestCount} already-v2 ${vy(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-v2 ${vy(i,e.alreadyV2ModuleCount)}.`),t&&R.dimmed(" + fileFormat: v2");for(let c of n.upgradedAgents)R.dimmed(` + ai.agentConfig.${c.type}: ${c.newValue}`);n.enabledUseMemory&&R.dimmed(" + ai.useMemory: true"),n.enabledFailureRecovery&&R.dimmed(" + ai.failureRecovery: true");}var ZN=false,q3;try{let e=await import('@sentry/node');e.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",dist:"production",release:"cli-2.138.3",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(t,n){return a2(n?.originalException)||l2(n?.originalException)||c2(n?.originalException)||eO(n?.originalException)||bT(n?.originalException,_e)||d2(n?.originalException)?null:t}}),N1(e.captureException),q3=t=>{if(!t){e.setUser(null);return}e.setUser({id:t.userId,organizationId:t.orgId,...t.email&&{email:t.email}});},ZN=!0;}catch{}var K3=e=>q3?.(e);var hve=new BE(30,60*1e3),RR="https://api.momentic.ai",bR,Y3,Bd=e=>{RR=e;},wr=()=>RR,J3=()=>Km(RR),Ec=e=>{Y3=e;},Cc=()=>Y3,go=()=>bR;var gS,TR,Q3,X3,Z3,AR,eQ,tQ=({authInfo:e,apiKey:t,apiClient:n})=>{bR=n,gS=e.orgId,TR=e.userId,Q3=e.email,X3=e.name,Z3=e.pylonEmailHash,AR=t,eQ=e.selfServe;},fS=async({apiClient:e,apiKey:t,skipPrompts:n})=>{let o=await Lh({client:e});return tQ({authInfo:o,apiKey:t,apiClient:e}),o},vR=async e=>{if(bR&&gS&&AR)return gS;let t=new Dt({baseUrl:RR,apiKey:e,logger:R});bR=t;try{let n=await t.getAuthInfo();return tQ({authInfo:n,apiKey:e,apiClient:t}),n.orgId}catch(n){throw new Error(`Error checking API key against server: ${n}`,{cause:n})}},Bn=()=>{if(!gS)throw new Error("Your organization ID is invalid.");return gS},gl=()=>{if(!TR)throw new Error("Your user ID is invalid.");return TR},nQ=()=>TR,Gh=()=>Q3,oQ=()=>X3,rQ=()=>Z3,wR=()=>eQ,vs=()=>{if(!AR)throw new Error("Your API key is invalid.");return AR},ER,CR,fl=()=>{CR?.abort(),CR=void 0;},lp=(e,t)=>{ER=e,fl(),CR=new AbortController;let n=CR.signal,o=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=En__default.resolve(e.rootDir,r.envFile);try{if(Mo__default.lstatSync(i).isSymbolicLink())return;Mo__default.existsSync(i)&&o.push(i);}catch(s){R.warn({err:s},`Failed to check if env file ${i} exists`);}});try{gve({filesToWatch:o,revalidator:t,signal:n,project:e});}catch(r){R.error({err:r},"Failed to start config file watchers");}};async function jh({project:e,apiClient:t}){let n=o=>aa({project:o,apiClient:t});lp(await n(e),async o=>n(await an({configFilePath:o})));}var Qe=()=>{if(!ER)throw new _e("No Momentic project is currently loaded. Open or select a project before invoking this action.");return ER};function gve({filesToWatch:e,revalidator:t,signal:n,project:o}){R.debug("Starting watch on the following files:"),e.forEach(r=>{R.debug(`- ${r}`);}),e.forEach(r=>{let i=async(a,l)=>{a.mtime.getTime()!==l.mtime.getTime()&&(hve.increment("setLocalProject")&&R.warn(`A file change under the ${o.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),ER=await Promise.resolve(t(o.configFilePath)));};Mo__default.watchFile(r,{persistent:false},i);let s=()=>{Mo__default.unwatchFile(r,i),n.removeEventListener("abort",s);};n.addEventListener("abort",s);});}function ut(e){return function(...t){let n=t[t.length-1],o=e(...t);Promise.resolve(o).catch(n);}}var yve="2.138.3",cp=Jm({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:yve});(async()=>{try{let e=await Cs(cp);e.gitBranchName&&cp.addBinding("branch",e.gitBranchName);}catch{}})();var iQ=Router();iQ.get("/",async(e,t)=>{let n=Qe(),o=go();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Rr(cp,o,n),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:s,alwaysSaveCache:a}=Cc(),l=!s&&(a||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var eL=iQ;var Tve=5e3,Ave=[".js",".mjs",".cjs",".ts"];function tL(e={}){let t=Router();function n(){let u=Qe();return En__default.dirname(u.configFilePath)}function o(u){return En__default.join(n(),...u)}function r(u){let p=En__default.relative(n(),u);return p?p.split(En__default.sep):[]}function i(u,p){let m=Mo__default.statSync(u),h=r(u);return tP.parse({name:p,absolutePath:u,relativePath:h.join(En__default.sep),pathSegments:h,isDirectory:m.isDirectory(),size:m.size,createdAt:m.birthtime,modifiedAt:m.mtime,accessedAt:m.atime})}function s(u){let p=En__default.relative(n(),u);return p===""||!p.startsWith("..")&&!En__default.isAbsolute(p)}async function a(u){let p=Qe();return gc(["*"],{cwd:u,ignore:p.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(Tve)})}function l(u){let p=u.trimStart().replace(/^file:\/\//,"").replaceAll("\\","/"),m=p.lastIndexOf("/");return m===-1?{directoryText:"",filePrefix:p}:{directoryText:p.slice(0,m+1),filePrefix:p.slice(m+1)}}function c(u){return u.replaceAll("\\","/").split("/").filter(p=>p&&p!==".")}function d({sourceDirectoryPath:u,targetPath:p,isDirectory:m}){let h=En__default.relative(u,p).split(En__default.sep).join("/");return m?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",ut(async(u,p,m)=>{let h=Lj.safeParse(u.body);if(!h.success){p.status(400).json({error:`Failed to parse file-reference-suggestions body: ${h.error.message}`});return}let{sourceDirectoryPath:g="",value:f}=h.data,b=new Set((h.data.allowedExtensions??Ave).map(E=>E.toLowerCase())),T=l(f);if(T.directoryText.startsWith("/")){p.status(200).json({suggestions:[]});return}let A=En__default.resolve(n(),...c(g)),C=En__default.resolve(A,...c(T.directoryText));if(!s(A)||!s(C)){p.status(200).json({suggestions:[]});return}if(!Mo__default.existsSync(C)||!Mo__default.statSync(C).isDirectory()){p.status(200).json({suggestions:[]});return}let v;try{v=await a(C);}catch(E){if(E instanceof Error&&E.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw E}let I=v.map(E=>{let O=En__default.join(C,E);return {entryName:E,targetPath:O,isDirectory:Mo__default.statSync(O).isDirectory()}}),_=T.filePrefix.toLowerCase(),x=I.filter(E=>E.entryName.startsWith(".")||!E.entryName.toLowerCase().startsWith(_)?false:E.isDirectory?true:b.has(En__default.extname(E.entryName).toLowerCase())).sort((E,O)=>E.isDirectory!==O.isDirectory?E.isDirectory?-1:1:E.entryName.localeCompare(O.entryName)).map(E=>({name:E.entryName,isDirectory:E.isDirectory,value:d({sourceDirectoryPath:A,targetPath:E.targetPath,isDirectory:E.isDirectory})}));p.status(200).json({suggestions:x});})),t.post("/",ut(async(u,p,m)=>{let h;try{h=Nj.parse(u.body).pathSegments;}catch(C){p.status(400).json({error:`Failed to parse folder read body: ${C}`});return}let g=o(h);if(!Mo__default.existsSync(g)){p.status(404).json({error:`Path not found: ${h.join(En__default.sep)}`});return}if(!Mo__default.statSync(g).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(En__default.sep)}`});return}let b;try{b=await a(g);}catch(C){if(C instanceof Error&&C.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw C}let T=b.map(C=>{let v=En__default.join(g,C);return i(v,C)});if(e.allowedFileTypes){let C=new Set(e.allowedFileTypes);T=(await Promise.all(T.map(async v=>{if(v.isDirectory||!(v.name.endsWith(".test.yaml")||v.name.endsWith(".module.yaml")))return v;let _=await Eve(v.absolutePath);return _!==void 0&&C.has(_)?v:null}))).filter(v=>v!==null);}let A={absolutePath:g,pathSegments:h,contents:T};p.status(200).json(A);})),t.put("/",ut(async(u,p,m)=>{let h;try{h=kj.parse(u.body).pathSegments;}catch(b){p.status(400).json({error:`Failed to parse folder create body: ${b}`});return}let g=o(h);if(Mo__default.existsSync(g)){p.status(200).json({success:true,message:`Folder already exists: ${h.join(En__default.sep)}`,pathSegments:h});return}Mo__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(En__default.sep)}`,pathSegments:h};p.status(201).json(f);})),t.patch("/",ut(async(u,p,m)=>{let h,g;try{let C=Dj.parse(u.body);h=C.pathSegments,g=C.newPathSegments;}catch(C){p.status(400).json({error:`Failed to parse folder update body: ${C}`});return}let f=o(h),b=o(g);if(!Mo__default.existsSync(f)){p.status(400).json({error:`Folder not found: ${h.join(En__default.sep)}`});return}if(Mo__default.existsSync(b)){p.status(400).json({error:`Destination already exists: ${g.join(En__default.sep)}`});return}let T=En__default.dirname(b);Mo__default.existsSync(T)||Mo__default.mkdirSync(T,{recursive:true}),Mo__default.renameSync(f,b);let A={success:true,message:`Folder moved from ${h.join(En__default.sep)} to ${g.join(En__default.sep)}`,pathSegments:g};p.status(200).json(A);})),t.delete("/",ut(async(u,p,m)=>{let h,g=true;try{let A=Fj.parse(u.body);h=A.pathSegments,g=A.recursive??!0;}catch(A){p.status(400).json({error:`Failed to parse folder delete body: ${A}`});return}let f=o(h);if(!Mo__default.existsSync(f)){p.status(200).json({success:true,message:`Folder not found: ${h.join(En__default.sep)}`,pathSegments:h});return}if(!Mo__default.statSync(f).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(En__default.sep)}`});return}try{if(g)Mo__default.rmSync(f,{recursive:!0,force:!0});else {if(Mo__default.readdirSync(f).length>0){p.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}Mo__default.rmdirSync(f);}}catch(A){let{status:C,body:v}=g3(A,`delete folder ${h.join("/")}`);p.status(C).json(v);return}let T={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};p.status(200).json(T);})),t}async function Eve(e){try{let t=await Mo__default.promises.open(e,"r");try{let n=Buffer.alloc(4096),{bytesRead:o}=await t.read(n,0,n.length,0);return n.toString("utf-8",0,o).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await t.close();}}catch{}}var sQ=Router();sQ.get("/",async(e,t)=>{let n=Qe(),o=go();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Rr(cp,o,n);t.status(200).json(r);});var nL=sQ;var Rve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async()=>{t.info({sessionId:o},"Cancel event received");let r=n.getSession(o);if(!r)throw new Error("No active session found");try{r.controller.setClosed();}catch{}}},aQ={event:"cancel",createHandler:Rve};var vve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{testId:o,sessionId:r}=e;return async(i,s)=>{let{stepId:a,environment:l}=i;t.info({testId:o,stepId:a},"Clearing AI action cache");try{let c=n.getSession(r);if(!c)throw new Error("No active session found");await c.cacheStorage.deleteStepCacheEntry({logger:t,testId:o,key:a,environment:l}),s({ok:!0});}catch(c){t.error({testId:o,stepId:a,err:c},"Failed to clear AI action cache"),s({ok:false,error:Q(c)});}}},lQ={event:"clearAIActionCache",createHandler:vve};var wve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let c=(await a.getBrowserState({skipWait:!0})).serialize();t.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c});}catch(l){t.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message});}}},cQ={event:"fetchA11yTree",createHandler:wve};var Ive=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let l=await a.html();i({html:l});}catch(l){t.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message});}}},dQ={event:"fetchDom",createHandler:Ive};var xve=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return r=>{t.info({sessionId:o,reason:r},`Disconnect event received (${r})`),n.removeSession(o,t);}},uQ={event:"disconnect",createHandler:xve};function ws(e){let{result:t,nestedResults:n}=e;if(!e.nestedResults.length)return;let{firstMetadata:o,lastMetadata:r}=_ve(n);Pve(t,o,r);let i=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await Mve(i,t,o,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function _ve(e){let t=e[0],n;for(;;){switch(t.type){case "PRESET_ACTION":case "CONDITIONAL":n=t;break;case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "MODULE":case "SECTION":if(!t.results.length){n=t;break}t=t.results[0];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(n)break}let o=e[e.length-1],r;for(;;){switch(o.type){case "PRESET_ACTION":{r=o;break}case "AI_ACTION_DYNAMIC":case "CONDITIONAL":case "AI_ACTION":case "MODULE":case "SECTION":if(!o.results.length){r=o;break}o=o.results[o.results.length-1];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(r)break}return {firstMetadata:n,lastMetadata:r}}function Pve(e,t,n){t&&(e.beforeUrl=t.beforeUrl),n&&(e.afterUrl=n.afterUrl,e.data=n.data,n.status!=="SUCCESS"&&(e.message=n.message,e.failureClassification=n.failureClassification));}async function Mve(e,t,n,o){await Promise.allSettled(e),n&&(t.beforeSnapshot=n.beforeSnapshot),o&&(t.afterSnapshot=o.afterSnapshot);}async function pQ(e){let t;try{t=new URL(e.url).hostname;}catch{}let n=[];return e.headers.getSetCookie()?.forEach(o=>{let r=uA(o,t);n.push(...r);}),n}function Uve(e,t){if(!e&&!t)return;let n;if(e){let{url:r,options:i}=e;n=new Request(r,i);}let o;if(t){let{body:r,options:i}=t;o=new Response(r??null,i);}return {request:n,response:o}}async function Hve(e,t){switch(e){case "RAW":return t;case "RESPONSE":if(t instanceof Response){let n=[];return t.headers.forEach((r,i)=>{n.push([i,r]);}),{status:t.status,headers:n,body:await t.text()}}else throw new Error("Result is not a Response object")}}var Gve=Object.getPrototypeOf(async function(){}).constructor;async function mQ(e,t,n){let o=t.code;t.options.fragment&&(o=`return ${t.code}`),o=`${o}
296
296
  //# sourceURL=${fA}`;let{env:r,additionalBindings:i,request:s,response:a}=t.bindings,l=t.tools,c={},d=(A,C)=>{r[A]=C,c[A]=C;},u={},p=(A,C)=>{r[A]=C,u[A]=C;},m;o.includes("Octokit")&&(m=(await import('@octokit/rest')).Octokit);let h;o.includes("createAppAuth")&&(h=(await import('@octokit/auth-app')).createAppAuth);let g=async()=>{try{return await Promise.resolve(new Gve("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","mock",...Object.keys(i??{}),o)(Lve,Dve,l.fakerInstance??faker,Nve,Bve,m,h,Fve,kve,pQ,r,t.options.disallowVariableUpdates?void 0:d,t.options.disallowVariableUpdates?void 0:p,C=>l.sms.send(C),C=>l.sms.fetchLatest(C),l.email,l.sms,Uve(s,a),...Object.values(i??{})))}catch(A){throw new hT(Q(A),{cause:A})}},f=true,b,T;try{let A=await Re(g(),{milliseconds:t.options.timeoutMs,message:`Timeout of ${t.options.timeoutMs}ms exceeded for code execution`,signal:t.signal});b=await Hve(t.options.responseSerialization??"RAW",A);}catch(A){n.error({err:A,env:r,evalCode:o},`[${e}] Error executing code: ${A}`),f=false,A instanceof cd?T=`Timeout of ${t.options.timeoutMs}ms exceeded for code execution`:T=A instanceof Error?A.message:`${A}`;}return {result:b,variableUpdates:c,persistentVariableUpdates:u,success:f,error:T}}async function hQ({code:e,fragment:t,context:n,localTools:o,logger:r,signal:i,timeoutMs:s=id,disallowVariableUpdates:a,additionalBindings:l,responseSerialization:c,mock:d}){let u=randomUUID(),p=await mQ(u,{code:e,options:{fragment:t,timeoutMs:s,disallowVariableUpdates:a,responseSerialization:c},bindings:{...n.toObjectCopy(),...d,additionalBindings:l},tools:o,signal:i},r);return R.debug(`[${u}] Got execution result: ${JSON.stringify(p)}`),p}var Wve=Hpe(global.fetch,{retries:3,retryOn:function(e,t,n){return !!(t!==null||n&&n.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}}),gQ=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,fQ=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function yQ({orgId:e,code:t,fragment:n,context:o,timeoutMs:r=id,retries:i=2,signal:s,logger:a,additionalBindings:l,disallowVariableUpdates:c,responseSerialization:d,mock:u}){if(!gQ)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,h=0;if(!fQ)throw new Error("Missing lambda auth secret.");let g=createHmac("sha256",fQ).update(e).digest("hex");for(;h<=i;){h++,s?.throwIfAborted();let b={id:randomUUID(),orgId:e,momenticLambdaAuthHash:g,code:t,fragment:n,state:{...o.toObjectCopy(),...u,additionalBindings:l},timeoutMs:r,disallowVariableUpdates:c,responseSerialization:d};try{if(p=await Re(Wve(gQ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),{milliseconds:r,message:`Timeout of ${r}ms exceeded for code execution`,signal:s}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(T){m=T;}}if(m)throw a.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=ZG.parse(await p.json());}catch(b){throw new Error(`Code evaluation server returned invalid response: ${b}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Ud(e){let t;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)t=await yQ(e);else if(e.localTools)t=await hQ({...e,localTools:e.localTools});else throw new Error("No code evaluation environment available");if(t.error){let n=`Failed to evaluate code:
297
297
  ${t.error}
298
298
  Code received:
@@ -5746,7 +5746,7 @@ ${e}`;case "ELEMENT_CHECK":return `${b4}
5746
5746
  ${e}`;default:return e}}async function _s({frameConfig:e,action:t,browser:n}){let o=n.getActiveFrameConfig();e?n.setActiveFrameConfig(e):o?.type==="auto"&&n.setActiveFrameConfig(void 0);try{return await t()}finally{n.setActiveFrameConfig(o);}}var Sxe=["NAVIGATE","NEW_TAB","CLOSE_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function E4({beforeUrl:e,beforePages:t,browser:n,command:o,logger:r}){if(Sxe.includes(o.type))return;await oo().startAsyncSpan("AUTO_FOLLOW_NEW_TABS",async s=>{let c=("cache"in o&&o.cache&&"target"in o.cache?o.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??false?300:3e3,d=Date.now(),u=0;for(r.info({command:o.type,beforePages:t,beforeUrl:e,timeout:c},"Checking for new tabs to auto-follow");u===0||Date.now()-d<c;){await Ye(250),u++;let p=(await n.getOpenPages()).map(h=>h.url),m=n.url();if(p.length!==t.length)for(let h=p.length-1;h>=t.length;h--){let g=p[h];if(Ad(g,r)&&g!==e&&g!==m){r.info({beforePages:t,afterPages:p,beforeUrl:e},"Auto-following new tab after preset action"),await n.switchToPage({type:"INDEX",index:String(h)}),s.result={followed:true};return}}}s.result={followed:false};});}async function Tl(e,t={}){let n=await e.getBrowserState(t);return {serializedTree:n.serialize(t.serializationOpts),tree:n}}var C4=e=>!!e&&Kp(e),R4=e=>{let{cache:t,description:n,disableSecondaryCacheResolution:o,logger:r}=e,i=t,s=false,a;return i&&o&&i.targetSource==="HEURISTIC_HEALED"&&(s=true,a="Heuristic healed cache incompatible",i=void 0),i?.inputDescription&&!T4(n,i.inputDescription)&&(r.warn({old:i.inputDescription,new:n},"Target cache was generated with a different description, clearing it automatically"),s=true,a="Description changed",i=void 0),{cache:i,cacheBustedBeforeAction:s,cacheBustReason:a}};var w4={minChunkTokenCount:1e4,acceptableChunkTokenCount:25e3,maxChunkTokenCount:5e4,maxLineLength:4e3},v4=/<(\S+) id="(\d+)".*?>/g,bxe=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,I4=["h1","h2","section","footer","nav","aside","form","label","dialog"],Txe=[...I4,"span","div","h3"],Axe=["table","select","form","ul","ol","menu","pre","code","dialog"],Exe=["table","form","dialog","nav","section","ul","select"];function x4(e){return Cxe(e)}function Cxe({logger:e,serializedTree:t,options:n}){let{minChunkTokenCount:o,acceptableChunkTokenCount:r,maxChunkTokenCount:i,maxLineLength:s}=n,a=[],l=t.split(`
5747
5747
  `),c=0,d=[],u=0,p=[],m=[],h=false;for(;c<l.length;){h&&(a.push({ids:p,content:d.join(`
5748
5748
  `),tokenLength:u}),d=[],u=0,p=m.length?[m[m.length-1].id]:[],h=false);let g=l[c],f=nt(g);u+=f,g.length>s&&(g=g.slice(0,s));let A=Array.from(g.matchAll(v4)).map($=>$&&$.length>=3?{tagName:$[1],id:$[2]}:void 0).filter($=>!!$),v=Array.from(g.matchAll(bxe)).map($=>$&&($[2]||$[4])).filter($=>!!$);v.reverse();let I=g.replace(/ id="[0-9]+"/g,"");d.push(I);for(let $ of A)p.push($.id),m.push($);for(let $ of v){let oe=m[m.length-1];oe&&oe.tagName===$&&m.pop();}let _=m.some($=>Axe.includes($.tagName)),x=l[c+1]??"",E=nt(x),N=Array.from(x.matchAll(v4)).map($=>$&&$.length>2?$[1]:void 0).filter($=>!!$),H=N.some($=>I4.includes($)),U=N.some($=>Txe.includes($));u+E>=i&&(h=true),u>=o&&(H&&!_||v.some($=>Exe.includes($)))&&(h=true),u>=r&&U&&!_&&(h=true),c++;}return d.length&&a.push({ids:p,content:d.join(`
5749
- `),tokenLength:u}),a.forEach((g,f)=>{let b=g.ids[0],T=g.ids[g.ids.length-1];e.debug({tokenLength:g.tokenLength,minId:b,maxId:T},`Chunk for page filtering (index ${f+1}/${a.length})`);}),{chunks:a}}var _4=5e6,vxe=1e5,wxe=3e4,Ixe=6e4,xxe=1e5;async function Ji(e){let{fixtures:t}=e,{logger:n}=t,o=e.tree,r=e.serializedTree,i=nt(r);if(i>_4)throw new Y("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${_4} tokens.`);if(i>vxe){let s=x4({serializedTree:r,options:w4,logger:n}),a=randomUUID();o=await _xe({...e,chunks:s.chunks,callId:a}),r=o.serialize();let l=nt(r);n.info({oldTokens:i,newTokens:l,langfuseCallId:a},"Filtered page using AI chunk ranking");}return r}async function _xe({type:e,callId:t,chunks:n,description:o,fixtures:r,tree:i}){let{generator:s,signal:a,logger:l}=r,c=await s.rankChunksWithAi({chunks:n,description:o,type:e,softTokenLimit:wxe,mediumTokenLimit:Ixe,hardTokenLimit:xxe,callId:t},{abortSignal:a,logger:l,loggerTags:vt(l)}),d=[];return n.forEach((p,m)=>{c.indices.includes(m)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}async function WL(e,t){if(!e.description)throw new Y("UserConfigurationError","Cannot locate element with empty description");return _s({action:async()=>Mxe(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function Mxe(e,t){let{disableCache:n,testContext:o,filterByViewport:r,skipWait:i,source:s,memory:a,logger:l,allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,skipSavingVisualAttributes:p,isAutoHeal:m,cacheBustReason:h,acceptElementMovedError:g}=e,{orgId:f,browser:b,localCodeEvalTools:T,generator:A,abortSignal:C}=t,v=e.description,I=oo(),_=e.useMemory&&!n;o&&(v=await Ir({orgId:f,s:v,context:o,localTools:T,signal:C,logger:l})),s&&(v=A4(v,s));let{serializedTree:x,tree:E}=await I.startAsyncSpan("GET_PAGE_STATE",async()=>Tl(b,{allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,filterByViewport:r,abortSignal:C,skipWait:i,logger:l}),{}),O=await I.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let te,B=Date.now(),le;for(;!te&&Date.now()-B<3e3;){C.throwIfAborted();try{te=await b.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(be){le=be;}}if(!te)throw new Y("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${le?.message}`);return te}),N=x,H=false,$=`data:image/jpeg;base64,${O.toString("base64")}`,oe=vt(l);N=await Ji({type:"locator",description:v,screenshot:$,serializedTree:x,tree:E,fixtures:{generator:A,signal:C,logger:l,orgId:f}}),N!==x&&(H=true);let X=await I.startAsyncSpan("AI_LOCATOR_CALL",async te=>{m&&(te.attributes.isAutoHeal=true),h&&(te.attributes.cacheBustReason=h);let B=await A.getElementLocation({browserState:N,goal:v,screenshot:$,source:s,memory:_?a:void 0},{disableCache:n,abortSignal:C,logger:l,loggerTags:oe,useMemory:_,cacheBustReason:h});if(te.result=B,I.storeTraceAsset){let le=randomUUID();I.storeTraceAsset({snapshotId:le,data:O}),te.screenshotSnapshotId=le;}return B});if(l.debug({usedRag:H,result:X},"Got locator result"),!(X.id>0))throw new cm(`Could not find any relevant element: ${X.thoughts}`,X.updatedMemory?{type:"GCS_TRACES",traces:X.updatedMemory}:void 0);let{resolution:K,target:q,frameConfig:J}=await I.startAsyncSpan("TARGET_RESOLUTION",async te=>{let B=await b.createTargetFromA11yId({id:X.id,requirements:X.requirements,additionalElements:X.additionalElements,description:v,targetSource:"AI",logger:l,skipSavingVisualAttributes:p,acceptElementMovedError:g});return te.result={serializedElement:B.target.nodeOnlySerializedHtml??"Unknown HTML element"},B});if(K.a11yNode?.properties?.hidden&&K.a11yNode?.properties?.hidden!=="false")throw new Y("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${K.displayString}`);return _&&(X.updatedMemory?q.memory={type:"GCS_TRACES",traces:X.updatedMemory}:a&&(q.memory=a)),{thoughts:X.thoughts,target:q,resolution:K,frameConfig:J,screenshot:$}}var Oxe=15;async function zR({command:e,logger:t,fixtures:n,useMemory:o,maxRetries:r=Oxe,recoveryHint:i}){if(!e.assertion.trim())throw new Y("ActionFailureError","Assertion command is missing the assertion content");let s=n_.optional().catch(void 0).parse(e.source);e.source&&!s&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let a=oo();return a.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,d=e.timeout?e.timeout*1e3:c.smartWaitingTimeout,u=Xq(d,r-1),p=0,m=Date.now(),h=m+d,g=m,f,b,T;try{await _s({action:()=>c.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:c,logger:t});}catch(v){t.warn({err:v},"Failed to clear highlights before AI check, continuing...");}for(;p<r;){n.abortSignal.throwIfAborted();let v=Date.now();if(p>0){if(v>=h)break;let x=h-v,E=g-v,O=Math.min(E,x);O>0&&await Ye(O,n.abortSignal);}let I=Date.now();if(p>0&&I>=h)break;let _=false;try{if(f=await _s({action:async()=>{let E=await M4(c,t,n.abortSignal);return b&&b.serializedTree===E.serializedTree&&b.screenshotBuff.equals(E.screenshotBuff)?(_=!0,f):(b=E,O4({command:e,state:E,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:p,logger:t,source:s,recoveryHint:i}))},frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c}),f?.aiResult.result){f?.updatedMemory&&Py(e,f.updatedMemory,t);break}else throw f?.aiResult.thoughts?new Y("AssertionFailureError",f.aiResult.thoughts):new Y("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(x){n.abortSignal.throwIfAborted(),T=x instanceof Error?x:new Error(`${x}`),_?t.info(`AI check attempt ${p} failed (re-used previous result)`):t.info({err:x},`AI check assert attempt ${p} failed, retrying...`);}finally{p++,g=I+u;}}if(!f?.aiResult.result){let v=h-Date.now();v>0&&await Ye(v,n.abortSignal);}if(!f?.aiResult.result)try{f=await _s({action:async()=>O4({command:e,state:await M4(c,t,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:p,logger:t,recoveryHint:i}),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c});}catch(v){n.abortSignal.throwIfAborted(),T=v instanceof Error?v:new Error(`${v}`);}finally{p++;}f?.updatedMemory&&Py(e,f.updatedMemory,t);let A=f?.afterScreenshotOverride;if(A&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:A}),l.screenshotSnapshotId=v;}let C=f?.elementScreenshotOverride;if(C&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:C}),l.elementScreenshotSnapshotId=v;}if(!f?.aiResult.result){l.result=f?.aiResult??{thoughts:T?.message??"AI check failed after all attempts",result:false};let v=`AI check still failing after ${p} attempts.`;throw T&&(v+=` Latest result: ${T.message}`),new Y("AssertionFailureError",v)}return l.result=f.aiResult,{...f,thoughts:f.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:c.url()}})}async function M4(e,t,n){await e.waitForPageLoad({signal:n});let[o,r]=await Promise.all([Tl(e,{abortSignal:n,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...o,screenshotBuff:r}}async function O4({command:e,state:t,fixtures:n,useConsensus:o,useMemory:r,highlightElementsOnFailure:i,attemptNumber:s,source:a,logger:l,recoveryHint:c}){let {browser:d,generator:u,abortSignal:p}=n,{serializedTree:h,tree:g}=t,f=t.screenshotBuff,b=f.toString("base64"),T=d.url(),A=e.contextChoice??"MULTIMODAL",C=h;A!=="VISION_ONLY"&&(C=await Ji({type:"assertion",serializedTree:h,tree:g,description:e.assertion,screenshot:b,fixtures:{generator:u,signal:p,logger:l,orgId:n.orgId}}),C);let v={goal:e.assertion,url:T,memory:r?e.cache?.memory:void 0,browserState:C,screenshot:b,contextChoice:A,source:a,recoveryHint:c},_=await(A==="VISION_ONLY"?(E,O)=>u.getVisualAssertionResult(E,O):(E,O)=>u.getAssertionResult(E,O))(v,{useConsensus:o,attemptNumber:s,useMemory:r,disableCache:!!e.disableCache,abortSignal:p,logger:l,loggerTags:vt(l)}),x;if((_.result||i)&&_.relevantElements?.length){_.relevantElements.map(E=>d.getSerializedFormFromA11yId(E)).filter(E=>!!E);try{let E=_.relevantElements[0],{resolution:O}=await d.createTargetFromA11yId({id:E,description:null,targetSource:"AI",skipSaveToCache:!0});x=await d.screenshot({locator:O.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(E){l.debug({err:E},"Failed to capture element screenshot for trace, continuing...");}await Nxe(_.relevantElements,d,l);}return {aiResult:_,afterScreenshotOverride:f,elementScreenshotOverride:x,updatedMemory:r?_.updatedMemory:void 0}}async function Nxe(e,t,n){let o=Date.now();for(let r of e){if(Date.now()-o>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await Re(t.highlightA11yId(r),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}});}catch(i){n.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}async function L4(e){let{command:t,logger:n,fixtures:o,disableCache:r}=e,{browser:i,generator:s,abortSignal:a}=o;if(!t.goal.trim())throw new Y("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let u=e1(t.schema);if(u)throw new Y("UserConfigurationError",u)}let l=await i.getCondensedHtml(),c=await i.screenshot({retries:2}),d=oo();try{return await d.startAsyncSpan("AI_EXTRACTION_CALL",async u=>{let p=await s.getTextExtraction({goal:t.goal,browserState:l,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${c.toString("base64")}`},{disableCache:r,abortSignal:a,loggerTags:vt(n)});if(u.result=p,Lxe({tracer:d,span:u,screenshot:c,htmlState:l,logger:n}),p.result==="NOT_FOUND")throw new Y("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new Y("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:i.url()}})}catch(u){let p=Q(u);throw p.includes("MaxGenerationLengthExceededError")?new Y("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):p.includes("AIProviderError")&&p.includes("time")?new Y("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:u}}):u}}function Lxe(e){let{tracer:t,span:n,screenshot:o,htmlState:r,logger:i}=e;if(t.storeTraceAsset)try{let s=randomUUID();t.storeTraceAsset({snapshotId:s,data:o}),n.screenshotSnapshotId=s;let a=randomUUID();t.storeTraceAsset({snapshotId:a,data:Buffer.from(r),extension:"html"}),n.browserStateSnapshotId=a;}catch(s){i.debug({err:s},"Failed to store extraction trace assets");}}async function k4(e,t){let{logger:n}=e,{abortSignal:o,browser:r}=t,i=Date.now();try{await kxe(i,e,t);}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")||o.aborted)return;n.warn({err:s},"Unexpected error occurred during AI smart waiting");let a=r.smartWaitingTimeout-(Date.now()-i);a>0&&await Ye(a,o);}finally{n.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function kxe(e,t,n){let{abortSignal:o,browser:r}=n;if(r.smartWaitingTimeout<3e3){await Ye(r.smartWaitingTimeout,o);return}if(!t.description)throw new Y("UserConfigurationError","Cannot locate element with empty description");await Re(Dxe(e,t,n),{milliseconds:r.smartWaitingTimeout});}async function Dxe(e,t,n){let{logger:o,iframeUrl:r}=t,{browser:i}=n;for(;Date.now()-e<i.smartWaitingTimeout;)if(await _s({action:async()=>Fxe(t,n),frameConfig:r?{type:"url",url:r}:void 0,browser:i,logger:o}))return}async function Fxe(e,t){let{testContext:n,logger:o}=e,{browser:r,abortSignal:i,localCodeEvalTools:s,orgId:a,generator:l}=t,c=e.description;n&&(c=await Ir({orgId:a,s:c,context:n,localTools:s,signal:i,logger:o})),i.throwIfAborted();let d;try{d=await r.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(h){throw new Y("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${h instanceof Error?h.message:h}`)}let p=`data:image/jpeg;base64,${d.toString("base64")}`;i.throwIfAborted();let m=await l.getSmartWaitingDecision({description:c,screenshot:p},{abortSignal:i,loggerTags:vt(o)});return o.debug({result:m},"Got smart waiting result"),m.isPageReady}var Bxe=15e3,Uxe=6e4;async function B4(e){return oo().startAsyncSpan("ELEMENT_ASSERTION",async n=>Hxe(e,n),{name:"Element check"})}async function Hxe(e,t){let{command:n,timeoutMs:o,fixtures:r,disableCache:i}=e,{abortSignal:s}=r,a=()=>nT(n.cache)?n.cache:void 0,l=a(),c=!i&&!!l?.target&&Kp(l.target),d=cloneDeep(l),u=(C=false)=>{if(l=a(),!!l)if(C){let v=cO(d,l);l.target=v.target,l.updatedAt=v.updatedAt;}else {if(!d){l=void 0;return}l.target=d.target,l.updatedAt=d.updatedAt;}},p=Date.now(),m=c?Math.min(Math.max(o/10,Bxe),Uxe):0,h=p,g=0,f,b=500,T=false;for(;g<2||Date.now()-p<o;){g++,g>1&&await Ye(b,s),s?.throwIfAborted(),l=a();let C=g===1,v=c&&Date.now()-h>=m;v&&(h=Date.now());let{result:I,elementWasFound:_}=await D4({cacheToUse:l,skipAISmartWaiting:!C,useAIIfCacheFails:!c||v,params:e});if(f=I,T=T||_,I.success)break;u(),b=Math.min(b*1.25,1e4);}if(!f)throw new Y("InternalPlatformError",`Failed to evaluate manual element assertion in ${o}ms.`);if(s?.throwIfAborted(),!f.success){let C=a(),v=C?.target?.memory?{target:{id:-1,memory:C.target.memory}}:void 0,{result:I,elementWasFound:_}=await D4({cacheToUse:v,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});f=I,T=T||_,f.success||u(true);}let A=a();return f.success&&A?.target&&!T&&(A.target=_y(A.target),A.updatedAt=new Date),t.result={success:f.success,message:f.err?.message},f}async function D4({cacheToUse:e,skipAISmartWaiting:t,useAIIfCacheFails:n,params:o}){let{command:r,disableCache:i,fixtures:s,tracer:a,targetingWrapper:l}=o,{logger:c}=s;if(r.target&&!$c(r.target))throw new Error("Element assertion with x/y is not supported yet");let d=B2(r.assertion),u=Gxe(r.assertion),p,m=false,h=cloneDeep(e);try{let{elementInteractedDisplayString:g,result:f,thoughts:b}=await l({tracer:a,command:r,target:r.target,cache:h?.target,action:async T=>jxe(T.locator,o),options:{...r,allowNotActionableNodesOverride:u,allowIneligibleTagRedirect:u,showZeroOpacityElementsOverride:!0,disableCache:i,memory:h?.target?.memory,disableGlobalLocatorRedirect:!0,source:Tu(r),skipAISmartWaiting:t,targetName:"target"},retriesWithAI:n?1:0});return p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:g,thoughts:b},m=!0,f.success||(c.warn({aiThoughts:b,elementString:g,err:f.err},"Element check found an element but failed"),p={...f,thoughts:b}),{result:p,elementWasFound:m}}catch(g){if(d)return p={success:true,thoughts:`The element described does not exist on the page: ${g.message}`,err:void 0,data:void 0},{result:p,elementWasFound:m};if(!(g instanceof Y)||g.reason!="ActionFailureError")throw g;return p={success:false,err:g,data:void 0,thoughts:void 0},c.warn({err:g},"Element check did not find an element and failed"),{result:p,elementWasFound:m}}}function Gxe(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function jxe(e,{command:t,fixtures:n}){return await n.browser.highlight(e),await $xe(e,t.assertion)}async function $xe(e,t){let n=true,o,r;switch(t.type){case "ELEMENT_CONTENT":{let s=await e.textContent()??"";if(r={elementTextContent:sn(s,500,true)},!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=lh(t);n=false,o=new Y("AssertionFailureError",`The content ${a} '${t.value}': ${s}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:sn(await e.evaluate(a=>a.cloneNode(false).outerHTML),500,true)};let s=null;try{s=await e.getAttribute(t.attr,{timeout:3e3});}catch(a){o=new Y("AssertionFailureError",Q(a)),n=false;break}if(!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=lh(t);n=false,t.operation==="EXISTS"?o=new Y("AssertionFailureError",`The attribute ${t.attr} ${a}`):o=new Y("AssertionFailureError",`The attribute ${t.attr} ${a} '${t.value}': ${s}`);}break}case "ELEMENT_EXISTENCE":{switch(t.condition){case "VISIBLE":{n=await e.evaluate(async(a,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(u=>setTimeout(u,250));let d=a.getBoundingClientRect();if(!(d.width===0||d.height===0)&&window.getComputedStyle(a).visibility!=="hidden"&&window.getComputedStyle(a).display!=="none")return true}return false},ss*1e3);break}case "EDITABLE":{n=await e.isEditable({timeout:ss*1e3});break}case "EXISTS":{n=true;break}case "ENABLED":{n=await e.isEnabled({timeout:ss*1e3});break}case "FOCUSED":{n=await e.evaluate(a=>a===document.activeElement);break}default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})(t.condition)}if(n=t.negated?!n:n,!n){let s=lh(t);o=new Y("AssertionFailureError",`The element ${s}`);}break}case "ELEMENT_NAME":{let s=await e.evaluate(a=>a.tagName);if(!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let a=lh(t);n=false,o=new Y("AssertionFailureError",`The element tag name ${a} '${t.value}': ${s}`);}break}case "ELEMENT_STYLE":{let s=await e.evaluate((a,l)=>window.getComputedStyle(a).getPropertyValue(l),t.property);if(!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=lh(t);n=false,t.operation==="EXISTS"?o=new Y("AssertionFailureError",`The style property ${t.property} ${a}`):o=new Y("AssertionFailureError",`The style property ${t.property} ${a} '${t.value}': ${s}`);}break}default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {thoughts:void 0,success:n,data:r,err:o}}function U4(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function ES(e,t){let n=await e.screenshot(t),{width:o,height:r}=imageSize(n);return {buffer:n,width:Math.ceil(o),height:Math.ceil(r)}}async function G4({tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:r,logger:i,screenshotStorage:s}){if(t.target&&!$c(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForStability({logger:i});let a={clearHighlights:true,hideCaret:true},l;t.target?.elementDescriptor?l=(await r({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async O=>ES(o,{locator:O.locator,...a}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ES(o,a);let c=await s.prepareGoldenScreenshotForComparison(i,t,l);if((l.height!==c.height||l.width!==c.width)&&i.warn({currHeight:l.height,currWidth:l.width,savedHeight:c.height,savedWidth:c.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-c.height)>10||Math.abs(l.width-c.width)>10){let E=`${l.width}x${l.height}`,O=`${c.width}x${c.height}`;return {fail:true,thoughts:`Current screenshot (${E}) does not match saved screenshot dimensions (${O}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:false,urlAfterCommand:o.url()}}let d=await Jimp.fromBuffer(l.buffer),u={width:l.width,height:l.height},p=await Jimp.fromBuffer(c.buffer),m={width:c.width,height:c.height},h,g=u.width*u.height,f=m.width*m.height,b=Math.abs(u.height-m.height),T=Math.abs(u.width-m.width);if(g>f){let E=d.cover({w:m.width,h:m.height});l.buffer=await E.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height;}else if(f>g){let E=p.cover({w:u.width,h:u.height});c.buffer=await E.getBuffer("image/jpeg"),h="saved";}let A={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},C=t.threshold??.1,I=_Ie(qL.decode(c.buffer).data,qL.decode(l.buffer).data,A.data,l.width,l.height,{threshold:C,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,_=I>C*100,x=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${C*100}%.`;if(h&&(x+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${T} pixels.`),_)throw new Y("ActionFailureError",x);return {fail:_,thoughts:x,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:qL.encode(A,75).data,succeedImmediately:false,urlAfterCommand:o.url()}}var Wxe=3e4;function qxe(e){if(!e.body)return {};switch(e.body.type){case "json":return {content:e.body.content,contentType:"application/json"};case "form-urlencoded":{let t=new URLSearchParams;return Object.entries(e.body.content).forEach(([n,o])=>{t.append(n,o);}),{content:t.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function j4({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??Wxe/1e3,i=Object.fromEntries(Object.entries(e.headers||{}).filter(([h,g])=>h&&g)),s=new URLSearchParams;Object.entries(e.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{s.append(h,g);});let a=s.toString(),l;if(mh(e.url)&&(l=e.url),n&&hh(e.url,n)&&(l=new URL(e.url,n).toString()),!l)throw new Y("ActionFailureError",`Invalid URL: ${e.url}`);let c=l;t.info({url:c,searchParams:a,headers:i,body:e.body,method:e.method},"Making HTTP request");let u=await Re((async()=>{let h=a?`${c}?${a}`:c;try{let g=qxe(e),f=new Headers(i);return g.contentType&&!f.has("Content-Type")&&f.set("Content-Type",g.contentType),await o(h,{headers:f,method:e.method,body:g.content})}catch(g){throw new Error(`Failed to make HTTP request: ${g}`,{cause:g})}})(),{milliseconds:r*1e3,fallback:()=>{throw new Y("ActionFailureError",`Fetch request timed out after ${r} seconds`)}});if(!u.ok){let h;try{h=await u.text();}catch(g){h=`Failed to read response body: ${g}`;}throw new Y("ActionFailureError",`Fetch request failed with status ${u.status}: ${h}`)}let p={};u.headers.forEach((h,g)=>{p[g]=h;});let m={status:u.status,headers:p,request:{url:u.url,method:e.method,headers:i}};if(e.body?.type==="json"&&e.body.content)try{m.request.json=JSON.parse(e.body.content);}catch{}if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json();}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var Kxe=5e3;async function WR({timeout:e=ss,...t}){let n=Date.now(),o=e*1e3,r=o+1e4,i,s=0,a=500;for(;s-n<o;){if(Date.now()-n>r){t.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}t.signal?.throwIfAborted();let l=Date.now();i=await $4(t),s=Date.now();let c=s-l;if(c>1e3&&t.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Ye(a,t.signal),a=Math.min(Math.floor(a*1.5),Kxe);else return i}return i=await $4(t),i}async function $4(e){return oo().startAsyncSpan("PAGE_ASSERTION",async n=>{let o=await Yxe(e);return n.result={success:o.success,message:o.err?.message},o},{name:"Page check"})}async function Yxe({assertion:e,browser:t,autoExpandIframes:n}){switch(e.type){case "CONTENT":case "CONTENT":{let r,i=false,s;try{let a;if(n){let l=await t.evaluateFunctionInAllFrames(V4,{value:e.value,negated:!!e.negated,returnHtml:!1});i=e.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml;}else ({evaluation:i,pageHtml:a}=await t.evaluateFunctionInPage(V4,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?uc.CONTAINS:pc.CONTAINS;s=new Y("AssertionFailureError",`The page ${l} '${e.value}'.`),r=a;}}catch(a){s=new Y("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`);}return {success:i,err:s,data:i||!r?void 0:{pageContent:r}}}default:return (r=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}}function V4({value:e,negated:t,returnHtml:n}){let o=document.body.innerHTML,r=o.includes(e)===!t;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),{evaluation:r,pageHtml:!r&&n?o:void 0}}var Jxe=3e4;async function z4({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??Jxe/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(e.headers||{}).filter(([u,p])=>u&&p));s["Content-Type"]="application/json";let a;if(mh(e.url)&&(a=e.url),n&&hh(e.url,n)&&(a=new URL(e.url,n).toString()),!a)throw new Y("ActionFailureError",`Invalid URL: ${e.url}`);let c=await Re((async()=>{try{return await o(a,{headers:s,method:"POST",body:JSON.stringify({query:e.query,variables:e.variables?JSON.parse(e.variables):void 0}),signal:i.signal})}catch(u){throw new Error(`Failed to make HTTP request: ${u}`,{cause:u})}})(),{milliseconds:r*1e3});if(!c)throw new Y("ActionFailureError",`GraphQL request timed out after ${r} seconds`);if(!c.ok){let u,p=await c.text();try{u=JSON.parse(p);}catch{throw new Y("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}throw u?.errors?.length&&u?.errors[0]?.message?new Y("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new Y("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}let d={};return c.headers.forEach((u,p)=>{d[p]=u;}),{status:c.status,headers:d,json:await c.json()}}var Wh=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:t,generator:n,logger:o,storage:r,orgId:i,localCodeEvalTools:s,uploadedFileStorage:a,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=t,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=r,this.uploadedFileStorage=a,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=s,this.generator=n,this.logger=o;}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal);}setClosed(){this.executeAbortController.abort();}throwIfClosed(){this.executeAbortController.signal.throwIfAborted();}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(t,n){this.executionOptionsStack.push(t);try{return await n()}finally{this.executionOptionsStack.pop();}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:t,startingScreenshot:n,history:o,disableCache:r,langfuseSessionId:i,lastError:s,logger:a=this.logger}){let[l,c]=await Promise.all([Tl(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:a}),this.browser.screenshot({retries:1,clearHighlights:true})]),d=`data:image/jpeg;base64,${c.toString("base64")}`,u=await Ji({type:"ai-action",description:t,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:this.browser.url(),browserState:u,startingScreenshot:n,history:o,goal:t,screenshot:d,lastError:s};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:{...vt(a)},langfuseSessionId:i})}async promptToCommand({goal:t,startingScreenshot:n,history:o,actionHint:r,disableCache:i,logger:s=this.logger,langfuseSessionId:a}){let l=this.browser.url(),[c,d]=await Promise.all([Tl(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:s}),this.browser.screenshot({retries:1,clearHighlights:true})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,p=await Ji({type:"ai-action",description:t,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:l,browserState:p,startingScreenshot:n,history:o,goal:t,actionHint:r,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...vt(s)},langfuseSessionId:a})}catch(h){throw new Y("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return Tl(this.browser,t)}async locateElement(t){return await WL(t,this.getControllerFixtures())}async locateElementWithSelector(t,n){return _s({action:async()=>{let o=await this.browser.resolveHardcodedCssSelector({selector:t,timeoutMs:2e3,logger:this.logger});return {thoughts:"Located element with selector",target:{id:-1,selector:t,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:o}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return {browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??true}async wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:i,action:s,options:a,retriesWithAI:l=1}){let c=[];for(let d=0;d<r.length;d++){let u=r[d],p=await this.wrapElementTargetingCommand({tracer:t,command:n,target:u,cache:i[d],action:async m=>m,options:{...a,targetName:o[d]}});c.push(p);}try{let d=await s(...c.map(m=>m.result)),u=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",p=c.map((m,h)=>m.thoughts?`${u(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return {result:d,elementInteractedDisplayStrings:c.map(m=>m.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:r.map(()=>{}),action:s,options:a,retriesWithAI:l-1});throw new Y("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapHardcodedCssTargetingCommandHelper({target:t,action:n,options:o,command:r}){let i=this.logger.child({commandId:r.id}),{targetName:s}=o;if(t.type!=="description")throw new Y("ActionFailureError","Cannot use selector with non-description target");let a,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({selector:t.elementDescriptor,targetName:s,logger:i});return {result:await n({locator:d.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;a=d,i.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Ye(500);}}throw a}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:n,disableGlobalLocatorRedirect:o,logger:r}=t,i=oo(),s=!o&&this.browser.userBrowserSettings.globalLocatorRedirect!==false;(this.browser.userBrowserSettings.visualActions||s)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(n.locator);});let a;return s&&(a=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:d}=await this.browser.performTargetRedirection(n,r);if(l.result=d,d.outcome==="redirected to new element"&&c&&i.storeTraceAsset&&!this.browser.userBrowserSettings.disableBrowserMonitoring){let u=randomUUID();(async()=>{try{let p=await this.browser.screenshot({locator:c.locator,clearHighlights:!0,boundingBoxOverride:c.serverSideBoundingBox??void 0});i.storeTraceAsset?.({snapshotId:u,data:p});}catch(p){r.debug({err:p},"Failed to capture element screenshot for redirect trace");}})(),l.elementScreenshotSnapshotId=u;}return c})),a||(a={locator:n.locator,serverSideBoundingBox:await n.locator.boundingBox({timeout:Ve}),originalElementLocationResult:n.originalElementLocationResult}),a}async resolveCachedTargetForAction(t){let{cache:n,options:o,logger:r}=t,s=await oo().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=n.targetSource,l.attributes.smartWaitingTimeoutMs=this.browser.smartWaitingTimeout;try{let c=await this.browser.resolveTarget(n,{allowNotActionableNodesOverride:o.allowNotActionableNodesOverride,logger:r,signal:this.executeAbortController.signal,...o.resolveTargetOptions,acceptElementMovedError:o.force});l.attributes.targetDisplayString=c.displayString,l.attributes.decisions=c.decisions;let d=c.decisions.find(u=>u.matched);return d&&(l.resolutionMethod=d.type),c}catch(c){throw c instanceof Hr&&(l.cacheMissReason=c.cacheMissReason,l.attributes.decisions=c.decisions),c}}),a=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:s,disableGlobalLocatorRedirect:o.disableGlobalLocatorRedirect,logger:r});return o.force||await s.revalidator?.(),{resolutionResult:s,finalTarget:a}}async wrapElementTargetingCommand(t){return await _s({action:()=>this.wrapElementTargetingCommandHelper(t),frameConfig:t.options.iframeUrl?{type:"url",url:t.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(t){let{tracer:n,target:o,action:r,options:i,command:s,finalAttempt:a=false,originalCache:l=t.cache}=t,{retriesWithAI:c=1}=t,{disableCache:d,useSelector:u,targetName:p}=i,m=oo(),h=this.logger.child({commandId:s.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||d)&&!xB(o))throw new Y("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(t);let b=false,T;d&&(h.info("Cache explicitly disabled for this step"),b=true,T="Cache explicitly disabled",f=void 0);let A=R4({cache:f,description:o.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:h});f=A.cache,b=b||A.cacheBustedBeforeAction,!T&&A.cacheBustReason&&(T=A.cacheBustReason);let C=true;if(!C4(f))return c--,C=false,this.executeTargetingCommandWithAI({tracer:m,stepTracer:n,target:o,options:i,command:s,action:r,originalCache:l,logger:h,useMemory:g,cacheBustedBeforeAction:b,cacheBustReason:T});try{let{resolutionResult:v,finalTarget:I}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),_=await r(I);if(gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.138.2"]),YE({cmd:s,key:p,newTarget:f,logger:h,updatedWithAI:!1}),C){let x=v.decisions.filter(E=>E.matched);if(x.length!==1)h.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let E=x[0].type;n.recordTargetAutoHeal({healType:E});}}return {result:_,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let I=yx(v);if(I&&!a)return h.warn({err:v},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,action:r,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:true,options:i});if(v instanceof Y&&!I)throw h.warn({err:v},"Failed to execute command with target (fatal)"),v;if(c>0&&o){h.info({err:v},"Failed to execute action with cached target, retrying with AI"),gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.138.2",`missReason:${v instanceof Hr?v.cacheMissReason:"unknown"}`]);let _;f.memory&&eT(f.memory)&&(_=f.memory);let x=v instanceof Hr&&v.cacheMissReason==="failing-ldist";return this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,cache:void 0,action:r,originalCache:l,retriesWithAI:c,finalAttempt:true,options:{...i,memory:_,targetHealingInProgress:true},skipInitialLocateWait:x})}throw new Y("ActionFailureError",`Failed to execute interactive command: ${v instanceof Error?v.message:`${v}`}`,{errOptions:{cause:v}})}}async executeTargetingCommandWithAI(t){let{tracer:n,stepTracer:o,target:r,options:i,command:s,action:a,originalCache:l,logger:c,useMemory:d,cacheBustedBeforeAction:u,cacheBustReason:p,skipInitialLocateWait:m}=t;c.info({description:r.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:u,memory:i.memory,useMemory:d},"Prompting AI for an updated element location");let h=false;(u||!l)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?(await n.startAsyncSpan("SMART_WAITING",async()=>await k4({description:r.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())),h=true):(u||!l)&&(i.skipAISmartWaiting?c.debug("Skipping AI smart waiting for this targeting attempt"):c.debug("Skipping AI smart waiting due to controller execution options"));let g=2;for(let f=1;f<=g;f++){let b=false,T=this.browser.getActiveFrameConfig(),A=i.force||f>1;try{let C;try{C=await WL({description:r.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:d,memory:d?i.memory:void 0,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,allowIneligibleTagRedirect:i.allowIneligibleTagRedirect,showZeroOpacityElementsOverride:i.showZeroOpacityElementsOverride,logger:c,skipWait:h||m,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:p,acceptElementMovedError:A},this.getControllerFixtures());}catch(_){if(_ instanceof cm&&_.updatedLocatorMemory){let x={id:-1,...l,memory:_.updatedLocatorMemory};YE({cmd:s,key:i.targetName,newTarget:x,logger:c,updatedWithAI:!0});}throw _}C.frameConfig&&(this.browser.setActiveFrameConfig(C.frameConfig),b=!0);let v=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:C.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),I=await a(v);return YE({cmd:s,key:i.targetName,newTarget:C.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(o.recordTargetAutoHeal({healType:"AI"}),C.target.targetSource="AI_HEALED",C.target.targetUpdateTime=new Date().toUTCString(),C.target.targetUpdateLoggerTags=vt(c)),{result:I,elementInteractedDisplayString:C.resolution.displayString,thoughts:C.thoughts}}catch(C){if(b&&this.browser.setActiveFrameConfig(T),this.throwIfClosed(),f<g&&yx(C)){c.warn({err:C,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw C instanceof Y?C:new Y("ActionFailureError",C.message)}}throw new Y("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return ES(this.browser,t)}async executePresetCommand(t,n,o,r,i){this.options?.slowMoMs&&await Ye(this.options.slowMoMs);let s=await this.browser.getOpenPages(),a=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(n,o);}catch(c){throw this.throwIfClosed(),new Y("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await it({name:`cli.command.${n.type}`,attributes:{"momentic.command_type":n.type,"momentic.command_id":n.id},fn:()=>this.executePresetCommandHelper(t,n,o,r,i)});return this.options?.autoFollowNewTabs&&await E4({beforeUrl:a,command:n,beforePages:s.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{bQ(n,l);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>EL(t)}}async traceBrowserInteraction(t,n,o){return oo().startAsyncSpan("BROWSER_INTERACTION",async i=>n(i),{name:t,...o})}async resolveCommandTemplateStrings(t,n){return IR({obj:t,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(t,n,o,r,i){r=r||"disableCache"in n&&!!n.disableCache;let s=this.logger.child({commandId:n.id});switch(n.type){case "SUCCESS":{let a=n.condition;return a?.assertion.trim()?zR({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i}):{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AI_ASSERTION":{if(!n.assertion.trim())throw new Y("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new Y("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return zR({command:n,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i})}case "AI_EXTRACT":return L4({command:n,logger:s,fixtures:this.getControllerFixtures(),disableCache:r});case "NAVIGATE":if(!mh(n.url)&&!hh(n.url,this.browser.baseUrl))throw new Y("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "DIALOG":this.browser.registerDialogHandler(n.action);break;case "CAPTCHA":throw new Y("UserConfigurationError","Captcha solving is no longer available on Momentic");case "GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case "GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_DOWN":case "SCROLL_UP":{let a,l;if(n.target&&Ma(n.target)){let u=pr(n.target.pixels);await this.browser.hoverUsingVisualCoordinates(u);}else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:p}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:m=>this.browser.hover(m),options:{...n,targetName:"target",disableGlobalLocatorRedirect:true,disableCache:r}});a=u,l=p;}let c=this.browser.getViewport()?.height??di.height,d=this.browser.getViewport()?.width??di.width;switch(n.type){case "SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(n.deltaY??c)));break;case "SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(n.deltaY??c));break;case "SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(n.deltaX??d)));break;case "SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(n.deltaX??d));break}return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new Y("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case "WAIT":{if(n.delay>1800)throw new Y("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=n.delay*1e3;await Ye(a,this.executeAbortController.signal);break}case "REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "CLICK":{if(Ma(n.target)){let p=pr(n.target.pixels),m={...n,relativePosition:n.relativePosition?pr(n.relativePosition):void 0};await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(p,m),{coordinates:p});break}let a=this.browser.url(),{elementInteractedDisplayString:l,result:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:p=>this.traceBrowserInteraction("Click",async m=>{let h={...n,relativePosition:n.relativePosition?pr(n.relativePosition):void 0},g=await this.browser.click(p,this.createCallbacksForBrowser(this.orgId),h);return g.coordinates&&(m.coordinates=g.coordinates),g},{selector:p.locator.toString()}),options:{...n,targetName:"target",disableCache:r}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:d,data:c.downloadedFile?{downloadedFile:c.downloadedFile}:void 0};return aC(a,u.urlAfterCommand)&&(u.succeedImmediately=true,u.succeedImmediatelyReason="URL changed"),u}case "COPY":return await this.browser.copy(n.value),{succeedImmediately:false,data:n.value,urlAfterCommand:this.browser.url()};case "PASTE":{await this.browser.paste();break}case "DRAG":{if(Ma(n.fromTarget)&&Ma(n.toTarget)){let c=pr(n.fromTarget.pixels),d=pr(n.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(Ma(n.fromTarget)||Ma(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:l}=await this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(c,d)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps})),options:{...n,disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:l}}case "MOUSE_DRAG":{let a=parseInt(n.deltaX),l=parseInt(n.deltaY),c=n.steps??5;if(isNaN(a)||isNaN(l))throw new Y("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ma(n.target)){let p=pr(n.target.pixels);await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:l,steps:c,fromTarget:p}),{coordinates:p});break}let d,u;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:p,thoughts:m}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async h=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,h.locator,{force:n.force})),options:{...n,targetName:"target",disableCache:r}});d=p,u=m;}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,void 0,{force:n.force}));return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:d,thoughts:u}}case "SELECT_OPTION":{if(!$c(n.target))throw new Error("Select with x/y is not supported yet");let a=n.target.elementDescriptor,l=n.choice,{elementInteractedDisplayString:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:{type:"description",elementDescriptor:a},cache:n.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,l,n.force),{value:l.type==="LABEL"?l.label:l.type==="VALUE"?l.value:l.index}),options:{...n,targetName:"target",disableCache:r,source:Tu(n)}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:d}}case "TAB":{let a={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:true};await this.browser.switchToPage(n.action,a);break}case "NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case "CLOSE_TAB":await this.browser.closePage(n.action,{retry:true});break;case "COOKIE":{if(!n.value)break;let a=await this.browser.setCookie(n.value);s.debug({results:a},"Set cookies");break}case "LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case "JAVASCRIPT":{let a;try{n.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),s.info({result:a},"Executed JavaScript in browser")):a=await Ud({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async l=>{if(!this.options?.scratchPadId){s.warn({updates:l},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:l,logger:s});}}});}catch(l){throw this.throwIfClosed(),new Y("ActionFailureError",l instanceof Error?l.message:`${l}`,{errOptions:{cause:l}})}try{JSON.stringify(a);}catch(l){throw new Y("ActionFailureError",`Return value is not serializable: ${l instanceof Error?l.message:`${l}`}`,{errOptions:{cause:l}})}return {urlAfterCommand:this.browser.url(),succeedImmediately:false,data:a}}case "TYPE":{if(n.target&&Ma(n.target)){let m=pr(n.target.pixels),h={...n,relativePosition:n.relativePosition?pr(n.relativePosition):void 0};await this.browser.clickUsingVisualCoordinates(m,h),await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});break}let a=this.browser.url(),l,c,d=cloneDeep(n.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(d){let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:d,cache:n.cache?.target,action:g=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(n.value,g,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),{value:n.value,selector:g.locator.toString()}),options:{...n,targetName:"target",disableCache:r,disableGlobalLocatorRedirect:!u,source:Tu(n)}});l=m,c=h;}else await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});let p={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:c};return aC(a,p.urlAfterCommand)&&(p.succeedImmediately=true,p.succeedImmediatelyReason="URL changed"),p}case "HOVER":{if(Ma(n.target)){let c=pr(n.target.pixels);await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(c),{coordinates:c});break}let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(c,{relativePosition:n.relativePosition?pr(n.relativePosition):void 0}),{selector:c.locator.toString()}),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "FOCUS":{if(!$c(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.browser.focus(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "BLUR":{if(n.target&&!$c(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:false,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:c=>this.browser.blur(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??true,delayMs:n.delayMs}),{value:n.value});let l={urlAfterCommand:this.browser.url(),succeedImmediately:false};return aC(a,l.urlAfterCommand)&&(l.succeedImmediately=true,l.succeedImmediatelyReason="URL changed"),l}case "KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "REQUEST":{let a=new CookieJar,l=Xxe(fetch,a),c;try{c=new URL(n.url).hostname;}catch{}let d=await j4({command:n,baseUrl:this.browser.baseUrl,logger:s,fetchImplementation:l});return {data:qg.parse({...d,cookies:LG(a,c)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await z4({command:n,baseUrl:this.browser.baseUrl,logger:s}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return G4({tracer:t,command:n,disableCache:r,browser:this.browser,logger:s,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case "FILE_UPLOAD":{let a,l;if(n.fileSource.type==="URL"?(l=n.fileSource.url,a=await iX({uri:n.fileSource.url,logger:s,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(l=n.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!a)throw new Y("UserConfigurationError",`Attempted to use non-existent file for upload step: ${l}`);await this.browser.setFileChooserHandler({...a,filename:n.filename});break}case "AUTH_SAVE":{let a=await this.browser.saveAuthState();if(n.storageState&&wd(n.storageState)){let l=En__default.resolve(n.storageState);Mo__default.mkdirSync(En__default.dirname(l),{recursive:true}),Mo__default.writeFileSync(l,`${JSON.stringify(a,null,2)}
5749
+ `),tokenLength:u}),a.forEach((g,f)=>{let b=g.ids[0],T=g.ids[g.ids.length-1];e.debug({tokenLength:g.tokenLength,minId:b,maxId:T},`Chunk for page filtering (index ${f+1}/${a.length})`);}),{chunks:a}}var _4=5e6,vxe=1e5,wxe=3e4,Ixe=6e4,xxe=1e5;async function Ji(e){let{fixtures:t}=e,{logger:n}=t,o=e.tree,r=e.serializedTree,i=nt(r);if(i>_4)throw new Y("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${_4} tokens.`);if(i>vxe){let s=x4({serializedTree:r,options:w4,logger:n}),a=randomUUID();o=await _xe({...e,chunks:s.chunks,callId:a}),r=o.serialize();let l=nt(r);n.info({oldTokens:i,newTokens:l,langfuseCallId:a},"Filtered page using AI chunk ranking");}return r}async function _xe({type:e,callId:t,chunks:n,description:o,fixtures:r,tree:i}){let{generator:s,signal:a,logger:l}=r,c=await s.rankChunksWithAi({chunks:n,description:o,type:e,softTokenLimit:wxe,mediumTokenLimit:Ixe,hardTokenLimit:xxe,callId:t},{abortSignal:a,logger:l,loggerTags:vt(l)}),d=[];return n.forEach((p,m)=>{c.indices.includes(m)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}async function WL(e,t){if(!e.description)throw new Y("UserConfigurationError","Cannot locate element with empty description");return _s({action:async()=>Mxe(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function Mxe(e,t){let{disableCache:n,testContext:o,filterByViewport:r,skipWait:i,source:s,memory:a,logger:l,allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,skipSavingVisualAttributes:p,isAutoHeal:m,cacheBustReason:h,acceptElementMovedError:g}=e,{orgId:f,browser:b,localCodeEvalTools:T,generator:A,abortSignal:C}=t,v=e.description,I=oo(),_=e.useMemory&&!n;o&&(v=await Ir({orgId:f,s:v,context:o,localTools:T,signal:C,logger:l})),s&&(v=A4(v,s));let{serializedTree:x,tree:E}=await I.startAsyncSpan("GET_PAGE_STATE",async()=>Tl(b,{allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,filterByViewport:r,abortSignal:C,skipWait:i,logger:l}),{}),O=await I.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let te,B=Date.now(),le;for(;!te&&Date.now()-B<3e3;){C.throwIfAborted();try{te=await b.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(be){le=be;}}if(!te)throw new Y("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${le?.message}`);return te}),N=x,H=false,$=`data:image/jpeg;base64,${O.toString("base64")}`,oe=vt(l);N=await Ji({type:"locator",description:v,screenshot:$,serializedTree:x,tree:E,fixtures:{generator:A,signal:C,logger:l,orgId:f}}),N!==x&&(H=true);let X=await I.startAsyncSpan("AI_LOCATOR_CALL",async te=>{m&&(te.attributes.isAutoHeal=true),h&&(te.attributes.cacheBustReason=h);let B=await A.getElementLocation({browserState:N,goal:v,screenshot:$,source:s,memory:_?a:void 0},{disableCache:n,abortSignal:C,logger:l,loggerTags:oe,useMemory:_,cacheBustReason:h});if(te.result=B,I.storeTraceAsset){let le=randomUUID();I.storeTraceAsset({snapshotId:le,data:O}),te.screenshotSnapshotId=le;}return B});if(l.debug({usedRag:H,result:X},"Got locator result"),!(X.id>0))throw new cm(`Could not find any relevant element: ${X.thoughts}`,X.updatedMemory?{type:"GCS_TRACES",traces:X.updatedMemory}:void 0);let{resolution:K,target:q,frameConfig:J}=await I.startAsyncSpan("TARGET_RESOLUTION",async te=>{let B=await b.createTargetFromA11yId({id:X.id,requirements:X.requirements,additionalElements:X.additionalElements,description:v,targetSource:"AI",logger:l,skipSavingVisualAttributes:p,acceptElementMovedError:g});return te.result={serializedElement:B.target.nodeOnlySerializedHtml??"Unknown HTML element"},B});if(K.a11yNode?.properties?.hidden&&K.a11yNode?.properties?.hidden!=="false")throw new Y("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${K.displayString}`);return _&&(X.updatedMemory?q.memory={type:"GCS_TRACES",traces:X.updatedMemory}:a&&(q.memory=a)),{thoughts:X.thoughts,target:q,resolution:K,frameConfig:J,screenshot:$}}var Oxe=15;async function zR({command:e,logger:t,fixtures:n,useMemory:o,maxRetries:r=Oxe,recoveryHint:i}){if(!e.assertion.trim())throw new Y("ActionFailureError","Assertion command is missing the assertion content");let s=n_.optional().catch(void 0).parse(e.source);e.source&&!s&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let a=oo();return a.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,d=e.timeout?e.timeout*1e3:c.smartWaitingTimeout,u=Xq(d,r-1),p=0,m=Date.now(),h=m+d,g=m,f,b,T;try{await _s({action:()=>c.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:c,logger:t});}catch(v){t.warn({err:v},"Failed to clear highlights before AI check, continuing...");}for(;p<r;){n.abortSignal.throwIfAborted();let v=Date.now();if(p>0){if(v>=h)break;let x=h-v,E=g-v,O=Math.min(E,x);O>0&&await Ye(O,n.abortSignal);}let I=Date.now();if(p>0&&I>=h)break;let _=false;try{if(f=await _s({action:async()=>{let E=await M4(c,t,n.abortSignal);return b&&b.serializedTree===E.serializedTree&&b.screenshotBuff.equals(E.screenshotBuff)?(_=!0,f):(b=E,O4({command:e,state:E,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:p,logger:t,source:s,recoveryHint:i}))},frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c}),f?.aiResult.result){f?.updatedMemory&&Py(e,f.updatedMemory,t);break}else throw f?.aiResult.thoughts?new Y("AssertionFailureError",f.aiResult.thoughts):new Y("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(x){n.abortSignal.throwIfAborted(),T=x instanceof Error?x:new Error(`${x}`),_?t.info(`AI check attempt ${p} failed (re-used previous result)`):t.info({err:x},`AI check assert attempt ${p} failed, retrying...`);}finally{p++,g=I+u;}}if(!f?.aiResult.result){let v=h-Date.now();v>0&&await Ye(v,n.abortSignal);}if(!f?.aiResult.result)try{f=await _s({action:async()=>O4({command:e,state:await M4(c,t,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:p,logger:t,recoveryHint:i}),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c});}catch(v){n.abortSignal.throwIfAborted(),T=v instanceof Error?v:new Error(`${v}`);}finally{p++;}f?.updatedMemory&&Py(e,f.updatedMemory,t);let A=f?.afterScreenshotOverride;if(A&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:A}),l.screenshotSnapshotId=v;}let C=f?.elementScreenshotOverride;if(C&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:C}),l.elementScreenshotSnapshotId=v;}if(!f?.aiResult.result){l.result=f?.aiResult??{thoughts:T?.message??"AI check failed after all attempts",result:false};let v=`AI check still failing after ${p} attempts.`;throw T&&(v+=` Latest result: ${T.message}`),new Y("AssertionFailureError",v)}return l.result=f.aiResult,{...f,thoughts:f.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:c.url()}})}async function M4(e,t,n){await e.waitForPageLoad({signal:n});let[o,r]=await Promise.all([Tl(e,{abortSignal:n,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...o,screenshotBuff:r}}async function O4({command:e,state:t,fixtures:n,useConsensus:o,useMemory:r,highlightElementsOnFailure:i,attemptNumber:s,source:a,logger:l,recoveryHint:c}){let {browser:d,generator:u,abortSignal:p}=n,{serializedTree:h,tree:g}=t,f=t.screenshotBuff,b=f.toString("base64"),T=d.url(),A=e.contextChoice??"MULTIMODAL",C=h;A!=="VISION_ONLY"&&(C=await Ji({type:"assertion",serializedTree:h,tree:g,description:e.assertion,screenshot:b,fixtures:{generator:u,signal:p,logger:l,orgId:n.orgId}}),C);let v={goal:e.assertion,url:T,memory:r?e.cache?.memory:void 0,browserState:C,screenshot:b,contextChoice:A,source:a,recoveryHint:c},_=await(A==="VISION_ONLY"?(E,O)=>u.getVisualAssertionResult(E,O):(E,O)=>u.getAssertionResult(E,O))(v,{useConsensus:o,attemptNumber:s,useMemory:r,disableCache:!!e.disableCache,abortSignal:p,logger:l,loggerTags:vt(l)}),x;if((_.result||i)&&_.relevantElements?.length){_.relevantElements.map(E=>d.getSerializedFormFromA11yId(E)).filter(E=>!!E);try{let E=_.relevantElements[0],{resolution:O}=await d.createTargetFromA11yId({id:E,description:null,targetSource:"AI",skipSaveToCache:!0});x=await d.screenshot({locator:O.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(E){l.debug({err:E},"Failed to capture element screenshot for trace, continuing...");}await Nxe(_.relevantElements,d,l);}return {aiResult:_,afterScreenshotOverride:f,elementScreenshotOverride:x,updatedMemory:r?_.updatedMemory:void 0}}async function Nxe(e,t,n){let o=Date.now();for(let r of e){if(Date.now()-o>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await Re(t.highlightA11yId(r),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}});}catch(i){n.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}async function L4(e){let{command:t,logger:n,fixtures:o,disableCache:r}=e,{browser:i,generator:s,abortSignal:a}=o;if(!t.goal.trim())throw new Y("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let u=e1(t.schema);if(u)throw new Y("UserConfigurationError",u)}let l=await i.getCondensedHtml(),c=await i.screenshot({retries:2}),d=oo();try{return await d.startAsyncSpan("AI_EXTRACTION_CALL",async u=>{let p=await s.getTextExtraction({goal:t.goal,browserState:l,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${c.toString("base64")}`},{disableCache:r,abortSignal:a,loggerTags:vt(n)});if(u.result=p,Lxe({tracer:d,span:u,screenshot:c,htmlState:l,logger:n}),p.result==="NOT_FOUND")throw new Y("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new Y("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:i.url()}})}catch(u){let p=Q(u);throw p.includes("MaxGenerationLengthExceededError")?new Y("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):p.includes("AIProviderError")&&p.includes("time")?new Y("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:u}}):u}}function Lxe(e){let{tracer:t,span:n,screenshot:o,htmlState:r,logger:i}=e;if(t.storeTraceAsset)try{let s=randomUUID();t.storeTraceAsset({snapshotId:s,data:o}),n.screenshotSnapshotId=s;let a=randomUUID();t.storeTraceAsset({snapshotId:a,data:Buffer.from(r),extension:"html"}),n.browserStateSnapshotId=a;}catch(s){i.debug({err:s},"Failed to store extraction trace assets");}}async function k4(e,t){let{logger:n}=e,{abortSignal:o,browser:r}=t,i=Date.now();try{await kxe(i,e,t);}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")||o.aborted)return;n.warn({err:s},"Unexpected error occurred during AI smart waiting");let a=r.smartWaitingTimeout-(Date.now()-i);a>0&&await Ye(a,o);}finally{n.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function kxe(e,t,n){let{abortSignal:o,browser:r}=n;if(r.smartWaitingTimeout<3e3){await Ye(r.smartWaitingTimeout,o);return}if(!t.description)throw new Y("UserConfigurationError","Cannot locate element with empty description");await Re(Dxe(e,t,n),{milliseconds:r.smartWaitingTimeout});}async function Dxe(e,t,n){let{logger:o,iframeUrl:r}=t,{browser:i}=n;for(;Date.now()-e<i.smartWaitingTimeout;)if(await _s({action:async()=>Fxe(t,n),frameConfig:r?{type:"url",url:r}:void 0,browser:i,logger:o}))return}async function Fxe(e,t){let{testContext:n,logger:o}=e,{browser:r,abortSignal:i,localCodeEvalTools:s,orgId:a,generator:l}=t,c=e.description;n&&(c=await Ir({orgId:a,s:c,context:n,localTools:s,signal:i,logger:o})),i.throwIfAborted();let d;try{d=await r.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(h){throw new Y("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${h instanceof Error?h.message:h}`)}let p=`data:image/jpeg;base64,${d.toString("base64")}`;i.throwIfAborted();let m=await l.getSmartWaitingDecision({description:c,screenshot:p},{abortSignal:i,loggerTags:vt(o)});return o.debug({result:m},"Got smart waiting result"),m.isPageReady}var Bxe=15e3,Uxe=6e4;async function B4(e){return oo().startAsyncSpan("ELEMENT_ASSERTION",async n=>Hxe(e,n),{name:"Element check"})}async function Hxe(e,t){let{command:n,timeoutMs:o,fixtures:r,disableCache:i}=e,{abortSignal:s}=r,a=()=>nT(n.cache)?n.cache:void 0,l=a(),c=!i&&!!l?.target&&Kp(l.target),d=cloneDeep(l),u=(C=false)=>{if(l=a(),!!l)if(C){let v=cO(d,l);l.target=v.target,l.updatedAt=v.updatedAt;}else {if(!d){l=void 0;return}l.target=d.target,l.updatedAt=d.updatedAt;}},p=Date.now(),m=c?Math.min(Math.max(o/10,Bxe),Uxe):0,h=p,g=0,f,b=500,T=false;for(;g<2||Date.now()-p<o;){g++,g>1&&await Ye(b,s),s?.throwIfAborted(),l=a();let C=g===1,v=c&&Date.now()-h>=m;v&&(h=Date.now());let{result:I,elementWasFound:_}=await D4({cacheToUse:l,skipAISmartWaiting:!C,useAIIfCacheFails:!c||v,params:e});if(f=I,T=T||_,I.success)break;u(),b=Math.min(b*1.25,1e4);}if(!f)throw new Y("InternalPlatformError",`Failed to evaluate manual element assertion in ${o}ms.`);if(s?.throwIfAborted(),!f.success){let C=a(),v=C?.target?.memory?{target:{id:-1,memory:C.target.memory}}:void 0,{result:I,elementWasFound:_}=await D4({cacheToUse:v,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});f=I,T=T||_,f.success||u(true);}let A=a();return f.success&&A?.target&&!T&&(A.target=_y(A.target),A.updatedAt=new Date),t.result={success:f.success,message:f.err?.message},f}async function D4({cacheToUse:e,skipAISmartWaiting:t,useAIIfCacheFails:n,params:o}){let{command:r,disableCache:i,fixtures:s,tracer:a,targetingWrapper:l}=o,{logger:c}=s;if(r.target&&!$c(r.target))throw new Error("Element assertion with x/y is not supported yet");let d=B2(r.assertion),u=Gxe(r.assertion),p,m=false,h=cloneDeep(e);try{let{elementInteractedDisplayString:g,result:f,thoughts:b}=await l({tracer:a,command:r,target:r.target,cache:h?.target,action:async T=>jxe(T.locator,o),options:{...r,allowNotActionableNodesOverride:u,allowIneligibleTagRedirect:u,showZeroOpacityElementsOverride:!0,disableCache:i,memory:h?.target?.memory,disableGlobalLocatorRedirect:!0,source:Tu(r),skipAISmartWaiting:t,targetName:"target"},retriesWithAI:n?1:0});return p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:g,thoughts:b},m=!0,f.success||(c.warn({aiThoughts:b,elementString:g,err:f.err},"Element check found an element but failed"),p={...f,thoughts:b}),{result:p,elementWasFound:m}}catch(g){if(d)return p={success:true,thoughts:`The element described does not exist on the page: ${g.message}`,err:void 0,data:void 0},{result:p,elementWasFound:m};if(!(g instanceof Y)||g.reason!="ActionFailureError")throw g;return p={success:false,err:g,data:void 0,thoughts:void 0},c.warn({err:g},"Element check did not find an element and failed"),{result:p,elementWasFound:m}}}function Gxe(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function jxe(e,{command:t,fixtures:n}){return await n.browser.highlight(e),await $xe(e,t.assertion)}async function $xe(e,t){let n=true,o,r;switch(t.type){case "ELEMENT_CONTENT":{let s=await e.textContent()??"";if(r={elementTextContent:sn(s,500,true)},!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=lh(t);n=false,o=new Y("AssertionFailureError",`The content ${a} '${t.value}': ${s}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:sn(await e.evaluate(a=>a.cloneNode(false).outerHTML),500,true)};let s=null;try{s=await e.getAttribute(t.attr,{timeout:3e3});}catch(a){o=new Y("AssertionFailureError",Q(a)),n=false;break}if(!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=lh(t);n=false,t.operation==="EXISTS"?o=new Y("AssertionFailureError",`The attribute ${t.attr} ${a}`):o=new Y("AssertionFailureError",`The attribute ${t.attr} ${a} '${t.value}': ${s}`);}break}case "ELEMENT_EXISTENCE":{switch(t.condition){case "VISIBLE":{n=await e.evaluate(async(a,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(u=>setTimeout(u,250));let d=a.getBoundingClientRect();if(!(d.width===0||d.height===0)&&window.getComputedStyle(a).visibility!=="hidden"&&window.getComputedStyle(a).display!=="none")return true}return false},ss*1e3);break}case "EDITABLE":{n=await e.isEditable({timeout:ss*1e3});break}case "EXISTS":{n=true;break}case "ENABLED":{n=await e.isEnabled({timeout:ss*1e3});break}case "FOCUSED":{n=await e.evaluate(a=>a===document.activeElement);break}default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})(t.condition)}if(n=t.negated?!n:n,!n){let s=lh(t);o=new Y("AssertionFailureError",`The element ${s}`);}break}case "ELEMENT_NAME":{let s=await e.evaluate(a=>a.tagName);if(!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let a=lh(t);n=false,o=new Y("AssertionFailureError",`The element tag name ${a} '${t.value}': ${s}`);}break}case "ELEMENT_STYLE":{let s=await e.evaluate((a,l)=>window.getComputedStyle(a).getPropertyValue(l),t.property);if(!wy(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=lh(t);n=false,t.operation==="EXISTS"?o=new Y("AssertionFailureError",`The style property ${t.property} ${a}`):o=new Y("AssertionFailureError",`The style property ${t.property} ${a} '${t.value}': ${s}`);}break}default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {thoughts:void 0,success:n,data:r,err:o}}function U4(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function ES(e,t){let n=await e.screenshot(t),{width:o,height:r}=imageSize(n);return {buffer:n,width:Math.ceil(o),height:Math.ceil(r)}}async function G4({tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:r,logger:i,screenshotStorage:s}){if(t.target&&!$c(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForStability({logger:i});let a={clearHighlights:true,hideCaret:true},l;t.target?.elementDescriptor?l=(await r({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async O=>ES(o,{locator:O.locator,...a}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ES(o,a);let c=await s.prepareGoldenScreenshotForComparison(i,t,l);if((l.height!==c.height||l.width!==c.width)&&i.warn({currHeight:l.height,currWidth:l.width,savedHeight:c.height,savedWidth:c.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-c.height)>10||Math.abs(l.width-c.width)>10){let E=`${l.width}x${l.height}`,O=`${c.width}x${c.height}`;return {fail:true,thoughts:`Current screenshot (${E}) does not match saved screenshot dimensions (${O}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:false,urlAfterCommand:o.url()}}let d=await Jimp.fromBuffer(l.buffer),u={width:l.width,height:l.height},p=await Jimp.fromBuffer(c.buffer),m={width:c.width,height:c.height},h,g=u.width*u.height,f=m.width*m.height,b=Math.abs(u.height-m.height),T=Math.abs(u.width-m.width);if(g>f){let E=d.cover({w:m.width,h:m.height});l.buffer=await E.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height;}else if(f>g){let E=p.cover({w:u.width,h:u.height});c.buffer=await E.getBuffer("image/jpeg"),h="saved";}let A={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},C=t.threshold??.1,I=_Ie(qL.decode(c.buffer).data,qL.decode(l.buffer).data,A.data,l.width,l.height,{threshold:C,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,_=I>C*100,x=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${C*100}%.`;if(h&&(x+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${T} pixels.`),_)throw new Y("ActionFailureError",x);return {fail:_,thoughts:x,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:qL.encode(A,75).data,succeedImmediately:false,urlAfterCommand:o.url()}}var Wxe=3e4;function qxe(e){if(!e.body)return {};switch(e.body.type){case "json":return {content:e.body.content,contentType:"application/json"};case "form-urlencoded":{let t=new URLSearchParams;return Object.entries(e.body.content).forEach(([n,o])=>{t.append(n,o);}),{content:t.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function j4({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??Wxe/1e3,i=Object.fromEntries(Object.entries(e.headers||{}).filter(([h,g])=>h&&g)),s=new URLSearchParams;Object.entries(e.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{s.append(h,g);});let a=s.toString(),l;if(mh(e.url)&&(l=e.url),n&&hh(e.url,n)&&(l=new URL(e.url,n).toString()),!l)throw new Y("ActionFailureError",`Invalid URL: ${e.url}`);let c=l;t.info({url:c,searchParams:a,headers:i,body:e.body,method:e.method},"Making HTTP request");let u=await Re((async()=>{let h=a?`${c}?${a}`:c;try{let g=qxe(e),f=new Headers(i);return g.contentType&&!f.has("Content-Type")&&f.set("Content-Type",g.contentType),await o(h,{headers:f,method:e.method,body:g.content})}catch(g){throw new Error(`Failed to make HTTP request: ${g}`,{cause:g})}})(),{milliseconds:r*1e3,fallback:()=>{throw new Y("ActionFailureError",`Fetch request timed out after ${r} seconds`)}});if(!u.ok){let h;try{h=await u.text();}catch(g){h=`Failed to read response body: ${g}`;}throw new Y("ActionFailureError",`Fetch request failed with status ${u.status}: ${h}`)}let p={};u.headers.forEach((h,g)=>{p[g]=h;});let m={status:u.status,headers:p,request:{url:u.url,method:e.method,headers:i}};if(e.body?.type==="json"&&e.body.content)try{m.request.json=JSON.parse(e.body.content);}catch{}if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json();}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var Kxe=5e3;async function WR({timeout:e=ss,...t}){let n=Date.now(),o=e*1e3,r=o+1e4,i,s=0,a=500;for(;s-n<o;){if(Date.now()-n>r){t.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}t.signal?.throwIfAborted();let l=Date.now();i=await $4(t),s=Date.now();let c=s-l;if(c>1e3&&t.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Ye(a,t.signal),a=Math.min(Math.floor(a*1.5),Kxe);else return i}return i=await $4(t),i}async function $4(e){return oo().startAsyncSpan("PAGE_ASSERTION",async n=>{let o=await Yxe(e);return n.result={success:o.success,message:o.err?.message},o},{name:"Page check"})}async function Yxe({assertion:e,browser:t,autoExpandIframes:n}){switch(e.type){case "CONTENT":case "CONTENT":{let r,i=false,s;try{let a;if(n){let l=await t.evaluateFunctionInAllFrames(V4,{value:e.value,negated:!!e.negated,returnHtml:!1});i=e.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml;}else ({evaluation:i,pageHtml:a}=await t.evaluateFunctionInPage(V4,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?uc.CONTAINS:pc.CONTAINS;s=new Y("AssertionFailureError",`The page ${l} '${e.value}'.`),r=a;}}catch(a){s=new Y("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`);}return {success:i,err:s,data:i||!r?void 0:{pageContent:r}}}default:return (r=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}}function V4({value:e,negated:t,returnHtml:n}){let o=document.body.innerHTML,r=o.includes(e)===!t;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),{evaluation:r,pageHtml:!r&&n?o:void 0}}var Jxe=3e4;async function z4({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??Jxe/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(e.headers||{}).filter(([u,p])=>u&&p));s["Content-Type"]="application/json";let a;if(mh(e.url)&&(a=e.url),n&&hh(e.url,n)&&(a=new URL(e.url,n).toString()),!a)throw new Y("ActionFailureError",`Invalid URL: ${e.url}`);let c=await Re((async()=>{try{return await o(a,{headers:s,method:"POST",body:JSON.stringify({query:e.query,variables:e.variables?JSON.parse(e.variables):void 0}),signal:i.signal})}catch(u){throw new Error(`Failed to make HTTP request: ${u}`,{cause:u})}})(),{milliseconds:r*1e3});if(!c)throw new Y("ActionFailureError",`GraphQL request timed out after ${r} seconds`);if(!c.ok){let u,p=await c.text();try{u=JSON.parse(p);}catch{throw new Y("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}throw u?.errors?.length&&u?.errors[0]?.message?new Y("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new Y("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}let d={};return c.headers.forEach((u,p)=>{d[p]=u;}),{status:c.status,headers:d,json:await c.json()}}var Wh=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:t,generator:n,logger:o,storage:r,orgId:i,localCodeEvalTools:s,uploadedFileStorage:a,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=t,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=r,this.uploadedFileStorage=a,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=s,this.generator=n,this.logger=o;}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal);}setClosed(){this.executeAbortController.abort();}throwIfClosed(){this.executeAbortController.signal.throwIfAborted();}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(t,n){this.executionOptionsStack.push(t);try{return await n()}finally{this.executionOptionsStack.pop();}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:t,startingScreenshot:n,history:o,disableCache:r,langfuseSessionId:i,lastError:s,logger:a=this.logger}){let[l,c]=await Promise.all([Tl(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:a}),this.browser.screenshot({retries:1,clearHighlights:true})]),d=`data:image/jpeg;base64,${c.toString("base64")}`,u=await Ji({type:"ai-action",description:t,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:this.browser.url(),browserState:u,startingScreenshot:n,history:o,goal:t,screenshot:d,lastError:s};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:{...vt(a)},langfuseSessionId:i})}async promptToCommand({goal:t,startingScreenshot:n,history:o,actionHint:r,disableCache:i,logger:s=this.logger,langfuseSessionId:a}){let l=this.browser.url(),[c,d]=await Promise.all([Tl(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:s}),this.browser.screenshot({retries:1,clearHighlights:true})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,p=await Ji({type:"ai-action",description:t,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:l,browserState:p,startingScreenshot:n,history:o,goal:t,actionHint:r,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...vt(s)},langfuseSessionId:a})}catch(h){throw new Y("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return Tl(this.browser,t)}async locateElement(t){return await WL(t,this.getControllerFixtures())}async locateElementWithSelector(t,n){return _s({action:async()=>{let o=await this.browser.resolveHardcodedCssSelector({selector:t,timeoutMs:2e3,logger:this.logger});return {thoughts:"Located element with selector",target:{id:-1,selector:t,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:o}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return {browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??true}async wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:i,action:s,options:a,retriesWithAI:l=1}){let c=[];for(let d=0;d<r.length;d++){let u=r[d],p=await this.wrapElementTargetingCommand({tracer:t,command:n,target:u,cache:i[d],action:async m=>m,options:{...a,targetName:o[d]}});c.push(p);}try{let d=await s(...c.map(m=>m.result)),u=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",p=c.map((m,h)=>m.thoughts?`${u(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return {result:d,elementInteractedDisplayStrings:c.map(m=>m.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:r.map(()=>{}),action:s,options:a,retriesWithAI:l-1});throw new Y("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapHardcodedCssTargetingCommandHelper({target:t,action:n,options:o,command:r}){let i=this.logger.child({commandId:r.id}),{targetName:s}=o;if(t.type!=="description")throw new Y("ActionFailureError","Cannot use selector with non-description target");let a,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({selector:t.elementDescriptor,targetName:s,logger:i});return {result:await n({locator:d.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;a=d,i.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Ye(500);}}throw a}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:n,disableGlobalLocatorRedirect:o,logger:r}=t,i=oo(),s=!o&&this.browser.userBrowserSettings.globalLocatorRedirect!==false;(this.browser.userBrowserSettings.visualActions||s)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(n.locator);});let a;return s&&(a=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:d}=await this.browser.performTargetRedirection(n,r);if(l.result=d,d.outcome==="redirected to new element"&&c&&i.storeTraceAsset&&!this.browser.userBrowserSettings.disableBrowserMonitoring){let u=randomUUID();(async()=>{try{let p=await this.browser.screenshot({locator:c.locator,clearHighlights:!0,boundingBoxOverride:c.serverSideBoundingBox??void 0});i.storeTraceAsset?.({snapshotId:u,data:p});}catch(p){r.debug({err:p},"Failed to capture element screenshot for redirect trace");}})(),l.elementScreenshotSnapshotId=u;}return c})),a||(a={locator:n.locator,serverSideBoundingBox:await n.locator.boundingBox({timeout:Ve}),originalElementLocationResult:n.originalElementLocationResult}),a}async resolveCachedTargetForAction(t){let{cache:n,options:o,logger:r}=t,s=await oo().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=n.targetSource,l.attributes.smartWaitingTimeoutMs=this.browser.smartWaitingTimeout;try{let c=await this.browser.resolveTarget(n,{allowNotActionableNodesOverride:o.allowNotActionableNodesOverride,logger:r,signal:this.executeAbortController.signal,...o.resolveTargetOptions,acceptElementMovedError:o.force});l.attributes.targetDisplayString=c.displayString,l.attributes.decisions=c.decisions;let d=c.decisions.find(u=>u.matched);return d&&(l.resolutionMethod=d.type),c}catch(c){throw c instanceof Hr&&(l.cacheMissReason=c.cacheMissReason,l.attributes.decisions=c.decisions),c}}),a=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:s,disableGlobalLocatorRedirect:o.disableGlobalLocatorRedirect,logger:r});return o.force||await s.revalidator?.(),{resolutionResult:s,finalTarget:a}}async wrapElementTargetingCommand(t){return await _s({action:()=>this.wrapElementTargetingCommandHelper(t),frameConfig:t.options.iframeUrl?{type:"url",url:t.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(t){let{tracer:n,target:o,action:r,options:i,command:s,finalAttempt:a=false,originalCache:l=t.cache}=t,{retriesWithAI:c=1}=t,{disableCache:d,useSelector:u,targetName:p}=i,m=oo(),h=this.logger.child({commandId:s.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||d)&&!xB(o))throw new Y("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(t);let b=false,T;d&&(h.info("Cache explicitly disabled for this step"),b=true,T="Cache explicitly disabled",f=void 0);let A=R4({cache:f,description:o.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:h});f=A.cache,b=b||A.cacheBustedBeforeAction,!T&&A.cacheBustReason&&(T=A.cacheBustReason);let C=true;if(!C4(f))return c--,C=false,this.executeTargetingCommandWithAI({tracer:m,stepTracer:n,target:o,options:i,command:s,action:r,originalCache:l,logger:h,useMemory:g,cacheBustedBeforeAction:b,cacheBustReason:T});try{let{resolutionResult:v,finalTarget:I}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),_=await r(I);if(gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.138.3"]),YE({cmd:s,key:p,newTarget:f,logger:h,updatedWithAI:!1}),C){let x=v.decisions.filter(E=>E.matched);if(x.length!==1)h.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let E=x[0].type;n.recordTargetAutoHeal({healType:E});}}return {result:_,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let I=yx(v);if(I&&!a)return h.warn({err:v},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,action:r,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:true,options:i});if(v instanceof Y&&!I)throw h.warn({err:v},"Failed to execute command with target (fatal)"),v;if(c>0&&o){h.info({err:v},"Failed to execute action with cached target, retrying with AI"),gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.138.3",`missReason:${v instanceof Hr?v.cacheMissReason:"unknown"}`]);let _;f.memory&&eT(f.memory)&&(_=f.memory);let x=v instanceof Hr&&v.cacheMissReason==="failing-ldist";return this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,cache:void 0,action:r,originalCache:l,retriesWithAI:c,finalAttempt:true,options:{...i,memory:_,targetHealingInProgress:true},skipInitialLocateWait:x})}throw new Y("ActionFailureError",`Failed to execute interactive command: ${v instanceof Error?v.message:`${v}`}`,{errOptions:{cause:v}})}}async executeTargetingCommandWithAI(t){let{tracer:n,stepTracer:o,target:r,options:i,command:s,action:a,originalCache:l,logger:c,useMemory:d,cacheBustedBeforeAction:u,cacheBustReason:p,skipInitialLocateWait:m}=t;c.info({description:r.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:u,memory:i.memory,useMemory:d},"Prompting AI for an updated element location");let h=false;(u||!l)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?(await n.startAsyncSpan("SMART_WAITING",async()=>await k4({description:r.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())),h=true):(u||!l)&&(i.skipAISmartWaiting?c.debug("Skipping AI smart waiting for this targeting attempt"):c.debug("Skipping AI smart waiting due to controller execution options"));let g=2;for(let f=1;f<=g;f++){let b=false,T=this.browser.getActiveFrameConfig(),A=i.force||f>1;try{let C;try{C=await WL({description:r.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:d,memory:d?i.memory:void 0,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,allowIneligibleTagRedirect:i.allowIneligibleTagRedirect,showZeroOpacityElementsOverride:i.showZeroOpacityElementsOverride,logger:c,skipWait:h||m,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:p,acceptElementMovedError:A},this.getControllerFixtures());}catch(_){if(_ instanceof cm&&_.updatedLocatorMemory){let x={id:-1,...l,memory:_.updatedLocatorMemory};YE({cmd:s,key:i.targetName,newTarget:x,logger:c,updatedWithAI:!0});}throw _}C.frameConfig&&(this.browser.setActiveFrameConfig(C.frameConfig),b=!0);let v=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:C.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),I=await a(v);return YE({cmd:s,key:i.targetName,newTarget:C.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(o.recordTargetAutoHeal({healType:"AI"}),C.target.targetSource="AI_HEALED",C.target.targetUpdateTime=new Date().toUTCString(),C.target.targetUpdateLoggerTags=vt(c)),{result:I,elementInteractedDisplayString:C.resolution.displayString,thoughts:C.thoughts}}catch(C){if(b&&this.browser.setActiveFrameConfig(T),this.throwIfClosed(),f<g&&yx(C)){c.warn({err:C,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw C instanceof Y?C:new Y("ActionFailureError",C.message)}}throw new Y("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return ES(this.browser,t)}async executePresetCommand(t,n,o,r,i){this.options?.slowMoMs&&await Ye(this.options.slowMoMs);let s=await this.browser.getOpenPages(),a=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(n,o);}catch(c){throw this.throwIfClosed(),new Y("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await it({name:`cli.command.${n.type}`,attributes:{"momentic.command_type":n.type,"momentic.command_id":n.id},fn:()=>this.executePresetCommandHelper(t,n,o,r,i)});return this.options?.autoFollowNewTabs&&await E4({beforeUrl:a,command:n,beforePages:s.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{bQ(n,l);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>EL(t)}}async traceBrowserInteraction(t,n,o){return oo().startAsyncSpan("BROWSER_INTERACTION",async i=>n(i),{name:t,...o})}async resolveCommandTemplateStrings(t,n){return IR({obj:t,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(t,n,o,r,i){r=r||"disableCache"in n&&!!n.disableCache;let s=this.logger.child({commandId:n.id});switch(n.type){case "SUCCESS":{let a=n.condition;return a?.assertion.trim()?zR({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i}):{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AI_ASSERTION":{if(!n.assertion.trim())throw new Y("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new Y("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return zR({command:n,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i})}case "AI_EXTRACT":return L4({command:n,logger:s,fixtures:this.getControllerFixtures(),disableCache:r});case "NAVIGATE":if(!mh(n.url)&&!hh(n.url,this.browser.baseUrl))throw new Y("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "DIALOG":this.browser.registerDialogHandler(n.action);break;case "CAPTCHA":throw new Y("UserConfigurationError","Captcha solving is no longer available on Momentic");case "GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case "GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_DOWN":case "SCROLL_UP":{let a,l;if(n.target&&Ma(n.target)){let u=pr(n.target.pixels);await this.browser.hoverUsingVisualCoordinates(u);}else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:p}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:m=>this.browser.hover(m),options:{...n,targetName:"target",disableGlobalLocatorRedirect:true,disableCache:r}});a=u,l=p;}let c=this.browser.getViewport()?.height??di.height,d=this.browser.getViewport()?.width??di.width;switch(n.type){case "SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(n.deltaY??c)));break;case "SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(n.deltaY??c));break;case "SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(n.deltaX??d)));break;case "SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(n.deltaX??d));break}return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new Y("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case "WAIT":{if(n.delay>1800)throw new Y("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=n.delay*1e3;await Ye(a,this.executeAbortController.signal);break}case "REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "CLICK":{if(Ma(n.target)){let p=pr(n.target.pixels),m={...n,relativePosition:n.relativePosition?pr(n.relativePosition):void 0};await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(p,m),{coordinates:p});break}let a=this.browser.url(),{elementInteractedDisplayString:l,result:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:p=>this.traceBrowserInteraction("Click",async m=>{let h={...n,relativePosition:n.relativePosition?pr(n.relativePosition):void 0},g=await this.browser.click(p,this.createCallbacksForBrowser(this.orgId),h);return g.coordinates&&(m.coordinates=g.coordinates),g},{selector:p.locator.toString()}),options:{...n,targetName:"target",disableCache:r}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:d,data:c.downloadedFile?{downloadedFile:c.downloadedFile}:void 0};return aC(a,u.urlAfterCommand)&&(u.succeedImmediately=true,u.succeedImmediatelyReason="URL changed"),u}case "COPY":return await this.browser.copy(n.value),{succeedImmediately:false,data:n.value,urlAfterCommand:this.browser.url()};case "PASTE":{await this.browser.paste();break}case "DRAG":{if(Ma(n.fromTarget)&&Ma(n.toTarget)){let c=pr(n.fromTarget.pixels),d=pr(n.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(Ma(n.fromTarget)||Ma(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:l}=await this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(c,d)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps})),options:{...n,disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:l}}case "MOUSE_DRAG":{let a=parseInt(n.deltaX),l=parseInt(n.deltaY),c=n.steps??5;if(isNaN(a)||isNaN(l))throw new Y("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ma(n.target)){let p=pr(n.target.pixels);await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:l,steps:c,fromTarget:p}),{coordinates:p});break}let d,u;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:p,thoughts:m}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async h=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,h.locator,{force:n.force})),options:{...n,targetName:"target",disableCache:r}});d=p,u=m;}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,void 0,{force:n.force}));return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:d,thoughts:u}}case "SELECT_OPTION":{if(!$c(n.target))throw new Error("Select with x/y is not supported yet");let a=n.target.elementDescriptor,l=n.choice,{elementInteractedDisplayString:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:{type:"description",elementDescriptor:a},cache:n.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,l,n.force),{value:l.type==="LABEL"?l.label:l.type==="VALUE"?l.value:l.index}),options:{...n,targetName:"target",disableCache:r,source:Tu(n)}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:d}}case "TAB":{let a={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:true};await this.browser.switchToPage(n.action,a);break}case "NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case "CLOSE_TAB":await this.browser.closePage(n.action,{retry:true});break;case "COOKIE":{if(!n.value)break;let a=await this.browser.setCookie(n.value);s.debug({results:a},"Set cookies");break}case "LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case "JAVASCRIPT":{let a;try{n.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),s.info({result:a},"Executed JavaScript in browser")):a=await Ud({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async l=>{if(!this.options?.scratchPadId){s.warn({updates:l},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:l,logger:s});}}});}catch(l){throw this.throwIfClosed(),new Y("ActionFailureError",l instanceof Error?l.message:`${l}`,{errOptions:{cause:l}})}try{JSON.stringify(a);}catch(l){throw new Y("ActionFailureError",`Return value is not serializable: ${l instanceof Error?l.message:`${l}`}`,{errOptions:{cause:l}})}return {urlAfterCommand:this.browser.url(),succeedImmediately:false,data:a}}case "TYPE":{if(n.target&&Ma(n.target)){let m=pr(n.target.pixels),h={...n,relativePosition:n.relativePosition?pr(n.relativePosition):void 0};await this.browser.clickUsingVisualCoordinates(m,h),await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});break}let a=this.browser.url(),l,c,d=cloneDeep(n.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(d){let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:d,cache:n.cache?.target,action:g=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(n.value,g,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),{value:n.value,selector:g.locator.toString()}),options:{...n,targetName:"target",disableCache:r,disableGlobalLocatorRedirect:!u,source:Tu(n)}});l=m,c=h;}else await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});let p={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:c};return aC(a,p.urlAfterCommand)&&(p.succeedImmediately=true,p.succeedImmediatelyReason="URL changed"),p}case "HOVER":{if(Ma(n.target)){let c=pr(n.target.pixels);await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(c),{coordinates:c});break}let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(c,{relativePosition:n.relativePosition?pr(n.relativePosition):void 0}),{selector:c.locator.toString()}),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "FOCUS":{if(!$c(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.browser.focus(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "BLUR":{if(n.target&&!$c(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:false,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:c=>this.browser.blur(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??true,delayMs:n.delayMs}),{value:n.value});let l={urlAfterCommand:this.browser.url(),succeedImmediately:false};return aC(a,l.urlAfterCommand)&&(l.succeedImmediately=true,l.succeedImmediatelyReason="URL changed"),l}case "KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "REQUEST":{let a=new CookieJar,l=Xxe(fetch,a),c;try{c=new URL(n.url).hostname;}catch{}let d=await j4({command:n,baseUrl:this.browser.baseUrl,logger:s,fetchImplementation:l});return {data:qg.parse({...d,cookies:LG(a,c)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await z4({command:n,baseUrl:this.browser.baseUrl,logger:s}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return G4({tracer:t,command:n,disableCache:r,browser:this.browser,logger:s,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case "FILE_UPLOAD":{let a,l;if(n.fileSource.type==="URL"?(l=n.fileSource.url,a=await iX({uri:n.fileSource.url,logger:s,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(l=n.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!a)throw new Y("UserConfigurationError",`Attempted to use non-existent file for upload step: ${l}`);await this.browser.setFileChooserHandler({...a,filename:n.filename});break}case "AUTH_SAVE":{let a=await this.browser.saveAuthState();if(n.storageState&&wd(n.storageState)){let l=En__default.resolve(n.storageState);Mo__default.mkdirSync(En__default.dirname(l),{recursive:true}),Mo__default.writeFileSync(l,`${JSON.stringify(a,null,2)}
5750
5750
  `,"utf8");}return {data:a,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AUTH_LOAD":{let a;if(wd(n.storageState))try{a=JSON.parse(Mo__default.readFileSync(En__default.resolve(n.storageState),"utf8"));}catch(c){throw new Y("UserConfigurationError",`Failed to read auth state from '${n.storageState}': ${Q(c)}`,{errOptions:{cause:c}})}else if(!n.storageState.trim())a=void 0;else if(a=await Ud({orgId:this.orgId,code:n.storageState,fragment:false,context:o,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new Y("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let l;try{l=pA.optional().parse(a);}catch(c){throw new Y("ActionFailureError",`Credentials provided do not follow the required format: ${c}`)}await this.browser.loadAuthState(l);break}case "ELEMENT_CHECK":{let a=(n.timeout??ss)*1e3,l=this.generator.getAgentConfig()?.assertion;if(U4(n.assertion)&&!n.useSelector&&n.target.type==="description"&&l&&l!=="v1"){let d={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,source:"NEGATED_CHECK",cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let u=await zR({command:d,logger:s,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory()});return {succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${u.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:u.afterScreenshotOverride}}finally{d.cache?.memory&&Py(n,d.cache?.memory.traces,s);}}let c=await B4({command:n,tracer:t,timeoutMs:a,targetingWrapper:d=>this.wrapElementTargetingCommand(d),fixtures:this.getControllerFixtures(),disableCache:r});return {fail:!c.success,data:c.data,elementInteracted:c.elementInteractedDisplayString,thoughts:c.err?.message??c.thoughts??`Element assertion ${c.success?"succeeded":"failed"}.`,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "PAGE_CHECK":{let a=await _s({action:async()=>WR({assertion:n.assertion,browser:this.browser,logger:s,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:s});return {fail:!a.success,data:a.data,thoughts:a.success?"Page assertion passed.":a.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:false}}case "REGISTER_REQUEST_LISTENER":{let a=new zd(n.requestMatcher),l=this.browser.registerRequestListener(a);return this.registeredListeners[n.key]=l.then(async c=>await wL(c)).catch(c=>{s.error({err:c},"Failed to get request listener response");}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AWAIT_LISTENER":{let a=this.registeredListeners[n.key];if(!a)throw new Y("ActionFailureError",`No listener registered with key: ${n.key}`);let l=n.timeout??10;return {data:await Re(a,{milliseconds:l*1e3,message:`Request listener timed out after ${l} seconds`}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "RECORD_REQUESTS":{let a=new zd(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:l=>a.matches({url:l.request.url,method:l.request.method}),onRequestStart:(l,c)=>{this.recordedRequests[n.key][l]=kR(c);},onRequestComplete:(l,c)=>{this.recordedRequests[n.key]?.[l]&&(this.recordedRequests[n.key][l]=kR(c));}}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GET_RECORDED_REQUESTS":{let a=this.recordedRequests[n.key];if(!a)throw new Y("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(a),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "SET_HEADER":{let a;return n.requestMatcher&&(a=new zd(n.requestMatcher)),this.browser.setHeader(n.name,n.value,a),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "MOCK_ROUTE":return {data:{key:this.browser.registerMock(n.key,new zd(n.requestMatcher),async(l,c)=>{let d=await Ud({orgId:this.orgId,code:n.responseGenerator,fragment:false,context:o,timeoutMs:void 0,logger:s,localTools:this.localCodeEvalTools,mock:{request:l,response:c},disallowVariableUpdates:true,responseSerialization:"RESPONSE"}),u=XG.parse(d);return new Response(u.body,{status:u.status,headers:u.headers})},n.fetchOriginalResponse??false)},succeedImmediately:false,urlAfterCommand:this.browser.url()};case "REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:false,urlAfterCommand:this.browser.url()};case "OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:false,urlAfterCommand:this.browser.url()};default:return (l=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {succeedImmediately:false,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:t,targetId:n,disableCache:o,screenshot:r}){return (await this.generator.getReverseMappedDescription({browserState:t,target:n,screenshot:r},{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:vt(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights();}async startRecordMode({params:t,abortController:n,isClickToRecord:o}){this.recordAbortController=n;let r=new GR({signal:n.signal,...t});return await this.browser.startRecording(this.recordAbortController.signal,r,o),r}async runSectionAutohealing(t){return this.generator.getAutohealingProposal(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:vt(this.logger)})}async getFailureRecoveryPlan(t,n){return this.generator.getFailureRecoveryPlan(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:vt(n??this.logger)})}};var JL=async e=>{let{step:t,resolvedInputs:n}=e.moduleParams,{logger:o,context:r,storage:i,codeEvalTools:s,controller:a}=e.fixtures,l=a.browser,{orgId:c,runId:d}=e.inputs,u=a.executeAbortController.signal;Object.keys(n).length>0&&(r.setInputs(n),o.info(Gi({json:{inputs:n,moduleId:t.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=false,h,g;if(t.cacheConfig||t.defaultCacheAllInvocations){let f=t.cacheConfig?.cacheKey||t.defaultCacheKey||"",b=await Ir({orgId:c,s:f,context:r,logger:o,localTools:s,signal:u});g={orgId:c,cacheKeys:[b,...Object.entries(n).map(([A,C])=>`${A}:${C}`)]},o.info({original:f,keyParams:g},"Module cache key params");let T=Date.now();for(;Date.now()-T<Hj;){u?.throwIfAborted();let A=await i.getCacheResult(g);if(A){o.info({cacheResult:sn(A,1e3,true)},"Got result from module execution cache"),p=qR(t,n,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(A),m=true;break}else o.info({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let C=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${hostname()};runId:${d}`},u);if(C.acquired){h=C.keyPrefix,o.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else o.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Ye(2500+Math.random()*1e4,u);}}try{if(!p)p=await t_e(e);else if(t.autoAuth){let f=pA.safeParse(p.data);if(!f.success)throw new Y("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);o.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let b=!1,T=t.advanced?.cacheInvalidation;if(T&&T.type==="PAGE_CHECK"){let A={type:"CONTENT",value:T.substring},C=await WR({timeout:ss,assertion:A,browser:l,logger:o,signal:u,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});C.success?o.debug({invalResult:C},"Cached result still valid after page check, continuing..."):(o.info({invalResult:C},"Invalidating cached result due to page check failure"),b=!0);}if(g&&b)return await i.deleteCacheResult(g),JL(e)}}finally{try{h!==void 0&&!m&&p?.status==="SUCCESS"&&await n_e({step:t,result:p,browser:a.browser,cacheKeyPrefix:h,logger:o,storage:i});}finally{h!==void 0&&await i.releaseCacheLock(h);}}return p},t_e=async e=>{let{currentParentIdChain:t}=e,{step:n,tracer:o}=e.moduleParams,r=qR(n,e.moduleParams.resolvedInputs,"SUCCESS"),i=await o.startSubSteps(),{status:s,results:a}=await e.executeStepList({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:i,currentParentIdChain:t}});return r.results=a,r.status=s,r.finishedAt=new Date,ws({asyncTasks:e.work.asyncTasks,nestedResults:a,result:r,logger:e.fixtures.logger}),r};function qR(e,t,n){let o={};return Object.entries(t).forEach(([i,s])=>{o[i]=JSON.stringify(s);}),{type:"MODULE",id:e.id,moduleId:e.moduleId,moduleName:e.name,startedAt:new Date,cacheConfig:e.cacheConfig,inputs:o,results:[],finishedAt:new Date,status:n}}async function q4({orgId:e,step:t,context:n,logger:o,codeEvalTools:r,signal:i}){let s={};try{for(let a of t.parameters??[]){let l=t.inputs?.[a]??t.defaultParameters?.[a];if(!l){o.warn(`No value or default found for parameter '${a}' that is required by module '${t.name}'`);continue}s[a]=await Ud({orgId:e,code:l,fragment:!0,context:n,logger:o,localTools:r,signal:i});}return s}catch(a){throw i?.throwIfAborted(),new Y("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function n_e({step:e,result:t,browser:n,cacheKeyPrefix:o,logger:r,storage:i}){let s=e.cacheConfig?.cacheExpiryMs;(!s||s===Yz)&&(s=e.defaultCacheTtl??Jz);let a;e.autoAuth?a=JSON.stringify(await n.saveAuthState()):t.data!==void 0?a=JSON.stringify(t.data):a='""',r.debug({cacheKeyPrefix:o,ttlMs:s,truncatedCacheResultJson:Gi({json:a,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:o,ttlMs:s});}async function gp(e,t,n){return o_e(e,t,n)}async function o_e(e,t,n){let o=new Date;try{return n.throwIfAborted(),await t()}catch(r){let i=new Date,s="FAILED",a;if(n.aborted||r instanceof DOMException&&r.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):r instanceof Y?a=`${r}`:a=`An unexpected error occurred: ${r.message}`,e.type==="RESOLVED_MODULE"){let l=qR(e,{},"FAILED");return l.message=a,l.startedAt=o,l.finishedAt=i,l}return {...iC(e),startedAt:o,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function bi(e,t){let n=false;try{return e&&!e.state.failureRecoveryDisabled&&(e.state.failureRecoveryDisabled=!0,n=!0),await t()}finally{e&&n&&(e.state.failureRecoveryDisabled=void 0);}}var KR=20;function j({text:e,section:t}){if(!t)return [{type:"text",text:e}];let n=`### ${t}`;return e.length===0?[{type:"text",text:n}]:[{type:"text",text:`${n}
5751
5751
  ${e}`}]}function ei({base64Data:e,mediaType:t,section:n}){return n?[{type:"text",text:`### ${n}`},{type:"media",data:e,mediaType:t}]:[{type:"media",data:e,mediaType:t}]}function re(e){if(e.length===0)throw new dt("No content parts provided to construct the tool response content.");return {type:"content",value:e}}function ya(e){return {type:"content",value:[{type:"text",text:e}]}}function K4(e,t=2e4){let n={};for(let[o,r]of Object.entries(e)){if(typeof r=="object"&&r!==null){let i=JSON.stringify(r,null,2);if(nt(i)>t){n[o]="[too large truncated]";continue}n[o]=r;continue}n[o]=r;}return n}function Y4(e,t){let n={},o=0,r=Object.entries(e).map(([i,s])=>{let a=JSON.stringify(s,null,2),l=nt(a);return {key:i,value:s,tokens:l}}).sort((i,s)=>i.tokens-s.tokens);for(let{key:i,value:s,tokens:a}of r)o+a<=t&&(n[i]=s,o+=a);return n}function J4({projectRoot:e,filePath:t,pathLabel:n="path"}){if(!t||!En__default.isAbsolute(t))return t;let o=En__default.relative(e,t);if(o.startsWith("..")||En__default.isAbsolute(o))throw new Error(`Error: ${n} "${t}" must be inside project root "${e}".`);return o}function Q4(e){return e.map(t=>{switch(t.type){case "text":return t;case "media":return {type:"image",data:t.data,mimeType:t.mediaType};default:return (o=>{throw new Error("Unhandled content part")})()}})}var Z4=["__generated__"],e5=[".env",".npmrc",".netrc",".git-credentials","credentials","credentials.json"],t5=[".env.","id_rsa","id_ecdsa","id_ed25519","service-account"],n5=[".pem",".key",".p12",".pfx",".keystore",".jks",".tfstate"],o5=[".tfstate."],YR=[...e5.map(e=>`**/${e}`),...t5.map(e=>`**/${e}*`),...n5.map(e=>`**/*${e}`),...o5.map(e=>`**/*${e}*`)];function X4(e){let t=En__default.basename(e).toLowerCase();return e5.includes(t)||t5.some(n=>t.startsWith(n))||n5.some(n=>t.endsWith(n))||o5.some(n=>t.includes(n))}function CS(e,t){return En__default.resolve(En__default.resolve(e),t)}async function r5(e,t){let n=CS(e,t);if(X4(n))throw new Error(`Path '${t}' matches the sensitive-file deny list (likely credentials or secrets) and cannot be read.`);let o=await ek.realpath(n);if(X4(o))throw new Error(`Path '${t}' matches the sensitive-file deny list (likely credentials or secrets) and cannot be read.`);return o}var s_e=z.object({pattern:z.string().min(1).describe("Glob pattern to match against file paths (relative to the search root). Patterns are NOT recursive by default \u2014 `*` matches a single path segment, the same way shell globs do. Prefix with `**/` for recursive globs (e.g. `**/*.ts` to find all TypeScript files, `**/open-app*` to find any file whose basename starts with `open-app`)."),path:z.string().optional().describe("Optional repo-relative directory to start the search in. Defaults to the working directory root."),maxResults:z.int().min(1).max(1e3).default(100).describe("Maximum number of paths to return. Defaults to 100.")}),a_e="Find files by glob pattern. Skips common build/dependency/IDE directories (package manager folders, .git, dist, build, .next, __generated__, etc.) by default. Returns one repo-relative path per line.";function QR(e){return {tool:tool({description:a_e,inputSchema:s_e,execute:async n=>{let o=await l_e(n,e);return re(j({text:c_e(n.pattern,o)}))},toModelOutput:({output:n})=>n}),name:Ga}}async function l_e({pattern:e,path:t,maxResults:n},o){let r=En__default.resolve(o.repoRoot),i=t?CS(r,t):r;return (await gc([e],{cwd:i,ignore:[...Z4.map(a=>`**/${a}`),...YR],maxDepth:1/0,nodir:true,signal:AbortSignal.timeout(3e4)})).slice(0,n).map(a=>En__default.relative(r,En__default.resolve(i,a)))}function c_e(e,t){return t.length===0?!e.includes("**/")&&!e.startsWith("**")?`(no matching files. Tip: '${e}' only matches at the top of the search root \u2014 prepend '**/' for a recursive match, e.g. '**/${e}'.)`:"(no matching files)":t.join(`
5752
5752
  `)}function XR({lines:e,startLine:t,maxLines:n,maxBytes:o,truncateLineChars:r}){let i=e.length,s=Math.max(1,t);if(s>i)return {content:"",endLine:s-1,droppedLines:0,droppedBytesFromByteCap:0};let a=Math.min(i,s-1+n),l=e.slice(s-1,a).map(g=>r?i5(g,300):g),c=l.join(`
@@ -7428,7 +7428,7 @@ with this test we are editing:
7428
7428
  to pick which of these modules are relevant:
7429
7429
 
7430
7430
  `;let p=vFe(c);u+=p;let m=streamObject({schema:vD,model:d("claude-sonnet-4-5-20250929"),system:RFe,messages:[{role:"user",content:u}],providerOptions:{anthropic:vl}}),h=[];for await(let A of m.textStream)h.push(A);let g=h.join(""),f;try{let A=JSON.parse(g);f=vD.parse(A);}catch(A){r.error({rawResponse:g,parseError:A},"Failed to parse AI response as JSON"),n.addError(`Failed to parse AI response: ${Q(A)}. Raw response: ${g}`);return}let b=new Set(c.map(A=>A.moduleId)),T=f.recommendations.filter(A=>b.has(A.moduleId)?!0:(r.warn({moduleId:A.moduleId,moduleName:A.moduleName},"AI recommended a module that doesn't exist"),!1));n.addPartFromText(JSON.stringify({recommendations:T,totalModulesAnalyzed:c.length},null,2));}catch(c){r.error({err:c},"Error in module recommendation"),n.addError(`Failed to recommend modules: ${Q(c)}`);}}}),vw=[IFe,EFe];var xFe=1e5,z9=Lo({schema:{name:xx,description:"Get the current browser state for a granular session. Defaults: screenshot on, browser snapshot off. The browser snapshot includes the URL, accessibility tree, and other context. Ask for it (returnBrowserState: true) when you need it for locator resolution or richer page structure\u2014e.g. when screenshot-only output is insufficient. For large pages, pass `hint` to AI-filter the snapshot down to the relevant sections.",inputSchema:{sessionId:z.string().describe("The session id to query."),returnBrowserState:z.boolean().default(false).describe("Include the serialized browser snapshot. Default false. Set to true when you need the browser snapshot for element targeting or page structure."),returnScreenshot:z.boolean().default(true).describe("Include a screenshot. Default true. Set to false if you already have a screenshot of the present state and don't need a new one. EX: you just previewed a step and see that the page is too complicated and need the browser snapshot."),hint:z.string().optional().describe("Short natural-language description of what you need from the page (e.g. the action you are about to take or the element you are looking for). Required when returnBrowserState=true and the page is large: the hint is fed into an AI page-filtering step that returns only the most relevant sections of the accessibility tree, keeping the snapshot under the per-tool token budget.")}},handle:async(e,t,n)=>{let o=iu({response:n,sessionId:t.sessionId,toolName:xx});if(!o)return;o.controller.setOpen();let r=await AD({browser:o.controller.browser,supportsFileOutput:e.supportsFileOutput,returnBrowserState:t.returnBrowserState,returnScreenshot:t.returnScreenshot,tokenLimit:xFe,hint:t.hint,filtering:{generator:e.generator,orgId:e.orgId,logger:e.logger,signal:o.controller.executeAbortController.signal}});n.addContentParts(r);}}),W9=Lo({schema:{name:_x,description:"Get the current environment variables for a session.",inputSchema:{sessionId:z.string()}},handle:async(e,t,n)=>{let o=iu({response:n,sessionId:t.sessionId,toolName:_x});if(!o)return;let r=await Ns({testContext:o.context,supportsFileOutput:e.supportsFileOutput});n.addContentParts(r);}});var q9=Lo({schema:{name:Su,description:`Start a granular browser session for a specific test. Requires a testId. Returns session metadata (sessionId, testId, testFileAbsolutePath, projectConfigAbsolutePath, cwd, viewport, etc.), a Step Authoring Guide artifact that includes projectRootAbsolutePath, projectConfigAbsolutePath, and cwd, and a Test Content section that lists every step in the bound test with its stable stepId context. ${kS} Read the Step Authoring Guide artifact before creating, previewing, running, or splicing CLI-style steps. Use the Test Content section for the step ids required by tools that operate on existing steps in this session's test. After editing with splice, prefer the splice response or request returnTest for the updated active-session step ids. Use ${zs} to inspect persisted test state by id or path, especially for a different test.`,inputSchema:{testId:z.string().describe("The test id to target when starting a session."),envName:z.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:z.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:z.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:z.boolean().optional().describe("Whether to launch a headful browser for the session. When omitted, uses the MCP server default if configured."),video:z.boolean().optional().describe("Whether to record a video of the browser session. When omitted, uses the MCP server default if configured. When the session is terminated, the response will include the path to the video output directory.")}},handle:async(e,t,n)=>{let{logger:o}=e,r=t.video??e.videoDefault??false,i;r&&(Qi(e.project.rootDir),i=Xi({rootDir:e.project.rootDir,entity:"video",ext:"d"}),mkdirSync(i,{recursive:true}));let s;try{let l=go();if(!l){n.addError("API client is not initialized; cannot start MCP session.");return}let c=await aa({project:await an({configFilePath:t.projectConfigPath??e.project.configFilePath,nameFilter:t.projectNameFilter,skipExitOnError:!0}),apiClient:l}),d=new ns(l,e.orgId,c);s=await ts.startSession({logger:o,storage:d,testId:t.testId,idleTimeoutMs:e.sessionIdleTimeoutMs,envName:t.envName,headfulOverride:t.headfulBrowser??e.headfulDefault??!0,customHeaders:e.customHeaders,devicePixelRatio:e.devicePixelRatio,videoOutputDir:i});}catch(l){n.addError(Q(l));return}es({type:"mcp:session_started",test_platform:"web"});let a=s.controller.browser.getViewport();n.addPartFromText(JSON.stringify({sessionId:s.sessionId,testId:s.testId,testFileAbsolutePath:s.testFileAbsolutePath,projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:process.cwd(),createdAt:s.createdAt,expiresAt:s.lastAccessedAt+s.idleTimeoutMs,idleTimeoutMinutes:s.idleTimeoutMs/(60*1e3),envName:s.envName,baseUrl:s.baseUrl,viewport:a},null,2)),n.addContentParts(await bZ({projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:process.cwd(),stepSchema:Ms(),stepSchemaTitle:"Step schema",supportsFileOutput:e.supportsFileOutput}));try{let l=await ou({project:s.storage.getProject(),storage:s.storage,selector:{id:s.testId},envName:s.envName,logger:o,mutableStepState:s.mutableStepState,includeCache:!1,hydrateStepIdentity:!0,supportsFileOutput:e.supportsFileOutput});n.addContentParts(l);}catch(l){o.warn({sessionId:s.sessionId,err:l},"Session started but resolved test content could not be loaded");}try{n.addContentParts(await _r({browser:s.controller.browser,supportsFileOutput:e.supportsFileOutput}));}catch(l){o.warn({sessionId:s.sessionId,err:l},"Session started but initial screenshot capture failed"),n.addPartFromText(JSON.stringify({warning:"Session started successfully, but initial screenshot capture failed.",screenshotError:Q(l)},null,2));}i&&n.addContentParts(j({text:Yo({filePath:i,title:"Video output directory"}),section:"Video Output"}));}}),K9=Lo({schema:{name:Q0,description:"Kill a granular browser session by sessionId. Returns available session ids if the target is missing.",inputSchema:{sessionId:z.string().describe("The session id to terminate.")}},handle:async(e,t,n)=>{let{sessionId:o}=t;try{let r=ts.getSession(o),i=r?.videoOutputDir,s=await ts.killSession(t.sessionId,"explicit kill");if(s.killed&&es({type:"mcp:session_killed",test_platform:"web",reason:"explicit kill"}),!s.killed){r?n.addError(`Failed to terminate session '${t.sessionId}'.`):n.addError(JSON.stringify({message:`No active session found for id '${t.sessionId}'.`,availableSessionIds:ts.listSessionIds()},null,2));return}n.addPartFromText(JSON.stringify({sessionId:t.sessionId,killed:!0},null,2));let a=await TZ({killResult:s,rootDir:e.project.rootDir});a&&n.addContentParts(j({text:Yo({filePath:a.filePath,title:"Session span report"}),section:"Session Spans"})),i&&n.addContentParts(j({text:Yo({filePath:i,title:"Video output directory"}),section:"Video Output"}));}catch(r){n.addError(Q(r));}}});var yg=async({step:e,controller:t,executionOptions:n,storage:o,codeEvalTools:r,logger:i,socket:s,testContext:a,orgId:l,sessionId:c,usageTracker:d,apiClient:u})=>{let{results:p}=await wD({steps:[e],controller:t,executionOptions:n,storage:o,codeEvalTools:r,logger:i,socket:s,testContext:a,orgId:l,sessionId:c,usageTracker:d,apiClient:u});return p[0]},wD=async({steps:e,fromStep:t,toStep:n,tracer:o,controller:r,executionOptions:i,storage:s,codeEvalTools:a,logger:l,socket:c,testContext:d,orgId:u,sessionId:p,usageTracker:m,apiClient:h})=>{let g={controller:r,storage:s,codeEvalTools:a,logger:l,context:d,usageTracker:m},f=o??(c?new Nc({orgId:u,parentStep:null,parentTracer:null,socket:c}):new sy);r.setOpen();let b={results:[],asyncTasks:[],state:{autoHealingDisabled:true,failureRecoveryDisabled:true,failureRecoveryAttempts:0},...t&&{fastForwardingToStep:true}},T=()=>Os({listParams:{containerName:"agent-step-list",steps:e,tracer:f},fixtures:g,options:{collectDebugData:false,reinitializeBrowser:false,disableHealing:true},inputs:{orgId:u,userId:nQ(),runId:randomUUID(),sessionId:p,steps:e,testMetadata:null,orgSettings:{},fromStep:t,toStep:n},callbacks:{test:{},step:{}},runParams:h?{apiClient:h}:null,work:b});return i?r.withExecutionOptions(i,T):T()};async function ww({step:e,project:t,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,tempCaches:u,usageTracker:p,apiClient:m}){let h=await Lv(e,{project:t,logger:n,tempCaches:u});switch(h.type){case "PRESET_ACTION":return NFe({step:h,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,tempCaches:u,usageTracker:p,apiClient:m});case "AI_ACTION_DYNAMIC":return LFe({step:h,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,usageTracker:p,apiClient:m});case "RESOLVED_MODULE":return kFe({step:h,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,usageTracker:p,apiClient:m});default:{let[g,f]=await Promise.all([_r({browser:r.browser,supportsFileOutput:d}),Ns({testContext:c,supportsFileOutput:d})]);return [...j({text:`Preview for step type ${h.type} is not supported. Only PRESET_ACTION, RESOLVED_MODULE, and AI_ACTION_DYNAMIC are supported.`,section:"Error"}),...g,...f]}}}async function NFe({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,tempCaches:d,usageTracker:u,apiClient:p}){let m=await yg({step:e,logger:t,storage:n,controller:o,executionOptions:{skipAISmartWaiting:true},codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,usageTracker:u,apiClient:p}),h=[];m?m.status==="SUCCESS"?(DFe({logger:t,tempCaches:d,command:e.command,parts:h}),h.push(...j({text:`Step Execution successful: ${m.message}`,section:"Successful Result"}))):h.push(...j({text:`Step Execution failed: ${m.message}`,section:"Error"})):h.push(...j({text:"Step Execution errored for an unknown reason.",section:"Error"}));let[g,f]=await Promise.all([_r({browser:o.browser,supportsFileOutput:c}),Ns({testContext:l,supportsFileOutput:c})]);return h.push(...g,...f),h}async function LFe({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,usageTracker:d,apiClient:u}){let p=await yg({step:e,logger:t,storage:n,controller:o,executionOptions:{skipAISmartWaiting:true},codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,usageTracker:d,apiClient:u}),m=[];p?p.status==="SUCCESS"?m.push(...j({text:`AI action completed successfully: ${p.message??"Goal achieved"}`,section:"Successful Result"})):m.push(...j({text:`AI action failed: ${p.message??"Unknown error while previewing AI action"}`,section:"Error"})):m.push(...j({text:"AI action executed with unknown result.",section:"Error"}));let[h,g]=await Promise.all([_r({browser:o.browser,supportsFileOutput:c}),Ns({testContext:l,supportsFileOutput:c})]);return m.push(...h,...g),m}async function kFe({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,usageTracker:d,apiClient:u}){let p=await yg({step:e,logger:t,storage:n,controller:o,executionOptions:{skipAISmartWaiting:true},codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,usageTracker:d,apiClient:u}),m=[];p?p.status==="SUCCESS"?m.push(...j({text:`Module executed successfully: ${p.message}`,section:"Successful Result"})):m.push(...j({text:`Module execution failed: ${p.message}`,section:"Error"})):m.push(...j({text:"Module execution errored for an unknown reason.",section:"Error"}));let[h,g]=await Promise.all([_r({browser:o.browser,supportsFileOutput:c}),Ns({testContext:l,supportsFileOutput:c})]);return m.push(...h,...g),m}function DFe({logger:e,tempCaches:t,command:n,parts:o}){if(t&&Xo(n)&&n.cache)try{let r=randomUUID();t[r]=Da.parse(cloneDeep({type:n.type,cache:n.cache})),o.push(...j({text:r,section:"CacheId"}));}catch(r){e.warn({err:r},"Failed to save temp cache for step. Continuing...");}}var Y9=({steps:e,fromStep:t,toStep:n})=>{let o={total:0,fastForwardingToStep:true},r=(i,s)=>{if(i.skipped)return false;let a=s.map(c=>c.id),l=qS(i.id,a,t.fromStepId,t.parentStepIdChain);if(o.fastForwardingToStep){if(!l)return false;o.fastForwardingToStep=false;}return o.total+=1,!!(n&&qS(i.id,a,n.toStepId,n.parentStepIdChain))};return pi({steps:e,earlyStop:true,onPresetAction:(i,s)=>r(i,s.parentChain),onConditional:(i,s)=>{if(i.skipped)return false;let a=s.parentChain.map(c=>c.id),l=qS(i.id,a,t.fromStepId,t.parentStepIdChain);if(o.fastForwardingToStep){if(!l)return false;o.fastForwardingToStep=false;}return !!(n&&qS(i.id,a,n.toStepId,n.parentStepIdChain))},onSimpleStepContainer:(i,s)=>r(i,s.parentChain)}),o.total};var BFe="Cannot add a module step inside another module. Modules cannot be nested.";function ID(e,t){switch(t){case "setup":return e.beforeSteps??[];case "teardown":return e.afterSteps??[];case "main":return e.steps;default:{throw new Error("Unknown test section")}}}function UFe(e,t,n){let o=ID(e,t);if(!n?.length)return o;let r=H2(o,n);if(!r)throw new Error(`No step found with parent chain [${n.join(", ")}] in ${t} section, or parent does not support nested steps`);return r}function J9(e,t){let n=t.moduleId,o=r=>{r.type!=="RESOLVED_MODULE"||r.moduleId!==n||(t.parameters!==void 0&&(r.parameters=t.parameters),t.parameterEnums!==void 0&&(r.parameterEnums=t.parameterEnums),t.defaultParameters!==void 0&&(r.defaultParameters=t.defaultParameters),t.name!==void 0&&(r.name=t.name),t.description!==void 0&&(r.description=t.description),t.enabled!==void 0&&(r.enabled=t.enabled),t.steps!==void 0&&(r.steps=t.steps));};for(let r of [e.steps,e.beforeSteps,e.afterSteps])pi({steps:r,onPresetAction:o,onConditional:o,onSimpleStepContainer:o});}async function Iw({project:e,storage:t,orgId:n,logger:o,testPath:r,saveChangesToDisk:i,supportsFileOutput:s,tempCaches:a,mutableStepState:l,params:c,envName:d}){let u=En__default.join(e.rootDir,r),p=await t.getTestByPath({relativeTestPath:r,logger:o}),m=l?.stepLists??p,h=cloneDeep({steps:m.steps??[],beforeSteps:m.beforeSteps??[],afterSteps:m.afterSteps??[]}),g=cloneDeep(h),f=await Promise.all(c.steps.map(E=>Lv(E,{project:e,logger:o,tempCaches:a}))),b=cloneDeep(f),T=c.parentStepIdChain,A;try{A=UFe(g,c.targetSection,T);}catch(E){return re(j({text:`Error: ${Q(E)}`,section:"Error"}))}if(c.startIndex<0||c.startIndex>A.length)return re(j({text:`Error: Invalid startIndex ${c.startIndex} for splicing ${c.targetSection} section with ${A.length} steps (must be 0-${A.length})`,section:"Error"}));let C=f.length,v=c.deleteCount,I=cloneDeep(A.slice(c.startIndex,c.startIndex+v)),_=[];if(T?.length){let E=G2(ID(g,c.targetSection),T,c.targetSection);if(_.push(...E),E.some(N=>N.type==="RESOLVED_MODULE")&&f.some(N=>N.type==="RESOLVED_MODULE"))return re(j({text:`Error: ${BFe}`,section:"Error"}))}A.splice(c.startIndex,c.deleteCount,...f);for(let E of f)E.type==="RESOLVED_MODULE"&&J9(g,E);for(let E of _)E.type==="RESOLVED_MODULE"&&J9(g,E);if(l&&(l.stepLists=g),o.info({testPath:r,testFilePath:u,saveChangesToDisk:i,projectFileFormat:e.config.fileFormat,targetSection:c.targetSection,parentStepIdChain:T??[],insertedCount:C,deletedCount:v},"MCP splice persistence decision"),i){let E=await t.updateTestByPath({logger:o,relativeTestPath:r,stepLists:g,schemaVersion:at});o.info({testPath:r,testFilePath:u,projectFileFormat:e.config.fileFormat,moduleUpdateCount:E.moduleUpdates.length,snapshotCacheCount:E.snapshotCachesToSave.length},"MCP splice persisted test changes to disk");}else o.info({testPath:r,testFilePath:u,projectFileFormat:e.config.fileFormat},"MCP splice skipped disk persistence");let x=[...j({text:`Successfully spliced ${C} step(s) at index ${c.startIndex} in the ${c.targetSection} section, removing ${v} step(s).`,section:"Result"})];return x.push(...await HFe({logger:o,project:e,orgId:n,testId:p.id,environment:d,originalSteps:h,updatedSteps:g})),x.push(...await r8({rootDir:e.rootDir,supportsFileOutput:s,deletedStepRefs:I.map((E,O)=>({id:E.id,index:c.startIndex+O})),insertedStepRefs:b.map((E,O)=>({id:E.id,index:c.startIndex+O})),deletedSteps:Cd(I,{includeCache:false}),insertedSteps:Cd(b,{includeCache:false}),metadata:{section:c.targetSection,parentStepIdChain:T??[],startIndex:c.startIndex,deleteCount:v,insertedCount:C},artifactEntity:"splice-restoration-payload"})),c.returnTest&&x.push(...j({text:JSON.stringify(await Tw({project:e,storage:t,selector:{path:r},envName:d,logger:o,mutableStepState:l,supportsFileOutput:s,hydrateStepIdentity:false}),null,2),section:"Test Content"})),re(x)}async function xw({project:e,logger:t,testPath:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,envName:c,testContext:d,tracer:u,params:p,tokenLimit:m,supportsFileOutput:h,usageTracker:g,mutableStepState:f,apiClient:b}){let{fromStep:T,toStep:A,targetSection:C}=p,v=await o.getTestByPath({relativeTestPath:n,logger:t}),{alwaysSaveCache:I,noCache:_}=Cc(),x=await Ei({logger:t,orgId:a,project:e,alwaysSaveCache:I,noCache:_}),E=f?.stepLists??{beforeSteps:v.beforeSteps??[],afterSteps:v.afterSteps??[],steps:v.steps};await x.resolveStepCacheEntries({logger:t,schemaVersion:v.schemaVersion,stepLists:E,testId:v.id,environment:c,useSnapshotIdentityCache:!f&&e.config.fileFormat==="v2"}),f&&(f.stepLists=E);let O=ID(E,C),N=cloneDeep({steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps}),{result:H}=Gu(O,T.fromStepId,T.parentStepIdChain);if(!H)return re(j({text:`Error: No step found with id "${T.fromStepId}" and parent chain [${T.parentStepIdChain.join(", ")}] in ${C} section.`,section:"Error"}));if(A){let{result:De}=Gu(O,A.toStepId,A.parentStepIdChain);if(!De)return re(j({text:`Error: No step found with id "${A.toStepId}" and parent chain [${A.parentStepIdChain.join(", ")}] in ${C} section.`,section:"Error"}))}if(u?.setProgressTotal){let De=Y9({steps:O,fromStep:T,toStep:A});u.setProgressTotal(De);}r.setOpen();let U;try{U=await wD({steps:O,controller:r,storage:o,codeEvalTools:i,logger:t,socket:s,orgId:a,sessionId:l,testContext:d,fromStep:T,toStep:A,tracer:u,usageTracker:g,apiClient:b});}finally{await g.flush(t);}let{results:$}=U;if(!$||$.length===0)return re(j({text:"Error: No steps were executed.",section:"Error"}));let oe=$.at(-1);if(!oe)return re(j({text:"Error: No steps were executed.",section:"Error"}));let X={logger:t,cacheStorage:x,orgId:a,testId:v.id,environment:c,originalStepsWithCaches:N,updatedStepsWithCaches:{steps:E.steps,beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[]}},z=oe.status!=="SUCCESS";await $u({logger:t,cacheStorage:x,orgId:a,testId:v.id,environment:c,stepLists:X.updatedStepsWithCaches,useSnapshotIdentityCache:e.config.fileFormat==="v2"}),z?oe.status==="FAILED"&&await uh(X):await Vu(X);let K=C==="main"?"":` in ${C}`,q=De=>{let Oe="fromStepId"in De?De.fromStepId:De.toStepId;return De.parentStepIdChain.length>0?`id "${Oe}" (parent chain [${De.parentStepIdChain.join(", ")}])`:`id "${Oe}"`},J=T?q(T):"beginning",te=A?`Steps from ${J} through ${q(A)}${K}`:`Steps from ${J} to end${K}`,B=[];if(z)B.push(...j({text:`Error: step with id ${oe.id} failed: ${oe.message}`,section:"Error"}));else {r.setOpen();let De=`${te} executed successfully.`;B.push(...j({text:De,section:"Result"})),oe.data&&B.push(...j({text:`Data: ${JSON.stringify(oe.data,null,2)}`,section:"Result Data"}));}let[le,be]=await Promise.all([_r({browser:r.browser,supportsFileOutput:h}),Ns({testContext:d,supportsFileOutput:h,limits:{tokenLimit:m}})]);return re([...B,...le,...be])}async function HFe({logger:e,project:t,orgId:n,testId:o,environment:r,originalSteps:i,updatedSteps:s}){let a=[];try{let{alwaysSaveCache:l,noCache:c}=Cc(),d=await Ei({logger:e,orgId:n,project:t,alwaysSaveCache:l,noCache:c});await $u({logger:e,cacheStorage:d,orgId:n,testId:o,environment:r,stepLists:s,useSnapshotIdentityCache:t.config.fileFormat==="v2"}),await Vu({logger:e,cacheStorage:d,orgId:n,testId:o,environment:r,originalStepsWithCaches:i,updatedStepsWithCaches:s});}catch(l){e.warn({err:l},"Failed to save step caches after execution, future runs may be slower"),a.push(...j({text:"Warning: Steps were saved successfully, but updating the step cache failed. Future runs may be slower until the cache is refreshed.",section:"Warning"}));}return a}var xD=class{constructor(t,n,o,r){this.reporter=t;this.step=n;this.parentStepIdChain=o;this.setTotal=r;}loggerBindings;attachBeforeScreenshot(t){}attachAfterScreenshot(t){}attachBeforeHtmlSnapshot(t){}attachAfterHtmlSnapshot(t){}recordTargetAutoHeal(t){}storeTraceAsset(){}async finish(t){this.reporter.onStepComplete(this.step);}async startSubSteps(){return new _w(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},_w=class{constructor(t,n=[],o){this.reporter=t;this.parentStepIdChain=n;this.setTotal=o;}loggerBindings;setProgressTotal(t){this.setTotal(t);}async getScreenshot(t,n){}async getHtmlSnapshot(t,n){}flushResults(t){}async startStep(t,n){return this.reporter.onStepStart(t.step),new xD(this.reporter,t.step,this.parentStepIdChain,this.setTotal)}};function Q9(e,t,n,o){let r=WS(e),i={completed:0,total:0},s=new AbortController,a=false,l=p=>{r&&$6(e,i,p,t,s,n);},c=()=>{r&&(a||(a=true,l("Starting step execution...")));},d=p=>{!Number.isFinite(p)||p<0||(i.total=p);},u={onStepStart:p=>{c(),i.total===i.completed&&(i.total+=1),l(`Starting: ${In(p)}`);},onStepComplete:p=>{o(),c(),i.completed+=1,i.total<i.completed&&(i.total=i.completed),l(`Completed: ${In(p)}`);}};return new _w(u,[],d)}var Z9=`CLI-style step definition. Use the Step Authoring Guide artifact returned from ${Su} when you start your session to get the full step schema.`,GFe=Lo({schema:{name:J0,description:"Create a test. The name must satisfy Momentic entity naming rules, and you must provide either a baseUrl or environment or the tool will fail.",inputSchema:eP},handle:async(e,t,n,o)=>{try{let r=await e.storage.createTest(t);es({type:"mcp:test_create",test_platform:"web"}),n.addPartFromText(JSON.stringify(r,null,2));}catch(r){n.addError(Q(r));return}}}),jFe=Lo({schema:{name:zs,description:`Fetch a loaded test by id or path, including resolved module steps and stable stepId and parentStepIdChain values for the persisted test state. Use this to inspect a test before starting a session or to inspect a different test. For the active session after ${pf}, prefer the splice response or request returnTest on the splice call for updated step ids. Step ids from another test are inspection-only for the active session. Start a session for that test before running or editing it.`,inputSchema:{testId:z.string().optional().describe(`Id of the test to fetch. If you do not already know it, list project tests with ${Ix}. Either testId or testPath is required.`),testPath:z.string().optional().describe("Path to the test file, relative to the project root or absolute. When provided, skips the entity-registry lookup. Either testId or testPath is required.")}},handle:async(e,t,n,o)=>{try{let r=t.testId?{id:t.testId}:t.testPath?{path:t.testPath}:void 0;if(!r){n.addError("Either testId or testPath is required.");return}let i=await ou({project:e.project,storage:e.storage,selector:r,envName:void 0,logger:e.logger,includeCache:!1,hydrateStepIdentity:!0,supportsFileOutput:e.supportsFileOutput});n.addContentParts(i);}catch(r){n.addError(Q(r));return}}}),X9=Lo({schema:{name:vT,description:`Reload the active session's test from disk into mutable in-memory step state. Use this after manually editing a v2 YAML test/module on disk and running lint, before ${wT}. Returns updated Test Content with step ids for the active session.`,inputSchema:{sessionId:z.string().describe("The active session whose bound test should be reloaded.")}},handle:async(e,t,n,o)=>{let r=iu({response:n,sessionId:t.sessionId,toolName:vT});if(!r)return;let i=r.storage.getProject();if(i.config.fileFormat!=="v2"){n.addError(`${vT} is only available for v2 file-format projects.`);return}let s=await r.storage.getTestByPath({relativeTestPath:r.relativeTestPath,logger:e.logger}),a={beforeSteps:s.beforeSteps,steps:s.steps,afterSteps:s.afterSteps},{alwaysSaveCache:l,noCache:c}=Cc(),d=await Ei({logger:e.logger,orgId:r.orgId,project:i,alwaysSaveCache:l,noCache:c});r.mutableStepState.testId=s.id,r.mutableStepState.stepLists=await bd({cacheStorage:d,logger:e.logger,schemaVersion:s.schemaVersion,stepLists:a,testId:s.id,environment:r.envName,useSnapshotIdentityCache:true}),n.addContentParts(j({text:`Reloaded test ${s.id} from disk into session ${r.sessionId}.`,section:"Result"})),n.addContentParts(await ou({project:i,storage:r.storage,selector:{path:r.relativeTestPath},envName:r.envName,logger:e.logger,mutableStepState:r.mutableStepState,includeCache:false,hydrateStepIdentity:false,supportsFileOutput:e.supportsFileOutput}));}}),$Fe={...X9,addToolToMcpServer:(e,t)=>{e.project.config.fileFormat==="v2"&&X9.addToolToMcpServer(e,t);}},VFe=Lo({schema:{name:Ix,description:`List local test artifacts. Returns a Project Context section with projectRootAbsolutePath, projectConfigAbsolutePath, and cwd, plus separate segments for each relevant artifact type: tests, modules, and environments. ${kS} When file output is enabled, the artifact links are relative to cwd. Read or grep only the specific artifact files you need instead of loading everything at once. Assume nothing changed since your last successful call to this tool unless the user indicates updates (e.g. new/changed tests, modules, environments, or project config change); avoid redundant calls just to refresh.`,inputSchema:{}},handle:async(e,t,n,o)=>{let{project:r,logger:i}=e,s=[],a=[];try{let[c,d]=await Promise.all([e.storage.listTests(),e.storage.listModules()]),u=c.map(m=>({id:m.id,name:m.name,description:m.description,testFileAbsolutePath:m.fullFilePath,labels:m.labels||[]}));s.push({title:"Tests",entity:"test-list",payload:{tests:u}});let p=d.map(m=>({id:m.id,name:m.name,description:m.description,fullFilePath:m.fullFilePath,type:m.type}));s.push({title:"Modules",entity:"module-list",payload:{modules:p}});}catch(c){a.push(`Tests and modules discovery failed: ${Q(c)}`);}try{let c=e.storage.listEnvironments(i);s.push({title:"Environments",entity:"environment-list",payload:{environments:c}});}catch(c){a.push(`Environments discovery failed: ${Q(c)}`);}let l=await AZ({artifacts:s,rootDir:r.rootDir,supportsFileOutput:e.supportsFileOutput,projectRootAbsolutePath:r.rootDir,projectConfigAbsolutePath:r.configFilePath,cwd:process.cwd()});n.addContentParts(l),a.length>0&&n.addContentParts(j({section:"Discovery Errors",text:a.map(c=>`- ${c}`).join(`
7431
- `)}));}}),e7=Lo({schema:{name:Px,description:"Execute a step without adding it to the test.",inputSchema:{sessionId:z.string(),step:z.string().describe(Z9)}},handle:async(e,t,n,o)=>{let{sessionId:r,step:i}=t,s=iu({response:n,sessionId:r,toolName:Px});if(!s)return;s.controller.setOpen();let a;try{a=await ww({project:s.storage.getProject(),step:i,logger:e.logger,storage:s.storage,controller:s.controller,codeEvalTools:s.codeEvalTools,orgId:s.orgId,sessionId:s.sessionId,testContext:s.context,supportsFileOutput:e.supportsFileOutput,tempCaches:s.tempCaches,usageTracker:s.usageTracker,apiClient:go()});}finally{await s.usageTracker.flush(e.logger);}n.addContentParts(a);}}),t7=Lo({schema:{name:pf,description:"Insert, delete, or replace steps in the active session's test by index. Use parentStepIdChain to splice into nested steps (e.g. inside a conditional or module). The response includes inserted/deleted step refs with the updated active-session ids; use those ids for later run_step calls. The response always includes a recovery artifact with the full deleted and inserted payloads; only inspect it when you need to undo or inspect a mistaken splice.",inputSchema:{sessionId:z.string(),startIndex:z.number(),deleteCount:z.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:z.array(z.string()).describe(Z9),targetSection:bu.default("main"),parentStepIdChain:z.array(z.string()).optional().describe("When splicing into a nested step (e.g. conditional or module), the chain of parent step ids from root to the container. Empty or omit for top-level."),returnTest:z.boolean().default(false).describe("Return the full post-splice test snapshot. Avoid this by default. Use true only when you truly need the full updated test; the normal response already includes inserted/deleted step references plus a recovery artifact for mistaken-splice recovery.")}},handle:async(e,t,n,o)=>{let r=iu({response:n,sessionId:t.sessionId,toolName:pf});if(!r)return;let i=await Iw({project:r.storage.getProject(),storage:r.storage,orgId:r.orgId,logger:e.logger,testPath:r.relativeTestPath,envName:r.envName,saveChangesToDisk:e.saveChangesToDisk,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,mutableStepState:r.mutableStepState,params:{startIndex:t.startIndex,deleteCount:t.deleteCount,steps:t.steps,targetSection:t.targetSection,parentStepIdChain:t.parentStepIdChain,returnTest:t.returnTest}});t.steps.length>0&&es({type:"mcp:step_added",test_platform:"web",step_count:t.steps.length});let s=i.value.map(a=>a.type==="media"?{type:"media",data:a.data,mediaType:"image/jpeg"}:a);n.addContentParts(s);}}),n7=Lo({schema:{name:wT,description:`${RT} Use step ids from the active session: the Test Content section returned by ${Su}, or the inserted/deleted refs returned by ${pf}. If you need a full updated post-splice view, set returnTest on the splice call. Do not parse the raw YAML at testFileAbsolutePath for step ids; v2 simplified test files do not store step ids on disk.`,inputSchema:{sessionId:z.string(),fromStep:UT,toStep:HT.optional(),targetSection:bu.default("main"),resetSession:z.boolean().default(false).describe("Whether to reset the browser session before running the steps.")}},handle:async(e,t,n,o)=>{let r=iu({response:n,sessionId:t.sessionId,toolName:wT});if(!r)return;r.controller.setOpen(),t.resetSession&&await Aw({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,apiKey:vs(),baseUrl:wr(),controller:r.controller,testContext:r.context,supportsFileOutput:e.supportsFileOutput});let i=Q9(o,e.logger,n,()=>{ts.touchSession(r.sessionId);}),s=await xw({project:r.storage.getProject(),logger:e.logger,testPath:r.relativeTestPath,storage:r.storage,controller:r.controller,codeEvalTools:r.codeEvalTools,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,tracer:i,params:{fromStep:t.fromStep,toStep:t.toStep,targetSection:t.targetSection},supportsFileOutput:e.supportsFileOutput,envName:r.envName,usageTracker:r.usageTracker,mutableStepState:r.mutableStepState,apiClient:go()});es({type:"mcp:run_step_completed",test_platform:"web",status:"completed"});let a=s.value.map(l=>l.type==="media"?{type:"media",data:l.data,mediaType:"image/jpeg"}:l);n.addContentParts(a);}}),o7=[VFe,GFe,jFe,$Fe];var r7=[z9,W9,q9,K9,e7,n7,t7];async function qFe({testPath:e,logger:t,project:n,storage:o,orgId:r,mutableStepState:i}){let s=await o.getTestByPath({relativeTestPath:e,logger:t}),a=s.envs?.find(u=>u.default)?.name;if(i&&i.testId!==s.id)throw new Error(`Cannot extract a module from test ${s.id} with mutable state for ${i.testId}.`);let l=i?.stepLists??{steps:s.steps,beforeSteps:s.beforeSteps??void 0,afterSteps:s.afterSteps??void 0},c=await Ei({logger:t,orgId:r,project:n}),d=await bd({cacheStorage:c,logger:t,schemaVersion:s.schemaVersion,stepLists:l,testId:s.id,environment:a,useSnapshotIdentityCache:n.config.fileFormat==="v2"});return {availableSteps:d.steps,baseState:{steps:d.steps,beforeSteps:d.beforeSteps??[],afterSteps:d.afterSteps??[]},cacheSaveContext:{testId:s.id,environment:a,stepCacheStorage:c}}}async function Pw({project:e,storage:t,logger:n,relativeTestPath:o,saveChangesToDisk:r,mutableStepState:i,params:s}){let a=Bn();Ha(s.name);let l=await t.scanEntities(),c;s.startIndex!==void 0&&o!==void 0&&(c=await qFe({testPath:o,logger:n,project:e,storage:t,orgId:a,mutableStepState:i}));let{stepsToExtract:d,startIndex:u,endIndex:p}=i8({moduleName:s.name,existingModuleNames:Object.values(l.modules).map(E=>E.name),...s,parameterNames:s.parameters,testPath:o,availableSteps:c?.availableSteps,containsNestedModuleStep:U2}),{module:m}=await t.createModule({name:s.name,description:s.description??"",enabled:s.enabled??true,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,steps:d,subDir:s.subDir,momenticFiles:l});if(s.startIndex===void 0)return {module:m};if(!o||!c)throw new Error("Failed to initialize extraction state for module create");let h=Object.keys(s.moduleInputs??{}).length>0,g=(m.parameters?.length??0)>0,f;h?f=s.moduleInputs:g?f={}:f=void 0;let b={...m,type:"RESOLVED_MODULE",id:randomUUID(),steps:m.steps,inputs:f},T=cloneDeep(c.baseState);T.steps.splice(u,p-u,b),i&&(i.stepLists=T);let{environment:A,stepCacheStorage:C,testId:v}=c.cacheSaveContext,I=e.config.fileFormat==="v2",{cachesToSave:_,snapshotCachesToSave:x}=await An({stepLists:T,useSnapshotIdentityCache:I,cacheCreationParams:{orgId:a,testId:v,environment:A}});return I&&await C.saveSnapshotCacheEntries({logger:n,entries:x}),await C.saveStepCacheEntries({logger:n,entries:_}),r&&await t.updateTestByPath({logger:n,relativeTestPath:o,stepLists:T,schemaVersion:at}),{module:m}}var i7=Lo({schema:{name:K0,description:"Create a module. The name must satisfy Momentic entity naming rules or the tool will fail. If startIndex is provided, testPath is required and the specified test range is extracted into the module, then replaced with a module invocation in that test. endIndex may only be provided when startIndex is set.",inputSchema:{name:z.string().describe(Zf),description:z.string(),enabled:z.boolean().default(true),parameters:z.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:z.record(z.string(),z.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:z.record(z.string(),z.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:z.record(z.string(),z.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant when extracting from a test."),subDir:z.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:z.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:z.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:z.number().optional().describe("End index of steps to extract from the target test (exclusive). Only valid when startIndex is provided. If not provided, extracts just startIndex.")}},handle:async(e,t,n,o)=>{let{testPath:r,...i}=t;try{let s=J4({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),a=await Pw({project:e.project,storage:e.storage,logger:e.logger,relativeTestPath:s,saveChangesToDisk:e.saveChangesToDisk,params:i});n.addPartFromText(JSON.stringify(a.module,null,2));}catch(s){n.addError(Q(s));}}});var Sg=[...o7,...vw,...r7,i7,FZ,WZ,QZ,HZ];var a7=Sg.map(e=>e.tool),s7=new Map(a7.map(e=>[e.schema.name,e]));async function l7(e){let{project:t,applicationName:n,daemonPort:o,daemonToken:r,daemonSessionId:i,logger:s,cliVersion:a}=e,l=t.configFilePath;await Ew(e);let{context:c}=Cw({...e,logger:s.child({daemonSessionId:i}),applicationName:`${n}-daemon`,serverId:i});await Q6({adapter:{getTool:d=>{let u=s7.get(d);if(!u)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(s7.keys()).join(", ")}`);return {name:u.schema.name,execute:async({input:p,extra:m})=>await K6({context:c,tool:u,input:p,extra:m})}}},sessionManager:ts,daemonPort:o,daemonToken:r,daemonId:i,cliVersion:a,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:RD(e)*2,onShutdown:()=>{fl();}});}async function c7({project:e,logger:t,apiKey:n,serverUrl:o,cliVersion:r,applicationName:i,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u}){Bd(o);let p=e.configFilePath,m=async()=>j6({workerType:"momentic-web-mcp",configPath:p,apiKey:n,serverUrl:o,cliVersion:r,logger:t,buildDaemonArgs:({entryScript:f})=>YFe({entryScript:f,serverUrl:o,configPath:p,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u})});await m();let{info:h,mcpLogger:g}=CD({logger:t,applicationName:`${i}-daemon-proxy`,cliVersion:r});return Vv({context:{logger:g},info:h,tools:Y6({tools:a7,resolveDaemonStateForCall:m,logger:g})})}function YFe({entryScript:e,serverUrl:t,configPath:n,alwaysSaveCache:o,noCache:r,videoDefault:i,headfulDefault:s,devicePixelRatio:a,sessionIdleTimeoutMinutes:l}){let c=[e,"mcp","--server",t,"--daemon","--config",n,"--headful-browser",s?"true":"false","--video",i?"true":"false"];return o&&c.push("--save-cache"),r&&c.push("--disable-cache"),c.push("--pixel-ratio",String(a)),l!==void 0&&c.push("--session-idle-timeout-minutes",String(l)),c}var _D=async(e,t)=>{try{let{killed:n,failed:o}=await ts.killAllSessions(e);o.length>0?t.warn({failed:o,reason:e},"Some browser sessions failed to terminate on shutdown"):n.length>0&&t.info({killedCount:n.length,reason:e},"Terminated browser sessions on shutdown");}catch(n){t.warn({err:n,reason:e},"Failed to terminate browser sessions on shutdown");}};async function PD(e){let{daemon:t,logger:n}=e,o=G6.safeParse(process.env);if(t&&o.success&&o.data[jv]==="momentic-web-mcp")return l7({...e,daemonPort:o.data[Hv],daemonToken:o.data[Gv],daemonSessionId:o.data[$v]});if(gd(n,true),t)return await c7(e);await Ew(e);let{context:r,info:i}=Cw(e);return Vv({context:r,info:i,tools:Sg,shutdownHandlers:[_D,fl,async()=>{await Sw();}]})}var lb="2.138.2",cn=Jm({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:lb});(async()=>{try{let e=await Cs(cn);e.gitBranchName&&cn.addBinding("branch",e.gitBranchName);}catch{}})();var au=Router();async function Ow(e){return (await xh(e,cn)).map(o=>{let r=e.modules[o.moduleId];if(!r){R.warn(`Found a dangling module with ID ${o.moduleId} that could not be found on disk.`);return}return {...r,content:o}}).filter(o=>o!==void 0)}au.get("/",ut(async(e,t)=>{let n=Qe(),o=await Vi(n),r=await Ow(o);t.status(200).json(r);}));au.post("/",ut(async(e,t)=>{let n;try{n=Ij.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{Ha(n.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let o=Qe(),r=await je(o),i=r.modules;if(Object.values(i).find(l=>l.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=En__default.join(o.rootDir,n.folderPath??En__default.dirname(n.testFilePath));if(!Mo__default.existsSync(s)||!Mo__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let a=await NC({...n,folder:s,project:o,momenticFiles:r});t.status(201).json(a);}));au.get("/:moduleId/tests",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=Qe(),o=await je(n),r=e.params.moduleId;if(!o.modules[r]){t.status(404).json({error:"Module not found."});return}let i=[];for(let a of Object.values(o.tests))wY(a.fullFilePath,o).has(r)&&i.push({id:a.id,name:a.name,relativePath:a.relativePath});let s={tests:i};t.status(200).json(s);}));au.get("/:moduleId",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=await Vi(Qe()),o=n.modules[e.params.moduleId];if(!o){t.status(404).json({error:"Module not found."});return}try{let r=await ul({modHandle:o,momenticFiles:n,logger:R});t.json(r);}catch(r){t.status(400).json({err:r});}}));au.post("/:moduleId/duplicate",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=wj.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Ha(n.name);}catch(h){t.status(400).json({error:h.message});return}let o=Qe(),r=await je(o),i=r.modules[e.params.moduleId];if(!i){t.status(404).json({error:"Module not found."});return}if(Object.values(r.modules).find(h=>h.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=n.sourceModuleContent;if(s.moduleId!==e.params.moduleId){t.status(400).json({error:"Duplicate source module content does not match moduleId."});return}let a=En__default.join(o.rootDir,En__default.dirname(i.relativePath));if(!Mo__default.existsSync(a)||!Mo__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let l=hn(n.name),c=En__default.join(a,`${l}.module.yaml`),d=dl({projectConfig:o.config,momenticFiles:r,entityType:"module"}),{stepsToSave:u}=await An({stepLists:{steps:s.steps},createNewCacheIds:true}),p={fileType:we.MODULE,schemaVersion:at,moduleId:d,name:n.name,description:"",enabled:true,steps:u.steps,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,defaultCacheKey:s.defaultCacheKey,defaultCacheTtl:s.defaultCacheTtl,defaultCacheAllInvocations:s.defaultCacheAllInvocations,autoAuth:s.autoAuth,advanced:s.advanced,defaultRetries:s.defaultRetries};Ts({module:p,filePath:c,projectConfig:o.config,momenticFiles:r});let m={relativeFilePath:En__default.relative(o.rootDir,c)};t.status(201).json(m);}));au.patch("/:moduleId/move",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=_j.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${Q(i)}`});return}let o=Qe();if(!(await Vi(o)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await PY({moduleId:e.params.moduleId,targetFolderRelativePath:n.folderPath,project:o}),t.status(200).json({message:"ok"});}));au.patch("/:moduleId/metadata",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=xj.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let o=Qe(),r=await Vi(o);EY({moduleId:e.params.moduleId,content:n,momenticFiles:r,logger:R,project:o}),t.status(201).json({message:"ok"});}));var d7=au;var cb=Router();cb.get("/",ut(async(e,t)=>{let n=Qe(),o=await je(n),r=new Set;o?.tests&&Object.values(o.tests).forEach(c=>{c.labels?.forEach(d=>r.add(d));});let i=Array.from(r).sort(),s=Object.values(o.tests),a=await Ow(o),l={labels:i,tests:s,modules:a};t.status(200).json(l);}));cb.get("/folders",ut(async(e,t)=>{let n=Qe(),o=await hY(n);t.status(200).json(o);}));cb.get("/labels",ut(async(e,t)=>{let n=Qe(),o=await je(n),r=new Set;for(let s of Object.values(o.tests))s.labels?.forEach(a=>r.add(a));let i=Array.from(r).sort();t.status(200).json(i);}));cb.post("/in-folder",ut(async(e,t)=>{let n=Aj.safeParse(e.body);if(!n.success){t.status(400).json({error:`Failed to parse entities-in-folder body: ${n.error.message}`});return}let{pathSegments:o}=n.data,r=Qe(),[i,s]=await Promise.all([mY(r,o),Vi(r)]),a=Object.values(i.tests),l=await Ow(s),c=new Set(Object.keys(i.modules)),d=l.filter(p=>c.has(p.id)),u={tests:a,modules:d};t.status(200).json(u);}));var u7=cb;var MD=Router();MD.get("/",ut((e,t)=>{let n=BC(Qe(),cn);t.status(200).json(n);}));MD.get("/names",ut((e,t)=>{let o=Qe().config.environments?.map(r=>r.name)??[];t.status(200).json(o);}));var p7=MD;var m7=Router();m7.get("/",ut((e,t)=>{let n={userId:gl(),orgId:Bn(),email:Gh(),name:oQ(),pylonEmailHash:rQ(),cliVersion:lb};t.status(200).json(n);}));var h7=m7;var OD="mcp-session-id",g7="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",Nw=Router();function rBe(){let e=process.env[g7];if(!e)return ru*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(cn.warn({envVar:g7,rawValue:e,fallback:ru},"Invalid MCP session idle timeout env var; falling back to default"),ru*60*1e3):t*60*1e3}function iBe(e){let{headfulDefault:t,supportsFileOutput:n}={},o={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:lb},r=Qe(),i=vs(),s=wr(),a=cn.child({orgId:Bn(),userId:gl(),...o}),l=new Dt({baseUrl:s,apiKey:i,logger:a}),c=Vf(process.env.MOMENTIC_HEADFUL_BROWSER),d=new sr(r.config.ai?.agentConfig,{baseUrl:s,apiKey:i,logger:a,mode:"interactive"}),u=Bn(),p=new ns(l,u,r);return {context:{project:r,orgId:u,logger:a,generator:d,apiClient:l,storage:p,serverId:o.serverId,extractBaseDir:ba(r.rootDir),saveChangesToDisk:true,supportsFileOutput:n??true,knowledgeRetrievalResults:rn,knowledgeCitations:[],sessionIdleTimeoutMs:rBe(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??Ur},info:o}}var kc={};Nw.post("/",async(e,t)=>{let n=String(e.headers[OD]??"");try{if(n&&kc[n]){await kc[n].handleRequest(e,t,e.body);return}if(!n&&isInitializeRequest(e.body)){let{context:o,info:r}=iBe(),i=Xk(o,r,Sg),s=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:a=>{kc[a]=s;}});s.onclose=()=>{let a=s.sessionId;a&&kc[a]&&delete kc[a],i.close().catch(()=>{});},await i.connect(s),await s.handleRequest(e,t,e.body);return}t.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});}catch{t.headersSent||t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null});}});Nw.get("/",async(e,t)=>{let n=String(e.headers[OD]??"");if(!n||!kc[n]){t.status(400).send("Invalid or missing session ID");return}await kc[n].handleRequest(e,t);});Nw.delete("/",async(e,t)=>{let n=String(e.headers[OD]??"");if(!n||!kc[n]){t.status(400).send("Invalid or missing session ID");return}let o=kc[n];try{await o.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var y7=Nw;var S7=Router();S7.get("/:id",ut(async(e,t)=>{let{id:n}=e.params;if(!n){t.status(400).json({error:"Missing ID"});return}let o=go();if(!o){t.status(500).json({error:"API client not initialized"});return}try{let{data:r,contentType:i}=await o.fetchOnDemandScreenshot(n);t.setHeader("Content-Type",i),t.status(200).send(r);}catch(r){cn.error({err:r,screenshotId:n},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var b7=S7;var Lw=Router();Lw.get("/",ut(async(e,t)=>{let n=new Map;for(let i of await eN())n.set(i.configFilePath,i);let o=Qe();n.set(o.configFilePath,o);let r=[...n.values()].map(i=>({name:i.config.name,configFilePath:i.configFilePath,fileFormat:i.config.fileFormat}));t.status(200).json(r);}));Lw.get("/current",ut((e,t)=>{let n=Qe();if(!n){t.status(404).json({error:"No project found."});return}let o={name:n.config.name,configFilePath:n.configFilePath,fileFormat:n.config.fileFormat};t.status(200).json(o);}));Lw.post("/set",ut(async(e,t)=>{let n;try{n=Oj.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}cn.info("Setting local project");try{let o=await an({configFilePath:n.configFilePath}),r=go();if(!r)throw new Error("API client is not initialized.");await jh({project:o,apiClient:r});}catch(o){t.status(400).json({error:`Error setting project: ${o}`});return}t.sendStatus(204);}));var T7=Lw;var A7=Router();A7.get("/",ut((e,t)=>{let n=Qe(),o={ai:n.config.ai,browser:n.config.browser,displayRoot:n.config.displayRoot};t.status(200).json(o);}));var E7=A7;var Ll=Router();Ll.post("/",ut(async(e,t)=>{let n;try{n=Rj.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}try{let o=Qe(),r=await ib({project:o,input:n});es({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(o){if(o instanceof dt){t.status(400).json({error:o.message});return}throw o}}));Ll.get("/:testPath",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=Qe(),r=await Vi(o),i;try{i=await hi(En__default.join(o.rootDir,n),cn,r),await(await Ei({logger:cn,orgId:Bn(),project:o})).resolveStepCacheEntries({schemaVersion:i.schemaVersion,testId:i.id,environment:i.envs?.find(a=>a.default)?.name,stepLists:{beforeSteps:i.beforeSteps,steps:i.steps,afterSteps:i.afterSteps},logger:cn,useSnapshotIdentityCache:o.config.fileFormat==="v2"}),t.status(200).json(i);}catch(s){t.status(400).send({error:s.message});return}(async()=>{try{await FC({relativeTestPath:n,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:at,momenticFiles:r,project:o});}catch(s){cn.error({err:s},"Failed to save migrated test to disk after initial fetch");}})();}));Ll.get("/:testPath/metadata",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=Qe(),r=En__default.join(o.rootDir,n);if(!Mo__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=Mo__default.statSync(r),s=await Cs(cn),a={gitBranch:s.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:s.gitCommitSha??"unknown"};t.status(200).json(a);}));Ll.patch("/:testPath/metadata",ut(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Cj.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:Qy(e.params.testPath,n,Qe()).newRelativeTestPath};t.status(200).json(r);}));Ll.patch("/:testPath",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=Ej.parse(e.body);}catch(m){cn.warn({err:m},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${m}`});return}cn.info({testPath:n},"Save received");let r=Qe(),i=await Vi(r),s;try{s=Xu(n,r);}catch(m){t.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let a=r.config.fileFormat==="v2",{stepsToSave:l,moduleUpdates:c,cachesToSave:d,snapshotCachesToSave:u}=await An({stepLists:o.stepLists,useSnapshotIdentityCache:a,cacheCreationParams:{orgId:Bn(),testId:s.id,environment:s.envs?.find(m=>m.default)?.name}}),p=await Ei({logger:cn,orgId:Bn(),project:r});a&&await p.saveSnapshotCacheEntries({logger:cn,entries:u}),await p.saveStepCacheEntries({logger:cn,entries:d}),JO({relativeTestPath:n,stepsToSave:l,moduleUpdates:c,schemaVersion:o.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));Ll.patch("/:testPath/environments",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=Mj.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}Qy(n,{envs:o.defaultEnv?[{name:o.defaultEnv,default:true}]:[]},Qe()),t.status(201).json({message:"ok"});}));Ll.patch("/:testPath/move",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=Pj.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${Q(i)}`});return}let r=Qe();if(!Mo__default.existsSync(En__default.join(r.rootDir,n))){t.status(404).json({error:"Test not found."});return}await MY({relativeTestPath:n,targetFolderRelativePath:o.folderPath,project:r}),t.status(200).json({message:"ok"});}));Ll.delete("/:testPath",ut((e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=Qe(),r=En__default.join(o.rootDir,n);if(!Mo__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}Mo__default.unlinkSync(r),t.status(200).json({message:"ok"});}));Ll.post("/:testPath/duplicate",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=vj.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Ha(o.name);}catch(h){t.status(400).json({error:h.message});return}let r=Qe(),i=En__default.join(r.rootDir,n);if(!Mo__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let s=await je(r),a;try{a=await hi(i,cn,s);}catch(h){t.status(400).send({error:h.message});return}let l=dl({projectConfig:r.config,momenticFiles:s,entityType:"test"}),c=Wn.parse({...a,name:o.name,id:l}),{stepsToSave:d}=await An({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewCacheIds:true}),u=En__default.dirname(i),p=En__default.join(u,`${o.name}.test.yaml`);As({test:{fileType:we.TEST,...c,...d},filePath:p,projectConfig:r.config,momenticFiles:s});let m={relativeFilePath:En__default.relative(r.rootDir,p)};es({type:"test_editor:test_duplicated"}),t.status(201).json(m);}));var C7=Ll;var cu=(r=>(r.SUCCEEDED="succeeded",r.FAILED="failed",r.BLOCKED="blocked",r.UNTESTABLE="untestable",r))(cu||{});function Ag(e,t={}){let n=[];(t.includeTitle??true)&&n.push("# Explorer agent result"),n.push(R7({titleBase:"## Changed user journeys",emptyMessage:"_No user-facing journeys identified in this diff window._",items:e.changedJourneys,format:dBe})),n.push(R7({titleBase:"## Proposed test plans",emptyMessage:"_No test plans proposed._",items:e.testPlans,format:uBe})),e.buildSummary&&n.push(pBe(e.buildSummary));let o=v7(e.notes,"## Notes");return o&&n.push(o),n.join(`
7431
+ `)}));}}),e7=Lo({schema:{name:Px,description:"Execute a step without adding it to the test.",inputSchema:{sessionId:z.string(),step:z.string().describe(Z9)}},handle:async(e,t,n,o)=>{let{sessionId:r,step:i}=t,s=iu({response:n,sessionId:r,toolName:Px});if(!s)return;s.controller.setOpen();let a;try{a=await ww({project:s.storage.getProject(),step:i,logger:e.logger,storage:s.storage,controller:s.controller,codeEvalTools:s.codeEvalTools,orgId:s.orgId,sessionId:s.sessionId,testContext:s.context,supportsFileOutput:e.supportsFileOutput,tempCaches:s.tempCaches,usageTracker:s.usageTracker,apiClient:go()});}finally{await s.usageTracker.flush(e.logger);}n.addContentParts(a);}}),t7=Lo({schema:{name:pf,description:"Insert, delete, or replace steps in the active session's test by index. Use parentStepIdChain to splice into nested steps (e.g. inside a conditional or module). The response includes inserted/deleted step refs with the updated active-session ids; use those ids for later run_step calls. The response always includes a recovery artifact with the full deleted and inserted payloads; only inspect it when you need to undo or inspect a mistaken splice.",inputSchema:{sessionId:z.string(),startIndex:z.number(),deleteCount:z.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:z.array(z.string()).describe(Z9),targetSection:bu.default("main"),parentStepIdChain:z.array(z.string()).optional().describe("When splicing into a nested step (e.g. conditional or module), the chain of parent step ids from root to the container. Empty or omit for top-level."),returnTest:z.boolean().default(false).describe("Return the full post-splice test snapshot. Avoid this by default. Use true only when you truly need the full updated test; the normal response already includes inserted/deleted step references plus a recovery artifact for mistaken-splice recovery.")}},handle:async(e,t,n,o)=>{let r=iu({response:n,sessionId:t.sessionId,toolName:pf});if(!r)return;let i=await Iw({project:r.storage.getProject(),storage:r.storage,orgId:r.orgId,logger:e.logger,testPath:r.relativeTestPath,envName:r.envName,saveChangesToDisk:e.saveChangesToDisk,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,mutableStepState:r.mutableStepState,params:{startIndex:t.startIndex,deleteCount:t.deleteCount,steps:t.steps,targetSection:t.targetSection,parentStepIdChain:t.parentStepIdChain,returnTest:t.returnTest}});t.steps.length>0&&es({type:"mcp:step_added",test_platform:"web",step_count:t.steps.length});let s=i.value.map(a=>a.type==="media"?{type:"media",data:a.data,mediaType:"image/jpeg"}:a);n.addContentParts(s);}}),n7=Lo({schema:{name:wT,description:`${RT} Use step ids from the active session: the Test Content section returned by ${Su}, or the inserted/deleted refs returned by ${pf}. If you need a full updated post-splice view, set returnTest on the splice call. Do not parse the raw YAML at testFileAbsolutePath for step ids; v2 simplified test files do not store step ids on disk.`,inputSchema:{sessionId:z.string(),fromStep:UT,toStep:HT.optional(),targetSection:bu.default("main"),resetSession:z.boolean().default(false).describe("Whether to reset the browser session before running the steps.")}},handle:async(e,t,n,o)=>{let r=iu({response:n,sessionId:t.sessionId,toolName:wT});if(!r)return;r.controller.setOpen(),t.resetSession&&await Aw({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,apiKey:vs(),baseUrl:wr(),controller:r.controller,testContext:r.context,supportsFileOutput:e.supportsFileOutput});let i=Q9(o,e.logger,n,()=>{ts.touchSession(r.sessionId);}),s=await xw({project:r.storage.getProject(),logger:e.logger,testPath:r.relativeTestPath,storage:r.storage,controller:r.controller,codeEvalTools:r.codeEvalTools,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,tracer:i,params:{fromStep:t.fromStep,toStep:t.toStep,targetSection:t.targetSection},supportsFileOutput:e.supportsFileOutput,envName:r.envName,usageTracker:r.usageTracker,mutableStepState:r.mutableStepState,apiClient:go()});es({type:"mcp:run_step_completed",test_platform:"web",status:"completed"});let a=s.value.map(l=>l.type==="media"?{type:"media",data:l.data,mediaType:"image/jpeg"}:l);n.addContentParts(a);}}),o7=[VFe,GFe,jFe,$Fe];var r7=[z9,W9,q9,K9,e7,n7,t7];async function qFe({testPath:e,logger:t,project:n,storage:o,orgId:r,mutableStepState:i}){let s=await o.getTestByPath({relativeTestPath:e,logger:t}),a=s.envs?.find(u=>u.default)?.name;if(i&&i.testId!==s.id)throw new Error(`Cannot extract a module from test ${s.id} with mutable state for ${i.testId}.`);let l=i?.stepLists??{steps:s.steps,beforeSteps:s.beforeSteps??void 0,afterSteps:s.afterSteps??void 0},c=await Ei({logger:t,orgId:r,project:n}),d=await bd({cacheStorage:c,logger:t,schemaVersion:s.schemaVersion,stepLists:l,testId:s.id,environment:a,useSnapshotIdentityCache:n.config.fileFormat==="v2"});return {availableSteps:d.steps,baseState:{steps:d.steps,beforeSteps:d.beforeSteps??[],afterSteps:d.afterSteps??[]},cacheSaveContext:{testId:s.id,environment:a,stepCacheStorage:c}}}async function Pw({project:e,storage:t,logger:n,relativeTestPath:o,saveChangesToDisk:r,mutableStepState:i,params:s}){let a=Bn();Ha(s.name);let l=await t.scanEntities(),c;s.startIndex!==void 0&&o!==void 0&&(c=await qFe({testPath:o,logger:n,project:e,storage:t,orgId:a,mutableStepState:i}));let{stepsToExtract:d,startIndex:u,endIndex:p}=i8({moduleName:s.name,existingModuleNames:Object.values(l.modules).map(E=>E.name),...s,parameterNames:s.parameters,testPath:o,availableSteps:c?.availableSteps,containsNestedModuleStep:U2}),{module:m}=await t.createModule({name:s.name,description:s.description??"",enabled:s.enabled??true,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,steps:d,subDir:s.subDir,momenticFiles:l});if(s.startIndex===void 0)return {module:m};if(!o||!c)throw new Error("Failed to initialize extraction state for module create");let h=Object.keys(s.moduleInputs??{}).length>0,g=(m.parameters?.length??0)>0,f;h?f=s.moduleInputs:g?f={}:f=void 0;let b={...m,type:"RESOLVED_MODULE",id:randomUUID(),steps:m.steps,inputs:f},T=cloneDeep(c.baseState);T.steps.splice(u,p-u,b),i&&(i.stepLists=T);let{environment:A,stepCacheStorage:C,testId:v}=c.cacheSaveContext,I=e.config.fileFormat==="v2",{cachesToSave:_,snapshotCachesToSave:x}=await An({stepLists:T,useSnapshotIdentityCache:I,cacheCreationParams:{orgId:a,testId:v,environment:A}});return I&&await C.saveSnapshotCacheEntries({logger:n,entries:x}),await C.saveStepCacheEntries({logger:n,entries:_}),r&&await t.updateTestByPath({logger:n,relativeTestPath:o,stepLists:T,schemaVersion:at}),{module:m}}var i7=Lo({schema:{name:K0,description:"Create a module. The name must satisfy Momentic entity naming rules or the tool will fail. If startIndex is provided, testPath is required and the specified test range is extracted into the module, then replaced with a module invocation in that test. endIndex may only be provided when startIndex is set.",inputSchema:{name:z.string().describe(Zf),description:z.string(),enabled:z.boolean().default(true),parameters:z.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:z.record(z.string(),z.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:z.record(z.string(),z.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:z.record(z.string(),z.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant when extracting from a test."),subDir:z.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:z.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:z.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:z.number().optional().describe("End index of steps to extract from the target test (exclusive). Only valid when startIndex is provided. If not provided, extracts just startIndex.")}},handle:async(e,t,n,o)=>{let{testPath:r,...i}=t;try{let s=J4({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),a=await Pw({project:e.project,storage:e.storage,logger:e.logger,relativeTestPath:s,saveChangesToDisk:e.saveChangesToDisk,params:i});n.addPartFromText(JSON.stringify(a.module,null,2));}catch(s){n.addError(Q(s));}}});var Sg=[...o7,...vw,...r7,i7,FZ,WZ,QZ,HZ];var a7=Sg.map(e=>e.tool),s7=new Map(a7.map(e=>[e.schema.name,e]));async function l7(e){let{project:t,applicationName:n,daemonPort:o,daemonToken:r,daemonSessionId:i,logger:s,cliVersion:a}=e,l=t.configFilePath;await Ew(e);let{context:c}=Cw({...e,logger:s.child({daemonSessionId:i}),applicationName:`${n}-daemon`,serverId:i});await Q6({adapter:{getTool:d=>{let u=s7.get(d);if(!u)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(s7.keys()).join(", ")}`);return {name:u.schema.name,execute:async({input:p,extra:m})=>await K6({context:c,tool:u,input:p,extra:m})}}},sessionManager:ts,daemonPort:o,daemonToken:r,daemonId:i,cliVersion:a,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:RD(e)*2,onShutdown:()=>{fl();}});}async function c7({project:e,logger:t,apiKey:n,serverUrl:o,cliVersion:r,applicationName:i,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u}){Bd(o);let p=e.configFilePath,m=async()=>j6({workerType:"momentic-web-mcp",configPath:p,apiKey:n,serverUrl:o,cliVersion:r,logger:t,buildDaemonArgs:({entryScript:f})=>YFe({entryScript:f,serverUrl:o,configPath:p,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u})});await m();let{info:h,mcpLogger:g}=CD({logger:t,applicationName:`${i}-daemon-proxy`,cliVersion:r});return Vv({context:{logger:g},info:h,tools:Y6({tools:a7,resolveDaemonStateForCall:m,logger:g})})}function YFe({entryScript:e,serverUrl:t,configPath:n,alwaysSaveCache:o,noCache:r,videoDefault:i,headfulDefault:s,devicePixelRatio:a,sessionIdleTimeoutMinutes:l}){let c=[e,"mcp","--server",t,"--daemon","--config",n,"--headful-browser",s?"true":"false","--video",i?"true":"false"];return o&&c.push("--save-cache"),r&&c.push("--disable-cache"),c.push("--pixel-ratio",String(a)),l!==void 0&&c.push("--session-idle-timeout-minutes",String(l)),c}var _D=async(e,t)=>{try{let{killed:n,failed:o}=await ts.killAllSessions(e);o.length>0?t.warn({failed:o,reason:e},"Some browser sessions failed to terminate on shutdown"):n.length>0&&t.info({killedCount:n.length,reason:e},"Terminated browser sessions on shutdown");}catch(n){t.warn({err:n,reason:e},"Failed to terminate browser sessions on shutdown");}};async function PD(e){let{daemon:t,logger:n}=e,o=G6.safeParse(process.env);if(t&&o.success&&o.data[jv]==="momentic-web-mcp")return l7({...e,daemonPort:o.data[Hv],daemonToken:o.data[Gv],daemonSessionId:o.data[$v]});if(gd(n,true),t)return await c7(e);await Ew(e);let{context:r,info:i}=Cw(e);return Vv({context:r,info:i,tools:Sg,shutdownHandlers:[_D,fl,async()=>{await Sw();}]})}var lb="2.138.3",cn=Jm({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:lb});(async()=>{try{let e=await Cs(cn);e.gitBranchName&&cn.addBinding("branch",e.gitBranchName);}catch{}})();var au=Router();async function Ow(e){return (await xh(e,cn)).map(o=>{let r=e.modules[o.moduleId];if(!r){R.warn(`Found a dangling module with ID ${o.moduleId} that could not be found on disk.`);return}return {...r,content:o}}).filter(o=>o!==void 0)}au.get("/",ut(async(e,t)=>{let n=Qe(),o=await Vi(n),r=await Ow(o);t.status(200).json(r);}));au.post("/",ut(async(e,t)=>{let n;try{n=Ij.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{Ha(n.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let o=Qe(),r=await je(o),i=r.modules;if(Object.values(i).find(l=>l.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=En__default.join(o.rootDir,n.folderPath??En__default.dirname(n.testFilePath));if(!Mo__default.existsSync(s)||!Mo__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let a=await NC({...n,folder:s,project:o,momenticFiles:r});t.status(201).json(a);}));au.get("/:moduleId/tests",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=Qe(),o=await je(n),r=e.params.moduleId;if(!o.modules[r]){t.status(404).json({error:"Module not found."});return}let i=[];for(let a of Object.values(o.tests))wY(a.fullFilePath,o).has(r)&&i.push({id:a.id,name:a.name,relativePath:a.relativePath});let s={tests:i};t.status(200).json(s);}));au.get("/:moduleId",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=await Vi(Qe()),o=n.modules[e.params.moduleId];if(!o){t.status(404).json({error:"Module not found."});return}try{let r=await ul({modHandle:o,momenticFiles:n,logger:R});t.json(r);}catch(r){t.status(400).json({err:r});}}));au.post("/:moduleId/duplicate",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=wj.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Ha(n.name);}catch(h){t.status(400).json({error:h.message});return}let o=Qe(),r=await je(o),i=r.modules[e.params.moduleId];if(!i){t.status(404).json({error:"Module not found."});return}if(Object.values(r.modules).find(h=>h.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=n.sourceModuleContent;if(s.moduleId!==e.params.moduleId){t.status(400).json({error:"Duplicate source module content does not match moduleId."});return}let a=En__default.join(o.rootDir,En__default.dirname(i.relativePath));if(!Mo__default.existsSync(a)||!Mo__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let l=hn(n.name),c=En__default.join(a,`${l}.module.yaml`),d=dl({projectConfig:o.config,momenticFiles:r,entityType:"module"}),{stepsToSave:u}=await An({stepLists:{steps:s.steps},createNewCacheIds:true}),p={fileType:we.MODULE,schemaVersion:at,moduleId:d,name:n.name,description:"",enabled:true,steps:u.steps,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,defaultCacheKey:s.defaultCacheKey,defaultCacheTtl:s.defaultCacheTtl,defaultCacheAllInvocations:s.defaultCacheAllInvocations,autoAuth:s.autoAuth,advanced:s.advanced,defaultRetries:s.defaultRetries};Ts({module:p,filePath:c,projectConfig:o.config,momenticFiles:r});let m={relativeFilePath:En__default.relative(o.rootDir,c)};t.status(201).json(m);}));au.patch("/:moduleId/move",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=_j.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${Q(i)}`});return}let o=Qe();if(!(await Vi(o)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await PY({moduleId:e.params.moduleId,targetFolderRelativePath:n.folderPath,project:o}),t.status(200).json({message:"ok"});}));au.patch("/:moduleId/metadata",ut(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=xj.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let o=Qe(),r=await Vi(o);EY({moduleId:e.params.moduleId,content:n,momenticFiles:r,logger:R,project:o}),t.status(201).json({message:"ok"});}));var d7=au;var cb=Router();cb.get("/",ut(async(e,t)=>{let n=Qe(),o=await je(n),r=new Set;o?.tests&&Object.values(o.tests).forEach(c=>{c.labels?.forEach(d=>r.add(d));});let i=Array.from(r).sort(),s=Object.values(o.tests),a=await Ow(o),l={labels:i,tests:s,modules:a};t.status(200).json(l);}));cb.get("/folders",ut(async(e,t)=>{let n=Qe(),o=await hY(n);t.status(200).json(o);}));cb.get("/labels",ut(async(e,t)=>{let n=Qe(),o=await je(n),r=new Set;for(let s of Object.values(o.tests))s.labels?.forEach(a=>r.add(a));let i=Array.from(r).sort();t.status(200).json(i);}));cb.post("/in-folder",ut(async(e,t)=>{let n=Aj.safeParse(e.body);if(!n.success){t.status(400).json({error:`Failed to parse entities-in-folder body: ${n.error.message}`});return}let{pathSegments:o}=n.data,r=Qe(),[i,s]=await Promise.all([mY(r,o),Vi(r)]),a=Object.values(i.tests),l=await Ow(s),c=new Set(Object.keys(i.modules)),d=l.filter(p=>c.has(p.id)),u={tests:a,modules:d};t.status(200).json(u);}));var u7=cb;var MD=Router();MD.get("/",ut((e,t)=>{let n=BC(Qe(),cn);t.status(200).json(n);}));MD.get("/names",ut((e,t)=>{let o=Qe().config.environments?.map(r=>r.name)??[];t.status(200).json(o);}));var p7=MD;var m7=Router();m7.get("/",ut((e,t)=>{let n={userId:gl(),orgId:Bn(),email:Gh(),name:oQ(),pylonEmailHash:rQ(),cliVersion:lb};t.status(200).json(n);}));var h7=m7;var OD="mcp-session-id",g7="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",Nw=Router();function rBe(){let e=process.env[g7];if(!e)return ru*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(cn.warn({envVar:g7,rawValue:e,fallback:ru},"Invalid MCP session idle timeout env var; falling back to default"),ru*60*1e3):t*60*1e3}function iBe(e){let{headfulDefault:t,supportsFileOutput:n}={},o={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:lb},r=Qe(),i=vs(),s=wr(),a=cn.child({orgId:Bn(),userId:gl(),...o}),l=new Dt({baseUrl:s,apiKey:i,logger:a}),c=Vf(process.env.MOMENTIC_HEADFUL_BROWSER),d=new sr(r.config.ai?.agentConfig,{baseUrl:s,apiKey:i,logger:a,mode:"interactive"}),u=Bn(),p=new ns(l,u,r);return {context:{project:r,orgId:u,logger:a,generator:d,apiClient:l,storage:p,serverId:o.serverId,extractBaseDir:ba(r.rootDir),saveChangesToDisk:true,supportsFileOutput:n??true,knowledgeRetrievalResults:rn,knowledgeCitations:[],sessionIdleTimeoutMs:rBe(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??Ur},info:o}}var kc={};Nw.post("/",async(e,t)=>{let n=String(e.headers[OD]??"");try{if(n&&kc[n]){await kc[n].handleRequest(e,t,e.body);return}if(!n&&isInitializeRequest(e.body)){let{context:o,info:r}=iBe(),i=Xk(o,r,Sg),s=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:a=>{kc[a]=s;}});s.onclose=()=>{let a=s.sessionId;a&&kc[a]&&delete kc[a],i.close().catch(()=>{});},await i.connect(s),await s.handleRequest(e,t,e.body);return}t.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});}catch{t.headersSent||t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null});}});Nw.get("/",async(e,t)=>{let n=String(e.headers[OD]??"");if(!n||!kc[n]){t.status(400).send("Invalid or missing session ID");return}await kc[n].handleRequest(e,t);});Nw.delete("/",async(e,t)=>{let n=String(e.headers[OD]??"");if(!n||!kc[n]){t.status(400).send("Invalid or missing session ID");return}let o=kc[n];try{await o.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var y7=Nw;var S7=Router();S7.get("/:id",ut(async(e,t)=>{let{id:n}=e.params;if(!n){t.status(400).json({error:"Missing ID"});return}let o=go();if(!o){t.status(500).json({error:"API client not initialized"});return}try{let{data:r,contentType:i}=await o.fetchOnDemandScreenshot(n);t.setHeader("Content-Type",i),t.status(200).send(r);}catch(r){cn.error({err:r,screenshotId:n},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var b7=S7;var Lw=Router();Lw.get("/",ut(async(e,t)=>{let n=new Map;for(let i of await eN())n.set(i.configFilePath,i);let o=Qe();n.set(o.configFilePath,o);let r=[...n.values()].map(i=>({name:i.config.name,configFilePath:i.configFilePath,fileFormat:i.config.fileFormat}));t.status(200).json(r);}));Lw.get("/current",ut((e,t)=>{let n=Qe();if(!n){t.status(404).json({error:"No project found."});return}let o={name:n.config.name,configFilePath:n.configFilePath,fileFormat:n.config.fileFormat};t.status(200).json(o);}));Lw.post("/set",ut(async(e,t)=>{let n;try{n=Oj.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}cn.info("Setting local project");try{let o=await an({configFilePath:n.configFilePath}),r=go();if(!r)throw new Error("API client is not initialized.");await jh({project:o,apiClient:r});}catch(o){t.status(400).json({error:`Error setting project: ${o}`});return}t.sendStatus(204);}));var T7=Lw;var A7=Router();A7.get("/",ut((e,t)=>{let n=Qe(),o={ai:n.config.ai,browser:n.config.browser,displayRoot:n.config.displayRoot};t.status(200).json(o);}));var E7=A7;var Ll=Router();Ll.post("/",ut(async(e,t)=>{let n;try{n=Rj.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}try{let o=Qe(),r=await ib({project:o,input:n});es({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(o){if(o instanceof dt){t.status(400).json({error:o.message});return}throw o}}));Ll.get("/:testPath",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=Qe(),r=await Vi(o),i;try{i=await hi(En__default.join(o.rootDir,n),cn,r),await(await Ei({logger:cn,orgId:Bn(),project:o})).resolveStepCacheEntries({schemaVersion:i.schemaVersion,testId:i.id,environment:i.envs?.find(a=>a.default)?.name,stepLists:{beforeSteps:i.beforeSteps,steps:i.steps,afterSteps:i.afterSteps},logger:cn,useSnapshotIdentityCache:o.config.fileFormat==="v2"}),t.status(200).json(i);}catch(s){t.status(400).send({error:s.message});return}(async()=>{try{await FC({relativeTestPath:n,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:at,momenticFiles:r,project:o});}catch(s){cn.error({err:s},"Failed to save migrated test to disk after initial fetch");}})();}));Ll.get("/:testPath/metadata",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=Qe(),r=En__default.join(o.rootDir,n);if(!Mo__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=Mo__default.statSync(r),s=await Cs(cn),a={gitBranch:s.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:s.gitCommitSha??"unknown"};t.status(200).json(a);}));Ll.patch("/:testPath/metadata",ut(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Cj.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:Qy(e.params.testPath,n,Qe()).newRelativeTestPath};t.status(200).json(r);}));Ll.patch("/:testPath",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=Ej.parse(e.body);}catch(m){cn.warn({err:m},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${m}`});return}cn.info({testPath:n},"Save received");let r=Qe(),i=await Vi(r),s;try{s=Xu(n,r);}catch(m){t.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let a=r.config.fileFormat==="v2",{stepsToSave:l,moduleUpdates:c,cachesToSave:d,snapshotCachesToSave:u}=await An({stepLists:o.stepLists,useSnapshotIdentityCache:a,cacheCreationParams:{orgId:Bn(),testId:s.id,environment:s.envs?.find(m=>m.default)?.name}}),p=await Ei({logger:cn,orgId:Bn(),project:r});a&&await p.saveSnapshotCacheEntries({logger:cn,entries:u}),await p.saveStepCacheEntries({logger:cn,entries:d}),JO({relativeTestPath:n,stepsToSave:l,moduleUpdates:c,schemaVersion:o.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));Ll.patch("/:testPath/environments",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=Mj.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}Qy(n,{envs:o.defaultEnv?[{name:o.defaultEnv,default:true}]:[]},Qe()),t.status(201).json({message:"ok"});}));Ll.patch("/:testPath/move",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=Pj.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${Q(i)}`});return}let r=Qe();if(!Mo__default.existsSync(En__default.join(r.rootDir,n))){t.status(404).json({error:"Test not found."});return}await MY({relativeTestPath:n,targetFolderRelativePath:o.folderPath,project:r}),t.status(200).json({message:"ok"});}));Ll.delete("/:testPath",ut((e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=Qe(),r=En__default.join(o.rootDir,n);if(!Mo__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}Mo__default.unlinkSync(r),t.status(200).json({message:"ok"});}));Ll.post("/:testPath/duplicate",ut(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=vj.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Ha(o.name);}catch(h){t.status(400).json({error:h.message});return}let r=Qe(),i=En__default.join(r.rootDir,n);if(!Mo__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let s=await je(r),a;try{a=await hi(i,cn,s);}catch(h){t.status(400).send({error:h.message});return}let l=dl({projectConfig:r.config,momenticFiles:s,entityType:"test"}),c=Wn.parse({...a,name:o.name,id:l}),{stepsToSave:d}=await An({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewCacheIds:true}),u=En__default.dirname(i),p=En__default.join(u,`${o.name}.test.yaml`);As({test:{fileType:we.TEST,...c,...d},filePath:p,projectConfig:r.config,momenticFiles:s});let m={relativeFilePath:En__default.relative(r.rootDir,p)};es({type:"test_editor:test_duplicated"}),t.status(201).json(m);}));var C7=Ll;var cu=(r=>(r.SUCCEEDED="succeeded",r.FAILED="failed",r.BLOCKED="blocked",r.UNTESTABLE="untestable",r))(cu||{});function Ag(e,t={}){let n=[];(t.includeTitle??true)&&n.push("# Explorer agent result"),n.push(R7({titleBase:"## Changed user journeys",emptyMessage:"_No user-facing journeys identified in this diff window._",items:e.changedJourneys,format:dBe})),n.push(R7({titleBase:"## Proposed test plans",emptyMessage:"_No test plans proposed._",items:e.testPlans,format:uBe})),e.buildSummary&&n.push(pBe(e.buildSummary));let o=v7(e.notes,"## Notes");return o&&n.push(o),n.join(`
7432
7432
 
7433
7433
  `)}function dBe(e){let t=e.evidence.length>0?`
7434
7434
 
@@ -8322,7 +8322,7 @@ ${s.stack}`),l.status(500).send(`Internal Server Error: ${s.message}`);}),e){let
8322
8322
  ${e.length===0?"(none)":r.join(`
8323
8323
  `)}
8324
8324
  </inScopeTests>
8325
- `}function cje(e){return ` - ${e.path} (${e.status}, +${e.insertions??0} -${e.deletions??0})`}var Fc={searchObservedTests:"search_observed_tests",searchSegments:"search_segments",getObservedTest:"get_observed_test",getSegment:"get_segment",listObservedTestsForSegment:"list_observed_tests_for_segment",addSelectedTest:"add_selected_test",removeSelectedTest:"remove_selected_test",viewSelectedTests:"view_selected_tests",submit:"submit_selection"},Bte="ai-select",dF=200,Ute=z.object({query:z.string().min(1).max(2e3).describe("Natural-language query against App Graph node text."),k:z.number().int().min(1).max(50).describe("Max results to return. Start small (5-10) when narrowing a surface; raise for broad/exploratory searches.")}),uF=z.object({id:z.string().min(1)}),dje=z.object({testId:z.string().min(1).describe("Test id (from search_observed_tests results or the <inScopeTests> list)."),testName:z.string().min(1).max(500).optional().describe("Short human-readable test name (used in view_selected_tests output and logs)."),rationale:z.string().min(1).max(500).describe("Why this test should run for this diff. Reference the changed surface, not the test id."),relevanceLabel:Gx.describe("high = directly exercises the changed surface; medium = adjacent feature coverage; low = broad smoke or fallback.")}),uje=z.object({testId:z.string().min(1),reason:z.string().min(1).max(500).optional().describe("Why this test is being removed (for logs).")}),pje=z.object({userSummary:z.string().min(1).max(2e3).describe("Plain-English summary written directly to the developer reading their CI output. 2-3 sentences in human terms about what kinds of tests were picked and why, referencing product surface (e.g. 'payment method UI', 'invoice export', 'sign-in retry') \u2014 not segment ids, observed-test ids, or tool calls. Example: 'Picked 14 tests covering payment-method UI because this PR changes the card-entry form. Also added 3 checkout end-to-end tests since payments are central to that flow.'"),anchorSegmentIds:z.array(z.string().min(1)).max(20).default([]).describe("Segment ids the agent identified as directly relevant to the change. Recorded in the plan for context.")});function Hte(e){let t={[Fc.searchObservedTests]:tool({description:"Hybrid (vector + lexical) search over previously-observed tests in the App Graph. Use to find tests by name, goal, test path, or description.",inputSchema:Ute,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.searchObservedTests({repository:e.repository,query:o.query,k:o.k});return re(j({text:JSON.stringify(r.results,null,2),section:"observed-test search results"}))},toModelOutput:({output:o})=>o}),[Fc.searchSegments]:tool({description:"Hybrid (vector + lexical) search over App Graph segments. Use to find feature surfaces, journeys, or product areas relevant to the diff.",inputSchema:Ute,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.searchSegments({repository:e.repository,query:o.query,k:o.k});return re(j({text:JSON.stringify(r.results,null,2),section:"segment search results"}))},toModelOutput:({output:o})=>o}),[Fc.getObservedTest]:tool({description:"Fetch the full record for an observed test by test id (matched realizations, coverage edges, recent execution metadata).",inputSchema:uF,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.getObservedTest(o.id);return re(j({text:JSON.stringify(r,null,2),section:`observed-test ${o.id}`}))},toModelOutput:({output:o})=>o}),[Fc.getSegment]:tool({description:"Fetch a segment's realizations and feature memberships. Use to understand a candidate anchor segment before submitting.",inputSchema:uF,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.getSegment(o.id);return re(j({text:JSON.stringify(r,null,2),section:`segment ${o.id}`}))},toModelOutput:({output:o})=>o}),[Fc.listObservedTestsForSegment]:tool({description:"List observed tests whose realizations match a given segment. Useful for enumerating coverage of an anchor segment.",inputSchema:uF,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.listObservedTestsForSegment(o.id);return re(j({text:JSON.stringify(r,null,2),section:`observed tests for segment ${o.id}`}))},toModelOutput:({output:o})=>o}),...mje(e),[Fc.addSelectedTest]:tool({description:`Add a test to the running selection list (or replace the entry if it is already on the list). Use throughout the investigation as evidence accumulates \u2014 do not wait until the end. Capped at ${dF} entries; remove low-value picks with remove_selected_test before adding more if you hit the cap.`,inputSchema:dje,execute:async o=>(e.toolCallCount+=1,e.inScopeTestIds.has(o.testId)?e.selectedTestCandidates.size>=dF&&!e.selectedTestCandidates.has(o.testId)?re(j({text:JSON.stringify({ok:false,reason:`selection list is at the ${dF}-test cap; remove a lower-value pick first`,total:e.selectedTestCandidates.size},null,2),section:"selection rejected"})):(e.selectedTestCandidates.set(o.testId,{testId:o.testId,testName:o.testName,rationale:o.rationale,relevanceLabel:o.relevanceLabel}),re(j({text:JSON.stringify({ok:true,testId:o.testId,total:e.selectedTestCandidates.size},null,2),section:"selection updated"}))):re(j({text:JSON.stringify({ok:false,reason:`testId "${o.testId}" is not in <inScopeTests>; only those tests can run, so this pick would be discarded. Find the matching test in <inScopeTests> by path/name and add it with that exact testId.`,testId:o.testId},null,2),section:"selection rejected"}))),toModelOutput:({output:o})=>o}),[Fc.removeSelectedTest]:tool({description:"Remove a test from the running selection list. Use when new evidence shows a previously-added test is not relevant after all.",inputSchema:uje,execute:async o=>{e.toolCallCount+=1;let r=e.selectedTestCandidates.delete(o.testId);return re(j({text:JSON.stringify({removed:r,testId:o.testId,total:e.selectedTestCandidates.size},null,2),section:"selection updated"}))},toModelOutput:({output:o})=>o}),[Fc.viewSelectedTests]:tool({description:"View the current state of the selection list. Returns every added test with its rationale and relevance label, plus the running anchor-segment set. Use to check progress before submitting.",inputSchema:z.object({}),execute:async()=>{e.toolCallCount+=1;let o=Array.from(e.selectedTestCandidates.values()).map(r=>({testId:r.testId,testName:r.testName,rationale:r.rationale,relevanceLabel:r.relevanceLabel}));return re(j({text:JSON.stringify({selectedTests:o,anchorSegmentIds:Array.from(e.anchorSegmentIds),total:o.length},null,2),section:"current selection"}))},toModelOutput:({output:o})=>o}),[Fc.submit]:tool({description:"Finalize the selection: provide the userSummary and the anchor-segment set. The list of tests itself is the running state built with add_selected_test / remove_selected_test \u2014 do not pass it here. Call this exactly once when investigation is complete.",inputSchema:pje,execute:async o=>{for(let r of o.anchorSegmentIds)e.anchorSegmentIds.add(r);return e.finalSubmission={userSummary:o.userSummary,candidates:Array.from(e.selectedTestCandidates.values()),anchorSegmentIds:Array.from(e.anchorSegmentIds)},re(j({text:JSON.stringify({accepted:e.finalSubmission.candidates.length,anchorSegmentIds:e.finalSubmission.anchorSegmentIds},null,2),section:"selection submitted"}))},toModelOutput:({output:o})=>o})},n={};for(let[o,r]of Object.entries(t)){let i=No({tool:r,name:o,logger:e.logger,logPrefix:"AI Select ",agentName:Bte});n[o]=lr({tool:i,name:o,spanName:`ai_select.tool.${o}`,attributes:{"momentic.agent_name":Bte}});}return n}function mje(e){let t={};for(let n of yp){let o=n(e.codeReadingContext);t[o.name]=hje({tool:o.tool,context:e});}return t}function hje(e){let t=e.tool,n=t.execute?.bind(t);return n?{...t,execute:async(o,r)=>(e.context.toolCallCount+=1,n(o,r))}:t}var Gte="gpt-5.5-2026-04-23",Eje=25,Cje=18e4,Rje=4096;async function jte(e){let t=e.logger.bindings().sessionId??randomUUID$1(),n=e.logger.child({agentName:"ai-select",sessionId:t}),o=await mkdtemp(np.join(tmpdir$1(),`momentic-ai-select-${t}-`)),r={apiClient:e.apiClient,logger:n,repository:e.repository,codeReadingContext:{logger:n,repoRoot:e.repoRoot,baseSha:e.diff.mergeBase,headSha:e.diff.headSha,spoolDir:o},toolCallCount:0,inScopeTestIds:new Set(e.candidateTests.map(p=>p.testId)),selectedTestCandidates:new Map,anchorSegmentIds:new Set,finalSubmission:null},i=Hte(r),s=e.diff.changedFiles.reduce((p,m)=>p+(m.insertions??0)+(m.deletions??0),0),a={logger:n,streamType:"github-pr-summary",sessionId:t},l=e.generator.getAzureOpenAIModelFactory(a),c=e.generator.getOpenAIModelFactory({...a,useOpenAIResponsesWebSocket:true}),d=Date.now();try{let p=Ti({providerFallback:{logger:n,providers:[{id:"azure",model:l(Gte)},{id:"openai",model:c(Gte)}]},system:Dte(s),messages:[{role:"user",content:Fte(e.diff,e.budgetCap,e.candidateTests)}],tools:i,stopWhen:[stepCountIs(Eje),hasToolCall("submit_selection")],maxOutputTokens:Rje,abortSignal:AbortSignal.timeout(Cje),providerOptions:{openai:{reasoningEffort:"low",store:!1,textVerbosity:"low"},azure:{reasoningEffort:"low",store:!1,textVerbosity:"low"}}});await Promise.all([p.text,p.steps,p.response]);}catch(p){return n.error({err:p},"ai-select agent stream errored or was aborted"),{submission:null,reason:`AI selection failed: ${Q(p)}`,toolCallCount:r.toolCallCount,durationMs:Date.now()-d}}finally{await rm$1(o,{recursive:true,force:true}).catch(p=>{n.warn({err:p,spoolDir:o},"failed to clean ai-select spool dir");});}let u=Date.now()-d;return r.finalSubmission?{submission:r.finalSubmission,toolCallCount:r.toolCallCount,durationMs:u}:(n.error({toolCallCount:r.toolCallCount,durationMs:u},"ai-select agent finished without calling submit_selection; falling open"),{submission:null,reason:"AI selection finished without returning a result.",toolCallCount:r.toolCallCount,durationMs:u})}var Bc="/v1/app-graph",dI=class{constructor(t,n){this.apiClient=t;this.logger=n;}async claim(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/claim`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return xU.parse(n)}async getPlan(t){let n=new URLSearchParams({repository:t.repository,headSha:t.headSha}),o=await this.apiClient.sendRequest(`${Bc}/ai-select/plan?${n.toString()}`,{method:"GET",retries:1,requestTimeoutMs:1e4});return PU.parse(o)}async finalize(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/finalize`,{method:"POST",body:t,retries:2,requestTimeoutMs:3e4});return _U.parse(n)}async release(t){await this.apiClient.sendRequest(`${Bc}/ai-select/release`,{method:"POST",body:{selectionPlanKey:t},retries:1,requestTimeoutMs:5e3}).catch(n=>{this.logger.warn({err:n,selectionPlanKey:t},"Failed to release ai-select lock");});}async searchObservedTests(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/search/observed-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return $x.parse(n)}async searchSegments(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/search/segments`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return $x.parse(n)}async getObservedTest(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/observed-tests/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return MU.parse(n)}async getSegment(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/segments/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return OU.parse(n)}async listObservedTestsForSegment(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/segments/${encodeURIComponent(t)}/observed-tests`,{method:"GET",retries:2,requestTimeoutMs:1e4});return NU.parse(n)}},vje=2e3,$te=12e4;async function Vte(e){let t=Date.now()+(e.timeoutMs??$te),n=0;for(;;){n+=1;let o=await e.client.claim(e.claim);if(o.status==="claimed")return {kind:"claimed",selectionPlanKey:o.selectionPlanKey,trackId:o.trackId};if(o.status==="ready")return {kind:"ready",plan:o.plan,planId:o.planId};if(Date.now()>=t)throw new Error(`ai-select: timed out waiting for plan after ${e.timeoutMs??$te}ms`);e.logger.info({attempt:n,claimedBy:o.claimedBy},"ai-select plan computing on another shard; polling"),await Ye(o.retryAfterMs??vje);}}async function wje(e){try{return await lI({repoRoot:e.repoRoot,explicitBase:"HEAD~1",logger:e.logger})}catch{return aF({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:null,logger:e.logger})}}async function pF(e){let t=new dI(e.apiClient,e.logger),n;try{n=await lI({repoRoot:e.repoRoot,explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch,logger:e.logger});}catch(a){let l=a instanceof Gp?a.message:`Could not assemble diff against base ref: ${Q(a)}.`,c=kte({explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch}),d=c?await aF({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:c,logger:e.logger}):null;if(d)n=d;else {let u=e.config?.onBaseUnavailable??"use-head";if(u==="fail")throw new Gp(`AI selection base unavailable and ai.select.onBaseUnavailable is "fail": ${l}`);if(u==="run-all")return {kind:"run-all",reason:l,diff:null};let p=await wje(e);if(p===null)return {kind:"run-all",reason:`Could not assemble diff against the HEAD commit's parent: ${l}`,diff:null};n=p;}}if(n.changedFiles.length===0)return {kind:"run-none",reason:"No source-code changes detected between base and head.",diff:n};let o=await Vte({client:t,claim:{repository:e.repository,headSha:n.headSha,baseRef:n.baseRef,changedFiles:n.changedFiles.map(a=>a.path),diffSummary:null,budgetCap:e.budgetCap,dryRun:e.dryRun},logger:e.logger});if(o.kind==="ready")return {kind:"ready",plan:o.plan,planId:o.planId,mode:"SELECTED",diff:n};let r=await jte({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:e.repoRoot,diff:n,budgetCap:e.budgetCap,candidateTests:e.candidateTests});if(r.submission===null)return await t.release(o.selectionPlanKey),{kind:"run-all",reason:r.reason,diff:n};let i=new Map(e.candidateTests.map(a=>[a.testId,a.testPath])),s=r.submission.candidates.map(a=>({testId:a.testId,testPath:i.get(a.testId)??null,name:a.testName??a.testId,rationale:a.rationale,relevanceLabel:a.relevanceLabel}));try{let a=await t.finalize({selectionPlanKey:o.selectionPlanKey,repository:e.repository,headSha:n.headSha,mode:"SELECTED",userSummary:r.submission.userSummary,toolCallCount:r.toolCallCount,selectedTests:s,anchorSegmentIds:r.submission.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap}});return {kind:"ready",plan:a.plan,planId:a.planId,mode:"SELECTED",diff:n}}catch(a){return e.logger.error({err:a},"ai-select finalize failed; falling back to run-all"),await t.release(o.selectionPlanKey),{kind:"run-all",reason:`Could not record selection plan: ${Q(a)}.`,diff:n}}}var zte=()=>process.exit(130),Wte=()=>process.exit(143);process.on("SIGINT",zte);process.on("SIGTERM",Wte);function Pg(){process.off("SIGINT",zte),process.off("SIGTERM",Wte);}function Ab(e){let t=e??Pje();return qte()&&t===1&&R.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function Pje(){let e=qte(),t=e?2:1;return R.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var qte=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function uI(e,t=true,n=false){let o=Lje(e),r=await Oje.which(o[0],true),i=o.slice(1),s=Mje.exec(Nje(r),i,{delay:100,silent:n});if(t)return s}var Kte="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function kje(e,{context:t}){return e instanceof Fn?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${Kte}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${Q(e)}`}function Yte(e){return e instanceof Fn?e.rawError.includes("Resource not accessible by integration")?Kte:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":Q(e)}function Jte(e,t){R.error(kje(e,t));}function Qte(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let n;try{n=new URL(t);}catch{throw new Error(`Invalid run URL: ${e}`)}let o=n.pathname.split("/").filter(i=>i.length>0),r=o.indexOf("runs");if(r===-1||r===o.length-1)throw new Error(`Could not extract run ID from URL: ${e}. Expected a URL like https://app.momentic.ai/runs/<runId>.`);return o[r+1]}return t}function pI(e){return new Promise((t,n)=>{let o=[];createReadStream(e).pipe(Dje()).on("data",r=>o.push(r)).on("end",()=>t(o)).on("error",r=>n(r));})}var Hn="2.138.2",{checkCLIVersion:Pr,getLatestCLIVersion:Xte}=$3({packageName:"momentic",currentVersion:Hn,changelogUrl:"https://github.com/momentic-ai/cli/blob/main/CHANGELOG.md",updateCommand:"npx momentic@latest upgrade"});Nve("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:Uc,setAnalyticsIdentity:mF,shutdownAnalytics:Zte}=zA({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:K3});async function ft(){try{await Re(Promise.all([$A(),gt.flush(),Zte(),XA()]),{milliseconds:5e3});}catch{}}async function Mg({tests:e,momenticFiles:t,project:n,yes:o,include:r,exclude:i,labels:s,logger:a}){let l=new Set;if(e&&e.length>0){let d=e.some(p=>Mo__default.existsSync(p)),u=cwd();d?(u!==n.rootDir&&a.warn(`Test paths resolve against the current directory ('${u}'), not the project root ('${n.rootDir}'). Run from the project root or use substring filters to avoid surprises.`),e.forEach(p=>{if(!Mo__default.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m;try{m=Mo__default.statSync(p).isDirectory();}catch(g){a.warn({err:g},`Skipping path ${p} because it cannot be read`);return}let h=En__default.resolve(p);Object.values(t.tests).filter(g=>m?g.fullFilePath.startsWith(h):g.fullFilePath===h).forEach(g=>{l.add(g.fullFilePath);});})):Object.values(t.tests).forEach(p=>{e.some(m=>p.relativePath.includes(m))&&l.add(p.fullFilePath);});}else !o&&!await xo("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1)),Object.values(t.tests).forEach(u=>{l.add(u.fullFilePath);});for(let d of l){let u=En__default.relative(n.rootDir,d);r&&!r.some(p=>new RegExp(p).test(u))&&l.delete(d),i&&i.some(p=>new RegExp(p).test(u))&&l.delete(d);}let c=Array.from(l).map(async d=>{try{let u=await hi(d,ve,t);if(Hh.gt(u.schemaVersion,at)&&a.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),s&&s.length>0){let p=u.labels||[];if(!s.some(h=>p.includes(h)))return null}return {...u,fullFilePath:d,relativeFilePath:En__default.relative(n.rootDir,d)}}catch(u){a.error(`Failed to read and resolve test at '${d}': ${Q(u)}`),process.exit(1);}});return compact(await Promise.all(c))}function tne({testDefinitions:e,quarantinedTestsMetadata:t,onlyQuarantined:n=false,skipQuarantined:o=false}){let[r,i]=partition(e,l=>l.disabled),[s,a]=partition(i,l=>l.id in t);return {testsToSkip:r,quarantinedTestsToSkip:o?s:[],testsToRun:n?[]:a,quarantinedTestsToRun:o?[]:s}}function nne({testsToRun:e,quarantinedTestsToRun:t,quarantinedTestsMetadata:n,testInputMatrix:o}){let r=[],i=(s,a,l)=>{o?o.forEach((c,d)=>{r.push({inputs:c,inputIndex:d,testDefinition:s,quarantined:a,quarantinedMetadata:l});}):r.push({inputs:void 0,testDefinition:s,quarantined:a,quarantinedMetadata:l});};return e.forEach(s=>i(s,false)),t.forEach(s=>i(s,true,n[s.id])),r}async function one({orgId:e,codeEvalTools:t,logger:n,outputDefinitions:o,testContext:r}){let i={};for(let s of o){let{name:a,value:l}=s;i[a]=await Ir({orgId:e,s:l,localTools:t,logger:n,context:r});}return i}var rne=new Set;async function ine({baseUrl:e,envName:t,devicePixelRatio:n,apiClient:o,test:r,storageClient:i,codeEvalTools:s,generator:a,orgId:l,variables:c,logger:d,customHeaders:u,testInputs:p,localBrowserConfig:m,aiSettings:h,visualDiffScreenshotStorage:g,tracer:f,runId:b,browserTypeOverride:T,attemptedRemoteBrowserProviders:A}){let C={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:ve,mode:"runner"},{controller:v,context:I}=await mw({baseUrl:e,envName:t,test:r,variables:c,logger:d,orgId:l,localBrowserConfig:m,aiSettings:h,customHeaders:u,codeEvalTools:s,storage:i,enricher:new Nd(C,a),generator:a,visualDiffScreenshotStorage:g,devicePixelRatio:n,browserTypeOverride:T,callbacks:{onNetworkPage:_=>f.onNetworkPage(_),onNetworkLogs:_=>f.onNetworkLogs(_)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:_,timestamp:x})=>{f.setActiveVideo(_,x);}}:void 0,validateBrowserType:_=>{LE(_)||(ve.warn({browserType:_,testName:r.name},"Browser required by test does not appear to be installed"),!rne.has(_)&&(rne.add(_),R.warn(`Browser ${_} does not appear to be installed. Run '${Tm(_)}' if you hit launch errors.`)));},createRemoteBrowserConnection:m.remoteBrowser?async()=>{let _=await o.createRemoteBrowserConnection({runId:b,attemptedProviders:A});return _.provider&&A?.push(_.provider),_}:void 0});try{await hw({orgId:l,test:r,testInputs:p,localTools:s,logger:d,context:I});}catch(_){try{await v.browser.cleanup();}catch(x){d.error({err:x},"Failed to clean up browser after test input resolution failed");}throw _ instanceof eb&&(R.error(_.message),process.exit(1)),_}return {controller:v,context:I}}function sne({testAdvancedSettings:e,orgSettings:t,logger:n}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!ic){let o="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(o),R.debug(o),false}return true}async function ane({attemptInputs:e,attemptFixtures:t,attemptMetadata:n,runFixtures:o,stepCallbacks:r}){let{orgId:i,userId:s,runId:a}=n,{runTracer:l,runGroupTracer:c,project:d,apiClient:u}=o,{controller:p,context:m,codeEvalTools:h,storageClient:g,logger:f,usageTracker:b,tracer:T}=t,{test:A,orgSettings:C}=e;f.info(`Running test '${A.name}' locally (run link: https://app.momentic.ai/runs/${a})`);let v={controller:p,storage:g,usageTracker:b,context:m,logger:f,codeEvalTools:h},I={orgId:i,userId:s,runId:a,testMetadata:A,steps:A.steps,beforeSteps:A.beforeSteps,afterSteps:A.afterSteps,orgSettings:C},_={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await sne({testAdvancedSettings:A.advanced,orgSettings:C.ai,logger:f})};return f9({fixtures:v,inputs:I,options:_,callbacks:{step:r??{},test:{onTestComplete:async()=>{await p.browser.cleanup(),await h.dispose();}}},testParams:{attemptTracer:T},runParams:{runTracer:l,runGroupTracer:c,project:d,apiClient:u,captureEvent:Uc,abortSignal:o.abortSignal}})}async function lne(e){let{testDefinition:t,logger:n}=e,o=new Date;try{return await Vje(e)}catch(r){dd(r);let i="Fatal error running test";n.error({err:r},i),R.error({err:r},i);let s=yu(r);return {results:[],parameters:e,failureReason:"UnknownError",failureDetails:{errorMessage:s.message,errorStack:s.stack},status:"FAILED",attempts:0,test:t,filePath:t.relativeFilePath,startedAt:o,lastAttemptStartedAt:o,finishedAt:new Date,outputs:{},quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata}}}async function Vje(e){let{testDefinition:t,project:n,apiClient:o,orgId:r,userId:i,urlOverride:s,runGroupTracer:a,logger:l,gitMetadata:c,cacheOptions:d,runId:u,testInputs:p,quarantined:m,quarantinedMetadata:h,usageTracker:g}=e,f=new kh(o,r),b=ap({logger:l,orgId:r,client:o,gitMetadata:c,regenerateCache:d.regenerateCache,alwaysSaveCache:d.alwaysSaveCache,noCache:d.noCache,isolateCachesByEnvironment:n.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:d.bustOldestCachePercentage}),{envName:T,resolvedEnv:A,environmentVariables:C,baseUrl:v}=sR({test:t,envNameOverride:e.envName,urlOverride:s,resolveEnv:U=>Zu(U,n,l)}),I=await bd({cacheStorage:b,logger:l,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:T,useSnapshotIdentityCache:n.config.fileFormat==="v2"}),_=I.steps,x=I.beforeSteps??void 0,E=I.afterSteps??void 0,O=await a.startRun({logger:l,runId:u,originalSteps:{beforeSteps:t.beforeSteps,steps:t.steps,afterSteps:t.afterSteps},testId:t.id,testName:t.name,directory:dirname(t.relativeFilePath),testDescription:t.description??void 0,testLabels:t.labels,baseUrl:v,environmentName:T,schemaVersion:t.schemaVersion,resolvedInputs:p,quarantined:m,quarantinedReason:h?.quarantinedReason,aiSettings:e.project.config.ai}),N=l.child(O.loggerBindings||{});Object.entries(O.envVarBindings||{}).forEach(([U,$])=>{C[U]=$;});let H=await zje({...e,variables:C,envName:T,resolvedEnv:A,baseUrl:v,storageClient:f,tracer:O,runGroupTracer:a,logger:N,cacheStorage:b,stepsWithCaches:_,beforeStepsWithCaches:x,afterStepsWithCaches:E,usageTracker:g});return await O.finish({logger:l,status:H.status,finishedAt:H.finishedAt,failureDetails:H.failureDetails,failureReason:H.failureReason,isFlake:H.isFlake,failureRecoveryDetails:H.failureRecoveryDetails}),{runId:O.runId,...H}}async function zje(e){let{testDefinition:t,stepsWithCaches:n,beforeStepsWithCaches:o,afterStepsWithCaches:r,project:i,regenerateGoldenFiles:s,apiClient:a,generator:l,baseUrl:c,storageClient:d,orgId:u,userId:p,envName:m,urlOverride:h,customHeaders:g,testInputs:f,variables:b,resolvedEnv:T,retriesOverride:A,devicePixelRatio:C,logUpdate:v,tracer:I,runGroupTracer:_,logger:x,cacheStorage:E,gitMetadata:O,quarantined:N,quarantinedMetadata:H,usageTracker:U}=e,$=i.config.ai?.aiFailureAnalysis??false,oe=new Date,X=new Ph(i,a,s),z={...i.config},K={envName:m,urlOverride:h,customHeaders:g,testInputs:f},q={...i.config.browser||{},...T?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},J=q.remoteBrowser===true,te=[],B,le=Math.abs(A??t.retries??i.config.retries??1),be=[];x.info({...O,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let De=0;De<=le;De++){let Oe=randomUUID(),Ne=await I.startAttempt(Oe),et=x.child(Ne.loggerBindings||{}),Be={...t,steps:cloneDeep(n),beforeSteps:cloneDeep(o),afterSteps:cloneDeep(r)};De!==0&&v("RETRY",`attempt ${De+1}/${le+1}`);let ne=new Date,Fe=new Ld({httpClient:new gi({baseUrl:a.baseUrl,apiKey:a.apiKey,logger:et,mode:"runner"}),fakerSeed:z.advanced?.fakerConstantSeed?gA:void 0});try{let{controller:ot,context:mt}=await ine({tracer:Ne,runId:I.runId,baseUrl:c,envName:m,apiClient:a,devicePixelRatio:C,logger:et,storageClient:d,codeEvalTools:Fe,test:Be,generator:l,orgId:u,variables:b,customHeaders:g,testInputs:f,localBrowserConfig:q,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:te,aiSettings:{...i.config.ai||{},...Be.advanced||{}},visualDiffScreenshotStorage:X});e.abortSignal&&(e.abortSignal.aborted?ot.executeAbortController.abort():e.abortSignal.addEventListener("abort",()=>{ot.executeAbortController.abort();},{once:!0})),B=await ane({attemptMetadata:{attemptNumber:De+1,orgId:u,userId:p,runId:I.runId},attemptFixtures:{logger:et,storageClient:d,usageTracker:U,codeEvalTools:Fe,context:mt,controller:ot,tracer:Ne},attemptInputs:{test:Be,orgSettings:z},runFixtures:{runTracer:I,runGroupTracer:_,project:i,apiClient:a,abortSignal:e.abortSignal},stepCallbacks:{onStepStart:e.onStepStart}});let xe=new Date,si={logger:x,cacheStorage:E,orgId:u,testId:t.id,environment:m,originalStepsWithCaches:{steps:cloneDeep(n),beforeSteps:cloneDeep(o),afterSteps:cloneDeep(r)},updatedStepsWithCaches:{steps:Be.steps,beforeSteps:Be.beforeSteps,afterSteps:Be.afterSteps}};await $u({logger:x,cacheStorage:E,orgId:u,testId:t.id,environment:m,stepLists:si.updatedStepsWithCaches,useSnapshotIdentityCache:i.config.fileFormat==="v2"}),B?.status==="PASSED"?await Vu(si):B?.status==="FAILED"&&De===le&&await uh(si),await Ne.finish({logger:et,result:B}),be.unshift(B.status);let ai=await one({orgId:u,codeEvalTools:Fe,logger:et,outputDefinitions:t.outputs??[],testContext:mt}),Fs=YU(be),wa=De+1;if(B.status!=="FAILED")return {...B,runAttemptId:Oe,parameters:K,test:Be,filePath:Be.relativeFilePath,startedAt:oe,lastAttemptStartedAt:ne,finishedAt:xe,attempts:wa,baseUrl:c,outputs:ai,isFlake:Fs,quarantined:N,quarantinedMetadata:H,usedRemoteBrowser:J};let Ci=B.failedStepResult,io=Ci?.message||"Unknown failure",jn=Ci?.failureReason??I0(io)??"UnknownError",bo=et.child({failureReason:jn,errorMessage:io,numAttempts:(le+1).toString(),name:Be.name});if(De<le){bo.warn(`Retrying failed execution attempt for run: ${io}`);continue}bo.error(`Test failed after all exhausting attempts: ${io}`);let Lr=new Error(io),$n={errorMessage:io,errorStack:Lr.stack},Do;if(i.config.ai?.classification?.enabled===!0){let tn=Ci?.failureClassification;tn||(e.onStepStart?.("Classifying failure"),tn=await Wv({runTracer:I,runGroupTracer:_,outputDir:e.outputDir,orgId:u,project:i,generator:l,apiClient:a,logger:x,testPlatform:"web",aiSettings:i.config.ai,captureEvent:Uc,abortSignal:e.abortSignal,failedStepMessage:Ci?.message})),tn&&(Do=tn.classification.category,jn=tn.classification.category,$n.classification={reason:tn.classification.category,secondaryCategories:tn.classification.secondaryCategories,summary:tn.classification.reasoning,recoverable:tn.classification.recoverable,confidence:tn.classification.confidence,action:tn.action,citations:tn.classification.citations,source:"v2"});}else if($){let tn;try{if(B.results&&B.results.length>0){e.onStepStart?.("Classifying failure");let{classification:rs,aiFailureReason:L}=await eK({logger:et,browserStateStorage:Ne,generator:l,fullResults:B,failureReason:jn,error:Lr,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});tn=rs,Do=L;}}catch(rs){et.warn({err:rs},"Failed to classify test results");}tn&&($n.classification=tn,jn=Do??jn,$n.classification.source="v1");}return {...B,runAttemptId:Oe,parameters:K,failureDetails:$n,failureReason:jn,test:Be,filePath:Be.relativeFilePath,startedAt:oe,lastAttemptStartedAt:ne,finishedAt:xe,attempts:De+1,baseUrl:c,outputs:ai,quarantined:N,quarantinedMetadata:H,usedRemoteBrowser:J}}catch(ot){let mt=`Encountered fatal platform error while running test '${Be.name}'`;et.error({err:ot},mt),R.error({err:ot},mt);let xe=yu(ot);return await Ne.finish({logger:et,result:{status:"FAILED"}}),{status:"FAILED",failureDetails:{errorMessage:xe.message,errorStack:xe.stack},failureReason:"InternalPlatformError",runAttemptId:Oe,results:[],parameters:K,test:Be,filePath:Be.relativeFilePath,startedAt:oe,lastAttemptStartedAt:ne,finishedAt:new Date,attempts:De+1,baseUrl:c,outputs:{},quarantined:N,quarantinedMetadata:H,usedRemoteBrowser:J}}}throw new Error("This code should not be reachable")}function fF(e){return createHash("sha1").update(e).digest("hex")}var qje=["tab","view","mode","step"],Kje=[/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i,/^(?=.*\d)[A-Za-z0-9_-]{16,256}$/,/^\d{3,32}$/,/^[0-9A-HJKMNP-TV-Z]{26}$/];function Yje(e){return Kje.some(t=>t.test(e))}function cne(e,t={}){let n;try{n=new URL(e);}catch{return e}let o=new Set(t.queryAllowlist??qje),i=n.pathname.split("/").map(c=>c.length>0&&Yje(c)?"{id}":c).join("/"),s=[],a=Array.from(n.searchParams.keys()).sort();for(let c of a){if(!o.has(c))continue;let d=n.searchParams.getAll(c).sort();for(let u of d)s.push(`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);}let l=s.length>0?`?${s.join("&")}`:"";return `${n.protocol}//${n.host}${i}${l}`}var Jje=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),Qje=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,Xje=[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,/\b[0-9a-f]{12,64}\b/gi,/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,/\b\d{5,}\b/g,/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,16}\b/g],dne=new Set(["h1","h2","h3","h4","h5","h6"]),Zje=new Set(["input","select","textarea"]);function e$e(e){let t=e;for(let n of Xje)t=t.replace(n,"{id}");return t}function une(e){return e$e(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function t$e(e){let t=e.length;return t<=4?"txt:xs":t<=16?"txt:s":t<=64?"txt:m":t<=256?"txt:l":"txt:xl"}function n$e(e,t){return e==="href"?t.startsWith("#")?"href:hash":t.startsWith("/")?"href:rel":/^https?:\/\//.test(t)?"href:abs":/^(mailto|tel):/.test(t)?`href:${t.split(":")[0]}`:"href:other":Qje.test(t)?"@gen":une(t)}function pne(e,t,n){let o=e.tag.toLowerCase(),r=(e.role??e.attributes?.role)?.toLowerCase(),i=Math.min(Math.floor(t/4),6),s=`<${o}@${i}`;if(r!==void 0&&(s+=` role=${r}`),e.attributes!==void 0){let l=Object.keys(e.attributes).filter(c=>Jje.has(c.toLowerCase())).sort();for(let c of l){let d=c.toLowerCase();if(d==="role")continue;let u=e.attributes[c];if(u===void 0)continue;let p=n$e(d,u);s+=` ${d}=${p}`;}}n.tokens.push(s);let a=e.text?.trim();a!==void 0&&a.length>0&&(r==="button"||r==="link"||r==="heading"||o==="button"||o==="a"||o==="label"||dne.has(o)?n.tokens.push(`label=${une(a)}`):n.tokens.push(t$e(a))),(o==="button"||r==="button")&&(n.counts.buttons+=1),(o==="a"||r==="link")&&(n.counts.links+=1),(Zje.has(o)||r==="textbox"||r==="combobox")&&(n.counts.formFields+=1),(dne.has(o)||r==="heading")&&(n.counts.headings+=1);for(let l of e.children??[])pne(l,t+1,n);}function mne(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return pne(e,0,t),{tokens:t.tokens,counts:t.counts}}function hne(e,t){let n=new TextEncoder().encode(e),o=n.length,r=Math.floor(o/4),i=t>>>0,s=3432918353,a=461845907;for(let u=0;u<r;u++){let p=u*4,m=n[p]|n[p+1]<<8|n[p+2]<<16|n[p+3]<<24;m=Math.imul(m,s),m=m<<15|m>>>17,m=Math.imul(m,a),i^=m,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}let l=0,c=o&3,d=r*4;return c===3&&(l^=n[d+2]<<16),c>=2&&(l^=n[d+1]<<8),c>=1&&(l^=n[d],l=Math.imul(l,s),l=l<<15|l>>>17,l=Math.imul(l,a),i^=l),i^=o,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}var mI=128,o$e=4294967295,r$e=(()=>{let e=[];for(let t=0;t<mI;t++)e.push(hne(`perm:${t}`,0));return e})();function gne(e){let t=new Uint32Array(mI);for(let o=0;o<mI;o++)t[o]=o$e;let n=new Set(e);for(let o of n)for(let r=0;r<mI;r++){let i=hne(o,r$e[r]);i<t[r]&&(t[r]=i);}return t}var s$e=32;function yF(e){let t=cne(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:n,counts:o}=mne(e.dom),r=[`url:${t}`,`counts:buttons=${o.buttons}`,`counts:links=${o.links}`,`counts:formFields=${o.formFields}`,`counts:headings=${o.headings}`,...n],i=gne(r),s=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(s).digest("hex").slice(0,s$e),minhash:Array.from(i),canonicalUrl:t}}var a$e=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),yn="\uFFFD",P;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z";})(P||(P={}));var oi={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function hI(e){return e>=55296&&e<=57343}function fne(e){return e>=56320&&e<=57343}function yne(e,t){return (e-55296)*1024+9216+t}function gI(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function fI(e){return e>=64976&&e<=65007||a$e.has(e)}var Z;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text";})(Z||(Z={}));var c$e=65536,yI=class{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=false,this.lastChunkWritten=false,this.endOfChunkHit=false,this.bufferWaterline=c$e,this.isEol=false,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1;}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){let{line:o,col:r,offset:i}=this,s=r+n,a=i+n;return {code:t,startLine:o,endLine:o,startCol:s,endCol:s,startOffset:a,endOffset:a}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)));}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos;}_processSurrogate(t){if(this.pos!==this.html.length-1){let n=this.html.charCodeAt(this.pos+1);if(fne(n))return this.pos++,this._addGap(),yne(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,P.EOF;return this._err(Z.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0);}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=false,this.lastChunkWritten=n;}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=false;}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,false;if(n)return this.html.startsWith(t,this.pos);for(let o=0;o<t.length;o++)if((this.html.charCodeAt(this.pos+o)|32)!==t.charCodeAt(o))return false;return true}peek(t){let n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,P.EOF;let o=this.html.charCodeAt(n);return o===P.CARRIAGE_RETURN?P.LINE_FEED:o}advance(){if(this.pos++,this.isEol&&(this.isEol=false,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,P.EOF;let t=this.html.charCodeAt(this.pos);return t===P.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,P.LINE_FEED):t===P.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,hI(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===P.LINE_FEED||t===P.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){gI(t)?this._err(Z.controlCharacterInInputStream):fI(t)&&this._err(Z.noncharacterInInputStream);}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=false;}};var Ut;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION";})(Ut||(Ut={}));function SI(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}var u$e=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function Sne(e){return e>=55296&&e<=57343||e>1114111?65533:u$e.get(e)??e}function bne(e){let t=atob(e),n=t.length&-2,o=new Uint16Array(n/2);for(let r=0,i=0;r<n;r+=2){let s=t.charCodeAt(r),a=t.charCodeAt(r+1);o[i++]=s|a<<8;}return o}var SF=bne("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var Mr;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE";})(Mr||(Mr={}));var Gn;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z";})(Gn||(Gn={}));var Tne=32;function bF(e){return e>=Gn.ZERO&&e<=Gn.NINE}function p$e(e){return e>=Gn.UPPER_A&&e<=Gn.UPPER_F||e>=Gn.LOWER_A&&e<=Gn.LOWER_F}function m$e(e){return e>=Gn.UPPER_A&&e<=Gn.UPPER_Z||e>=Gn.LOWER_A&&e<=Gn.LOWER_Z||bF(e)}function h$e(e){return e===Gn.EQUALS||m$e(e)}var Jo;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity";})(Jo||(Jo={}));var Fl;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(Fl||(Fl={}));var bI=class{decodeTree;emitCodePoint;errors;constructor(t,n,o){this.decodeTree=t,this.emitCodePoint=n,this.errors=o;}state=Jo.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Fl.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=Jo.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,n){switch(this.state){case Jo.EntityStart:return t.charCodeAt(n)===Gn.NUM?(this.state=Jo.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Jo.NamedEntity,this.stateNamedEntity(t,n));case Jo.NumericStart:return this.stateNumericStart(t,n);case Jo.NumericDecimal:return this.stateNumericDecimal(t,n);case Jo.NumericHex:return this.stateNumericHex(t,n);case Jo.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|Tne)===Gn.LOWER_X?(this.state=Jo.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Jo.NumericDecimal,this.stateNumericDecimal(t,n))}stateNumericHex(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(bF(o)||p$e(o)){let r=o<=Gn.NINE?o-Gn.ZERO:(o|Tne)-Gn.LOWER_A+10;this.result=this.result*16+r,this.consumed++,n++;}else return this.emitNumericEntity(o,3)}return -1}stateNumericDecimal(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(bF(o))this.result=this.result*10+(o-Gn.ZERO),this.consumed++,n++;else return this.emitNumericEntity(o,2)}return -1}emitNumericEntity(t,n){if(this.consumed<=n)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===Gn.SEMI)this.consumed+=1;else if(this.decodeMode===Fl.Strict)return 0;return this.emitCodePoint(Sne(this.result),this.consumed),this.errors&&(t!==Gn.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){let{decodeTree:o}=this,r=o[this.treeIndex],i=(r&Mr.VALUE_LENGTH)>>14;for(;n<t.length;){if(i===0&&r&Mr.FLAG13){let a=(r&Mr.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&Mr.JUMP_TABLE;if(t.charCodeAt(n)!==l)return this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}for(;this.runConsumed<a;){if(n>=t.length)return -1;let l=this.runConsumed-1,c=o[this.treeIndex+1+(l>>1)],d=l%2===0?c&255:c>>8&255;if(t.charCodeAt(n)!==d)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}this.runConsumed=0,this.treeIndex+=1+(a>>1),r=o[this.treeIndex],i=(r&Mr.VALUE_LENGTH)>>14;}if(n>=t.length)break;let s=t.charCodeAt(n);if(s===Gn.SEMI&&i!==0&&r&Mr.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=g$e(o,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Fl.Attribute&&(i===0||h$e(s))?0:this.emitNotTerminatedNamedEntity();if(r=o[this.treeIndex],i=(r&Mr.VALUE_LENGTH)>>14,i!==0){if(s===Gn.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==Fl.Strict&&!(r&Mr.FLAG13)&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}n++,this.excess++;}return -1}emitNotTerminatedNamedEntity(){let{result:t,decodeTree:n}=this,o=(n[t]&Mr.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,o,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,o){let{decodeTree:r}=this;return this.emitCodePoint(n===1?r[t]&~(Mr.VALUE_LENGTH|Mr.FLAG13):r[t+1],o),n===3&&this.emitCodePoint(r[t+2],o),o}end(){switch(this.state){case Jo.NamedEntity:return this.result!==0&&(this.decodeMode!==Fl.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Jo.NumericDecimal:return this.emitNumericEntity(0,2);case Jo.NumericHex:return this.emitNumericEntity(0,3);case Jo.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Jo.EntityStart:return 0}}};function g$e(e,t,n,o){let r=(t&Mr.BRANCH_LENGTH)>>7,i=t&Mr.JUMP_TABLE;if(r===0)return i!==0&&o===i?n:-1;if(i){let c=o-i;return c<0||c>=r?-1:e[n+c]-1}let s=r+1>>1,a=0,l=r-1;for(;a<=l;){let c=a+l>>>1,d=c>>1,p=e[n+d]>>(c&1)*8&255;if(p<o)a=c+1;else if(p>o)l=c-1;else return e[n+s+c]}return -1}var me;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/";})(me||(me={}));var Hc;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size";})(Hc||(Hc={}));var ri;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(ri||(ri={}));var W;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp";})(W||(W={}));var y;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP";})(y||(y={}));var f$e=new Map([[W.A,y.A],[W.ADDRESS,y.ADDRESS],[W.ANNOTATION_XML,y.ANNOTATION_XML],[W.APPLET,y.APPLET],[W.AREA,y.AREA],[W.ARTICLE,y.ARTICLE],[W.ASIDE,y.ASIDE],[W.B,y.B],[W.BASE,y.BASE],[W.BASEFONT,y.BASEFONT],[W.BGSOUND,y.BGSOUND],[W.BIG,y.BIG],[W.BLOCKQUOTE,y.BLOCKQUOTE],[W.BODY,y.BODY],[W.BR,y.BR],[W.BUTTON,y.BUTTON],[W.CAPTION,y.CAPTION],[W.CENTER,y.CENTER],[W.CODE,y.CODE],[W.COL,y.COL],[W.COLGROUP,y.COLGROUP],[W.DD,y.DD],[W.DESC,y.DESC],[W.DETAILS,y.DETAILS],[W.DIALOG,y.DIALOG],[W.DIR,y.DIR],[W.DIV,y.DIV],[W.DL,y.DL],[W.DT,y.DT],[W.EM,y.EM],[W.EMBED,y.EMBED],[W.FIELDSET,y.FIELDSET],[W.FIGCAPTION,y.FIGCAPTION],[W.FIGURE,y.FIGURE],[W.FONT,y.FONT],[W.FOOTER,y.FOOTER],[W.FOREIGN_OBJECT,y.FOREIGN_OBJECT],[W.FORM,y.FORM],[W.FRAME,y.FRAME],[W.FRAMESET,y.FRAMESET],[W.H1,y.H1],[W.H2,y.H2],[W.H3,y.H3],[W.H4,y.H4],[W.H5,y.H5],[W.H6,y.H6],[W.HEAD,y.HEAD],[W.HEADER,y.HEADER],[W.HGROUP,y.HGROUP],[W.HR,y.HR],[W.HTML,y.HTML],[W.I,y.I],[W.IMG,y.IMG],[W.IMAGE,y.IMAGE],[W.INPUT,y.INPUT],[W.IFRAME,y.IFRAME],[W.KEYGEN,y.KEYGEN],[W.LABEL,y.LABEL],[W.LI,y.LI],[W.LINK,y.LINK],[W.LISTING,y.LISTING],[W.MAIN,y.MAIN],[W.MALIGNMARK,y.MALIGNMARK],[W.MARQUEE,y.MARQUEE],[W.MATH,y.MATH],[W.MENU,y.MENU],[W.META,y.META],[W.MGLYPH,y.MGLYPH],[W.MI,y.MI],[W.MO,y.MO],[W.MN,y.MN],[W.MS,y.MS],[W.MTEXT,y.MTEXT],[W.NAV,y.NAV],[W.NOBR,y.NOBR],[W.NOFRAMES,y.NOFRAMES],[W.NOEMBED,y.NOEMBED],[W.NOSCRIPT,y.NOSCRIPT],[W.OBJECT,y.OBJECT],[W.OL,y.OL],[W.OPTGROUP,y.OPTGROUP],[W.OPTION,y.OPTION],[W.P,y.P],[W.PARAM,y.PARAM],[W.PLAINTEXT,y.PLAINTEXT],[W.PRE,y.PRE],[W.RB,y.RB],[W.RP,y.RP],[W.RT,y.RT],[W.RTC,y.RTC],[W.RUBY,y.RUBY],[W.S,y.S],[W.SCRIPT,y.SCRIPT],[W.SEARCH,y.SEARCH],[W.SECTION,y.SECTION],[W.SELECT,y.SELECT],[W.SOURCE,y.SOURCE],[W.SMALL,y.SMALL],[W.SPAN,y.SPAN],[W.STRIKE,y.STRIKE],[W.STRONG,y.STRONG],[W.STYLE,y.STYLE],[W.SUB,y.SUB],[W.SUMMARY,y.SUMMARY],[W.SUP,y.SUP],[W.TABLE,y.TABLE],[W.TBODY,y.TBODY],[W.TEMPLATE,y.TEMPLATE],[W.TEXTAREA,y.TEXTAREA],[W.TFOOT,y.TFOOT],[W.TD,y.TD],[W.TH,y.TH],[W.THEAD,y.THEAD],[W.TITLE,y.TITLE],[W.TR,y.TR],[W.TRACK,y.TRACK],[W.TT,y.TT],[W.U,y.U],[W.UL,y.UL],[W.SVG,y.SVG],[W.VAR,y.VAR],[W.WBR,y.WBR],[W.XMP,y.XMP]]);function jp(e){var t;return (t=f$e.get(e))!==null&&t!==void 0?t:y.UNKNOWN}var ye=y,Ane={[me.HTML]:new Set([ye.ADDRESS,ye.APPLET,ye.AREA,ye.ARTICLE,ye.ASIDE,ye.BASE,ye.BASEFONT,ye.BGSOUND,ye.BLOCKQUOTE,ye.BODY,ye.BR,ye.BUTTON,ye.CAPTION,ye.CENTER,ye.COL,ye.COLGROUP,ye.DD,ye.DETAILS,ye.DIR,ye.DIV,ye.DL,ye.DT,ye.EMBED,ye.FIELDSET,ye.FIGCAPTION,ye.FIGURE,ye.FOOTER,ye.FORM,ye.FRAME,ye.FRAMESET,ye.H1,ye.H2,ye.H3,ye.H4,ye.H5,ye.H6,ye.HEAD,ye.HEADER,ye.HGROUP,ye.HR,ye.HTML,ye.IFRAME,ye.IMG,ye.INPUT,ye.LI,ye.LINK,ye.LISTING,ye.MAIN,ye.MARQUEE,ye.MENU,ye.META,ye.NAV,ye.NOEMBED,ye.NOFRAMES,ye.NOSCRIPT,ye.OBJECT,ye.OL,ye.P,ye.PARAM,ye.PLAINTEXT,ye.PRE,ye.SCRIPT,ye.SECTION,ye.SELECT,ye.SOURCE,ye.STYLE,ye.SUMMARY,ye.TABLE,ye.TBODY,ye.TD,ye.TEMPLATE,ye.TEXTAREA,ye.TFOOT,ye.TH,ye.THEAD,ye.TITLE,ye.TR,ye.TRACK,ye.UL,ye.WBR,ye.XMP]),[me.MATHML]:new Set([ye.MI,ye.MO,ye.MN,ye.MS,ye.MTEXT,ye.ANNOTATION_XML]),[me.SVG]:new Set([ye.TITLE,ye.FOREIGN_OBJECT,ye.DESC]),[me.XLINK]:new Set,[me.XML]:new Set,[me.XMLNS]:new Set},Eb=new Set([ye.H1,ye.H2,ye.H3,ye.H4,ye.H5,ye.H6]);new Set([W.STYLE,W.SCRIPT,W.XMP,W.IFRAME,W.NOEMBED,W.NOFRAMES,W.PLAINTEXT]);var k;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND";})(k||(k={}));var Or={DATA:k.DATA,RCDATA:k.RCDATA,RAWTEXT:k.RAWTEXT,SCRIPT_DATA:k.SCRIPT_DATA,PLAINTEXT:k.PLAINTEXT,CDATA_SECTION:k.CDATA_SECTION};function S$e(e){return e>=P.DIGIT_0&&e<=P.DIGIT_9}function Cb(e){return e>=P.LATIN_CAPITAL_A&&e<=P.LATIN_CAPITAL_Z}function b$e(e){return e>=P.LATIN_SMALL_A&&e<=P.LATIN_SMALL_Z}function uu(e){return b$e(e)||Cb(e)}function Ene(e){return uu(e)||S$e(e)}function TI(e){return e+32}function Rne(e){return e===P.SPACE||e===P.LINE_FEED||e===P.TABULATION||e===P.FORM_FEED}function Cne(e){return Rne(e)||e===P.SOLIDUS||e===P.GREATER_THAN_SIGN}function T$e(e){return e===P.NULL?Z.nullCharacterReference:e>1114111?Z.characterReferenceOutsideUnicodeRange:hI(e)?Z.surrogateCharacterReference:fI(e)?Z.noncharacterCharacterReference:gI(e)||e===P.CARRIAGE_RETURN?Z.controlCharacterReference:null}var Rb=class{constructor(t,n){this.options=t,this.handler=n,this.paused=false,this.inLoop=false,this.inForeignNode=false,this.lastStartTagName="",this.active=false,this.state=k.DATA,this.returnState=k.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new yI(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new bI(SF,(o,r)=>{this.preprocessor.pos=this.entityStartPos+r-1,this._flushCodePointConsumedAsCharacterReference(o);},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(Z.missingSemicolonAfterCharacterReference,1);},absenceOfDigitsInNumericCharacterReference:o=>{this._err(Z.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+o);},validateNumericCharacterReference:o=>{let r=T$e(o);r&&this._err(r,1);}}:void 0);}_err(t,n=0){var o,r;(r=(o=this.handler).onParseError)===null||r===void 0||r.call(o,this.preprocessor.getError(t,n));}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=true;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let t=this._consume();this._ensureHibernation()||this._callState(t);}this.inLoop=false;}}pause(){this.paused=true;}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=false,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.());}write(t,n,o){this.active=true,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||o?.();}insertHtmlAtCurrentPos(t){this.active=true,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop();}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=false,true):false}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance();}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),true):false}_createStartTagToken(){this.currentToken={type:Ut.START_TAG,tagName:"",tagID:y.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:Ut.END_TAG,tagName:"",tagID:y.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:Ut.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:Ut.DOCTYPE,name:t,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation};}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation};}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0);}_leaveAttrName(){var t,n;let o=this.currentToken;if(SI(o,this.currentAttr.name)===null){if(o.attrs.push(this.currentAttr),o.location&&this.currentLocation){let r=(t=(n=o.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue();}}else this._err(Z.duplicateAttribute);}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset);}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1);}emitCurrentTagToken(){let t=this.currentToken;this.prepareToken(t),t.tagID=jp(t.tagName),t.type===Ut.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(Z.endTagWithAttributes),t.selfClosing&&this._err(Z.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk();}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk();}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk();}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Ut.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ut.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ut.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null;}}_emitEOFToken(){let t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Ut.EOF,location:t}),this.active=false;}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n);}_emitCodePoint(t){let n=Rne(t)?Ut.WHITESPACE_CHARACTER:t===P.NULL?Ut.NULL_CHARACTER:Ut.CHARACTER;this._appendCharToCurrentCharacterToken(n,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(Ut.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=k.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Fl.Attribute:Fl.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===k.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===k.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===k.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case k.DATA:{this._stateData(t);break}case k.RCDATA:{this._stateRcdata(t);break}case k.RAWTEXT:{this._stateRawtext(t);break}case k.SCRIPT_DATA:{this._stateScriptData(t);break}case k.PLAINTEXT:{this._statePlaintext(t);break}case k.TAG_OPEN:{this._stateTagOpen(t);break}case k.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case k.TAG_NAME:{this._stateTagName(t);break}case k.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case k.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case k.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case k.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case k.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case k.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case k.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case k.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case k.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case k.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case k.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case k.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case k.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case k.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case k.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case k.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case k.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case k.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case k.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case k.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case k.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case k.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case k.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case k.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case k.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case k.BOGUS_COMMENT:{this._stateBogusComment(t);break}case k.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case k.COMMENT_START:{this._stateCommentStart(t);break}case k.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case k.COMMENT:{this._stateComment(t);break}case k.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case k.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case k.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case k.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case k.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case k.COMMENT_END:{this._stateCommentEnd(t);break}case k.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case k.DOCTYPE:{this._stateDoctype(t);break}case k.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case k.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case k.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case k.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case k.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case k.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case k.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case k.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case k.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case k.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case k.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case k.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case k.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case k.CDATA_SECTION:{this._stateCdataSection(t);break}case k.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case k.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case k.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case k.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case P.LESS_THAN_SIGN:{this.state=k.TAG_OPEN;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitCodePoint(t);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case P.AMPERSAND:{this._startCharacterReference();break}case P.LESS_THAN_SIGN:{this.state=k.RCDATA_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case P.LESS_THAN_SIGN:{this.state=k.RAWTEXT_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(uu(t))this._createStartTagToken(),this.state=k.TAG_NAME,this._stateTagName(t);else switch(t){case P.EXCLAMATION_MARK:{this.state=k.MARKUP_DECLARATION_OPEN;break}case P.SOLIDUS:{this.state=k.END_TAG_OPEN;break}case P.QUESTION_MARK:{this._err(Z.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=k.BOGUS_COMMENT,this._stateBogusComment(t);break}case P.EOF:{this._err(Z.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(Z.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=k.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(uu(t))this._createEndTagToken(),this.state=k.TAG_NAME,this._stateTagName(t);else switch(t){case P.GREATER_THAN_SIGN:{this._err(Z.missingEndTagName),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(Z.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=k.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_ATTRIBUTE_NAME;break}case P.SOLIDUS:{this.state=k.SELF_CLOSING_START_TAG;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentTagToken();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.tagName+=yn;break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(Cb(t)?TI(t):t);}}_stateRcdataLessThanSign(t){t===P.SOLIDUS?this.state=k.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=k.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){uu(t)?(this.state=k.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=k.RCDATA,this._stateRcdata(t));}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,false))return !this._ensureHibernation();this._createEndTagToken();let n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=k.BEFORE_ATTRIBUTE_NAME,false;case P.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=k.SELF_CLOSING_START_TAG,false;case P.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=k.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===P.SOLIDUS?this.state=k.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=k.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){uu(t)?(this.state=k.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=k.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case P.SOLIDUS:{this.state=k.SCRIPT_DATA_END_TAG_OPEN;break}case P.EXCLAMATION_MARK:{this.state=k.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=k.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){uu(t)?(this.state=k.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===P.HYPHEN_MINUS?(this.state=k.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===P.HYPHEN_MINUS?(this.state=k.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case P.HYPHEN_MINUS:{this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case P.GREATER_THAN_SIGN:{this.state=k.SCRIPT_DATA,this._emitChars(">");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===P.SOLIDUS?this.state=k.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:uu(t)?(this._emitChars("<"),this.state=k.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){uu(t)?(this.state=k.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(oi.SCRIPT,false)&&Cne(this.preprocessor.peek(oi.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<oi.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case P.HYPHEN_MINUS:{this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case P.GREATER_THAN_SIGN:{this.state=k.SCRIPT_DATA,this._emitChars(">");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===P.SOLIDUS?(this.state=k.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(oi.SCRIPT,false)&&Cne(this.preprocessor.peek(oi.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<oi.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=k.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.SOLIDUS:case P.GREATER_THAN_SIGN:case P.EOF:{this.state=k.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case P.EQUALS_SIGN:{this._err(Z.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=k.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=k.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:case P.SOLIDUS:case P.GREATER_THAN_SIGN:case P.EOF:{this._leaveAttrName(),this.state=k.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case P.EQUALS_SIGN:{this._leaveAttrName(),this.state=k.BEFORE_ATTRIBUTE_VALUE;break}case P.QUOTATION_MARK:case P.APOSTROPHE:case P.LESS_THAN_SIGN:{this._err(Z.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.name+=yn;break}default:this.currentAttr.name+=String.fromCodePoint(Cb(t)?TI(t):t);}}_stateAfterAttributeName(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.SOLIDUS:{this.state=k.SELF_CLOSING_START_TAG;break}case P.EQUALS_SIGN:{this.state=k.BEFORE_ATTRIBUTE_VALUE;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentTagToken();break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=k.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.QUOTATION_MARK:{this.state=k.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this.state=k.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingAttributeValue),this.state=k.DATA,this.emitCurrentTagToken();break}default:this.state=k.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case P.QUOTATION_MARK:{this.state=k.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.value+=yn;break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case P.APOSTROPHE:{this.state=k.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.value+=yn;break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this._leaveAttrValue(),this.state=k.BEFORE_ATTRIBUTE_NAME;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=k.DATA,this.emitCurrentTagToken();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.value+=yn;break}case P.QUOTATION_MARK:case P.APOSTROPHE:case P.LESS_THAN_SIGN:case P.EQUALS_SIGN:case P.GRAVE_ACCENT:{this._err(Z.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this._leaveAttrValue(),this.state=k.BEFORE_ATTRIBUTE_NAME;break}case P.SOLIDUS:{this._leaveAttrValue(),this.state=k.SELF_CLOSING_START_TAG;break}case P.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=k.DATA,this.emitCurrentTagToken();break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this._err(Z.missingWhitespaceBetweenAttributes),this.state=k.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case P.GREATER_THAN_SIGN:{let n=this.currentToken;n.selfClosing=true,this.state=k.DATA,this.emitCurrentTagToken();break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this._err(Z.unexpectedSolidusInTag),this.state=k.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let n=this.currentToken;switch(t){case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentComment(n);break}case P.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.data+=yn;break}default:n.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(oi.DASH_DASH,true)?(this._createCommentToken(oi.DASH_DASH.length+1),this.state=k.COMMENT_START):this._consumeSequenceIfMatch(oi.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation(oi.DOCTYPE.length+1),this.state=k.DOCTYPE):this._consumeSequenceIfMatch(oi.CDATA_START,true)?this.inForeignNode?this.state=k.CDATA_SECTION:(this._err(Z.cdataInHtmlContent),this._createCommentToken(oi.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=k.BOGUS_COMMENT):this._ensureHibernation()||(this._err(Z.incorrectlyOpenedComment),this._createCommentToken(2),this.state=k.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_START_DASH;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptClosingOfEmptyComment),this.state=k.DATA;let n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=k.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_END;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptClosingOfEmptyComment),this.state=k.DATA,this.emitCurrentComment(n);break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=k.COMMENT,this._stateComment(t);}}_stateComment(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_END_DASH;break}case P.LESS_THAN_SIGN:{n.data+="<",this.state=k.COMMENT_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.data+=yn;break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t);}}_stateCommentLessThanSign(t){let n=this.currentToken;switch(t){case P.EXCLAMATION_MARK:{n.data+="!",this.state=k.COMMENT_LESS_THAN_SIGN_BANG;break}case P.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=k.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===P.HYPHEN_MINUS?this.state=k.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=k.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===P.HYPHEN_MINUS?this.state=k.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=k.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==P.GREATER_THAN_SIGN&&t!==P.EOF&&this._err(Z.nestedComment),this.state=k.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_END;break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=k.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let n=this.currentToken;switch(t){case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentComment(n);break}case P.EXCLAMATION_MARK:{this.state=k.COMMENT_END_BANG;break}case P.HYPHEN_MINUS:{n.data+="-";break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=k.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{n.data+="--!",this.state=k.COMMENT_END_DASH;break}case P.GREATER_THAN_SIGN:{this._err(Z.incorrectlyClosedComment),this.state=k.DATA,this.emitCurrentComment(n);break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=k.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_DOCTYPE_NAME;break}case P.GREATER_THAN_SIGN:{this.state=k.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case P.EOF:{this._err(Z.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingWhitespaceBeforeDoctypeName),this.state=k.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(Cb(t))this._createDoctypeToken(String.fromCharCode(TI(t))),this.state=k.DOCTYPE_NAME;else switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.NULL:{this._err(Z.unexpectedNullCharacter),this._createDoctypeToken(yn),this.state=k.DOCTYPE_NAME;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypeName),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=k.DOCTYPE_NAME;}}_stateDoctypeName(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.AFTER_DOCTYPE_NAME;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.name+=yn;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(Cb(t)?TI(t):t);}}_stateAfterDoctypeName(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(oi.PUBLIC,false)?this.state=k.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(oi.SYSTEM,false)?this.state=k.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(Z.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case P.QUOTATION_MARK:{this._err(Z.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this._err(Z.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.QUOTATION_MARK:{n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case P.QUOTATION_MARK:{this.state=k.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.publicId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateDoctypePublicIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case P.APOSTROPHE:{this.state=k.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.publicId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateAfterDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.QUOTATION_MARK:{this._err(Z.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this._err(Z.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.QUOTATION_MARK:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case P.QUOTATION_MARK:{this._err(Z.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this._err(Z.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.QUOTATION_MARK:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case P.QUOTATION_MARK:{this.state=k.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.systemId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateDoctypeSystemIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case P.APOSTROPHE:{this.state=k.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.systemId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateAfterDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let n=this.currentToken;switch(t){case P.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.NULL:{this._err(Z.unexpectedNullCharacter);break}case P.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case P.RIGHT_SQUARE_BRACKET:{this.state=k.CDATA_SECTION_BRACKET;break}case P.EOF:{this._err(Z.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===P.RIGHT_SQUARE_BRACKET?this.state=k.CDATA_SECTION_END:(this._emitChars("]"),this.state=k.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case P.GREATER_THAN_SIGN:{this.state=k.DATA;break}case P.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=k.CDATA_SECTION,this._stateCdataSection(t);}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else {this.active=false,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=true;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(P.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Ene(this.preprocessor.peek(1))?k.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){Ene(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===P.SEMICOLON&&this._err(Z.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var xne=new Set([y.DD,y.DT,y.LI,y.OPTGROUP,y.OPTION,y.P,y.RB,y.RP,y.RT,y.RTC]),vne=new Set([...xne,y.CAPTION,y.COLGROUP,y.TBODY,y.TD,y.TFOOT,y.TH,y.THEAD,y.TR]),AI=new Set([y.APPLET,y.CAPTION,y.HTML,y.MARQUEE,y.OBJECT,y.TABLE,y.TD,y.TEMPLATE,y.TH]),A$e=new Set([...AI,y.OL,y.UL]),E$e=new Set([...AI,y.BUTTON]),wne=new Set([y.ANNOTATION_XML,y.MI,y.MN,y.MO,y.MS,y.MTEXT]),Ine=new Set([y.DESC,y.FOREIGN_OBJECT,y.TITLE]),C$e=new Set([y.TR,y.TEMPLATE,y.HTML]),R$e=new Set([y.TBODY,y.TFOOT,y.THEAD,y.TEMPLATE,y.HTML]),v$e=new Set([y.TABLE,y.TEMPLATE,y.HTML]),w$e=new Set([y.TD,y.TH]),EI=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,o){this.treeAdapter=n,this.handler=o,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=y.UNKNOWN,this.current=t;}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===y.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===me.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop];}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,true);}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,true);}replace(t,n){let o=this._indexOf(t);this.items[o]=n,o===this.stackTop&&(this.current=n);}insertAfter(t,n,o){let r=this._indexOf(t)+1;this.items.splice(r,0,n),this.tagIDs.splice(r,0,o),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop);}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==me.HTML);this.shortenToLength(Math.max(n,0));}shortenToLength(t){for(;this.stackTop>=t;){let n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t);}}popUntilElementPopped(t){let n=this._indexOf(t);this.shortenToLength(Math.max(n,0));}popUntilPopped(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(o,0));}popUntilNumberedHeaderPopped(){this.popUntilPopped(Eb,me.HTML);}popUntilTableCellPopped(){this.popUntilPopped(w$e,me.HTML);}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1);}_indexOfTagNames(t,n){for(let o=this.stackTop;o>=0;o--)if(t.has(this.tagIDs[o])&&this.treeAdapter.getNamespaceURI(this.items[o])===n)return o;return -1}clearBackTo(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(o+1);}clearBackToTableContext(){this.clearBackTo(v$e,me.HTML);}clearBackToTableBodyContext(){this.clearBackTo(R$e,me.HTML);}clearBackToTableRowContext(){this.clearBackTo(C$e,me.HTML);}remove(t){let n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,false)));}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===y.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===y.HTML}hasInDynamicScope(t,n){for(let o=this.stackTop;o>=0;o--){let r=this.tagIDs[o];switch(this.treeAdapter.getNamespaceURI(this.items[o])){case me.HTML:{if(r===t)return true;if(n.has(r))return false;break}case me.SVG:{if(Ine.has(r))return false;break}case me.MATHML:{if(wne.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,AI)}hasInListItemScope(t){return this.hasInDynamicScope(t,A$e)}hasInButtonScope(t){return this.hasInDynamicScope(t,E$e)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case me.HTML:{if(Eb.has(n))return true;if(AI.has(n))return false;break}case me.SVG:{if(Ine.has(n))return false;break}case me.MATHML:{if(wne.has(n))return false;break}}}return true}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===me.HTML)switch(this.tagIDs[n]){case t:return true;case y.TABLE:case y.HTML:return false}return true}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===me.HTML)switch(this.tagIDs[t]){case y.TBODY:case y.THEAD:case y.TFOOT:return true;case y.TABLE:case y.HTML:return false}return true}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===me.HTML)switch(this.tagIDs[n]){case t:return true;case y.OPTION:case y.OPTGROUP:break;default:return false}return true}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&xne.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&vne.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&vne.has(this.currentTagId);)this.pop();}};var Ea;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(Ea||(Ea={}));var _ne={type:Ea.Marker},CI=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null;}_getNoahArkConditionCandidates(t,n){let o=[],r=n.length,i=this.treeAdapter.getTagName(t),s=this.treeAdapter.getNamespaceURI(t);for(let a=0;a<this.entries.length;a++){let l=this.entries[a];if(l.type===Ea.Marker)break;let{element:c}=l;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===s){let d=this.treeAdapter.getAttrList(c);d.length===r&&o.push({idx:a,attrs:d});}}return o}_ensureNoahArkCondition(t){if(this.entries.length<3)return;let n=this.treeAdapter.getAttrList(t),o=this._getNoahArkConditionCandidates(t,n);if(o.length<3)return;let r=new Map(n.map(s=>[s.name,s.value])),i=0;for(let s=0;s<o.length;s++){let a=o[s];a.attrs.every(l=>r.get(l.name)===l.value)&&(i+=1,i>=3&&this.entries.splice(a.idx,1));}}insertMarker(){this.entries.unshift(_ne);}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:Ea.Element,element:t,token:n});}insertElementAfterBookmark(t,n){let o=this.entries.indexOf(this.bookmark);this.entries.splice(o,0,{type:Ea.Element,element:t,token:n});}removeEntry(t){let n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1);}clearToLastMarker(){let t=this.entries.indexOf(_ne);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let n=this.entries.find(o=>o.type===Ea.Marker||this.treeAdapter.getTagName(o.element)===t);return n&&n.type===Ea.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===Ea.Element&&n.element===t)}};var Ca={createDocument(){return {nodeName:"#document",mode:ri.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return {nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return {nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return {nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return {nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e;},insertBefore(e,t,n){let o=e.childNodes.indexOf(n);e.childNodes.splice(o,0,t),t.parentNode=e;},setTemplateContent(e,t){e.content=t;},getTemplateContent(e){return e.content},setDocumentType(e,t,n,o){let r=e.childNodes.find(i=>i.nodeName==="#documentType");if(r)r.name=t,r.publicId=n,r.systemId=o;else {let i={nodeName:"#documentType",name:t,publicId:n,systemId:o,parentNode:null};Ca.appendChild(e,i);}},setDocumentMode(e,t){e.mode=t;},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){let t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null;}},insertText(e,t){if(e.childNodes.length>0){let n=e.childNodes[e.childNodes.length-1];if(Ca.isTextNode(n)){n.value+=t;return}}Ca.appendChild(e,Ca.createTextNode(t));},insertTextBefore(e,t,n){let o=e.childNodes[e.childNodes.indexOf(n)-1];o&&Ca.isTextNode(o)?o.value+=t:Ca.insertBefore(e,Ca.createTextNode(t),n);},adoptAttributes(e,t){let n=new Set(e.attrs.map(o=>o.name));for(let o=0;o<t.length;o++)n.has(t[o].name)||e.attrs.push(t[o]);},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t;},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t};}};var Mne="html",I$e="about:legacy-compat",x$e="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",One=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],_$e=[...One,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],P$e=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),Nne=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],M$e=[...Nne,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function Pne(e,t){return t.some(n=>e.startsWith(n))}function Lne(e){return e.name===Mne&&e.publicId===null&&(e.systemId===null||e.systemId===I$e)}function kne(e){if(e.name!==Mne)return ri.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===x$e)return ri.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),P$e.has(n))return ri.QUIRKS;let o=t===null?_$e:One;if(Pne(n,o))return ri.QUIRKS;if(o=t===null?Nne:M$e,Pne(n,o))return ri.LIMITED_QUIRKS}return ri.NO_QUIRKS}var Dne={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},N$e="definitionurl",L$e="definitionURL",k$e=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),D$e=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:me.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:me.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:me.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:me.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:me.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:me.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:me.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:me.XML}],["xml:space",{prefix:"xml",name:"space",namespace:me.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:me.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:me.XMLNS}]]),F$e=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),B$e=new Set([y.B,y.BIG,y.BLOCKQUOTE,y.BODY,y.BR,y.CENTER,y.CODE,y.DD,y.DIV,y.DL,y.DT,y.EM,y.EMBED,y.H1,y.H2,y.H3,y.H4,y.H5,y.H6,y.HEAD,y.HR,y.I,y.IMG,y.LI,y.LISTING,y.MENU,y.META,y.NOBR,y.OL,y.P,y.PRE,y.RUBY,y.S,y.SMALL,y.SPAN,y.STRONG,y.STRIKE,y.SUB,y.SUP,y.TABLE,y.TT,y.U,y.UL,y.VAR]);function Fne(e){let t=e.tagID;return t===y.FONT&&e.attrs.some(({name:o})=>o===Hc.COLOR||o===Hc.SIZE||o===Hc.FACE)||B$e.has(t)}function TF(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===N$e){e.attrs[t].name=L$e;break}}function AF(e){for(let t=0;t<e.attrs.length;t++){let n=k$e.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n);}}function RI(e){for(let t=0;t<e.attrs.length;t++){let n=D$e.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace);}}function Bne(e){let t=F$e.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=jp(e.tagName));}function U$e(e,t){return t===me.MATHML&&(e===y.MI||e===y.MO||e===y.MN||e===y.MS||e===y.MTEXT)}function H$e(e,t,n){if(t===me.MATHML&&e===y.ANNOTATION_XML){for(let o=0;o<n.length;o++)if(n[o].name===Hc.ENCODING){let r=n[o].value.toLowerCase();return r===Dne.TEXT_HTML||r===Dne.APPLICATION_XML}}return t===me.SVG&&(e===y.FOREIGN_OBJECT||e===y.DESC||e===y.TITLE)}function Une(e,t,n,o){return (!o||o===me.HTML)&&H$e(e,t,n)||(!o||o===me.MATHML)&&U$e(e,t)}var G$e="hidden",j$e=8,$$e=3,F;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET";})(F||(F={}));var V$e={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Vne=new Set([y.TABLE,y.TBODY,y.TFOOT,y.THEAD,y.TR]),Gne={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:Ca,onParseError:null},Ob=class{constructor(t,n,o=null,r=null){this.fragmentContext=o,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=F.INITIAL,this.originalInsertionMode=F.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=false,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=false,this.framesetOk=true,this.skipNextNewLine=false,this.fosterParentingEnabled=false,this.options={...Gne,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=true),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new Rb(this.options,this),this.activeFormattingElements=new CI(this.treeAdapter),this.fragmentContextID=o?jp(this.treeAdapter.getTagName(o)):y.UNKNOWN,this._setContextModes(o??this.document,this.fragmentContextID),this.openElements=new EI(this.document,this.treeAdapter,this);}static parse(t,n){let o=new this(n);return o.tokenizer.write(t,true),o.document}static getFragmentParser(t,n){let o={...Gne,...n};t??(t=o.treeAdapter.createElement(W.TEMPLATE,me.HTML,[]));let r=o.treeAdapter.createElement("documentmock",me.HTML,[]),i=new this(o,r,t);return i.fragmentContextID===y.TEMPLATE&&i.tmplInsertionModeStack.unshift(F.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,o){var r;if(!this.onParseError)return;let i=(r=t.location)!==null&&r!==void 0?r:V$e,s={code:n,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:o?i.startLine:i.endLine,endCol:o?i.startCol:i.endCol,endOffset:o?i.startOffset:i.endOffset};this.onParseError(s);}onItemPush(t,n,o){var r,i;(i=(r=this.treeAdapter).onItemPush)===null||i===void 0||i.call(r,t),o&&this.openElements.stackTop>0&&this._setContextModes(t,n);}onItemPop(t,n){var o,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(r=(o=this.treeAdapter).onItemPop)===null||r===void 0||r.call(o,t,this.openElements.current),n){let i,s;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,s=this.fragmentContextID):{current:i,currentTagId:s}=this.openElements,this._setContextModes(i,s);}}_setContextModes(t,n){let o=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===me.HTML;this.currentNotInHTML=!o,this.tokenizer.inForeignNode=!o&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t);}_switchToTextParsing(t,n){this._insertElement(t,me.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=F.TEXT;}switchToPlaintextParsing(){this.insertionMode=F.TEXT,this.originalInsertionMode=F.IN_BODY,this.tokenizer.state=Or.PLAINTEXT;}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===W.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t);}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==me.HTML))switch(this.fragmentContextID){case y.TITLE:case y.TEXTAREA:{this.tokenizer.state=Or.RCDATA;break}case y.STYLE:case y.XMP:case y.IFRAME:case y.NOEMBED:case y.NOFRAMES:case y.NOSCRIPT:{this.tokenizer.state=Or.RAWTEXT;break}case y.SCRIPT:{this.tokenizer.state=Or.SCRIPT_DATA;break}case y.PLAINTEXT:{this.tokenizer.state=Or.PLAINTEXT;break}}}_setDocumentType(t){let n=t.name||"",o=t.publicId||"",r=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,o,r),t.location){let s=this.treeAdapter.getChildNodes(this.document).find(a=>this.treeAdapter.isDocumentTypeNode(a));s&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){let o=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,o);}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else {let o=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(o??this.document,t);}}_appendElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location);}_insertElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location),this.openElements.push(o,t.tagID);}_insertFakeElement(t,n){let o=this.treeAdapter.createElement(t,me.HTML,[]);this._attachElementToTree(o,null),this.openElements.push(o,n);}_insertTemplate(t){let n=this.treeAdapter.createElement(t.tagName,me.HTML,t.attrs),o=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,o),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,null);}_insertFakeRootElement(){let t=this.treeAdapter.createElement(W.HTML,me.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,y.HTML);}_appendCommentNode(t,n){let o=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,o),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location);}_insertCharacters(t){let n,o;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:o}=this._findFosterParentingLocation(),o?this.treeAdapter.insertTextBefore(n,t.chars,o):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;let r=this.treeAdapter.getChildNodes(n),i=o?r.lastIndexOf(o):r.length,s=r[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(s)){let{endLine:l,endCol:c,endOffset:d}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(s,{endLine:l,endCol:c,endOffset:d});}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}_adoptNodes(t,n){for(let o=this.treeAdapter.getFirstChild(t);o;o=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(o),this.treeAdapter.appendChild(n,o);}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){let o=n.location,r=this.treeAdapter.getTagName(t),i=n.type===Ut.END_TAG&&r===n.tagName?{endTag:{...o},endLine:o.endLine,endCol:o.endCol,endOffset:o.endOffset}:{endLine:o.startLine,endCol:o.startCol,endOffset:o.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i);}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return false;let n,o;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,o=this.fragmentContextID):{current:n,currentTagId:o}=this.openElements,t.tagID===y.SVG&&this.treeAdapter.getTagName(n)===W.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===me.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===y.MGLYPH||t.tagID===y.MALIGNMARK)&&o!==void 0&&!this._isIntegrationPoint(o,n,me.HTML)}_processToken(t){switch(t.type){case Ut.CHARACTER:{this.onCharacter(t);break}case Ut.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ut.COMMENT:{this.onComment(t);break}case Ut.DOCTYPE:{this.onDoctype(t);break}case Ut.START_TAG:{this._processStartTag(t);break}case Ut.END_TAG:{this.onEndTag(t);break}case Ut.EOF:{this.onEof(t);break}case Ut.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,o){let r=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return Une(t,r,i,o)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let n=this.activeFormattingElements.entries.findIndex(r=>r.type===Ea.Marker||this.openElements.contains(r.element)),o=n===-1?t-1:n-1;for(let r=o;r>=0;r--){let i=this.activeFormattingElements.entries[r];this._insertElement(i.token,this.treeAdapter.getNamespaceURI(i.element)),i.element=this.openElements.current;}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=F.IN_ROW;}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(y.P),this.openElements.popUntilTagNamePopped(y.P);}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case y.TR:{this.insertionMode=F.IN_ROW;return}case y.TBODY:case y.THEAD:case y.TFOOT:{this.insertionMode=F.IN_TABLE_BODY;return}case y.CAPTION:{this.insertionMode=F.IN_CAPTION;return}case y.COLGROUP:{this.insertionMode=F.IN_COLUMN_GROUP;return}case y.TABLE:{this.insertionMode=F.IN_TABLE;return}case y.BODY:{this.insertionMode=F.IN_BODY;return}case y.FRAMESET:{this.insertionMode=F.IN_FRAMESET;return}case y.SELECT:{this._resetInsertionModeForSelect(t);return}case y.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case y.HTML:{this.insertionMode=this.headElement?F.AFTER_HEAD:F.BEFORE_HEAD;return}case y.TD:case y.TH:{if(t>0){this.insertionMode=F.IN_CELL;return}break}case y.HEAD:{if(t>0){this.insertionMode=F.IN_HEAD;return}break}}this.insertionMode=F.IN_BODY;}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){let o=this.openElements.tagIDs[n];if(o===y.TEMPLATE)break;if(o===y.TABLE){this.insertionMode=F.IN_SELECT_IN_TABLE;return}}this.insertionMode=F.IN_SELECT;}_isElementCausesFosterParenting(t){return Vne.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){let n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case y.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===me.HTML)return {parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case y.TABLE:{let o=this.treeAdapter.getParentNode(n);return o?{parent:o,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return {parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t);}_isSpecialElement(t,n){let o=this.treeAdapter.getNamespaceURI(t);return Ane[o].has(n)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){Tze(this,t);return}switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{Ib(this,t);break}case F.BEFORE_HEAD:{xb(this,t);break}case F.IN_HEAD:{_b(this,t);break}case F.IN_HEAD_NO_SCRIPT:{Pb(this,t);break}case F.AFTER_HEAD:{Mb(this,t);break}case F.IN_BODY:case F.IN_CAPTION:case F.IN_CELL:case F.IN_TEMPLATE:{Wne(this,t);break}case F.TEXT:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case F.IN_TABLE:case F.IN_TABLE_BODY:case F.IN_ROW:{EF(this,t);break}case F.IN_TABLE_TEXT:{Xne(this,t);break}case F.IN_COLUMN_GROUP:{wI(this,t);break}case F.AFTER_BODY:{II(this,t);break}case F.AFTER_AFTER_BODY:{vI(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){bze(this,t);return}switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{Ib(this,t);break}case F.BEFORE_HEAD:{xb(this,t);break}case F.IN_HEAD:{_b(this,t);break}case F.IN_HEAD_NO_SCRIPT:{Pb(this,t);break}case F.AFTER_HEAD:{Mb(this,t);break}case F.TEXT:{this._insertCharacters(t);break}case F.IN_TABLE:case F.IN_TABLE_BODY:case F.IN_ROW:{EF(this,t);break}case F.IN_COLUMN_GROUP:{wI(this,t);break}case F.AFTER_BODY:{II(this,t);break}case F.AFTER_AFTER_BODY:{vI(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){CF(this,t);return}switch(this.insertionMode){case F.INITIAL:case F.BEFORE_HTML:case F.BEFORE_HEAD:case F.IN_HEAD:case F.IN_HEAD_NO_SCRIPT:case F.AFTER_HEAD:case F.IN_BODY:case F.IN_TABLE:case F.IN_CAPTION:case F.IN_COLUMN_GROUP:case F.IN_TABLE_BODY:case F.IN_ROW:case F.IN_CELL:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:case F.IN_TEMPLATE:case F.IN_FRAMESET:case F.AFTER_FRAMESET:{CF(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.AFTER_BODY:{Q$e(this,t);break}case F.AFTER_AFTER_BODY:case F.AFTER_AFTER_FRAMESET:{X$e(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case F.INITIAL:{Z$e(this,t);break}case F.BEFORE_HEAD:case F.IN_HEAD:case F.IN_HEAD_NO_SCRIPT:case F.AFTER_HEAD:{this._err(t,Z.misplacedDoctype);break}case F.IN_TABLE_TEXT:{wb(this,t);break}}}onStartTag(t){this.skipNextNewLine=false,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,Z.nonVoidHtmlElementStartTagWithTrailingSolidus);}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?Aze(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{eVe(this,t);break}case F.BEFORE_HEAD:{nVe(this,t);break}case F.IN_HEAD:{Ra(this,t);break}case F.IN_HEAD_NO_SCRIPT:{iVe(this,t);break}case F.AFTER_HEAD:{aVe(this,t);break}case F.IN_BODY:{Nr(this,t);break}case F.IN_TABLE:{Ng(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.IN_CAPTION:{oze(this,t);break}case F.IN_COLUMN_GROUP:{IF(this,t);break}case F.IN_TABLE_BODY:{PI(this,t);break}case F.IN_ROW:{MI(this,t);break}case F.IN_CELL:{sze(this,t);break}case F.IN_SELECT:{toe(this,t);break}case F.IN_SELECT_IN_TABLE:{lze(this,t);break}case F.IN_TEMPLATE:{dze(this,t);break}case F.AFTER_BODY:{pze(this,t);break}case F.IN_FRAMESET:{mze(this,t);break}case F.AFTER_FRAMESET:{gze(this,t);break}case F.AFTER_AFTER_BODY:{yze(this,t);break}case F.AFTER_AFTER_FRAMESET:{Sze(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?Eze(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{tVe(this,t);break}case F.BEFORE_HEAD:{oVe(this,t);break}case F.IN_HEAD:{rVe(this,t);break}case F.IN_HEAD_NO_SCRIPT:{sVe(this,t);break}case F.AFTER_HEAD:{lVe(this,t);break}case F.IN_BODY:{_I(this,t);break}case F.TEXT:{qVe(this,t);break}case F.IN_TABLE:{Nb(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.IN_CAPTION:{rze(this,t);break}case F.IN_COLUMN_GROUP:{ize(this,t);break}case F.IN_TABLE_BODY:{RF(this,t);break}case F.IN_ROW:{eoe(this,t);break}case F.IN_CELL:{aze(this,t);break}case F.IN_SELECT:{noe(this,t);break}case F.IN_SELECT_IN_TABLE:{cze(this,t);break}case F.IN_TEMPLATE:{uze(this,t);break}case F.AFTER_BODY:{roe(this,t);break}case F.IN_FRAMESET:{hze(this,t);break}case F.AFTER_FRAMESET:{fze(this,t);break}case F.AFTER_AFTER_BODY:{vI(this,t);break}}}onEof(t){switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{Ib(this,t);break}case F.BEFORE_HEAD:{xb(this,t);break}case F.IN_HEAD:{_b(this,t);break}case F.IN_HEAD_NO_SCRIPT:{Pb(this,t);break}case F.AFTER_HEAD:{Mb(this,t);break}case F.IN_BODY:case F.IN_TABLE:case F.IN_CAPTION:case F.IN_COLUMN_GROUP:case F.IN_TABLE_BODY:case F.IN_ROW:case F.IN_CELL:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:{Jne(this,t);break}case F.TEXT:{KVe(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.IN_TEMPLATE:{ooe(this,t);break}case F.AFTER_BODY:case F.IN_FRAMESET:case F.AFTER_FRAMESET:case F.AFTER_AFTER_BODY:case F.AFTER_AFTER_FRAMESET:{wF(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===P.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1);}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case F.IN_HEAD:case F.IN_HEAD_NO_SCRIPT:case F.AFTER_HEAD:case F.TEXT:case F.IN_COLUMN_GROUP:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:case F.IN_FRAMESET:case F.AFTER_FRAMESET:{this._insertCharacters(t);break}case F.IN_BODY:case F.IN_CAPTION:case F.IN_CELL:case F.IN_TEMPLATE:case F.AFTER_BODY:case F.AFTER_AFTER_BODY:case F.AFTER_AFTER_FRAMESET:{zne(this,t);break}case F.IN_TABLE:case F.IN_TABLE_BODY:case F.IN_ROW:{EF(this,t);break}case F.IN_TABLE_TEXT:{Qne(this,t);break}}}};function z$e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):Yne(e,t),n}function W$e(e,t){let n=null,o=e.openElements.stackTop;for(;o>=0;o--){let r=e.openElements.items[o];if(r===t.element)break;e._isSpecialElement(r,e.openElements.tagIDs[o])&&(n=r);}return n||(e.openElements.shortenToLength(Math.max(o,0)),e.activeFormattingElements.removeEntry(t)),n}function q$e(e,t,n){let o=t,r=e.openElements.getCommonAncestor(t);for(let i=0,s=r;s!==n;i++,s=r){r=e.openElements.getCommonAncestor(s);let a=e.activeFormattingElements.getElementEntry(s),l=a&&i>=$$e;!a||l?(l&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(s)):(s=K$e(e,a),o===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(o),e.treeAdapter.appendChild(s,o),o=s);}return o}function K$e(e,t){let n=e.treeAdapter.getNamespaceURI(t.element),o=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,o),t.element=o,o}function Y$e(e,t,n){let o=e.treeAdapter.getTagName(t),r=jp(o);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else {let i=e.treeAdapter.getNamespaceURI(t);r===y.TEMPLATE&&i===me.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n);}}function J$e(e,t,n){let o=e.treeAdapter.getNamespaceURI(n.element),{token:r}=n,i=e.treeAdapter.createElement(r.tagName,o,r.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,r),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,r.tagID);}function vF(e,t){for(let n=0;n<j$e;n++){let o=z$e(e,t);if(!o)break;let r=W$e(e,o);if(!r)break;e.activeFormattingElements.bookmark=o;let i=q$e(e,r,o.element),s=e.openElements.getCommonAncestor(o.element);e.treeAdapter.detachNode(i),s&&Y$e(e,s,i),J$e(e,r,o);}}function CF(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function Q$e(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function X$e(e,t){e._appendCommentNode(t,e.document);}function wF(e,t){if(e.stopped=true,t.location){let n=e.fragmentContext?0:2;for(let o=e.openElements.stackTop;o>=n;o--)e._setEndLocation(e.openElements.items[o],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let o=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(o);if(r&&!r.endTag&&(e._setEndLocation(o,t),e.openElements.stackTop>=1)){let i=e.openElements.items[1],s=e.treeAdapter.getNodeSourceCodeLocation(i);s&&!s.endTag&&e._setEndLocation(i,t);}}}}function Z$e(e,t){e._setDocumentType(t);let n=t.forceQuirks?ri.QUIRKS:kne(t);Lne(t)||e._err(t,Z.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=F.BEFORE_HTML;}function vb(e,t){e._err(t,Z.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,ri.QUIRKS),e.insertionMode=F.BEFORE_HTML,e._processToken(t);}function eVe(e,t){t.tagID===y.HTML?(e._insertElement(t,me.HTML),e.insertionMode=F.BEFORE_HEAD):Ib(e,t);}function tVe(e,t){let n=t.tagID;(n===y.HTML||n===y.HEAD||n===y.BODY||n===y.BR)&&Ib(e,t);}function Ib(e,t){e._insertFakeRootElement(),e.insertionMode=F.BEFORE_HEAD,e._processToken(t);}function nVe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.HEAD:{e._insertElement(t,me.HTML),e.headElement=e.openElements.current,e.insertionMode=F.IN_HEAD;break}default:xb(e,t);}}function oVe(e,t){let n=t.tagID;n===y.HEAD||n===y.BODY||n===y.HTML||n===y.BR?xb(e,t):e._err(t,Z.endTagWithoutMatchingOpenElement);}function xb(e,t){e._insertFakeElement(W.HEAD,y.HEAD),e.headElement=e.openElements.current,e.insertionMode=F.IN_HEAD,e._processToken(t);}function Ra(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.BASE:case y.BASEFONT:case y.BGSOUND:case y.LINK:case y.META:{e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.TITLE:{e._switchToTextParsing(t,Or.RCDATA);break}case y.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,Or.RAWTEXT):(e._insertElement(t,me.HTML),e.insertionMode=F.IN_HEAD_NO_SCRIPT);break}case y.NOFRAMES:case y.STYLE:{e._switchToTextParsing(t,Or.RAWTEXT);break}case y.SCRIPT:{e._switchToTextParsing(t,Or.SCRIPT_DATA);break}case y.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=F.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(F.IN_TEMPLATE);break}case y.HEAD:{e._err(t,Z.misplacedStartTagForHeadElement);break}default:_b(e,t);}}function rVe(e,t){switch(t.tagID){case y.HEAD:{e.openElements.pop(),e.insertionMode=F.AFTER_HEAD;break}case y.BODY:case y.BR:case y.HTML:{_b(e,t);break}case y.TEMPLATE:{$p(e,t);break}default:e._err(t,Z.endTagWithoutMatchingOpenElement);}}function $p(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==y.TEMPLATE&&e._err(t,Z.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(y.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,Z.endTagWithoutMatchingOpenElement);}function _b(e,t){e.openElements.pop(),e.insertionMode=F.AFTER_HEAD,e._processToken(t);}function iVe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.BASEFONT:case y.BGSOUND:case y.HEAD:case y.LINK:case y.META:case y.NOFRAMES:case y.STYLE:{Ra(e,t);break}case y.NOSCRIPT:{e._err(t,Z.nestedNoscriptInHead);break}default:Pb(e,t);}}function sVe(e,t){switch(t.tagID){case y.NOSCRIPT:{e.openElements.pop(),e.insertionMode=F.IN_HEAD;break}case y.BR:{Pb(e,t);break}default:e._err(t,Z.endTagWithoutMatchingOpenElement);}}function Pb(e,t){let n=t.type===Ut.EOF?Z.openElementsLeftAfterEof:Z.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=F.IN_HEAD,e._processToken(t);}function aVe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.BODY:{e._insertElement(t,me.HTML),e.framesetOk=false,e.insertionMode=F.IN_BODY;break}case y.FRAMESET:{e._insertElement(t,me.HTML),e.insertionMode=F.IN_FRAMESET;break}case y.BASE:case y.BASEFONT:case y.BGSOUND:case y.LINK:case y.META:case y.NOFRAMES:case y.SCRIPT:case y.STYLE:case y.TEMPLATE:case y.TITLE:{e._err(t,Z.abandonedHeadElementChild),e.openElements.push(e.headElement,y.HEAD),Ra(e,t),e.openElements.remove(e.headElement);break}case y.HEAD:{e._err(t,Z.misplacedStartTagForHeadElement);break}default:Mb(e,t);}}function lVe(e,t){switch(t.tagID){case y.BODY:case y.HTML:case y.BR:{Mb(e,t);break}case y.TEMPLATE:{$p(e,t);break}default:e._err(t,Z.endTagWithoutMatchingOpenElement);}}function Mb(e,t){e._insertFakeElement(W.BODY,y.BODY),e.insertionMode=F.IN_BODY,xI(e,t);}function xI(e,t){switch(t.type){case Ut.CHARACTER:{Wne(e,t);break}case Ut.WHITESPACE_CHARACTER:{zne(e,t);break}case Ut.COMMENT:{CF(e,t);break}case Ut.START_TAG:{Nr(e,t);break}case Ut.END_TAG:{_I(e,t);break}case Ut.EOF:{Jne(e,t);break}}}function zne(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function Wne(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function cVe(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function dVe(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(n,t.attrs));}function uVe(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_FRAMESET);}function pVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML);}function mVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Eb.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,me.HTML);}function hVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function gVe(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),n||(e.formElement=e.openElements.current));}function fVe(e,t){e.framesetOk=false;let n=t.tagID;for(let o=e.openElements.stackTop;o>=0;o--){let r=e.openElements.tagIDs[o];if(n===y.LI&&r===y.LI||(n===y.DD||n===y.DT)&&(r===y.DD||r===y.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==y.ADDRESS&&r!==y.DIV&&r!==y.P&&e._isSpecialElement(e.openElements.items[o],r))break}e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML);}function yVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.tokenizer.state=Or.PLAINTEXT;}function SVe(e,t){e.openElements.hasInScope(y.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(y.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.framesetOk=false;}function bVe(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(W.A);n&&(vF(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function TVe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function AVe(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(y.NOBR)&&(vF(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function EVe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function CVe(e,t){e.treeAdapter.getDocumentMode(e.document)!==ri.QUIRKS&&e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.framesetOk=false,e.insertionMode=F.IN_TABLE;}function qne(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,me.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function Kne(e){let t=SI(e,Hc.TYPE);return t!=null&&t.toLowerCase()===G$e}function RVe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,me.HTML),Kne(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function vVe(e,t){e._appendElement(t,me.HTML),t.ackSelfClosing=true;}function wVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._appendElement(t,me.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function IVe(e,t){t.tagName=W.IMG,t.tagID=y.IMG,qne(e,t);}function xVe(e,t){e._insertElement(t,me.HTML),e.skipNextNewLine=true,e.tokenizer.state=Or.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=F.TEXT;}function _Ve(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,Or.RAWTEXT);}function PVe(e,t){e.framesetOk=false,e._switchToTextParsing(t,Or.RAWTEXT);}function jne(e,t){e._switchToTextParsing(t,Or.RAWTEXT);}function MVe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===F.IN_TABLE||e.insertionMode===F.IN_CAPTION||e.insertionMode===F.IN_TABLE_BODY||e.insertionMode===F.IN_ROW||e.insertionMode===F.IN_CELL?F.IN_SELECT_IN_TABLE:F.IN_SELECT;}function OVe(e,t){e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML);}function NVe(e,t){e.openElements.hasInScope(y.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,me.HTML);}function LVe(e,t){e.openElements.hasInScope(y.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(y.RTC),e._insertElement(t,me.HTML);}function kVe(e,t){e._reconstructActiveFormattingElements(),TF(t),RI(t),t.selfClosing?e._appendElement(t,me.MATHML):e._insertElement(t,me.MATHML),t.ackSelfClosing=true;}function DVe(e,t){e._reconstructActiveFormattingElements(),AF(t),RI(t),t.selfClosing?e._appendElement(t,me.SVG):e._insertElement(t,me.SVG),t.ackSelfClosing=true;}function $ne(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML);}function Nr(e,t){switch(t.tagID){case y.I:case y.S:case y.B:case y.U:case y.EM:case y.TT:case y.BIG:case y.CODE:case y.FONT:case y.SMALL:case y.STRIKE:case y.STRONG:{TVe(e,t);break}case y.A:{bVe(e,t);break}case y.H1:case y.H2:case y.H3:case y.H4:case y.H5:case y.H6:{mVe(e,t);break}case y.P:case y.DL:case y.OL:case y.UL:case y.DIV:case y.DIR:case y.NAV:case y.MAIN:case y.MENU:case y.ASIDE:case y.CENTER:case y.FIGURE:case y.FOOTER:case y.HEADER:case y.HGROUP:case y.DIALOG:case y.DETAILS:case y.ADDRESS:case y.ARTICLE:case y.SEARCH:case y.SECTION:case y.SUMMARY:case y.FIELDSET:case y.BLOCKQUOTE:case y.FIGCAPTION:{pVe(e,t);break}case y.LI:case y.DD:case y.DT:{fVe(e,t);break}case y.BR:case y.IMG:case y.WBR:case y.AREA:case y.EMBED:case y.KEYGEN:{qne(e,t);break}case y.HR:{wVe(e,t);break}case y.RB:case y.RTC:{NVe(e,t);break}case y.RT:case y.RP:{LVe(e,t);break}case y.PRE:case y.LISTING:{hVe(e,t);break}case y.XMP:{_Ve(e,t);break}case y.SVG:{DVe(e,t);break}case y.HTML:{cVe(e,t);break}case y.BASE:case y.LINK:case y.META:case y.STYLE:case y.TITLE:case y.SCRIPT:case y.BGSOUND:case y.BASEFONT:case y.TEMPLATE:{Ra(e,t);break}case y.BODY:{dVe(e,t);break}case y.FORM:{gVe(e,t);break}case y.NOBR:{AVe(e,t);break}case y.MATH:{kVe(e,t);break}case y.TABLE:{CVe(e,t);break}case y.INPUT:{RVe(e,t);break}case y.PARAM:case y.TRACK:case y.SOURCE:{vVe(e,t);break}case y.IMAGE:{IVe(e,t);break}case y.BUTTON:{SVe(e,t);break}case y.APPLET:case y.OBJECT:case y.MARQUEE:{EVe(e,t);break}case y.IFRAME:{PVe(e,t);break}case y.SELECT:{MVe(e,t);break}case y.OPTION:case y.OPTGROUP:{OVe(e,t);break}case y.NOEMBED:case y.NOFRAMES:{jne(e,t);break}case y.FRAMESET:{uVe(e,t);break}case y.TEXTAREA:{xVe(e,t);break}case y.NOSCRIPT:{e.options.scriptingEnabled?jne(e,t):$ne(e,t);break}case y.PLAINTEXT:{yVe(e,t);break}case y.COL:case y.TH:case y.TD:case y.TR:case y.HEAD:case y.FRAME:case y.TBODY:case y.TFOOT:case y.THEAD:case y.CAPTION:case y.COLGROUP:break;default:$ne(e,t);}}function FVe(e,t){if(e.openElements.hasInScope(y.BODY)&&(e.insertionMode=F.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t);}}function BVe(e,t){e.openElements.hasInScope(y.BODY)&&(e.insertionMode=F.AFTER_BODY,roe(e,t));}function UVe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n));}function HVe(e){let t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(y.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(y.FORM):n&&e.openElements.remove(n));}function GVe(e){e.openElements.hasInButtonScope(y.P)||e._insertFakeElement(W.P,y.P),e._closePElement();}function jVe(e){e.openElements.hasInListItemScope(y.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(y.LI),e.openElements.popUntilTagNamePopped(y.LI));}function $Ve(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n));}function VVe(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function zVe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker());}function WVe(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(W.BR,y.BR),e.openElements.pop(),e.framesetOk=false;}function Yne(e,t){let n=t.tagName,o=t.tagID;for(let r=e.openElements.stackTop;r>0;r--){let i=e.openElements.items[r],s=e.openElements.tagIDs[r];if(o===s&&(o!==y.UNKNOWN||e.treeAdapter.getTagName(i)===n)){e.openElements.generateImpliedEndTagsWithExclusion(o),e.openElements.stackTop>=r&&e.openElements.shortenToLength(r);break}if(e._isSpecialElement(i,s))break}}function _I(e,t){switch(t.tagID){case y.A:case y.B:case y.I:case y.S:case y.U:case y.EM:case y.TT:case y.BIG:case y.CODE:case y.FONT:case y.NOBR:case y.SMALL:case y.STRIKE:case y.STRONG:{vF(e,t);break}case y.P:{GVe(e);break}case y.DL:case y.UL:case y.OL:case y.DIR:case y.DIV:case y.NAV:case y.PRE:case y.MAIN:case y.MENU:case y.ASIDE:case y.BUTTON:case y.CENTER:case y.FIGURE:case y.FOOTER:case y.HEADER:case y.HGROUP:case y.DIALOG:case y.ADDRESS:case y.ARTICLE:case y.DETAILS:case y.SEARCH:case y.SECTION:case y.SUMMARY:case y.LISTING:case y.FIELDSET:case y.BLOCKQUOTE:case y.FIGCAPTION:{UVe(e,t);break}case y.LI:{jVe(e);break}case y.DD:case y.DT:{$Ve(e,t);break}case y.H1:case y.H2:case y.H3:case y.H4:case y.H5:case y.H6:{VVe(e);break}case y.BR:{WVe(e);break}case y.BODY:{FVe(e,t);break}case y.HTML:{BVe(e,t);break}case y.FORM:{HVe(e);break}case y.APPLET:case y.OBJECT:case y.MARQUEE:{zVe(e,t);break}case y.TEMPLATE:{$p(e,t);break}default:Yne(e,t);}}function Jne(e,t){e.tmplInsertionModeStack.length>0?ooe(e,t):wF(e,t);}function qVe(e,t){var n;t.tagID===y.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode;}function KVe(e,t){e._err(t,Z.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function EF(e,t){if(e.openElements.currentTagId!==void 0&&Vne.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=F.IN_TABLE_TEXT,t.type){case Ut.CHARACTER:{Xne(e,t);break}case Ut.WHITESPACE_CHARACTER:{Qne(e,t);break}}else Lb(e,t);}function YVe(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_CAPTION;}function JVe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_COLUMN_GROUP;}function QVe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(W.COLGROUP,y.COLGROUP),e.insertionMode=F.IN_COLUMN_GROUP,IF(e,t);}function XVe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_TABLE_BODY;}function ZVe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(W.TBODY,y.TBODY),e.insertionMode=F.IN_TABLE_BODY,PI(e,t);}function eze(e,t){e.openElements.hasInTableScope(y.TABLE)&&(e.openElements.popUntilTagNamePopped(y.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function tze(e,t){Kne(t)?e._appendElement(t,me.HTML):Lb(e,t),t.ackSelfClosing=true;}function nze(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,me.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function Ng(e,t){switch(t.tagID){case y.TD:case y.TH:case y.TR:{ZVe(e,t);break}case y.STYLE:case y.SCRIPT:case y.TEMPLATE:{Ra(e,t);break}case y.COL:{QVe(e,t);break}case y.FORM:{nze(e,t);break}case y.TABLE:{eze(e,t);break}case y.TBODY:case y.TFOOT:case y.THEAD:{XVe(e,t);break}case y.INPUT:{tze(e,t);break}case y.CAPTION:{YVe(e,t);break}case y.COLGROUP:{JVe(e,t);break}default:Lb(e,t);}}function Nb(e,t){switch(t.tagID){case y.TABLE:{e.openElements.hasInTableScope(y.TABLE)&&(e.openElements.popUntilTagNamePopped(y.TABLE),e._resetInsertionMode());break}case y.TEMPLATE:{$p(e,t);break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:case y.TBODY:case y.TD:case y.TFOOT:case y.TH:case y.THEAD:case y.TR:break;default:Lb(e,t);}}function Lb(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=true,xI(e,t),e.fosterParentingEnabled=n;}function Qne(e,t){e.pendingCharacterTokens.push(t);}function Xne(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function wb(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)Lb(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var Zne=new Set([y.CAPTION,y.COL,y.COLGROUP,y.TBODY,y.TD,y.TFOOT,y.TH,y.THEAD,y.TR]);function oze(e,t){let n=t.tagID;Zne.has(n)?e.openElements.hasInTableScope(y.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(y.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=F.IN_TABLE,Ng(e,t)):Nr(e,t);}function rze(e,t){let n=t.tagID;switch(n){case y.CAPTION:case y.TABLE:{e.openElements.hasInTableScope(y.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(y.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=F.IN_TABLE,n===y.TABLE&&Nb(e,t));break}case y.BODY:case y.COL:case y.COLGROUP:case y.HTML:case y.TBODY:case y.TD:case y.TFOOT:case y.TH:case y.THEAD:case y.TR:break;default:_I(e,t);}}function IF(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.COL:{e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.TEMPLATE:{Ra(e,t);break}default:wI(e,t);}}function ize(e,t){switch(t.tagID){case y.COLGROUP:{e.openElements.currentTagId===y.COLGROUP&&(e.openElements.pop(),e.insertionMode=F.IN_TABLE);break}case y.TEMPLATE:{$p(e,t);break}case y.COL:break;default:wI(e,t);}}function wI(e,t){e.openElements.currentTagId===y.COLGROUP&&(e.openElements.pop(),e.insertionMode=F.IN_TABLE,e._processToken(t));}function PI(e,t){switch(t.tagID){case y.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_ROW;break}case y.TH:case y.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(W.TR,y.TR),e.insertionMode=F.IN_ROW,MI(e,t);break}case y.CAPTION:case y.COL:case y.COLGROUP:case y.TBODY:case y.TFOOT:case y.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE,Ng(e,t));break}default:Ng(e,t);}}function RF(e,t){let n=t.tagID;switch(t.tagID){case y.TBODY:case y.TFOOT:case y.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE);break}case y.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE,Nb(e,t));break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:case y.TD:case y.TH:case y.TR:break;default:Nb(e,t);}}function MI(e,t){switch(t.tagID){case y.TH:case y.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_CELL,e.activeFormattingElements.insertMarker();break}case y.CAPTION:case y.COL:case y.COLGROUP:case y.TBODY:case y.TFOOT:case y.THEAD:case y.TR:{e.openElements.hasInTableScope(y.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY,PI(e,t));break}default:Ng(e,t);}}function eoe(e,t){switch(t.tagID){case y.TR:{e.openElements.hasInTableScope(y.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY);break}case y.TABLE:{e.openElements.hasInTableScope(y.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY,RF(e,t));break}case y.TBODY:case y.TFOOT:case y.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(y.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY,RF(e,t));break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:case y.TD:case y.TH:break;default:Nb(e,t);}}function sze(e,t){let n=t.tagID;Zne.has(n)?(e.openElements.hasInTableScope(y.TD)||e.openElements.hasInTableScope(y.TH))&&(e._closeTableCell(),MI(e,t)):Nr(e,t);}function aze(e,t){let n=t.tagID;switch(n){case y.TD:case y.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=F.IN_ROW);break}case y.TABLE:case y.TBODY:case y.TFOOT:case y.THEAD:case y.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),eoe(e,t));break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:break;default:_I(e,t);}}function toe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.OPTION:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e._insertElement(t,me.HTML);break}case y.OPTGROUP:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e.openElements.currentTagId===y.OPTGROUP&&e.openElements.pop(),e._insertElement(t,me.HTML);break}case y.HR:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e.openElements.currentTagId===y.OPTGROUP&&e.openElements.pop(),e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.INPUT:case y.KEYGEN:case y.TEXTAREA:case y.SELECT:{e.openElements.hasInSelectScope(y.SELECT)&&(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode(),t.tagID!==y.SELECT&&e._processStartTag(t));break}case y.SCRIPT:case y.TEMPLATE:{Ra(e,t);break}}}function noe(e,t){switch(t.tagID){case y.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===y.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===y.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===y.OPTGROUP&&e.openElements.pop();break}case y.OPTION:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop();break}case y.SELECT:{e.openElements.hasInSelectScope(y.SELECT)&&(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode());break}case y.TEMPLATE:{$p(e,t);break}}}function lze(e,t){let n=t.tagID;n===y.CAPTION||n===y.TABLE||n===y.TBODY||n===y.TFOOT||n===y.THEAD||n===y.TR||n===y.TD||n===y.TH?(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode(),e._processStartTag(t)):toe(e,t);}function cze(e,t){let n=t.tagID;n===y.CAPTION||n===y.TABLE||n===y.TBODY||n===y.TFOOT||n===y.THEAD||n===y.TR||n===y.TD||n===y.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode(),e.onEndTag(t)):noe(e,t);}function dze(e,t){switch(t.tagID){case y.BASE:case y.BASEFONT:case y.BGSOUND:case y.LINK:case y.META:case y.NOFRAMES:case y.SCRIPT:case y.STYLE:case y.TEMPLATE:case y.TITLE:{Ra(e,t);break}case y.CAPTION:case y.COLGROUP:case y.TBODY:case y.TFOOT:case y.THEAD:{e.tmplInsertionModeStack[0]=F.IN_TABLE,e.insertionMode=F.IN_TABLE,Ng(e,t);break}case y.COL:{e.tmplInsertionModeStack[0]=F.IN_COLUMN_GROUP,e.insertionMode=F.IN_COLUMN_GROUP,IF(e,t);break}case y.TR:{e.tmplInsertionModeStack[0]=F.IN_TABLE_BODY,e.insertionMode=F.IN_TABLE_BODY,PI(e,t);break}case y.TD:case y.TH:{e.tmplInsertionModeStack[0]=F.IN_ROW,e.insertionMode=F.IN_ROW,MI(e,t);break}default:e.tmplInsertionModeStack[0]=F.IN_BODY,e.insertionMode=F.IN_BODY,Nr(e,t);}}function uze(e,t){t.tagID===y.TEMPLATE&&$p(e,t);}function ooe(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(y.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):wF(e,t);}function pze(e,t){t.tagID===y.HTML?Nr(e,t):II(e,t);}function roe(e,t){var n;if(t.tagID===y.HTML){if(e.fragmentContext||(e.insertionMode=F.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===y.HTML){e._setEndLocation(e.openElements.items[0],t);let o=e.openElements.items[1];o&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(o))===null||n===void 0)&&n.endTag)&&e._setEndLocation(o,t);}}else II(e,t);}function II(e,t){e.insertionMode=F.IN_BODY,xI(e,t);}function mze(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.FRAMESET:{e._insertElement(t,me.HTML);break}case y.FRAME:{e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.NOFRAMES:{Ra(e,t);break}}}function hze(e,t){t.tagID===y.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==y.FRAMESET&&(e.insertionMode=F.AFTER_FRAMESET));}function gze(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.NOFRAMES:{Ra(e,t);break}}}function fze(e,t){t.tagID===y.HTML&&(e.insertionMode=F.AFTER_AFTER_FRAMESET);}function yze(e,t){t.tagID===y.HTML?Nr(e,t):vI(e,t);}function vI(e,t){e.insertionMode=F.IN_BODY,xI(e,t);}function Sze(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.NOFRAMES:{Ra(e,t);break}}}function bze(e,t){t.chars=yn,e._insertCharacters(t);}function Tze(e,t){e._insertCharacters(t),e.framesetOk=false;}function ioe(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==me.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function Aze(e,t){if(Fne(t))ioe(e),e._startTagOutsideForeignContent(t);else {let n=e._getAdjustedCurrentElement(),o=e.treeAdapter.getNamespaceURI(n);o===me.MATHML?TF(t):o===me.SVG&&(Bne(t),AF(t)),RI(t),t.selfClosing?e._appendElement(t,o):e._insertElement(t,o),t.ackSelfClosing=true;}}function Eze(e,t){if(t.tagID===y.P||t.tagID===y.BR){ioe(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){let o=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(o)===me.HTML){e._endTagOutsideForeignContent(t);break}let r=e.treeAdapter.getTagName(o);if(r.toLowerCase()===t.tagName){t.tagName=r,e.openElements.shortenToLength(n);break}}}new Set([W.AREA,W.BASE,W.BASEFONT,W.BGSOUND,W.BR,W.COL,W.EMBED,W.FRAME,W.HR,W.IMG,W.INPUT,W.KEYGEN,W.LINK,W.META,W.PARAM,W.SOURCE,W.TRACK,W.WBR]);function soe(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);let o=Ob.getFragmentParser(e,n);return o.tokenizer.write(t,true),o.getFragment()}var Cze=5e3,aoe=1024;function xF(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function Rze(e){return e.nodeName==="#text"}function _F(e,t){if(t.nodesLeft<=0)return;t.nodesLeft-=1;let n=e.tagName.toLowerCase(),o,r;for(let{name:l,value:c}of e.attrs){let d=l.toLowerCase();if(d==="role"){r=c;continue}o===void 0&&(o={}),o[d]=c;}let i,s=[];for(let l of e.childNodes){if(t.nodesLeft<=0)break;if(Rze(l)){let c=l.value;if(c&&c.trim().length>0){let d=c.length>aoe?c.slice(0,aoe):c;i=i===void 0?d:`${i} ${d}`;}}else if(xF(l)){let c=_F(l,t);c!==void 0&&s.push(c);}}let a={tag:n};return r!==void 0&&(a.role=r),o!==void 0&&(a.attributes=o),i!==void 0&&(a.text=i),s.length>0&&(a.children=s),a}function PF(e){let t=soe(e),n={nodesLeft:Cze};for(let i of t.childNodes)if(xF(i)&&i.tagName.toLowerCase()==="body"){let s=_F(i,n);if(s!==void 0)return s}let o=[];for(let i of t.childNodes){if(n.nodesLeft<=0)break;if(xF(i)){let s=_F(i,n);s!==void 0&&o.push(s);}}let r={tag:"body"};return o.length>0&&(r.children=o),r}var vze=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),Vp=class{constructor(t,n,o,r,i,s){this.orgId=t;this.testId=n;this.testName=o;this.diskStorage=r;this.parentFlushResults=i;this.appGraphSink=s;}children=[];finished=false;stepFrequenciesByType={};currentResults=[];async getScreenshot(t,n){return this.diskStorage.readFile(`${tr}/${n}.jpeg`)}async getHtmlSnapshot(t,n){return this.diskStorage.readFile(`${tr}/${n}.html`)?.toString()}recordStepStat(t){t.type!=="PRESET_ACTION"?this.stepFrequenciesByType[t.type]=(this.stepFrequenciesByType[t.type]||0)+1:this.stepFrequenciesByType[t.command.type]=(this.stepFrequenciesByType[t.command.type]||0)+1;}sendFinalizedStepStats(){for(let[t,n]of Object.entries(this.stepFrequenciesByType))gt.increment("test_step_execution",n,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}flushResults(t){this.currentResults=t,this.parentFlushResults(t);}async startStep(t,n){let{step:o,parentStepIdChain:r}=t;this.recordStepStat(o);let i={step:o,status:"RUNNING",startedAt:new Date},s=[...n];this.currentResults=s;let a=new OF(this.orgId,this.testId,this.testName,i,this.diskStorage,l=>{this.flushResults([...s,l]);},r??[],this.appGraphSink);return this.children.push(a),a}async finish(t){this.finished||(this.finished=true,await Promise.all(this.children.map(n=>n.finishInternal({status:lH(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function wze(e){switch(e){case "SUCCESS":return "PASSED";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":return "RUNNING";case "IDLE":return "PENDING";default:return bt(e)}}function MF(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var OF=class{constructor(t,n,o,r,i,s,a,l){this.orgId=t;this.testId=n;this.testName=o;this.metadata=r;this.diskStorage=i;this.parentFlushResults=s;this.parentStepIdChain=a;this.appGraphSink=l;this.interactionTracer=new $d(void 0,c=>this.storeTraceAsset(c)),jd.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;attachBeforeScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.jpeg`,contents:o});}attachAfterScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.jpeg`,contents:o});}attachBeforeHtmlSnapshot(t){let{snapshotId:n,html:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.html`,contents:o});}attachAfterHtmlSnapshot(t){let{snapshotId:n,html:o,url:r,logger:i}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.html`,contents:o}),this.appGraphSink&&vze.has(this.metadata.step.type)&&this.appGraphSink({html:o,url:r,stepId:this.metadata.step.id,parentStepIdChain:[...this.parentStepIdChain],logger:i});}recordTargetAutoHeal(t){let{healType:n}=t,o=n==="AI"?"ai-target-heal":"cache-heal";gt.increment("test_event",1,[`name:${o}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:n,healedAt:new Date};}storeTraceAsset(t){this.diskStorage.storeFile({name:`${tr}/${t.snapshotId}.${t.extension??"jpeg"}`,contents:t.data});}async finishInternal(t){this.finished||(this.finished=true,this.interactionTracer.finish(),await Promise.all(this.children.map(n=>n.finish({status:wze(t.status),finishedAt:t.finishedAt}))));}recordStepDuration(t,n){if(!HA(t))return;let o=UA(t);gt.distribution("test_step_duration",n,[`type:${o}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}async finish(t){!this.finished&&t.resolvedStep!==void 0&&t.durationMs!==void 0&&this.recordStepDuration(t.resolvedStep,t.durationMs),await this.finishInternal(t.step),t.step.trace=this.interactionTracer.getRootSpan();}getResultBuilderForCurrentStep(){let t=this.metadata.step;switch(t.type){case "RESOLVED_MODULE":return n=>({...t,status:MF(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n,type:"MODULE"});case "CONDITIONAL":return n=>({...t,blocks:t.blocks.map(r=>({assertion:r.assertion,steps:zu(r.steps)})),elseSteps:t.elseSteps?zu(t.elseSteps):void 0,status:MF(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "AI_ACTION":case "AI_ACTION_DYNAMIC":case "PRESET_ACTION":case "SECTION":return n=>({...t,status:MF(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});default:return bt(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),n=new Vp(this.orgId,this.testId,this.testName,this.diskStorage,o=>{let r=t(o);this.parentFlushResults(r);});return this.children.push(n),n}};var OI=class{constructor(t,n,o,r,i,s,a){this.orgId=t;this.testId=n;this.testName=o;this.runAttemptId=r;this.metadata=i;this.diskStorage=s;this.recordVideo=a;this.diskStorage.mkdir(tr),this.harPagesStream=this.diskStorage.createFileStream(`${tr}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${tr}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${tr}/resource-usage.ndjson`),this.resourceUsageSampler=C1({keepSamples:false,onSample:l=>{this.resourceUsageStream.write(`${JSON.stringify(l)}
8325
+ `}function cje(e){return ` - ${e.path} (${e.status}, +${e.insertions??0} -${e.deletions??0})`}var Fc={searchObservedTests:"search_observed_tests",searchSegments:"search_segments",getObservedTest:"get_observed_test",getSegment:"get_segment",listObservedTestsForSegment:"list_observed_tests_for_segment",addSelectedTest:"add_selected_test",removeSelectedTest:"remove_selected_test",viewSelectedTests:"view_selected_tests",submit:"submit_selection"},Bte="ai-select",dF=200,Ute=z.object({query:z.string().min(1).max(2e3).describe("Natural-language query against App Graph node text."),k:z.number().int().min(1).max(50).describe("Max results to return. Start small (5-10) when narrowing a surface; raise for broad/exploratory searches.")}),uF=z.object({id:z.string().min(1)}),dje=z.object({testId:z.string().min(1).describe("Test id (from search_observed_tests results or the <inScopeTests> list)."),testName:z.string().min(1).max(500).optional().describe("Short human-readable test name (used in view_selected_tests output and logs)."),rationale:z.string().min(1).max(500).describe("Why this test should run for this diff. Reference the changed surface, not the test id."),relevanceLabel:Gx.describe("high = directly exercises the changed surface; medium = adjacent feature coverage; low = broad smoke or fallback.")}),uje=z.object({testId:z.string().min(1),reason:z.string().min(1).max(500).optional().describe("Why this test is being removed (for logs).")}),pje=z.object({userSummary:z.string().min(1).max(2e3).describe("Plain-English summary written directly to the developer reading their CI output. 2-3 sentences in human terms about what kinds of tests were picked and why, referencing product surface (e.g. 'payment method UI', 'invoice export', 'sign-in retry') \u2014 not segment ids, observed-test ids, or tool calls. Example: 'Picked 14 tests covering payment-method UI because this PR changes the card-entry form. Also added 3 checkout end-to-end tests since payments are central to that flow.'"),anchorSegmentIds:z.array(z.string().min(1)).max(20).default([]).describe("Segment ids the agent identified as directly relevant to the change. Recorded in the plan for context.")});function Hte(e){let t={[Fc.searchObservedTests]:tool({description:"Hybrid (vector + lexical) search over previously-observed tests in the App Graph. Use to find tests by name, goal, test path, or description.",inputSchema:Ute,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.searchObservedTests({repository:e.repository,query:o.query,k:o.k});return re(j({text:JSON.stringify(r.results,null,2),section:"observed-test search results"}))},toModelOutput:({output:o})=>o}),[Fc.searchSegments]:tool({description:"Hybrid (vector + lexical) search over App Graph segments. Use to find feature surfaces, journeys, or product areas relevant to the diff.",inputSchema:Ute,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.searchSegments({repository:e.repository,query:o.query,k:o.k});return re(j({text:JSON.stringify(r.results,null,2),section:"segment search results"}))},toModelOutput:({output:o})=>o}),[Fc.getObservedTest]:tool({description:"Fetch the full record for an observed test by test id (matched realizations, coverage edges, recent execution metadata).",inputSchema:uF,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.getObservedTest(o.id);return re(j({text:JSON.stringify(r,null,2),section:`observed-test ${o.id}`}))},toModelOutput:({output:o})=>o}),[Fc.getSegment]:tool({description:"Fetch a segment's realizations and feature memberships. Use to understand a candidate anchor segment before submitting.",inputSchema:uF,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.getSegment(o.id);return re(j({text:JSON.stringify(r,null,2),section:`segment ${o.id}`}))},toModelOutput:({output:o})=>o}),[Fc.listObservedTestsForSegment]:tool({description:"List observed tests whose realizations match a given segment. Useful for enumerating coverage of an anchor segment.",inputSchema:uF,execute:async o=>{e.toolCallCount+=1;let r=await e.apiClient.listObservedTestsForSegment(o.id);return re(j({text:JSON.stringify(r,null,2),section:`observed tests for segment ${o.id}`}))},toModelOutput:({output:o})=>o}),...mje(e),[Fc.addSelectedTest]:tool({description:`Add a test to the running selection list (or replace the entry if it is already on the list). Use throughout the investigation as evidence accumulates \u2014 do not wait until the end. Capped at ${dF} entries; remove low-value picks with remove_selected_test before adding more if you hit the cap.`,inputSchema:dje,execute:async o=>(e.toolCallCount+=1,e.inScopeTestIds.has(o.testId)?e.selectedTestCandidates.size>=dF&&!e.selectedTestCandidates.has(o.testId)?re(j({text:JSON.stringify({ok:false,reason:`selection list is at the ${dF}-test cap; remove a lower-value pick first`,total:e.selectedTestCandidates.size},null,2),section:"selection rejected"})):(e.selectedTestCandidates.set(o.testId,{testId:o.testId,testName:o.testName,rationale:o.rationale,relevanceLabel:o.relevanceLabel}),re(j({text:JSON.stringify({ok:true,testId:o.testId,total:e.selectedTestCandidates.size},null,2),section:"selection updated"}))):re(j({text:JSON.stringify({ok:false,reason:`testId "${o.testId}" is not in <inScopeTests>; only those tests can run, so this pick would be discarded. Find the matching test in <inScopeTests> by path/name and add it with that exact testId.`,testId:o.testId},null,2),section:"selection rejected"}))),toModelOutput:({output:o})=>o}),[Fc.removeSelectedTest]:tool({description:"Remove a test from the running selection list. Use when new evidence shows a previously-added test is not relevant after all.",inputSchema:uje,execute:async o=>{e.toolCallCount+=1;let r=e.selectedTestCandidates.delete(o.testId);return re(j({text:JSON.stringify({removed:r,testId:o.testId,total:e.selectedTestCandidates.size},null,2),section:"selection updated"}))},toModelOutput:({output:o})=>o}),[Fc.viewSelectedTests]:tool({description:"View the current state of the selection list. Returns every added test with its rationale and relevance label, plus the running anchor-segment set. Use to check progress before submitting.",inputSchema:z.object({}),execute:async()=>{e.toolCallCount+=1;let o=Array.from(e.selectedTestCandidates.values()).map(r=>({testId:r.testId,testName:r.testName,rationale:r.rationale,relevanceLabel:r.relevanceLabel}));return re(j({text:JSON.stringify({selectedTests:o,anchorSegmentIds:Array.from(e.anchorSegmentIds),total:o.length},null,2),section:"current selection"}))},toModelOutput:({output:o})=>o}),[Fc.submit]:tool({description:"Finalize the selection: provide the userSummary and the anchor-segment set. The list of tests itself is the running state built with add_selected_test / remove_selected_test \u2014 do not pass it here. Call this exactly once when investigation is complete.",inputSchema:pje,execute:async o=>{for(let r of o.anchorSegmentIds)e.anchorSegmentIds.add(r);return e.finalSubmission={userSummary:o.userSummary,candidates:Array.from(e.selectedTestCandidates.values()),anchorSegmentIds:Array.from(e.anchorSegmentIds)},re(j({text:JSON.stringify({accepted:e.finalSubmission.candidates.length,anchorSegmentIds:e.finalSubmission.anchorSegmentIds},null,2),section:"selection submitted"}))},toModelOutput:({output:o})=>o})},n={};for(let[o,r]of Object.entries(t)){let i=No({tool:r,name:o,logger:e.logger,logPrefix:"AI Select ",agentName:Bte});n[o]=lr({tool:i,name:o,spanName:`ai_select.tool.${o}`,attributes:{"momentic.agent_name":Bte}});}return n}function mje(e){let t={};for(let n of yp){let o=n(e.codeReadingContext);t[o.name]=hje({tool:o.tool,context:e});}return t}function hje(e){let t=e.tool,n=t.execute?.bind(t);return n?{...t,execute:async(o,r)=>(e.context.toolCallCount+=1,n(o,r))}:t}var Gte="gpt-5.5-2026-04-23",Eje=25,Cje=18e4,Rje=4096;async function jte(e){let t=e.logger.bindings().sessionId??randomUUID$1(),n=e.logger.child({agentName:"ai-select",sessionId:t}),o=await mkdtemp(np.join(tmpdir$1(),`momentic-ai-select-${t}-`)),r={apiClient:e.apiClient,logger:n,repository:e.repository,codeReadingContext:{logger:n,repoRoot:e.repoRoot,baseSha:e.diff.mergeBase,headSha:e.diff.headSha,spoolDir:o},toolCallCount:0,inScopeTestIds:new Set(e.candidateTests.map(p=>p.testId)),selectedTestCandidates:new Map,anchorSegmentIds:new Set,finalSubmission:null},i=Hte(r),s=e.diff.changedFiles.reduce((p,m)=>p+(m.insertions??0)+(m.deletions??0),0),a={logger:n,streamType:"github-pr-summary",sessionId:t},l=e.generator.getAzureOpenAIModelFactory(a),c=e.generator.getOpenAIModelFactory({...a,useOpenAIResponsesWebSocket:true}),d=Date.now();try{let p=Ti({providerFallback:{logger:n,providers:[{id:"azure",model:l(Gte)},{id:"openai",model:c(Gte)}]},system:Dte(s),messages:[{role:"user",content:Fte(e.diff,e.budgetCap,e.candidateTests)}],tools:i,stopWhen:[stepCountIs(Eje),hasToolCall("submit_selection")],maxOutputTokens:Rje,abortSignal:AbortSignal.timeout(Cje),providerOptions:{openai:{reasoningEffort:"low",store:!1,textVerbosity:"low"},azure:{reasoningEffort:"low",store:!1,textVerbosity:"low"}}});await Promise.all([p.text,p.steps,p.response]);}catch(p){return n.error({err:p},"ai-select agent stream errored or was aborted"),{submission:null,reason:`AI selection failed: ${Q(p)}`,toolCallCount:r.toolCallCount,durationMs:Date.now()-d}}finally{await rm$1(o,{recursive:true,force:true}).catch(p=>{n.warn({err:p,spoolDir:o},"failed to clean ai-select spool dir");});}let u=Date.now()-d;return r.finalSubmission?{submission:r.finalSubmission,toolCallCount:r.toolCallCount,durationMs:u}:(n.error({toolCallCount:r.toolCallCount,durationMs:u},"ai-select agent finished without calling submit_selection; falling open"),{submission:null,reason:"AI selection finished without returning a result.",toolCallCount:r.toolCallCount,durationMs:u})}var Bc="/v1/app-graph",dI=class{constructor(t,n){this.apiClient=t;this.logger=n;}async claim(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/claim`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return xU.parse(n)}async getPlan(t){let n=new URLSearchParams({repository:t.repository,headSha:t.headSha}),o=await this.apiClient.sendRequest(`${Bc}/ai-select/plan?${n.toString()}`,{method:"GET",retries:1,requestTimeoutMs:1e4});return PU.parse(o)}async finalize(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/finalize`,{method:"POST",body:t,retries:2,requestTimeoutMs:3e4});return _U.parse(n)}async release(t){await this.apiClient.sendRequest(`${Bc}/ai-select/release`,{method:"POST",body:{selectionPlanKey:t},retries:1,requestTimeoutMs:5e3}).catch(n=>{this.logger.warn({err:n,selectionPlanKey:t},"Failed to release ai-select lock");});}async searchObservedTests(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/search/observed-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return $x.parse(n)}async searchSegments(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/search/segments`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return $x.parse(n)}async getObservedTest(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/observed-tests/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return MU.parse(n)}async getSegment(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/segments/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return OU.parse(n)}async listObservedTestsForSegment(t){let n=await this.apiClient.sendRequest(`${Bc}/ai-select/segments/${encodeURIComponent(t)}/observed-tests`,{method:"GET",retries:2,requestTimeoutMs:1e4});return NU.parse(n)}},vje=2e3,$te=12e4;async function Vte(e){let t=Date.now()+(e.timeoutMs??$te),n=0;for(;;){n+=1;let o=await e.client.claim(e.claim);if(o.status==="claimed")return {kind:"claimed",selectionPlanKey:o.selectionPlanKey,trackId:o.trackId};if(o.status==="ready")return {kind:"ready",plan:o.plan,planId:o.planId};if(Date.now()>=t)throw new Error(`ai-select: timed out waiting for plan after ${e.timeoutMs??$te}ms`);e.logger.info({attempt:n,claimedBy:o.claimedBy},"ai-select plan computing on another shard; polling"),await Ye(o.retryAfterMs??vje);}}async function wje(e){try{return await lI({repoRoot:e.repoRoot,explicitBase:"HEAD~1",logger:e.logger})}catch{return aF({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:null,logger:e.logger})}}async function pF(e){let t=new dI(e.apiClient,e.logger),n;try{n=await lI({repoRoot:e.repoRoot,explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch,logger:e.logger});}catch(a){let l=a instanceof Gp?a.message:`Could not assemble diff against base ref: ${Q(a)}.`,c=kte({explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch}),d=c?await aF({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:c,logger:e.logger}):null;if(d)n=d;else {let u=e.config?.onBaseUnavailable??"use-head";if(u==="fail")throw new Gp(`AI selection base unavailable and ai.select.onBaseUnavailable is "fail": ${l}`);if(u==="run-all")return {kind:"run-all",reason:l,diff:null};let p=await wje(e);if(p===null)return {kind:"run-all",reason:`Could not assemble diff against the HEAD commit's parent: ${l}`,diff:null};n=p;}}if(n.changedFiles.length===0)return {kind:"run-none",reason:"No source-code changes detected between base and head.",diff:n};let o=await Vte({client:t,claim:{repository:e.repository,headSha:n.headSha,baseRef:n.baseRef,changedFiles:n.changedFiles.map(a=>a.path),diffSummary:null,budgetCap:e.budgetCap,dryRun:e.dryRun},logger:e.logger});if(o.kind==="ready")return {kind:"ready",plan:o.plan,planId:o.planId,mode:"SELECTED",diff:n};let r=await jte({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:e.repoRoot,diff:n,budgetCap:e.budgetCap,candidateTests:e.candidateTests});if(r.submission===null)return await t.release(o.selectionPlanKey),{kind:"run-all",reason:r.reason,diff:n};let i=new Map(e.candidateTests.map(a=>[a.testId,a.testPath])),s=r.submission.candidates.map(a=>({testId:a.testId,testPath:i.get(a.testId)??null,name:a.testName??a.testId,rationale:a.rationale,relevanceLabel:a.relevanceLabel}));try{let a=await t.finalize({selectionPlanKey:o.selectionPlanKey,repository:e.repository,headSha:n.headSha,mode:"SELECTED",userSummary:r.submission.userSummary,toolCallCount:r.toolCallCount,selectedTests:s,anchorSegmentIds:r.submission.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap}});return {kind:"ready",plan:a.plan,planId:a.planId,mode:"SELECTED",diff:n}}catch(a){return e.logger.error({err:a},"ai-select finalize failed; falling back to run-all"),await t.release(o.selectionPlanKey),{kind:"run-all",reason:`Could not record selection plan: ${Q(a)}.`,diff:n}}}var zte=()=>process.exit(130),Wte=()=>process.exit(143);process.on("SIGINT",zte);process.on("SIGTERM",Wte);function Pg(){process.off("SIGINT",zte),process.off("SIGTERM",Wte);}function Ab(e){let t=e??Pje();return qte()&&t===1&&R.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function Pje(){let e=qte(),t=e?2:1;return R.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var qte=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function uI(e,t=true,n=false){let o=Lje(e),r=await Oje.which(o[0],true),i=o.slice(1),s=Mje.exec(Nje(r),i,{delay:100,silent:n});if(t)return s}var Kte="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function kje(e,{context:t}){return e instanceof Fn?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${Kte}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${Q(e)}`}function Yte(e){return e instanceof Fn?e.rawError.includes("Resource not accessible by integration")?Kte:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":Q(e)}function Jte(e,t){R.error(kje(e,t));}function Qte(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let n;try{n=new URL(t);}catch{throw new Error(`Invalid run URL: ${e}`)}let o=n.pathname.split("/").filter(i=>i.length>0),r=o.indexOf("runs");if(r===-1||r===o.length-1)throw new Error(`Could not extract run ID from URL: ${e}. Expected a URL like https://app.momentic.ai/runs/<runId>.`);return o[r+1]}return t}function pI(e){return new Promise((t,n)=>{let o=[];createReadStream(e).pipe(Dje()).on("data",r=>o.push(r)).on("end",()=>t(o)).on("error",r=>n(r));})}var Hn="2.138.3",{checkCLIVersion:Pr,getLatestCLIVersion:Xte}=$3({packageName:"momentic",currentVersion:Hn,changelogUrl:"https://github.com/momentic-ai/cli/blob/main/CHANGELOG.md",updateCommand:"npx momentic@latest upgrade"});Nve("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:Uc,setAnalyticsIdentity:mF,shutdownAnalytics:Zte}=zA({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:K3});async function ft(){try{await Re(Promise.all([$A(),gt.flush(),Zte(),XA()]),{milliseconds:5e3});}catch{}}async function Mg({tests:e,momenticFiles:t,project:n,yes:o,include:r,exclude:i,labels:s,logger:a}){let l=new Set;if(e&&e.length>0){let d=e.some(p=>Mo__default.existsSync(p)),u=cwd();d?(u!==n.rootDir&&a.warn(`Test paths resolve against the current directory ('${u}'), not the project root ('${n.rootDir}'). Run from the project root or use substring filters to avoid surprises.`),e.forEach(p=>{if(!Mo__default.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m;try{m=Mo__default.statSync(p).isDirectory();}catch(g){a.warn({err:g},`Skipping path ${p} because it cannot be read`);return}let h=En__default.resolve(p);Object.values(t.tests).filter(g=>m?g.fullFilePath.startsWith(h):g.fullFilePath===h).forEach(g=>{l.add(g.fullFilePath);});})):Object.values(t.tests).forEach(p=>{e.some(m=>p.relativePath.includes(m))&&l.add(p.fullFilePath);});}else !o&&!await xo("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1)),Object.values(t.tests).forEach(u=>{l.add(u.fullFilePath);});for(let d of l){let u=En__default.relative(n.rootDir,d);r&&!r.some(p=>new RegExp(p).test(u))&&l.delete(d),i&&i.some(p=>new RegExp(p).test(u))&&l.delete(d);}let c=Array.from(l).map(async d=>{try{let u=await hi(d,ve,t);if(Hh.gt(u.schemaVersion,at)&&a.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),s&&s.length>0){let p=u.labels||[];if(!s.some(h=>p.includes(h)))return null}return {...u,fullFilePath:d,relativeFilePath:En__default.relative(n.rootDir,d)}}catch(u){a.error(`Failed to read and resolve test at '${d}': ${Q(u)}`),process.exit(1);}});return compact(await Promise.all(c))}function tne({testDefinitions:e,quarantinedTestsMetadata:t,onlyQuarantined:n=false,skipQuarantined:o=false}){let[r,i]=partition(e,l=>l.disabled),[s,a]=partition(i,l=>l.id in t);return {testsToSkip:r,quarantinedTestsToSkip:o?s:[],testsToRun:n?[]:a,quarantinedTestsToRun:o?[]:s}}function nne({testsToRun:e,quarantinedTestsToRun:t,quarantinedTestsMetadata:n,testInputMatrix:o}){let r=[],i=(s,a,l)=>{o?o.forEach((c,d)=>{r.push({inputs:c,inputIndex:d,testDefinition:s,quarantined:a,quarantinedMetadata:l});}):r.push({inputs:void 0,testDefinition:s,quarantined:a,quarantinedMetadata:l});};return e.forEach(s=>i(s,false)),t.forEach(s=>i(s,true,n[s.id])),r}async function one({orgId:e,codeEvalTools:t,logger:n,outputDefinitions:o,testContext:r}){let i={};for(let s of o){let{name:a,value:l}=s;i[a]=await Ir({orgId:e,s:l,localTools:t,logger:n,context:r});}return i}var rne=new Set;async function ine({baseUrl:e,envName:t,devicePixelRatio:n,apiClient:o,test:r,storageClient:i,codeEvalTools:s,generator:a,orgId:l,variables:c,logger:d,customHeaders:u,testInputs:p,localBrowserConfig:m,aiSettings:h,visualDiffScreenshotStorage:g,tracer:f,runId:b,browserTypeOverride:T,attemptedRemoteBrowserProviders:A}){let C={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:ve,mode:"runner"},{controller:v,context:I}=await mw({baseUrl:e,envName:t,test:r,variables:c,logger:d,orgId:l,localBrowserConfig:m,aiSettings:h,customHeaders:u,codeEvalTools:s,storage:i,enricher:new Nd(C,a),generator:a,visualDiffScreenshotStorage:g,devicePixelRatio:n,browserTypeOverride:T,callbacks:{onNetworkPage:_=>f.onNetworkPage(_),onNetworkLogs:_=>f.onNetworkLogs(_)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:_,timestamp:x})=>{f.setActiveVideo(_,x);}}:void 0,validateBrowserType:_=>{LE(_)||(ve.warn({browserType:_,testName:r.name},"Browser required by test does not appear to be installed"),!rne.has(_)&&(rne.add(_),R.warn(`Browser ${_} does not appear to be installed. Run '${Tm(_)}' if you hit launch errors.`)));},createRemoteBrowserConnection:m.remoteBrowser?async()=>{let _=await o.createRemoteBrowserConnection({runId:b,attemptedProviders:A});return _.provider&&A?.push(_.provider),_}:void 0});try{await hw({orgId:l,test:r,testInputs:p,localTools:s,logger:d,context:I});}catch(_){try{await v.browser.cleanup();}catch(x){d.error({err:x},"Failed to clean up browser after test input resolution failed");}throw _ instanceof eb&&(R.error(_.message),process.exit(1)),_}return {controller:v,context:I}}function sne({testAdvancedSettings:e,orgSettings:t,logger:n}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!ic){let o="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(o),R.debug(o),false}return true}async function ane({attemptInputs:e,attemptFixtures:t,attemptMetadata:n,runFixtures:o,stepCallbacks:r}){let{orgId:i,userId:s,runId:a}=n,{runTracer:l,runGroupTracer:c,project:d,apiClient:u}=o,{controller:p,context:m,codeEvalTools:h,storageClient:g,logger:f,usageTracker:b,tracer:T}=t,{test:A,orgSettings:C}=e;f.info(`Running test '${A.name}' locally (run link: https://app.momentic.ai/runs/${a})`);let v={controller:p,storage:g,usageTracker:b,context:m,logger:f,codeEvalTools:h},I={orgId:i,userId:s,runId:a,testMetadata:A,steps:A.steps,beforeSteps:A.beforeSteps,afterSteps:A.afterSteps,orgSettings:C},_={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await sne({testAdvancedSettings:A.advanced,orgSettings:C.ai,logger:f})};return f9({fixtures:v,inputs:I,options:_,callbacks:{step:r??{},test:{onTestComplete:async()=>{await p.browser.cleanup(),await h.dispose();}}},testParams:{attemptTracer:T},runParams:{runTracer:l,runGroupTracer:c,project:d,apiClient:u,captureEvent:Uc,abortSignal:o.abortSignal}})}async function lne(e){let{testDefinition:t,logger:n}=e,o=new Date;try{return await Vje(e)}catch(r){dd(r);let i="Fatal error running test";n.error({err:r},i),R.error({err:r},i);let s=yu(r);return {results:[],parameters:e,failureReason:"UnknownError",failureDetails:{errorMessage:s.message,errorStack:s.stack},status:"FAILED",attempts:0,test:t,filePath:t.relativeFilePath,startedAt:o,lastAttemptStartedAt:o,finishedAt:new Date,outputs:{},quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata}}}async function Vje(e){let{testDefinition:t,project:n,apiClient:o,orgId:r,userId:i,urlOverride:s,runGroupTracer:a,logger:l,gitMetadata:c,cacheOptions:d,runId:u,testInputs:p,quarantined:m,quarantinedMetadata:h,usageTracker:g}=e,f=new kh(o,r),b=ap({logger:l,orgId:r,client:o,gitMetadata:c,regenerateCache:d.regenerateCache,alwaysSaveCache:d.alwaysSaveCache,noCache:d.noCache,isolateCachesByEnvironment:n.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:d.bustOldestCachePercentage}),{envName:T,resolvedEnv:A,environmentVariables:C,baseUrl:v}=sR({test:t,envNameOverride:e.envName,urlOverride:s,resolveEnv:U=>Zu(U,n,l)}),I=await bd({cacheStorage:b,logger:l,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:T,useSnapshotIdentityCache:n.config.fileFormat==="v2"}),_=I.steps,x=I.beforeSteps??void 0,E=I.afterSteps??void 0,O=await a.startRun({logger:l,runId:u,originalSteps:{beforeSteps:t.beforeSteps,steps:t.steps,afterSteps:t.afterSteps},testId:t.id,testName:t.name,directory:dirname(t.relativeFilePath),testDescription:t.description??void 0,testLabels:t.labels,baseUrl:v,environmentName:T,schemaVersion:t.schemaVersion,resolvedInputs:p,quarantined:m,quarantinedReason:h?.quarantinedReason,aiSettings:e.project.config.ai}),N=l.child(O.loggerBindings||{});Object.entries(O.envVarBindings||{}).forEach(([U,$])=>{C[U]=$;});let H=await zje({...e,variables:C,envName:T,resolvedEnv:A,baseUrl:v,storageClient:f,tracer:O,runGroupTracer:a,logger:N,cacheStorage:b,stepsWithCaches:_,beforeStepsWithCaches:x,afterStepsWithCaches:E,usageTracker:g});return await O.finish({logger:l,status:H.status,finishedAt:H.finishedAt,failureDetails:H.failureDetails,failureReason:H.failureReason,isFlake:H.isFlake,failureRecoveryDetails:H.failureRecoveryDetails}),{runId:O.runId,...H}}async function zje(e){let{testDefinition:t,stepsWithCaches:n,beforeStepsWithCaches:o,afterStepsWithCaches:r,project:i,regenerateGoldenFiles:s,apiClient:a,generator:l,baseUrl:c,storageClient:d,orgId:u,userId:p,envName:m,urlOverride:h,customHeaders:g,testInputs:f,variables:b,resolvedEnv:T,retriesOverride:A,devicePixelRatio:C,logUpdate:v,tracer:I,runGroupTracer:_,logger:x,cacheStorage:E,gitMetadata:O,quarantined:N,quarantinedMetadata:H,usageTracker:U}=e,$=i.config.ai?.aiFailureAnalysis??false,oe=new Date,X=new Ph(i,a,s),z={...i.config},K={envName:m,urlOverride:h,customHeaders:g,testInputs:f},q={...i.config.browser||{},...T?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},J=q.remoteBrowser===true,te=[],B,le=Math.abs(A??t.retries??i.config.retries??1),be=[];x.info({...O,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let De=0;De<=le;De++){let Oe=randomUUID(),Ne=await I.startAttempt(Oe),et=x.child(Ne.loggerBindings||{}),Be={...t,steps:cloneDeep(n),beforeSteps:cloneDeep(o),afterSteps:cloneDeep(r)};De!==0&&v("RETRY",`attempt ${De+1}/${le+1}`);let ne=new Date,Fe=new Ld({httpClient:new gi({baseUrl:a.baseUrl,apiKey:a.apiKey,logger:et,mode:"runner"}),fakerSeed:z.advanced?.fakerConstantSeed?gA:void 0});try{let{controller:ot,context:mt}=await ine({tracer:Ne,runId:I.runId,baseUrl:c,envName:m,apiClient:a,devicePixelRatio:C,logger:et,storageClient:d,codeEvalTools:Fe,test:Be,generator:l,orgId:u,variables:b,customHeaders:g,testInputs:f,localBrowserConfig:q,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:te,aiSettings:{...i.config.ai||{},...Be.advanced||{}},visualDiffScreenshotStorage:X});e.abortSignal&&(e.abortSignal.aborted?ot.executeAbortController.abort():e.abortSignal.addEventListener("abort",()=>{ot.executeAbortController.abort();},{once:!0})),B=await ane({attemptMetadata:{attemptNumber:De+1,orgId:u,userId:p,runId:I.runId},attemptFixtures:{logger:et,storageClient:d,usageTracker:U,codeEvalTools:Fe,context:mt,controller:ot,tracer:Ne},attemptInputs:{test:Be,orgSettings:z},runFixtures:{runTracer:I,runGroupTracer:_,project:i,apiClient:a,abortSignal:e.abortSignal},stepCallbacks:{onStepStart:e.onStepStart}});let xe=new Date,si={logger:x,cacheStorage:E,orgId:u,testId:t.id,environment:m,originalStepsWithCaches:{steps:cloneDeep(n),beforeSteps:cloneDeep(o),afterSteps:cloneDeep(r)},updatedStepsWithCaches:{steps:Be.steps,beforeSteps:Be.beforeSteps,afterSteps:Be.afterSteps}};await $u({logger:x,cacheStorage:E,orgId:u,testId:t.id,environment:m,stepLists:si.updatedStepsWithCaches,useSnapshotIdentityCache:i.config.fileFormat==="v2"}),B?.status==="PASSED"?await Vu(si):B?.status==="FAILED"&&De===le&&await uh(si),await Ne.finish({logger:et,result:B}),be.unshift(B.status);let ai=await one({orgId:u,codeEvalTools:Fe,logger:et,outputDefinitions:t.outputs??[],testContext:mt}),Fs=YU(be),wa=De+1;if(B.status!=="FAILED")return {...B,runAttemptId:Oe,parameters:K,test:Be,filePath:Be.relativeFilePath,startedAt:oe,lastAttemptStartedAt:ne,finishedAt:xe,attempts:wa,baseUrl:c,outputs:ai,isFlake:Fs,quarantined:N,quarantinedMetadata:H,usedRemoteBrowser:J};let Ci=B.failedStepResult,io=Ci?.message||"Unknown failure",jn=Ci?.failureReason??I0(io)??"UnknownError",bo=et.child({failureReason:jn,errorMessage:io,numAttempts:(le+1).toString(),name:Be.name});if(De<le){bo.warn(`Retrying failed execution attempt for run: ${io}`);continue}bo.error(`Test failed after all exhausting attempts: ${io}`);let Lr=new Error(io),$n={errorMessage:io,errorStack:Lr.stack},Do;if(i.config.ai?.classification?.enabled===!0){let tn=Ci?.failureClassification;tn||(e.onStepStart?.("Classifying failure"),tn=await Wv({runTracer:I,runGroupTracer:_,outputDir:e.outputDir,orgId:u,project:i,generator:l,apiClient:a,logger:x,testPlatform:"web",aiSettings:i.config.ai,captureEvent:Uc,abortSignal:e.abortSignal,failedStepMessage:Ci?.message})),tn&&(Do=tn.classification.category,jn=tn.classification.category,$n.classification={reason:tn.classification.category,secondaryCategories:tn.classification.secondaryCategories,summary:tn.classification.reasoning,recoverable:tn.classification.recoverable,confidence:tn.classification.confidence,action:tn.action,citations:tn.classification.citations,source:"v2"});}else if($){let tn;try{if(B.results&&B.results.length>0){e.onStepStart?.("Classifying failure");let{classification:rs,aiFailureReason:L}=await eK({logger:et,browserStateStorage:Ne,generator:l,fullResults:B,failureReason:jn,error:Lr,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});tn=rs,Do=L;}}catch(rs){et.warn({err:rs},"Failed to classify test results");}tn&&($n.classification=tn,jn=Do??jn,$n.classification.source="v1");}return {...B,runAttemptId:Oe,parameters:K,failureDetails:$n,failureReason:jn,test:Be,filePath:Be.relativeFilePath,startedAt:oe,lastAttemptStartedAt:ne,finishedAt:xe,attempts:De+1,baseUrl:c,outputs:ai,quarantined:N,quarantinedMetadata:H,usedRemoteBrowser:J}}catch(ot){let mt=`Encountered fatal platform error while running test '${Be.name}'`;et.error({err:ot},mt),R.error({err:ot},mt);let xe=yu(ot);return await Ne.finish({logger:et,result:{status:"FAILED"}}),{status:"FAILED",failureDetails:{errorMessage:xe.message,errorStack:xe.stack},failureReason:"InternalPlatformError",runAttemptId:Oe,results:[],parameters:K,test:Be,filePath:Be.relativeFilePath,startedAt:oe,lastAttemptStartedAt:ne,finishedAt:new Date,attempts:De+1,baseUrl:c,outputs:{},quarantined:N,quarantinedMetadata:H,usedRemoteBrowser:J}}}throw new Error("This code should not be reachable")}function fF(e){return createHash("sha1").update(e).digest("hex")}var qje=["tab","view","mode","step"],Kje=[/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i,/^(?=.*\d)[A-Za-z0-9_-]{16,256}$/,/^\d{3,32}$/,/^[0-9A-HJKMNP-TV-Z]{26}$/];function Yje(e){return Kje.some(t=>t.test(e))}function cne(e,t={}){let n;try{n=new URL(e);}catch{return e}let o=new Set(t.queryAllowlist??qje),i=n.pathname.split("/").map(c=>c.length>0&&Yje(c)?"{id}":c).join("/"),s=[],a=Array.from(n.searchParams.keys()).sort();for(let c of a){if(!o.has(c))continue;let d=n.searchParams.getAll(c).sort();for(let u of d)s.push(`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);}let l=s.length>0?`?${s.join("&")}`:"";return `${n.protocol}//${n.host}${i}${l}`}var Jje=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),Qje=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,Xje=[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,/\b[0-9a-f]{12,64}\b/gi,/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,/\b\d{5,}\b/g,/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,16}\b/g],dne=new Set(["h1","h2","h3","h4","h5","h6"]),Zje=new Set(["input","select","textarea"]);function e$e(e){let t=e;for(let n of Xje)t=t.replace(n,"{id}");return t}function une(e){return e$e(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function t$e(e){let t=e.length;return t<=4?"txt:xs":t<=16?"txt:s":t<=64?"txt:m":t<=256?"txt:l":"txt:xl"}function n$e(e,t){return e==="href"?t.startsWith("#")?"href:hash":t.startsWith("/")?"href:rel":/^https?:\/\//.test(t)?"href:abs":/^(mailto|tel):/.test(t)?`href:${t.split(":")[0]}`:"href:other":Qje.test(t)?"@gen":une(t)}function pne(e,t,n){let o=e.tag.toLowerCase(),r=(e.role??e.attributes?.role)?.toLowerCase(),i=Math.min(Math.floor(t/4),6),s=`<${o}@${i}`;if(r!==void 0&&(s+=` role=${r}`),e.attributes!==void 0){let l=Object.keys(e.attributes).filter(c=>Jje.has(c.toLowerCase())).sort();for(let c of l){let d=c.toLowerCase();if(d==="role")continue;let u=e.attributes[c];if(u===void 0)continue;let p=n$e(d,u);s+=` ${d}=${p}`;}}n.tokens.push(s);let a=e.text?.trim();a!==void 0&&a.length>0&&(r==="button"||r==="link"||r==="heading"||o==="button"||o==="a"||o==="label"||dne.has(o)?n.tokens.push(`label=${une(a)}`):n.tokens.push(t$e(a))),(o==="button"||r==="button")&&(n.counts.buttons+=1),(o==="a"||r==="link")&&(n.counts.links+=1),(Zje.has(o)||r==="textbox"||r==="combobox")&&(n.counts.formFields+=1),(dne.has(o)||r==="heading")&&(n.counts.headings+=1);for(let l of e.children??[])pne(l,t+1,n);}function mne(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return pne(e,0,t),{tokens:t.tokens,counts:t.counts}}function hne(e,t){let n=new TextEncoder().encode(e),o=n.length,r=Math.floor(o/4),i=t>>>0,s=3432918353,a=461845907;for(let u=0;u<r;u++){let p=u*4,m=n[p]|n[p+1]<<8|n[p+2]<<16|n[p+3]<<24;m=Math.imul(m,s),m=m<<15|m>>>17,m=Math.imul(m,a),i^=m,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}let l=0,c=o&3,d=r*4;return c===3&&(l^=n[d+2]<<16),c>=2&&(l^=n[d+1]<<8),c>=1&&(l^=n[d],l=Math.imul(l,s),l=l<<15|l>>>17,l=Math.imul(l,a),i^=l),i^=o,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}var mI=128,o$e=4294967295,r$e=(()=>{let e=[];for(let t=0;t<mI;t++)e.push(hne(`perm:${t}`,0));return e})();function gne(e){let t=new Uint32Array(mI);for(let o=0;o<mI;o++)t[o]=o$e;let n=new Set(e);for(let o of n)for(let r=0;r<mI;r++){let i=hne(o,r$e[r]);i<t[r]&&(t[r]=i);}return t}var s$e=32;function yF(e){let t=cne(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:n,counts:o}=mne(e.dom),r=[`url:${t}`,`counts:buttons=${o.buttons}`,`counts:links=${o.links}`,`counts:formFields=${o.formFields}`,`counts:headings=${o.headings}`,...n],i=gne(r),s=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(s).digest("hex").slice(0,s$e),minhash:Array.from(i),canonicalUrl:t}}var a$e=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),yn="\uFFFD",P;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z";})(P||(P={}));var oi={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function hI(e){return e>=55296&&e<=57343}function fne(e){return e>=56320&&e<=57343}function yne(e,t){return (e-55296)*1024+9216+t}function gI(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function fI(e){return e>=64976&&e<=65007||a$e.has(e)}var Z;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text";})(Z||(Z={}));var c$e=65536,yI=class{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=false,this.lastChunkWritten=false,this.endOfChunkHit=false,this.bufferWaterline=c$e,this.isEol=false,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1;}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){let{line:o,col:r,offset:i}=this,s=r+n,a=i+n;return {code:t,startLine:o,endLine:o,startCol:s,endCol:s,startOffset:a,endOffset:a}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)));}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos;}_processSurrogate(t){if(this.pos!==this.html.length-1){let n=this.html.charCodeAt(this.pos+1);if(fne(n))return this.pos++,this._addGap(),yne(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,P.EOF;return this._err(Z.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0);}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=false,this.lastChunkWritten=n;}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=false;}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,false;if(n)return this.html.startsWith(t,this.pos);for(let o=0;o<t.length;o++)if((this.html.charCodeAt(this.pos+o)|32)!==t.charCodeAt(o))return false;return true}peek(t){let n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,P.EOF;let o=this.html.charCodeAt(n);return o===P.CARRIAGE_RETURN?P.LINE_FEED:o}advance(){if(this.pos++,this.isEol&&(this.isEol=false,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,P.EOF;let t=this.html.charCodeAt(this.pos);return t===P.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,P.LINE_FEED):t===P.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,hI(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===P.LINE_FEED||t===P.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){gI(t)?this._err(Z.controlCharacterInInputStream):fI(t)&&this._err(Z.noncharacterInInputStream);}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=false;}};var Ut;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION";})(Ut||(Ut={}));function SI(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}var u$e=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function Sne(e){return e>=55296&&e<=57343||e>1114111?65533:u$e.get(e)??e}function bne(e){let t=atob(e),n=t.length&-2,o=new Uint16Array(n/2);for(let r=0,i=0;r<n;r+=2){let s=t.charCodeAt(r),a=t.charCodeAt(r+1);o[i++]=s|a<<8;}return o}var SF=bne("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var Mr;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE";})(Mr||(Mr={}));var Gn;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z";})(Gn||(Gn={}));var Tne=32;function bF(e){return e>=Gn.ZERO&&e<=Gn.NINE}function p$e(e){return e>=Gn.UPPER_A&&e<=Gn.UPPER_F||e>=Gn.LOWER_A&&e<=Gn.LOWER_F}function m$e(e){return e>=Gn.UPPER_A&&e<=Gn.UPPER_Z||e>=Gn.LOWER_A&&e<=Gn.LOWER_Z||bF(e)}function h$e(e){return e===Gn.EQUALS||m$e(e)}var Jo;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity";})(Jo||(Jo={}));var Fl;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(Fl||(Fl={}));var bI=class{decodeTree;emitCodePoint;errors;constructor(t,n,o){this.decodeTree=t,this.emitCodePoint=n,this.errors=o;}state=Jo.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Fl.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=Jo.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,n){switch(this.state){case Jo.EntityStart:return t.charCodeAt(n)===Gn.NUM?(this.state=Jo.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Jo.NamedEntity,this.stateNamedEntity(t,n));case Jo.NumericStart:return this.stateNumericStart(t,n);case Jo.NumericDecimal:return this.stateNumericDecimal(t,n);case Jo.NumericHex:return this.stateNumericHex(t,n);case Jo.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|Tne)===Gn.LOWER_X?(this.state=Jo.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Jo.NumericDecimal,this.stateNumericDecimal(t,n))}stateNumericHex(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(bF(o)||p$e(o)){let r=o<=Gn.NINE?o-Gn.ZERO:(o|Tne)-Gn.LOWER_A+10;this.result=this.result*16+r,this.consumed++,n++;}else return this.emitNumericEntity(o,3)}return -1}stateNumericDecimal(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(bF(o))this.result=this.result*10+(o-Gn.ZERO),this.consumed++,n++;else return this.emitNumericEntity(o,2)}return -1}emitNumericEntity(t,n){if(this.consumed<=n)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===Gn.SEMI)this.consumed+=1;else if(this.decodeMode===Fl.Strict)return 0;return this.emitCodePoint(Sne(this.result),this.consumed),this.errors&&(t!==Gn.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){let{decodeTree:o}=this,r=o[this.treeIndex],i=(r&Mr.VALUE_LENGTH)>>14;for(;n<t.length;){if(i===0&&r&Mr.FLAG13){let a=(r&Mr.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&Mr.JUMP_TABLE;if(t.charCodeAt(n)!==l)return this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}for(;this.runConsumed<a;){if(n>=t.length)return -1;let l=this.runConsumed-1,c=o[this.treeIndex+1+(l>>1)],d=l%2===0?c&255:c>>8&255;if(t.charCodeAt(n)!==d)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}this.runConsumed=0,this.treeIndex+=1+(a>>1),r=o[this.treeIndex],i=(r&Mr.VALUE_LENGTH)>>14;}if(n>=t.length)break;let s=t.charCodeAt(n);if(s===Gn.SEMI&&i!==0&&r&Mr.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=g$e(o,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Fl.Attribute&&(i===0||h$e(s))?0:this.emitNotTerminatedNamedEntity();if(r=o[this.treeIndex],i=(r&Mr.VALUE_LENGTH)>>14,i!==0){if(s===Gn.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==Fl.Strict&&!(r&Mr.FLAG13)&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}n++,this.excess++;}return -1}emitNotTerminatedNamedEntity(){let{result:t,decodeTree:n}=this,o=(n[t]&Mr.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,o,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,o){let{decodeTree:r}=this;return this.emitCodePoint(n===1?r[t]&~(Mr.VALUE_LENGTH|Mr.FLAG13):r[t+1],o),n===3&&this.emitCodePoint(r[t+2],o),o}end(){switch(this.state){case Jo.NamedEntity:return this.result!==0&&(this.decodeMode!==Fl.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Jo.NumericDecimal:return this.emitNumericEntity(0,2);case Jo.NumericHex:return this.emitNumericEntity(0,3);case Jo.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Jo.EntityStart:return 0}}};function g$e(e,t,n,o){let r=(t&Mr.BRANCH_LENGTH)>>7,i=t&Mr.JUMP_TABLE;if(r===0)return i!==0&&o===i?n:-1;if(i){let c=o-i;return c<0||c>=r?-1:e[n+c]-1}let s=r+1>>1,a=0,l=r-1;for(;a<=l;){let c=a+l>>>1,d=c>>1,p=e[n+d]>>(c&1)*8&255;if(p<o)a=c+1;else if(p>o)l=c-1;else return e[n+s+c]}return -1}var me;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/";})(me||(me={}));var Hc;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size";})(Hc||(Hc={}));var ri;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(ri||(ri={}));var W;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp";})(W||(W={}));var y;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP";})(y||(y={}));var f$e=new Map([[W.A,y.A],[W.ADDRESS,y.ADDRESS],[W.ANNOTATION_XML,y.ANNOTATION_XML],[W.APPLET,y.APPLET],[W.AREA,y.AREA],[W.ARTICLE,y.ARTICLE],[W.ASIDE,y.ASIDE],[W.B,y.B],[W.BASE,y.BASE],[W.BASEFONT,y.BASEFONT],[W.BGSOUND,y.BGSOUND],[W.BIG,y.BIG],[W.BLOCKQUOTE,y.BLOCKQUOTE],[W.BODY,y.BODY],[W.BR,y.BR],[W.BUTTON,y.BUTTON],[W.CAPTION,y.CAPTION],[W.CENTER,y.CENTER],[W.CODE,y.CODE],[W.COL,y.COL],[W.COLGROUP,y.COLGROUP],[W.DD,y.DD],[W.DESC,y.DESC],[W.DETAILS,y.DETAILS],[W.DIALOG,y.DIALOG],[W.DIR,y.DIR],[W.DIV,y.DIV],[W.DL,y.DL],[W.DT,y.DT],[W.EM,y.EM],[W.EMBED,y.EMBED],[W.FIELDSET,y.FIELDSET],[W.FIGCAPTION,y.FIGCAPTION],[W.FIGURE,y.FIGURE],[W.FONT,y.FONT],[W.FOOTER,y.FOOTER],[W.FOREIGN_OBJECT,y.FOREIGN_OBJECT],[W.FORM,y.FORM],[W.FRAME,y.FRAME],[W.FRAMESET,y.FRAMESET],[W.H1,y.H1],[W.H2,y.H2],[W.H3,y.H3],[W.H4,y.H4],[W.H5,y.H5],[W.H6,y.H6],[W.HEAD,y.HEAD],[W.HEADER,y.HEADER],[W.HGROUP,y.HGROUP],[W.HR,y.HR],[W.HTML,y.HTML],[W.I,y.I],[W.IMG,y.IMG],[W.IMAGE,y.IMAGE],[W.INPUT,y.INPUT],[W.IFRAME,y.IFRAME],[W.KEYGEN,y.KEYGEN],[W.LABEL,y.LABEL],[W.LI,y.LI],[W.LINK,y.LINK],[W.LISTING,y.LISTING],[W.MAIN,y.MAIN],[W.MALIGNMARK,y.MALIGNMARK],[W.MARQUEE,y.MARQUEE],[W.MATH,y.MATH],[W.MENU,y.MENU],[W.META,y.META],[W.MGLYPH,y.MGLYPH],[W.MI,y.MI],[W.MO,y.MO],[W.MN,y.MN],[W.MS,y.MS],[W.MTEXT,y.MTEXT],[W.NAV,y.NAV],[W.NOBR,y.NOBR],[W.NOFRAMES,y.NOFRAMES],[W.NOEMBED,y.NOEMBED],[W.NOSCRIPT,y.NOSCRIPT],[W.OBJECT,y.OBJECT],[W.OL,y.OL],[W.OPTGROUP,y.OPTGROUP],[W.OPTION,y.OPTION],[W.P,y.P],[W.PARAM,y.PARAM],[W.PLAINTEXT,y.PLAINTEXT],[W.PRE,y.PRE],[W.RB,y.RB],[W.RP,y.RP],[W.RT,y.RT],[W.RTC,y.RTC],[W.RUBY,y.RUBY],[W.S,y.S],[W.SCRIPT,y.SCRIPT],[W.SEARCH,y.SEARCH],[W.SECTION,y.SECTION],[W.SELECT,y.SELECT],[W.SOURCE,y.SOURCE],[W.SMALL,y.SMALL],[W.SPAN,y.SPAN],[W.STRIKE,y.STRIKE],[W.STRONG,y.STRONG],[W.STYLE,y.STYLE],[W.SUB,y.SUB],[W.SUMMARY,y.SUMMARY],[W.SUP,y.SUP],[W.TABLE,y.TABLE],[W.TBODY,y.TBODY],[W.TEMPLATE,y.TEMPLATE],[W.TEXTAREA,y.TEXTAREA],[W.TFOOT,y.TFOOT],[W.TD,y.TD],[W.TH,y.TH],[W.THEAD,y.THEAD],[W.TITLE,y.TITLE],[W.TR,y.TR],[W.TRACK,y.TRACK],[W.TT,y.TT],[W.U,y.U],[W.UL,y.UL],[W.SVG,y.SVG],[W.VAR,y.VAR],[W.WBR,y.WBR],[W.XMP,y.XMP]]);function jp(e){var t;return (t=f$e.get(e))!==null&&t!==void 0?t:y.UNKNOWN}var ye=y,Ane={[me.HTML]:new Set([ye.ADDRESS,ye.APPLET,ye.AREA,ye.ARTICLE,ye.ASIDE,ye.BASE,ye.BASEFONT,ye.BGSOUND,ye.BLOCKQUOTE,ye.BODY,ye.BR,ye.BUTTON,ye.CAPTION,ye.CENTER,ye.COL,ye.COLGROUP,ye.DD,ye.DETAILS,ye.DIR,ye.DIV,ye.DL,ye.DT,ye.EMBED,ye.FIELDSET,ye.FIGCAPTION,ye.FIGURE,ye.FOOTER,ye.FORM,ye.FRAME,ye.FRAMESET,ye.H1,ye.H2,ye.H3,ye.H4,ye.H5,ye.H6,ye.HEAD,ye.HEADER,ye.HGROUP,ye.HR,ye.HTML,ye.IFRAME,ye.IMG,ye.INPUT,ye.LI,ye.LINK,ye.LISTING,ye.MAIN,ye.MARQUEE,ye.MENU,ye.META,ye.NAV,ye.NOEMBED,ye.NOFRAMES,ye.NOSCRIPT,ye.OBJECT,ye.OL,ye.P,ye.PARAM,ye.PLAINTEXT,ye.PRE,ye.SCRIPT,ye.SECTION,ye.SELECT,ye.SOURCE,ye.STYLE,ye.SUMMARY,ye.TABLE,ye.TBODY,ye.TD,ye.TEMPLATE,ye.TEXTAREA,ye.TFOOT,ye.TH,ye.THEAD,ye.TITLE,ye.TR,ye.TRACK,ye.UL,ye.WBR,ye.XMP]),[me.MATHML]:new Set([ye.MI,ye.MO,ye.MN,ye.MS,ye.MTEXT,ye.ANNOTATION_XML]),[me.SVG]:new Set([ye.TITLE,ye.FOREIGN_OBJECT,ye.DESC]),[me.XLINK]:new Set,[me.XML]:new Set,[me.XMLNS]:new Set},Eb=new Set([ye.H1,ye.H2,ye.H3,ye.H4,ye.H5,ye.H6]);new Set([W.STYLE,W.SCRIPT,W.XMP,W.IFRAME,W.NOEMBED,W.NOFRAMES,W.PLAINTEXT]);var k;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND";})(k||(k={}));var Or={DATA:k.DATA,RCDATA:k.RCDATA,RAWTEXT:k.RAWTEXT,SCRIPT_DATA:k.SCRIPT_DATA,PLAINTEXT:k.PLAINTEXT,CDATA_SECTION:k.CDATA_SECTION};function S$e(e){return e>=P.DIGIT_0&&e<=P.DIGIT_9}function Cb(e){return e>=P.LATIN_CAPITAL_A&&e<=P.LATIN_CAPITAL_Z}function b$e(e){return e>=P.LATIN_SMALL_A&&e<=P.LATIN_SMALL_Z}function uu(e){return b$e(e)||Cb(e)}function Ene(e){return uu(e)||S$e(e)}function TI(e){return e+32}function Rne(e){return e===P.SPACE||e===P.LINE_FEED||e===P.TABULATION||e===P.FORM_FEED}function Cne(e){return Rne(e)||e===P.SOLIDUS||e===P.GREATER_THAN_SIGN}function T$e(e){return e===P.NULL?Z.nullCharacterReference:e>1114111?Z.characterReferenceOutsideUnicodeRange:hI(e)?Z.surrogateCharacterReference:fI(e)?Z.noncharacterCharacterReference:gI(e)||e===P.CARRIAGE_RETURN?Z.controlCharacterReference:null}var Rb=class{constructor(t,n){this.options=t,this.handler=n,this.paused=false,this.inLoop=false,this.inForeignNode=false,this.lastStartTagName="",this.active=false,this.state=k.DATA,this.returnState=k.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new yI(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new bI(SF,(o,r)=>{this.preprocessor.pos=this.entityStartPos+r-1,this._flushCodePointConsumedAsCharacterReference(o);},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(Z.missingSemicolonAfterCharacterReference,1);},absenceOfDigitsInNumericCharacterReference:o=>{this._err(Z.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+o);},validateNumericCharacterReference:o=>{let r=T$e(o);r&&this._err(r,1);}}:void 0);}_err(t,n=0){var o,r;(r=(o=this.handler).onParseError)===null||r===void 0||r.call(o,this.preprocessor.getError(t,n));}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=true;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let t=this._consume();this._ensureHibernation()||this._callState(t);}this.inLoop=false;}}pause(){this.paused=true;}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=false,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.());}write(t,n,o){this.active=true,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||o?.();}insertHtmlAtCurrentPos(t){this.active=true,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop();}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=false,true):false}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance();}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),true):false}_createStartTagToken(){this.currentToken={type:Ut.START_TAG,tagName:"",tagID:y.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:Ut.END_TAG,tagName:"",tagID:y.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:Ut.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:Ut.DOCTYPE,name:t,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation};}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation};}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0);}_leaveAttrName(){var t,n;let o=this.currentToken;if(SI(o,this.currentAttr.name)===null){if(o.attrs.push(this.currentAttr),o.location&&this.currentLocation){let r=(t=(n=o.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue();}}else this._err(Z.duplicateAttribute);}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset);}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1);}emitCurrentTagToken(){let t=this.currentToken;this.prepareToken(t),t.tagID=jp(t.tagName),t.type===Ut.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(Z.endTagWithAttributes),t.selfClosing&&this._err(Z.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk();}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk();}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk();}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Ut.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ut.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ut.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null;}}_emitEOFToken(){let t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Ut.EOF,location:t}),this.active=false;}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n);}_emitCodePoint(t){let n=Rne(t)?Ut.WHITESPACE_CHARACTER:t===P.NULL?Ut.NULL_CHARACTER:Ut.CHARACTER;this._appendCharToCurrentCharacterToken(n,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(Ut.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=k.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Fl.Attribute:Fl.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===k.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===k.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===k.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case k.DATA:{this._stateData(t);break}case k.RCDATA:{this._stateRcdata(t);break}case k.RAWTEXT:{this._stateRawtext(t);break}case k.SCRIPT_DATA:{this._stateScriptData(t);break}case k.PLAINTEXT:{this._statePlaintext(t);break}case k.TAG_OPEN:{this._stateTagOpen(t);break}case k.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case k.TAG_NAME:{this._stateTagName(t);break}case k.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case k.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case k.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case k.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case k.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case k.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case k.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case k.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case k.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case k.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case k.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case k.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case k.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case k.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case k.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case k.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case k.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case k.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case k.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case k.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case k.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case k.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case k.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case k.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case k.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case k.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case k.BOGUS_COMMENT:{this._stateBogusComment(t);break}case k.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case k.COMMENT_START:{this._stateCommentStart(t);break}case k.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case k.COMMENT:{this._stateComment(t);break}case k.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case k.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case k.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case k.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case k.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case k.COMMENT_END:{this._stateCommentEnd(t);break}case k.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case k.DOCTYPE:{this._stateDoctype(t);break}case k.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case k.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case k.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case k.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case k.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case k.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case k.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case k.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case k.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case k.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case k.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case k.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case k.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case k.CDATA_SECTION:{this._stateCdataSection(t);break}case k.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case k.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case k.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case k.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case P.LESS_THAN_SIGN:{this.state=k.TAG_OPEN;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitCodePoint(t);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case P.AMPERSAND:{this._startCharacterReference();break}case P.LESS_THAN_SIGN:{this.state=k.RCDATA_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case P.LESS_THAN_SIGN:{this.state=k.RAWTEXT_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(uu(t))this._createStartTagToken(),this.state=k.TAG_NAME,this._stateTagName(t);else switch(t){case P.EXCLAMATION_MARK:{this.state=k.MARKUP_DECLARATION_OPEN;break}case P.SOLIDUS:{this.state=k.END_TAG_OPEN;break}case P.QUESTION_MARK:{this._err(Z.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=k.BOGUS_COMMENT,this._stateBogusComment(t);break}case P.EOF:{this._err(Z.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(Z.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=k.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(uu(t))this._createEndTagToken(),this.state=k.TAG_NAME,this._stateTagName(t);else switch(t){case P.GREATER_THAN_SIGN:{this._err(Z.missingEndTagName),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(Z.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=k.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_ATTRIBUTE_NAME;break}case P.SOLIDUS:{this.state=k.SELF_CLOSING_START_TAG;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentTagToken();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.tagName+=yn;break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(Cb(t)?TI(t):t);}}_stateRcdataLessThanSign(t){t===P.SOLIDUS?this.state=k.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=k.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){uu(t)?(this.state=k.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=k.RCDATA,this._stateRcdata(t));}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,false))return !this._ensureHibernation();this._createEndTagToken();let n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=k.BEFORE_ATTRIBUTE_NAME,false;case P.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=k.SELF_CLOSING_START_TAG,false;case P.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=k.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===P.SOLIDUS?this.state=k.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=k.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){uu(t)?(this.state=k.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=k.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case P.SOLIDUS:{this.state=k.SCRIPT_DATA_END_TAG_OPEN;break}case P.EXCLAMATION_MARK:{this.state=k.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=k.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){uu(t)?(this.state=k.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===P.HYPHEN_MINUS?(this.state=k.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===P.HYPHEN_MINUS?(this.state=k.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=k.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case P.HYPHEN_MINUS:{this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case P.GREATER_THAN_SIGN:{this.state=k.SCRIPT_DATA,this._emitChars(">");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===P.SOLIDUS?this.state=k.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:uu(t)?(this._emitChars("<"),this.state=k.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){uu(t)?(this.state=k.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(oi.SCRIPT,false)&&Cne(this.preprocessor.peek(oi.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<oi.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=k.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case P.HYPHEN_MINUS:{this._emitChars("-");break}case P.LESS_THAN_SIGN:{this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case P.GREATER_THAN_SIGN:{this.state=k.SCRIPT_DATA,this._emitChars(">");break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(yn);break}case P.EOF:{this._err(Z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===P.SOLIDUS?(this.state=k.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(oi.SCRIPT,false)&&Cne(this.preprocessor.peek(oi.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<oi.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=k.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=k.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.SOLIDUS:case P.GREATER_THAN_SIGN:case P.EOF:{this.state=k.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case P.EQUALS_SIGN:{this._err(Z.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=k.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=k.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:case P.SOLIDUS:case P.GREATER_THAN_SIGN:case P.EOF:{this._leaveAttrName(),this.state=k.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case P.EQUALS_SIGN:{this._leaveAttrName(),this.state=k.BEFORE_ATTRIBUTE_VALUE;break}case P.QUOTATION_MARK:case P.APOSTROPHE:case P.LESS_THAN_SIGN:{this._err(Z.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.name+=yn;break}default:this.currentAttr.name+=String.fromCodePoint(Cb(t)?TI(t):t);}}_stateAfterAttributeName(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.SOLIDUS:{this.state=k.SELF_CLOSING_START_TAG;break}case P.EQUALS_SIGN:{this.state=k.BEFORE_ATTRIBUTE_VALUE;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentTagToken();break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=k.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.QUOTATION_MARK:{this.state=k.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this.state=k.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingAttributeValue),this.state=k.DATA,this.emitCurrentTagToken();break}default:this.state=k.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case P.QUOTATION_MARK:{this.state=k.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.value+=yn;break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case P.APOSTROPHE:{this.state=k.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.value+=yn;break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this._leaveAttrValue(),this.state=k.BEFORE_ATTRIBUTE_NAME;break}case P.AMPERSAND:{this._startCharacterReference();break}case P.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=k.DATA,this.emitCurrentTagToken();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),this.currentAttr.value+=yn;break}case P.QUOTATION_MARK:case P.APOSTROPHE:case P.LESS_THAN_SIGN:case P.EQUALS_SIGN:case P.GRAVE_ACCENT:{this._err(Z.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this._leaveAttrValue(),this.state=k.BEFORE_ATTRIBUTE_NAME;break}case P.SOLIDUS:{this._leaveAttrValue(),this.state=k.SELF_CLOSING_START_TAG;break}case P.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=k.DATA,this.emitCurrentTagToken();break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this._err(Z.missingWhitespaceBetweenAttributes),this.state=k.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case P.GREATER_THAN_SIGN:{let n=this.currentToken;n.selfClosing=true,this.state=k.DATA,this.emitCurrentTagToken();break}case P.EOF:{this._err(Z.eofInTag),this._emitEOFToken();break}default:this._err(Z.unexpectedSolidusInTag),this.state=k.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let n=this.currentToken;switch(t){case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentComment(n);break}case P.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.data+=yn;break}default:n.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(oi.DASH_DASH,true)?(this._createCommentToken(oi.DASH_DASH.length+1),this.state=k.COMMENT_START):this._consumeSequenceIfMatch(oi.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation(oi.DOCTYPE.length+1),this.state=k.DOCTYPE):this._consumeSequenceIfMatch(oi.CDATA_START,true)?this.inForeignNode?this.state=k.CDATA_SECTION:(this._err(Z.cdataInHtmlContent),this._createCommentToken(oi.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=k.BOGUS_COMMENT):this._ensureHibernation()||(this._err(Z.incorrectlyOpenedComment),this._createCommentToken(2),this.state=k.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_START_DASH;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptClosingOfEmptyComment),this.state=k.DATA;let n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=k.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_END;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptClosingOfEmptyComment),this.state=k.DATA,this.emitCurrentComment(n);break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=k.COMMENT,this._stateComment(t);}}_stateComment(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_END_DASH;break}case P.LESS_THAN_SIGN:{n.data+="<",this.state=k.COMMENT_LESS_THAN_SIGN;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.data+=yn;break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t);}}_stateCommentLessThanSign(t){let n=this.currentToken;switch(t){case P.EXCLAMATION_MARK:{n.data+="!",this.state=k.COMMENT_LESS_THAN_SIGN_BANG;break}case P.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=k.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===P.HYPHEN_MINUS?this.state=k.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=k.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===P.HYPHEN_MINUS?this.state=k.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=k.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==P.GREATER_THAN_SIGN&&t!==P.EOF&&this._err(Z.nestedComment),this.state=k.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{this.state=k.COMMENT_END;break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=k.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let n=this.currentToken;switch(t){case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentComment(n);break}case P.EXCLAMATION_MARK:{this.state=k.COMMENT_END_BANG;break}case P.HYPHEN_MINUS:{n.data+="-";break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=k.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let n=this.currentToken;switch(t){case P.HYPHEN_MINUS:{n.data+="--!",this.state=k.COMMENT_END_DASH;break}case P.GREATER_THAN_SIGN:{this._err(Z.incorrectlyClosedComment),this.state=k.DATA,this.emitCurrentComment(n);break}case P.EOF:{this._err(Z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=k.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_DOCTYPE_NAME;break}case P.GREATER_THAN_SIGN:{this.state=k.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case P.EOF:{this._err(Z.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingWhitespaceBeforeDoctypeName),this.state=k.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(Cb(t))this._createDoctypeToken(String.fromCharCode(TI(t))),this.state=k.DOCTYPE_NAME;else switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.NULL:{this._err(Z.unexpectedNullCharacter),this._createDoctypeToken(yn),this.state=k.DOCTYPE_NAME;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypeName),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=k.DOCTYPE_NAME;}}_stateDoctypeName(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.AFTER_DOCTYPE_NAME;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.name+=yn;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(Cb(t)?TI(t):t);}}_stateAfterDoctypeName(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(oi.PUBLIC,false)?this.state=k.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(oi.SYSTEM,false)?this.state=k.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(Z.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case P.QUOTATION_MARK:{this._err(Z.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this._err(Z.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.QUOTATION_MARK:{n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{n.publicId="",this.state=k.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case P.QUOTATION_MARK:{this.state=k.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.publicId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateDoctypePublicIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case P.APOSTROPHE:{this.state=k.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.publicId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateAfterDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case P.GREATER_THAN_SIGN:{this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.QUOTATION_MARK:{this._err(Z.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this._err(Z.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.QUOTATION_MARK:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:{this.state=k.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case P.QUOTATION_MARK:{this._err(Z.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{this._err(Z.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.QUOTATION_MARK:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case P.APOSTROPHE:{n.systemId="",this.state=k.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case P.GREATER_THAN_SIGN:{this._err(Z.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.DATA,this.emitCurrentDoctype(n);break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case P.QUOTATION_MARK:{this.state=k.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.systemId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateDoctypeSystemIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case P.APOSTROPHE:{this.state=k.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case P.NULL:{this._err(Z.unexpectedNullCharacter),n.systemId+=yn;break}case P.GREATER_THAN_SIGN:{this._err(Z.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateAfterDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case P.SPACE:case P.LINE_FEED:case P.TABULATION:case P.FORM_FEED:break;case P.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.EOF:{this._err(Z.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(Z.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=k.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let n=this.currentToken;switch(t){case P.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=k.DATA;break}case P.NULL:{this._err(Z.unexpectedNullCharacter);break}case P.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case P.RIGHT_SQUARE_BRACKET:{this.state=k.CDATA_SECTION_BRACKET;break}case P.EOF:{this._err(Z.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===P.RIGHT_SQUARE_BRACKET?this.state=k.CDATA_SECTION_END:(this._emitChars("]"),this.state=k.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case P.GREATER_THAN_SIGN:{this.state=k.DATA;break}case P.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=k.CDATA_SECTION,this._stateCdataSection(t);}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else {this.active=false,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=true;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(P.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Ene(this.preprocessor.peek(1))?k.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){Ene(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===P.SEMICOLON&&this._err(Z.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var xne=new Set([y.DD,y.DT,y.LI,y.OPTGROUP,y.OPTION,y.P,y.RB,y.RP,y.RT,y.RTC]),vne=new Set([...xne,y.CAPTION,y.COLGROUP,y.TBODY,y.TD,y.TFOOT,y.TH,y.THEAD,y.TR]),AI=new Set([y.APPLET,y.CAPTION,y.HTML,y.MARQUEE,y.OBJECT,y.TABLE,y.TD,y.TEMPLATE,y.TH]),A$e=new Set([...AI,y.OL,y.UL]),E$e=new Set([...AI,y.BUTTON]),wne=new Set([y.ANNOTATION_XML,y.MI,y.MN,y.MO,y.MS,y.MTEXT]),Ine=new Set([y.DESC,y.FOREIGN_OBJECT,y.TITLE]),C$e=new Set([y.TR,y.TEMPLATE,y.HTML]),R$e=new Set([y.TBODY,y.TFOOT,y.THEAD,y.TEMPLATE,y.HTML]),v$e=new Set([y.TABLE,y.TEMPLATE,y.HTML]),w$e=new Set([y.TD,y.TH]),EI=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,o){this.treeAdapter=n,this.handler=o,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=y.UNKNOWN,this.current=t;}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===y.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===me.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop];}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,true);}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,true);}replace(t,n){let o=this._indexOf(t);this.items[o]=n,o===this.stackTop&&(this.current=n);}insertAfter(t,n,o){let r=this._indexOf(t)+1;this.items.splice(r,0,n),this.tagIDs.splice(r,0,o),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop);}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==me.HTML);this.shortenToLength(Math.max(n,0));}shortenToLength(t){for(;this.stackTop>=t;){let n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t);}}popUntilElementPopped(t){let n=this._indexOf(t);this.shortenToLength(Math.max(n,0));}popUntilPopped(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(o,0));}popUntilNumberedHeaderPopped(){this.popUntilPopped(Eb,me.HTML);}popUntilTableCellPopped(){this.popUntilPopped(w$e,me.HTML);}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1);}_indexOfTagNames(t,n){for(let o=this.stackTop;o>=0;o--)if(t.has(this.tagIDs[o])&&this.treeAdapter.getNamespaceURI(this.items[o])===n)return o;return -1}clearBackTo(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(o+1);}clearBackToTableContext(){this.clearBackTo(v$e,me.HTML);}clearBackToTableBodyContext(){this.clearBackTo(R$e,me.HTML);}clearBackToTableRowContext(){this.clearBackTo(C$e,me.HTML);}remove(t){let n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,false)));}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===y.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===y.HTML}hasInDynamicScope(t,n){for(let o=this.stackTop;o>=0;o--){let r=this.tagIDs[o];switch(this.treeAdapter.getNamespaceURI(this.items[o])){case me.HTML:{if(r===t)return true;if(n.has(r))return false;break}case me.SVG:{if(Ine.has(r))return false;break}case me.MATHML:{if(wne.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,AI)}hasInListItemScope(t){return this.hasInDynamicScope(t,A$e)}hasInButtonScope(t){return this.hasInDynamicScope(t,E$e)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case me.HTML:{if(Eb.has(n))return true;if(AI.has(n))return false;break}case me.SVG:{if(Ine.has(n))return false;break}case me.MATHML:{if(wne.has(n))return false;break}}}return true}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===me.HTML)switch(this.tagIDs[n]){case t:return true;case y.TABLE:case y.HTML:return false}return true}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===me.HTML)switch(this.tagIDs[t]){case y.TBODY:case y.THEAD:case y.TFOOT:return true;case y.TABLE:case y.HTML:return false}return true}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===me.HTML)switch(this.tagIDs[n]){case t:return true;case y.OPTION:case y.OPTGROUP:break;default:return false}return true}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&xne.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&vne.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&vne.has(this.currentTagId);)this.pop();}};var Ea;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(Ea||(Ea={}));var _ne={type:Ea.Marker},CI=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null;}_getNoahArkConditionCandidates(t,n){let o=[],r=n.length,i=this.treeAdapter.getTagName(t),s=this.treeAdapter.getNamespaceURI(t);for(let a=0;a<this.entries.length;a++){let l=this.entries[a];if(l.type===Ea.Marker)break;let{element:c}=l;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===s){let d=this.treeAdapter.getAttrList(c);d.length===r&&o.push({idx:a,attrs:d});}}return o}_ensureNoahArkCondition(t){if(this.entries.length<3)return;let n=this.treeAdapter.getAttrList(t),o=this._getNoahArkConditionCandidates(t,n);if(o.length<3)return;let r=new Map(n.map(s=>[s.name,s.value])),i=0;for(let s=0;s<o.length;s++){let a=o[s];a.attrs.every(l=>r.get(l.name)===l.value)&&(i+=1,i>=3&&this.entries.splice(a.idx,1));}}insertMarker(){this.entries.unshift(_ne);}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:Ea.Element,element:t,token:n});}insertElementAfterBookmark(t,n){let o=this.entries.indexOf(this.bookmark);this.entries.splice(o,0,{type:Ea.Element,element:t,token:n});}removeEntry(t){let n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1);}clearToLastMarker(){let t=this.entries.indexOf(_ne);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let n=this.entries.find(o=>o.type===Ea.Marker||this.treeAdapter.getTagName(o.element)===t);return n&&n.type===Ea.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===Ea.Element&&n.element===t)}};var Ca={createDocument(){return {nodeName:"#document",mode:ri.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return {nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return {nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return {nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return {nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e;},insertBefore(e,t,n){let o=e.childNodes.indexOf(n);e.childNodes.splice(o,0,t),t.parentNode=e;},setTemplateContent(e,t){e.content=t;},getTemplateContent(e){return e.content},setDocumentType(e,t,n,o){let r=e.childNodes.find(i=>i.nodeName==="#documentType");if(r)r.name=t,r.publicId=n,r.systemId=o;else {let i={nodeName:"#documentType",name:t,publicId:n,systemId:o,parentNode:null};Ca.appendChild(e,i);}},setDocumentMode(e,t){e.mode=t;},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){let t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null;}},insertText(e,t){if(e.childNodes.length>0){let n=e.childNodes[e.childNodes.length-1];if(Ca.isTextNode(n)){n.value+=t;return}}Ca.appendChild(e,Ca.createTextNode(t));},insertTextBefore(e,t,n){let o=e.childNodes[e.childNodes.indexOf(n)-1];o&&Ca.isTextNode(o)?o.value+=t:Ca.insertBefore(e,Ca.createTextNode(t),n);},adoptAttributes(e,t){let n=new Set(e.attrs.map(o=>o.name));for(let o=0;o<t.length;o++)n.has(t[o].name)||e.attrs.push(t[o]);},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t;},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t};}};var Mne="html",I$e="about:legacy-compat",x$e="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",One=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],_$e=[...One,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],P$e=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),Nne=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],M$e=[...Nne,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function Pne(e,t){return t.some(n=>e.startsWith(n))}function Lne(e){return e.name===Mne&&e.publicId===null&&(e.systemId===null||e.systemId===I$e)}function kne(e){if(e.name!==Mne)return ri.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===x$e)return ri.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),P$e.has(n))return ri.QUIRKS;let o=t===null?_$e:One;if(Pne(n,o))return ri.QUIRKS;if(o=t===null?Nne:M$e,Pne(n,o))return ri.LIMITED_QUIRKS}return ri.NO_QUIRKS}var Dne={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},N$e="definitionurl",L$e="definitionURL",k$e=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),D$e=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:me.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:me.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:me.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:me.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:me.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:me.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:me.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:me.XML}],["xml:space",{prefix:"xml",name:"space",namespace:me.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:me.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:me.XMLNS}]]),F$e=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),B$e=new Set([y.B,y.BIG,y.BLOCKQUOTE,y.BODY,y.BR,y.CENTER,y.CODE,y.DD,y.DIV,y.DL,y.DT,y.EM,y.EMBED,y.H1,y.H2,y.H3,y.H4,y.H5,y.H6,y.HEAD,y.HR,y.I,y.IMG,y.LI,y.LISTING,y.MENU,y.META,y.NOBR,y.OL,y.P,y.PRE,y.RUBY,y.S,y.SMALL,y.SPAN,y.STRONG,y.STRIKE,y.SUB,y.SUP,y.TABLE,y.TT,y.U,y.UL,y.VAR]);function Fne(e){let t=e.tagID;return t===y.FONT&&e.attrs.some(({name:o})=>o===Hc.COLOR||o===Hc.SIZE||o===Hc.FACE)||B$e.has(t)}function TF(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===N$e){e.attrs[t].name=L$e;break}}function AF(e){for(let t=0;t<e.attrs.length;t++){let n=k$e.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n);}}function RI(e){for(let t=0;t<e.attrs.length;t++){let n=D$e.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace);}}function Bne(e){let t=F$e.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=jp(e.tagName));}function U$e(e,t){return t===me.MATHML&&(e===y.MI||e===y.MO||e===y.MN||e===y.MS||e===y.MTEXT)}function H$e(e,t,n){if(t===me.MATHML&&e===y.ANNOTATION_XML){for(let o=0;o<n.length;o++)if(n[o].name===Hc.ENCODING){let r=n[o].value.toLowerCase();return r===Dne.TEXT_HTML||r===Dne.APPLICATION_XML}}return t===me.SVG&&(e===y.FOREIGN_OBJECT||e===y.DESC||e===y.TITLE)}function Une(e,t,n,o){return (!o||o===me.HTML)&&H$e(e,t,n)||(!o||o===me.MATHML)&&U$e(e,t)}var G$e="hidden",j$e=8,$$e=3,F;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET";})(F||(F={}));var V$e={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Vne=new Set([y.TABLE,y.TBODY,y.TFOOT,y.THEAD,y.TR]),Gne={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:Ca,onParseError:null},Ob=class{constructor(t,n,o=null,r=null){this.fragmentContext=o,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=F.INITIAL,this.originalInsertionMode=F.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=false,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=false,this.framesetOk=true,this.skipNextNewLine=false,this.fosterParentingEnabled=false,this.options={...Gne,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=true),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new Rb(this.options,this),this.activeFormattingElements=new CI(this.treeAdapter),this.fragmentContextID=o?jp(this.treeAdapter.getTagName(o)):y.UNKNOWN,this._setContextModes(o??this.document,this.fragmentContextID),this.openElements=new EI(this.document,this.treeAdapter,this);}static parse(t,n){let o=new this(n);return o.tokenizer.write(t,true),o.document}static getFragmentParser(t,n){let o={...Gne,...n};t??(t=o.treeAdapter.createElement(W.TEMPLATE,me.HTML,[]));let r=o.treeAdapter.createElement("documentmock",me.HTML,[]),i=new this(o,r,t);return i.fragmentContextID===y.TEMPLATE&&i.tmplInsertionModeStack.unshift(F.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,o){var r;if(!this.onParseError)return;let i=(r=t.location)!==null&&r!==void 0?r:V$e,s={code:n,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:o?i.startLine:i.endLine,endCol:o?i.startCol:i.endCol,endOffset:o?i.startOffset:i.endOffset};this.onParseError(s);}onItemPush(t,n,o){var r,i;(i=(r=this.treeAdapter).onItemPush)===null||i===void 0||i.call(r,t),o&&this.openElements.stackTop>0&&this._setContextModes(t,n);}onItemPop(t,n){var o,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(r=(o=this.treeAdapter).onItemPop)===null||r===void 0||r.call(o,t,this.openElements.current),n){let i,s;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,s=this.fragmentContextID):{current:i,currentTagId:s}=this.openElements,this._setContextModes(i,s);}}_setContextModes(t,n){let o=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===me.HTML;this.currentNotInHTML=!o,this.tokenizer.inForeignNode=!o&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t);}_switchToTextParsing(t,n){this._insertElement(t,me.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=F.TEXT;}switchToPlaintextParsing(){this.insertionMode=F.TEXT,this.originalInsertionMode=F.IN_BODY,this.tokenizer.state=Or.PLAINTEXT;}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===W.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t);}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==me.HTML))switch(this.fragmentContextID){case y.TITLE:case y.TEXTAREA:{this.tokenizer.state=Or.RCDATA;break}case y.STYLE:case y.XMP:case y.IFRAME:case y.NOEMBED:case y.NOFRAMES:case y.NOSCRIPT:{this.tokenizer.state=Or.RAWTEXT;break}case y.SCRIPT:{this.tokenizer.state=Or.SCRIPT_DATA;break}case y.PLAINTEXT:{this.tokenizer.state=Or.PLAINTEXT;break}}}_setDocumentType(t){let n=t.name||"",o=t.publicId||"",r=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,o,r),t.location){let s=this.treeAdapter.getChildNodes(this.document).find(a=>this.treeAdapter.isDocumentTypeNode(a));s&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){let o=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,o);}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else {let o=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(o??this.document,t);}}_appendElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location);}_insertElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location),this.openElements.push(o,t.tagID);}_insertFakeElement(t,n){let o=this.treeAdapter.createElement(t,me.HTML,[]);this._attachElementToTree(o,null),this.openElements.push(o,n);}_insertTemplate(t){let n=this.treeAdapter.createElement(t.tagName,me.HTML,t.attrs),o=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,o),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,null);}_insertFakeRootElement(){let t=this.treeAdapter.createElement(W.HTML,me.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,y.HTML);}_appendCommentNode(t,n){let o=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,o),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location);}_insertCharacters(t){let n,o;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:o}=this._findFosterParentingLocation(),o?this.treeAdapter.insertTextBefore(n,t.chars,o):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;let r=this.treeAdapter.getChildNodes(n),i=o?r.lastIndexOf(o):r.length,s=r[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(s)){let{endLine:l,endCol:c,endOffset:d}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(s,{endLine:l,endCol:c,endOffset:d});}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}_adoptNodes(t,n){for(let o=this.treeAdapter.getFirstChild(t);o;o=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(o),this.treeAdapter.appendChild(n,o);}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){let o=n.location,r=this.treeAdapter.getTagName(t),i=n.type===Ut.END_TAG&&r===n.tagName?{endTag:{...o},endLine:o.endLine,endCol:o.endCol,endOffset:o.endOffset}:{endLine:o.startLine,endCol:o.startCol,endOffset:o.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i);}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return false;let n,o;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,o=this.fragmentContextID):{current:n,currentTagId:o}=this.openElements,t.tagID===y.SVG&&this.treeAdapter.getTagName(n)===W.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===me.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===y.MGLYPH||t.tagID===y.MALIGNMARK)&&o!==void 0&&!this._isIntegrationPoint(o,n,me.HTML)}_processToken(t){switch(t.type){case Ut.CHARACTER:{this.onCharacter(t);break}case Ut.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ut.COMMENT:{this.onComment(t);break}case Ut.DOCTYPE:{this.onDoctype(t);break}case Ut.START_TAG:{this._processStartTag(t);break}case Ut.END_TAG:{this.onEndTag(t);break}case Ut.EOF:{this.onEof(t);break}case Ut.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,o){let r=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return Une(t,r,i,o)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let n=this.activeFormattingElements.entries.findIndex(r=>r.type===Ea.Marker||this.openElements.contains(r.element)),o=n===-1?t-1:n-1;for(let r=o;r>=0;r--){let i=this.activeFormattingElements.entries[r];this._insertElement(i.token,this.treeAdapter.getNamespaceURI(i.element)),i.element=this.openElements.current;}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=F.IN_ROW;}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(y.P),this.openElements.popUntilTagNamePopped(y.P);}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case y.TR:{this.insertionMode=F.IN_ROW;return}case y.TBODY:case y.THEAD:case y.TFOOT:{this.insertionMode=F.IN_TABLE_BODY;return}case y.CAPTION:{this.insertionMode=F.IN_CAPTION;return}case y.COLGROUP:{this.insertionMode=F.IN_COLUMN_GROUP;return}case y.TABLE:{this.insertionMode=F.IN_TABLE;return}case y.BODY:{this.insertionMode=F.IN_BODY;return}case y.FRAMESET:{this.insertionMode=F.IN_FRAMESET;return}case y.SELECT:{this._resetInsertionModeForSelect(t);return}case y.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case y.HTML:{this.insertionMode=this.headElement?F.AFTER_HEAD:F.BEFORE_HEAD;return}case y.TD:case y.TH:{if(t>0){this.insertionMode=F.IN_CELL;return}break}case y.HEAD:{if(t>0){this.insertionMode=F.IN_HEAD;return}break}}this.insertionMode=F.IN_BODY;}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){let o=this.openElements.tagIDs[n];if(o===y.TEMPLATE)break;if(o===y.TABLE){this.insertionMode=F.IN_SELECT_IN_TABLE;return}}this.insertionMode=F.IN_SELECT;}_isElementCausesFosterParenting(t){return Vne.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){let n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case y.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===me.HTML)return {parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case y.TABLE:{let o=this.treeAdapter.getParentNode(n);return o?{parent:o,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return {parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t);}_isSpecialElement(t,n){let o=this.treeAdapter.getNamespaceURI(t);return Ane[o].has(n)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){Tze(this,t);return}switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{Ib(this,t);break}case F.BEFORE_HEAD:{xb(this,t);break}case F.IN_HEAD:{_b(this,t);break}case F.IN_HEAD_NO_SCRIPT:{Pb(this,t);break}case F.AFTER_HEAD:{Mb(this,t);break}case F.IN_BODY:case F.IN_CAPTION:case F.IN_CELL:case F.IN_TEMPLATE:{Wne(this,t);break}case F.TEXT:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case F.IN_TABLE:case F.IN_TABLE_BODY:case F.IN_ROW:{EF(this,t);break}case F.IN_TABLE_TEXT:{Xne(this,t);break}case F.IN_COLUMN_GROUP:{wI(this,t);break}case F.AFTER_BODY:{II(this,t);break}case F.AFTER_AFTER_BODY:{vI(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){bze(this,t);return}switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{Ib(this,t);break}case F.BEFORE_HEAD:{xb(this,t);break}case F.IN_HEAD:{_b(this,t);break}case F.IN_HEAD_NO_SCRIPT:{Pb(this,t);break}case F.AFTER_HEAD:{Mb(this,t);break}case F.TEXT:{this._insertCharacters(t);break}case F.IN_TABLE:case F.IN_TABLE_BODY:case F.IN_ROW:{EF(this,t);break}case F.IN_COLUMN_GROUP:{wI(this,t);break}case F.AFTER_BODY:{II(this,t);break}case F.AFTER_AFTER_BODY:{vI(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){CF(this,t);return}switch(this.insertionMode){case F.INITIAL:case F.BEFORE_HTML:case F.BEFORE_HEAD:case F.IN_HEAD:case F.IN_HEAD_NO_SCRIPT:case F.AFTER_HEAD:case F.IN_BODY:case F.IN_TABLE:case F.IN_CAPTION:case F.IN_COLUMN_GROUP:case F.IN_TABLE_BODY:case F.IN_ROW:case F.IN_CELL:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:case F.IN_TEMPLATE:case F.IN_FRAMESET:case F.AFTER_FRAMESET:{CF(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.AFTER_BODY:{Q$e(this,t);break}case F.AFTER_AFTER_BODY:case F.AFTER_AFTER_FRAMESET:{X$e(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case F.INITIAL:{Z$e(this,t);break}case F.BEFORE_HEAD:case F.IN_HEAD:case F.IN_HEAD_NO_SCRIPT:case F.AFTER_HEAD:{this._err(t,Z.misplacedDoctype);break}case F.IN_TABLE_TEXT:{wb(this,t);break}}}onStartTag(t){this.skipNextNewLine=false,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,Z.nonVoidHtmlElementStartTagWithTrailingSolidus);}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?Aze(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{eVe(this,t);break}case F.BEFORE_HEAD:{nVe(this,t);break}case F.IN_HEAD:{Ra(this,t);break}case F.IN_HEAD_NO_SCRIPT:{iVe(this,t);break}case F.AFTER_HEAD:{aVe(this,t);break}case F.IN_BODY:{Nr(this,t);break}case F.IN_TABLE:{Ng(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.IN_CAPTION:{oze(this,t);break}case F.IN_COLUMN_GROUP:{IF(this,t);break}case F.IN_TABLE_BODY:{PI(this,t);break}case F.IN_ROW:{MI(this,t);break}case F.IN_CELL:{sze(this,t);break}case F.IN_SELECT:{toe(this,t);break}case F.IN_SELECT_IN_TABLE:{lze(this,t);break}case F.IN_TEMPLATE:{dze(this,t);break}case F.AFTER_BODY:{pze(this,t);break}case F.IN_FRAMESET:{mze(this,t);break}case F.AFTER_FRAMESET:{gze(this,t);break}case F.AFTER_AFTER_BODY:{yze(this,t);break}case F.AFTER_AFTER_FRAMESET:{Sze(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?Eze(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{tVe(this,t);break}case F.BEFORE_HEAD:{oVe(this,t);break}case F.IN_HEAD:{rVe(this,t);break}case F.IN_HEAD_NO_SCRIPT:{sVe(this,t);break}case F.AFTER_HEAD:{lVe(this,t);break}case F.IN_BODY:{_I(this,t);break}case F.TEXT:{qVe(this,t);break}case F.IN_TABLE:{Nb(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.IN_CAPTION:{rze(this,t);break}case F.IN_COLUMN_GROUP:{ize(this,t);break}case F.IN_TABLE_BODY:{RF(this,t);break}case F.IN_ROW:{eoe(this,t);break}case F.IN_CELL:{aze(this,t);break}case F.IN_SELECT:{noe(this,t);break}case F.IN_SELECT_IN_TABLE:{cze(this,t);break}case F.IN_TEMPLATE:{uze(this,t);break}case F.AFTER_BODY:{roe(this,t);break}case F.IN_FRAMESET:{hze(this,t);break}case F.AFTER_FRAMESET:{fze(this,t);break}case F.AFTER_AFTER_BODY:{vI(this,t);break}}}onEof(t){switch(this.insertionMode){case F.INITIAL:{vb(this,t);break}case F.BEFORE_HTML:{Ib(this,t);break}case F.BEFORE_HEAD:{xb(this,t);break}case F.IN_HEAD:{_b(this,t);break}case F.IN_HEAD_NO_SCRIPT:{Pb(this,t);break}case F.AFTER_HEAD:{Mb(this,t);break}case F.IN_BODY:case F.IN_TABLE:case F.IN_CAPTION:case F.IN_COLUMN_GROUP:case F.IN_TABLE_BODY:case F.IN_ROW:case F.IN_CELL:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:{Jne(this,t);break}case F.TEXT:{KVe(this,t);break}case F.IN_TABLE_TEXT:{wb(this,t);break}case F.IN_TEMPLATE:{ooe(this,t);break}case F.AFTER_BODY:case F.IN_FRAMESET:case F.AFTER_FRAMESET:case F.AFTER_AFTER_BODY:case F.AFTER_AFTER_FRAMESET:{wF(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===P.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1);}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case F.IN_HEAD:case F.IN_HEAD_NO_SCRIPT:case F.AFTER_HEAD:case F.TEXT:case F.IN_COLUMN_GROUP:case F.IN_SELECT:case F.IN_SELECT_IN_TABLE:case F.IN_FRAMESET:case F.AFTER_FRAMESET:{this._insertCharacters(t);break}case F.IN_BODY:case F.IN_CAPTION:case F.IN_CELL:case F.IN_TEMPLATE:case F.AFTER_BODY:case F.AFTER_AFTER_BODY:case F.AFTER_AFTER_FRAMESET:{zne(this,t);break}case F.IN_TABLE:case F.IN_TABLE_BODY:case F.IN_ROW:{EF(this,t);break}case F.IN_TABLE_TEXT:{Qne(this,t);break}}}};function z$e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):Yne(e,t),n}function W$e(e,t){let n=null,o=e.openElements.stackTop;for(;o>=0;o--){let r=e.openElements.items[o];if(r===t.element)break;e._isSpecialElement(r,e.openElements.tagIDs[o])&&(n=r);}return n||(e.openElements.shortenToLength(Math.max(o,0)),e.activeFormattingElements.removeEntry(t)),n}function q$e(e,t,n){let o=t,r=e.openElements.getCommonAncestor(t);for(let i=0,s=r;s!==n;i++,s=r){r=e.openElements.getCommonAncestor(s);let a=e.activeFormattingElements.getElementEntry(s),l=a&&i>=$$e;!a||l?(l&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(s)):(s=K$e(e,a),o===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(o),e.treeAdapter.appendChild(s,o),o=s);}return o}function K$e(e,t){let n=e.treeAdapter.getNamespaceURI(t.element),o=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,o),t.element=o,o}function Y$e(e,t,n){let o=e.treeAdapter.getTagName(t),r=jp(o);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else {let i=e.treeAdapter.getNamespaceURI(t);r===y.TEMPLATE&&i===me.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n);}}function J$e(e,t,n){let o=e.treeAdapter.getNamespaceURI(n.element),{token:r}=n,i=e.treeAdapter.createElement(r.tagName,o,r.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,r),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,r.tagID);}function vF(e,t){for(let n=0;n<j$e;n++){let o=z$e(e,t);if(!o)break;let r=W$e(e,o);if(!r)break;e.activeFormattingElements.bookmark=o;let i=q$e(e,r,o.element),s=e.openElements.getCommonAncestor(o.element);e.treeAdapter.detachNode(i),s&&Y$e(e,s,i),J$e(e,r,o);}}function CF(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function Q$e(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function X$e(e,t){e._appendCommentNode(t,e.document);}function wF(e,t){if(e.stopped=true,t.location){let n=e.fragmentContext?0:2;for(let o=e.openElements.stackTop;o>=n;o--)e._setEndLocation(e.openElements.items[o],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let o=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(o);if(r&&!r.endTag&&(e._setEndLocation(o,t),e.openElements.stackTop>=1)){let i=e.openElements.items[1],s=e.treeAdapter.getNodeSourceCodeLocation(i);s&&!s.endTag&&e._setEndLocation(i,t);}}}}function Z$e(e,t){e._setDocumentType(t);let n=t.forceQuirks?ri.QUIRKS:kne(t);Lne(t)||e._err(t,Z.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=F.BEFORE_HTML;}function vb(e,t){e._err(t,Z.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,ri.QUIRKS),e.insertionMode=F.BEFORE_HTML,e._processToken(t);}function eVe(e,t){t.tagID===y.HTML?(e._insertElement(t,me.HTML),e.insertionMode=F.BEFORE_HEAD):Ib(e,t);}function tVe(e,t){let n=t.tagID;(n===y.HTML||n===y.HEAD||n===y.BODY||n===y.BR)&&Ib(e,t);}function Ib(e,t){e._insertFakeRootElement(),e.insertionMode=F.BEFORE_HEAD,e._processToken(t);}function nVe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.HEAD:{e._insertElement(t,me.HTML),e.headElement=e.openElements.current,e.insertionMode=F.IN_HEAD;break}default:xb(e,t);}}function oVe(e,t){let n=t.tagID;n===y.HEAD||n===y.BODY||n===y.HTML||n===y.BR?xb(e,t):e._err(t,Z.endTagWithoutMatchingOpenElement);}function xb(e,t){e._insertFakeElement(W.HEAD,y.HEAD),e.headElement=e.openElements.current,e.insertionMode=F.IN_HEAD,e._processToken(t);}function Ra(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.BASE:case y.BASEFONT:case y.BGSOUND:case y.LINK:case y.META:{e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.TITLE:{e._switchToTextParsing(t,Or.RCDATA);break}case y.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,Or.RAWTEXT):(e._insertElement(t,me.HTML),e.insertionMode=F.IN_HEAD_NO_SCRIPT);break}case y.NOFRAMES:case y.STYLE:{e._switchToTextParsing(t,Or.RAWTEXT);break}case y.SCRIPT:{e._switchToTextParsing(t,Or.SCRIPT_DATA);break}case y.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=F.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(F.IN_TEMPLATE);break}case y.HEAD:{e._err(t,Z.misplacedStartTagForHeadElement);break}default:_b(e,t);}}function rVe(e,t){switch(t.tagID){case y.HEAD:{e.openElements.pop(),e.insertionMode=F.AFTER_HEAD;break}case y.BODY:case y.BR:case y.HTML:{_b(e,t);break}case y.TEMPLATE:{$p(e,t);break}default:e._err(t,Z.endTagWithoutMatchingOpenElement);}}function $p(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==y.TEMPLATE&&e._err(t,Z.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(y.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,Z.endTagWithoutMatchingOpenElement);}function _b(e,t){e.openElements.pop(),e.insertionMode=F.AFTER_HEAD,e._processToken(t);}function iVe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.BASEFONT:case y.BGSOUND:case y.HEAD:case y.LINK:case y.META:case y.NOFRAMES:case y.STYLE:{Ra(e,t);break}case y.NOSCRIPT:{e._err(t,Z.nestedNoscriptInHead);break}default:Pb(e,t);}}function sVe(e,t){switch(t.tagID){case y.NOSCRIPT:{e.openElements.pop(),e.insertionMode=F.IN_HEAD;break}case y.BR:{Pb(e,t);break}default:e._err(t,Z.endTagWithoutMatchingOpenElement);}}function Pb(e,t){let n=t.type===Ut.EOF?Z.openElementsLeftAfterEof:Z.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=F.IN_HEAD,e._processToken(t);}function aVe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.BODY:{e._insertElement(t,me.HTML),e.framesetOk=false,e.insertionMode=F.IN_BODY;break}case y.FRAMESET:{e._insertElement(t,me.HTML),e.insertionMode=F.IN_FRAMESET;break}case y.BASE:case y.BASEFONT:case y.BGSOUND:case y.LINK:case y.META:case y.NOFRAMES:case y.SCRIPT:case y.STYLE:case y.TEMPLATE:case y.TITLE:{e._err(t,Z.abandonedHeadElementChild),e.openElements.push(e.headElement,y.HEAD),Ra(e,t),e.openElements.remove(e.headElement);break}case y.HEAD:{e._err(t,Z.misplacedStartTagForHeadElement);break}default:Mb(e,t);}}function lVe(e,t){switch(t.tagID){case y.BODY:case y.HTML:case y.BR:{Mb(e,t);break}case y.TEMPLATE:{$p(e,t);break}default:e._err(t,Z.endTagWithoutMatchingOpenElement);}}function Mb(e,t){e._insertFakeElement(W.BODY,y.BODY),e.insertionMode=F.IN_BODY,xI(e,t);}function xI(e,t){switch(t.type){case Ut.CHARACTER:{Wne(e,t);break}case Ut.WHITESPACE_CHARACTER:{zne(e,t);break}case Ut.COMMENT:{CF(e,t);break}case Ut.START_TAG:{Nr(e,t);break}case Ut.END_TAG:{_I(e,t);break}case Ut.EOF:{Jne(e,t);break}}}function zne(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function Wne(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function cVe(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function dVe(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(n,t.attrs));}function uVe(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_FRAMESET);}function pVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML);}function mVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Eb.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,me.HTML);}function hVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function gVe(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),n||(e.formElement=e.openElements.current));}function fVe(e,t){e.framesetOk=false;let n=t.tagID;for(let o=e.openElements.stackTop;o>=0;o--){let r=e.openElements.tagIDs[o];if(n===y.LI&&r===y.LI||(n===y.DD||n===y.DT)&&(r===y.DD||r===y.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==y.ADDRESS&&r!==y.DIV&&r!==y.P&&e._isSpecialElement(e.openElements.items[o],r))break}e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML);}function yVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.tokenizer.state=Or.PLAINTEXT;}function SVe(e,t){e.openElements.hasInScope(y.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(y.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.framesetOk=false;}function bVe(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(W.A);n&&(vF(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function TVe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function AVe(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(y.NOBR)&&(vF(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function EVe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function CVe(e,t){e.treeAdapter.getDocumentMode(e.document)!==ri.QUIRKS&&e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.framesetOk=false,e.insertionMode=F.IN_TABLE;}function qne(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,me.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function Kne(e){let t=SI(e,Hc.TYPE);return t!=null&&t.toLowerCase()===G$e}function RVe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,me.HTML),Kne(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function vVe(e,t){e._appendElement(t,me.HTML),t.ackSelfClosing=true;}function wVe(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._appendElement(t,me.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function IVe(e,t){t.tagName=W.IMG,t.tagID=y.IMG,qne(e,t);}function xVe(e,t){e._insertElement(t,me.HTML),e.skipNextNewLine=true,e.tokenizer.state=Or.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=F.TEXT;}function _Ve(e,t){e.openElements.hasInButtonScope(y.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,Or.RAWTEXT);}function PVe(e,t){e.framesetOk=false,e._switchToTextParsing(t,Or.RAWTEXT);}function jne(e,t){e._switchToTextParsing(t,Or.RAWTEXT);}function MVe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===F.IN_TABLE||e.insertionMode===F.IN_CAPTION||e.insertionMode===F.IN_TABLE_BODY||e.insertionMode===F.IN_ROW||e.insertionMode===F.IN_CELL?F.IN_SELECT_IN_TABLE:F.IN_SELECT;}function OVe(e,t){e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML);}function NVe(e,t){e.openElements.hasInScope(y.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,me.HTML);}function LVe(e,t){e.openElements.hasInScope(y.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(y.RTC),e._insertElement(t,me.HTML);}function kVe(e,t){e._reconstructActiveFormattingElements(),TF(t),RI(t),t.selfClosing?e._appendElement(t,me.MATHML):e._insertElement(t,me.MATHML),t.ackSelfClosing=true;}function DVe(e,t){e._reconstructActiveFormattingElements(),AF(t),RI(t),t.selfClosing?e._appendElement(t,me.SVG):e._insertElement(t,me.SVG),t.ackSelfClosing=true;}function $ne(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML);}function Nr(e,t){switch(t.tagID){case y.I:case y.S:case y.B:case y.U:case y.EM:case y.TT:case y.BIG:case y.CODE:case y.FONT:case y.SMALL:case y.STRIKE:case y.STRONG:{TVe(e,t);break}case y.A:{bVe(e,t);break}case y.H1:case y.H2:case y.H3:case y.H4:case y.H5:case y.H6:{mVe(e,t);break}case y.P:case y.DL:case y.OL:case y.UL:case y.DIV:case y.DIR:case y.NAV:case y.MAIN:case y.MENU:case y.ASIDE:case y.CENTER:case y.FIGURE:case y.FOOTER:case y.HEADER:case y.HGROUP:case y.DIALOG:case y.DETAILS:case y.ADDRESS:case y.ARTICLE:case y.SEARCH:case y.SECTION:case y.SUMMARY:case y.FIELDSET:case y.BLOCKQUOTE:case y.FIGCAPTION:{pVe(e,t);break}case y.LI:case y.DD:case y.DT:{fVe(e,t);break}case y.BR:case y.IMG:case y.WBR:case y.AREA:case y.EMBED:case y.KEYGEN:{qne(e,t);break}case y.HR:{wVe(e,t);break}case y.RB:case y.RTC:{NVe(e,t);break}case y.RT:case y.RP:{LVe(e,t);break}case y.PRE:case y.LISTING:{hVe(e,t);break}case y.XMP:{_Ve(e,t);break}case y.SVG:{DVe(e,t);break}case y.HTML:{cVe(e,t);break}case y.BASE:case y.LINK:case y.META:case y.STYLE:case y.TITLE:case y.SCRIPT:case y.BGSOUND:case y.BASEFONT:case y.TEMPLATE:{Ra(e,t);break}case y.BODY:{dVe(e,t);break}case y.FORM:{gVe(e,t);break}case y.NOBR:{AVe(e,t);break}case y.MATH:{kVe(e,t);break}case y.TABLE:{CVe(e,t);break}case y.INPUT:{RVe(e,t);break}case y.PARAM:case y.TRACK:case y.SOURCE:{vVe(e,t);break}case y.IMAGE:{IVe(e,t);break}case y.BUTTON:{SVe(e,t);break}case y.APPLET:case y.OBJECT:case y.MARQUEE:{EVe(e,t);break}case y.IFRAME:{PVe(e,t);break}case y.SELECT:{MVe(e,t);break}case y.OPTION:case y.OPTGROUP:{OVe(e,t);break}case y.NOEMBED:case y.NOFRAMES:{jne(e,t);break}case y.FRAMESET:{uVe(e,t);break}case y.TEXTAREA:{xVe(e,t);break}case y.NOSCRIPT:{e.options.scriptingEnabled?jne(e,t):$ne(e,t);break}case y.PLAINTEXT:{yVe(e,t);break}case y.COL:case y.TH:case y.TD:case y.TR:case y.HEAD:case y.FRAME:case y.TBODY:case y.TFOOT:case y.THEAD:case y.CAPTION:case y.COLGROUP:break;default:$ne(e,t);}}function FVe(e,t){if(e.openElements.hasInScope(y.BODY)&&(e.insertionMode=F.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t);}}function BVe(e,t){e.openElements.hasInScope(y.BODY)&&(e.insertionMode=F.AFTER_BODY,roe(e,t));}function UVe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n));}function HVe(e){let t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(y.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(y.FORM):n&&e.openElements.remove(n));}function GVe(e){e.openElements.hasInButtonScope(y.P)||e._insertFakeElement(W.P,y.P),e._closePElement();}function jVe(e){e.openElements.hasInListItemScope(y.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(y.LI),e.openElements.popUntilTagNamePopped(y.LI));}function $Ve(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n));}function VVe(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function zVe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker());}function WVe(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(W.BR,y.BR),e.openElements.pop(),e.framesetOk=false;}function Yne(e,t){let n=t.tagName,o=t.tagID;for(let r=e.openElements.stackTop;r>0;r--){let i=e.openElements.items[r],s=e.openElements.tagIDs[r];if(o===s&&(o!==y.UNKNOWN||e.treeAdapter.getTagName(i)===n)){e.openElements.generateImpliedEndTagsWithExclusion(o),e.openElements.stackTop>=r&&e.openElements.shortenToLength(r);break}if(e._isSpecialElement(i,s))break}}function _I(e,t){switch(t.tagID){case y.A:case y.B:case y.I:case y.S:case y.U:case y.EM:case y.TT:case y.BIG:case y.CODE:case y.FONT:case y.NOBR:case y.SMALL:case y.STRIKE:case y.STRONG:{vF(e,t);break}case y.P:{GVe(e);break}case y.DL:case y.UL:case y.OL:case y.DIR:case y.DIV:case y.NAV:case y.PRE:case y.MAIN:case y.MENU:case y.ASIDE:case y.BUTTON:case y.CENTER:case y.FIGURE:case y.FOOTER:case y.HEADER:case y.HGROUP:case y.DIALOG:case y.ADDRESS:case y.ARTICLE:case y.DETAILS:case y.SEARCH:case y.SECTION:case y.SUMMARY:case y.LISTING:case y.FIELDSET:case y.BLOCKQUOTE:case y.FIGCAPTION:{UVe(e,t);break}case y.LI:{jVe(e);break}case y.DD:case y.DT:{$Ve(e,t);break}case y.H1:case y.H2:case y.H3:case y.H4:case y.H5:case y.H6:{VVe(e);break}case y.BR:{WVe(e);break}case y.BODY:{FVe(e,t);break}case y.HTML:{BVe(e,t);break}case y.FORM:{HVe(e);break}case y.APPLET:case y.OBJECT:case y.MARQUEE:{zVe(e,t);break}case y.TEMPLATE:{$p(e,t);break}default:Yne(e,t);}}function Jne(e,t){e.tmplInsertionModeStack.length>0?ooe(e,t):wF(e,t);}function qVe(e,t){var n;t.tagID===y.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode;}function KVe(e,t){e._err(t,Z.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function EF(e,t){if(e.openElements.currentTagId!==void 0&&Vne.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=F.IN_TABLE_TEXT,t.type){case Ut.CHARACTER:{Xne(e,t);break}case Ut.WHITESPACE_CHARACTER:{Qne(e,t);break}}else Lb(e,t);}function YVe(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_CAPTION;}function JVe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_COLUMN_GROUP;}function QVe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(W.COLGROUP,y.COLGROUP),e.insertionMode=F.IN_COLUMN_GROUP,IF(e,t);}function XVe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_TABLE_BODY;}function ZVe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(W.TBODY,y.TBODY),e.insertionMode=F.IN_TABLE_BODY,PI(e,t);}function eze(e,t){e.openElements.hasInTableScope(y.TABLE)&&(e.openElements.popUntilTagNamePopped(y.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function tze(e,t){Kne(t)?e._appendElement(t,me.HTML):Lb(e,t),t.ackSelfClosing=true;}function nze(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,me.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function Ng(e,t){switch(t.tagID){case y.TD:case y.TH:case y.TR:{ZVe(e,t);break}case y.STYLE:case y.SCRIPT:case y.TEMPLATE:{Ra(e,t);break}case y.COL:{QVe(e,t);break}case y.FORM:{nze(e,t);break}case y.TABLE:{eze(e,t);break}case y.TBODY:case y.TFOOT:case y.THEAD:{XVe(e,t);break}case y.INPUT:{tze(e,t);break}case y.CAPTION:{YVe(e,t);break}case y.COLGROUP:{JVe(e,t);break}default:Lb(e,t);}}function Nb(e,t){switch(t.tagID){case y.TABLE:{e.openElements.hasInTableScope(y.TABLE)&&(e.openElements.popUntilTagNamePopped(y.TABLE),e._resetInsertionMode());break}case y.TEMPLATE:{$p(e,t);break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:case y.TBODY:case y.TD:case y.TFOOT:case y.TH:case y.THEAD:case y.TR:break;default:Lb(e,t);}}function Lb(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=true,xI(e,t),e.fosterParentingEnabled=n;}function Qne(e,t){e.pendingCharacterTokens.push(t);}function Xne(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function wb(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)Lb(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var Zne=new Set([y.CAPTION,y.COL,y.COLGROUP,y.TBODY,y.TD,y.TFOOT,y.TH,y.THEAD,y.TR]);function oze(e,t){let n=t.tagID;Zne.has(n)?e.openElements.hasInTableScope(y.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(y.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=F.IN_TABLE,Ng(e,t)):Nr(e,t);}function rze(e,t){let n=t.tagID;switch(n){case y.CAPTION:case y.TABLE:{e.openElements.hasInTableScope(y.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(y.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=F.IN_TABLE,n===y.TABLE&&Nb(e,t));break}case y.BODY:case y.COL:case y.COLGROUP:case y.HTML:case y.TBODY:case y.TD:case y.TFOOT:case y.TH:case y.THEAD:case y.TR:break;default:_I(e,t);}}function IF(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.COL:{e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.TEMPLATE:{Ra(e,t);break}default:wI(e,t);}}function ize(e,t){switch(t.tagID){case y.COLGROUP:{e.openElements.currentTagId===y.COLGROUP&&(e.openElements.pop(),e.insertionMode=F.IN_TABLE);break}case y.TEMPLATE:{$p(e,t);break}case y.COL:break;default:wI(e,t);}}function wI(e,t){e.openElements.currentTagId===y.COLGROUP&&(e.openElements.pop(),e.insertionMode=F.IN_TABLE,e._processToken(t));}function PI(e,t){switch(t.tagID){case y.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_ROW;break}case y.TH:case y.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(W.TR,y.TR),e.insertionMode=F.IN_ROW,MI(e,t);break}case y.CAPTION:case y.COL:case y.COLGROUP:case y.TBODY:case y.TFOOT:case y.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE,Ng(e,t));break}default:Ng(e,t);}}function RF(e,t){let n=t.tagID;switch(t.tagID){case y.TBODY:case y.TFOOT:case y.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE);break}case y.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE,Nb(e,t));break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:case y.TD:case y.TH:case y.TR:break;default:Nb(e,t);}}function MI(e,t){switch(t.tagID){case y.TH:case y.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,me.HTML),e.insertionMode=F.IN_CELL,e.activeFormattingElements.insertMarker();break}case y.CAPTION:case y.COL:case y.COLGROUP:case y.TBODY:case y.TFOOT:case y.THEAD:case y.TR:{e.openElements.hasInTableScope(y.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY,PI(e,t));break}default:Ng(e,t);}}function eoe(e,t){switch(t.tagID){case y.TR:{e.openElements.hasInTableScope(y.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY);break}case y.TABLE:{e.openElements.hasInTableScope(y.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY,RF(e,t));break}case y.TBODY:case y.TFOOT:case y.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(y.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=F.IN_TABLE_BODY,RF(e,t));break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:case y.TD:case y.TH:break;default:Nb(e,t);}}function sze(e,t){let n=t.tagID;Zne.has(n)?(e.openElements.hasInTableScope(y.TD)||e.openElements.hasInTableScope(y.TH))&&(e._closeTableCell(),MI(e,t)):Nr(e,t);}function aze(e,t){let n=t.tagID;switch(n){case y.TD:case y.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=F.IN_ROW);break}case y.TABLE:case y.TBODY:case y.TFOOT:case y.THEAD:case y.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),eoe(e,t));break}case y.BODY:case y.CAPTION:case y.COL:case y.COLGROUP:case y.HTML:break;default:_I(e,t);}}function toe(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.OPTION:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e._insertElement(t,me.HTML);break}case y.OPTGROUP:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e.openElements.currentTagId===y.OPTGROUP&&e.openElements.pop(),e._insertElement(t,me.HTML);break}case y.HR:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop(),e.openElements.currentTagId===y.OPTGROUP&&e.openElements.pop(),e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.INPUT:case y.KEYGEN:case y.TEXTAREA:case y.SELECT:{e.openElements.hasInSelectScope(y.SELECT)&&(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode(),t.tagID!==y.SELECT&&e._processStartTag(t));break}case y.SCRIPT:case y.TEMPLATE:{Ra(e,t);break}}}function noe(e,t){switch(t.tagID){case y.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===y.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===y.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===y.OPTGROUP&&e.openElements.pop();break}case y.OPTION:{e.openElements.currentTagId===y.OPTION&&e.openElements.pop();break}case y.SELECT:{e.openElements.hasInSelectScope(y.SELECT)&&(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode());break}case y.TEMPLATE:{$p(e,t);break}}}function lze(e,t){let n=t.tagID;n===y.CAPTION||n===y.TABLE||n===y.TBODY||n===y.TFOOT||n===y.THEAD||n===y.TR||n===y.TD||n===y.TH?(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode(),e._processStartTag(t)):toe(e,t);}function cze(e,t){let n=t.tagID;n===y.CAPTION||n===y.TABLE||n===y.TBODY||n===y.TFOOT||n===y.THEAD||n===y.TR||n===y.TD||n===y.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(y.SELECT),e._resetInsertionMode(),e.onEndTag(t)):noe(e,t);}function dze(e,t){switch(t.tagID){case y.BASE:case y.BASEFONT:case y.BGSOUND:case y.LINK:case y.META:case y.NOFRAMES:case y.SCRIPT:case y.STYLE:case y.TEMPLATE:case y.TITLE:{Ra(e,t);break}case y.CAPTION:case y.COLGROUP:case y.TBODY:case y.TFOOT:case y.THEAD:{e.tmplInsertionModeStack[0]=F.IN_TABLE,e.insertionMode=F.IN_TABLE,Ng(e,t);break}case y.COL:{e.tmplInsertionModeStack[0]=F.IN_COLUMN_GROUP,e.insertionMode=F.IN_COLUMN_GROUP,IF(e,t);break}case y.TR:{e.tmplInsertionModeStack[0]=F.IN_TABLE_BODY,e.insertionMode=F.IN_TABLE_BODY,PI(e,t);break}case y.TD:case y.TH:{e.tmplInsertionModeStack[0]=F.IN_ROW,e.insertionMode=F.IN_ROW,MI(e,t);break}default:e.tmplInsertionModeStack[0]=F.IN_BODY,e.insertionMode=F.IN_BODY,Nr(e,t);}}function uze(e,t){t.tagID===y.TEMPLATE&&$p(e,t);}function ooe(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(y.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):wF(e,t);}function pze(e,t){t.tagID===y.HTML?Nr(e,t):II(e,t);}function roe(e,t){var n;if(t.tagID===y.HTML){if(e.fragmentContext||(e.insertionMode=F.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===y.HTML){e._setEndLocation(e.openElements.items[0],t);let o=e.openElements.items[1];o&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(o))===null||n===void 0)&&n.endTag)&&e._setEndLocation(o,t);}}else II(e,t);}function II(e,t){e.insertionMode=F.IN_BODY,xI(e,t);}function mze(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.FRAMESET:{e._insertElement(t,me.HTML);break}case y.FRAME:{e._appendElement(t,me.HTML),t.ackSelfClosing=true;break}case y.NOFRAMES:{Ra(e,t);break}}}function hze(e,t){t.tagID===y.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==y.FRAMESET&&(e.insertionMode=F.AFTER_FRAMESET));}function gze(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.NOFRAMES:{Ra(e,t);break}}}function fze(e,t){t.tagID===y.HTML&&(e.insertionMode=F.AFTER_AFTER_FRAMESET);}function yze(e,t){t.tagID===y.HTML?Nr(e,t):vI(e,t);}function vI(e,t){e.insertionMode=F.IN_BODY,xI(e,t);}function Sze(e,t){switch(t.tagID){case y.HTML:{Nr(e,t);break}case y.NOFRAMES:{Ra(e,t);break}}}function bze(e,t){t.chars=yn,e._insertCharacters(t);}function Tze(e,t){e._insertCharacters(t),e.framesetOk=false;}function ioe(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==me.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function Aze(e,t){if(Fne(t))ioe(e),e._startTagOutsideForeignContent(t);else {let n=e._getAdjustedCurrentElement(),o=e.treeAdapter.getNamespaceURI(n);o===me.MATHML?TF(t):o===me.SVG&&(Bne(t),AF(t)),RI(t),t.selfClosing?e._appendElement(t,o):e._insertElement(t,o),t.ackSelfClosing=true;}}function Eze(e,t){if(t.tagID===y.P||t.tagID===y.BR){ioe(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){let o=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(o)===me.HTML){e._endTagOutsideForeignContent(t);break}let r=e.treeAdapter.getTagName(o);if(r.toLowerCase()===t.tagName){t.tagName=r,e.openElements.shortenToLength(n);break}}}new Set([W.AREA,W.BASE,W.BASEFONT,W.BGSOUND,W.BR,W.COL,W.EMBED,W.FRAME,W.HR,W.IMG,W.INPUT,W.KEYGEN,W.LINK,W.META,W.PARAM,W.SOURCE,W.TRACK,W.WBR]);function soe(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);let o=Ob.getFragmentParser(e,n);return o.tokenizer.write(t,true),o.getFragment()}var Cze=5e3,aoe=1024;function xF(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function Rze(e){return e.nodeName==="#text"}function _F(e,t){if(t.nodesLeft<=0)return;t.nodesLeft-=1;let n=e.tagName.toLowerCase(),o,r;for(let{name:l,value:c}of e.attrs){let d=l.toLowerCase();if(d==="role"){r=c;continue}o===void 0&&(o={}),o[d]=c;}let i,s=[];for(let l of e.childNodes){if(t.nodesLeft<=0)break;if(Rze(l)){let c=l.value;if(c&&c.trim().length>0){let d=c.length>aoe?c.slice(0,aoe):c;i=i===void 0?d:`${i} ${d}`;}}else if(xF(l)){let c=_F(l,t);c!==void 0&&s.push(c);}}let a={tag:n};return r!==void 0&&(a.role=r),o!==void 0&&(a.attributes=o),i!==void 0&&(a.text=i),s.length>0&&(a.children=s),a}function PF(e){let t=soe(e),n={nodesLeft:Cze};for(let i of t.childNodes)if(xF(i)&&i.tagName.toLowerCase()==="body"){let s=_F(i,n);if(s!==void 0)return s}let o=[];for(let i of t.childNodes){if(n.nodesLeft<=0)break;if(xF(i)){let s=_F(i,n);s!==void 0&&o.push(s);}}let r={tag:"body"};return o.length>0&&(r.children=o),r}var vze=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),Vp=class{constructor(t,n,o,r,i,s){this.orgId=t;this.testId=n;this.testName=o;this.diskStorage=r;this.parentFlushResults=i;this.appGraphSink=s;}children=[];finished=false;stepFrequenciesByType={};currentResults=[];async getScreenshot(t,n){return this.diskStorage.readFile(`${tr}/${n}.jpeg`)}async getHtmlSnapshot(t,n){return this.diskStorage.readFile(`${tr}/${n}.html`)?.toString()}recordStepStat(t){t.type!=="PRESET_ACTION"?this.stepFrequenciesByType[t.type]=(this.stepFrequenciesByType[t.type]||0)+1:this.stepFrequenciesByType[t.command.type]=(this.stepFrequenciesByType[t.command.type]||0)+1;}sendFinalizedStepStats(){for(let[t,n]of Object.entries(this.stepFrequenciesByType))gt.increment("test_step_execution",n,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}flushResults(t){this.currentResults=t,this.parentFlushResults(t);}async startStep(t,n){let{step:o,parentStepIdChain:r}=t;this.recordStepStat(o);let i={step:o,status:"RUNNING",startedAt:new Date},s=[...n];this.currentResults=s;let a=new OF(this.orgId,this.testId,this.testName,i,this.diskStorage,l=>{this.flushResults([...s,l]);},r??[],this.appGraphSink);return this.children.push(a),a}async finish(t){this.finished||(this.finished=true,await Promise.all(this.children.map(n=>n.finishInternal({status:lH(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function wze(e){switch(e){case "SUCCESS":return "PASSED";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":return "RUNNING";case "IDLE":return "PENDING";default:return bt(e)}}function MF(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var OF=class{constructor(t,n,o,r,i,s,a,l){this.orgId=t;this.testId=n;this.testName=o;this.metadata=r;this.diskStorage=i;this.parentFlushResults=s;this.parentStepIdChain=a;this.appGraphSink=l;this.interactionTracer=new $d(void 0,c=>this.storeTraceAsset(c)),jd.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;attachBeforeScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.jpeg`,contents:o});}attachAfterScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.jpeg`,contents:o});}attachBeforeHtmlSnapshot(t){let{snapshotId:n,html:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.html`,contents:o});}attachAfterHtmlSnapshot(t){let{snapshotId:n,html:o,url:r,logger:i}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${tr}/${n}.html`,contents:o}),this.appGraphSink&&vze.has(this.metadata.step.type)&&this.appGraphSink({html:o,url:r,stepId:this.metadata.step.id,parentStepIdChain:[...this.parentStepIdChain],logger:i});}recordTargetAutoHeal(t){let{healType:n}=t,o=n==="AI"?"ai-target-heal":"cache-heal";gt.increment("test_event",1,[`name:${o}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:n,healedAt:new Date};}storeTraceAsset(t){this.diskStorage.storeFile({name:`${tr}/${t.snapshotId}.${t.extension??"jpeg"}`,contents:t.data});}async finishInternal(t){this.finished||(this.finished=true,this.interactionTracer.finish(),await Promise.all(this.children.map(n=>n.finish({status:wze(t.status),finishedAt:t.finishedAt}))));}recordStepDuration(t,n){if(!HA(t))return;let o=UA(t);gt.distribution("test_step_duration",n,[`type:${o}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}async finish(t){!this.finished&&t.resolvedStep!==void 0&&t.durationMs!==void 0&&this.recordStepDuration(t.resolvedStep,t.durationMs),await this.finishInternal(t.step),t.step.trace=this.interactionTracer.getRootSpan();}getResultBuilderForCurrentStep(){let t=this.metadata.step;switch(t.type){case "RESOLVED_MODULE":return n=>({...t,status:MF(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n,type:"MODULE"});case "CONDITIONAL":return n=>({...t,blocks:t.blocks.map(r=>({assertion:r.assertion,steps:zu(r.steps)})),elseSteps:t.elseSteps?zu(t.elseSteps):void 0,status:MF(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "AI_ACTION":case "AI_ACTION_DYNAMIC":case "PRESET_ACTION":case "SECTION":return n=>({...t,status:MF(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});default:return bt(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),n=new Vp(this.orgId,this.testId,this.testName,this.diskStorage,o=>{let r=t(o);this.parentFlushResults(r);});return this.children.push(n),n}};var OI=class{constructor(t,n,o,r,i,s,a){this.orgId=t;this.testId=n;this.testName=o;this.runAttemptId=r;this.metadata=i;this.diskStorage=s;this.recordVideo=a;this.diskStorage.mkdir(tr),this.harPagesStream=this.diskStorage.createFileStream(`${tr}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${tr}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${tr}/resource-usage.ndjson`),this.resourceUsageSampler=C1({keepSamples:false,onSample:l=>{this.resourceUsageStream.write(`${JSON.stringify(l)}
8326
8326
  `),l.system.cpu&&(this.cpuUsageSum+=l.system.cpu.total,this.cpuSampleCount++);let c=l.system.memory.total-l.system.memory.free;this.memoryUsageSum+=c,this.memorySampleCount++;}});}finished=false;children=[];beforeResults;mainResults=[];afterResults;harPagesStream;inProgressHarEntries;harEntriesStream;resourceUsageStream;resourceUsageSampler;uiStatesStream;previousHtmlByteHash;previousFingerprint;cpuUsageSum=0;cpuSampleCount=0;memoryUsageSum=0;memorySampleCount=0;get loggerBindings(){return {runAttemptId:this.runAttemptId}}getResourceUsageAverages(){return {avgCpuUsage:this.cpuSampleCount>0?this.cpuUsageSum/this.cpuSampleCount:0,avgMemoryUsage:this.memorySampleCount>0?this.memoryUsageSum/this.memorySampleCount:0}}get videoOutputPath(){if(this.recordVideo)return En__default.resolve(this.diskStorage.cwd(),tr)}setActiveVideo(t,n){this.recordVideo&&(this.metadata.activeVideos=this.metadata.activeVideos||[],this.metadata.activeVideos.push({videoName:t,timestamp:n}));}setViewport(t){this.metadata.viewport=t;}onNetworkPage(t){this.finished||this.harPagesStream.write(`${JSON.stringify(t)}
8327
8327
  `);}appendUiState(t){this.finished||(this.uiStatesStream||(this.uiStatesStream=this.diskStorage.createFileStream(MG)),this.uiStatesStream.write(`${JSON.stringify(t)}
8328
8328
  `));}buildAppGraphSink(){return ({html:t,url:n,stepId:o,parentStepIdChain:r,logger:i})=>{let s=fF(t),a=s===this.previousHtmlByteHash?this.previousFingerprint:void 0;if(!a){try{a=yF({url:n,dom:PF(t)});}catch(l){i.debug({err:l,stepId:o},"Failed to compute app-graph UIState fingerprint");return}this.previousHtmlByteHash=s,this.previousFingerprint=a;}this.appendUiState({stepId:o,parentStepIdChain:r,fingerprintHash:a.fingerprintHash,minhash:Array.from(a.minhash),canonicalUrl:a.canonicalUrl,capturedAt:Date.now()});}}onNetworkLogs(t){if(!this.finished)for(let[n,o]of Object.entries(t))o.response?(delete this.inProgressHarEntries[n],this.harEntriesStream.write(`${JSON.stringify(o)}
@@ -8377,4 +8377,4 @@ Entering interactive mode. Ask follow-up questions about run ${C.context.runId??
8377
8377
  ${Qw(b,Xt())}`),await ft(),process.exit(0);}catch(s){n.signal.aborted&&(ve.warn({err:s,sessionId:t},"AI seed command cancelled by signal"),await ft(),process.exit(130));let a=qI(s);ve.error({err:a,sessionId:t},"AI seed command failed"),R.error({err:a},"AI seed command failed"),await ft(),process.exit(1);}finally{fl(),process.off("SIGINT",r),process.off("SIGTERM",i);}});QI.command("triage").alias("heal").description("Group failed test results by shared test fixes. Alias: heal. Pass --dry-run to print the bucketing plan without healing.").addArgument(new Argument("[results]","Path to the results archive. Omit when using --run-group-id.").argOptional()).addOption(nre).addOption(So).addOption(ro).addOption(xn).addOption(Ds).addOption(va).addOption(Gb).addOption(jI).addOption(zb).addOption(Wb).addOption($b).addOption(Vb).addOption(jb).addOption(eB).addOption(GI).addOption(new Option("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Option("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Option("--wait-on-proxy <waitOnProxy>","HTTP proxy to use with the --wait-on command. Specify as https://username:pass@domain.com:2345")).addOption(new Option("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(ii)).addOption(qb).addOption(new Option("--limit <limit>","Abort if the number of healable failed runs exceeds this threshold.").argParser(WF)).addOption(iB).addOption(sB).addOption(KF).addOption(qF).addOption(Hb).option("--dry-run","Print the failure bucketing plan that would be dispatched to healing subagents, then exit without healing any tests.").option("--json","Suppress progress output and print the triage result as JSON.").option("--no-upload","Do not automatically upload the local results archive.").addOption(Joe).action(async(e,t)=>{let n=t.json??false;n&&R.setMinLevel(50),await Pr(ve);let o=t.runGroupId;if(e&&o)throw new _e("Provide either a results archive path or --run-group-id, not both.");if(!e&&!o)throw new _e("Provide a results archive path or --run-group-id to heal.");let r=t.dryRun??false,i=Ey(t),s=Ub(t.customHeaders),a=await an({configFilePath:t.config,nameFilter:t.filter}),l=new Dt({baseUrl:t.server,apiKey:t.apiKey,logger:ve}),{orgId:c,userId:d,email:u,selfServe:p}=await Lh({client:l,skipPrompts:t.yes});mF({userId:d,orgId:c,email:u,selfServe:p});let m=await aa({project:a,apiClient:l}),h=m.config.ai?.triage,g=h?.remoteBrowser??m.config.browser?.remoteBrowser??false,f=t.exitCodeOnHeal!=null?Number(t.exitCodeOnHeal):h?.exitCodeOnHeal??0,{parallel:b,autoParallel:T}=XI({options:t,project:m});T||TE({parallel:b,remoteBrowser:g});let A;t.inputCsv&&(A=await pI(t.inputCsv));let C=Ab(t.pixelRatio),v=t.headfulBrowser??false,I=pT.parse({onFail:h?.onHealFail,onSuccess:h?.onHealSuccess}),_=await Rr(ve,l,m),x=xoe({resultsDir:e,runGroupId:o});if(!x){DF({output:void 0,dryRun:r,jsonOutput:n});return}let E=ve.child({cliVersion:Hn,orgId:c,userId:d,runGroupId:x.runGroupId});E.info({gitMetadata:_,config:m.config,nodeVersion:process.versions.node},"Got local metadata");let O=new sr(m.config.ai?.agentConfig,{baseUrl:t.server,apiKey:t.apiKey,logger:E,mode:"runner"}),N=new AbortController,H=new AbortController,U=new Lc({sessionGuard:{maxConcurrentSessions:b,mode:"queue"}});gd(E),dc(async J=>{N.abort(),H.abort(),await U.killAllSessions(J);});let $={limit:t.limit,project:m,apiClient:l,generator:O,logger:E,gitMetadata:_,parallel:b,orgId:c,serverId:x.runGroupId,apiKey:t.apiKey,start:t.start,waitOn:t.waitOn,waitOnProxy:t.waitOnProxy,waitOnTimeout:t.waitOnTimeout,alwaysSaveCache:i.alwaysSaveCache,noCache:i.noCache,excludePatterns:t.exclude,sessionOptions:{envName:t.env,urlOverride:t.urlOverride,customHeaders:s,devicePixelRatio:C,testInputs:A&&A.length===1?A[0]:void 0,browserTypeOverride:t.browser,remoteBrowserOverride:g,headfulOverride:v},timeoutMinutes:t.timeoutMinutes,sessionManager:U,agentOutputStream:t.quiet||n?void 0:process.stdout,dryRun:r,jsonOutput:n,abortController:N};await Nu({serviceName:"heal",enabled:t.shareDiagnostics===true});let oe=0,X;try{X=await it({name:"heal.run",root:!0,attributes:{"momentic.org_id":c,"momentic.run_group_id":x.runGroupId,"momentic.parallel":b,"momentic.dry_run":r},fn:async()=>x.kind==="run-group"?goe({...$,runGroupId:x.runGroupId}):hoe({...$,resultsDir:x.resultsDir})});}catch(J){X={heals:[],bucketingIterations:[],failure:{err:J,message:Q(J)}};}if(H.signal.aborted)return;let z=X;if(!r&&!X?.failure)try{let J=await voe({output:X,resultsDir:x.kind==="results"?x.resultsDir:void 0,healingConfig:I,gitMetadata:_,project:m,apiClient:l,generator:O,logger:E,suppressOutput:n});z=J.output,oe=J.exitCode,(J.output?.heals.filter(B=>B.status==="FIXED").length??0)>0&&(oe=Math.max(oe,f));}catch(J){z={...X??{heals:[],bucketingIterations:[]},failure:{err:J,message:Q(J)}};}if(DF({output:z,dryRun:r,jsonOutput:n}),H.signal.aborted)return;let K=await foe({output:z,generator:O,logger:E,serverId:x.runGroupId,dryRun:r,categoryDefinitions:m.config.ai?.classification?.categories??Ur,healingConfig:I,abortSignal:H.signal});if(H.signal.aborted)return;let q=false;if(t.upload&&x.kind==="run-group")R.warn("Skipping automatic results upload: --run-group-id does not provide a local results archive to upload.");else if(t.upload&&x.kind==="results"){K&&yoe({resultsDir:x.resultsDir,summary:K});let J=Xt(),te=()=>it({name:"file-storage.upload_test_outputs",serviceName:"file-storage",fn:()=>aS({client:l,resultsPath:x.resultsDir})}),B=n?await te():await Jr({text:"Uploading results to Momentic\u2026",screen:J},te);q=B.success,B.success?(R.success("Uploaded results to Momentic."),R.dimmed(` ${cc(B.runGroupUrl,J)}`)):R.error(`Results upload failed: ${B.error}.`);}if(K&&!q)try{await l.updateGithubPRHealRiskSummary(x.runGroupId,{summary:K});}catch(J){E.warn({err:J},"Failed to submit GitHub PR heal risk summary update");}if(z?.failure)throw z.failure.err;await ft(),process.exit(oe);});_n.command("upgrade").description("Upgrade your configuration to the latest recommended settings").addOption(xn).addOption(Ds).addOption(ro).addOption(So).option("--dry-run","Preview the upgrade without writing any files or pushing snapshots.").action(async e=>{let t=await an({configFilePath:e.config,nameFilter:e.filter}),n=e.dryRun??false;n||await Fre();let o=new Dt({baseUrl:e.server,apiKey:e.apiKey,logger:ve}),{orgId:r}=await o.getAuthInfo(),i=await Rr(ve,o,t),s=await W3({project:t,dryRun:n,migrate:()=>$I({project:t,apiClient:o,gitMetadata:i,orgId:r,dryRun:n})});XN({summary:s.migration,fileFormatChanged:s.fileFormatChanged,aiSettings:s.aiSettings,dryRun:n}),s.fileFormatChanged||JN(s.aiSettings)?n?R.success("Dry run complete. Rerun without --dry-run to apply."):(R.success("Upgraded project to latest recommended settings."),R.dimmed(" Optional: rerun tests with --regenerate-cache to rebuild caches from scratch (slower).")):R.success("Project is already up to date."),await ft(),process.exit(0);});function XI({options:e,project:t}){let n=e.parallel??t.config.parallel??1;if(n!=="auto")return {parallel:n,autoParallel:false};let o=e.remoteBrowsers??t.config.browser?.remoteBrowser??false,r=cpus().length;return {parallel:o?Math.max(1,r*4-2):Math.max(1,Math.floor(r/2)),autoParallel:true}}async function jre(e){let t=e.config.fileFormat==="v2",{totalErrors:n,parsingErrors:o,parsingErrorDetails:r,failedTestFilePaths:i,failedModuleFilePaths:s}=t?await GF({project:e}):await HF({project:e,fix:false});o>0&&(sh({parsingErrors:o,parsingErrorDetails:r,failedTestFilePaths:i,failedModuleFilePaths:s,rootDir:e.rootDir}),process.exit(1)),n>0&&(R.error(`Found ${n} ${t?"lint ":""}errors`),R.warn(t?"Run 'npx momentic lint' for details":"To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));}async function dWe(){Hre("Main program started");try{await _n.parseAsync(process.argv),await ft();}catch(e){let t={};try{t.playwrightVersion=execSync("npx playwright --version").toString();}catch(n){ve.error({err:n},"Error fetching debug information");}ve.error({err:e,debugInfo:t},"Uncaught error in CLI"),R.error({err:e},"Momentic CLI exited unexpectedly"),await ft(),process.exit(1);}}lGe.setMaxListeners(25);process.on("warning",e=>{ve.warn({err:e},`Node warning received on CLI: ${e.message}`);});Hre("CLI parsing setup complete");dWe();
8378
8378
  //# sourceMappingURL=out.js.map
8379
8379
  //# sourceMappingURL=cli.js.map
8380
- //# debugId=56954989-257d-5a8f-8880-8804bf12978d
8380
+ //# debugId=066a2024-d456-59be-9d76-b49981e0d2b0