@zaip-ai/cli 3.5.0 → 3.6.0

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.
Files changed (80) hide show
  1. package/dist/services/adapters.d.ts +1 -1
  2. package/dist/services/adapters.js +1 -1
  3. package/dist/services/stack-install.d.ts.map +1 -1
  4. package/dist/services/stack-install.js +19 -9
  5. package/dist/services/stack-install.js.map +1 -1
  6. package/dist/services/stack-node.d.ts.map +1 -1
  7. package/dist/services/stack-node.js +1 -1
  8. package/dist/services/stack-node.js.map +1 -1
  9. package/package.json +1 -1
  10. package/templates/.agents/config/agents/discovery.json +1 -1
  11. package/templates/.agents/dashboard/.zaip-managed.json +57 -29
  12. package/templates/.agents/dashboard/apps/frontend/dist/assets/DashboardHelpDialog-BDQR0U4a.js +2938 -0
  13. package/templates/.agents/dashboard/apps/frontend/dist/assets/DashboardHelpDialog-DRI_XwUf.css +1 -0
  14. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-OulA4CoX.js +3 -0
  15. package/templates/.agents/dashboard/apps/frontend/dist/assets/TraceabilityWorkspace-Ckxk_izu.js +1 -0
  16. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-CqfSgtk9.js +2 -0
  17. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-OBJXZOwe.css +1 -0
  18. package/templates/.agents/dashboard/apps/frontend/dist/index.html +2 -2
  19. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  20. package/templates/.agents/dashboard/apps/frontend/src/AppDashboardContent.tsx +0 -2
  21. package/templates/.agents/dashboard/apps/frontend/src/DashboardGlobalSettings.tsx +7 -0
  22. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsCard.tsx +15 -2
  23. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.tsx +1 -1
  24. package/templates/.agents/dashboard/apps/frontend/src/cost-calculation-guide.css +1 -1
  25. package/templates/.agents/dashboard/apps/frontend/src/dashboard-help-dialog.css +2 -2
  26. package/templates/.agents/dashboard/apps/frontend/src/operations-entity-page-projection.ts +4 -1
  27. package/templates/.agents/dashboard/apps/frontend/src/operations-period-contract.test.ts +20 -9
  28. package/templates/.agents/dashboard/apps/frontend/src/pricing-settings-dialog.css +5 -5
  29. package/templates/.agents/dashboard/apps/frontend/src/use-app-work-board.test.ts +1 -1
  30. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  31. package/templates/.agents/dashboard/modules/operations/package.json +1 -1
  32. package/templates/.agents/dashboard/modules/operations/src/react/OperationsEntityFilters.tsx +1 -1
  33. package/templates/.agents/dashboard/modules/operations/src/react/PagedWorkList.tsx +2 -2
  34. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  35. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  36. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  37. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  38. package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
  39. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.test.ts +3 -3
  40. package/templates/.agents/dashboard/packages/local-runtime/src/server-snapshot-refresh.test.ts +2 -2
  41. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-filter-matrix.test.ts +1 -1
  42. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-pricing-provenance.test.ts +49 -13
  43. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  44. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  45. package/templates/.agents/dashboard/tests/e2e/specs/dashboard.spec.ts +4 -6
  46. package/templates/.agents/dashboard/tests/e2e/specs/work-board-hydration.ts +38 -0
  47. package/templates/.agents/design/.zaip-managed.json +11 -7
  48. package/templates/.agents/design/apps/catalog/dist/assets/index-Cv4VfxTQ.js +72 -0
  49. package/templates/.agents/design/apps/catalog/dist/index.html +1 -1
  50. package/templates/.agents/design/apps/catalog/package.json +1 -1
  51. package/templates/.agents/design/apps/catalog/src/components/DashboardFiltersSpecimen.tsx +26 -21
  52. package/templates/.agents/design/apps/catalog/src/components/StackVersionFieldSpecimen.tsx +1 -5
  53. package/templates/.agents/design/apps/catalog/src/styles/stack-version-field.css +75 -13
  54. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  55. package/templates/.agents/requirements/autonomous-assurance.md +1 -1
  56. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  57. package/templates/.agents/requirements/comparative-audit.md +1 -1
  58. package/templates/.agents/requirements/context-engine.md +1 -1
  59. package/templates/.agents/requirements/cost-observability.md +1 -1
  60. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  61. package/templates/.agents/requirements/data-export.md +1 -1
  62. package/templates/.agents/requirements/design-system.md +1 -1
  63. package/templates/.agents/requirements/execution-engine.md +1 -1
  64. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  65. package/templates/.agents/requirements/model-orchestration.md +1 -1
  66. package/templates/.agents/requirements/public-distribution.md +1 -1
  67. package/templates/.agents/requirements/software-architecture.md +1 -1
  68. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  69. package/templates/.agents/requirements/work-lifecycle.md +1 -1
  70. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  71. package/templates/.agents/runtime/VERSION +1 -1
  72. package/templates/.agents/runtime/bin/zaip.mjs +42 -11
  73. package/templates/.agents/runtime/checksums.sha256 +5 -5
  74. package/templates/.agents/runtime/manifest.json +1 -1
  75. package/templates/.agents/runtime/provenance.json +4 -4
  76. package/templates/.agents/runtime/sbom.cdx.json +1 -1
  77. package/templates/.agents/skills/zaip-skill-execution/SKILL.md +1 -0
  78. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-deploy-contract.test.mjs +3 -1
  79. package/templates/.agents/zaip-aios/VERSION +1 -1
  80. package/templates/template-manifest.json +98 -66
@@ -93,7 +93,7 @@ ${yaml}
93
93
  ${FRONTMATTER_BOUNDARY}
94
94
 
95
95
  ${body}
96
- `}var import_yaml3,FRONTMATTER_BOUNDARY,MAX_SAFE_ALIAS_COUNT2,MarkdownContractError;var init_markdown=__esm({"../core/src/markdown.ts"(){"use strict";import_yaml3=__toESM(require_dist(),1);FRONTMATTER_BOUNDARY="---";MAX_SAFE_ALIAS_COUNT2=10;MarkdownContractError=class extends Error{name="MarkdownContractError"}}});function parseRuleDocument(source){return parseMarkdown(source,ruleMetadataSchema)}function parseRequirementDocument(source){const document=parseMarkdown(source,requirementMetadataSchema);if(!/^## REQ-[A-Z0-9-]+\s/m.test(document.body)){throw new Error("Requirement document must declare at least one REQ section")}if(!/`?AC-[A-Z0-9-]+`?/m.test(document.body)){throw new Error("Requirement document must declare at least one Acceptance Criterion")}return document}function buildRequirementReferenceCatalog(sources){const requirementIds=new Set;const acceptanceIds=new Set;const requirementAliases=new Map;const acceptanceAliases=new Map;for(const source of sources){const document=parseRequirementDocument(source);if(document.metadata.status==="deprecated"){collectAliases(document.body,"REQ",requirementAliases);collectAliases(document.body,"AC",acceptanceAliases);continue}for(const match of document.body.matchAll(/^##\s+(REQ-[A-Z0-9-]+)(?:\s|$)/gm)){if(match[1]!==void 0)requirementIds.add(match[1])}for(const match of document.body.matchAll(/^\s*-\s+`?(AC-[A-Z0-9-]+)`?\s*:/gm)){if(match[1]!==void 0)acceptanceIds.add(match[1])}}const resolvedRequirementAliases=resolvedAliases(requirementAliases,requirementIds);const resolvedAcceptanceAliases=resolvedAliases(acceptanceAliases,acceptanceIds);return{requirement_ids:[...requirementIds].sort(),acceptance_ids:[...acceptanceIds].sort(),requirement_aliases:Object.fromEntries(resolvedRequirementAliases),acceptance_aliases:Object.fromEntries(resolvedAcceptanceAliases)}}function validateRequirementReferences(catalog,requirementIds,acceptanceIds){const knownRequirements=new Set(catalog.requirement_ids);const knownAcceptance=new Set(catalog.acceptance_ids);const findings=[];for(const id of[...new Set(requirementIds)].sort()){if(!knownRequirements.has(id)&&catalog.requirement_aliases[id]===void 0){findings.push({kind:"requirement",id,message:`Requirement does not resolve: ${id}`})}}for(const id of[...new Set(acceptanceIds)].sort()){if(!knownAcceptance.has(id)&&catalog.acceptance_aliases[id]===void 0){findings.push({kind:"acceptance",id,message:`Acceptance Criterion does not resolve: ${id}`})}}return findings}function collectAliases(body,prefix,aliases){const expression=new RegExp(`^\\s*-\\s+\\x60(${prefix}-[A-Z0-9-]+)\\x60\\s*->\\s*\\x60(${prefix}-[A-Z0-9-]+)\\x60`,"gm");for(const match of body.matchAll(expression)){const source=match[1];const target=match[2];if(source===void 0||target===void 0)continue;const existing=aliases.get(source);if(existing!==void 0&&existing!==target){throw new Error(`Divergent ${prefix} alias: ${source}`)}aliases.set(source,target)}}function resolvedAliases(aliases,canonicalIds){const resolved=[];for(const[source,target]of aliases){if(!canonicalIds.has(target)){throw new Error(`Alias target does not resolve: ${source} -> ${target}`)}resolved.push([source,target])}return resolved.sort(([left],[right])=>left.localeCompare(right))}var ruleMetadataSchema,requirementMetadataSchema;var init_governance=__esm({"../core/src/governance.ts"(){"use strict";init_zod();init_markdown();ruleMetadataSchema=external_exports.object({id:external_exports.string().regex(/^RULE-[A-Z0-9-]+$/),load:external_exports.enum(["always","auto","file_match","manual"]),globs:external_exports.array(external_exports.string().min(1)).default([]),priority:external_exports.enum(["critical","high","medium","low"]),max_context_tokens:external_exports.number().int().positive(),requires:external_exports.array(external_exports.string().regex(/^RULE-[A-Z0-9-]+$/)),triggers:external_exports.array(external_exports.string().min(1)).default([]),phases:external_exports.array(external_exports.enum(["conversation","definition","planning","execution","verification","evidence"])).default([]),domains:external_exports.array(external_exports.string().min(1)).default([])}).strict().superRefine((metadata2,context)=>{if(metadata2.load==="file_match"&&metadata2.globs.length===0){context.addIssue({code:"custom",path:["globs"],message:"file_match Rules require at least one glob"})}});requirementMetadataSchema=external_exports.object({schema_version:external_exports.literal(2),id:external_exports.string().regex(/^REQUIREMENTS-[A-Z0-9-]+$/),area:external_exports.string().regex(/^[a-z][a-z0-9-]*$/),title:external_exports.string().min(1),status:external_exports.enum(["proposed","active","deprecated"]),version:external_exports.number().int().positive(),source_change:external_exports.string().min(1).nullable(),source_release:external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional()}).strict().superRefine((metadata2,context)=>{if(metadata2.source_change===null&&metadata2.source_release===void 0){context.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"})}if(metadata2.source_change!==null&&metadata2.source_release!==void 0){context.addIssue({code:"custom",path:["source_release"],message:"source_release is only valid when source_change is null"})}})}});function validateCodexFirstRoute(input){const profile=hostCapabilityProfileSchema.parse(input.profile);if(profile.default_mode!=="codex_host_native"||!input.host_authentication_available){return{status:"exception",code:"host_authentication_unavailable"}}if(input.requires_external_provider===true){return{status:"exception",code:"external_provider_required"}}if(input.requires_remote_operation===true){return{status:"exception",code:"remote_operation_required"}}return{status:"valid",authentication:"host",remote_provider_required:false}}async function loadHostCapabilityProfile(filesystem,path=".agents/config/models/codex-host.yaml"){return hostCapabilityProfileSchema.parse(parseYaml(await filesystem.readText(path)))}var HOST_EXECUTION_MODES,MODEL_CLASSES,CODEX_NATIVE_SURFACES,hostExecutionModeSchema,modelClassSchema,codexNativeSurfaceSchema,uniqueNativeSurfacesSchema,hostCapabilityEvidenceSchema,implementedHostCapabilityClaimSchema,nativeModeProfileSchema,subprocessModeProfileSchema,modelClassProfileSchema,hostCapabilityProfileSchema,providerSubprocessOptInSchema;var init_contracts2=__esm({"../core/src/host-capabilities/contracts.ts"(){"use strict";init_zod();init_yaml();HOST_EXECUTION_MODES=["codex_host_native","provider_subprocess"];MODEL_CLASSES=["frontier","balanced","fast_scan","review"];CODEX_NATIVE_SURFACES=["subagents","worktrees","sandbox","approvals","skills","mcp"];hostExecutionModeSchema=external_exports.enum(HOST_EXECUTION_MODES);modelClassSchema=external_exports.enum(MODEL_CLASSES);codexNativeSurfaceSchema=external_exports.enum(CODEX_NATIVE_SURFACES);uniqueNativeSurfacesSchema=external_exports.array(codexNativeSurfaceSchema).min(1).refine(surfaces=>new Set(surfaces).size===surfaces.length,{message:"native_surfaces must be unique"});hostCapabilityEvidenceSchema=external_exports.object({locator:external_exports.string().min(1),candidate_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict();implementedHostCapabilityClaimSchema=external_exports.object({capability_id:external_exports.string().regex(/^CAP-[A-Z0-9-]+$/),current_state:external_exports.literal("implemented"),previous_states:external_exports.tuple([external_exports.literal("declared")]),evidence:external_exports.array(hostCapabilityEvidenceSchema).length(0)}).strict();nativeModeProfileSchema=external_exports.object({tier:external_exports.literal(1),enabled:external_exports.literal(true),optional:external_exports.literal(false),invokes_provider_subprocess:external_exports.literal(false),authority:external_exports.literal("host"),native_surfaces:uniqueNativeSurfacesSchema,capability_bindings:external_exports.record(codexNativeSurfaceSchema,implementedHostCapabilityClaimSchema)}).strict().superRefine((mode,context)=>{const bindings=Object.keys(mode.capability_bindings).sort();const surfaces=[...mode.native_surfaces].sort();if(JSON.stringify(bindings)!==JSON.stringify(surfaces)){context.addIssue({code:"custom",path:["capability_bindings"],message:"every native surface requires exactly one conformance/maturity binding"})}});subprocessModeProfileSchema=external_exports.object({tier:external_exports.union([external_exports.literal(2),external_exports.literal(3)]),enabled:external_exports.boolean(),optional:external_exports.literal(true),invokes_provider_subprocess:external_exports.literal(true),authority:external_exports.literal("framework"),native_surfaces:external_exports.array(external_exports.never()).length(0),opt_in:external_exports.object({required:external_exports.literal(true),allowed_sources:external_exports.array(external_exports.enum(["project_config","human_decision"])).min(1).refine(sources=>new Set(sources).size===sources.length,{message:"opt-in sources must be unique"})}).strict()}).strict();modelClassProfileSchema=external_exports.object({selection:external_exports.enum(["host_available","inherit_host"]),reasoning:external_exports.enum(["low","medium","high"]),intent:external_exports.string().min(1)}).strict();hostCapabilityProfileSchema=external_exports.object({schema_version:external_exports.literal(1),host_id:external_exports.literal("codex"),candidate_sha256:external_exports.null(),default_mode:external_exports.literal("codex_host_native"),modes:external_exports.object({codex_host_native:nativeModeProfileSchema,provider_subprocess:subprocessModeProfileSchema}).strict(),model_classes:external_exports.object({frontier:modelClassProfileSchema,balanced:modelClassProfileSchema,fast_scan:modelClassProfileSchema,review:modelClassProfileSchema}).strict()}).strict();providerSubprocessOptInSchema=external_exports.object({enabled:external_exports.literal(true),source:external_exports.enum(["project_config","human_decision"]),provenance:external_exports.object({reference:external_exports.string().min(1),recorded_at:external_exports.string().datetime({offset:true})}).strict()}).strict()}});var init_host_capabilities=__esm({"../core/src/host-capabilities/index.ts"(){"use strict";init_contracts2()}});function lifecycleClaimPath(kind,digest6){return`${LIFECYCLE_CLAIMS_ROOT}/${kind}/${digest6}.json`}var LIFECYCLE_CLAIMS_ROOT;var init_lifecycle_claims=__esm({"../core/src/lifecycle-claims.ts"(){"use strict";LIFECYCLE_CLAIMS_ROOT=".local/claims"}});function parseZaipManifest(value){return zaipManifestSchema.parse(value)}var zaipManifestSchema,zaipManifestJsonSchema,ManifestRepository;var init_manifest=__esm({"../core/src/manifest.ts"(){"use strict";init_zod();init_yaml();zaipManifestSchema=external_exports.object({schema_version:external_exports.literal(1),project:external_exports.object({id:external_exports.string().min(1),name:external_exports.string().min(1),timezone:external_exports.string().min(1).default("America/Sao_Paulo")}),framework:external_exports.object({version:external_exports.string().min(1)}),layout:external_exports.object({version:external_exports.literal(1),managed_namespace:external_exports.string().min(1).default(".agents/managed"),project_namespace:external_exports.string().min(1).default(".agents/project")}).default({version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"}),profile:external_exports.object({id:external_exports.string().min(1).default("zaip-aios-stack")}),paths:external_exports.object({specs:external_exports.string().min(1).default(".agents/specs"),changes:external_exports.string().min(1).default(".agents/changes"),tasks:external_exports.string().min(1).default(".agents/tasks"),decisions:external_exports.string().min(1).default(".agents/decisions"),runs:external_exports.string().min(1).default(".agents/runs")}).default({specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}),agents:external_exports.array(external_exports.enum(["codex","claude"])).default(["codex","claude"])}).strict();zaipManifestJsonSchema=external_exports.toJSONSchema(zaipManifestSchema);ManifestRepository=class{constructor(filesystem,path=".agents/manifest.yaml"){this.filesystem=filesystem;this.path=path}filesystem;path;async read(){return parseZaipManifest(parseYaml(await this.filesystem.readText(this.path)))}async write(manifest){await this.filesystem.writeTextAtomic(this.path,serializeYaml(zaipManifestSchema.parse(manifest)))}}}});function datedIdPartsWithDay(id){const match=id.match(/^([A-Z]+(?:-[A-Z]+)*)-(\d{4})-(\d{2})-(\d{2})-\d{2}-\d{2}-/);if(match?.[1]===void 0||match[2]===void 0||match[3]===void 0||match[4]===void 0){throw new TypeError(`ID does not contain the canonical date: ${id}`)}const[,prefix,year,month,day]=match;const date5=new Date(`${year}-${month}-${day}T00:00:00.000Z`);if(Number.isNaN(date5.getTime())||String(date5.getUTCFullYear()).padStart(4,"0")!==year||String(date5.getUTCMonth()+1).padStart(2,"0")!==month||String(date5.getUTCDate()).padStart(2,"0")!==day){throw new TypeError(`ID contains an invalid canonical date: ${id}`)}return{prefix,year,month,day}}function datedIdParts(id){const{year,month}=datedIdPartsWithDay(id);return{year,month}}function datedMarkdownPath(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}/${id}.md`}function datedMonthDirectory(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}`}function datedEntityDirectory(basePath,id){const{year,month,day}=datedIdPartsWithDay(id);return`${basePath}/${year}/${month}/${day}`}var init_paths=__esm({"../core/src/paths.ts"(){"use strict"}});function redactSensitive(value){return value.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/g,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[REDACTED]").replace(/\bgh[opsu]_[A-Za-z0-9_]{8,}\b/g,"[REDACTED]").replace(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]")}var init_permissions=__esm({"../core/src/policy/permissions/permissions.ts"(){"use strict"}});var init_permissions2=__esm({"../core/src/policy/permissions/index.ts"(){"use strict";init_permissions()}});var init_routing=__esm({"../core/src/policy/routing/routing.ts"(){"use strict"}});var init_routing2=__esm({"../core/src/policy/routing/index.ts"(){"use strict";init_routing()}});function assertSafeRecordContent(value){const seen=new WeakSet;function visit(item,key=""){if(typeof item==="string"){if(item.length===0||placeholder.test(item))return;if(sensitiveKey.test(key)||unsafeText(item)){throw new Error("Sensitive content cannot be persisted; redact credentials and sensitive URL parameters first.")}return}if(item===null||typeof item!=="object"||seen.has(item))return;seen.add(item);for(const[childKey,child]of Object.entries(item)){visit(child,sensitiveKey.test(key)?key:childKey)}}visit(value)}function unsafeText(text){if(redactSensitive(text)!==text)return true;if(/\bbearer\s+[a-z0-9._~+/-]+=*/i.test(text))return true;for(const match of text.matchAll(/\bbasic\s+([a-z0-9+/]+={0,2})/gi)){if(Buffer.from(match[1]??"","base64").toString("utf8").includes(":"))return true}if(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text))return true;for(const match of text.matchAll(/[a-z][a-z0-9+.-]*:\/\/[^\s<>"']+/gi)){try{const url2=new URL(match[0]);if(url2.password||/^https?:$/.test(url2.protocol)&&url2.username)return true;for(const[key,value]of url2.searchParams){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}for(const[key,value]of new URLSearchParams(url2.hash.slice(1))){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}text=text.replace(match[0],"")}catch{}}for(const match of text.matchAll(assignment)){if(!placeholder.test((match[1]??"").replace(/^(?:bearer|basic)\s+/i,"")))return true}return false}var sensitiveKeyName,sensitiveKey,placeholder,assignment;var init_record_safety=__esm({"../core/src/record-safety.ts"(){"use strict";init_permissions();sensitiveKeyName="(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|password|passwd|secret|client[_-]?secret|authorization|signature|sig)";sensitiveKey=new RegExp(`^${sensitiveKeyName}$`,"i");placeholder=/^(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})$/i;assignment=new RegExp(String.raw`\b${sensitiveKeyName}["']?\s*[:=]\s*["']?((?:(?:bearer|basic)\s+)?(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})|[^\s"',;]+)`,"gi")}});var init_result=__esm({"../core/src/result.ts"(){"use strict"}});var StateMachine,workItemStateMachine;var init_state_machine=__esm({"../core/src/state-machine.ts"(){"use strict";StateMachine=class{#transitions;constructor(transitions){const mutable=new Map;for(const transition2 of transitions){const targets=mutable.get(transition2.from)??new Set;targets.add(transition2.to);mutable.set(transition2.from,targets)}this.#transitions=mutable}canTransition(from,to){return this.#transitions.get(from)?.has(to)??false}assertTransition(from,to){if(!this.canTransition(from,to)){throw new Error(`Invalid state transition: ${from} -> ${to}`)}}nextStates(from){return[...this.#transitions.get(from)??[]]}};workItemStateMachine=new StateMachine([{from:"draft",to:"planned"},{from:"draft",to:"cancelled"},{from:"planned",to:"executing"},{from:"planned",to:"cancelled"},{from:"executing",to:"verifying"},{from:"executing",to:"blocked"},{from:"executing",to:"cancelled"},{from:"verifying",to:"completed"},{from:"verifying",to:"failed"},{from:"verifying",to:"blocked"},{from:"verifying",to:"cancelled"},{from:"blocked",to:"executing"},{from:"blocked",to:"cancelled"}])}});var stopTranscriptProofSchema,stopReceiptSchema;var init_stop_receipt_schema=__esm({"../core/src/stop-receipt-schema.ts"(){"use strict";init_zod();stopTranscriptProofSchema=external_exports.object({offset:external_exports.number().int().nonnegative(),length:external_exports.number().int().min(1).max(4194304),sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)});stopReceiptSchema=external_exports.object({schema_version:external_exports.literal(1),session_id:external_exports.string().min(1),turn_id:external_exports.string().min(1),run_id:external_exports.string().startsWith("RUN-"),observed_at:external_exports.string().datetime(),cursor:external_exports.object({path:external_exports.string().min(1),dev:external_exports.number(),ino:external_exports.number(),birthtime_ms:external_exports.number(),size:external_exports.number().int().nonnegative(),offset:external_exports.number().int().nonnegative(),mtime_ms:external_exports.number(),ctime_ms:external_exports.number(),trusted:external_exports.literal(true),terminal_status:external_exports.enum(["completed","failed","cancelled"]),session_proof:stopTranscriptProofSchema,terminal_proof:stopTranscriptProofSchema,anchor:stopTranscriptProofSchema})})}});async function loadWorkspaceLayout(filesystem){const[hasProjectConfig,hasFrameworkLock]=await Promise.all([filesystem.exists(PROJECT_CONFIG_PATH),filesystem.exists(FRAMEWORK_LOCK_PATH)]);if(hasProjectConfig!==hasFrameworkLock){const missing=hasProjectConfig?FRAMEWORK_LOCK_PATH:PROJECT_CONFIG_PATH;throw new PartialWorkspaceConfigError(`Partial V2 configuration; missing ${missing}`)}if(hasProjectConfig&&hasFrameworkLock){const[projectConfig2,frameworkLock]=await Promise.all([new ProjectConfigRepository(filesystem).read(),new FrameworkLockRepository(filesystem).read()]);return createV2WorkspaceLayout(projectConfig2,frameworkLock)}if(await filesystem.exists(".agents/manifest.yaml")){return createLegacyWorkspaceLayout(await new ManifestRepository(filesystem).read())}throw new WorkspaceLayoutNotFoundError("Workspace has neither complete V2 config nor a legacy V1 manifest")}function createV2WorkspaceLayout(projectConfig2,frameworkLock){const version2=frameworkLock.layout.version;const activeDataRoot=version2===3?".agents/records":".agents/data";return{version:version2,source:"project-config",project:projectConfig2.project,projectConfig:projectConfig2,frameworkLock,legacyManifest:null,supports:()=>true,entityRoot:kind=>`${activeDataRoot}/${v2DirectoryNames[kind]}`,activePath(kind,id){assertDatedEntityId(kind,id);const root=this.entityRoot(kind);const directory2=version2===3?datedMonthDirectory(root,id):datedEntityDirectory(root,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`},legacyReadRoot(kind){if(version2===3)return`.agents/data/${v2DirectoryNames[kind]}`;return legacyRoot(defaultLegacyRoots,kind)},legacyReadCandidate(kind,id,options){if(version2===3){return{path:v2EntityPath(".agents/data",kind,id),readOnly:true}}return legacyCandidate(defaultLegacyRoots,kind,id,options)},legacyReadCandidates(kind,id,options){if(version2===3){return[{path:v2EntityPath(".agents/records",kind,id),readOnly:true},{path:v2EntityPath(".agents/data",kind,id),readOnly:true}]}const candidate=legacyCandidate(defaultLegacyRoots,kind,id,options);return candidate===null?[]:[candidate]}}}function v2EntityPath(root,kind,id){assertDatedEntityId(kind,id);const directory2=datedEntityDirectory(`${root}/${v2DirectoryNames[kind]}`,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`}function createLegacyWorkspaceLayout(manifest){const roots2={spec:canonicalRoot(`${manifest.paths.specs}/capabilities`),change:canonicalRoot(manifest.paths.changes),task:canonicalRoot(manifest.paths.tasks),run:canonicalRoot(manifest.paths.runs)};return{version:1,source:"legacy-manifest",project:manifest.project,projectConfig:null,frameworkLock:null,legacyManifest:manifest,supports:kind=>kind!=="prd"&&kind!=="execution",entityRoot(kind){const root=legacyRoot(roots2,kind);if(root===null)throw unsupported(kind,1);return root},activePath(kind,id,options){if(!this.supports(kind))throw unsupported(kind,1);return legacyEntityPath(roots2,kind,id,options)},legacyReadRoot:()=>null,legacyReadCandidate:()=>null,legacyReadCandidates:()=>[]}}async function inspectArtifactReadState(filesystem,layout,kind,id,options){const activePath=layout.activePath(kind,id,options);const candidates=layout.legacyReadCandidates(kind,id,options);const[hasActive,...candidateExists]=await Promise.all([filesystem.exists(activePath),...candidates.map(candidate=>filesystem.exists(candidate.path))]);const existingLegacyPaths=candidates.filter((_,index)=>candidateExists[index]).map(candidate=>candidate.path);const legacyPath=existingLegacyPaths[0]??candidates[0]?.path??null;const hasLegacy=existingLegacyPaths.length>0;if(!hasActive&&!hasLegacy)return{state:"missing",activePath,legacyPath};if(hasActive&&!hasLegacy)return{state:"active-only",activePath,legacyPath};const contents=await Promise.all([...hasActive?[filesystem.readText(activePath)]:[],...existingLegacyPaths.map(path=>filesystem.readText(path))]);if(!hasActive){const[first,...rest]=contents;return{state:rest.every(content=>content===first)?"legacy-only":"duplicate-divergent",activePath,legacyPath}}const[active,...legacyContents]=contents;return{state:legacyContents.every(content=>content===active)?"duplicate-identical":"duplicate-divergent",activePath,legacyPath}}async function resolveArtifactReadPath(filesystem,layout,kind,id,options){const inspection=await inspectArtifactReadState(filesystem,layout,kind,id,options);if(inspection.state==="duplicate-divergent"){throw new InactiveLayoutConflictError(`Divergent ${kind} ${id} exists in active and legacy layouts: ${inspection.activePath}, ${inspection.legacyPath}`)}if(inspection.state==="missing")return null;if(inspection.state==="legacy-only")return inspection.legacyPath;return inspection.activePath}function legacyCandidate(roots2,kind,id,options){if(kind==="prd"||kind==="execution")return null;if(kind==="spec"&&options?.legacyCapability===void 0)return null;return{path:legacyEntityPath(roots2,kind,id,options),readOnly:true}}function legacyEntityPath(roots2,kind,id,options){assertEntityPrefix(kind,id);if(kind==="prd"||kind==="execution")throw unsupported(kind,1);if(kind==="spec"){const capability=options?.legacyCapability;if(capability===void 0||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(capability)){throw new WorkspaceLayoutError("Legacy spec lookup requires a canonical legacyCapability")}return`${roots2.spec}/${capability}/spec.md`}datedIdParts(id);if(kind==="change"){const{year,month}=datedIdParts(id);return`${roots2.change}/${year}/${month}/${id}/proposal.md`}if(kind==="task")return datedMarkdownPath(roots2.task,id);return datedMarkdownPath(roots2.run,id)}function legacyRoot(roots2,kind){if(kind==="prd"||kind==="execution")return null;return roots2[kind]}function assertDatedEntityId(kind,id){assertEntityPrefix(kind,id);datedIdPartsWithDay(id)}function assertEntityPrefix(kind,id){const prefix=expectedPrefixes[kind];if(!id.startsWith(`${prefix}-`)){throw new ArtifactKindMismatchError(`Expected ${kind} id to start with ${prefix}-: ${id}`)}}function canonicalRoot(path){if(path.length===0||path.includes("\\")||path.includes("\0")||path.startsWith("/")||path.startsWith("./")||path.endsWith("/")||/^[A-Za-z]:/.test(path)||path.split("/").some(segment2=>segment2.length===0||segment2==="."||segment2==="..")){throw new WorkspaceLayoutError(`Workspace layout path is not canonical: ${path}`)}return path}function unsupported(kind,version2){return new UnsupportedLayoutEntityError(`Layout V${version2} does not support ${kind}`)}var WorkspaceLayoutError,PartialWorkspaceConfigError,WorkspaceLayoutNotFoundError,UnsupportedLayoutEntityError,ArtifactKindMismatchError,InactiveLayoutConflictError,expectedPrefixes,v2DirectoryNames,defaultLegacyRoots;var init_workspace_layout=__esm({"../core/src/workspace-layout.ts"(){"use strict";init_config();init_manifest();init_paths();WorkspaceLayoutError=class extends Error{name="WorkspaceLayoutError"};PartialWorkspaceConfigError=class extends WorkspaceLayoutError{name="PartialWorkspaceConfigError"};WorkspaceLayoutNotFoundError=class extends WorkspaceLayoutError{name="WorkspaceLayoutNotFoundError"};UnsupportedLayoutEntityError=class extends WorkspaceLayoutError{name="UnsupportedLayoutEntityError"};ArtifactKindMismatchError=class extends WorkspaceLayoutError{name="ArtifactKindMismatchError"};InactiveLayoutConflictError=class extends WorkspaceLayoutError{name="InactiveLayoutConflictError"};expectedPrefixes={prd:"PRD",spec:"SPEC",change:"CHG",task:"TASK",execution:"EXEC",run:"RUN"};v2DirectoryNames={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};defaultLegacyRoots={spec:".agents/specs/capabilities",change:".agents/changes",task:".agents/tasks",run:".agents/runs"}}});var CORE_VERSION;var init_src=__esm({"../core/src/index.ts"(){"use strict";init_agent_runtime();init_agents();init_autonomy_policy();init_autonomy_recovery();init_clock();init_config();init_filesystem();init_git();init_governance();init_host_capabilities();init_ids();init_lifecycle_claims();init_manifest();init_markdown();init_model_orchestration();init_paths();init_permissions2();init_routing2();init_record_safety();init_result();init_state_machine();init_stop_receipt_schema();init_workspace_layout();init_yaml();CORE_VERSION="3.5.0"}});var require_lib=__commonJS({"../../node_modules/.pnpm/@babel+parser@7.29.7/node_modules/@babel/parser/lib/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _objectWithoutPropertiesLoose(r,e){if(null==r)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(-1!==e.indexOf(n))continue;t[n]=r[n]}return t}var Position=class{constructor(line,col,index){this.line=void 0;this.column=void 0;this.index=void 0;this.line=line;this.column=col;this.index=index}};var SourceLocation=class{constructor(start,end){this.start=void 0;this.end=void 0;this.filename=void 0;this.identifierName=void 0;this.start=start;this.end=end}};function createPositionWithColumnOffset(position,columnOffset){const{line,column,index}=position;return new Position(line,column+columnOffset,index+columnOffset)}var code="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";var ModuleErrors={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code}};var NodeDescriptions={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"};var toNodeDescription=node=>node.type==="UpdateExpression"?NodeDescriptions.UpdateExpression[`${node.prefix}`]:NodeDescriptions[node.type];var StandardErrors={AccessorIsGenerator:({kind})=>`A ${kind}ter cannot be a generator.`,ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:({kind})=>`Missing initializer in ${kind} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:({exportName})=>`\`${exportName}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName,exportName})=>`A string literal cannot be used as an exported binding without \`from\`.
96
+ `}var import_yaml3,FRONTMATTER_BOUNDARY,MAX_SAFE_ALIAS_COUNT2,MarkdownContractError;var init_markdown=__esm({"../core/src/markdown.ts"(){"use strict";import_yaml3=__toESM(require_dist(),1);FRONTMATTER_BOUNDARY="---";MAX_SAFE_ALIAS_COUNT2=10;MarkdownContractError=class extends Error{name="MarkdownContractError"}}});function parseRuleDocument(source){return parseMarkdown(source,ruleMetadataSchema)}function parseRequirementDocument(source){const document=parseMarkdown(source,requirementMetadataSchema);if(!/^## REQ-[A-Z0-9-]+\s/m.test(document.body)){throw new Error("Requirement document must declare at least one REQ section")}if(!/`?AC-[A-Z0-9-]+`?/m.test(document.body)){throw new Error("Requirement document must declare at least one Acceptance Criterion")}return document}function buildRequirementReferenceCatalog(sources){const requirementIds=new Set;const acceptanceIds=new Set;const requirementAliases=new Map;const acceptanceAliases=new Map;for(const source of sources){const document=parseRequirementDocument(source);if(document.metadata.status==="deprecated"){collectAliases(document.body,"REQ",requirementAliases);collectAliases(document.body,"AC",acceptanceAliases);continue}for(const match of document.body.matchAll(/^##\s+(REQ-[A-Z0-9-]+)(?:\s|$)/gm)){if(match[1]!==void 0)requirementIds.add(match[1])}for(const match of document.body.matchAll(/^\s*-\s+`?(AC-[A-Z0-9-]+)`?\s*:/gm)){if(match[1]!==void 0)acceptanceIds.add(match[1])}}const resolvedRequirementAliases=resolvedAliases(requirementAliases,requirementIds);const resolvedAcceptanceAliases=resolvedAliases(acceptanceAliases,acceptanceIds);return{requirement_ids:[...requirementIds].sort(),acceptance_ids:[...acceptanceIds].sort(),requirement_aliases:Object.fromEntries(resolvedRequirementAliases),acceptance_aliases:Object.fromEntries(resolvedAcceptanceAliases)}}function validateRequirementReferences(catalog,requirementIds,acceptanceIds){const knownRequirements=new Set(catalog.requirement_ids);const knownAcceptance=new Set(catalog.acceptance_ids);const findings=[];for(const id of[...new Set(requirementIds)].sort()){if(!knownRequirements.has(id)&&catalog.requirement_aliases[id]===void 0){findings.push({kind:"requirement",id,message:`Requirement does not resolve: ${id}`})}}for(const id of[...new Set(acceptanceIds)].sort()){if(!knownAcceptance.has(id)&&catalog.acceptance_aliases[id]===void 0){findings.push({kind:"acceptance",id,message:`Acceptance Criterion does not resolve: ${id}`})}}return findings}function collectAliases(body,prefix,aliases){const expression=new RegExp(`^\\s*-\\s+\\x60(${prefix}-[A-Z0-9-]+)\\x60\\s*->\\s*\\x60(${prefix}-[A-Z0-9-]+)\\x60`,"gm");for(const match of body.matchAll(expression)){const source=match[1];const target=match[2];if(source===void 0||target===void 0)continue;const existing=aliases.get(source);if(existing!==void 0&&existing!==target){throw new Error(`Divergent ${prefix} alias: ${source}`)}aliases.set(source,target)}}function resolvedAliases(aliases,canonicalIds){const resolved=[];for(const[source,target]of aliases){if(!canonicalIds.has(target)){throw new Error(`Alias target does not resolve: ${source} -> ${target}`)}resolved.push([source,target])}return resolved.sort(([left],[right])=>left.localeCompare(right))}var ruleMetadataSchema,requirementMetadataSchema;var init_governance=__esm({"../core/src/governance.ts"(){"use strict";init_zod();init_markdown();ruleMetadataSchema=external_exports.object({id:external_exports.string().regex(/^RULE-[A-Z0-9-]+$/),load:external_exports.enum(["always","auto","file_match","manual"]),globs:external_exports.array(external_exports.string().min(1)).default([]),priority:external_exports.enum(["critical","high","medium","low"]),max_context_tokens:external_exports.number().int().positive(),requires:external_exports.array(external_exports.string().regex(/^RULE-[A-Z0-9-]+$/)),triggers:external_exports.array(external_exports.string().min(1)).default([]),phases:external_exports.array(external_exports.enum(["conversation","definition","planning","execution","verification","evidence"])).default([]),domains:external_exports.array(external_exports.string().min(1)).default([])}).strict().superRefine((metadata2,context)=>{if(metadata2.load==="file_match"&&metadata2.globs.length===0){context.addIssue({code:"custom",path:["globs"],message:"file_match Rules require at least one glob"})}});requirementMetadataSchema=external_exports.object({schema_version:external_exports.literal(2),id:external_exports.string().regex(/^REQUIREMENTS-[A-Z0-9-]+$/),area:external_exports.string().regex(/^[a-z][a-z0-9-]*$/),title:external_exports.string().min(1),status:external_exports.enum(["proposed","active","deprecated"]),version:external_exports.number().int().positive(),source_change:external_exports.string().min(1).nullable(),source_release:external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional()}).strict().superRefine((metadata2,context)=>{if(metadata2.source_change===null&&metadata2.source_release===void 0){context.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"})}if(metadata2.source_change!==null&&metadata2.source_release!==void 0){context.addIssue({code:"custom",path:["source_release"],message:"source_release is only valid when source_change is null"})}})}});function validateCodexFirstRoute(input){const profile=hostCapabilityProfileSchema.parse(input.profile);if(profile.default_mode!=="codex_host_native"||!input.host_authentication_available){return{status:"exception",code:"host_authentication_unavailable"}}if(input.requires_external_provider===true){return{status:"exception",code:"external_provider_required"}}if(input.requires_remote_operation===true){return{status:"exception",code:"remote_operation_required"}}return{status:"valid",authentication:"host",remote_provider_required:false}}async function loadHostCapabilityProfile(filesystem,path=".agents/config/models/codex-host.yaml"){return hostCapabilityProfileSchema.parse(parseYaml(await filesystem.readText(path)))}var HOST_EXECUTION_MODES,MODEL_CLASSES,CODEX_NATIVE_SURFACES,hostExecutionModeSchema,modelClassSchema,codexNativeSurfaceSchema,uniqueNativeSurfacesSchema,hostCapabilityEvidenceSchema,implementedHostCapabilityClaimSchema,nativeModeProfileSchema,subprocessModeProfileSchema,modelClassProfileSchema,hostCapabilityProfileSchema,providerSubprocessOptInSchema;var init_contracts2=__esm({"../core/src/host-capabilities/contracts.ts"(){"use strict";init_zod();init_yaml();HOST_EXECUTION_MODES=["codex_host_native","provider_subprocess"];MODEL_CLASSES=["frontier","balanced","fast_scan","review"];CODEX_NATIVE_SURFACES=["subagents","worktrees","sandbox","approvals","skills","mcp"];hostExecutionModeSchema=external_exports.enum(HOST_EXECUTION_MODES);modelClassSchema=external_exports.enum(MODEL_CLASSES);codexNativeSurfaceSchema=external_exports.enum(CODEX_NATIVE_SURFACES);uniqueNativeSurfacesSchema=external_exports.array(codexNativeSurfaceSchema).min(1).refine(surfaces=>new Set(surfaces).size===surfaces.length,{message:"native_surfaces must be unique"});hostCapabilityEvidenceSchema=external_exports.object({locator:external_exports.string().min(1),candidate_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict();implementedHostCapabilityClaimSchema=external_exports.object({capability_id:external_exports.string().regex(/^CAP-[A-Z0-9-]+$/),current_state:external_exports.literal("implemented"),previous_states:external_exports.tuple([external_exports.literal("declared")]),evidence:external_exports.array(hostCapabilityEvidenceSchema).length(0)}).strict();nativeModeProfileSchema=external_exports.object({tier:external_exports.literal(1),enabled:external_exports.literal(true),optional:external_exports.literal(false),invokes_provider_subprocess:external_exports.literal(false),authority:external_exports.literal("host"),native_surfaces:uniqueNativeSurfacesSchema,capability_bindings:external_exports.record(codexNativeSurfaceSchema,implementedHostCapabilityClaimSchema)}).strict().superRefine((mode,context)=>{const bindings=Object.keys(mode.capability_bindings).sort();const surfaces=[...mode.native_surfaces].sort();if(JSON.stringify(bindings)!==JSON.stringify(surfaces)){context.addIssue({code:"custom",path:["capability_bindings"],message:"every native surface requires exactly one conformance/maturity binding"})}});subprocessModeProfileSchema=external_exports.object({tier:external_exports.union([external_exports.literal(2),external_exports.literal(3)]),enabled:external_exports.boolean(),optional:external_exports.literal(true),invokes_provider_subprocess:external_exports.literal(true),authority:external_exports.literal("framework"),native_surfaces:external_exports.array(external_exports.never()).length(0),opt_in:external_exports.object({required:external_exports.literal(true),allowed_sources:external_exports.array(external_exports.enum(["project_config","human_decision"])).min(1).refine(sources=>new Set(sources).size===sources.length,{message:"opt-in sources must be unique"})}).strict()}).strict();modelClassProfileSchema=external_exports.object({selection:external_exports.enum(["host_available","inherit_host"]),reasoning:external_exports.enum(["low","medium","high"]),intent:external_exports.string().min(1)}).strict();hostCapabilityProfileSchema=external_exports.object({schema_version:external_exports.literal(1),host_id:external_exports.literal("codex"),candidate_sha256:external_exports.null(),default_mode:external_exports.literal("codex_host_native"),modes:external_exports.object({codex_host_native:nativeModeProfileSchema,provider_subprocess:subprocessModeProfileSchema}).strict(),model_classes:external_exports.object({frontier:modelClassProfileSchema,balanced:modelClassProfileSchema,fast_scan:modelClassProfileSchema,review:modelClassProfileSchema}).strict()}).strict();providerSubprocessOptInSchema=external_exports.object({enabled:external_exports.literal(true),source:external_exports.enum(["project_config","human_decision"]),provenance:external_exports.object({reference:external_exports.string().min(1),recorded_at:external_exports.string().datetime({offset:true})}).strict()}).strict()}});var init_host_capabilities=__esm({"../core/src/host-capabilities/index.ts"(){"use strict";init_contracts2()}});function lifecycleClaimPath(kind,digest6){return`${LIFECYCLE_CLAIMS_ROOT}/${kind}/${digest6}.json`}var LIFECYCLE_CLAIMS_ROOT;var init_lifecycle_claims=__esm({"../core/src/lifecycle-claims.ts"(){"use strict";LIFECYCLE_CLAIMS_ROOT=".local/claims"}});function parseZaipManifest(value){return zaipManifestSchema.parse(value)}var zaipManifestSchema,zaipManifestJsonSchema,ManifestRepository;var init_manifest=__esm({"../core/src/manifest.ts"(){"use strict";init_zod();init_yaml();zaipManifestSchema=external_exports.object({schema_version:external_exports.literal(1),project:external_exports.object({id:external_exports.string().min(1),name:external_exports.string().min(1),timezone:external_exports.string().min(1).default("America/Sao_Paulo")}),framework:external_exports.object({version:external_exports.string().min(1)}),layout:external_exports.object({version:external_exports.literal(1),managed_namespace:external_exports.string().min(1).default(".agents/managed"),project_namespace:external_exports.string().min(1).default(".agents/project")}).default({version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"}),profile:external_exports.object({id:external_exports.string().min(1).default("zaip-aios-stack")}),paths:external_exports.object({specs:external_exports.string().min(1).default(".agents/specs"),changes:external_exports.string().min(1).default(".agents/changes"),tasks:external_exports.string().min(1).default(".agents/tasks"),decisions:external_exports.string().min(1).default(".agents/decisions"),runs:external_exports.string().min(1).default(".agents/runs")}).default({specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}),agents:external_exports.array(external_exports.enum(["codex","claude"])).default(["codex","claude"])}).strict();zaipManifestJsonSchema=external_exports.toJSONSchema(zaipManifestSchema);ManifestRepository=class{constructor(filesystem,path=".agents/manifest.yaml"){this.filesystem=filesystem;this.path=path}filesystem;path;async read(){return parseZaipManifest(parseYaml(await this.filesystem.readText(this.path)))}async write(manifest){await this.filesystem.writeTextAtomic(this.path,serializeYaml(zaipManifestSchema.parse(manifest)))}}}});function datedIdPartsWithDay(id){const match=id.match(/^([A-Z]+(?:-[A-Z]+)*)-(\d{4})-(\d{2})-(\d{2})-\d{2}-\d{2}-/);if(match?.[1]===void 0||match[2]===void 0||match[3]===void 0||match[4]===void 0){throw new TypeError(`ID does not contain the canonical date: ${id}`)}const[,prefix,year,month,day]=match;const date5=new Date(`${year}-${month}-${day}T00:00:00.000Z`);if(Number.isNaN(date5.getTime())||String(date5.getUTCFullYear()).padStart(4,"0")!==year||String(date5.getUTCMonth()+1).padStart(2,"0")!==month||String(date5.getUTCDate()).padStart(2,"0")!==day){throw new TypeError(`ID contains an invalid canonical date: ${id}`)}return{prefix,year,month,day}}function datedIdParts(id){const{year,month}=datedIdPartsWithDay(id);return{year,month}}function datedMarkdownPath(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}/${id}.md`}function datedMonthDirectory(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}`}function datedEntityDirectory(basePath,id){const{year,month,day}=datedIdPartsWithDay(id);return`${basePath}/${year}/${month}/${day}`}var init_paths=__esm({"../core/src/paths.ts"(){"use strict"}});function redactSensitive(value){return value.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/g,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[REDACTED]").replace(/\bgh[opsu]_[A-Za-z0-9_]{8,}\b/g,"[REDACTED]").replace(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]")}var init_permissions=__esm({"../core/src/policy/permissions/permissions.ts"(){"use strict"}});var init_permissions2=__esm({"../core/src/policy/permissions/index.ts"(){"use strict";init_permissions()}});var init_routing=__esm({"../core/src/policy/routing/routing.ts"(){"use strict"}});var init_routing2=__esm({"../core/src/policy/routing/index.ts"(){"use strict";init_routing()}});function assertSafeRecordContent(value){const seen=new WeakSet;function visit(item,key=""){if(typeof item==="string"){if(item.length===0||placeholder.test(item))return;if(sensitiveKey.test(key)||unsafeText(item)){throw new Error("Sensitive content cannot be persisted; redact credentials and sensitive URL parameters first.")}return}if(item===null||typeof item!=="object"||seen.has(item))return;seen.add(item);for(const[childKey,child]of Object.entries(item)){visit(child,sensitiveKey.test(key)?key:childKey)}}visit(value)}function unsafeText(text){if(redactSensitive(text)!==text)return true;if(/\bbearer\s+[a-z0-9._~+/-]+=*/i.test(text))return true;for(const match of text.matchAll(/\bbasic\s+([a-z0-9+/]+={0,2})/gi)){if(Buffer.from(match[1]??"","base64").toString("utf8").includes(":"))return true}if(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text))return true;for(const match of text.matchAll(/[a-z][a-z0-9+.-]*:\/\/[^\s<>"']+/gi)){try{const url2=new URL(match[0]);if(url2.password||/^https?:$/.test(url2.protocol)&&url2.username)return true;for(const[key,value]of url2.searchParams){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}for(const[key,value]of new URLSearchParams(url2.hash.slice(1))){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}text=text.replace(match[0],"")}catch{}}for(const match of text.matchAll(assignment)){if(!placeholder.test((match[1]??"").replace(/^(?:bearer|basic)\s+/i,"")))return true}return false}var sensitiveKeyName,sensitiveKey,placeholder,assignment;var init_record_safety=__esm({"../core/src/record-safety.ts"(){"use strict";init_permissions();sensitiveKeyName="(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|password|passwd|secret|client[_-]?secret|authorization|signature|sig)";sensitiveKey=new RegExp(`^${sensitiveKeyName}$`,"i");placeholder=/^(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})$/i;assignment=new RegExp(String.raw`\b${sensitiveKeyName}["']?\s*[:=]\s*["']?((?:(?:bearer|basic)\s+)?(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})|[^\s"',;]+)`,"gi")}});var init_result=__esm({"../core/src/result.ts"(){"use strict"}});var StateMachine,workItemStateMachine;var init_state_machine=__esm({"../core/src/state-machine.ts"(){"use strict";StateMachine=class{#transitions;constructor(transitions){const mutable=new Map;for(const transition2 of transitions){const targets=mutable.get(transition2.from)??new Set;targets.add(transition2.to);mutable.set(transition2.from,targets)}this.#transitions=mutable}canTransition(from,to){return this.#transitions.get(from)?.has(to)??false}assertTransition(from,to){if(!this.canTransition(from,to)){throw new Error(`Invalid state transition: ${from} -> ${to}`)}}nextStates(from){return[...this.#transitions.get(from)??[]]}};workItemStateMachine=new StateMachine([{from:"draft",to:"planned"},{from:"draft",to:"cancelled"},{from:"planned",to:"executing"},{from:"planned",to:"cancelled"},{from:"executing",to:"verifying"},{from:"executing",to:"blocked"},{from:"executing",to:"cancelled"},{from:"verifying",to:"completed"},{from:"verifying",to:"failed"},{from:"verifying",to:"blocked"},{from:"verifying",to:"cancelled"},{from:"blocked",to:"executing"},{from:"blocked",to:"cancelled"}])}});var stopTranscriptProofSchema,stopReceiptSchema;var init_stop_receipt_schema=__esm({"../core/src/stop-receipt-schema.ts"(){"use strict";init_zod();stopTranscriptProofSchema=external_exports.object({offset:external_exports.number().int().nonnegative(),length:external_exports.number().int().min(1).max(4194304),sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)});stopReceiptSchema=external_exports.object({schema_version:external_exports.literal(1),session_id:external_exports.string().min(1),turn_id:external_exports.string().min(1),run_id:external_exports.string().startsWith("RUN-"),observed_at:external_exports.string().datetime(),cursor:external_exports.object({path:external_exports.string().min(1),dev:external_exports.number(),ino:external_exports.number(),birthtime_ms:external_exports.number(),size:external_exports.number().int().nonnegative(),offset:external_exports.number().int().nonnegative(),mtime_ms:external_exports.number(),ctime_ms:external_exports.number(),trusted:external_exports.literal(true),terminal_status:external_exports.enum(["completed","failed","cancelled"]),session_proof:stopTranscriptProofSchema,terminal_proof:stopTranscriptProofSchema,anchor:stopTranscriptProofSchema})})}});async function loadWorkspaceLayout(filesystem){const[hasProjectConfig,hasFrameworkLock]=await Promise.all([filesystem.exists(PROJECT_CONFIG_PATH),filesystem.exists(FRAMEWORK_LOCK_PATH)]);if(hasProjectConfig!==hasFrameworkLock){const missing=hasProjectConfig?FRAMEWORK_LOCK_PATH:PROJECT_CONFIG_PATH;throw new PartialWorkspaceConfigError(`Partial V2 configuration; missing ${missing}`)}if(hasProjectConfig&&hasFrameworkLock){const[projectConfig2,frameworkLock]=await Promise.all([new ProjectConfigRepository(filesystem).read(),new FrameworkLockRepository(filesystem).read()]);return createV2WorkspaceLayout(projectConfig2,frameworkLock)}if(await filesystem.exists(".agents/manifest.yaml")){return createLegacyWorkspaceLayout(await new ManifestRepository(filesystem).read())}throw new WorkspaceLayoutNotFoundError("Workspace has neither complete V2 config nor a legacy V1 manifest")}function createV2WorkspaceLayout(projectConfig2,frameworkLock){const version2=frameworkLock.layout.version;const activeDataRoot=version2===3?".agents/records":".agents/data";return{version:version2,source:"project-config",project:projectConfig2.project,projectConfig:projectConfig2,frameworkLock,legacyManifest:null,supports:()=>true,entityRoot:kind=>`${activeDataRoot}/${v2DirectoryNames[kind]}`,activePath(kind,id){assertDatedEntityId(kind,id);const root=this.entityRoot(kind);const directory2=version2===3?datedMonthDirectory(root,id):datedEntityDirectory(root,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`},legacyReadRoot(kind){if(version2===3)return`.agents/data/${v2DirectoryNames[kind]}`;return legacyRoot(defaultLegacyRoots,kind)},legacyReadCandidate(kind,id,options){if(version2===3){return{path:v2EntityPath(".agents/data",kind,id),readOnly:true}}return legacyCandidate(defaultLegacyRoots,kind,id,options)},legacyReadCandidates(kind,id,options){if(version2===3){return[{path:v2EntityPath(".agents/records",kind,id),readOnly:true},{path:v2EntityPath(".agents/data",kind,id),readOnly:true}]}const candidate=legacyCandidate(defaultLegacyRoots,kind,id,options);return candidate===null?[]:[candidate]}}}function v2EntityPath(root,kind,id){assertDatedEntityId(kind,id);const directory2=datedEntityDirectory(`${root}/${v2DirectoryNames[kind]}`,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`}function createLegacyWorkspaceLayout(manifest){const roots2={spec:canonicalRoot(`${manifest.paths.specs}/capabilities`),change:canonicalRoot(manifest.paths.changes),task:canonicalRoot(manifest.paths.tasks),run:canonicalRoot(manifest.paths.runs)};return{version:1,source:"legacy-manifest",project:manifest.project,projectConfig:null,frameworkLock:null,legacyManifest:manifest,supports:kind=>kind!=="prd"&&kind!=="execution",entityRoot(kind){const root=legacyRoot(roots2,kind);if(root===null)throw unsupported(kind,1);return root},activePath(kind,id,options){if(!this.supports(kind))throw unsupported(kind,1);return legacyEntityPath(roots2,kind,id,options)},legacyReadRoot:()=>null,legacyReadCandidate:()=>null,legacyReadCandidates:()=>[]}}async function inspectArtifactReadState(filesystem,layout,kind,id,options){const activePath=layout.activePath(kind,id,options);const candidates=layout.legacyReadCandidates(kind,id,options);const[hasActive,...candidateExists]=await Promise.all([filesystem.exists(activePath),...candidates.map(candidate=>filesystem.exists(candidate.path))]);const existingLegacyPaths=candidates.filter((_,index)=>candidateExists[index]).map(candidate=>candidate.path);const legacyPath=existingLegacyPaths[0]??candidates[0]?.path??null;const hasLegacy=existingLegacyPaths.length>0;if(!hasActive&&!hasLegacy)return{state:"missing",activePath,legacyPath};if(hasActive&&!hasLegacy)return{state:"active-only",activePath,legacyPath};const contents=await Promise.all([...hasActive?[filesystem.readText(activePath)]:[],...existingLegacyPaths.map(path=>filesystem.readText(path))]);if(!hasActive){const[first,...rest]=contents;return{state:rest.every(content=>content===first)?"legacy-only":"duplicate-divergent",activePath,legacyPath}}const[active,...legacyContents]=contents;return{state:legacyContents.every(content=>content===active)?"duplicate-identical":"duplicate-divergent",activePath,legacyPath}}async function resolveArtifactReadPath(filesystem,layout,kind,id,options){const inspection=await inspectArtifactReadState(filesystem,layout,kind,id,options);if(inspection.state==="duplicate-divergent"){throw new InactiveLayoutConflictError(`Divergent ${kind} ${id} exists in active and legacy layouts: ${inspection.activePath}, ${inspection.legacyPath}`)}if(inspection.state==="missing")return null;if(inspection.state==="legacy-only")return inspection.legacyPath;return inspection.activePath}function legacyCandidate(roots2,kind,id,options){if(kind==="prd"||kind==="execution")return null;if(kind==="spec"&&options?.legacyCapability===void 0)return null;return{path:legacyEntityPath(roots2,kind,id,options),readOnly:true}}function legacyEntityPath(roots2,kind,id,options){assertEntityPrefix(kind,id);if(kind==="prd"||kind==="execution")throw unsupported(kind,1);if(kind==="spec"){const capability=options?.legacyCapability;if(capability===void 0||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(capability)){throw new WorkspaceLayoutError("Legacy spec lookup requires a canonical legacyCapability")}return`${roots2.spec}/${capability}/spec.md`}datedIdParts(id);if(kind==="change"){const{year,month}=datedIdParts(id);return`${roots2.change}/${year}/${month}/${id}/proposal.md`}if(kind==="task")return datedMarkdownPath(roots2.task,id);return datedMarkdownPath(roots2.run,id)}function legacyRoot(roots2,kind){if(kind==="prd"||kind==="execution")return null;return roots2[kind]}function assertDatedEntityId(kind,id){assertEntityPrefix(kind,id);datedIdPartsWithDay(id)}function assertEntityPrefix(kind,id){const prefix=expectedPrefixes[kind];if(!id.startsWith(`${prefix}-`)){throw new ArtifactKindMismatchError(`Expected ${kind} id to start with ${prefix}-: ${id}`)}}function canonicalRoot(path){if(path.length===0||path.includes("\\")||path.includes("\0")||path.startsWith("/")||path.startsWith("./")||path.endsWith("/")||/^[A-Za-z]:/.test(path)||path.split("/").some(segment2=>segment2.length===0||segment2==="."||segment2==="..")){throw new WorkspaceLayoutError(`Workspace layout path is not canonical: ${path}`)}return path}function unsupported(kind,version2){return new UnsupportedLayoutEntityError(`Layout V${version2} does not support ${kind}`)}var WorkspaceLayoutError,PartialWorkspaceConfigError,WorkspaceLayoutNotFoundError,UnsupportedLayoutEntityError,ArtifactKindMismatchError,InactiveLayoutConflictError,expectedPrefixes,v2DirectoryNames,defaultLegacyRoots;var init_workspace_layout=__esm({"../core/src/workspace-layout.ts"(){"use strict";init_config();init_manifest();init_paths();WorkspaceLayoutError=class extends Error{name="WorkspaceLayoutError"};PartialWorkspaceConfigError=class extends WorkspaceLayoutError{name="PartialWorkspaceConfigError"};WorkspaceLayoutNotFoundError=class extends WorkspaceLayoutError{name="WorkspaceLayoutNotFoundError"};UnsupportedLayoutEntityError=class extends WorkspaceLayoutError{name="UnsupportedLayoutEntityError"};ArtifactKindMismatchError=class extends WorkspaceLayoutError{name="ArtifactKindMismatchError"};InactiveLayoutConflictError=class extends WorkspaceLayoutError{name="InactiveLayoutConflictError"};expectedPrefixes={prd:"PRD",spec:"SPEC",change:"CHG",task:"TASK",execution:"EXEC",run:"RUN"};v2DirectoryNames={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};defaultLegacyRoots={spec:".agents/specs/capabilities",change:".agents/changes",task:".agents/tasks",run:".agents/runs"}}});var CORE_VERSION;var init_src=__esm({"../core/src/index.ts"(){"use strict";init_agent_runtime();init_agents();init_autonomy_policy();init_autonomy_recovery();init_clock();init_config();init_filesystem();init_git();init_governance();init_host_capabilities();init_ids();init_lifecycle_claims();init_manifest();init_markdown();init_model_orchestration();init_paths();init_permissions2();init_routing2();init_record_safety();init_result();init_state_machine();init_stop_receipt_schema();init_workspace_layout();init_yaml();CORE_VERSION="3.6.0"}});var require_lib=__commonJS({"../../node_modules/.pnpm/@babel+parser@7.29.7/node_modules/@babel/parser/lib/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _objectWithoutPropertiesLoose(r,e){if(null==r)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(-1!==e.indexOf(n))continue;t[n]=r[n]}return t}var Position=class{constructor(line,col,index){this.line=void 0;this.column=void 0;this.index=void 0;this.line=line;this.column=col;this.index=index}};var SourceLocation=class{constructor(start,end){this.start=void 0;this.end=void 0;this.filename=void 0;this.identifierName=void 0;this.start=start;this.end=end}};function createPositionWithColumnOffset(position,columnOffset){const{line,column,index}=position;return new Position(line,column+columnOffset,index+columnOffset)}var code="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";var ModuleErrors={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code}};var NodeDescriptions={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"};var toNodeDescription=node=>node.type==="UpdateExpression"?NodeDescriptions.UpdateExpression[`${node.prefix}`]:NodeDescriptions[node.type];var StandardErrors={AccessorIsGenerator:({kind})=>`A ${kind}ter cannot be a generator.`,ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:({kind})=>`Missing initializer in ${kind} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:({exportName})=>`\`${exportName}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName,exportName})=>`A string literal cannot be used as an exported binding without \`from\`.
97
97
  - Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type})=>`'${type==="ForInStatement"?"for-in":"for-of"}' loop variable declaration may not have an initializer.`,ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:({type})=>`Unsyntactic ${type==="BreakStatement"?"break":"continue"}.`,IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportAttributesUseAssert:"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",ImportBindingIsString:({importName})=>`A string literal cannot be used as an imported binding.
98
98
  - Did you mean \`import { "${importName}" as foo }\`?`,ImportCallArity:`\`import()\` requires exactly one or two arguments.`,ImportCallNotNewExpression:"Cannot use new with import(...).",ImportCallSpreadArgument:"`...` is not allowed in `import()`.",ImportJSONBindingNotDefault:"A JSON module can only be imported with `default`.",ImportReflectionHasAssertion:"`import module x` cannot have assertions.",ImportReflectionNotBinding:'Only `import module x from "./module"` is valid.',IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix})=>`Expected number in radix ${radix}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord})=>`Escape sequence in keyword ${reservedWord}.`,InvalidIdentifier:({identifierName})=>`Invalid identifier ${identifierName}.`,InvalidLhs:({ancestor})=>`Invalid left-hand side in ${toNodeDescription(ancestor)}.`,InvalidLhsBinding:({ancestor})=>`Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,InvalidLhsOptionalChaining:({ancestor})=>`Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected})=>`Unexpected character '${unexpected}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName})=>`Private name #${identifierName} is not defined.`,InvalidPropertyBindingPattern:"Binding member expression.",InvalidRecordProperty:"Only properties and spread elements are allowed in record definitions.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:({labelName})=>`Label '${labelName}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:({missingPlugin})=>`This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name=>JSON.stringify(name)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name=>JSON.stringify(name)).join(", ")}.`,MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeDifferentFromType:"The only accepted module attribute is `type`.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:({key})=>`Duplicate key "${key}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode})=>`An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,ModuleExportUndefined:({localName})=>`Export '${localName}' is not defined.`,MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:({identifierName})=>`Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,PrivateNameRedeclaration:({identifierName})=>`Duplicate private name #${identifierName}.`,RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",RecordNoProto:"'__proto__' is not allowed in Record expressions.",RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode code, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:({keyword})=>`Unexpected keyword '${keyword}'.`,UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:({reservedWord})=>`Unexpected reserved word '${reservedWord}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected,unexpected})=>`Unexpected token${unexpected?` '${unexpected}'.`:""}${expected?`, expected "${expected}"`:""}`,UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",UnsupportedBind:"Binding should be performed on object property.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:({target,onlyValidPropertyName})=>`The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName})=>`Identifier '${identifierName}' has already been declared.`,VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."};var StrictModeErrors={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName})=>`Assigning to '${referenceName}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName})=>`Binding '${bindingName}' in strict mode.`,StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block.",StrictNumericEscape:"The only valid numeric escape in strict mode is '\\0'.",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode.",StrictWith:"'with' in strict mode."};var ParseExpressionErrors={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.`};var UnparenthesizedPipeBodyDescriptions=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]);var PipelineOperatorErrors=Object.assign({PipeBodyIsTighter:"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",PipeTopicRequiresHackPipes:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:({token:token2})=>`Invalid topic token ${token2}. In order to use ${token2} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token2}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type})=>`Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({type})}; please wrap it in parentheses.`},{PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression.",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression.",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference.",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding.",PrimaryTopicRequiresSmartPipeline:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'});var _excluded=["message"];function defineHidden(obj,key,value){Object.defineProperty(obj,key,{enumerable:false,configurable:true,value})}function toParseErrorConstructor({toMessage,code:code2,reasonCode,syntaxPlugin}){const hasMissingPlugin=reasonCode==="MissingPlugin"||reasonCode==="MissingOneOfPlugins";const oldReasonCodes={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};if(oldReasonCodes[reasonCode]){reasonCode=oldReasonCodes[reasonCode]}return function constructor(loc,details){const error51=new SyntaxError;error51.code=code2;error51.reasonCode=reasonCode;error51.loc=loc;error51.pos=loc.index;error51.syntaxPlugin=syntaxPlugin;if(hasMissingPlugin){error51.missingPlugin=details.missingPlugin}defineHidden(error51,"clone",function clone2(overrides={}){var _overrides$loc;const{line,column,index}=(_overrides$loc=overrides.loc)!=null?_overrides$loc:loc;return constructor(new Position(line,column,index),Object.assign({},details,overrides.details))});defineHidden(error51,"details",details);Object.defineProperty(error51,"message",{configurable:true,get(){const message=`${toMessage(details)} (${loc.line}:${loc.column})`;this.message=message;return message},set(value){Object.defineProperty(this,"message",{value,writable:true})}});return error51}}function ParseErrorEnum(argument,syntaxPlugin){if(Array.isArray(argument)){return parseErrorTemplates=>ParseErrorEnum(parseErrorTemplates,argument[0])}const ParseErrorConstructors={};for(const reasonCode of Object.keys(argument)){const template=argument[reasonCode];const _ref=typeof template==="string"?{message:()=>template}:typeof template==="function"?{message:template}:template,{message}=_ref,rest=_objectWithoutPropertiesLoose(_ref,_excluded);const toMessage=typeof message==="string"?()=>message:message;ParseErrorConstructors[reasonCode]=toParseErrorConstructor(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode,toMessage},syntaxPlugin?{syntaxPlugin}:{},rest))}return ParseErrorConstructors}var Errors=Object.assign({},ParseErrorEnum(ModuleErrors),ParseErrorEnum(StandardErrors),ParseErrorEnum(StrictModeErrors),ParseErrorEnum(ParseExpressionErrors),ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));function createDefaultOptions(){return{sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:false,allowReturnOutsideFunction:false,allowNewTargetOutsideFunction:false,allowImportExportEverywhere:false,allowSuperOutsideMethod:false,allowUndeclaredExports:false,allowYieldOutsideFunction:false,plugins:[],strictMode:void 0,ranges:false,tokens:false,createImportExpressions:false,createParenthesizedExpressions:false,errorRecovery:false,attachComment:true,annexB:true}}function getOptions(opts){const options=createDefaultOptions();if(opts==null){return options}if(opts.annexB!=null&&opts.annexB!==false){throw new Error("The `annexB` option can only be set to `false`.")}for(const key of Object.keys(options)){if(opts[key]!=null)options[key]=opts[key]}if(options.startLine===1){if(opts.startIndex==null&&options.startColumn>0){options.startIndex=options.startColumn}else if(opts.startColumn==null&&options.startIndex>0){options.startColumn=options.startIndex}}else if(opts.startColumn==null||opts.startIndex==null){if(opts.startIndex!=null){throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.")}}if(options.sourceType==="commonjs"){if(opts.allowAwaitOutsideFunction!=null){throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.")}if(opts.allowReturnOutsideFunction!=null){throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.")}if(opts.allowNewTargetOutsideFunction!=null){throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}}return options}var{defineProperty}=Object;var toUnenumerable=(object2,key)=>{if(object2){defineProperty(object2,key,{enumerable:false,value:object2[key]})}};function toESTreeLocation(node){toUnenumerable(node.loc.start,"index");toUnenumerable(node.loc.end,"index");return node}var estree=superClass=>class ESTreeParserMixin extends superClass{parse(){const file2=toESTreeLocation(super.parse());if(this.optionFlags&256){file2.tokens=file2.tokens.map(toESTreeLocation)}return file2}parseRegExpLiteral({pattern,flags}){let regex=null;try{regex=new RegExp(pattern,flags)}catch(_){}const node=this.estreeParseLiteral(regex);node.regex={pattern,flags};return node}parseBigIntLiteral(value){let bigInt;try{bigInt=BigInt(value)}catch(_unused){bigInt=null}const node=this.estreeParseLiteral(bigInt);node.bigint=String(node.value||value);return node}parseDecimalLiteral(value){const decimal=null;const node=this.estreeParseLiteral(decimal);node.decimal=String(node.value||value);return node}estreeParseLiteral(value){return this.parseLiteral(value,"Literal")}parseStringLiteral(value){return this.estreeParseLiteral(value)}parseNumericLiteral(value){return this.estreeParseLiteral(value)}parseNullLiteral(){return this.estreeParseLiteral(null)}parseBooleanLiteral(value){return this.estreeParseLiteral(value)}estreeParseChainExpression(node,endLoc){const chain=this.startNodeAtNode(node);chain.expression=node;return this.finishNodeAt(chain,"ChainExpression",endLoc)}directiveToStmt(directive){const expression=directive.value;delete directive.value;this.castNodeTo(expression,"Literal");expression.raw=expression.extra.raw;expression.value=expression.extra.expressionValue;const stmt=this.castNodeTo(directive,"ExpressionStatement");stmt.expression=expression;stmt.directive=expression.extra.rawValue;delete expression.extra;return stmt}fillOptionalPropertiesForTSESLint(node){}cloneEstreeStringLiteral(node){const{start,end,loc,range,raw,value}=node;const cloned=Object.create(node.constructor.prototype);cloned.type="Literal";cloned.start=start;cloned.end=end;cloned.loc=loc;cloned.range=range;cloned.raw=raw;cloned.value=value;return cloned}initFunction(node,isAsync){super.initFunction(node,isAsync);node.expression=false}checkDeclaration(node){if(node!=null&&this.isObjectProperty(node)){this.checkDeclaration(node.value)}else{super.checkDeclaration(node)}}getObjectOrClassMethodParams(method){return method.value.params}isValidDirective(stmt){var _stmt$expression$extr;return stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&typeof stmt.expression.value==="string"&&!((_stmt$expression$extr=stmt.expression.extra)!=null&&_stmt$expression$extr.parenthesized)}parseBlockBody(node,allowDirectives,topLevel,end,afterBlockParse){super.parseBlockBody(node,allowDirectives,topLevel,end,afterBlockParse);const directiveStatements=node.directives.map(d=>this.directiveToStmt(d));node.body=directiveStatements.concat(node.body);delete node.directives}parsePrivateName(){const node=super.parsePrivateName();if(!this.getPluginOption("estree","classFeatures")){return node}return this.convertPrivateNameToPrivateIdentifier(node)}convertPrivateNameToPrivateIdentifier(node){const name=super.getPrivateNameSV(node);delete node.id;node.name=name;return this.castNodeTo(node,"PrivateIdentifier")}isPrivateName(node){if(!this.getPluginOption("estree","classFeatures")){return super.isPrivateName(node)}return node.type==="PrivateIdentifier"}getPrivateNameSV(node){if(!this.getPluginOption("estree","classFeatures")){return super.getPrivateNameSV(node)}return node.name}parseLiteral(value,type){const node=super.parseLiteral(value,type);node.raw=node.extra.raw;delete node.extra;return node}parseFunctionBody(node,allowExpression,isMethod=false){super.parseFunctionBody(node,allowExpression,isMethod);node.expression=node.body.type!=="BlockStatement"}parseMethod(node,isGenerator,isAsync,isConstructor,allowDirectSuper,type,inClassScope=false){let funcNode=this.startNode();funcNode.kind=node.kind;funcNode=super.parseMethod(funcNode,isGenerator,isAsync,isConstructor,allowDirectSuper,type,inClassScope);delete funcNode.kind;const{typeParameters}=node;if(typeParameters){delete node.typeParameters;funcNode.typeParameters=typeParameters;this.resetStartLocationFromNode(funcNode,typeParameters)}const valueNode=this.castNodeTo(funcNode,"FunctionExpression");node.value=valueNode;if(type==="ClassPrivateMethod"){node.computed=false}if(type==="ObjectMethod"){if(node.kind==="method"){node.kind="init"}node.shorthand=false;return this.finishNode(node,"Property")}else{return this.finishNode(node,"MethodDefinition")}}nameIsConstructor(key){if(key.type==="Literal")return key.value==="constructor";return super.nameIsConstructor(key)}parseClassProperty(...args){const propertyNode=super.parseClassProperty(...args);if(!this.getPluginOption("estree","classFeatures")){return propertyNode}this.castNodeTo(propertyNode,"PropertyDefinition");return propertyNode}parseClassPrivateProperty(...args){const propertyNode=super.parseClassPrivateProperty(...args);if(!this.getPluginOption("estree","classFeatures")){return propertyNode}this.castNodeTo(propertyNode,"PropertyDefinition");propertyNode.computed=false;return propertyNode}parseClassAccessorProperty(node){const accessorPropertyNode=super.parseClassAccessorProperty(node);if(!this.getPluginOption("estree","classFeatures")){return accessorPropertyNode}if(accessorPropertyNode.abstract&&this.hasPlugin("typescript")){delete accessorPropertyNode.abstract;this.castNodeTo(accessorPropertyNode,"TSAbstractAccessorProperty")}else{this.castNodeTo(accessorPropertyNode,"AccessorProperty")}return accessorPropertyNode}parseObjectProperty(prop,startLoc,isPattern,refExpressionErrors){const node=super.parseObjectProperty(prop,startLoc,isPattern,refExpressionErrors);if(node){node.kind="init";this.castNodeTo(node,"Property")}return node}finishObjectProperty(node){node.kind="init";return this.finishNode(node,"Property")}isValidLVal(type,disallowCallExpression,isUnparenthesizedInAssign,binding){return type==="Property"?"value":super.isValidLVal(type,disallowCallExpression,isUnparenthesizedInAssign,binding)}isAssignable(node,isBinding){if(node!=null&&this.isObjectProperty(node)){return this.isAssignable(node.value,isBinding)}return super.isAssignable(node,isBinding)}toAssignable(node,isLHS=false){if(node!=null&&this.isObjectProperty(node)){const{key,value}=node;if(this.isPrivateName(key)){this.classScope.usePrivateName(this.getPrivateNameSV(key),key.loc.start)}this.toAssignable(value,isLHS)}else{super.toAssignable(node,isLHS)}}toAssignableObjectExpressionProp(prop,isLast,isLHS){if(prop.type==="Property"&&(prop.kind==="get"||prop.kind==="set")){this.raise(Errors.PatternHasAccessor,prop.key)}else if(prop.type==="Property"&&prop.method){this.raise(Errors.PatternHasMethod,prop.key)}else{super.toAssignableObjectExpressionProp(prop,isLast,isLHS)}}finishCallExpression(unfinished,optional2){const node=super.finishCallExpression(unfinished,optional2);if(node.callee.type==="Import"){var _ref,_ref2;this.castNodeTo(node,"ImportExpression");node.source=node.arguments[0];node.options=(_ref=node.arguments[1])!=null?_ref:null;node.attributes=(_ref2=node.arguments[1])!=null?_ref2:null;delete node.arguments;delete node.callee}else if(node.type==="OptionalCallExpression"){this.castNodeTo(node,"CallExpression")}else{node.optional=false}return node}toReferencedArguments(node){if(node.type==="ImportExpression"){return}super.toReferencedArguments(node)}parseExport(unfinished,decorators){const exportStartLoc=this.state.lastTokStartLoc;const node=super.parseExport(unfinished,decorators);switch(node.type){case"ExportAllDeclaration":node.exported=null;break;case"ExportNamedDeclaration":if(node.specifiers.length===1&&node.specifiers[0].type==="ExportNamespaceSpecifier"){this.castNodeTo(node,"ExportAllDeclaration");node.exported=node.specifiers[0].exported;delete node.specifiers}case"ExportDefaultDeclaration":{var _declaration$decorato;const{declaration}=node;if((declaration==null?void 0:declaration.type)==="ClassDeclaration"&&((_declaration$decorato=declaration.decorators)==null?void 0:_declaration$decorato.length)>0&&declaration.start===node.start){this.resetStartLocation(node,exportStartLoc)}}break}return node}stopParseSubscript(base,state){const node=super.stopParseSubscript(base,state);if(state.optionalChainMember){return this.estreeParseChainExpression(node,base.loc.end)}return node}parseMember(base,startLoc,state,computed,optional2){const node=super.parseMember(base,startLoc,state,computed,optional2);if(node.type==="OptionalMemberExpression"){this.castNodeTo(node,"MemberExpression")}else{node.optional=false}return node}isOptionalMemberExpression(node){if(node.type==="ChainExpression"){return node.expression.type==="MemberExpression"}return super.isOptionalMemberExpression(node)}hasPropertyAsPrivateName(node){if(node.type==="ChainExpression"){node=node.expression}return super.hasPropertyAsPrivateName(node)}isObjectProperty(node){return node.type==="Property"&&node.kind==="init"&&!node.method}isObjectMethod(node){return node.type==="Property"&&(node.method||node.kind==="get"||node.kind==="set")}castNodeTo(node,type){const result2=super.castNodeTo(node,type);this.fillOptionalPropertiesForTSESLint(result2);return result2}cloneIdentifier(node){const cloned=super.cloneIdentifier(node);this.fillOptionalPropertiesForTSESLint(cloned);return cloned}cloneStringLiteral(node){if(node.type==="Literal"){return this.cloneEstreeStringLiteral(node)}return super.cloneStringLiteral(node)}finishNodeAt(node,type,endLoc){return toESTreeLocation(super.finishNodeAt(node,type,endLoc))}finishNode(node,type){const result2=super.finishNode(node,type);this.fillOptionalPropertiesForTSESLint(result2);return result2}resetStartLocation(node,startLoc){super.resetStartLocation(node,startLoc);toESTreeLocation(node)}resetEndLocation(node,endLoc=this.state.lastTokEndLoc){super.resetEndLocation(node,endLoc);toESTreeLocation(node)}};var TokContext=class{constructor(token2,preserveSpace){this.token=void 0;this.preserveSpace=void 0;this.token=token2;this.preserveSpace=!!preserveSpace}};var types={brace:new TokContext("{"),j_oTag:new TokContext("<tag"),j_cTag:new TokContext("</tag"),j_expr:new TokContext("<tag>...</tag>",true)};types.template=new TokContext("`",true);var beforeExpr=true;var startsExpr=true;var isLoop=true;var isAssign=true;var prefix=true;var postfix=true;var ExportedTokenType=class{constructor(label,conf={}){this.label=void 0;this.keyword=void 0;this.beforeExpr=void 0;this.startsExpr=void 0;this.rightAssociative=void 0;this.isLoop=void 0;this.isAssign=void 0;this.prefix=void 0;this.postfix=void 0;this.binop=void 0;this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.rightAssociative=!!conf.rightAssociative;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop!=null?conf.binop:null;this.updateContext=null}};var keywords$1=new Map;function createKeyword(name,options={}){options.keyword=name;const token2=createToken(name,options);keywords$1.set(name,token2);return token2}function createBinop(name,binop){return createToken(name,{beforeExpr,binop})}var tokenTypeCounter=-1;var tokenTypes=[];var tokenLabels=[];var tokenBinops=[];var tokenBeforeExprs=[];var tokenStartsExprs=[];var tokenPrefixes=[];function createToken(name,options={}){var _options$binop,_options$beforeExpr,_options$startsExpr,_options$prefix;++tokenTypeCounter;tokenLabels.push(name);tokenBinops.push((_options$binop=options.binop)!=null?_options$binop:-1);tokenBeforeExprs.push((_options$beforeExpr=options.beforeExpr)!=null?_options$beforeExpr:false);tokenStartsExprs.push((_options$startsExpr=options.startsExpr)!=null?_options$startsExpr:false);tokenPrefixes.push((_options$prefix=options.prefix)!=null?_options$prefix:false);tokenTypes.push(new ExportedTokenType(name,options));return tokenTypeCounter}function createKeywordLike(name,options={}){var _options$binop2,_options$beforeExpr2,_options$startsExpr2,_options$prefix2;++tokenTypeCounter;keywords$1.set(name,tokenTypeCounter);tokenLabels.push(name);tokenBinops.push((_options$binop2=options.binop)!=null?_options$binop2:-1);tokenBeforeExprs.push((_options$beforeExpr2=options.beforeExpr)!=null?_options$beforeExpr2:false);tokenStartsExprs.push((_options$startsExpr2=options.startsExpr)!=null?_options$startsExpr2:false);tokenPrefixes.push((_options$prefix2=options.prefix)!=null?_options$prefix2:false);tokenTypes.push(new ExportedTokenType("name",options));return tokenTypeCounter}var tt={bracketL:createToken("[",{beforeExpr,startsExpr}),bracketHashL:createToken("#[",{beforeExpr,startsExpr}),bracketBarL:createToken("[|",{beforeExpr,startsExpr}),bracketR:createToken("]"),bracketBarR:createToken("|]"),braceL:createToken("{",{beforeExpr,startsExpr}),braceBarL:createToken("{|",{beforeExpr,startsExpr}),braceHashL:createToken("#{",{beforeExpr,startsExpr}),braceR:createToken("}"),braceBarR:createToken("|}"),parenL:createToken("(",{beforeExpr,startsExpr}),parenR:createToken(")"),comma:createToken(",",{beforeExpr}),semi:createToken(";",{beforeExpr}),colon:createToken(":",{beforeExpr}),doubleColon:createToken("::",{beforeExpr}),dot:createToken("."),question:createToken("?",{beforeExpr}),questionDot:createToken("?."),arrow:createToken("=>",{beforeExpr}),template:createToken("template"),ellipsis:createToken("...",{beforeExpr}),backQuote:createToken("`",{startsExpr}),dollarBraceL:createToken("${",{beforeExpr,startsExpr}),templateTail:createToken("...`",{startsExpr}),templateNonTail:createToken("...${",{beforeExpr,startsExpr}),at:createToken("@"),hash:createToken("#",{startsExpr}),interpreterDirective:createToken("#!..."),eq:createToken("=",{beforeExpr,isAssign}),assign:createToken("_=",{beforeExpr,isAssign}),slashAssign:createToken("_=",{beforeExpr,isAssign}),xorAssign:createToken("_=",{beforeExpr,isAssign}),moduloAssign:createToken("_=",{beforeExpr,isAssign}),incDec:createToken("++/--",{prefix,postfix,startsExpr}),bang:createToken("!",{beforeExpr,prefix,startsExpr}),tilde:createToken("~",{beforeExpr,prefix,startsExpr}),doubleCaret:createToken("^^",{startsExpr}),doubleAt:createToken("@@",{startsExpr}),pipeline:createBinop("|>",0),nullishCoalescing:createBinop("??",1),logicalOR:createBinop("||",1),logicalAND:createBinop("&&",2),bitwiseOR:createBinop("|",3),bitwiseXOR:createBinop("^",4),bitwiseAND:createBinop("&",5),equality:createBinop("==/!=/===/!==",6),lt:createBinop("</>/<=/>=",7),gt:createBinop("</>/<=/>=",7),relational:createBinop("</>/<=/>=",7),bitShift:createBinop("<</>>/>>>",8),bitShiftL:createBinop("<</>>/>>>",8),bitShiftR:createBinop("<</>>/>>>",8),plusMin:createToken("+/-",{beforeExpr,binop:9,prefix,startsExpr}),modulo:createToken("%",{binop:10,startsExpr}),star:createToken("*",{binop:10}),slash:createBinop("/",10),exponent:createToken("**",{beforeExpr,binop:11,rightAssociative:true}),_in:createKeyword("in",{beforeExpr,binop:7}),_instanceof:createKeyword("instanceof",{beforeExpr,binop:7}),_break:createKeyword("break"),_case:createKeyword("case",{beforeExpr}),_catch:createKeyword("catch"),_continue:createKeyword("continue"),_debugger:createKeyword("debugger"),_default:createKeyword("default",{beforeExpr}),_else:createKeyword("else",{beforeExpr}),_finally:createKeyword("finally"),_function:createKeyword("function",{startsExpr}),_if:createKeyword("if"),_return:createKeyword("return",{beforeExpr}),_switch:createKeyword("switch"),_throw:createKeyword("throw",{beforeExpr,prefix,startsExpr}),_try:createKeyword("try"),_var:createKeyword("var"),_const:createKeyword("const"),_with:createKeyword("with"),_new:createKeyword("new",{beforeExpr,startsExpr}),_this:createKeyword("this",{startsExpr}),_super:createKeyword("super",{startsExpr}),_class:createKeyword("class",{startsExpr}),_extends:createKeyword("extends",{beforeExpr}),_export:createKeyword("export"),_import:createKeyword("import",{startsExpr}),_null:createKeyword("null",{startsExpr}),_true:createKeyword("true",{startsExpr}),_false:createKeyword("false",{startsExpr}),_typeof:createKeyword("typeof",{beforeExpr,prefix,startsExpr}),_void:createKeyword("void",{beforeExpr,prefix,startsExpr}),_delete:createKeyword("delete",{beforeExpr,prefix,startsExpr}),_do:createKeyword("do",{isLoop,beforeExpr}),_for:createKeyword("for",{isLoop}),_while:createKeyword("while",{isLoop}),_as:createKeywordLike("as",{startsExpr}),_assert:createKeywordLike("assert",{startsExpr}),_async:createKeywordLike("async",{startsExpr}),_await:createKeywordLike("await",{startsExpr}),_defer:createKeywordLike("defer",{startsExpr}),_from:createKeywordLike("from",{startsExpr}),_get:createKeywordLike("get",{startsExpr}),_let:createKeywordLike("let",{startsExpr}),_meta:createKeywordLike("meta",{startsExpr}),_of:createKeywordLike("of",{startsExpr}),_sent:createKeywordLike("sent",{startsExpr}),_set:createKeywordLike("set",{startsExpr}),_source:createKeywordLike("source",{startsExpr}),_static:createKeywordLike("static",{startsExpr}),_using:createKeywordLike("using",{startsExpr}),_yield:createKeywordLike("yield",{startsExpr}),_asserts:createKeywordLike("asserts",{startsExpr}),_checks:createKeywordLike("checks",{startsExpr}),_exports:createKeywordLike("exports",{startsExpr}),_global:createKeywordLike("global",{startsExpr}),_implements:createKeywordLike("implements",{startsExpr}),_intrinsic:createKeywordLike("intrinsic",{startsExpr}),_infer:createKeywordLike("infer",{startsExpr}),_is:createKeywordLike("is",{startsExpr}),_mixins:createKeywordLike("mixins",{startsExpr}),_proto:createKeywordLike("proto",{startsExpr}),_require:createKeywordLike("require",{startsExpr}),_satisfies:createKeywordLike("satisfies",{startsExpr}),_keyof:createKeywordLike("keyof",{startsExpr}),_readonly:createKeywordLike("readonly",{startsExpr}),_unique:createKeywordLike("unique",{startsExpr}),_abstract:createKeywordLike("abstract",{startsExpr}),_declare:createKeywordLike("declare",{startsExpr}),_enum:createKeywordLike("enum",{startsExpr}),_module:createKeywordLike("module",{startsExpr}),_namespace:createKeywordLike("namespace",{startsExpr}),_interface:createKeywordLike("interface",{startsExpr}),_type:createKeywordLike("type",{startsExpr}),_opaque:createKeywordLike("opaque",{startsExpr}),name:createToken("name",{startsExpr}),placeholder:createToken("%%",{startsExpr}),string:createToken("string",{startsExpr}),num:createToken("num",{startsExpr}),bigint:createToken("bigint",{startsExpr}),decimal:createToken("decimal",{startsExpr}),regexp:createToken("regexp",{startsExpr}),privateName:createToken("#name",{startsExpr}),eof:createToken("eof"),jsxName:createToken("jsxName"),jsxText:createToken("jsxText",{beforeExpr}),jsxTagStart:createToken("jsxTagStart",{startsExpr}),jsxTagEnd:createToken("jsxTagEnd")};function tokenIsIdentifier(token2){return token2>=93&&token2<=133}function tokenKeywordOrIdentifierIsKeyword(token2){return token2<=92}function tokenIsKeywordOrIdentifier(token2){return token2>=58&&token2<=133}function tokenIsLiteralPropertyName(token2){return token2>=58&&token2<=137}function tokenComesBeforeExpression(token2){return tokenBeforeExprs[token2]}function tokenCanStartExpression(token2){return tokenStartsExprs[token2]}function tokenIsAssignment(token2){return token2>=29&&token2<=33}function tokenIsFlowInterfaceOrTypeOrOpaque(token2){return token2>=129&&token2<=131}function tokenIsLoop(token2){return token2>=90&&token2<=92}function tokenIsKeyword(token2){return token2>=58&&token2<=92}function tokenIsOperator(token2){return token2>=39&&token2<=59}function tokenIsPostfix(token2){return token2===34}function tokenIsPrefix(token2){return tokenPrefixes[token2]}function tokenIsTSTypeOperator(token2){return token2>=121&&token2<=123}function tokenIsTSDeclarationStart(token2){return token2>=124&&token2<=130}function tokenLabelName(token2){return tokenLabels[token2]}function tokenOperatorPrecedence(token2){return tokenBinops[token2]}function tokenIsRightAssociative(token2){return token2===57}function tokenIsTemplate(token2){return token2>=24&&token2<=25}function getExportedToken(token2){return tokenTypes[token2]}tokenTypes[8].updateContext=context=>{context.pop()};tokenTypes[5].updateContext=tokenTypes[7].updateContext=tokenTypes[23].updateContext=context=>{context.push(types.brace)};tokenTypes[22].updateContext=context=>{if(context[context.length-1]===types.template){context.pop()}else{context.push(types.template)}};tokenTypes[143].updateContext=context=>{context.push(types.j_expr,types.j_oTag)};var nonASCIIidentifierStartChars="\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";var nonASCIIidentifierChars="\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");nonASCIIidentifierStartChars=nonASCIIidentifierChars=null;var astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489];var astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(code2,set2){let pos=65536;for(let i=0,length=set2.length;i<length;i+=2){pos+=set2[i];if(pos>code2)return false;pos+=set2[i+1];if(pos>=code2)return true}return false}function isIdentifierStart(code2){if(code2<65)return code2===36;if(code2<=90)return true;if(code2<97)return code2===95;if(code2<=122)return true;if(code2<=65535){return code2>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code2))}return isInAstralSet(code2,astralIdentifierStartCodes)}function isIdentifierChar(code2){if(code2<48)return code2===36;if(code2<58)return true;if(code2<65)return false;if(code2<=90)return true;if(code2<97)return code2===95;if(code2<=122)return true;if(code2<=65535){return code2>=170&&nonASCIIidentifier.test(String.fromCharCode(code2))}return isInAstralSet(code2,astralIdentifierStartCodes)||isInAstralSet(code2,astralIdentifierCodes)}var reservedWords={keyword:["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"],strict:["implements","interface","let","package","private","protected","public","static","yield"],strictBind:["eval","arguments"]};var keywords=new Set(reservedWords.keyword);var reservedWordsStrictSet=new Set(reservedWords.strict);var reservedWordsStrictBindSet=new Set(reservedWords.strictBind);function isReservedWord(word,inModule){return inModule&&word==="await"||word==="enum"}function isStrictReservedWord(word,inModule){return isReservedWord(word,inModule)||reservedWordsStrictSet.has(word)}function isStrictBindOnlyReservedWord(word){return reservedWordsStrictBindSet.has(word)}function isStrictBindReservedWord(word,inModule){return isStrictReservedWord(word,inModule)||isStrictBindOnlyReservedWord(word)}function isKeyword(word){return keywords.has(word)}function isIteratorStart(current,next,next2){return current===64&&next===64&&isIdentifierStart(next2)}var reservedWordLikeSet=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);function canBeReservedWord(word){return reservedWordLikeSet.has(word)}var Scope=class{constructor(flags){this.flags=0;this.names=new Map;this.firstLexicalName="";this.flags=flags}};var ScopeHandler=class{constructor(parser,inModule){this.parser=void 0;this.scopeStack=[];this.inModule=void 0;this.undefinedExports=new Map;this.parser=parser;this.inModule=inModule}get inTopLevel(){return(this.currentScope().flags&1)>0}get inFunction(){return(this.currentVarScopeFlags()&2)>0}get allowSuper(){return(this.currentThisScopeFlags()&16)>0}get allowDirectSuper(){return(this.currentThisScopeFlags()&32)>0}get allowNewTarget(){return(this.currentThisScopeFlags()&512)>0}get inClass(){return(this.currentThisScopeFlags()&64)>0}get inClassAndNotInNonArrowFunction(){const flags=this.currentThisScopeFlags();return(flags&64)>0&&(flags&2)===0}get inStaticBlock(){for(let i=this.scopeStack.length-1;;i--){const{flags}=this.scopeStack[i];if(flags&128){return true}if(flags&(1667|64)){return false}}}get inNonArrowFunction(){return(this.currentThisScopeFlags()&2)>0}get inBareCaseStatement(){return(this.currentScope().flags&256)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(flags){return new Scope(flags)}enter(flags){this.scopeStack.push(this.createScope(flags))}exit(){const scope=this.scopeStack.pop();return scope.flags}treatFunctionsAsVarInScope(scope){return!!(scope.flags&(2|128)||!this.parser.inModule&&scope.flags&1)}declareName(name,bindingType,loc){let scope=this.currentScope();if(bindingType&8||bindingType&16){this.checkRedeclarationInScope(scope,name,bindingType,loc);let type=scope.names.get(name)||0;if(bindingType&16){type=type|4}else{if(!scope.firstLexicalName){scope.firstLexicalName=name}type=type|2}scope.names.set(name,type);if(bindingType&8){this.maybeExportDefined(scope,name)}}else if(bindingType&4){for(let i=this.scopeStack.length-1;i>=0;--i){scope=this.scopeStack[i];this.checkRedeclarationInScope(scope,name,bindingType,loc);scope.names.set(name,(scope.names.get(name)||0)|1);this.maybeExportDefined(scope,name);if(scope.flags&1667)break}}if(this.parser.inModule&&scope.flags&1){this.undefinedExports.delete(name)}}maybeExportDefined(scope,name){if(this.parser.inModule&&scope.flags&1){this.undefinedExports.delete(name)}}checkRedeclarationInScope(scope,name,bindingType,loc){if(this.isRedeclaredInScope(scope,name,bindingType)){this.parser.raise(Errors.VarRedeclaration,loc,{identifierName:name})}}isRedeclaredInScope(scope,name,bindingType){if(!(bindingType&1))return false;if(bindingType&8){return scope.names.has(name)}const type=scope.names.get(name)||0;if(bindingType&16){return(type&2)>0||!this.treatFunctionsAsVarInScope(scope)&&(type&1)>0}return(type&2)>0&&!(scope.flags&8&&scope.firstLexicalName===name)||!this.treatFunctionsAsVarInScope(scope)&&(type&4)>0}checkLocalExport(id){const{name}=id;const topLevelScope=this.scopeStack[0];if(!topLevelScope.names.has(name)){this.undefinedExports.set(name,id.loc.start)}}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let i=this.scopeStack.length-1;;i--){const{flags}=this.scopeStack[i];if(flags&1667){return flags}}}currentThisScopeFlags(){for(let i=this.scopeStack.length-1;;i--){const{flags}=this.scopeStack[i];if(flags&(1667|64)&&!(flags&4)){return flags}}}};var FlowScope=class extends Scope{constructor(...args){super(...args);this.declareFunctions=new Set}};var FlowScopeHandler=class extends ScopeHandler{createScope(flags){return new FlowScope(flags)}declareName(name,bindingType,loc){const scope=this.currentScope();if(bindingType&2048){this.checkRedeclarationInScope(scope,name,bindingType,loc);this.maybeExportDefined(scope,name);scope.declareFunctions.add(name);return}super.declareName(name,bindingType,loc)}isRedeclaredInScope(scope,name,bindingType){if(super.isRedeclaredInScope(scope,name,bindingType))return true;if(bindingType&2048&&!scope.declareFunctions.has(name)){const type=scope.names.get(name);return(type&4)>0||(type&2)>0}return false}checkLocalExport(id){if(!this.scopeStack[0].declareFunctions.has(id.name)){super.checkLocalExport(id)}}};var reservedTypes=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]);var FlowErrors=ParseErrorEnum`flow`({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType})=>`Cannot overwrite reserved type ${reservedType}.`,DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:({memberName,enumName})=>`Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,EnumDuplicateMemberName:({memberName,enumName})=>`Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,EnumInconsistentMemberValues:({enumName})=>`Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType,enumName})=>`Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName,memberName,explicitType})=>`Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName,memberName})=>`Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName,memberName})=>`The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,EnumInvalidMemberName:({enumName,memberName,suggestion})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,EnumNumberMemberNotInitialized:({enumName,memberName})=>`Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` or `typeof` keyword.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:Object.assign({message:"A binding pattern parameter cannot be optional in an implementation signature."},{reasonCode:"OptionalBindingPattern"}),SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:({reservedType})=>`Unexpected reserved type ${reservedType}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind,suggestion})=>`\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function isEsModuleType(bodyElement){return bodyElement.type==="DeclareExportAllDeclaration"||bodyElement.type==="DeclareExportDeclaration"&&(!bodyElement.declaration||bodyElement.declaration.type!=="TypeAlias"&&bodyElement.declaration.type!=="InterfaceDeclaration")}function hasTypeImportKind(node){return node.importKind==="type"||node.importKind==="typeof"}var exportSuggestions={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function partition(list,test){const list1=[];const list2=[];for(let i=0;i<list.length;i++){(test(list[i],i,list)?list1:list2).push(list[i])}return[list1,list2]}var FLOW_PRAGMA_REGEX=/\*?\s*@((?:no)?flow)\b/;var flow=superClass=>class FlowParserMixin extends superClass{constructor(...args){super(...args);this.flowPragma=void 0}getScopeHandler(){return FlowScopeHandler}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(type,val){if(type!==134&&type!==13&&type!==28){if(this.flowPragma===void 0){this.flowPragma=null}}super.finishToken(type,val)}addComment(comment){if(this.flowPragma===void 0){const matches=FLOW_PRAGMA_REGEX.exec(comment.value);if(!matches);else if(matches[1]==="flow"){this.flowPragma="flow"}else if(matches[1]==="noflow"){this.flowPragma="noflow"}else{throw new Error("Unexpected flow pragma")}}super.addComment(comment)}flowParseTypeInitialiser(tok){const oldInType=this.state.inType;this.state.inType=true;this.expect(tok||14);const type=this.flowParseType();this.state.inType=oldInType;return type}flowParsePredicate(){const node=this.startNode();const moduloLoc=this.state.startLoc;this.next();this.expectContextual(110);if(this.state.lastTokStartLoc.index>moduloLoc.index+1){this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks,moduloLoc)}if(this.eat(10)){node.value=super.parseExpression();this.expect(11);return this.finishNode(node,"DeclaredPredicate")}else{return this.finishNode(node,"InferredPredicate")}}flowParseTypeAndPredicateInitialiser(){const oldInType=this.state.inType;this.state.inType=true;this.expect(14);let type=null;let predicate=null;if(this.match(54)){this.state.inType=oldInType;predicate=this.flowParsePredicate()}else{type=this.flowParseType();this.state.inType=oldInType;if(this.match(54)){predicate=this.flowParsePredicate()}}return[type,predicate]}flowParseDeclareClass(node){this.next();this.flowParseInterfaceish(node,true);return this.finishNode(node,"DeclareClass")}flowParseDeclareFunction(node){this.next();const id=node.id=this.parseIdentifier();const typeNode=this.startNode();const typeContainer=this.startNode();if(this.match(47)){typeNode.typeParameters=this.flowParseTypeParameterDeclaration()}else{typeNode.typeParameters=null}this.expect(10);const tmp=this.flowParseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;typeNode.this=tmp._this;this.expect(11);[typeNode.returnType,node.predicate]=this.flowParseTypeAndPredicateInitialiser();typeContainer.typeAnnotation=this.finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=this.finishNode(typeContainer,"TypeAnnotation");this.resetEndLocation(id);this.semicolon();this.scope.declareName(node.id.name,2048,node.id.loc.start);return this.finishNode(node,"DeclareFunction")}flowParseDeclare(node,insideModule){if(this.match(80)){return this.flowParseDeclareClass(node)}else if(this.match(68)){return this.flowParseDeclareFunction(node)}else if(this.match(74)){return this.flowParseDeclareVariable(node)}else if(this.eatContextual(127)){if(this.match(16)){return this.flowParseDeclareModuleExports(node)}else{if(insideModule){this.raise(FlowErrors.NestedDeclareModule,this.state.lastTokStartLoc)}return this.flowParseDeclareModule(node)}}else if(this.isContextual(130)){return this.flowParseDeclareTypeAlias(node)}else if(this.isContextual(131)){return this.flowParseDeclareOpaqueType(node)}else if(this.isContextual(129)){return this.flowParseDeclareInterface(node)}else if(this.match(82)){return this.flowParseDeclareExportDeclaration(node,insideModule)}throw this.unexpected()}flowParseDeclareVariable(node){this.next();node.id=this.flowParseTypeAnnotatableIdentifier();this.scope.declareName(node.id.name,5,node.id.loc.start);this.semicolon();return this.finishNode(node,"DeclareVariable")}flowParseDeclareModule(node){this.scope.enter(0);if(this.match(134)){node.id=super.parseExprAtom()}else{node.id=this.parseIdentifier()}const bodyNode=node.body=this.startNode();const body=bodyNode.body=[];this.expect(5);while(!this.match(8)){const bodyNode2=this.startNode();if(this.match(83)){this.next();if(!this.isContextual(130)&&!this.match(87)){this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc)}body.push(super.parseImport(bodyNode2))}else{this.expectContextual(125,FlowErrors.UnsupportedStatementInDeclareModule);body.push(this.flowParseDeclare(bodyNode2,true))}}this.scope.exit();this.expect(8);this.finishNode(bodyNode,"BlockStatement");let kind=null;let hasModuleExport=false;body.forEach(bodyElement=>{if(isEsModuleType(bodyElement)){if(kind==="CommonJS"){this.raise(FlowErrors.AmbiguousDeclareModuleKind,bodyElement)}kind="ES"}else if(bodyElement.type==="DeclareModuleExports"){if(hasModuleExport){this.raise(FlowErrors.DuplicateDeclareModuleExports,bodyElement)}if(kind==="ES"){this.raise(FlowErrors.AmbiguousDeclareModuleKind,bodyElement)}kind="CommonJS";hasModuleExport=true}});node.kind=kind||"CommonJS";return this.finishNode(node,"DeclareModule")}flowParseDeclareExportDeclaration(node,insideModule){this.expect(82);if(this.eat(65)){if(this.match(68)||this.match(80)){node.declaration=this.flowParseDeclare(this.startNode())}else{node.declaration=this.flowParseType();this.semicolon()}node.default=true;return this.finishNode(node,"DeclareExportDeclaration")}else{if(this.match(75)||this.isLet()||(this.isContextual(130)||this.isContextual(129))&&!insideModule){const label=this.state.value;throw this.raise(FlowErrors.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:label,suggestion:exportSuggestions[label]})}if(this.match(74)||this.match(68)||this.match(80)||this.isContextual(131)){node.declaration=this.flowParseDeclare(this.startNode());node.default=false;return this.finishNode(node,"DeclareExportDeclaration")}else if(this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131)){node=this.parseExport(node,null);if(node.type==="ExportNamedDeclaration"){node.default=false;delete node.exportKind;return this.castNodeTo(node,"DeclareExportDeclaration")}else{return this.castNodeTo(node,"DeclareExportAllDeclaration")}}}throw this.unexpected()}flowParseDeclareModuleExports(node){this.next();this.expectContextual(111);node.typeAnnotation=this.flowParseTypeAnnotation();this.semicolon();return this.finishNode(node,"DeclareModuleExports")}flowParseDeclareTypeAlias(node){this.next();const finished=this.flowParseTypeAlias(node);this.castNodeTo(finished,"DeclareTypeAlias");return finished}flowParseDeclareOpaqueType(node){this.next();const finished=this.flowParseOpaqueType(node,true);this.castNodeTo(finished,"DeclareOpaqueType");return finished}flowParseDeclareInterface(node){this.next();this.flowParseInterfaceish(node,false);return this.finishNode(node,"DeclareInterface")}flowParseInterfaceish(node,isClass){node.id=this.flowParseRestrictedIdentifier(!isClass,true);this.scope.declareName(node.id.name,isClass?17:8201,node.id.loc.start);if(this.match(47)){node.typeParameters=this.flowParseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(this.eat(81)){do{node.extends.push(this.flowParseInterfaceExtends())}while(!isClass&&this.eat(12))}if(isClass){node.implements=[];node.mixins=[];if(this.eatContextual(117)){do{node.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(12))}if(this.eatContextual(113)){do{node.implements.push(this.flowParseInterfaceExtends())}while(this.eat(12))}}node.body=this.flowParseObjectType({allowStatic:isClass,allowExact:false,allowSpread:false,allowProto:isClass,allowInexact:false})}flowParseInterfaceExtends(){const node=this.startNode();node.id=this.flowParseQualifiedTypeIdentifier();if(this.match(47)){node.typeParameters=this.flowParseTypeParameterInstantiation()}else{node.typeParameters=null}return this.finishNode(node,"InterfaceExtends")}flowParseInterface(node){this.flowParseInterfaceish(node,false);return this.finishNode(node,"InterfaceDeclaration")}checkNotUnderscore(word){if(word==="_"){this.raise(FlowErrors.UnexpectedReservedUnderscore,this.state.startLoc)}}checkReservedType(word,startLoc,declaration){if(!reservedTypes.has(word))return;this.raise(declaration?FlowErrors.AssignReservedType:FlowErrors.UnexpectedReservedType,startLoc,{reservedType:word})}flowParseRestrictedIdentifierName(liberal,declaration){this.checkReservedType(this.state.value,this.state.startLoc,declaration);return this.parseIdentifierName(liberal)}flowParseRestrictedIdentifier(liberal,declaration){const node=this.startNode();const name=this.flowParseRestrictedIdentifierName(liberal,declaration);return this.createIdentifier(node,name)}flowParseTypeAlias(node){node.id=this.flowParseRestrictedIdentifier(false,true);this.scope.declareName(node.id.name,8201,node.id.loc.start);if(this.match(47)){node.typeParameters=this.flowParseTypeParameterDeclaration()}else{node.typeParameters=null}node.right=this.flowParseTypeInitialiser(29);this.semicolon();return this.finishNode(node,"TypeAlias")}flowParseOpaqueType(node,declare){this.expectContextual(130);node.id=this.flowParseRestrictedIdentifier(true,true);this.scope.declareName(node.id.name,8201,node.id.loc.start);if(this.match(47)){node.typeParameters=this.flowParseTypeParameterDeclaration()}else{node.typeParameters=null}node.supertype=null;if(this.match(14)){node.supertype=this.flowParseTypeInitialiser(14)}node.impltype=null;if(!declare){node.impltype=this.flowParseTypeInitialiser(29)}this.semicolon();return this.finishNode(node,"OpaqueType")}flowParseTypeParameterBound(){if(this.match(14)||this.isContextual(81)){const node=this.startNode();this.next();node.typeAnnotation=this.flowParseType();return this.finishNode(node,"TypeAnnotation")}}flowParseTypeParameter(requireDefault=false){const nodeStartLoc=this.state.startLoc;const node=this.startNode();const variance=this.flowParseVariance();node.name=this.flowParseRestrictedIdentifierName();node.variance=variance;node.bound=this.flowParseTypeParameterBound();if(this.match(29)){this.eat(29);node.default=this.flowParseType()}else{if(requireDefault){this.raise(FlowErrors.MissingTypeParamDefault,nodeStartLoc)}}return this.finishNode(node,"TypeParameter")}flowParseTypeParameterDeclaration(){const oldInType=this.state.inType;const node=this.startNode();node.params=[];this.state.inType=true;if(this.match(47)||this.match(143)){this.next()}else{this.unexpected()}let defaultRequired=false;do{const typeParameter=this.flowParseTypeParameter(defaultRequired);node.params.push(typeParameter);if(typeParameter.default){defaultRequired=true}if(!this.match(48)){this.expect(12)}}while(!this.match(48));this.expect(48);this.state.inType=oldInType;return this.finishNode(node,"TypeParameterDeclaration")}flowInTopLevelContext(cb){if(this.curContext()!==types.brace){const oldContext=this.state.context;this.state.context=[oldContext[0]];try{return cb()}finally{this.state.context=oldContext}}else{return cb()}}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()!==47)return;return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){const node=this.startNode();const oldInType=this.state.inType;this.state.inType=true;node.params=[];this.flowInTopLevelContext(()=>{this.expect(47);const oldNoAnonFunctionType=this.state.noAnonFunctionType;this.state.noAnonFunctionType=false;while(!this.match(48)){node.params.push(this.flowParseType());if(!this.match(48)){this.expect(12)}}this.state.noAnonFunctionType=oldNoAnonFunctionType});this.state.inType=oldInType;if(!this.state.inType&&this.curContext()===types.brace){this.reScan_lt_gt()}this.expect(48);return this.finishNode(node,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;const node=this.startNode();const oldInType=this.state.inType;node.params=[];this.state.inType=true;this.expect(47);while(!this.match(48)){node.params.push(this.flowParseTypeOrImplicitInstantiation());if(!this.match(48)){this.expect(12)}}this.expect(48);this.state.inType=oldInType;return this.finishNode(node,"TypeParameterInstantiation")}flowParseInterfaceType(){const node=this.startNode();this.expectContextual(129);node.extends=[];if(this.eat(81)){do{node.extends.push(this.flowParseInterfaceExtends())}while(this.eat(12))}node.body=this.flowParseObjectType({allowStatic:false,allowExact:false,allowSpread:false,allowProto:false,allowInexact:false});return this.finishNode(node,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(135)||this.match(134)?super.parseExprAtom():this.parseIdentifier(true)}flowParseObjectTypeIndexer(node,isStatic,variance){node.static=isStatic;if(this.lookahead().type===14){node.id=this.flowParseObjectPropertyKey();node.key=this.flowParseTypeInitialiser()}else{node.id=null;node.key=this.flowParseType()}this.expect(3);node.value=this.flowParseTypeInitialiser();node.variance=variance;return this.finishNode(node,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(node,isStatic){node.static=isStatic;node.id=this.flowParseObjectPropertyKey();this.expect(3);this.expect(3);if(this.match(47)||this.match(10)){node.method=true;node.optional=false;node.value=this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start))}else{node.method=false;if(this.eat(17)){node.optional=true}node.value=this.flowParseTypeInitialiser()}return this.finishNode(node,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;node.this=null;if(this.match(47)){node.typeParameters=this.flowParseTypeParameterDeclaration()}this.expect(10);if(this.match(78)){node.this=this.flowParseFunctionTypeParam(true);node.this.name=null;if(!this.match(11)){this.expect(12)}}while(!this.match(11)&&!this.match(21)){node.params.push(this.flowParseFunctionTypeParam(false));if(!this.match(11)){this.expect(12)}}if(this.eat(21)){node.rest=this.flowParseFunctionTypeParam(false)}this.expect(11);node.returnType=this.flowParseTypeInitialiser();return this.finishNode(node,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(node,isStatic){const valueNode=this.startNode();node.static=isStatic;node.value=this.flowParseObjectTypeMethodish(valueNode);return this.finishNode(node,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic,allowExact,allowSpread,allowProto,allowInexact}){const oldInType=this.state.inType;this.state.inType=true;const nodeStart=this.startNode();nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];nodeStart.internalSlots=[];let endDelim;let exact;let inexact=false;if(allowExact&&this.match(6)){this.expect(6);endDelim=9;exact=true}else{this.expect(5);endDelim=8;exact=false}nodeStart.exact=exact;while(!this.match(endDelim)){let isStatic=false;let protoStartLoc=null;let inexactStartLoc=null;const node=this.startNode();if(allowProto&&this.isContextual(118)){const lookahead=this.lookahead();if(lookahead.type!==14&&lookahead.type!==17){this.next();protoStartLoc=this.state.startLoc;allowStatic=false}}if(allowStatic&&this.isContextual(106)){const lookahead=this.lookahead();if(lookahead.type!==14&&lookahead.type!==17){this.next();isStatic=true}}const variance=this.flowParseVariance();if(this.eat(0)){if(protoStartLoc!=null){this.unexpected(protoStartLoc)}if(this.eat(0)){if(variance){this.unexpected(variance.loc.start)}nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node,isStatic))}else{nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node,isStatic,variance))}}else if(this.match(10)||this.match(47)){if(protoStartLoc!=null){this.unexpected(protoStartLoc)}if(variance){this.unexpected(variance.loc.start)}nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node,isStatic))}else{let kind="init";if(this.isContextual(99)||this.isContextual(104)){const lookahead=this.lookahead();if(tokenIsLiteralPropertyName(lookahead.type)){kind=this.state.value;this.next()}}const propOrInexact=this.flowParseObjectTypeProperty(node,isStatic,protoStartLoc,variance,kind,allowSpread,allowInexact!=null?allowInexact:!exact);if(propOrInexact===null){inexact=true;inexactStartLoc=this.state.lastTokStartLoc}else{nodeStart.properties.push(propOrInexact)}}this.flowObjectTypeSemicolon();if(inexactStartLoc&&!this.match(8)&&!this.match(9)){this.raise(FlowErrors.UnexpectedExplicitInexactInObject,inexactStartLoc)}}this.expect(endDelim);if(allowSpread){nodeStart.inexact=inexact}const out=this.finishNode(nodeStart,"ObjectTypeAnnotation");this.state.inType=oldInType;return out}flowParseObjectTypeProperty(node,isStatic,protoStartLoc,variance,kind,allowSpread,allowInexact){if(this.eat(21)){const isInexactToken=this.match(12)||this.match(13)||this.match(8)||this.match(9);if(isInexactToken){if(!allowSpread){this.raise(FlowErrors.InexactInsideNonObject,this.state.lastTokStartLoc)}else if(!allowInexact){this.raise(FlowErrors.InexactInsideExact,this.state.lastTokStartLoc)}if(variance){this.raise(FlowErrors.InexactVariance,variance)}return null}if(!allowSpread){this.raise(FlowErrors.UnexpectedSpreadType,this.state.lastTokStartLoc)}if(protoStartLoc!=null){this.unexpected(protoStartLoc)}if(variance){this.raise(FlowErrors.SpreadVariance,variance)}node.argument=this.flowParseType();return this.finishNode(node,"ObjectTypeSpreadProperty")}else{node.key=this.flowParseObjectPropertyKey();node.static=isStatic;node.proto=protoStartLoc!=null;node.kind=kind;let optional2=false;if(this.match(47)||this.match(10)){node.method=true;if(protoStartLoc!=null){this.unexpected(protoStartLoc)}if(variance){this.unexpected(variance.loc.start)}node.value=this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));if(kind==="get"||kind==="set"){this.flowCheckGetterSetterParams(node)}if(!allowSpread&&node.key.name==="constructor"&&node.value.this){this.raise(FlowErrors.ThisParamBannedInConstructor,node.value.this)}}else{if(kind!=="init")this.unexpected();node.method=false;if(this.eat(17)){optional2=true}node.value=this.flowParseTypeInitialiser();node.variance=variance}node.optional=optional2;return this.finishNode(node,"ObjectTypeProperty")}}flowCheckGetterSetterParams(property){const paramCount=property.kind==="get"?0:1;const length=property.value.params.length+(property.value.rest?1:0);if(property.value.this){this.raise(property.kind==="get"?FlowErrors.GetterMayNotHaveThisParam:FlowErrors.SetterMayNotHaveThisParam,property.value.this)}if(length!==paramCount){this.raise(property.kind==="get"?Errors.BadGetterArity:Errors.BadSetterArity,property)}if(property.kind==="set"&&property.value.rest){this.raise(Errors.BadSetterRestParameter,property)}}flowObjectTypeSemicolon(){if(!this.eat(13)&&!this.eat(12)&&!this.match(8)&&!this.match(9)){this.unexpected()}}flowParseQualifiedTypeIdentifier(startLoc,id){startLoc!=null?startLoc:startLoc=this.state.startLoc;let node=id||this.flowParseRestrictedIdentifier(true);while(this.eat(16)){const node2=this.startNodeAt(startLoc);node2.qualification=node;node2.id=this.flowParseRestrictedIdentifier(true);node=this.finishNode(node2,"QualifiedTypeIdentifier")}return node}flowParseGenericType(startLoc,id){const node=this.startNodeAt(startLoc);node.typeParameters=null;node.id=this.flowParseQualifiedTypeIdentifier(startLoc,id);if(this.match(47)){node.typeParameters=this.flowParseTypeParameterInstantiation()}return this.finishNode(node,"GenericTypeAnnotation")}flowParseTypeofType(){const node=this.startNode();this.expect(87);node.argument=this.flowParsePrimaryType();return this.finishNode(node,"TypeofTypeAnnotation")}flowParseTupleType(){const node=this.startNode();node.types=[];this.expect(0);while(this.state.pos<this.length&&!this.match(3)){node.types.push(this.flowParseType());if(this.match(3))break;this.expect(12)}this.expect(3);return this.finishNode(node,"TupleTypeAnnotation")}flowParseFunctionTypeParam(first){let name=null;let optional2=false;let typeAnnotation=null;const node=this.startNode();const lh=this.lookahead();const isThis=this.state.type===78;if(lh.type===14||lh.type===17){if(isThis&&!first){this.raise(FlowErrors.ThisParamMustBeFirst,node)}name=this.parseIdentifier(isThis);if(this.eat(17)){optional2=true;if(isThis){this.raise(FlowErrors.ThisParamMayNotBeOptional,node)}}typeAnnotation=this.flowParseTypeInitialiser()}else{typeAnnotation=this.flowParseType()}node.name=name;node.optional=optional2;node.typeAnnotation=typeAnnotation;return this.finishNode(node,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(type){const node=this.startNodeAt(type.loc.start);node.name=null;node.optional=false;node.typeAnnotation=type;return this.finishNode(node,"FunctionTypeParam")}flowParseFunctionTypeParams(params=[]){let rest=null;let _this=null;if(this.match(78)){_this=this.flowParseFunctionTypeParam(true);_this.name=null;if(!this.match(11)){this.expect(12)}}while(!this.match(11)&&!this.match(21)){params.push(this.flowParseFunctionTypeParam(false));if(!this.match(11)){this.expect(12)}}if(this.eat(21)){rest=this.flowParseFunctionTypeParam(false)}return{params,rest,_this}}flowIdentToTypeAnnotation(startLoc,node,id){switch(id.name){case"any":return this.finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(node,"BooleanTypeAnnotation");case"mixed":return this.finishNode(node,"MixedTypeAnnotation");case"empty":return this.finishNode(node,"EmptyTypeAnnotation");case"number":return this.finishNode(node,"NumberTypeAnnotation");case"string":return this.finishNode(node,"StringTypeAnnotation");case"symbol":return this.finishNode(node,"SymbolTypeAnnotation");default:this.checkNotUnderscore(id.name);return this.flowParseGenericType(startLoc,id)}}flowParsePrimaryType(){const startLoc=this.state.startLoc;const node=this.startNode();let tmp;let type;let isGroupedType=false;const oldNoAnonFunctionType=this.state.noAnonFunctionType;switch(this.state.type){case 5:return this.flowParseObjectType({allowStatic:false,allowExact:false,allowSpread:true,allowProto:false,allowInexact:true});case 6:return this.flowParseObjectType({allowStatic:false,allowExact:true,allowSpread:true,allowProto:false,allowInexact:false});case 0:this.state.noAnonFunctionType=false;type=this.flowParseTupleType();this.state.noAnonFunctionType=oldNoAnonFunctionType;return type;case 47:{const node2=this.startNode();node2.typeParameters=this.flowParseTypeParameterDeclaration();this.expect(10);tmp=this.flowParseFunctionTypeParams();node2.params=tmp.params;node2.rest=tmp.rest;node2.this=tmp._this;this.expect(11);this.expect(19);node2.returnType=this.flowParseType();return this.finishNode(node2,"FunctionTypeAnnotation")}case 10:{const node2=this.startNode();this.next();if(!this.match(11)&&!this.match(21)){if(tokenIsIdentifier(this.state.type)||this.match(78)){const token2=this.lookahead().type;isGroupedType=token2!==17&&token2!==14}else{isGroupedType=true}}if(isGroupedType){this.state.noAnonFunctionType=false;type=this.flowParseType();this.state.noAnonFunctionType=oldNoAnonFunctionType;if(this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19)){this.expect(11);return type}else{this.eat(12)}}if(type){tmp=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)])}else{tmp=this.flowParseFunctionTypeParams()}node2.params=tmp.params;node2.rest=tmp.rest;node2.this=tmp._this;this.expect(11);this.expect(19);node2.returnType=this.flowParseType();node2.typeParameters=null;return this.finishNode(node2,"FunctionTypeAnnotation")}case 134:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 85:case 86:node.value=this.match(85);this.next();return this.finishNode(node,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){this.next();if(this.match(135)){return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",node)}if(this.match(136)){return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",node)}throw this.raise(FlowErrors.UnexpectedSubtractionOperand,this.state.startLoc)}throw this.unexpected();case 135:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 136:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 88:this.next();return this.finishNode(node,"VoidTypeAnnotation");case 84:this.next();return this.finishNode(node,"NullLiteralTypeAnnotation");case 78:this.next();return this.finishNode(node,"ThisTypeAnnotation");case 55:this.next();return this.finishNode(node,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(tokenIsKeyword(this.state.type)){const label=tokenLabelName(this.state.type);this.next();return super.createIdentifier(node,label)}else if(tokenIsIdentifier(this.state.type)){if(this.isContextual(129)){return this.flowParseInterfaceType()}return this.flowIdentToTypeAnnotation(startLoc,node,this.parseIdentifier())}}throw this.unexpected()}flowParsePostfixType(){const startLoc=this.state.startLoc;let type=this.flowParsePrimaryType();let seenOptionalIndexedAccess=false;while((this.match(0)||this.match(18))&&!this.canInsertSemicolon()){const node=this.startNodeAt(startLoc);const optional2=this.eat(18);seenOptionalIndexedAccess=seenOptionalIndexedAccess||optional2;this.expect(0);if(!optional2&&this.match(3)){node.elementType=type;this.next();type=this.finishNode(node,"ArrayTypeAnnotation")}else{node.objectType=type;node.indexType=this.flowParseType();this.expect(3);if(seenOptionalIndexedAccess){node.optional=optional2;type=this.finishNode(node,"OptionalIndexedAccessType")}else{type=this.finishNode(node,"IndexedAccessType")}}}return type}flowParsePrefixType(){const node=this.startNode();if(this.eat(17)){node.typeAnnotation=this.flowParsePrefixType();return this.finishNode(node,"NullableTypeAnnotation")}else{return this.flowParsePostfixType()}}flowParseAnonFunctionWithoutParens(){const param=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(19)){const node=this.startNodeAt(param.loc.start);node.params=[this.reinterpretTypeAsFunctionTypeParam(param)];node.rest=null;node.this=null;node.returnType=this.flowParseType();node.typeParameters=null;return this.finishNode(node,"FunctionTypeAnnotation")}return param}flowParseIntersectionType(){const node=this.startNode();this.eat(45);const type=this.flowParseAnonFunctionWithoutParens();node.types=[type];while(this.eat(45)){node.types.push(this.flowParseAnonFunctionWithoutParens())}return node.types.length===1?type:this.finishNode(node,"IntersectionTypeAnnotation")}flowParseUnionType(){const node=this.startNode();this.eat(43);const type=this.flowParseIntersectionType();node.types=[type];while(this.eat(43)){node.types.push(this.flowParseIntersectionType())}return node.types.length===1?type:this.finishNode(node,"UnionTypeAnnotation")}flowParseType(){const oldInType=this.state.inType;this.state.inType=true;const type=this.flowParseUnionType();this.state.inType=oldInType;return type}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){const startLoc=this.state.startLoc;const node=this.parseIdentifier();return this.flowParseGenericType(startLoc,node)}else{return this.flowParseType()}}flowParseTypeAnnotation(){const node=this.startNode();node.typeAnnotation=this.flowParseTypeInitialiser();return this.finishNode(node,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){const node=this.startNode();const name=this.parseIdentifierName();if(this.match(14)){node.typeAnnotation=this.flowParseTypeAnnotation()}return this.createIdentifier(node,name)}typeCastToParameter(node){node.expression.typeAnnotation=node.typeAnnotation;this.resetEndLocation(node.expression,node.typeAnnotation.loc.end);return node.expression}flowParseVariance(){let variance=null;if(this.match(53)){variance=this.startNode();if(this.state.value==="+"){variance.kind="plus"}else{variance.kind="minus"}this.next();return this.finishNode(variance,"Variance")}return variance}parseFunctionBody(node,allowExpressionBody,isMethod=false){if(allowExpressionBody){this.forwardNoArrowParamsConversionAt(node,()=>super.parseFunctionBody(node,true,isMethod));return}super.parseFunctionBody(node,false,isMethod)}parseFunctionBodyAndFinish(node,type,isMethod=false){if(this.match(14)){const typeNode=this.startNode();[typeNode.typeAnnotation,node.predicate]=this.flowParseTypeAndPredicateInitialiser();node.returnType=typeNode.typeAnnotation?this.finishNode(typeNode,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(node,type,isMethod)}parseStatementLike(flags){if(this.state.strict&&this.isContextual(129)){const lookahead=this.lookahead();if(tokenIsKeywordOrIdentifier(lookahead.type)){const node=this.startNode();this.next();return this.flowParseInterface(node)}}else if(this.isContextual(126)){const node=this.startNode();this.next();return this.flowParseEnumDeclaration(node)}const stmt=super.parseStatementLike(flags);if(this.flowPragma===void 0&&!this.isValidDirective(stmt)){this.flowPragma=null}return stmt}parseExpressionStatement(node,expr,decorators){if(expr.type==="Identifier"){if(expr.name==="declare"){if(this.match(80)||tokenIsIdentifier(this.state.type)||this.match(68)||this.match(74)||this.match(82)){return this.flowParseDeclare(node)}}else if(tokenIsIdentifier(this.state.type)){if(expr.name==="interface"){return this.flowParseInterface(node)}else if(expr.name==="type"){return this.flowParseTypeAlias(node)}else if(expr.name==="opaque"){return this.flowParseOpaqueType(node,false)}}}return super.parseExpressionStatement(node,expr,decorators)}shouldParseExportDeclaration(){const{type}=this.state;if(type===126||tokenIsFlowInterfaceOrTypeOrOpaque(type)){return!this.state.containsEsc}return super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){const{type}=this.state;if(type===126||tokenIsFlowInterfaceOrTypeOrOpaque(type)){return this.state.containsEsc}return super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(126)){const node=this.startNode();this.next();return this.flowParseEnumDeclaration(node)}return super.parseExportDefaultExpression()}parseConditional(expr,startLoc,refExpressionErrors){if(!this.match(17))return expr;if(this.state.maybeInArrowParameters){const nextCh=this.lookaheadCharCode();if(nextCh===44||nextCh===61||nextCh===58||nextCh===41){this.setOptionalParametersError(refExpressionErrors);return expr}}this.expect(17);const state=this.state.clone();const originalNoArrowAt=this.state.noArrowAt;const node=this.startNodeAt(startLoc);let{consequent,failed}=this.tryParseConditionalConsequent();let[valid2,invalid]=this.getArrowLikeExpressions(consequent);if(failed||invalid.length>0){const noArrowAt=[...originalNoArrowAt];if(invalid.length>0){this.state=state;this.state.noArrowAt=noArrowAt;for(let i=0;i<invalid.length;i++){noArrowAt.push(invalid[i].start)}({consequent,failed}=this.tryParseConditionalConsequent());[valid2,invalid]=this.getArrowLikeExpressions(consequent)}if(failed&&valid2.length>1){this.raise(FlowErrors.AmbiguousConditionalArrow,state.startLoc)}if(failed&&valid2.length===1){this.state=state;noArrowAt.push(valid2[0].start);this.state.noArrowAt=noArrowAt;({consequent,failed}=this.tryParseConditionalConsequent())}}this.getArrowLikeExpressions(consequent,true);this.state.noArrowAt=originalNoArrowAt;this.expect(14);node.test=expr;node.consequent=consequent;node.alternate=this.forwardNoArrowParamsConversionAt(node,()=>this.parseMaybeAssign(void 0,void 0));return this.finishNode(node,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);const consequent=this.parseMaybeAssignAllowIn();const failed=!this.match(14);this.state.noArrowParamsConversionAt.pop();return{consequent,failed}}getArrowLikeExpressions(node,disallowInvalid){const stack=[node];const arrows=[];while(stack.length!==0){const node2=stack.pop();if(node2.type==="ArrowFunctionExpression"&&node2.body.type!=="BlockStatement"){if(node2.typeParameters||!node2.returnType){this.finishArrowValidation(node2)}else{arrows.push(node2)}stack.push(node2.body)}else if(node2.type==="ConditionalExpression"){stack.push(node2.consequent);stack.push(node2.alternate)}}if(disallowInvalid){arrows.forEach(node2=>this.finishArrowValidation(node2));return[arrows,[]]}return partition(arrows,node2=>node2.params.every(param=>this.isAssignable(param,true)))}finishArrowValidation(node){var _node$extra;this.toAssignableList(node.params,(_node$extra=node.extra)==null?void 0:_node$extra.trailingCommaLoc,false);this.scope.enter(514|4);super.checkParams(node,false,true);this.scope.exit()}forwardNoArrowParamsConversionAt(node,parse6){let result2;if(this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))){this.state.noArrowParamsConversionAt.push(this.state.start);result2=parse6();this.state.noArrowParamsConversionAt.pop()}else{result2=parse6()}return result2}parseParenItem(node,startLoc){const newNode=super.parseParenItem(node,startLoc);if(this.eat(17)){newNode.optional=true;this.resetEndLocation(node)}if(this.match(14)){const typeCastNode=this.startNodeAt(startLoc);typeCastNode.expression=newNode;typeCastNode.typeAnnotation=this.flowParseTypeAnnotation();return this.finishNode(typeCastNode,"TypeCastExpression")}return newNode}assertModuleNodeAllowed(node){if(node.type==="ImportDeclaration"&&(node.importKind==="type"||node.importKind==="typeof")||node.type==="ExportNamedDeclaration"&&node.exportKind==="type"||node.type==="ExportAllDeclaration"&&node.exportKind==="type"){return}super.assertModuleNodeAllowed(node)}parseExportDeclaration(node){if(this.isContextual(130)){node.exportKind="type";const declarationNode=this.startNode();this.next();if(this.match(5)){node.specifiers=this.parseExportSpecifiers(true);super.parseExportFrom(node);return null}else{return this.flowParseTypeAlias(declarationNode)}}else if(this.isContextual(131)){node.exportKind="type";const declarationNode=this.startNode();this.next();return this.flowParseOpaqueType(declarationNode,false)}else if(this.isContextual(129)){node.exportKind="type";const declarationNode=this.startNode();this.next();return this.flowParseInterface(declarationNode)}else if(this.isContextual(126)){node.exportKind="value";const declarationNode=this.startNode();this.next();return this.flowParseEnumDeclaration(declarationNode)}else{return super.parseExportDeclaration(node)}}eatExportStar(node){if(super.eatExportStar(node))return true;if(this.isContextual(130)&&this.lookahead().type===55){node.exportKind="type";this.next();this.next();return true}return false}maybeParseExportNamespaceSpecifier(node){const{startLoc}=this.state;const hasNamespace=super.maybeParseExportNamespaceSpecifier(node);if(hasNamespace&&node.exportKind==="type"){this.unexpected(startLoc)}return hasNamespace}parseClassId(node,isStatement,optionalId){super.parseClassId(node,isStatement,optionalId);if(this.match(47)){node.typeParameters=this.flowParseTypeParameterDeclaration()}}parseClassMember(classBody,member,state){const{startLoc}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(classBody,member)){return}member.declare=true}super.parseClassMember(classBody,member,state);if(member.declare){if(member.type!=="ClassProperty"&&member.type!=="ClassPrivateProperty"&&member.type!=="PropertyDefinition"){this.raise(FlowErrors.DeclareClassElement,startLoc)}else if(member.value){this.raise(FlowErrors.DeclareClassFieldInitializer,member.value)}}}isIterator(word){return word==="iterator"||word==="asyncIterator"}readIterator(){const word=super.readWord1();const fullWord="@@"+word;if(!this.isIterator(word)||!this.state.inType){this.raise(Errors.InvalidIdentifier,this.state.curPosition(),{identifierName:fullWord})}this.finishToken(132,fullWord)}getTokenFromCode(code2){const next=this.input.charCodeAt(this.state.pos+1);if(code2===123&&next===124){this.finishOp(6,2)}else if(this.state.inType&&(code2===62||code2===60)){this.finishOp(code2===62?48:47,1)}else if(this.state.inType&&code2===63){if(next===46){this.finishOp(18,2)}else{this.finishOp(17,1)}}else if(isIteratorStart(code2,next,this.input.charCodeAt(this.state.pos+2))){this.state.pos+=2;this.readIterator()}else{super.getTokenFromCode(code2)}}isAssignable(node,isBinding){if(node.type==="TypeCastExpression"){return this.isAssignable(node.expression,isBinding)}else{return super.isAssignable(node,isBinding)}}toAssignable(node,isLHS=false){if(!isLHS&&node.type==="AssignmentExpression"&&node.left.type==="TypeCastExpression"){node.left=this.typeCastToParameter(node.left)}super.toAssignable(node,isLHS)}toAssignableList(exprList,trailingCommaLoc,isLHS){for(let i=0;i<exprList.length;i++){const expr=exprList[i];if((expr==null?void 0:expr.type)==="TypeCastExpression"){exprList[i]=this.typeCastToParameter(expr)}}super.toAssignableList(exprList,trailingCommaLoc,isLHS)}toReferencedList(exprList,isParenthesizedExpr){for(let i=0;i<exprList.length;i++){var _expr$extra;const expr=exprList[i];if(expr&&expr.type==="TypeCastExpression"&&!((_expr$extra=expr.extra)!=null&&_expr$extra.parenthesized)&&(exprList.length>1||!isParenthesizedExpr)){this.raise(FlowErrors.TypeCastInPattern,expr.typeAnnotation)}}return exprList}parseArrayLike(close,isTuple,refExpressionErrors){const node=super.parseArrayLike(close,isTuple,refExpressionErrors);if(refExpressionErrors!=null&&!this.state.maybeInArrowParameters){this.toReferencedList(node.elements)}return node}isValidLVal(type,disallowCallExpression,isParenthesized,binding){return type==="TypeCastExpression"||super.isValidLVal(type,disallowCallExpression,isParenthesized,binding)}parseClassProperty(node){if(this.match(14)){node.typeAnnotation=this.flowParseTypeAnnotation()}return super.parseClassProperty(node)}parseClassPrivateProperty(node){if(this.match(14)){node.typeAnnotation=this.flowParseTypeAnnotation()}return super.parseClassPrivateProperty(node)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(method){return!this.match(14)&&super.isNonstaticConstructor(method)}pushClassMethod(classBody,method,isGenerator,isAsync,isConstructor,allowsDirectSuper){if(method.variance){this.unexpected(method.variance.loc.start)}delete method.variance;if(this.match(47)){method.typeParameters=this.flowParseTypeParameterDeclaration()}super.pushClassMethod(classBody,method,isGenerator,isAsync,isConstructor,allowsDirectSuper);if(method.params&&isConstructor){const params=method.params;if(params.length>0&&this.isThisParam(params[0])){this.raise(FlowErrors.ThisParamBannedInConstructor,method)}}else if(method.type==="MethodDefinition"&&isConstructor&&method.value.params){const params=method.value.params;if(params.length>0&&this.isThisParam(params[0])){this.raise(FlowErrors.ThisParamBannedInConstructor,method)}}}pushClassPrivateMethod(classBody,method,isGenerator,isAsync){if(method.variance){this.unexpected(method.variance.loc.start)}delete method.variance;if(this.match(47)){method.typeParameters=this.flowParseTypeParameterDeclaration()}super.pushClassPrivateMethod(classBody,method,isGenerator,isAsync)}parseClassSuper(node){super.parseClassSuper(node);if(node.superClass&&(this.match(47)||this.match(51))){node.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()}if(this.isContextual(113)){this.next();const implemented=node.implements=[];do{const node2=this.startNode();node2.id=this.flowParseRestrictedIdentifier(true);if(this.match(47)){node2.typeParameters=this.flowParseTypeParameterInstantiation()}else{node2.typeParameters=null}implemented.push(this.finishNode(node2,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(method){super.checkGetterSetterParams(method);const params=this.getObjectOrClassMethodParams(method);if(params.length>0){const param=params[0];if(this.isThisParam(param)&&method.kind==="get"){this.raise(FlowErrors.GetterMayNotHaveThisParam,param)}else if(this.isThisParam(param)){this.raise(FlowErrors.SetterMayNotHaveThisParam,param)}}}parsePropertyNamePrefixOperator(node){node.variance=this.flowParseVariance()}parseObjPropValue(prop,startLoc,isGenerator,isAsync,isPattern,isAccessor,refExpressionErrors){if(prop.variance){this.unexpected(prop.variance.loc.start)}delete prop.variance;let typeParameters;if(this.match(47)&&!isAccessor){typeParameters=this.flowParseTypeParameterDeclaration();if(!this.match(10))this.unexpected()}const result2=super.parseObjPropValue(prop,startLoc,isGenerator,isAsync,isPattern,isAccessor,refExpressionErrors);if(typeParameters){(result2.value||result2).typeParameters=typeParameters}return result2}parseFunctionParamType(param){if(this.eat(17)){if(param.type!=="Identifier"){this.raise(FlowErrors.PatternIsOptional,param)}if(this.isThisParam(param)){this.raise(FlowErrors.ThisParamMayNotBeOptional,param)}param.optional=true}if(this.match(14)){param.typeAnnotation=this.flowParseTypeAnnotation()}else if(this.isThisParam(param)){this.raise(FlowErrors.ThisParamAnnotationRequired,param)}if(this.match(29)&&this.isThisParam(param)){this.raise(FlowErrors.ThisParamNoDefault,param)}this.resetEndLocation(param);return param}parseMaybeDefault(startLoc,left){const node=super.parseMaybeDefault(startLoc,left);if(node.type==="AssignmentPattern"&&node.typeAnnotation&&node.right.start<node.typeAnnotation.start){this.raise(FlowErrors.TypeBeforeInitializer,node.typeAnnotation)}return node}checkImportReflection(node){super.checkImportReflection(node);if(node.module&&node.importKind!=="value"){this.raise(FlowErrors.ImportReflectionHasImportType,node.specifiers[0].loc.start)}}parseImportSpecifierLocal(node,specifier,type){specifier.local=hasTypeImportKind(node)?this.flowParseRestrictedIdentifier(true,true):this.parseIdentifier();node.specifiers.push(this.finishImportSpecifier(specifier,type))}isPotentialImportPhase(isExport){if(super.isPotentialImportPhase(isExport))return true;if(this.isContextual(130)){if(!isExport)return true;const ch=this.lookaheadCharCode();return ch===123||ch===42}return!isExport&&this.isContextual(87)}applyImportPhase(node,isExport,phase2,loc){super.applyImportPhase(node,isExport,phase2,loc);if(isExport){if(!phase2&&this.match(65)){return}node.exportKind=phase2==="type"?phase2:"value"}else{if(phase2==="type"&&this.match(55))this.unexpected();node.importKind=phase2==="type"||phase2==="typeof"?phase2:"value"}}parseImportSpecifier(specifier,importedIsString,isInTypeOnlyImport,isMaybeTypeOnly,bindingType){const firstIdent=specifier.imported;let specifierTypeKind=null;if(firstIdent.type==="Identifier"){if(firstIdent.name==="type"){specifierTypeKind="type"}else if(firstIdent.name==="typeof"){specifierTypeKind="typeof"}}let isBinding=false;if(this.isContextual(93)&&!this.isLookaheadContextual("as")){const as_ident=this.parseIdentifier(true);if(specifierTypeKind!==null&&!tokenIsKeywordOrIdentifier(this.state.type)){specifier.imported=as_ident;specifier.importKind=specifierTypeKind;specifier.local=this.cloneIdentifier(as_ident)}else{specifier.imported=firstIdent;specifier.importKind=null;specifier.local=this.parseIdentifier()}}else{if(specifierTypeKind!==null&&tokenIsKeywordOrIdentifier(this.state.type)){specifier.imported=this.parseIdentifier(true);specifier.importKind=specifierTypeKind}else{if(importedIsString){throw this.raise(Errors.ImportBindingIsString,specifier,{importName:firstIdent.value})}specifier.imported=firstIdent;specifier.importKind=null}if(this.eatContextual(93)){specifier.local=this.parseIdentifier()}else{isBinding=true;specifier.local=this.cloneIdentifier(specifier.imported)}}const specifierIsTypeImport=hasTypeImportKind(specifier);if(isInTypeOnlyImport&&specifierIsTypeImport){this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport,specifier)}if(isInTypeOnlyImport||specifierIsTypeImport){this.checkReservedType(specifier.local.name,specifier.local.loc.start,true)}if(isBinding&&!isInTypeOnlyImport&&!specifierIsTypeImport){this.checkReservedWord(specifier.local.name,specifier.loc.start,true,true)}return this.finishImportSpecifier(specifier,"ImportSpecifier")}parseBindingAtom(){switch(this.state.type){case 78:return this.parseIdentifier(true);default:return super.parseBindingAtom()}}parseFunctionParams(node,isConstructor){const kind=node.kind;if(kind!=="get"&&kind!=="set"&&this.match(47)){node.typeParameters=this.flowParseTypeParameterDeclaration()}super.parseFunctionParams(node,isConstructor)}parseVarId(decl,kind){super.parseVarId(decl,kind);if(this.match(14)){decl.id.typeAnnotation=this.flowParseTypeAnnotation();this.resetEndLocation(decl.id)}}parseAsyncArrowFromCallExpression(node,call){if(this.match(14)){const oldNoAnonFunctionType=this.state.noAnonFunctionType;this.state.noAnonFunctionType=true;node.returnType=this.flowParseTypeAnnotation();this.state.noAnonFunctionType=oldNoAnonFunctionType}return super.parseAsyncArrowFromCallExpression(node,call)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(refExpressionErrors,afterLeftParse){var _jsx;let state=null;let jsx2;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){state=this.state.clone();jsx2=this.tryParse(()=>super.parseMaybeAssign(refExpressionErrors,afterLeftParse),state);if(!jsx2.error)return jsx2.node;const{context}=this.state;const currentContext=context[context.length-1];if(currentContext===types.j_oTag||currentContext===types.j_expr){context.pop()}}if((_jsx=jsx2)!=null&&_jsx.error||this.match(47)){var _jsx2,_jsx3;state=state||this.state.clone();let typeParameters;const arrow=this.tryParse(abort=>{var _arrowExpression$extr;typeParameters=this.flowParseTypeParameterDeclaration();const arrowExpression2=this.forwardNoArrowParamsConversionAt(typeParameters,()=>{const result2=super.parseMaybeAssign(refExpressionErrors,afterLeftParse);this.resetStartLocationFromNode(result2,typeParameters);return result2});if((_arrowExpression$extr=arrowExpression2.extra)!=null&&_arrowExpression$extr.parenthesized)abort();const expr=this.maybeUnwrapTypeCastExpression(arrowExpression2);if(expr.type!=="ArrowFunctionExpression")abort();expr.typeParameters=typeParameters;this.resetStartLocationFromNode(expr,typeParameters);return arrowExpression2},state);let arrowExpression=null;if(arrow.node&&this.maybeUnwrapTypeCastExpression(arrow.node).type==="ArrowFunctionExpression"){if(!arrow.error&&!arrow.aborted){if(arrow.node.async){this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction,typeParameters)}return arrow.node}arrowExpression=arrow.node}if((_jsx2=jsx2)!=null&&_jsx2.node){this.state=jsx2.failState;return jsx2.node}if(arrowExpression){this.state=arrow.failState;return arrowExpression}if((_jsx3=jsx2)!=null&&_jsx3.thrown)throw jsx2.error;if(arrow.thrown)throw arrow.error;throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter,typeParameters)}return super.parseMaybeAssign(refExpressionErrors,afterLeftParse)}parseArrow(node){if(this.match(14)){const result2=this.tryParse(()=>{const oldNoAnonFunctionType=this.state.noAnonFunctionType;this.state.noAnonFunctionType=true;const typeNode=this.startNode();[typeNode.typeAnnotation,node.predicate]=this.flowParseTypeAndPredicateInitialiser();this.state.noAnonFunctionType=oldNoAnonFunctionType;if(this.canInsertSemicolon())this.unexpected();if(!this.match(19))this.unexpected();return typeNode});if(result2.thrown)return null;if(result2.error)this.state=result2.failState;node.returnType=result2.node.typeAnnotation?this.finishNode(result2.node,"TypeAnnotation"):null}return super.parseArrow(node)}shouldParseArrow(params){return this.match(14)||super.shouldParseArrow(params)}setArrowFunctionParameters(node,params){if(this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))){node.params=params}else{super.setArrowFunctionParameters(node,params)}}checkParams(node,allowDuplicates,isArrowFunction,strictModeChanged=true){if(isArrowFunction&&this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))){return}for(let i=0;i<node.params.length;i++){if(this.isThisParam(node.params[i])&&i>0){this.raise(FlowErrors.ThisParamMustBeFirst,node.params[i])}}super.checkParams(node,allowDuplicates,isArrowFunction,strictModeChanged)}parseParenAndDistinguishExpression(canBeArrow){return super.parseParenAndDistinguishExpression(canBeArrow&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(base,startLoc,noCalls){if(base.type==="Identifier"&&base.name==="async"&&this.state.noArrowAt.includes(startLoc.index)){this.next();const node=this.startNodeAt(startLoc);node.callee=base;node.arguments=super.parseCallExpressionArguments();base=this.finishNode(node,"CallExpression")}else if(base.type==="Identifier"&&base.name==="async"&&this.match(47)){const state=this.state.clone();const arrow=this.tryParse(abort=>this.parseAsyncArrowWithTypeParameters(startLoc)||abort(),state);if(!arrow.error&&!arrow.aborted)return arrow.node;const result2=this.tryParse(()=>super.parseSubscripts(base,startLoc,noCalls),state);if(result2.node&&!result2.error)return result2.node;if(arrow.node){this.state=arrow.failState;return arrow.node}if(result2.node){this.state=result2.failState;return result2.node}throw arrow.error||result2.error}return super.parseSubscripts(base,startLoc,noCalls)}parseSubscript(base,startLoc,noCalls,subscriptState){if(this.match(18)&&this.isLookaheadToken_lt()){subscriptState.optionalChainMember=true;if(noCalls){subscriptState.stop=true;return base}this.next();const node=this.startNodeAt(startLoc);node.callee=base;node.typeArguments=this.flowParseTypeParameterInstantiationInExpression();this.expect(10);node.arguments=this.parseCallExpressionArguments();node.optional=true;return this.finishCallExpression(node,true)}else if(!noCalls&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){const node=this.startNodeAt(startLoc);node.callee=base;const result2=this.tryParse(()=>{node.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew();this.expect(10);node.arguments=super.parseCallExpressionArguments();if(subscriptState.optionalChainMember){node.optional=false}return this.finishCallExpression(node,subscriptState.optionalChainMember)});if(result2.node){if(result2.error)this.state=result2.failState;return result2.node}}return super.parseSubscript(base,startLoc,noCalls,subscriptState)}parseNewCallee(node){super.parseNewCallee(node);let targs=null;if(this.shouldParseTypes()&&this.match(47)){targs=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node}node.typeArguments=targs}parseAsyncArrowWithTypeParameters(startLoc){const node=this.startNodeAt(startLoc);this.parseFunctionParams(node,false);if(!this.parseArrow(node))return;return super.parseArrowExpression(node,void 0,true)}readToken_mult_modulo(code2){const next=this.input.charCodeAt(this.state.pos+1);if(code2===42&&next===47&&this.state.hasFlowComment){this.state.hasFlowComment=false;this.state.pos+=2;this.nextToken();return}super.readToken_mult_modulo(code2)}readToken_pipe_amp(code2){const next=this.input.charCodeAt(this.state.pos+1);if(code2===124&&next===125){this.finishOp(9,2);return}super.readToken_pipe_amp(code2)}parseTopLevel(file2,program){const fileNode=super.parseTopLevel(file2,program);if(this.state.hasFlowComment){this.raise(FlowErrors.UnterminatedFlowComment,this.state.curPosition())}return fileNode}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment){throw this.raise(FlowErrors.NestedFlowComment,this.state.startLoc)}this.hasFlowCommentCompletion();const commentSkip=this.skipFlowComment();if(commentSkip){this.state.pos+=commentSkip;this.state.hasFlowComment=true}return}return super.skipBlockComment(this.state.hasFlowComment?"*-/":"*/")}skipFlowComment(){const{pos}=this.state;let shiftToFirstNonWhiteSpace=2;while([32,9].includes(this.input.charCodeAt(pos+shiftToFirstNonWhiteSpace))){shiftToFirstNonWhiteSpace++}const ch2=this.input.charCodeAt(shiftToFirstNonWhiteSpace+pos);const ch3=this.input.charCodeAt(shiftToFirstNonWhiteSpace+pos+1);if(ch2===58&&ch3===58){return shiftToFirstNonWhiteSpace+2}if(this.input.slice(shiftToFirstNonWhiteSpace+pos,shiftToFirstNonWhiteSpace+pos+12)==="flow-include"){return shiftToFirstNonWhiteSpace+12}if(ch2===58&&ch3!==58){return shiftToFirstNonWhiteSpace}return false}hasFlowCommentCompletion(){const end=this.input.indexOf("*/",this.state.pos);if(end===-1){throw this.raise(Errors.UnterminatedComment,this.state.curPosition())}}flowEnumErrorBooleanMemberNotInitialized(loc,{enumName,memberName}){this.raise(FlowErrors.EnumBooleanMemberNotInitialized,loc,{memberName,enumName})}flowEnumErrorInvalidMemberInitializer(loc,enumContext){return this.raise(!enumContext.explicitType?FlowErrors.EnumInvalidMemberInitializerUnknownType:enumContext.explicitType==="symbol"?FlowErrors.EnumInvalidMemberInitializerSymbolType:FlowErrors.EnumInvalidMemberInitializerPrimaryType,loc,enumContext)}flowEnumErrorNumberMemberNotInitialized(loc,details){this.raise(FlowErrors.EnumNumberMemberNotInitialized,loc,details)}flowEnumErrorStringMemberInconsistentlyInitialized(node,details){this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized,node,details)}flowEnumMemberInit(){const startLoc=this.state.startLoc;const endOfInit=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{const literal3=this.parseNumericLiteral(this.state.value);if(endOfInit()){return{type:"number",loc:literal3.loc.start,value:literal3}}return{type:"invalid",loc:startLoc}}case 134:{const literal3=this.parseStringLiteral(this.state.value);if(endOfInit()){return{type:"string",loc:literal3.loc.start,value:literal3}}return{type:"invalid",loc:startLoc}}case 85:case 86:{const literal3=this.parseBooleanLiteral(this.match(85));if(endOfInit()){return{type:"boolean",loc:literal3.loc.start,value:literal3}}return{type:"invalid",loc:startLoc}}default:return{type:"invalid",loc:startLoc}}}flowEnumMemberRaw(){const loc=this.state.startLoc;const id=this.parseIdentifier(true);const init=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc};return{id,init}}flowEnumCheckExplicitTypeMismatch(loc,context,expectedType){const{explicitType}=context;if(explicitType===null){return}if(explicitType!==expectedType){this.flowEnumErrorInvalidMemberInitializer(loc,context)}}flowEnumMembers({enumName,explicitType}){const seenNames=new Set;const members={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]};let hasUnknownMembers=false;while(!this.match(8)){if(this.eat(21)){hasUnknownMembers=true;break}const memberNode=this.startNode();const{id,init}=this.flowEnumMemberRaw();const memberName=id.name;if(memberName===""){continue}if(/^[a-z]/.test(memberName)){this.raise(FlowErrors.EnumInvalidMemberName,id,{memberName,suggestion:memberName[0].toUpperCase()+memberName.slice(1),enumName})}if(seenNames.has(memberName)){this.raise(FlowErrors.EnumDuplicateMemberName,id,{memberName,enumName})}seenNames.add(memberName);const context={enumName,explicitType,memberName};memberNode.id=id;switch(init.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(init.loc,context,"boolean");memberNode.init=init.value;members.booleanMembers.push(this.finishNode(memberNode,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(init.loc,context,"number");memberNode.init=init.value;members.numberMembers.push(this.finishNode(memberNode,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(init.loc,context,"string");memberNode.init=init.value;members.stringMembers.push(this.finishNode(memberNode,"EnumStringMember"));break}case"invalid":{throw this.flowEnumErrorInvalidMemberInitializer(init.loc,context)}case"none":{switch(explicitType){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(init.loc,context);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(init.loc,context);break;default:members.defaultedMembers.push(this.finishNode(memberNode,"EnumDefaultedMember"))}}}if(!this.match(8)){this.expect(12)}}return{members,hasUnknownMembers}}flowEnumStringMembers(initializedMembers,defaultedMembers,{enumName}){if(initializedMembers.length===0){return defaultedMembers}else if(defaultedMembers.length===0){return initializedMembers}else if(defaultedMembers.length>initializedMembers.length){for(const member of initializedMembers){this.flowEnumErrorStringMemberInconsistentlyInitialized(member,{enumName})}return defaultedMembers}else{for(const member of defaultedMembers){this.flowEnumErrorStringMemberInconsistentlyInitialized(member,{enumName})}return initializedMembers}}flowEnumParseExplicitType({enumName}){if(!this.eatContextual(102))return null;if(!tokenIsIdentifier(this.state.type)){throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName})}const{value}=this.state;this.next();if(value!=="boolean"&&value!=="number"&&value!=="string"&&value!=="symbol"){this.raise(FlowErrors.EnumInvalidExplicitType,this.state.startLoc,{enumName,invalidEnumType:value})}return value}flowEnumBody(node,id){const enumName=id.name;const nameLoc=id.loc.start;const explicitType=this.flowEnumParseExplicitType({enumName});this.expect(5);const{members,hasUnknownMembers}=this.flowEnumMembers({enumName,explicitType});node.hasUnknownMembers=hasUnknownMembers;switch(explicitType){case"boolean":node.explicitType=true;node.members=members.booleanMembers;this.expect(8);return this.finishNode(node,"EnumBooleanBody");case"number":node.explicitType=true;node.members=members.numberMembers;this.expect(8);return this.finishNode(node,"EnumNumberBody");case"string":node.explicitType=true;node.members=this.flowEnumStringMembers(members.stringMembers,members.defaultedMembers,{enumName});this.expect(8);return this.finishNode(node,"EnumStringBody");case"symbol":node.members=members.defaultedMembers;this.expect(8);return this.finishNode(node,"EnumSymbolBody");default:{const empty=()=>{node.members=[];this.expect(8);return this.finishNode(node,"EnumStringBody")};node.explicitType=false;const boolsLen=members.booleanMembers.length;const numsLen=members.numberMembers.length;const strsLen=members.stringMembers.length;const defaultedLen=members.defaultedMembers.length;if(!boolsLen&&!numsLen&&!strsLen&&!defaultedLen){return empty()}else if(!boolsLen&&!numsLen){node.members=this.flowEnumStringMembers(members.stringMembers,members.defaultedMembers,{enumName});this.expect(8);return this.finishNode(node,"EnumStringBody")}else if(!numsLen&&!strsLen&&boolsLen>=defaultedLen){for(const member of members.defaultedMembers){this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start,{enumName,memberName:member.id.name})}node.members=members.booleanMembers;this.expect(8);return this.finishNode(node,"EnumBooleanBody")}else if(!boolsLen&&!strsLen&&numsLen>=defaultedLen){for(const member of members.defaultedMembers){this.flowEnumErrorNumberMemberNotInitialized(member.loc.start,{enumName,memberName:member.id.name})}node.members=members.numberMembers;this.expect(8);return this.finishNode(node,"EnumNumberBody")}else{this.raise(FlowErrors.EnumInconsistentMemberValues,nameLoc,{enumName});return empty()}}}}flowParseEnumDeclaration(node){const id=this.parseIdentifier();node.id=id;node.body=this.flowEnumBody(this.startNode(),id);return this.finishNode(node,"EnumDeclaration")}jsxParseOpeningElementAfterName(node){if(this.shouldParseTypes()){if(this.match(47)||this.match(51)){node.typeArguments=this.flowParseTypeParameterInstantiationInExpression()}}return super.jsxParseOpeningElementAfterName(node)}isLookaheadToken_lt(){const next=this.nextTokenStart();if(this.input.charCodeAt(next)===60){const afterNext=this.input.charCodeAt(next+1);return afterNext!==60&&afterNext!==61}return false}reScan_lt_gt(){const{type}=this.state;if(type===47){this.state.pos-=1;this.readToken_lt()}else if(type===48){this.state.pos-=1;this.readToken_gt()}}reScan_lt(){const{type}=this.state;if(type===51){this.state.pos-=2;this.finishOp(47,1);return 47}return type}maybeUnwrapTypeCastExpression(node){return node.type==="TypeCastExpression"?node.expression:node}};var entities={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02C6",tilde:"\u02DC",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203A",oline:"\u203E",frasl:"\u2044",euro:"\u20AC",image:"\u2111",weierp:"\u2118",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"};var lineBreak=/\r\n|[\r\n\u2028\u2029]/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code2){switch(code2){case 10:case 13:case 8232:case 8233:return true;default:return false}}function hasNewLine(input,start,end){for(let i=start;i<end;i++){if(isNewLine(input.charCodeAt(i))){return true}}return false}var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var skipWhiteSpaceInLine=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function isWhitespace(code2){switch(code2){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return true;default:return false}}var JsxErrors=ParseErrorEnum`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName})=>`Expected corresponding JSX closing tag for <${openingTagName}>.`,MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:({unexpected,HTMLEntity})=>`Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"});function isFragment(object2){return object2?object2.type==="JSXOpeningFragment"||object2.type==="JSXClosingFragment":false}function getQualifiedJSXName(object2){if(object2.type==="JSXIdentifier"){return object2.name}if(object2.type==="JSXNamespacedName"){return object2.namespace.name+":"+object2.name.name}if(object2.type==="JSXMemberExpression"){return getQualifiedJSXName(object2.object)+"."+getQualifiedJSXName(object2.property)}throw new Error("Node had unexpected type: "+object2.type)}var jsx=superClass=>class JSXParserMixin extends superClass{jsxReadToken(){let out="";let chunkStart=this.state.pos;for(;;){if(this.state.pos>=this.length){throw this.raise(JsxErrors.UnterminatedJsxContent,this.state.startLoc)}const ch=this.input.charCodeAt(this.state.pos);switch(ch){case 60:case 123:if(this.state.pos===this.state.start){if(ch===60&&this.state.canStartJSXElement){++this.state.pos;this.finishToken(143)}else{super.getTokenFromCode(ch)}return}out+=this.input.slice(chunkStart,this.state.pos);this.finishToken(142,out);return;case 38:out+=this.input.slice(chunkStart,this.state.pos);out+=this.jsxReadEntity();chunkStart=this.state.pos;break;case 62:case 125:default:if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.state.pos);out+=this.jsxReadNewLine(true);chunkStart=this.state.pos}else{++this.state.pos}}}}jsxReadNewLine(normalizeCRLF){const ch=this.input.charCodeAt(this.state.pos);let out;++this.state.pos;if(ch===13&&this.input.charCodeAt(this.state.pos)===10){++this.state.pos;out=normalizeCRLF?"\n":"\r\n"}else{out=String.fromCharCode(ch)}++this.state.curLine;this.state.lineStart=this.state.pos;return out}jsxReadString(quote){let out="";let chunkStart=++this.state.pos;for(;;){if(this.state.pos>=this.length){throw this.raise(Errors.UnterminatedString,this.state.startLoc)}const ch=this.input.charCodeAt(this.state.pos);if(ch===quote)break;if(ch===38){out+=this.input.slice(chunkStart,this.state.pos);out+=this.jsxReadEntity();chunkStart=this.state.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.state.pos);out+=this.jsxReadNewLine(false);chunkStart=this.state.pos}else{++this.state.pos}}out+=this.input.slice(chunkStart,this.state.pos++);this.finishToken(134,out)}jsxReadEntity(){const startPos=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let radix=10;if(this.codePointAtPos(this.state.pos)===120){radix=16;++this.state.pos}const codePoint=this.readInt(radix,void 0,false,"bail");if(codePoint!==null&&this.codePointAtPos(this.state.pos)===59){++this.state.pos;return String.fromCodePoint(codePoint)}}else{let count=0;let semi=false;while(count++<10&&this.state.pos<this.length&&!(semi=this.codePointAtPos(this.state.pos)===59)){++this.state.pos}if(semi){const desc=this.input.slice(startPos,this.state.pos);const entity=entities[desc];++this.state.pos;if(entity){return entity}}}this.state.pos=startPos;return"&"}jsxReadWord(){let ch;const start=this.state.pos;do{ch=this.input.charCodeAt(++this.state.pos)}while(isIdentifierChar(ch)||ch===45);this.finishToken(141,this.input.slice(start,this.state.pos))}jsxParseIdentifier(){const node=this.startNode();if(this.match(141)){node.name=this.state.value}else if(tokenIsKeyword(this.state.type)){node.name=tokenLabelName(this.state.type)}else{this.unexpected()}this.next();return this.finishNode(node,"JSXIdentifier")}jsxParseNamespacedName(){const startLoc=this.state.startLoc;const name=this.jsxParseIdentifier();if(!this.eat(14))return name;const node=this.startNodeAt(startLoc);node.namespace=name;node.name=this.jsxParseIdentifier();return this.finishNode(node,"JSXNamespacedName")}jsxParseElementName(){const startLoc=this.state.startLoc;let node=this.jsxParseNamespacedName();if(node.type==="JSXNamespacedName"){return node}while(this.eat(16)){const newNode=this.startNodeAt(startLoc);newNode.object=node;newNode.property=this.jsxParseIdentifier();node=this.finishNode(newNode,"JSXMemberExpression")}return node}jsxParseAttributeValue(){let node;switch(this.state.type){case 5:node=this.startNode();this.setContext(types.brace);this.next();node=this.jsxParseExpressionContainer(node,types.j_oTag);if(node.expression.type==="JSXEmptyExpression"){this.raise(JsxErrors.AttributeIsEmpty,node)}return node;case 143:case 134:return this.parseExprAtom();default:throw this.raise(JsxErrors.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){const node=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(node,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(node){this.next();node.expression=this.parseExpression();this.setContext(types.j_expr);this.state.canStartJSXElement=true;this.expect(8);return this.finishNode(node,"JSXSpreadChild")}jsxParseExpressionContainer(node,previousContext){if(this.match(8)){node.expression=this.jsxParseEmptyExpression()}else{const expression=this.parseExpression();node.expression=expression}this.setContext(previousContext);this.state.canStartJSXElement=true;this.expect(8);return this.finishNode(node,"JSXExpressionContainer")}jsxParseAttribute(){const node=this.startNode();if(this.match(5)){this.setContext(types.brace);this.next();this.expect(21);node.argument=this.parseMaybeAssignAllowIn();this.setContext(types.j_oTag);this.state.canStartJSXElement=true;this.expect(8);return this.finishNode(node,"JSXSpreadAttribute")}node.name=this.jsxParseNamespacedName();node.value=this.eat(29)?this.jsxParseAttributeValue():null;return this.finishNode(node,"JSXAttribute")}jsxParseOpeningElementAt(startLoc){const node=this.startNodeAt(startLoc);if(this.eat(144)){return this.finishNode(node,"JSXOpeningFragment")}node.name=this.jsxParseElementName();return this.jsxParseOpeningElementAfterName(node)}jsxParseOpeningElementAfterName(node){const attributes=[];while(!this.match(56)&&!this.match(144)){attributes.push(this.jsxParseAttribute())}node.attributes=attributes;node.selfClosing=this.eat(56);this.expect(144);return this.finishNode(node,"JSXOpeningElement")}jsxParseClosingElementAt(startLoc){const node=this.startNodeAt(startLoc);if(this.eat(144)){return this.finishNode(node,"JSXClosingFragment")}node.name=this.jsxParseElementName();this.expect(144);return this.finishNode(node,"JSXClosingElement")}jsxParseElementAt(startLoc){const node=this.startNodeAt(startLoc);const children=[];const openingElement=this.jsxParseOpeningElementAt(startLoc);let closingElement=null;if(!openingElement.selfClosing){contents:for(;;){switch(this.state.type){case 143:startLoc=this.state.startLoc;this.next();if(this.eat(56)){closingElement=this.jsxParseClosingElementAt(startLoc);break contents}children.push(this.jsxParseElementAt(startLoc));break;case 142:children.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{const node2=this.startNode();this.setContext(types.brace);this.next();if(this.match(21)){children.push(this.jsxParseSpreadChild(node2))}else{children.push(this.jsxParseExpressionContainer(node2,types.j_expr))}break}default:this.unexpected()}}if(isFragment(openingElement)&&!isFragment(closingElement)&&closingElement!==null){this.raise(JsxErrors.MissingClosingTagFragment,closingElement)}else if(!isFragment(openingElement)&&isFragment(closingElement)){this.raise(JsxErrors.MissingClosingTagElement,closingElement,{openingTagName:getQualifiedJSXName(openingElement.name)})}else if(!isFragment(openingElement)&&!isFragment(closingElement)){if(getQualifiedJSXName(closingElement.name)!==getQualifiedJSXName(openingElement.name)){this.raise(JsxErrors.MissingClosingTagElement,closingElement,{openingTagName:getQualifiedJSXName(openingElement.name)})}}}if(isFragment(openingElement)){node.openingFragment=openingElement;node.closingFragment=closingElement}else{node.openingElement=openingElement;node.closingElement=closingElement}node.children=children;if(this.match(47)){throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements,this.state.startLoc)}return isFragment(openingElement)?this.finishNode(node,"JSXFragment"):this.finishNode(node,"JSXElement")}jsxParseElement(){const startLoc=this.state.startLoc;this.next();return this.jsxParseElementAt(startLoc)}setContext(newContext){const{context}=this.state;context[context.length-1]=newContext}parseExprAtom(refExpressionErrors){if(this.match(143)){return this.jsxParseElement()}else if(this.match(47)&&this.input.charCodeAt(this.state.pos)!==33){this.replaceToken(143);return this.jsxParseElement()}else{return super.parseExprAtom(refExpressionErrors)}}skipSpace(){const curContext=this.curContext();if(!curContext.preserveSpace)super.skipSpace()}getTokenFromCode(code2){const context=this.curContext();if(context===types.j_expr){this.jsxReadToken();return}if(context===types.j_oTag||context===types.j_cTag){if(isIdentifierStart(code2)){this.jsxReadWord();return}if(code2===62){++this.state.pos;this.finishToken(144);return}if((code2===34||code2===39)&&context===types.j_oTag){this.jsxReadString(code2);return}}if(code2===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos;this.finishToken(143);return}super.getTokenFromCode(code2)}updateContext(prevType){const{context,type}=this.state;if(type===56&&prevType===143){context.splice(-2,2,types.j_cTag);this.state.canStartJSXElement=false}else if(type===143){context.push(types.j_oTag)}else if(type===144){const out=context[context.length-1];if(out===types.j_oTag&&prevType===56||out===types.j_cTag){context.pop();this.state.canStartJSXElement=context[context.length-1]===types.j_expr}else{this.setContext(types.j_expr);this.state.canStartJSXElement=true}}else{this.state.canStartJSXElement=tokenComesBeforeExpression(type)}}};var TypeScriptScope=class extends Scope{constructor(...args){super(...args);this.tsNames=new Map}};var TypeScriptScopeHandler=class extends ScopeHandler{constructor(...args){super(...args);this.importsStack=[]}createScope(flags){this.importsStack.push(new Set);return new TypeScriptScope(flags)}enter(flags){if(flags===1024){this.importsStack.push(new Set)}super.enter(flags)}exit(){const flags=super.exit();if(flags===1024){this.importsStack.pop()}return flags}hasImport(name,allowShadow){const len=this.importsStack.length;if(this.importsStack[len-1].has(name)){return true}if(!allowShadow&&len>1){for(let i=0;i<len-1;i++){if(this.importsStack[i].has(name))return true}}return false}declareName(name,bindingType,loc){if(bindingType&4096){if(this.hasImport(name,true)){this.parser.raise(Errors.VarRedeclaration,loc,{identifierName:name})}this.importsStack[this.importsStack.length-1].add(name);return}const scope=this.currentScope();let type=scope.tsNames.get(name)||0;if(bindingType&1024){this.maybeExportDefined(scope,name);scope.tsNames.set(name,type|16);return}super.declareName(name,bindingType,loc);if(bindingType&2){if(!(bindingType&1)){this.checkRedeclarationInScope(scope,name,bindingType,loc);this.maybeExportDefined(scope,name)}type=type|1}if(bindingType&256){type=type|2}if(bindingType&512){type=type|4}if(bindingType&128){type=type|8}if(type)scope.tsNames.set(name,type)}isRedeclaredInScope(scope,name,bindingType){const type=scope.tsNames.get(name);if((type&2)>0){if(bindingType&256){const isConst=!!(bindingType&512);const wasConst=(type&4)>0;return isConst!==wasConst}return true}if(bindingType&128&&(type&8)>0){if(scope.names.get(name)&2){return!!(bindingType&1)}else{return false}}if(bindingType&2&&(type&1)>0){return true}return super.isRedeclaredInScope(scope,name,bindingType)}checkLocalExport(id){const{name}=id;if(this.hasImport(name))return;const len=this.scopeStack.length;for(let i=len-1;i>=0;i--){const scope=this.scopeStack[i];const type=scope.tsNames.get(name);if((type&1)>0||(type&16)>0){return}}super.checkLocalExport(id)}};var ProductionParameterHandler=class{constructor(){this.stacks=[]}enter(flags){this.stacks.push(flags)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(this.currentFlags()&2)>0}get hasYield(){return(this.currentFlags()&1)>0}get hasReturn(){return(this.currentFlags()&4)>0}get hasIn(){return(this.currentFlags()&8)>0}};function functionFlags(isAsync,isGenerator){return(isAsync?2:0)|(isGenerator?1:0)}var BaseParser=class{constructor(){this.sawUnambiguousESM=false;this.ambiguousScriptDifferentAst=false}sourceToOffsetPos(sourcePos){return sourcePos+this.startIndex}offsetToSourcePos(offsetPos){return offsetPos-this.startIndex}hasPlugin(pluginConfig){if(typeof pluginConfig==="string"){return this.plugins.has(pluginConfig)}else{const[pluginName,pluginOptions]=pluginConfig;if(!this.hasPlugin(pluginName)){return false}const actualOptions=this.plugins.get(pluginName);for(const key of Object.keys(pluginOptions)){if((actualOptions==null?void 0:actualOptions[key])!==pluginOptions[key]){return false}}return true}}getPluginOption(plugin,name){var _this$plugins$get;return(_this$plugins$get=this.plugins.get(plugin))==null?void 0:_this$plugins$get[name]}};function setTrailingComments(node,comments){if(node.trailingComments===void 0){node.trailingComments=comments}else{node.trailingComments.unshift(...comments)}}function setLeadingComments(node,comments){if(node.leadingComments===void 0){node.leadingComments=comments}else{node.leadingComments.unshift(...comments)}}function setInnerComments(node,comments){if(node.innerComments===void 0){node.innerComments=comments}else{node.innerComments.unshift(...comments)}}function adjustInnerComments(node,elements,commentWS){let lastElement=null;let i=elements.length;while(lastElement===null&&i>0){lastElement=elements[--i]}if(lastElement===null||lastElement.start>commentWS.start){setInnerComments(node,commentWS.comments)}else{setTrailingComments(lastElement,commentWS.comments)}}var CommentsParser=class extends BaseParser{addComment(comment){if(this.filename)comment.loc.filename=this.filename;const{commentsLen}=this.state;if(this.comments.length!==commentsLen){this.comments.length=commentsLen}this.comments.push(comment);this.state.commentsLen++}processComment(node){const{commentStack}=this.state;const commentStackLength=commentStack.length;if(commentStackLength===0)return;let i=commentStackLength-1;const lastCommentWS=commentStack[i];if(lastCommentWS.start===node.end){lastCommentWS.leadingNode=node;i--}const{start:nodeStart}=node;for(;i>=0;i--){const commentWS=commentStack[i];const commentEnd=commentWS.end;if(commentEnd>nodeStart){commentWS.containingNode=node;this.finalizeComment(commentWS);commentStack.splice(i,1)}else{if(commentEnd===nodeStart){commentWS.trailingNode=node}break}}}finalizeComment(commentWS){var _node$options;const{comments}=commentWS;if(commentWS.leadingNode!==null||commentWS.trailingNode!==null){if(commentWS.leadingNode!==null){setTrailingComments(commentWS.leadingNode,comments)}if(commentWS.trailingNode!==null){setLeadingComments(commentWS.trailingNode,comments)}}else{const node=commentWS.containingNode;const commentStart=commentWS.start;if(this.input.charCodeAt(this.offsetToSourcePos(commentStart)-1)===44){switch(node.type){case"ObjectExpression":case"ObjectPattern":adjustInnerComments(node,node.properties,commentWS);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":adjustInnerComments(node,node.arguments,commentWS);break;case"ImportExpression":adjustInnerComments(node,[node.source,(_node$options=node.options)!=null?_node$options:null],commentWS);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":adjustInnerComments(node,node.params,commentWS);break;case"ArrayExpression":case"ArrayPattern":adjustInnerComments(node,node.elements,commentWS);break;case"ExportNamedDeclaration":case"ImportDeclaration":adjustInnerComments(node,node.specifiers,commentWS);break;case"TSEnumDeclaration":adjustInnerComments(node,node.members,commentWS);break;case"TSEnumBody":adjustInnerComments(node,node.members,commentWS);break;case"TSInterfaceBody":adjustInnerComments(node,node.body,commentWS);break;default:{if(node.type==="RecordExpression"){adjustInnerComments(node,node.properties,commentWS);break}if(node.type==="TupleExpression"){adjustInnerComments(node,node.elements,commentWS);break}setInnerComments(node,comments)}}}else{setInnerComments(node,comments)}}}finalizeRemainingComments(){const{commentStack}=this.state;for(let i=commentStack.length-1;i>=0;i--){this.finalizeComment(commentStack[i])}this.state.commentStack=[]}resetPreviousNodeTrailingComments(node){const{commentStack}=this.state;const{length}=commentStack;if(length===0)return;const commentWS=commentStack[length-1];if(commentWS.leadingNode===node){commentWS.leadingNode=null}}takeSurroundingComments(node,start,end){const{commentStack}=this.state;const commentStackLength=commentStack.length;if(commentStackLength===0)return;let i=commentStackLength-1;for(;i>=0;i--){const commentWS=commentStack[i];const commentEnd=commentWS.end;const commentStart=commentWS.start;if(commentStart===end){commentWS.leadingNode=node}else if(commentEnd===start){commentWS.trailingNode=node}else if(commentEnd<start){break}}}};var State=class _State{constructor(){this.flags=1024;this.startIndex=void 0;this.curLine=void 0;this.lineStart=void 0;this.startLoc=void 0;this.endLoc=void 0;this.errors=[];this.potentialArrowAt=-1;this.noArrowAt=[];this.noArrowParamsConversionAt=[];this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};this.labels=[];this.commentsLen=0;this.commentStack=[];this.pos=0;this.type=140;this.value=null;this.start=0;this.end=0;this.lastTokEndLoc=null;this.lastTokStartLoc=null;this.context=[types.brace];this.firstInvalidTemplateEscapePos=null;this.strictErrors=new Map;this.tokensLength=0}get strict(){return(this.flags&1)>0}set strict(v){if(v)this.flags|=1;else this.flags&=-2}init({strictMode,sourceType,startIndex,startLine,startColumn}){this.strict=strictMode===false?false:strictMode===true?true:sourceType==="module";this.startIndex=startIndex;this.curLine=startLine;this.lineStart=-startColumn;this.startLoc=this.endLoc=new Position(startLine,startColumn,startIndex)}get maybeInArrowParameters(){return(this.flags&2)>0}set maybeInArrowParameters(v){if(v)this.flags|=2;else this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(v){if(v)this.flags|=4;else this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(v){if(v)this.flags|=8;else this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(v){if(v)this.flags|=16;else this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(v){if(v)this.flags|=32;else this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(v){if(v)this.flags|=64;else this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(v){if(v)this.flags|=128;else this.flags&=-129}get soloAwait(){return(this.flags&256)>0}set soloAwait(v){if(v)this.flags|=256;else this.flags&=-257}get inFSharpPipelineDirectBody(){return(this.flags&512)>0}set inFSharpPipelineDirectBody(v){if(v)this.flags|=512;else this.flags&=-513}get canStartJSXElement(){return(this.flags&1024)>0}set canStartJSXElement(v){if(v)this.flags|=1024;else this.flags&=-1025}get containsEsc(){return(this.flags&2048)>0}set containsEsc(v){if(v)this.flags|=2048;else this.flags&=-2049}get hasTopLevelAwait(){return(this.flags&4096)>0}set hasTopLevelAwait(v){if(v)this.flags|=4096;else this.flags&=-4097}curPosition(){return new Position(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){const state=new _State;state.flags=this.flags;state.startIndex=this.startIndex;state.curLine=this.curLine;state.lineStart=this.lineStart;state.startLoc=this.startLoc;state.endLoc=this.endLoc;state.errors=this.errors.slice();state.potentialArrowAt=this.potentialArrowAt;state.noArrowAt=this.noArrowAt.slice();state.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice();state.topicContext=this.topicContext;state.labels=this.labels.slice();state.commentsLen=this.commentsLen;state.commentStack=this.commentStack.slice();state.pos=this.pos;state.type=this.type;state.value=this.value;state.start=this.start;state.end=this.end;state.lastTokEndLoc=this.lastTokEndLoc;state.lastTokStartLoc=this.lastTokStartLoc;state.context=this.context.slice();state.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos;state.strictErrors=this.strictErrors;state.tokensLength=this.tokensLength;return state}};var _isDigit=function isDigit(code2){return code2>=48&&code2<=57};var forbiddenNumericSeparatorSiblings={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])};var isAllowedNumericSeparatorSibling={bin:ch=>ch===48||ch===49,oct:ch=>ch>=48&&ch<=55,dec:ch=>ch>=48&&ch<=57,hex:ch=>ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102};function readStringContents(type,input,pos,lineStart,curLine,errors){const initialPos=pos;const initialLineStart=lineStart;const initialCurLine=curLine;let out="";let firstInvalidLoc=null;let chunkStart=pos;const{length}=input;for(;;){if(pos>=length){errors.unterminated(initialPos,initialLineStart,initialCurLine);out+=input.slice(chunkStart,pos);break}const ch=input.charCodeAt(pos);if(isStringEnd(type,ch,input,pos)){out+=input.slice(chunkStart,pos);break}if(ch===92){out+=input.slice(chunkStart,pos);const res=readEscapedChar(input,pos,lineStart,curLine,type==="template",errors);if(res.ch===null&&!firstInvalidLoc){firstInvalidLoc={pos,lineStart,curLine}}else{out+=res.ch}({pos,lineStart,curLine}=res);chunkStart=pos}else if(ch===8232||ch===8233){++pos;++curLine;lineStart=pos}else if(ch===10||ch===13){if(type==="template"){out+=input.slice(chunkStart,pos)+"\n";++pos;if(ch===13&&input.charCodeAt(pos)===10){++pos}++curLine;chunkStart=lineStart=pos}else{errors.unterminated(initialPos,initialLineStart,initialCurLine)}}else{++pos}}return{pos,str:out,firstInvalidLoc,lineStart,curLine,containsInvalid:!!firstInvalidLoc}}function isStringEnd(type,ch,input,pos){if(type==="template"){return ch===96||ch===36&&input.charCodeAt(pos+1)===123}return ch===(type==="double"?34:39)}function readEscapedChar(input,pos,lineStart,curLine,inTemplate,errors){const throwOnInvalid=!inTemplate;pos++;const res=ch2=>({pos,ch:ch2,lineStart,curLine});const ch=input.charCodeAt(pos++);switch(ch){case 110:return res("\n");case 114:return res("\r");case 120:{let code2;({code:code2,pos}=readHexChar(input,pos,lineStart,curLine,2,false,throwOnInvalid,errors));return res(code2===null?null:String.fromCharCode(code2))}case 117:{let code2;({code:code2,pos}=readCodePoint(input,pos,lineStart,curLine,throwOnInvalid,errors));return res(code2===null?null:String.fromCodePoint(code2))}case 116:return res(" ");case 98:return res("\b");case 118:return res("\v");case 102:return res("\f");case 13:if(input.charCodeAt(pos)===10){++pos}case 10:lineStart=pos;++curLine;case 8232:case 8233:return res("");case 56:case 57:if(inTemplate){return res(null)}else{errors.strictNumericEscape(pos-1,lineStart,curLine)}default:if(ch>=48&&ch<=55){const startPos=pos-1;const match=/^[0-7]+/.exec(input.slice(startPos,pos+2));let octalStr=match[0];let octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}pos+=octalStr.length-1;const next=input.charCodeAt(pos);if(octalStr!=="0"||next===56||next===57){if(inTemplate){return res(null)}else{errors.strictNumericEscape(startPos,lineStart,curLine)}}return res(String.fromCharCode(octal))}return res(String.fromCharCode(ch))}}function readHexChar(input,pos,lineStart,curLine,len,forceLen,throwOnInvalid,errors){const initialPos=pos;let n;({n,pos}=readInt(input,pos,lineStart,curLine,16,len,forceLen,false,errors,!throwOnInvalid));if(n===null){if(throwOnInvalid){errors.invalidEscapeSequence(initialPos,lineStart,curLine)}else{pos=initialPos-1}}return{code:n,pos}}function readInt(input,pos,lineStart,curLine,radix,len,forceLen,allowNumSeparator,errors,bailOnError){const start=pos;const forbiddenSiblings=radix===16?forbiddenNumericSeparatorSiblings.hex:forbiddenNumericSeparatorSiblings.decBinOct;const isAllowedSibling=radix===16?isAllowedNumericSeparatorSibling.hex:radix===10?isAllowedNumericSeparatorSibling.dec:radix===8?isAllowedNumericSeparatorSibling.oct:isAllowedNumericSeparatorSibling.bin;let invalid=false;let total=0;for(let i=0,e=len==null?Infinity:len;i<e;++i){const code2=input.charCodeAt(pos);let val;if(code2===95&&allowNumSeparator!=="bail"){const prev=input.charCodeAt(pos-1);const next=input.charCodeAt(pos+1);if(!allowNumSeparator){if(bailOnError)return{n:null,pos};errors.numericSeparatorInEscapeSequence(pos,lineStart,curLine)}else if(Number.isNaN(next)||!isAllowedSibling(next)||forbiddenSiblings.has(prev)||forbiddenSiblings.has(next)){if(bailOnError)return{n:null,pos};errors.unexpectedNumericSeparator(pos,lineStart,curLine)}++pos;continue}if(code2>=97){val=code2-97+10}else if(code2>=65){val=code2-65+10}else if(_isDigit(code2)){val=code2-48}else{val=Infinity}if(val>=radix){if(val<=9&&bailOnError){return{n:null,pos}}else if(val<=9&&errors.invalidDigit(pos,lineStart,curLine,radix)){val=0}else if(forceLen){val=0;invalid=true}else{break}}++pos;total=total*radix+val}if(pos===start||len!=null&&pos-start!==len||invalid){return{n:null,pos}}return{n:total,pos}}function readCodePoint(input,pos,lineStart,curLine,throwOnInvalid,errors){const ch=input.charCodeAt(pos);let code2;if(ch===123){++pos;({code:code2,pos}=readHexChar(input,pos,lineStart,curLine,input.indexOf("}",pos)-pos,true,throwOnInvalid,errors));++pos;if(code2!==null&&code2>1114111){if(throwOnInvalid){errors.invalidCodePoint(pos,lineStart,curLine)}else{return{code:null,pos}}}}else{({code:code2,pos}=readHexChar(input,pos,lineStart,curLine,4,false,throwOnInvalid,errors))}return{code:code2,pos}}function buildPosition(pos,lineStart,curLine){return new Position(curLine,pos-lineStart,pos)}var VALID_REGEX_FLAGS=new Set([103,109,115,105,121,117,100,118]);var Token=class{constructor(state){const startIndex=state.startIndex||0;this.type=state.type;this.value=state.value;this.start=startIndex+state.start;this.end=startIndex+state.end;this.loc=new SourceLocation(state.startLoc,state.endLoc)}};var Tokenizer=class extends CommentsParser{constructor(options,input){super();this.isLookahead=void 0;this.tokens=[];this.errorHandlers_readInt={invalidDigit:(pos,lineStart,curLine,radix)=>{if(!(this.optionFlags&2048))return false;this.raise(Errors.InvalidDigit,buildPosition(pos,lineStart,curLine),{radix});return true},numericSeparatorInEscapeSequence:this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(Errors.UnexpectedNumericSeparator)};this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(Errors.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(Errors.InvalidCodePoint)});this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(pos,lineStart,curLine)=>{this.recordStrictModeErrors(Errors.StrictNumericEscape,buildPosition(pos,lineStart,curLine))},unterminated:(pos,lineStart,curLine)=>{throw this.raise(Errors.UnterminatedString,buildPosition(pos-1,lineStart,curLine))}});this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(Errors.StrictNumericEscape),unterminated:(pos,lineStart,curLine)=>{throw this.raise(Errors.UnterminatedTemplate,buildPosition(pos,lineStart,curLine))}});this.state=new State;this.state.init(options);this.input=input;this.length=input.length;this.comments=[];this.isLookahead=false}pushToken(token2){this.tokens.length=this.state.tokensLength;this.tokens.push(token2);++this.state.tokensLength}next(){this.checkKeywordEscapes();if(this.optionFlags&256){this.pushToken(new Token(this.state))}this.state.lastTokEndLoc=this.state.endLoc;this.state.lastTokStartLoc=this.state.startLoc;this.nextToken()}eat(type){if(this.match(type)){this.next();return true}else{return false}}match(type){return this.state.type===type}createLookaheadState(state){return{pos:state.pos,value:null,type:state.type,start:state.start,end:state.end,context:[this.curContext()],inType:state.inType,startLoc:state.startLoc,lastTokEndLoc:state.lastTokEndLoc,curLine:state.curLine,lineStart:state.lineStart,curPosition:state.curPosition}}lookahead(){const old=this.state;this.state=this.createLookaheadState(old);this.isLookahead=true;this.nextToken();this.isLookahead=false;const curr=this.state;this.state=old;return curr}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(pos){skipWhiteSpace.lastIndex=pos;return skipWhiteSpace.test(this.input)?skipWhiteSpace.lastIndex:pos}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(pos){return this.input.charCodeAt(this.nextTokenStartSince(pos))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(pos){skipWhiteSpaceInLine.lastIndex=pos;return skipWhiteSpaceInLine.test(this.input)?skipWhiteSpaceInLine.lastIndex:pos}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(pos){let cp4=this.input.charCodeAt(pos);if((cp4&64512)===55296&&++pos<this.input.length){const trail=this.input.charCodeAt(pos);if((trail&64512)===56320){cp4=65536+((cp4&1023)<<10)+(trail&1023)}}return cp4}setStrict(strict){this.state.strict=strict;if(strict){this.state.strictErrors.forEach(([toParseError,at])=>this.raise(toParseError,at));this.state.strictErrors.clear()}}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){this.skipSpace();this.state.start=this.state.pos;if(!this.isLookahead)this.state.startLoc=this.state.curPosition();if(this.state.pos>=this.length){this.finishToken(140);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(commentEnd){let startLoc;if(!this.isLookahead)startLoc=this.state.curPosition();const start=this.state.pos;const end=this.input.indexOf(commentEnd,start+2);if(end===-1){throw this.raise(Errors.UnterminatedComment,this.state.curPosition())}this.state.pos=end+commentEnd.length;lineBreakG.lastIndex=start+2;while(lineBreakG.test(this.input)&&lineBreakG.lastIndex<=end){++this.state.curLine;this.state.lineStart=lineBreakG.lastIndex}if(this.isLookahead)return;const comment={type:"CommentBlock",value:this.input.slice(start+2,end),start:this.sourceToOffsetPos(start),end:this.sourceToOffsetPos(end+commentEnd.length),loc:new SourceLocation(startLoc,this.state.curPosition())};if(this.optionFlags&256)this.pushToken(comment);return comment}skipLineComment(startSkip){const start=this.state.pos;let startLoc;if(!this.isLookahead)startLoc=this.state.curPosition();let ch=this.input.charCodeAt(this.state.pos+=startSkip);if(this.state.pos<this.length){while(!isNewLine(ch)&&++this.state.pos<this.length){ch=this.input.charCodeAt(this.state.pos)}}if(this.isLookahead)return;const end=this.state.pos;const value=this.input.slice(start+startSkip,end);const comment={type:"CommentLine",value,start:this.sourceToOffsetPos(start),end:this.sourceToOffsetPos(end),loc:new SourceLocation(startLoc,this.state.curPosition())};if(this.optionFlags&256)this.pushToken(comment);return comment}skipSpace(){const spaceStart=this.state.pos;const comments=this.optionFlags&4096?[]:null;loop:while(this.state.pos<this.length){const ch=this.input.charCodeAt(this.state.pos);switch(ch){case 32:case 160:case 9:++this.state.pos;break;case 13:if(this.input.charCodeAt(this.state.pos+1)===10){++this.state.pos}case 10:case 8232:case 8233:++this.state.pos;++this.state.curLine;this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{const comment=this.skipBlockComment("*/");if(comment!==void 0){this.addComment(comment);comments==null||comments.push(comment)}break}case 47:{const comment=this.skipLineComment(2);if(comment!==void 0){this.addComment(comment);comments==null||comments.push(comment)}break}default:break loop}break;default:if(isWhitespace(ch)){++this.state.pos}else if(ch===45&&!this.inModule&&this.optionFlags&8192){const pos=this.state.pos;if(this.input.charCodeAt(pos+1)===45&&this.input.charCodeAt(pos+2)===62&&(spaceStart===0||this.state.lineStart>spaceStart)){const comment=this.skipLineComment(3);if(comment!==void 0){this.addComment(comment);comments==null||comments.push(comment)}}else{break loop}}else if(ch===60&&!this.inModule&&this.optionFlags&8192){const pos=this.state.pos;if(this.input.charCodeAt(pos+1)===33&&this.input.charCodeAt(pos+2)===45&&this.input.charCodeAt(pos+3)===45){const comment=this.skipLineComment(4);if(comment!==void 0){this.addComment(comment);comments==null||comments.push(comment)}}else{break loop}}else{break loop}}}if((comments==null?void 0:comments.length)>0){const end=this.state.pos;const commentWhitespace={start:this.sourceToOffsetPos(spaceStart),end:this.sourceToOffsetPos(end),comments,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(commentWhitespace)}}finishToken(type,val){this.state.end=this.state.pos;this.state.endLoc=this.state.curPosition();const prevType=this.state.type;this.state.type=type;this.state.value=val;if(!this.isLookahead){this.updateContext(prevType)}}replaceToken(type){this.state.type=type;this.updateContext()}readToken_numberSign(){if(this.state.pos===0&&this.readToken_interpreter()){return}const nextPos=this.state.pos+1;const next=this.codePointAtPos(nextPos);if(next>=48&&next<=57){throw this.raise(Errors.UnexpectedDigitAfterHash,this.state.curPosition())}if(next===123||next===91&&this.hasPlugin("recordAndTuple")){this.expectPlugin("recordAndTuple");if(this.getPluginOption("recordAndTuple","syntaxType")==="bar"){throw this.raise(next===123?Errors.RecordExpressionHashIncorrectStartSyntaxType:Errors.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition())}this.state.pos+=2;if(next===123){this.finishToken(7)}else{this.finishToken(1)}}else if(isIdentifierStart(next)){++this.state.pos;this.finishToken(139,this.readWord1(next))}else if(next===92){++this.state.pos;this.finishToken(139,this.readWord1())}else{this.finishOp(27,1)}}readToken_dot(){const next=this.input.charCodeAt(this.state.pos+1);if(next>=48&&next<=57){this.readNumber(true);return}if(next===46&&this.input.charCodeAt(this.state.pos+2)===46){this.state.pos+=3;this.finishToken(21)}else{++this.state.pos;this.finishToken(16)}}readToken_slash(){const next=this.input.charCodeAt(this.state.pos+1);if(next===61){this.finishOp(31,2)}else{this.finishOp(56,1)}}readToken_interpreter(){if(this.state.pos!==0||this.length<2)return false;let ch=this.input.charCodeAt(this.state.pos+1);if(ch!==33)return false;const start=this.state.pos;this.state.pos+=1;while(!isNewLine(ch)&&++this.state.pos<this.length){ch=this.input.charCodeAt(this.state.pos)}const value=this.input.slice(start+2,this.state.pos);this.finishToken(28,value);return true}readToken_mult_modulo(code2){let type=code2===42?55:54;let width=1;let next=this.input.charCodeAt(this.state.pos+1);if(code2===42&&next===42){width++;next=this.input.charCodeAt(this.state.pos+2);type=57}if(next===61&&!this.state.inType){width++;type=code2===37?33:30}this.finishOp(type,width)}readToken_pipe_amp(code2){const next=this.input.charCodeAt(this.state.pos+1);if(next===code2){if(this.input.charCodeAt(this.state.pos+2)===61){this.finishOp(30,3)}else{this.finishOp(code2===124?41:42,2)}return}if(code2===124){if(next===62){this.finishOp(39,2);return}if(this.hasPlugin("recordAndTuple")&&next===125){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar"){throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition())}this.state.pos+=2;this.finishToken(9);return}if(this.hasPlugin("recordAndTuple")&&next===93){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar"){throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition())}this.state.pos+=2;this.finishToken(4);return}}if(next===61){this.finishOp(30,2);return}this.finishOp(code2===124?43:45,1)}readToken_caret(){const next=this.input.charCodeAt(this.state.pos+1);if(next===61&&!this.state.inType){this.finishOp(32,2)}else if(next===94&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])){this.finishOp(37,2);const lookaheadCh=this.input.codePointAt(this.state.pos);if(lookaheadCh===94){this.unexpected()}}else{this.finishOp(44,1)}}readToken_atSign(){const next=this.input.charCodeAt(this.state.pos+1);if(next===64&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])){this.finishOp(38,2)}else{this.finishOp(26,1)}}readToken_plus_min(code2){const next=this.input.charCodeAt(this.state.pos+1);if(next===code2){this.finishOp(34,2);return}if(next===61){this.finishOp(30,2)}else{this.finishOp(53,1)}}readToken_lt(){const{pos}=this.state;const next=this.input.charCodeAt(pos+1);if(next===60){if(this.input.charCodeAt(pos+2)===61){this.finishOp(30,3);return}this.finishOp(51,2);return}if(next===61){this.finishOp(49,2);return}this.finishOp(47,1)}readToken_gt(){const{pos}=this.state;const next=this.input.charCodeAt(pos+1);if(next===62){const size=this.input.charCodeAt(pos+2)===62?3:2;if(this.input.charCodeAt(pos+size)===61){this.finishOp(30,size+1);return}this.finishOp(52,size);return}if(next===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(code2){const next=this.input.charCodeAt(this.state.pos+1);if(next===61){this.finishOp(46,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(code2===61&&next===62){this.state.pos+=2;this.finishToken(19);return}this.finishOp(code2===61?29:35,1)}readToken_question(){const next=this.input.charCodeAt(this.state.pos+1);const next2=this.input.charCodeAt(this.state.pos+2);if(next===63){if(next2===61){this.finishOp(30,3)}else{this.finishOp(40,2)}}else if(next===46&&!(next2>=48&&next2<=57)){this.state.pos+=2;this.finishToken(18)}else{++this.state.pos;this.finishToken(17)}}getTokenFromCode(code2){switch(code2){case 46:this.readToken_dot();return;case 40:++this.state.pos;this.finishToken(10);return;case 41:++this.state.pos;this.finishToken(11);return;case 59:++this.state.pos;this.finishToken(13);return;case 44:++this.state.pos;this.finishToken(12);return;case 91:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar"){throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType,this.state.curPosition())}this.state.pos+=2;this.finishToken(2)}else{++this.state.pos;this.finishToken(0)}return;case 93:++this.state.pos;this.finishToken(3);return;case 123:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar"){throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType,this.state.curPosition())}this.state.pos+=2;this.finishToken(6)}else{++this.state.pos;this.finishToken(5)}return;case 125:++this.state.pos;this.finishToken(8);return;case 58:if(this.hasPlugin("functionBind")&&this.input.charCodeAt(this.state.pos+1)===58){this.finishOp(15,2)}else{++this.state.pos;this.finishToken(14)}return;case 63:this.readToken_question();return;case 96:this.readTemplateToken();return;case 48:{const next=this.input.charCodeAt(this.state.pos+1);if(next===120||next===88){this.readRadixNumber(16);return}if(next===111||next===79){this.readRadixNumber(8);return}if(next===98||next===66){this.readRadixNumber(2);return}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:this.readNumber(false);return;case 34:case 39:this.readString(code2);return;case 47:this.readToken_slash();return;case 37:case 42:this.readToken_mult_modulo(code2);return;case 124:case 38:this.readToken_pipe_amp(code2);return;case 94:this.readToken_caret();return;case 43:case 45:this.readToken_plus_min(code2);return;case 60:this.readToken_lt();return;case 62:this.readToken_gt();return;case 61:case 33:this.readToken_eq_excl(code2);return;case 126:this.finishOp(36,1);return;case 64:this.readToken_atSign();return;case 35:this.readToken_numberSign();return;case 92:this.readWord();return;default:if(isIdentifierStart(code2)){this.readWord(code2);return}}throw this.raise(Errors.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(code2)})}finishOp(type,size){const str=this.input.slice(this.state.pos,this.state.pos+size);this.state.pos+=size;this.finishToken(type,str)}readRegexp(){const startLoc=this.state.startLoc;const start=this.state.start+1;let escaped,inClass;let{pos}=this.state;for(;;++pos){if(pos>=this.length){throw this.raise(Errors.UnterminatedRegExp,createPositionWithColumnOffset(startLoc,1))}const ch=this.input.charCodeAt(pos);if(isNewLine(ch)){throw this.raise(Errors.UnterminatedRegExp,createPositionWithColumnOffset(startLoc,1))}if(escaped){escaped=false}else{if(ch===91){inClass=true}else if(ch===93&&inClass){inClass=false}else if(ch===47&&!inClass){break}escaped=ch===92}}const content=this.input.slice(start,pos);++pos;let mods="";const nextPos=()=>createPositionWithColumnOffset(startLoc,pos+2-start);while(pos<this.length){const cp4=this.codePointAtPos(pos);const char=String.fromCharCode(cp4);if(VALID_REGEX_FLAGS.has(cp4)){if(cp4===118){if(mods.includes("u")){this.raise(Errors.IncompatibleRegExpUVFlags,nextPos())}}else if(cp4===117){if(mods.includes("v")){this.raise(Errors.IncompatibleRegExpUVFlags,nextPos())}}if(mods.includes(char)){this.raise(Errors.DuplicateRegExpFlags,nextPos())}}else if(isIdentifierChar(cp4)||cp4===92){this.raise(Errors.MalformedRegExpFlags,nextPos())}else{break}++pos;mods+=char}this.state.pos=pos;this.finishToken(138,{pattern:content,flags:mods})}readInt(radix,len,forceLen=false,allowNumSeparator=true){const{n,pos}=readInt(this.input,this.state.pos,this.state.lineStart,this.state.curLine,radix,len,forceLen,allowNumSeparator,this.errorHandlers_readInt,false);this.state.pos=pos;return n}readRadixNumber(radix){const start=this.state.pos;const startLoc=this.state.curPosition();let isBigInt=false;this.state.pos+=2;const val=this.readInt(radix);if(val==null){this.raise(Errors.InvalidDigit,createPositionWithColumnOffset(startLoc,2),{radix})}const next=this.input.charCodeAt(this.state.pos);if(next===110){++this.state.pos;isBigInt=true}else if(next===109){throw this.raise(Errors.InvalidDecimal,startLoc)}if(isIdentifierStart(this.codePointAtPos(this.state.pos))){throw this.raise(Errors.NumberIdentifier,this.state.curPosition())}if(isBigInt){const str=this.input.slice(start,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,str);return}this.finishToken(135,val)}readNumber(startsWithDot){const start=this.state.pos;const startLoc=this.state.curPosition();let isFloat=false;let isBigInt=false;let hasExponent=false;let isOctal=false;if(!startsWithDot&&this.readInt(10)===null){this.raise(Errors.InvalidNumber,this.state.curPosition())}const hasLeadingZero=this.state.pos-start>=2&&this.input.charCodeAt(start)===48;if(hasLeadingZero){const integer3=this.input.slice(start,this.state.pos);this.recordStrictModeErrors(Errors.StrictOctalLiteral,startLoc);if(!this.state.strict){const underscorePos=integer3.indexOf("_");if(underscorePos>0){this.raise(Errors.ZeroDigitNumericSeparator,createPositionWithColumnOffset(startLoc,underscorePos))}}isOctal=hasLeadingZero&&!/[89]/.test(integer3)}let next=this.input.charCodeAt(this.state.pos);if(next===46&&!isOctal){++this.state.pos;this.readInt(10);isFloat=true;next=this.input.charCodeAt(this.state.pos)}if((next===69||next===101)&&!isOctal){next=this.input.charCodeAt(++this.state.pos);if(next===43||next===45){++this.state.pos}if(this.readInt(10)===null){this.raise(Errors.InvalidOrMissingExponent,startLoc)}isFloat=true;hasExponent=true;next=this.input.charCodeAt(this.state.pos)}if(next===110){if(isFloat||hasLeadingZero){this.raise(Errors.InvalidBigIntLiteral,startLoc)}++this.state.pos;isBigInt=true}if(next===109){this.expectPlugin("decimal",this.state.curPosition());if(hasExponent||hasLeadingZero){this.raise(Errors.InvalidDecimal,startLoc)}++this.state.pos;var isDecimal=true}if(isIdentifierStart(this.codePointAtPos(this.state.pos))){throw this.raise(Errors.NumberIdentifier,this.state.curPosition())}const str=this.input.slice(start,this.state.pos).replace(/[_mn]/g,"");if(isBigInt){this.finishToken(136,str);return}if(isDecimal){this.finishToken(137,str);return}const val=isOctal?parseInt(str,8):parseFloat(str);this.finishToken(135,val)}readCodePoint(throwOnInvalid){const{code:code2,pos}=readCodePoint(this.input,this.state.pos,this.state.lineStart,this.state.curLine,throwOnInvalid,this.errorHandlers_readCodePoint);this.state.pos=pos;return code2}readString(quote){const{str,pos,curLine,lineStart}=readStringContents(quote===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=pos+1;this.state.lineStart=lineStart;this.state.curLine=curLine;this.finishToken(134,str)}readTemplateContinuation(){if(!this.match(8)){this.unexpected(null,8)}this.state.pos--;this.readTemplateToken()}readTemplateToken(){const opening=this.input[this.state.pos];const{str,firstInvalidLoc,pos,curLine,lineStart}=readStringContents("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=pos+1;this.state.lineStart=lineStart;this.state.curLine=curLine;if(firstInvalidLoc){this.state.firstInvalidTemplateEscapePos=new Position(firstInvalidLoc.curLine,firstInvalidLoc.pos-firstInvalidLoc.lineStart,this.sourceToOffsetPos(firstInvalidLoc.pos))}if(this.input.codePointAt(pos)===96){this.finishToken(24,firstInvalidLoc?null:opening+str+"`")}else{this.state.pos++;this.finishToken(25,firstInvalidLoc?null:opening+str+"${")}}recordStrictModeErrors(toParseError,at){const index=at.index;if(this.state.strict&&!this.state.strictErrors.has(index)){this.raise(toParseError,at)}else{this.state.strictErrors.set(index,[toParseError,at])}}readWord1(firstCode){this.state.containsEsc=false;let word="";const start=this.state.pos;let chunkStart=this.state.pos;if(firstCode!==void 0){this.state.pos+=firstCode<=65535?1:2}while(this.state.pos<this.length){const ch=this.codePointAtPos(this.state.pos);if(isIdentifierChar(ch)){this.state.pos+=ch<=65535?1:2}else if(ch===92){this.state.containsEsc=true;word+=this.input.slice(chunkStart,this.state.pos);const escStart=this.state.curPosition();const identifierCheck=this.state.pos===start?isIdentifierStart:isIdentifierChar;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(Errors.MissingUnicodeEscape,this.state.curPosition());chunkStart=this.state.pos-1;continue}++this.state.pos;const esc2=this.readCodePoint(true);if(esc2!==null){if(!identifierCheck(esc2)){this.raise(Errors.EscapedCharNotAnIdentifier,escStart)}word+=String.fromCodePoint(esc2)}chunkStart=this.state.pos}else{break}}return word+this.input.slice(chunkStart,this.state.pos)}readWord(firstCode){const word=this.readWord1(firstCode);const type=keywords$1.get(word);if(type!==void 0){this.finishToken(type,tokenLabelName(type))}else{this.finishToken(132,word)}}checkKeywordEscapes(){const{type}=this.state;if(tokenIsKeyword(type)&&this.state.containsEsc){this.raise(Errors.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:tokenLabelName(type)})}}raise(toParseError,at,details={}){const loc=at instanceof Position?at:at.loc.start;const error51=toParseError(loc,details);if(!(this.optionFlags&2048))throw error51;if(!this.isLookahead)this.state.errors.push(error51);return error51}raiseOverwrite(toParseError,at,details={}){const loc=at instanceof Position?at:at.loc.start;const pos=loc.index;const errors=this.state.errors;for(let i=errors.length-1;i>=0;i--){const error51=errors[i];if(error51.loc.index===pos){return errors[i]=toParseError(loc,details)}if(error51.loc.index<pos)break}return this.raise(toParseError,at,details)}updateContext(prevType){}unexpected(loc,type){throw this.raise(Errors.UnexpectedToken,loc!=null?loc:this.state.startLoc,{expected:type?tokenLabelName(type):null})}expectPlugin(pluginName,loc){if(this.hasPlugin(pluginName)){return true}throw this.raise(Errors.MissingPlugin,loc!=null?loc:this.state.startLoc,{missingPlugin:[pluginName]})}expectOnePlugin(pluginNames){if(!pluginNames.some(name=>this.hasPlugin(name))){throw this.raise(Errors.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:pluginNames})}}errorBuilder(error51){return(pos,lineStart,curLine)=>{this.raise(error51,buildPosition(pos,lineStart,curLine))}}};var ClassScope=class{constructor(){this.privateNames=new Set;this.loneAccessors=new Map;this.undefinedPrivateNames=new Map}};var ClassScopeHandler=class{constructor(parser){this.parser=void 0;this.stack=[];this.undefinedPrivateNames=new Map;this.parser=parser}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new ClassScope)}exit(){const oldClassScope=this.stack.pop();const current=this.current();for(const[name,loc]of Array.from(oldClassScope.undefinedPrivateNames)){if(current){if(!current.undefinedPrivateNames.has(name)){current.undefinedPrivateNames.set(name,loc)}}else{this.parser.raise(Errors.InvalidPrivateFieldResolution,loc,{identifierName:name})}}}declarePrivateName(name,elementType,loc){const{privateNames,loneAccessors,undefinedPrivateNames}=this.current();let redefined=privateNames.has(name);if(elementType&3){const accessor=redefined&&loneAccessors.get(name);if(accessor){const oldStatic=accessor&4;const newStatic=elementType&4;const oldKind=accessor&3;const newKind=elementType&3;redefined=oldKind===newKind||oldStatic!==newStatic;if(!redefined)loneAccessors.delete(name)}else if(!redefined){loneAccessors.set(name,elementType)}}if(redefined){this.parser.raise(Errors.PrivateNameRedeclaration,loc,{identifierName:name})}privateNames.add(name);undefinedPrivateNames.delete(name)}usePrivateName(name,loc){let classScope;for(classScope of this.stack){if(classScope.privateNames.has(name))return}if(classScope){classScope.undefinedPrivateNames.set(name,loc)}else{this.parser.raise(Errors.InvalidPrivateFieldResolution,loc,{identifierName:name})}}};var ExpressionScope=class{constructor(type=0){this.type=type}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}};var ArrowHeadParsingScope=class extends ExpressionScope{constructor(type){super(type);this.declarationErrors=new Map}recordDeclarationError(ParsingErrorClass,at){const index=at.index;this.declarationErrors.set(index,[ParsingErrorClass,at])}clearDeclarationError(index){this.declarationErrors.delete(index)}iterateErrors(iterator){this.declarationErrors.forEach(iterator)}};var ExpressionScopeHandler=class{constructor(parser){this.parser=void 0;this.stack=[new ExpressionScope];this.parser=parser}enter(scope){this.stack.push(scope)}exit(){this.stack.pop()}recordParameterInitializerError(toParseError,node){const origin=node.loc.start;const{stack}=this;let i=stack.length-1;let scope=stack[i];while(!scope.isCertainlyParameterDeclaration()){if(scope.canBeArrowParameterDeclaration()){scope.recordDeclarationError(toParseError,origin)}else{return}scope=stack[--i]}this.parser.raise(toParseError,origin)}recordArrowParameterBindingError(error51,node){const{stack}=this;const scope=stack[stack.length-1];const origin=node.loc.start;if(scope.isCertainlyParameterDeclaration()){this.parser.raise(error51,origin)}else if(scope.canBeArrowParameterDeclaration()){scope.recordDeclarationError(error51,origin)}else{return}}recordAsyncArrowParametersError(at){const{stack}=this;let i=stack.length-1;let scope=stack[i];while(scope.canBeArrowParameterDeclaration()){if(scope.type===2){scope.recordDeclarationError(Errors.AwaitBindingIdentifier,at)}scope=stack[--i]}}validateAsPattern(){const{stack}=this;const currentScope=stack[stack.length-1];if(!currentScope.canBeArrowParameterDeclaration())return;currentScope.iterateErrors(([toParseError,loc])=>{this.parser.raise(toParseError,loc);let i=stack.length-2;let scope=stack[i];while(scope.canBeArrowParameterDeclaration()){scope.clearDeclarationError(loc.index);scope=stack[--i]}})}};function newParameterDeclarationScope(){return new ExpressionScope(3)}function newArrowHeadScope(){return new ArrowHeadParsingScope(1)}function newAsyncArrowScope(){return new ArrowHeadParsingScope(2)}function newExpressionScope(){return new ExpressionScope}var UtilParser=class extends Tokenizer{addExtra(node,key,value,enumerable=true){if(!node)return;let{extra}=node;if(extra==null){extra={};node.extra=extra}if(enumerable){extra[key]=value}else{Object.defineProperty(extra,key,{enumerable,value})}}isContextual(token2){return this.state.type===token2&&!this.state.containsEsc}isUnparsedContextual(nameStart,name){if(this.input.startsWith(name,nameStart)){const nextCh=this.input.charCodeAt(nameStart+name.length);return!(isIdentifierChar(nextCh)||(nextCh&64512)===55296)}return false}isLookaheadContextual(name){const next=this.nextTokenStart();return this.isUnparsedContextual(next,name)}eatContextual(token2){if(this.isContextual(token2)){this.next();return true}return false}expectContextual(token2,toParseError){if(!this.eatContextual(token2)){if(toParseError!=null){throw this.raise(toParseError,this.state.startLoc)}this.unexpected(null,token2)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return hasNewLine(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return hasNewLine(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(allowAsi=true){if(allowAsi?this.isLineTerminator():this.eat(13))return;this.raise(Errors.MissingSemicolon,this.state.lastTokEndLoc)}expect(type,loc){if(!this.eat(type)){this.unexpected(loc,type)}}tryParse(fn,oldState=this.state.clone()){const abortSignal={node:null};try{const node=fn((node2=null)=>{abortSignal.node=node2;throw abortSignal});if(this.state.errors.length>oldState.errors.length){const failState=this.state;this.state=oldState;this.state.tokensLength=failState.tokensLength;return{node,error:failState.errors[oldState.errors.length],thrown:false,aborted:false,failState}}return{node,error:null,thrown:false,aborted:false,failState:null}}catch(error51){const failState=this.state;this.state=oldState;if(error51 instanceof SyntaxError){return{node:null,error:error51,thrown:true,aborted:false,failState}}if(error51===abortSignal){return{node:abortSignal.node,error:null,thrown:false,aborted:true,failState}}throw error51}}checkExpressionErrors(refExpressionErrors,andThrow){if(!refExpressionErrors)return false;const{shorthandAssignLoc,doubleProtoLoc,privateKeyLoc,optionalParametersLoc,voidPatternLoc}=refExpressionErrors;const hasErrors=!!shorthandAssignLoc||!!doubleProtoLoc||!!optionalParametersLoc||!!privateKeyLoc||!!voidPatternLoc;if(!andThrow){return hasErrors}if(shorthandAssignLoc!=null){this.raise(Errors.InvalidCoverInitializedName,shorthandAssignLoc)}if(doubleProtoLoc!=null){this.raise(Errors.DuplicateProto,doubleProtoLoc)}if(privateKeyLoc!=null){this.raise(Errors.UnexpectedPrivateField,privateKeyLoc)}if(optionalParametersLoc!=null){this.unexpected(optionalParametersLoc)}if(voidPatternLoc!=null){this.raise(Errors.InvalidCoverDiscardElement,voidPatternLoc)}}isLiteralPropertyName(){return tokenIsLiteralPropertyName(this.state.type)}isPrivateName(node){return node.type==="PrivateName"}getPrivateNameSV(node){return node.id.name}hasPropertyAsPrivateName(node){return(node.type==="MemberExpression"||node.type==="OptionalMemberExpression")&&this.isPrivateName(node.property)}isObjectProperty(node){return node.type==="ObjectProperty"}isObjectMethod(node){return node.type==="ObjectMethod"}initializeScopes(inModule=this.options.sourceType==="module"){const oldLabels=this.state.labels;this.state.labels=[];const oldExportedIdentifiers=this.exportedIdentifiers;this.exportedIdentifiers=new Set;const oldInModule=this.inModule;this.inModule=inModule;const oldScope=this.scope;const ScopeHandler2=this.getScopeHandler();this.scope=new ScopeHandler2(this,inModule);const oldProdParam=this.prodParam;this.prodParam=new ProductionParameterHandler;const oldClassScope=this.classScope;this.classScope=new ClassScopeHandler(this);const oldExpressionScope=this.expressionScope;this.expressionScope=new ExpressionScopeHandler(this);return()=>{this.state.labels=oldLabels;this.exportedIdentifiers=oldExportedIdentifiers;this.inModule=oldInModule;this.scope=oldScope;this.prodParam=oldProdParam;this.classScope=oldClassScope;this.expressionScope=oldExpressionScope}}enterInitialScopes(){let paramFlags=0;if(this.inModule||this.optionFlags&1){paramFlags|=2}if(this.optionFlags&32){paramFlags|=1}const isCommonJS=!this.inModule&&this.options.sourceType==="commonjs";if(isCommonJS||this.optionFlags&2){paramFlags|=4}this.prodParam.enter(paramFlags);let scopeFlags=isCommonJS?514:1;if(this.optionFlags&4){scopeFlags|=512}this.scope.enter(scopeFlags)}checkDestructuringPrivate(refExpressionErrors){const{privateKeyLoc}=refExpressionErrors;if(privateKeyLoc!==null){this.expectPlugin("destructuringPrivate",privateKeyLoc)}}};var ExpressionErrors=class{constructor(){this.shorthandAssignLoc=null;this.doubleProtoLoc=null;this.privateKeyLoc=null;this.optionalParametersLoc=null;this.voidPatternLoc=null}};var Node=class{constructor(parser,pos,loc){this.type="";this.start=pos;this.end=0;this.loc=new SourceLocation(loc);if((parser==null?void 0:parser.optionFlags)&128)this.range=[pos,0];if(parser!=null&&parser.filename)this.loc.filename=parser.filename}};var NodePrototype=Node.prototype;NodePrototype.__clone=function(){const newNode=new Node(void 0,this.start,this.loc.start);const keys2=Object.keys(this);for(let i=0,length=keys2.length;i<length;i++){const key=keys2[i];if(key!=="leadingComments"&&key!=="trailingComments"&&key!=="innerComments"){newNode[key]=this[key]}}return newNode};var NodeUtils=class extends UtilParser{startNode(){const loc=this.state.startLoc;return new Node(this,loc.index,loc)}startNodeAt(loc){return new Node(this,loc.index,loc)}startNodeAtNode(type){return this.startNodeAt(type.loc.start)}finishNode(node,type){return this.finishNodeAt(node,type,this.state.lastTokEndLoc)}finishNodeAt(node,type,endLoc){node.type=type;node.end=endLoc.index;node.loc.end=endLoc;if(this.optionFlags&128)node.range[1]=endLoc.index;if(this.optionFlags&4096){this.processComment(node)}return node}resetStartLocation(node,startLoc){node.start=startLoc.index;node.loc.start=startLoc;if(this.optionFlags&128)node.range[0]=startLoc.index}resetEndLocation(node,endLoc=this.state.lastTokEndLoc){node.end=endLoc.index;node.loc.end=endLoc;if(this.optionFlags&128)node.range[1]=endLoc.index}resetStartLocationFromNode(node,locationNode){this.resetStartLocation(node,locationNode.loc.start)}castNodeTo(node,type){node.type=type;return node}cloneIdentifier(node){const{type,start,end,loc,range,name}=node;const cloned=Object.create(NodePrototype);cloned.type=type;cloned.start=start;cloned.end=end;cloned.loc=loc;cloned.range=range;cloned.name=name;if(node.extra)cloned.extra=node.extra;return cloned}cloneStringLiteral(node){const{type,start,end,loc,range,extra}=node;const cloned=Object.create(NodePrototype);cloned.type=type;cloned.start=start;cloned.end=end;cloned.loc=loc;cloned.range=range;cloned.extra=extra;cloned.value=node.value;return cloned}};var unwrapParenthesizedExpression=node=>{return node.type==="ParenthesizedExpression"?unwrapParenthesizedExpression(node.expression):node};var LValParser=class extends NodeUtils{toAssignable(node,isLHS=false){var _node$extra,_node$extra3;let parenthesized=void 0;if(node.type==="ParenthesizedExpression"||(_node$extra=node.extra)!=null&&_node$extra.parenthesized){parenthesized=unwrapParenthesizedExpression(node);if(isLHS){if(parenthesized.type==="Identifier"){this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment,node)}else if(parenthesized.type!=="CallExpression"&&parenthesized.type!=="MemberExpression"&&!this.isOptionalMemberExpression(parenthesized)){this.raise(Errors.InvalidParenthesizedAssignment,node)}}else{this.raise(Errors.InvalidParenthesizedAssignment,node)}}switch(node.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(node,"ObjectPattern");for(let i=0,length=node.properties.length,last=length-1;i<length;i++){var _node$extra2;const prop=node.properties[i];const isLast=i===last;this.toAssignableObjectExpressionProp(prop,isLast,isLHS);if(isLast&&prop.type==="RestElement"&&(_node$extra2=node.extra)!=null&&_node$extra2.trailingCommaLoc){this.raise(Errors.RestTrailingComma,node.extra.trailingCommaLoc)}}break;case"ObjectProperty":{const{key,value}=node;if(this.isPrivateName(key)){this.classScope.usePrivateName(this.getPrivateNameSV(key),key.loc.start)}this.toAssignable(value,isLHS);break}case"SpreadElement":{throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.")}case"ArrayExpression":this.castNodeTo(node,"ArrayPattern");this.toAssignableList(node.elements,(_node$extra3=node.extra)==null?void 0:_node$extra3.trailingCommaLoc,isLHS);break;case"AssignmentExpression":if(node.operator!=="="){this.raise(Errors.MissingEqInAssignment,node.left.loc.end)}this.castNodeTo(node,"AssignmentPattern");delete node.operator;if(node.left.type==="VoidPattern"){this.raise(Errors.VoidPatternInitializer,node.left)}this.toAssignable(node.left,isLHS);break;case"ParenthesizedExpression":this.toAssignable(parenthesized,isLHS);break}}toAssignableObjectExpressionProp(prop,isLast,isLHS){if(prop.type==="ObjectMethod"){this.raise(prop.kind==="get"||prop.kind==="set"?Errors.PatternHasAccessor:Errors.PatternHasMethod,prop.key)}else if(prop.type==="SpreadElement"){this.castNodeTo(prop,"RestElement");const arg=prop.argument;this.checkToRestConversion(arg,false);this.toAssignable(arg,isLHS);if(!isLast){this.raise(Errors.RestTrailingComma,prop)}}else{this.toAssignable(prop,isLHS)}}toAssignableList(exprList,trailingCommaLoc,isLHS){const end=exprList.length-1;for(let i=0;i<=end;i++){const elt=exprList[i];if(!elt)continue;this.toAssignableListItem(exprList,i,isLHS);if(elt.type==="RestElement"){if(i<end){this.raise(Errors.RestTrailingComma,elt)}else if(trailingCommaLoc){this.raise(Errors.RestTrailingComma,trailingCommaLoc)}}}}toAssignableListItem(exprList,index,isLHS){const node=exprList[index];if(node.type==="SpreadElement"){this.castNodeTo(node,"RestElement");const arg=node.argument;this.checkToRestConversion(arg,true);this.toAssignable(arg,isLHS)}else{this.toAssignable(node,isLHS)}}isAssignable(node,isBinding){switch(node.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return true;case"ObjectExpression":{const last=node.properties.length-1;return node.properties.every((prop,i)=>{return prop.type!=="ObjectMethod"&&(i===last||prop.type!=="SpreadElement")&&this.isAssignable(prop)})}case"ObjectProperty":return this.isAssignable(node.value);case"SpreadElement":return this.isAssignable(node.argument);case"ArrayExpression":return node.elements.every(element=>element===null||this.isAssignable(element));case"AssignmentExpression":return node.operator==="=";case"ParenthesizedExpression":return this.isAssignable(node.expression);case"MemberExpression":case"OptionalMemberExpression":return!isBinding;default:return false}}toReferencedList(exprList,isParenthesizedExpr){return exprList}toReferencedListDeep(exprList,isParenthesizedExpr){this.toReferencedList(exprList,isParenthesizedExpr);for(const expr of exprList){if((expr==null?void 0:expr.type)==="ArrayExpression"){this.toReferencedListDeep(expr.elements)}}}parseSpread(refExpressionErrors){const node=this.startNode();this.next();node.argument=this.parseMaybeAssignAllowIn(refExpressionErrors,void 0);return this.finishNode(node,"SpreadElement")}parseRestBinding(){const node=this.startNode();this.next();const argument=this.parseBindingAtom();if(argument.type==="VoidPattern"){this.raise(Errors.UnexpectedVoidPattern,argument)}node.argument=argument;return this.finishNode(node,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{const node=this.startNode();this.next();node.elements=this.parseBindingList(3,93,1);return this.finishNode(node,"ArrayPattern")}case 5:return this.parseObjectLike(8,true);case 88:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(close,closeCharCode,flags){const allowEmpty=flags&1;const elts=[];let first=true;while(!this.eat(close)){if(first){first=false}else{this.expect(12)}if(allowEmpty&&this.match(12)){elts.push(null)}else if(this.eat(close)){break}else if(this.match(21)){let rest=this.parseRestBinding();if(this.hasPlugin("flow")||flags&2){rest=this.parseFunctionParamType(rest)}elts.push(rest);if(!this.checkCommaAfterRest(closeCharCode)){this.expect(close);break}}else{const decorators=[];if(flags&2){if(this.match(26)&&this.hasPlugin("decorators")){this.raise(Errors.UnsupportedParameterDecorator,this.state.startLoc)}while(this.match(26)){decorators.push(this.parseDecorator())}}elts.push(this.parseBindingElement(flags,decorators))}}return elts}parseBindingRestProperty(prop){this.next();if(this.hasPlugin("discardBinding")&&this.match(88)){prop.argument=this.parseVoidPattern(null);this.raise(Errors.UnexpectedVoidPattern,prop.argument)}else{prop.argument=this.parseIdentifier()}this.checkCommaAfterRest(125);return this.finishNode(prop,"RestElement")}parseBindingProperty(){const{type,startLoc}=this.state;if(type===21){return this.parseBindingRestProperty(this.startNode())}const prop=this.startNode();if(type===139){this.expectPlugin("destructuringPrivate",startLoc);this.classScope.usePrivateName(this.state.value,startLoc);prop.key=this.parsePrivateName()}else{this.parsePropertyName(prop)}prop.method=false;return this.parseObjPropValue(prop,startLoc,false,false,true,false)}parseBindingElement(flags,decorators){const left=this.parseMaybeDefault();if(this.hasPlugin("flow")||flags&2){this.parseFunctionParamType(left)}if(decorators.length){left.decorators=decorators;this.resetStartLocationFromNode(left,decorators[0])}const elt=this.parseMaybeDefault(left.loc.start,left);return elt}parseFunctionParamType(param){return param}parseMaybeDefault(startLoc,left){startLoc!=null?startLoc:startLoc=this.state.startLoc;left=left!=null?left:this.parseBindingAtom();if(!this.eat(29))return left;const node=this.startNodeAt(startLoc);if(left.type==="VoidPattern"){this.raise(Errors.VoidPatternInitializer,left)}node.left=left;node.right=this.parseMaybeAssignAllowIn();return this.finishNode(node,"AssignmentPattern")}isValidLVal(type,disallowCallExpression,isUnparenthesizedInAssign,binding){switch(type){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties";case"VoidPattern":return true;case"CallExpression":if(!disallowCallExpression&&!this.state.strict&&this.optionFlags&8192){return true}}return false}isOptionalMemberExpression(expression){return expression.type==="OptionalMemberExpression"}checkLVal(expression,ancestor,binding=64,checkClashes=false,strictModeChanged=false,hasParenthesizedAncestor=false,disallowCallExpression=false){var _expression$extra;const type=expression.type;if(this.isObjectMethod(expression))return;const isOptionalMemberExpression=this.isOptionalMemberExpression(expression);if(isOptionalMemberExpression||type==="MemberExpression"){if(isOptionalMemberExpression){this.expectPlugin("optionalChainingAssign",expression.loc.start);if(ancestor.type!=="AssignmentExpression"){this.raise(Errors.InvalidLhsOptionalChaining,expression,{ancestor})}}if(binding!==64){this.raise(Errors.InvalidPropertyBindingPattern,expression)}return}if(type==="Identifier"){this.checkIdentifier(expression,binding,strictModeChanged);const{name}=expression;if(checkClashes){if(checkClashes.has(name)){this.raise(Errors.ParamDupe,expression)}else{checkClashes.add(name)}}return}else if(type==="VoidPattern"&&ancestor.type==="CatchClause"){this.raise(Errors.VoidPatternCatchClauseParam,expression)}const unwrappedExpression=unwrapParenthesizedExpression(expression);disallowCallExpression||(disallowCallExpression=unwrappedExpression.type==="CallExpression"&&(unwrappedExpression.callee.type==="Import"||unwrappedExpression.callee.type==="Super"));const validity=this.isValidLVal(type,disallowCallExpression,!(hasParenthesizedAncestor||(_expression$extra=expression.extra)!=null&&_expression$extra.parenthesized)&&ancestor.type==="AssignmentExpression",binding);if(validity===true)return;if(validity===false){const ParseErrorClass=binding===64?Errors.InvalidLhs:Errors.InvalidLhsBinding;this.raise(ParseErrorClass,expression,{ancestor});return}let key,isParenthesizedExpression;if(typeof validity==="string"){key=validity;isParenthesizedExpression=type==="ParenthesizedExpression"}else{[key,isParenthesizedExpression]=validity}const nextAncestor=type==="ArrayPattern"||type==="ObjectPattern"?{type}:ancestor;const val=expression[key];if(Array.isArray(val)){for(const child of val){if(child){this.checkLVal(child,nextAncestor,binding,checkClashes,strictModeChanged,isParenthesizedExpression,true)}}}else if(val){this.checkLVal(val,nextAncestor,binding,checkClashes,strictModeChanged,isParenthesizedExpression,disallowCallExpression)}}checkIdentifier(at,bindingType,strictModeChanged=false){if(this.state.strict&&(strictModeChanged?isStrictBindReservedWord(at.name,this.inModule):isStrictBindOnlyReservedWord(at.name))){if(bindingType===64){this.raise(Errors.StrictEvalArguments,at,{referenceName:at.name})}else{this.raise(Errors.StrictEvalArgumentsBinding,at,{bindingName:at.name})}}if(bindingType&8192&&at.name==="let"){this.raise(Errors.LetInLexicalBinding,at)}if(!(bindingType&64)){this.declareNameFromIdentifier(at,bindingType)}}declareNameFromIdentifier(identifier,binding){this.scope.declareName(identifier.name,binding,identifier.loc.start)}checkToRestConversion(node,allowPattern){switch(node.type){case"ParenthesizedExpression":this.checkToRestConversion(node.expression,allowPattern);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(allowPattern)break;default:this.raise(Errors.InvalidRestAssignmentPattern,node)}}checkCommaAfterRest(close){if(!this.match(12)){return false}this.raise(this.lookaheadCharCode()===close?Errors.RestTrailingComma:Errors.ElementAfterRest,this.state.startLoc);return true}};var keywordAndTSRelationalOperator=/in(?:stanceof)?|as|satisfies/y;function nonNull(x){if(x==null){throw new Error(`Unexpected ${x} value.`)}return x}function assert2(x){if(!x){throw new Error("Assert fail")}}var TSErrors=ParseErrorEnum`typescript`({AbstractMethodHasImplementation:({methodName})=>`Method '${methodName}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName})=>`Property '${propertyName}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",ConstructorHasTypeParameters:"Type parameters cannot appear on a constructor declaration.",DeclareAccessor:({kind})=>`'declare' is not allowed in ${kind}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier})=>`Accessibility modifier already seen: '${modifier}'.`,DuplicateModifier:({modifier})=>`Duplicate modifier: '${modifier}'.`,EmptyHeritageClauseType:({token:token2})=>`'${token2}' list cannot be empty.`,EmptyTypeArguments:"Type argument list cannot be empty.",EmptyTypeParameters:"Type parameter list cannot be empty.",ExpectedAmbientAfterExportDeclare:"'export declare' must be followed by an ambient declaration.",ImportAliasHasImportType:"An import alias can not use 'import type'.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` modifier",IncompatibleModifiers:({modifiers})=>`'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier})=>`Index signatures cannot have an accessibility modifier ('${modifier}').`,IndexSignatureHasDeclare:"Index signatures cannot have the 'declare' modifier.",IndexSignatureHasOverride:"'override' modifier cannot appear on an index signature.",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier.",InitializerNotAllowedInAmbientContext:"Initializers are not allowed in ambient contexts.",InvalidHeritageClauseType:({token:token2})=>`'${token2}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:modifier=>`'${modifier}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier})=>`'${modifier}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier})=>`'${modifier}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier})=>`'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:modifier=>`'${modifier}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers})=>`'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,InvalidPropertyAccessAfterInstantiationExpression:"Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",InvalidTupleMemberLabel:"Tuple members must be labeled with a simple identifier.",MissingInterfaceName:"'interface' declarations must be followed by an identifier.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifier:"'abstract' modifier can only appear on a class, method, or property declaration.",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",OverrideNotInSubClass:"This member cannot have an 'override' modifier because its containing class does not extend another class.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:({modifier})=>`Private elements cannot have an accessibility modifier ('${modifier}').`,ReadonlyForMethodSignature:"'readonly' modifier can only appear on a property declaration or index signature.",ReservedArrowTypeParam:"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName})=>`Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:({type})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`,UsingDeclarationInAmbientContext:kind=>`'${kind}' declarations are not allowed in ambient contexts.`});function keywordTypeFromName(value){switch(value){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return void 0}}function tsIsAccessModifier(modifier){return modifier==="private"||modifier==="public"||modifier==="protected"}function tsIsVarianceAnnotations(modifier){return modifier==="in"||modifier==="out"}var typescript=superClass=>class TypeScriptParserMixin extends superClass{constructor(...args){super(...args);this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:TSErrors.InvalidModifierOnTypeParameter});this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:TSErrors.InvalidModifierOnTypeParameterPositions});this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:TSErrors.InvalidModifierOnTypeParameter})}getScopeHandler(){return TypeScriptScopeHandler}tsIsIdentifier(){return tokenIsIdentifier(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(139)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){this.next();if(this.hasPrecedingLineBreak()){return false}return this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){if(this.match(106)){this.next();return this.tsTokenCanFollowModifier()}return this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(allowedModifiers,stopOnStartOfClassStaticBlock,hasSeenStaticModifier){if(!tokenIsIdentifier(this.state.type)&&this.state.type!==58&&this.state.type!==75){return void 0}const modifier=this.state.value;if(allowedModifiers.includes(modifier)){if(hasSeenStaticModifier&&this.match(106)){return void 0}if(stopOnStartOfClassStaticBlock&&this.tsIsStartOfStaticBlocks()){return void 0}if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))){return modifier}}return void 0}tsParseModifiers({allowedModifiers,disallowedModifiers,stopOnStartOfClassStaticBlock,errorTemplate=TSErrors.InvalidModifierOnTypeMember},modified){const enforceOrder=(loc,modifier,before,after)=>{if(modifier===before&&modified[after]){this.raise(TSErrors.InvalidModifiersOrder,loc,{orderedModifiers:[before,after]})}};const incompatible=(loc,modifier,mod1,mod2)=>{if(modified[mod1]&&modifier===mod2||modified[mod2]&&modifier===mod1){this.raise(TSErrors.IncompatibleModifiers,loc,{modifiers:[mod1,mod2]})}};for(;;){const{startLoc}=this.state;const modifier=this.tsParseModifier(allowedModifiers.concat(disallowedModifiers!=null?disallowedModifiers:[]),stopOnStartOfClassStaticBlock,modified.static);if(!modifier)break;if(tsIsAccessModifier(modifier)){if(modified.accessibility){this.raise(TSErrors.DuplicateAccessibilityModifier,startLoc,{modifier})}else{enforceOrder(startLoc,modifier,modifier,"override");enforceOrder(startLoc,modifier,modifier,"static");enforceOrder(startLoc,modifier,modifier,"readonly");modified.accessibility=modifier}}else if(tsIsVarianceAnnotations(modifier)){if(modified[modifier]){this.raise(TSErrors.DuplicateModifier,startLoc,{modifier})}modified[modifier]=true;enforceOrder(startLoc,modifier,"in","out")}else{if(hasOwnProperty.call(modified,modifier)){this.raise(TSErrors.DuplicateModifier,startLoc,{modifier})}else{enforceOrder(startLoc,modifier,"static","readonly");enforceOrder(startLoc,modifier,"static","override");enforceOrder(startLoc,modifier,"override","readonly");enforceOrder(startLoc,modifier,"abstract","override");incompatible(startLoc,modifier,"declare","override");incompatible(startLoc,modifier,"static","abstract")}modified[modifier]=true}if(disallowedModifiers!=null&&disallowedModifiers.includes(modifier)){this.raise(errorTemplate,startLoc,{modifier})}}}tsIsListTerminator(kind){switch(kind){case"EnumMembers":case"TypeMembers":return this.match(8);case"HeritageClauseElement":return this.match(5);case"TupleElementTypes":return this.match(3);case"TypeParametersOrArguments":return this.match(48)}}tsParseList(kind,parseElement){const result2=[];while(!this.tsIsListTerminator(kind)){result2.push(parseElement())}return result2}tsParseDelimitedList(kind,parseElement,refTrailingCommaPos){return nonNull(this.tsParseDelimitedListWorker(kind,parseElement,true,refTrailingCommaPos))}tsParseDelimitedListWorker(kind,parseElement,expectSuccess,refTrailingCommaPos){const result2=[];let trailingCommaPos=-1;for(;;){if(this.tsIsListTerminator(kind)){break}trailingCommaPos=-1;const element=parseElement();if(element==null){return void 0}result2.push(element);if(this.eat(12)){trailingCommaPos=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(kind)){break}if(expectSuccess){this.expect(12)}return void 0}if(refTrailingCommaPos){refTrailingCommaPos.value=trailingCommaPos}return result2}tsParseBracketedList(kind,parseElement,bracket,skipFirstToken,refTrailingCommaPos){if(!skipFirstToken){if(bracket){this.expect(0)}else{this.expect(47)}}const result2=this.tsParseDelimitedList(kind,parseElement,refTrailingCommaPos);if(bracket){this.expect(3)}else{this.expect(48)}return result2}tsParseImportType(){const node=this.startNode();this.expect(83);this.expect(10);if(!this.match(134)){this.raise(TSErrors.UnsupportedImportTypeArgument,this.state.startLoc);node.argument=super.parseExprAtom()}else{node.argument=this.parseStringLiteral(this.state.value)}if(this.eat(12)){node.options=this.tsParseImportTypeOptions()}else{node.options=null}this.expect(11);if(this.eat(16)){node.qualifier=this.tsParseEntityName(1|2)}if(this.match(47)){node.typeParameters=this.tsParseTypeArguments()}return this.finishNode(node,"TSImportType")}tsParseImportTypeOptions(){const node=this.startNode();this.expect(5);const withProperty=this.startNode();if(this.isContextual(76)){withProperty.method=false;withProperty.key=this.parseIdentifier(true);withProperty.computed=false;withProperty.shorthand=false}else{this.unexpected(null,76)}this.expect(14);withProperty.value=this.tsParseImportTypeWithPropertyValue();node.properties=[this.finishObjectProperty(withProperty)];this.eat(12);this.expect(8);return this.finishNode(node,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){const node=this.startNode();const properties=[];this.expect(5);while(!this.match(8)){const type=this.state.type;if(tokenIsIdentifier(type)||type===134){properties.push(super.parsePropertyDefinition(null))}else{this.unexpected()}this.eat(12)}node.properties=properties;this.next();return this.finishNode(node,"ObjectExpression")}tsParseEntityName(flags){let entity;if(flags&1&&this.match(78)){if(flags&2){entity=this.parseIdentifier(true)}else{const node=this.startNode();this.next();entity=this.finishNode(node,"ThisExpression")}}else{entity=this.parseIdentifier(!!(flags&1))}while(this.eat(16)){const node=this.startNodeAtNode(entity);node.left=entity;node.right=this.parseIdentifier(!!(flags&1));entity=this.finishNode(node,"TSQualifiedName")}return entity}tsParseTypeReference(){const node=this.startNode();node.typeName=this.tsParseEntityName(1);if(!this.hasPrecedingLineBreak()&&this.match(47)){node.typeParameters=this.tsParseTypeArguments()}return this.finishNode(node,"TSTypeReference")}tsParseThisTypePredicate(lhs){this.next();const node=this.startNodeAtNode(lhs);node.parameterName=lhs;node.typeAnnotation=this.tsParseTypeAnnotation(false);node.asserts=false;return this.finishNode(node,"TSTypePredicate")}tsParseThisTypeNode(){const node=this.startNode();this.next();return this.finishNode(node,"TSThisType")}tsParseTypeQuery(){const node=this.startNode();this.expect(87);if(this.match(83)){node.exprName=this.tsParseImportType()}else{node.exprName=this.tsParseEntityName(1|2)}if(!this.hasPrecedingLineBreak()&&this.match(47)){node.typeParameters=this.tsParseTypeArguments()}return this.finishNode(node,"TSTypeQuery")}tsParseTypeParameter(parseModifiers){const node=this.startNode();parseModifiers(node);node.name=this.tsParseTypeParameterName();node.constraint=this.tsEatThenParseType(81);node.default=this.tsEatThenParseType(29);return this.finishNode(node,"TSTypeParameter")}tsTryParseTypeParameters(parseModifiers){if(this.match(47)){return this.tsParseTypeParameters(parseModifiers)}}tsParseTypeParameters(parseModifiers){const node=this.startNode();if(this.match(47)||this.match(143)){this.next()}else{this.unexpected()}const refTrailingCommaPos={value:-1};node.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,parseModifiers),false,true,refTrailingCommaPos);if(node.params.length===0){this.raise(TSErrors.EmptyTypeParameters,node)}if(refTrailingCommaPos.value!==-1){this.addExtra(node,"trailingComma",refTrailingCommaPos.value)}return this.finishNode(node,"TSTypeParameterDeclaration")}tsFillSignature(returnToken,signature){const returnTokenRequired=returnToken===19;const paramsKey="parameters";const returnTypeKey="typeAnnotation";signature.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier);this.expect(10);signature[paramsKey]=this.tsParseBindingListForSignature();if(returnTokenRequired){signature[returnTypeKey]=this.tsParseTypeOrTypePredicateAnnotation(returnToken)}else if(this.match(returnToken)){signature[returnTypeKey]=this.tsParseTypeOrTypePredicateAnnotation(returnToken)}}tsParseBindingListForSignature(){const list=super.parseBindingList(11,41,2);for(const pattern of list){const{type}=pattern;if(type==="AssignmentPattern"||type==="TSParameterProperty"){this.raise(TSErrors.UnsupportedSignatureParameterKind,pattern,{type})}}return list}tsParseTypeMemberSemicolon(){if(!this.eat(12)&&!this.isLineTerminator()){this.expect(13)}}tsParseSignatureMember(kind,node){this.tsFillSignature(14,node);this.tsParseTypeMemberSemicolon();return this.finishNode(node,kind)}tsIsUnambiguouslyIndexSignature(){this.next();if(tokenIsIdentifier(this.state.type)){this.next();return this.match(14)}return false}tsTryParseIndexSignature(node){if(!(this.match(0)&&this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))){return}this.expect(0);const id=this.parseIdentifier();id.typeAnnotation=this.tsParseTypeAnnotation();this.resetEndLocation(id);this.expect(3);node.parameters=[id];const type=this.tsTryParseTypeAnnotation();if(type)node.typeAnnotation=type;this.tsParseTypeMemberSemicolon();return this.finishNode(node,"TSIndexSignature")}tsParsePropertyOrMethodSignature(node,readonly2){if(this.eat(17))node.optional=true;if(this.match(10)||this.match(47)){if(readonly2){this.raise(TSErrors.ReadonlyForMethodSignature,node)}const method=node;if(method.kind&&this.match(47)){this.raise(TSErrors.AccessorCannotHaveTypeParameters,this.state.curPosition())}this.tsFillSignature(14,method);this.tsParseTypeMemberSemicolon();const paramsKey="parameters";const returnTypeKey="typeAnnotation";if(method.kind==="get"){if(method[paramsKey].length>0){this.raise(Errors.BadGetterArity,this.state.curPosition());if(this.isThisParam(method[paramsKey][0])){this.raise(TSErrors.AccessorCannotDeclareThisParameter,this.state.curPosition())}}}else if(method.kind==="set"){if(method[paramsKey].length!==1){this.raise(Errors.BadSetterArity,this.state.curPosition())}else{const firstParameter=method[paramsKey][0];if(this.isThisParam(firstParameter)){this.raise(TSErrors.AccessorCannotDeclareThisParameter,this.state.curPosition())}if(firstParameter.type==="Identifier"&&firstParameter.optional){this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter,this.state.curPosition())}if(firstParameter.type==="RestElement"){this.raise(TSErrors.SetAccessorCannotHaveRestParameter,this.state.curPosition())}}if(method[returnTypeKey]){this.raise(TSErrors.SetAccessorCannotHaveReturnType,method[returnTypeKey])}}else{method.kind="method"}return this.finishNode(method,"TSMethodSignature")}else{const property=node;if(readonly2)property.readonly=true;const type=this.tsTryParseTypeAnnotation();if(type)property.typeAnnotation=type;this.tsParseTypeMemberSemicolon();return this.finishNode(property,"TSPropertySignature")}}tsParseTypeMember(){const node=this.startNode();if(this.match(10)||this.match(47)){return this.tsParseSignatureMember("TSCallSignatureDeclaration",node)}if(this.match(77)){const id=this.startNode();this.next();if(this.match(10)||this.match(47)){return this.tsParseSignatureMember("TSConstructSignatureDeclaration",node)}else{node.key=this.createIdentifier(id,"new");return this.tsParsePropertyOrMethodSignature(node,false)}}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},node);const idx=this.tsTryParseIndexSignature(node);if(idx){return idx}super.parsePropertyName(node);if(!node.computed&&node.key.type==="Identifier"&&(node.key.name==="get"||node.key.name==="set")&&this.tsTokenCanFollowModifier()){node.kind=node.key.name;super.parsePropertyName(node);if(!this.match(10)&&!this.match(47)){this.unexpected(null,10)}}return this.tsParsePropertyOrMethodSignature(node,!!node.readonly)}tsParseTypeLiteral(){const node=this.startNode();node.members=this.tsParseObjectTypeMembers();return this.finishNode(node,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(5);const members=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));this.expect(8);return members}tsIsStartOfMappedType(){this.next();if(this.eat(53)){return this.isContextual(122)}if(this.isContextual(122)){this.next()}if(!this.match(0)){return false}this.next();if(!this.tsIsIdentifier()){return false}this.next();return this.match(58)}tsParseMappedType(){const node=this.startNode();this.expect(5);if(this.match(53)){node.readonly=this.state.value;this.next();this.expectContextual(122)}else if(this.eatContextual(122)){node.readonly=true}this.expect(0);const typeParameter=this.startNode();typeParameter.name=this.tsParseTypeParameterName();typeParameter.constraint=this.tsExpectThenParseType(58);node.typeParameter=this.finishNode(typeParameter,"TSTypeParameter");node.nameType=this.eatContextual(93)?this.tsParseType():null;this.expect(3);if(this.match(53)){node.optional=this.state.value;this.next();this.expect(17)}else if(this.eat(17)){node.optional=true}node.typeAnnotation=this.tsTryParseType();this.semicolon();this.expect(8);return this.finishNode(node,"TSMappedType")}tsParseTupleType(){const node=this.startNode();node.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),true,false);let seenOptionalElement=false;node.elementTypes.forEach(elementNode=>{const{type}=elementNode;if(seenOptionalElement&&type!=="TSRestType"&&type!=="TSOptionalType"&&!(type==="TSNamedTupleMember"&&elementNode.optional)){this.raise(TSErrors.OptionalTypeBeforeRequired,elementNode)}seenOptionalElement||(seenOptionalElement=type==="TSNamedTupleMember"&&elementNode.optional||type==="TSOptionalType")});return this.finishNode(node,"TSTupleType")}tsParseTupleElementType(){const restStartLoc=this.state.startLoc;const rest=this.eat(21);const{startLoc}=this.state;let labeled;let label;let optional2;let type;const isWord=tokenIsKeywordOrIdentifier(this.state.type);const chAfterWord=isWord?this.lookaheadCharCode():null;if(chAfterWord===58){labeled=true;optional2=false;label=this.parseIdentifier(true);this.expect(14);type=this.tsParseType()}else if(chAfterWord===63){optional2=true;const wordName=this.state.value;const typeOrLabel=this.tsParseNonArrayType();if(this.lookaheadCharCode()===58){labeled=true;label=this.createIdentifier(this.startNodeAt(startLoc),wordName);this.expect(17);this.expect(14);type=this.tsParseType()}else{labeled=false;type=typeOrLabel;this.expect(17)}}else{type=this.tsParseType();optional2=this.eat(17);labeled=this.eat(14)}if(labeled){let labeledNode;if(label){labeledNode=this.startNodeAt(startLoc);labeledNode.optional=optional2;labeledNode.label=label;labeledNode.elementType=type;if(this.eat(17)){labeledNode.optional=true;this.raise(TSErrors.TupleOptionalAfterType,this.state.lastTokStartLoc)}}else{labeledNode=this.startNodeAt(startLoc);labeledNode.optional=optional2;this.raise(TSErrors.InvalidTupleMemberLabel,type);labeledNode.label=type;labeledNode.elementType=this.tsParseType()}type=this.finishNode(labeledNode,"TSNamedTupleMember")}else if(optional2){const optionalTypeNode=this.startNodeAt(startLoc);optionalTypeNode.typeAnnotation=type;type=this.finishNode(optionalTypeNode,"TSOptionalType")}if(rest){const restNode=this.startNodeAt(restStartLoc);restNode.typeAnnotation=type;type=this.finishNode(restNode,"TSRestType")}return type}tsParseParenthesizedType(){const node=this.startNode();this.expect(10);node.typeAnnotation=this.tsParseType();this.expect(11);return this.finishNode(node,"TSParenthesizedType")}tsParseFunctionOrConstructorType(type,abstract){const node=this.startNode();if(type==="TSConstructorType"){node.abstract=!!abstract;if(abstract)this.next();this.next()}this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,node));return this.finishNode(node,type)}tsParseLiteralTypeNode(){const node=this.startNode();switch(this.state.type){case 135:case 136:case 134:case 85:case 86:node.literal=super.parseExprAtom();break;default:this.unexpected()}return this.finishNode(node,"TSLiteralType")}tsParseTemplateLiteralType(){const node=this.startNode();node.literal=super.parseTemplate(false);return this.finishNode(node,"TSLiteralType")}parseTemplateSubstitution(){if(this.state.inType)return this.tsParseType();return super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){const thisKeyword=this.tsParseThisTypeNode();if(this.isContextual(116)&&!this.hasPrecedingLineBreak()){return this.tsParseThisTypePredicate(thisKeyword)}else{return thisKeyword}}tsParseNonArrayType(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if(this.state.value==="-"){const node=this.startNode();const nextToken=this.lookahead();if(nextToken.type!==135&&nextToken.type!==136){this.unexpected()}node.literal=this.parseMaybeUnary();return this.finishNode(node,"TSLiteralType")}break;case 78:return this.tsParseThisTypeOrThisTypePredicate();case 87:return this.tsParseTypeQuery();case 83:return this.tsParseImportType();case 5:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 10:return this.tsParseParenthesizedType();case 25:case 24:return this.tsParseTemplateLiteralType();default:{const{type}=this.state;if(tokenIsIdentifier(type)||type===88||type===84){const nodeType=type===88?"TSVoidKeyword":type===84?"TSNullKeyword":keywordTypeFromName(this.state.value);if(nodeType!==void 0&&this.lookaheadCharCode()!==46){const node=this.startNode();this.next();return this.finishNode(node,nodeType)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){const{startLoc}=this.state;let type=this.tsParseNonArrayType();while(!this.hasPrecedingLineBreak()&&this.eat(0)){if(this.match(3)){const node=this.startNodeAt(startLoc);node.elementType=type;this.expect(3);type=this.finishNode(node,"TSArrayType")}else{const node=this.startNodeAt(startLoc);node.objectType=type;node.indexType=this.tsParseType();this.expect(3);type=this.finishNode(node,"TSIndexedAccessType")}}return type}tsParseTypeOperator(){const node=this.startNode();const operator=this.state.value;this.next();node.operator=operator;node.typeAnnotation=this.tsParseTypeOperatorOrHigher();if(operator==="readonly"){this.tsCheckTypeAnnotationForReadOnly(node)}return this.finishNode(node,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(node){switch(node.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(TSErrors.UnexpectedReadonly,node)}}tsParseInferType(){const node=this.startNode();this.expectContextual(115);const typeParameter=this.startNode();typeParameter.name=this.tsParseTypeParameterName();typeParameter.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType());node.typeParameter=this.finishNode(typeParameter,"TSTypeParameter");return this.finishNode(node,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(81)){const constraint=this.tsInDisallowConditionalTypesContext(()=>this.tsParseType());if(this.state.inDisallowConditionalTypesContext||!this.match(17)){return constraint}}}tsParseTypeOperatorOrHigher(){const isTypeOperator=tokenIsTSTypeOperator(this.state.type)&&!this.state.containsEsc;return isTypeOperator?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(kind,parseConstituentType,operator){const node=this.startNode();const hasLeadingOperator=this.eat(operator);const types2=[];do{types2.push(parseConstituentType())}while(this.eat(operator));if(types2.length===1&&!hasLeadingOperator){return types2[0]}node.types=types2;return this.finishNode(node,kind)}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),45)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),43)}tsIsStartOfFunctionType(){if(this.match(47)){return true}return this.match(10)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(tokenIsIdentifier(this.state.type)||this.match(78)){this.next();return true}if(this.match(5)){const{errors}=this.state;const previousErrorCount=errors.length;try{this.parseObjectLike(8,true);return errors.length===previousErrorCount}catch(_unused){return false}}if(this.match(0)){this.next();const{errors}=this.state;const previousErrorCount=errors.length;try{super.parseBindingList(3,93,1);return errors.length===previousErrorCount}catch(_unused2){return false}}return false}tsIsUnambiguouslyStartOfFunctionType(){this.next();if(this.match(11)||this.match(21)){return true}if(this.tsSkipParameterStart()){if(this.match(14)||this.match(12)||this.match(17)||this.match(29)){return true}if(this.match(11)){this.next();if(this.match(19)){return true}}}return false}tsParseTypeOrTypePredicateAnnotation(returnToken){return this.tsInType(()=>{const t=this.startNode();this.expect(returnToken);const node=this.startNode();const asserts=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(asserts&&this.match(78)){let thisTypePredicate=this.tsParseThisTypeOrThisTypePredicate();if(thisTypePredicate.type==="TSThisType"){node.parameterName=thisTypePredicate;node.asserts=true;node.typeAnnotation=null;thisTypePredicate=this.finishNode(node,"TSTypePredicate")}else{this.resetStartLocationFromNode(thisTypePredicate,node);thisTypePredicate.asserts=true}t.typeAnnotation=thisTypePredicate;return this.finishNode(t,"TSTypeAnnotation")}const typePredicateVariable=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!typePredicateVariable){if(!asserts){return this.tsParseTypeAnnotation(false,t)}node.parameterName=this.parseIdentifier();node.asserts=asserts;node.typeAnnotation=null;t.typeAnnotation=this.finishNode(node,"TSTypePredicate");return this.finishNode(t,"TSTypeAnnotation")}const type=this.tsParseTypeAnnotation(false);node.parameterName=typePredicateVariable;node.typeAnnotation=type;node.asserts=asserts;t.typeAnnotation=this.finishNode(node,"TSTypePredicate");return this.finishNode(t,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){if(this.match(14)){return this.tsParseTypeOrTypePredicateAnnotation(14)}}tsTryParseTypeAnnotation(){if(this.match(14)){return this.tsParseTypeAnnotation()}}tsTryParseType(){return this.tsEatThenParseType(14)}tsParseTypePredicatePrefix(){const id=this.parseIdentifier();if(this.isContextual(116)&&!this.hasPrecedingLineBreak()){this.next();return id}}tsParseTypePredicateAsserts(){if(this.state.type!==109){return false}const containsEsc=this.state.containsEsc;this.next();if(!tokenIsIdentifier(this.state.type)&&!this.match(78)){return false}if(containsEsc){this.raise(Errors.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"})}return true}tsParseTypeAnnotation(eatColon=true,t=this.startNode()){this.tsInType(()=>{if(eatColon)this.expect(14);t.typeAnnotation=this.tsParseType()});return this.finishNode(t,"TSTypeAnnotation")}tsParseType(){assert2(this.state.inType);const type=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81)){return type}const node=this.startNodeAtNode(type);node.checkType=type;node.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType());this.expect(17);node.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType());this.expect(14);node.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType());return this.finishNode(node,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(124)&&this.isLookaheadContextual("new")}tsParseNonConditionalType(){if(this.tsIsStartOfFunctionType()){return this.tsParseFunctionOrConstructorType("TSFunctionType")}if(this.match(77)){return this.tsParseFunctionOrConstructorType("TSConstructorType")}else if(this.isAbstractConstructorSignature()){return this.tsParseFunctionOrConstructorType("TSConstructorType",true)}return this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){if(this.getPluginOption("typescript","disallowAmbiguousJSXLike")){this.raise(TSErrors.ReservedTypeAssertion,this.state.startLoc)}const node=this.startNode();node.typeAnnotation=this.tsInType(()=>{this.next();return this.match(75)?this.tsParseTypeReference():this.tsParseType()});this.expect(48);node.expression=this.parseMaybeUnary();return this.finishNode(node,"TSTypeAssertion")}tsParseHeritageClause(token2){const originalStartLoc=this.state.startLoc;const delimitedList=this.tsParseDelimitedList("HeritageClauseElement",()=>{const node=this.startNode();node.expression=this.tsParseEntityName(1|2);if(this.match(47)){node.typeParameters=this.tsParseTypeArguments()}return this.finishNode(node,"TSExpressionWithTypeArguments")});if(!delimitedList.length){this.raise(TSErrors.EmptyHeritageClauseType,originalStartLoc,{token:token2})}return delimitedList}tsParseInterfaceDeclaration(node,properties={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129);if(properties.declare)node.declare=true;if(tokenIsIdentifier(this.state.type)){node.id=this.parseIdentifier();this.checkIdentifier(node.id,130)}else{node.id=null;this.raise(TSErrors.MissingInterfaceName,this.state.startLoc)}node.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);if(this.eat(81)){node.extends=this.tsParseHeritageClause("extends")}const body=this.startNode();body.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this));node.body=this.finishNode(body,"TSInterfaceBody");return this.finishNode(node,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(node){node.id=this.parseIdentifier();this.checkIdentifier(node.id,2);node.typeAnnotation=this.tsInType(()=>{node.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutModifiers);this.expect(29);if(this.isContextual(114)&&this.lookaheadCharCode()!==46){const node2=this.startNode();this.next();return this.finishNode(node2,"TSIntrinsicKeyword")}return this.tsParseType()});this.semicolon();return this.finishNode(node,"TSTypeAliasDeclaration")}tsInTopLevelContext(cb){if(this.curContext()!==types.brace){const oldContext=this.state.context;this.state.context=[oldContext[0]];try{return cb()}finally{this.state.context=oldContext}}else{return cb()}}tsInType(cb){const oldInType=this.state.inType;this.state.inType=true;try{return cb()}finally{this.state.inType=oldInType}}tsInDisallowConditionalTypesContext(cb){const oldInDisallowConditionalTypesContext=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=true;try{return cb()}finally{this.state.inDisallowConditionalTypesContext=oldInDisallowConditionalTypesContext}}tsInAllowConditionalTypesContext(cb){const oldInDisallowConditionalTypesContext=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=false;try{return cb()}finally{this.state.inDisallowConditionalTypesContext=oldInDisallowConditionalTypesContext}}tsEatThenParseType(token2){if(this.match(token2)){return this.tsNextThenParseType()}}tsExpectThenParseType(token2){return this.tsInType(()=>{this.expect(token2);return this.tsParseType()})}tsNextThenParseType(){return this.tsInType(()=>{this.next();return this.tsParseType()})}tsParseEnumMember(){const node=this.startNode();node.id=this.match(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(true);if(this.eat(29)){node.initializer=super.parseMaybeAssignAllowIn()}return this.finishNode(node,"TSEnumMember")}tsParseEnumDeclaration(node,properties={}){if(properties.const)node.const=true;if(properties.declare)node.declare=true;this.expectContextual(126);node.id=this.parseIdentifier();this.checkIdentifier(node.id,node.const?8971:8459);this.expect(5);node.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this));this.expect(8);return this.finishNode(node,"TSEnumDeclaration")}tsParseEnumBody(){const node=this.startNode();this.expect(5);node.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this));this.expect(8);return this.finishNode(node,"TSEnumBody")}tsParseModuleBlock(){const node=this.startNode();this.scope.enter(0);this.expect(5);super.parseBlockOrModuleBlockBody(node.body=[],void 0,true,8);this.scope.exit();return this.finishNode(node,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(node,nested=false){node.id=this.parseIdentifier();if(!nested){this.checkIdentifier(node.id,1024)}if(this.eat(16)){const inner=this.startNode();this.tsParseModuleOrNamespaceDeclaration(inner,true);node.body=inner}else{this.scope.enter(1024);this.prodParam.enter(0);node.body=this.tsParseModuleBlock();this.prodParam.exit();this.scope.exit()}return this.finishNode(node,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(node){if(this.isContextual(112)){node.kind="global";node.global=true;node.id=this.parseIdentifier()}else if(this.match(134)){node.kind="module";node.id=super.parseStringLiteral(this.state.value)}else{this.unexpected()}if(this.match(5)){this.scope.enter(1024);this.prodParam.enter(0);node.body=this.tsParseModuleBlock();this.prodParam.exit();this.scope.exit()}else{this.semicolon()}return this.finishNode(node,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(node,maybeDefaultIdentifier,isExport){node.isExport=isExport||false;node.id=maybeDefaultIdentifier||this.parseIdentifier();this.checkIdentifier(node.id,4096);this.expect(29);const moduleReference=this.tsParseModuleReference();if(node.importKind==="type"&&moduleReference.type!=="TSExternalModuleReference"){this.raise(TSErrors.ImportAliasHasImportType,moduleReference)}node.moduleReference=moduleReference;this.semicolon();return this.finishNode(node,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){const node=this.startNode();this.expectContextual(119);this.expect(10);if(!this.match(134)){this.unexpected()}node.expression=super.parseExprAtom();this.expect(11);this.sawUnambiguousESM=true;return this.finishNode(node,"TSExternalModuleReference")}tsLookAhead(f){const state=this.state.clone();const res=f();this.state=state;return res}tsTryParseAndCatch(f){const result2=this.tryParse(abort=>f()||abort());if(result2.aborted||!result2.node)return;if(result2.error)this.state=result2.failState;return result2.node}tsTryParse(f){const state=this.state.clone();const result2=f();if(result2!==void 0&&result2!==false){return result2}this.state=state}tsTryParseDeclare(node){if(this.isLineTerminator()){return}const startType=this.state.type;return this.tsInAmbientContext(()=>{switch(startType){case 68:node.declare=true;return super.parseFunctionStatement(node,false,false);case 80:node.declare=true;return this.parseClass(node,true,false);case 126:return this.tsParseEnumDeclaration(node,{declare:true});case 112:return this.tsParseAmbientExternalModuleDeclaration(node);case 100:if(this.state.containsEsc){return}case 75:case 74:if(!this.match(75)||!this.isLookaheadContextual("enum")){node.declare=true;return this.parseVarStatement(node,this.state.value,true)}this.expect(75);return this.tsParseEnumDeclaration(node,{const:true,declare:true});case 107:if(this.isUsing()){this.raise(TSErrors.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare");node.declare=true;return this.parseVarStatement(node,"using",true)}break;case 96:if(this.isAwaitUsing()){this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare");node.declare=true;this.next();return this.parseVarStatement(node,"await using",true)}break;case 129:{const result2=this.tsParseInterfaceDeclaration(node,{declare:true});if(result2)return result2}default:if(tokenIsIdentifier(startType)){return this.tsParseDeclaration(node,this.state.type,true,null)}}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,true,null)}tsParseDeclaration(node,type,next,decorators){switch(type){case 124:if(this.tsCheckLineTerminator(next)&&(this.match(80)||tokenIsIdentifier(this.state.type))){return this.tsParseAbstractDeclaration(node,decorators)}break;case 127:if(this.tsCheckLineTerminator(next)){if(this.match(134)){return this.tsParseAmbientExternalModuleDeclaration(node)}else if(tokenIsIdentifier(this.state.type)){node.kind="module";return this.tsParseModuleOrNamespaceDeclaration(node)}}break;case 128:if(this.tsCheckLineTerminator(next)&&tokenIsIdentifier(this.state.type)){node.kind="namespace";return this.tsParseModuleOrNamespaceDeclaration(node)}break;case 130:if(this.tsCheckLineTerminator(next)&&tokenIsIdentifier(this.state.type)){return this.tsParseTypeAliasDeclaration(node)}break}}tsCheckLineTerminator(next){if(next){if(this.hasFollowingLineBreak())return false;this.next();return true}return!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(startLoc){if(!this.match(47))return;const oldMaybeInArrowParameters=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=true;const res=this.tsTryParseAndCatch(()=>{const node=this.startNodeAt(startLoc);node.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier);super.parseFunctionParams(node);node.returnType=this.tsTryParseTypeOrTypePredicateAnnotation();this.expect(19);return node});this.state.maybeInArrowParameters=oldMaybeInArrowParameters;if(!res)return;return super.parseArrowExpression(res,null,true)}tsParseTypeArgumentsInExpression(){if(this.reScan_lt()!==47)return;return this.tsParseTypeArguments()}tsParseTypeArguments(){const node=this.startNode();node.params=this.tsInType(()=>this.tsInTopLevelContext(()=>{this.expect(47);return this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))}));if(node.params.length===0){this.raise(TSErrors.EmptyTypeArguments,node)}else if(!this.state.inType&&this.curContext()===types.brace){this.reScan_lt_gt()}this.expect(48);return this.finishNode(node,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return tokenIsTSDeclarationStart(this.state.type)}isExportDefaultSpecifier(){if(this.tsIsDeclarationStart())return false;return super.isExportDefaultSpecifier()}parseBindingElement(flags,decorators){const startLoc=decorators.length?decorators[0].loc.start:this.state.startLoc;const modified={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},modified);const accessibility=modified.accessibility;const override=modified.override;const readonly2=modified.readonly;if(!(flags&4)&&(accessibility||readonly2||override)){this.raise(TSErrors.UnexpectedParameterModifier,startLoc)}const left=this.parseMaybeDefault();if(flags&2){this.parseFunctionParamType(left)}const elt=this.parseMaybeDefault(left.loc.start,left);if(accessibility||readonly2||override){const pp=this.startNodeAt(startLoc);if(decorators.length){pp.decorators=decorators}if(accessibility)pp.accessibility=accessibility;if(readonly2)pp.readonly=readonly2;if(override)pp.override=override;if(elt.type!=="Identifier"&&elt.type!=="AssignmentPattern"){this.raise(TSErrors.UnsupportedParameterPropertyKind,pp)}pp.parameter=elt;return this.finishNode(pp,"TSParameterProperty")}if(decorators.length){left.decorators=decorators}return elt}isSimpleParameter(node){return node.type==="TSParameterProperty"&&super.isSimpleParameter(node.parameter)||super.isSimpleParameter(node)}tsDisallowOptionalPattern(node){for(const param of node.params){if(param.type!=="Identifier"&&param.optional&&!this.state.isAmbientContext){this.raise(TSErrors.PatternIsOptional,param)}}}setArrowFunctionParameters(node,params,trailingCommaLoc){super.setArrowFunctionParameters(node,params,trailingCommaLoc);this.tsDisallowOptionalPattern(node)}parseFunctionBodyAndFinish(node,type,isMethod=false){if(this.match(14)){node.returnType=this.tsParseTypeOrTypePredicateAnnotation(14)}const bodilessType=type==="FunctionDeclaration"?"TSDeclareFunction":type==="ClassMethod"||type==="ClassPrivateMethod"?"TSDeclareMethod":void 0;if(bodilessType&&!this.match(5)&&this.isLineTerminator()){return this.finishNode(node,bodilessType)}if(bodilessType==="TSDeclareFunction"&&this.state.isAmbientContext){this.raise(TSErrors.DeclareFunctionHasImplementation,node);if(node.declare){return super.parseFunctionBodyAndFinish(node,bodilessType,isMethod)}}this.tsDisallowOptionalPattern(node);return super.parseFunctionBodyAndFinish(node,type,isMethod)}registerFunctionStatementId(node){if(!node.body&&node.id){this.checkIdentifier(node.id,1024)}else{super.registerFunctionStatementId(node)}}tsCheckForInvalidTypeCasts(items){items.forEach(node=>{if((node==null?void 0:node.type)==="TSTypeCastExpression"){this.raise(TSErrors.UnexpectedTypeAnnotation,node.typeAnnotation)}})}toReferencedList(exprList,isInParens){this.tsCheckForInvalidTypeCasts(exprList);return exprList}parseArrayLike(close,isTuple,refExpressionErrors){const node=super.parseArrayLike(close,isTuple,refExpressionErrors);if(node.type==="ArrayExpression"){this.tsCheckForInvalidTypeCasts(node.elements)}return node}parseSubscript(base,startLoc,noCalls,state){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=false;this.next();const nonNullExpression=this.startNodeAt(startLoc);nonNullExpression.expression=base;return this.finishNode(nonNullExpression,"TSNonNullExpression")}let isOptionalCall=false;if(this.match(18)&&this.lookaheadCharCode()===60){if(noCalls){state.stop=true;return base}state.optionalChainMember=isOptionalCall=true;this.next()}if(this.match(47)||this.match(51)){let missingParenErrorLoc;const result2=this.tsTryParseAndCatch(()=>{if(!noCalls&&this.atPossibleAsyncArrow(base)){const asyncArrowFn=this.tsTryParseGenericAsyncArrowFunction(startLoc);if(asyncArrowFn){state.stop=true;return asyncArrowFn}}const typeArguments=this.tsParseTypeArgumentsInExpression();if(!typeArguments)return;if(isOptionalCall&&!this.match(10)){missingParenErrorLoc=this.state.curPosition();return}if(tokenIsTemplate(this.state.type)){const result3=super.parseTaggedTemplateExpression(base,startLoc,state);result3.typeParameters=typeArguments;return result3}if(!noCalls&&this.eat(10)){const node2=this.startNodeAt(startLoc);node2.callee=base;node2.arguments=this.parseCallExpressionArguments();this.tsCheckForInvalidTypeCasts(node2.arguments);node2.typeParameters=typeArguments;if(state.optionalChainMember){node2.optional=isOptionalCall}return this.finishCallExpression(node2,state.optionalChainMember)}const tokenType=this.state.type;if(tokenType===48||tokenType===52||tokenType!==10&&tokenType!==93&&tokenType!==120&&tokenCanStartExpression(tokenType)&&!this.hasPrecedingLineBreak()){return}const node=this.startNodeAt(startLoc);node.expression=base;node.typeParameters=typeArguments;return this.finishNode(node,"TSInstantiationExpression")});if(missingParenErrorLoc){this.unexpected(missingParenErrorLoc,10)}if(result2){if(result2.type==="TSInstantiationExpression"){if(this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40){this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc)}if(!this.match(16)&&!this.match(18)){result2.expression=super.stopParseSubscript(base,state)}}return result2}}return super.parseSubscript(base,startLoc,noCalls,state)}parseNewCallee(node){var _callee$extra;super.parseNewCallee(node);const{callee}=node;if(callee.type==="TSInstantiationExpression"&&!((_callee$extra=callee.extra)!=null&&_callee$extra.parenthesized)){node.typeParameters=callee.typeParameters;node.callee=callee.expression}}parseExprOp(left,leftStartLoc,minPrec){let isSatisfies;if(tokenOperatorPrecedence(58)>minPrec&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(isSatisfies=this.isContextual(120)))){const node=this.startNodeAt(leftStartLoc);node.expression=left;node.typeAnnotation=this.tsInType(()=>{this.next();if(this.match(75)){if(isSatisfies){this.raise(Errors.UnexpectedKeyword,this.state.startLoc,{keyword:"const"})}return this.tsParseTypeReference()}return this.tsParseType()});this.finishNode(node,isSatisfies?"TSSatisfiesExpression":"TSAsExpression");this.reScan_lt_gt();return this.parseExprOp(node,leftStartLoc,minPrec)}return super.parseExprOp(left,leftStartLoc,minPrec)}checkReservedWord(word,startLoc,checkKeywords,isBinding){if(!this.state.isAmbientContext){super.checkReservedWord(word,startLoc,checkKeywords,isBinding)}}checkImportReflection(node){super.checkImportReflection(node);if(node.module&&node.importKind!=="value"){this.raise(TSErrors.ImportReflectionHasImportType,node.specifiers[0].loc.start)}}checkDuplicateExports(){}isPotentialImportPhase(isExport){if(super.isPotentialImportPhase(isExport))return true;if(this.isContextual(130)){const ch=this.lookaheadCharCode();return isExport?ch===123||ch===42:ch!==61}return!isExport&&this.isContextual(87)}applyImportPhase(node,isExport,phase2,loc){super.applyImportPhase(node,isExport,phase2,loc);if(isExport){node.exportKind=phase2==="type"?"type":"value"}else{node.importKind=phase2==="type"||phase2==="typeof"?phase2:"value"}}parseImport(node){if(this.match(134)){node.importKind="value";return super.parseImport(node)}let importNode;if(tokenIsIdentifier(this.state.type)&&this.lookaheadCharCode()===61){node.importKind="value";return this.tsParseImportEqualsDeclaration(node)}else if(this.isContextual(130)){const maybeDefaultIdentifier=this.parseMaybeImportPhase(node,false);if(this.lookaheadCharCode()===61){return this.tsParseImportEqualsDeclaration(node,maybeDefaultIdentifier)}else{importNode=super.parseImportSpecifiersAndAfter(node,maybeDefaultIdentifier)}}else{importNode=super.parseImport(node)}if(importNode.importKind==="type"&&importNode.specifiers.length>1&&importNode.specifiers[0].type==="ImportDefaultSpecifier"){this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed,importNode)}return importNode}parseExport(node,decorators){if(this.match(83)){const nodeImportEquals=node;this.next();let maybeDefaultIdentifier=null;if(this.isContextual(130)&&this.isPotentialImportPhase(false)){maybeDefaultIdentifier=this.parseMaybeImportPhase(nodeImportEquals,false)}else{nodeImportEquals.importKind="value"}const declaration=this.tsParseImportEqualsDeclaration(nodeImportEquals,maybeDefaultIdentifier,true);return declaration}else if(this.eat(29)){const assign=node;assign.expression=super.parseExpression();this.semicolon();this.sawUnambiguousESM=true;return this.finishNode(assign,"TSExportAssignment")}else if(this.eatContextual(93)){const decl=node;this.expectContextual(128);decl.id=this.parseIdentifier();this.semicolon();return this.finishNode(decl,"TSNamespaceExportDeclaration")}else{return super.parseExport(node,decorators)}}isAbstractClass(){return this.isContextual(124)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){const cls=this.startNode();this.next();cls.abstract=true;return this.parseClass(cls,true,true)}if(this.match(129)){const result2=this.tsParseInterfaceDeclaration(this.startNode());if(result2)return result2}return super.parseExportDefaultExpression()}parseVarStatement(node,kind,allowMissingInitializer=false){const{isAmbientContext}=this.state;const declaration=super.parseVarStatement(node,kind,allowMissingInitializer||isAmbientContext);if(!isAmbientContext)return declaration;if(!node.declare&&(kind==="using"||kind==="await using")){this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext,node,kind);return declaration}for(const{id,init}of declaration.declarations){if(!init)continue;if(kind==="var"||kind==="let"||!!id.typeAnnotation){this.raise(TSErrors.InitializerNotAllowedInAmbientContext,init)}else if(!isValidAmbientConstInitializer(init,this.hasPlugin("estree"))){this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,init)}}return declaration}parseStatementContent(flags,decorators){if(!this.state.containsEsc){switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){const node=this.startNode();this.expect(75);return this.tsParseEnumDeclaration(node,{const:true})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){const token2=this.state.type;const node=this.startNode();this.next();const declaration=token2===125?this.tsTryParseDeclare(node):this.tsParseAbstractDeclaration(node,decorators);if(declaration){if(token2===125){declaration.declare=true}return declaration}else{node.expression=this.createIdentifier(this.startNodeAt(node.loc.start),token2===125?"declare":"abstract");this.semicolon(false);return this.finishNode(node,"ExpressionStatement")}}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{const nextCh=this.lookaheadCharCode();if(nextCh===123){const node=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(node)}break}case 129:{const result2=this.tsParseInterfaceDeclaration(this.startNode());if(result2)return result2;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){const node=this.startNode();this.next();return this.tsParseDeclaration(node,127,false,decorators)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){const node=this.startNode();this.next();return this.tsParseDeclaration(node,128,false,decorators)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){const node=this.startNode();this.next();return this.tsParseTypeAliasDeclaration(node)}break}}}return super.parseStatementContent(flags,decorators)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(member,modifiers){return modifiers.some(modifier=>{if(tsIsAccessModifier(modifier)){return member.accessibility===modifier}return!!member[modifier]})}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(classBody,member,state){const modifiers=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:modifiers,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:true,errorTemplate:TSErrors.InvalidModifierOnTypeParameterPositions},member);const callParseClassMemberWithIsStatic=()=>{if(this.tsIsStartOfStaticBlocks()){this.next();this.next();if(this.tsHasSomeModifiers(member,modifiers)){this.raise(TSErrors.StaticBlockCannotHaveModifier,this.state.curPosition())}super.parseClassStaticBlock(classBody,member)}else{this.parseClassMemberWithIsStatic(classBody,member,state,!!member.static)}};if(member.declare){this.tsInAmbientContext(callParseClassMemberWithIsStatic)}else{callParseClassMemberWithIsStatic()}}parseClassMemberWithIsStatic(classBody,member,state,isStatic){const idx=this.tsTryParseIndexSignature(member);if(idx){classBody.body.push(idx);if(member.abstract){this.raise(TSErrors.IndexSignatureHasAbstract,member)}if(member.accessibility){this.raise(TSErrors.IndexSignatureHasAccessibility,member,{modifier:member.accessibility})}if(member.declare){this.raise(TSErrors.IndexSignatureHasDeclare,member)}if(member.override){this.raise(TSErrors.IndexSignatureHasOverride,member)}return}if(!this.state.inAbstractClass&&member.abstract){this.raise(TSErrors.NonAbstractClassHasAbstractMethod,member)}if(member.override){if(!state.hadSuperClass){this.raise(TSErrors.OverrideNotInSubClass,member)}}super.parseClassMemberWithIsStatic(classBody,member,state,isStatic)}parsePostMemberNameModifiers(methodOrProp){const optional2=this.eat(17);if(optional2)methodOrProp.optional=true;if(methodOrProp.readonly&&this.match(10)){this.raise(TSErrors.ClassMethodHasReadonly,methodOrProp)}if(methodOrProp.declare&&this.match(10)){this.raise(TSErrors.ClassMethodHasDeclare,methodOrProp)}}shouldParseExportDeclaration(){if(this.tsIsDeclarationStart())return true;return super.shouldParseExportDeclaration()}parseConditional(expr,startLoc,refExpressionErrors){if(!this.match(17))return expr;if(this.state.maybeInArrowParameters){const nextCh=this.lookaheadCharCode();if(nextCh===44||nextCh===61||nextCh===58||nextCh===41){this.setOptionalParametersError(refExpressionErrors);return expr}}return super.parseConditional(expr,startLoc,refExpressionErrors)}parseParenItem(node,startLoc){const newNode=super.parseParenItem(node,startLoc);if(this.eat(17)){newNode.optional=true;this.resetEndLocation(node)}if(this.match(14)){const typeCastNode=this.startNodeAt(startLoc);typeCastNode.expression=node;typeCastNode.typeAnnotation=this.tsParseTypeAnnotation();return this.finishNode(typeCastNode,"TSTypeCastExpression")}return node}parseExportDeclaration(node){if(!this.state.isAmbientContext&&this.isContextual(125)){return this.tsInAmbientContext(()=>this.parseExportDeclaration(node))}const startLoc=this.state.startLoc;const isDeclare=this.eatContextual(125);if(isDeclare&&(this.isContextual(125)||!this.shouldParseExportDeclaration())){throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare,this.state.startLoc)}const isIdentifier=tokenIsIdentifier(this.state.type);const declaration=isIdentifier&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(node);if(!declaration)return null;if(declaration.type==="TSInterfaceDeclaration"||declaration.type==="TSTypeAliasDeclaration"||isDeclare){node.exportKind="type"}if(isDeclare&&declaration.type!=="TSImportEqualsDeclaration"){this.resetStartLocation(declaration,startLoc);declaration.declare=true}return declaration}parseClassId(node,isStatement,optionalId,bindingType){if((!isStatement||optionalId)&&this.isContextual(113)){return}super.parseClassId(node,isStatement,optionalId,node.declare?1024:8331);const typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);if(typeParameters)node.typeParameters=typeParameters}parseClassPropertyAnnotation(node){if(!node.optional){if(this.eat(35)){node.definite=true}else if(this.eat(17)){node.optional=true}}const type=this.tsTryParseTypeAnnotation();if(type)node.typeAnnotation=type}parseClassProperty(node){this.parseClassPropertyAnnotation(node);if(this.state.isAmbientContext&&!(node.readonly&&!node.typeAnnotation)&&this.match(29)){this.raise(TSErrors.DeclareClassFieldHasInitializer,this.state.startLoc)}if(node.abstract&&this.match(29)){const{key}=node;this.raise(TSErrors.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:key.type==="Identifier"&&!node.computed?key.name:`[${this.input.slice(this.offsetToSourcePos(key.start),this.offsetToSourcePos(key.end))}]`})}return super.parseClassProperty(node)}parseClassPrivateProperty(node){if(node.abstract){this.raise(TSErrors.PrivateElementHasAbstract,node)}if(node.accessibility){this.raise(TSErrors.PrivateElementHasAccessibility,node,{modifier:node.accessibility})}this.parseClassPropertyAnnotation(node);return super.parseClassPrivateProperty(node)}parseClassAccessorProperty(node){this.parseClassPropertyAnnotation(node);if(node.optional){this.raise(TSErrors.AccessorCannotBeOptional,node)}return super.parseClassAccessorProperty(node)}pushClassMethod(classBody,method,isGenerator,isAsync,isConstructor,allowsDirectSuper){const typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier);if(typeParameters&&isConstructor){this.raise(TSErrors.ConstructorHasTypeParameters,typeParameters)}const{declare=false,kind}=method;if(declare&&(kind==="get"||kind==="set")){this.raise(TSErrors.DeclareAccessor,method,{kind})}if(typeParameters)method.typeParameters=typeParameters;super.pushClassMethod(classBody,method,isGenerator,isAsync,isConstructor,allowsDirectSuper)}pushClassPrivateMethod(classBody,method,isGenerator,isAsync){const typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier);if(typeParameters)method.typeParameters=typeParameters;super.pushClassPrivateMethod(classBody,method,isGenerator,isAsync)}declareClassPrivateMethodInScope(node,kind){if(node.type==="TSDeclareMethod")return;if(node.type==="MethodDefinition"&&node.value.body==null){return}super.declareClassPrivateMethodInScope(node,kind)}parseClassSuper(node){super.parseClassSuper(node);if(node.superClass){if(node.superClass.type==="TSInstantiationExpression"){const tsInstantiationExpression=node.superClass;const superClass2=tsInstantiationExpression.expression;this.takeSurroundingComments(superClass2,superClass2.start,superClass2.end);const superTypeArguments=tsInstantiationExpression.typeParameters;this.takeSurroundingComments(superTypeArguments,superTypeArguments.start,superTypeArguments.end);node.superClass=superClass2;node.superTypeParameters=superTypeArguments}else if(this.match(47)||this.match(51)){node.superTypeParameters=this.tsParseTypeArgumentsInExpression()}}if(this.eatContextual(113)){node.implements=this.tsParseHeritageClause("implements")}}parseObjPropValue(prop,startLoc,isGenerator,isAsync,isPattern,isAccessor,refExpressionErrors){const typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier);if(typeParameters)prop.typeParameters=typeParameters;return super.parseObjPropValue(prop,startLoc,isGenerator,isAsync,isPattern,isAccessor,refExpressionErrors)}parseFunctionParams(node,isConstructor){const typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier);if(typeParameters)node.typeParameters=typeParameters;super.parseFunctionParams(node,isConstructor)}parseVarId(decl,kind){super.parseVarId(decl,kind);if(decl.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)){decl.definite=true}const type=this.tsTryParseTypeAnnotation();if(type){decl.id.typeAnnotation=type;this.resetEndLocation(decl.id)}}parseAsyncArrowFromCallExpression(node,call){if(this.match(14)){node.returnType=this.tsParseTypeAnnotation()}return super.parseAsyncArrowFromCallExpression(node,call)}parseMaybeAssign(refExpressionErrors,afterLeftParse){var _jsx,_jsx2,_typeCast,_jsx3,_typeCast2;let state;let jsx2;let typeCast;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){state=this.state.clone();jsx2=this.tryParse(()=>super.parseMaybeAssign(refExpressionErrors,afterLeftParse),state);if(!jsx2.error)return jsx2.node;const{context}=this.state;const currentContext=context[context.length-1];if(currentContext===types.j_oTag||currentContext===types.j_expr){context.pop()}}if(!((_jsx=jsx2)!=null&&_jsx.error)&&!this.match(47)){return super.parseMaybeAssign(refExpressionErrors,afterLeftParse)}if(!state||state===this.state)state=this.state.clone();let typeParameters;const arrow=this.tryParse(abort=>{var _expr$extra,_typeParameters;typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier);const expr=super.parseMaybeAssign(refExpressionErrors,afterLeftParse);if(expr.type!=="ArrowFunctionExpression"||(_expr$extra=expr.extra)!=null&&_expr$extra.parenthesized){abort()}if(((_typeParameters=typeParameters)==null?void 0:_typeParameters.params.length)!==0){this.resetStartLocationFromNode(expr,typeParameters)}expr.typeParameters=typeParameters;return expr},state);if(!arrow.error&&!arrow.aborted){if(typeParameters)this.reportReservedArrowTypeParam(typeParameters);return arrow.node}if(!jsx2){assert2(!this.hasPlugin("jsx"));typeCast=this.tryParse(()=>super.parseMaybeAssign(refExpressionErrors,afterLeftParse),state);if(!typeCast.error)return typeCast.node}if((_jsx2=jsx2)!=null&&_jsx2.node){this.state=jsx2.failState;return jsx2.node}if(arrow.node){this.state=arrow.failState;if(typeParameters)this.reportReservedArrowTypeParam(typeParameters);return arrow.node}if((_typeCast=typeCast)!=null&&_typeCast.node){this.state=typeCast.failState;return typeCast.node}throw((_jsx3=jsx2)==null?void 0:_jsx3.error)||arrow.error||((_typeCast2=typeCast)==null?void 0:_typeCast2.error)}reportReservedArrowTypeParam(node){var _node$extra2;if(node.params.length===1&&!node.params[0].constraint&&!((_node$extra2=node.extra)!=null&&_node$extra2.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")){this.raise(TSErrors.ReservedArrowTypeParam,node)}}parseMaybeUnary(refExpressionErrors,sawUnary){if(!this.hasPlugin("jsx")&&this.match(47)){return this.tsParseTypeAssertion()}return super.parseMaybeUnary(refExpressionErrors,sawUnary)}parseArrow(node){if(this.match(14)){const result2=this.tryParse(abort=>{const returnType=this.tsParseTypeOrTypePredicateAnnotation(14);if(this.canInsertSemicolon()||!this.match(19))abort();return returnType});if(result2.aborted)return;if(!result2.thrown){if(result2.error)this.state=result2.failState;node.returnType=result2.node}}return super.parseArrow(node)}parseFunctionParamType(param){if(this.eat(17)){param.optional=true}const type=this.tsTryParseTypeAnnotation();if(type)param.typeAnnotation=type;this.resetEndLocation(param);return param}isAssignable(node,isBinding){switch(node.type){case"TSTypeCastExpression":return this.isAssignable(node.expression,isBinding);case"TSParameterProperty":return true;default:return super.isAssignable(node,isBinding)}}toAssignable(node,isLHS=false){switch(node.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(node,isLHS);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":if(isLHS){this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter,node)}else{this.raise(TSErrors.UnexpectedTypeCastInParameter,node)}this.toAssignable(node.expression,isLHS);break;case"AssignmentExpression":if(!isLHS&&node.left.type==="TSTypeCastExpression"){node.left=this.typeCastToParameter(node.left)}default:super.toAssignable(node,isLHS)}}toAssignableParenthesizedExpression(node,isLHS){switch(node.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(node.expression,isLHS);break;default:super.toAssignable(node,isLHS)}}checkToRestConversion(node,allowPattern){switch(node.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(node.expression,false);break;default:super.checkToRestConversion(node,allowPattern)}}isValidLVal(type,disallowCallExpression,isUnparenthesizedInAssign,binding){switch(type){case"TSTypeCastExpression":return true;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(binding!==64||!isUnparenthesizedInAssign)&&["expression",true];default:return super.isValidLVal(type,disallowCallExpression,isUnparenthesizedInAssign,binding)}}parseBindingAtom(){if(this.state.type===78){return this.parseIdentifier(true)}return super.parseBindingAtom()}parseMaybeDecoratorArguments(expr,startLoc){if(this.match(47)||this.match(51)){const typeArguments=this.tsParseTypeArgumentsInExpression();if(this.match(10)){const call=super.parseMaybeDecoratorArguments(expr,startLoc);call.typeParameters=typeArguments;return call}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(expr,startLoc)}checkCommaAfterRest(close){if(this.state.isAmbientContext&&this.match(12)&&this.lookaheadCharCode()===close){this.next();return false}return super.checkCommaAfterRest(close)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(35)||this.match(14)||super.isClassProperty()}parseMaybeDefault(startLoc,left){const node=super.parseMaybeDefault(startLoc,left);if(node.type==="AssignmentPattern"&&node.typeAnnotation&&node.right.start<node.typeAnnotation.start){this.raise(TSErrors.TypeAnnotationAfterAssign,node.typeAnnotation)}return node}getTokenFromCode(code2){if(this.state.inType){if(code2===62){this.finishOp(48,1);return}if(code2===60){this.finishOp(47,1);return}}super.getTokenFromCode(code2)}reScan_lt_gt(){const{type}=this.state;if(type===47){this.state.pos-=1;this.readToken_lt()}else if(type===48){this.state.pos-=1;this.readToken_gt()}}reScan_lt(){const{type}=this.state;if(type===51){this.state.pos-=2;this.finishOp(47,1);return 47}return type}toAssignableListItem(exprList,index,isLHS){const node=exprList[index];if(node.type==="TSTypeCastExpression"){exprList[index]=this.typeCastToParameter(node)}super.toAssignableListItem(exprList,index,isLHS)}typeCastToParameter(node){node.expression.typeAnnotation=node.typeAnnotation;this.resetEndLocation(node.expression,node.typeAnnotation.loc.end);return node.expression}shouldParseArrow(params){if(this.match(14)){return params.every(expr=>this.isAssignable(expr,true))}return super.shouldParseArrow(params)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(node){if(this.match(47)||this.match(51)){const typeArguments=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());if(typeArguments){node.typeParameters=typeArguments}}return super.jsxParseOpeningElementAfterName(node)}getGetterSetterExpectedParamCount(method){const baseCount=super.getGetterSetterExpectedParamCount(method);const params=this.getObjectOrClassMethodParams(method);const firstParam=params[0];const hasContextParam=firstParam&&this.isThisParam(firstParam);return hasContextParam?baseCount+1:baseCount}parseCatchClauseParam(){const param=super.parseCatchClauseParam();const type=this.tsTryParseTypeAnnotation();if(type){param.typeAnnotation=type;this.resetEndLocation(param)}return param}tsInAmbientContext(cb){const{isAmbientContext:oldIsAmbientContext,strict:oldStrict}=this.state;this.state.isAmbientContext=true;this.state.strict=false;try{return cb()}finally{this.state.isAmbientContext=oldIsAmbientContext;this.state.strict=oldStrict}}parseClass(node,isStatement,optionalId){const oldInAbstractClass=this.state.inAbstractClass;this.state.inAbstractClass=!!node.abstract;try{return super.parseClass(node,isStatement,optionalId)}finally{this.state.inAbstractClass=oldInAbstractClass}}tsParseAbstractDeclaration(node,decorators){if(this.match(80)){node.abstract=true;return this.maybeTakeDecorators(decorators,this.parseClass(node,true,false))}else if(this.isContextual(129)){if(!this.hasFollowingLineBreak()){node.abstract=true;this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier,node);return this.tsParseInterfaceDeclaration(node)}else{return null}}throw this.unexpected(null,80)}parseMethod(node,isGenerator,isAsync,isConstructor,allowDirectSuper,type,inClassScope){const method=super.parseMethod(node,isGenerator,isAsync,isConstructor,allowDirectSuper,type,inClassScope);if(method.abstract||method.type==="TSAbstractMethodDefinition"){const hasEstreePlugin=this.hasPlugin("estree");const methodFn=hasEstreePlugin?method.value:method;if(methodFn.body){const{key}=method;this.raise(TSErrors.AbstractMethodHasImplementation,method,{methodName:key.type==="Identifier"&&!method.computed?key.name:`[${this.input.slice(this.offsetToSourcePos(key.start),this.offsetToSourcePos(key.end))}]`})}}return method}tsParseTypeParameterName(){const typeName=this.parseIdentifier();return typeName.name}shouldParseAsAmbientContext(){return!!this.getPluginOption("typescript","dts")}parse(){if(this.shouldParseAsAmbientContext()){this.state.isAmbientContext=true}return super.parse()}getExpression(){if(this.shouldParseAsAmbientContext()){this.state.isAmbientContext=true}return super.getExpression()}parseExportSpecifier(node,isString2,isInTypeExport,isMaybeTypeOnly){if(!isString2&&isMaybeTypeOnly){this.parseTypeOnlyImportExportSpecifier(node,false,isInTypeExport);return this.finishNode(node,"ExportSpecifier")}node.exportKind="value";return super.parseExportSpecifier(node,isString2,isInTypeExport,isMaybeTypeOnly)}parseImportSpecifier(specifier,importedIsString,isInTypeOnlyImport,isMaybeTypeOnly,bindingType){if(!importedIsString&&isMaybeTypeOnly){this.parseTypeOnlyImportExportSpecifier(specifier,true,isInTypeOnlyImport);return this.finishNode(specifier,"ImportSpecifier")}specifier.importKind="value";return super.parseImportSpecifier(specifier,importedIsString,isInTypeOnlyImport,isMaybeTypeOnly,isInTypeOnlyImport?4098:4096)}parseTypeOnlyImportExportSpecifier(node,isImport,isInTypeOnlyImportExport){const leftOfAsKey=isImport?"imported":"local";const rightOfAsKey=isImport?"local":"exported";let leftOfAs=node[leftOfAsKey];let rightOfAs;let hasTypeSpecifier=false;let canParseAsKeyword=true;const loc=leftOfAs.loc.start;if(this.isContextual(93)){const firstAs=this.parseIdentifier();if(this.isContextual(93)){const secondAs=this.parseIdentifier();if(tokenIsKeywordOrIdentifier(this.state.type)){hasTypeSpecifier=true;leftOfAs=firstAs;rightOfAs=isImport?this.parseIdentifier():this.parseModuleExportName();canParseAsKeyword=false}else{rightOfAs=secondAs;canParseAsKeyword=false}}else if(tokenIsKeywordOrIdentifier(this.state.type)){canParseAsKeyword=false;rightOfAs=isImport?this.parseIdentifier():this.parseModuleExportName()}else{hasTypeSpecifier=true;leftOfAs=firstAs}}else if(tokenIsKeywordOrIdentifier(this.state.type)){hasTypeSpecifier=true;if(isImport){leftOfAs=this.parseIdentifier(true);if(!this.isContextual(93)){this.checkReservedWord(leftOfAs.name,leftOfAs.loc.start,true,true)}}else{leftOfAs=this.parseModuleExportName()}}if(hasTypeSpecifier&&isInTypeOnlyImportExport){this.raise(isImport?TSErrors.TypeModifierIsUsedInTypeImports:TSErrors.TypeModifierIsUsedInTypeExports,loc)}node[leftOfAsKey]=leftOfAs;node[rightOfAsKey]=rightOfAs;const kindKey=isImport?"importKind":"exportKind";node[kindKey]=hasTypeSpecifier?"type":"value";if(canParseAsKeyword&&this.eatContextual(93)){node[rightOfAsKey]=isImport?this.parseIdentifier():this.parseModuleExportName()}if(!node[rightOfAsKey]){node[rightOfAsKey]=this.cloneIdentifier(node[leftOfAsKey])}if(isImport){this.checkIdentifier(node[rightOfAsKey],hasTypeSpecifier?4098:4096)}}fillOptionalPropertiesForTSESLint(node){var _node$directive,_node$decorators,_node$optional,_node$typeAnnotation,_node$accessibility,_node$decorators2,_node$override,_node$readonly,_node$static,_node$declare,_node$returnType,_node$typeParameters,_node$optional2,_node$optional3,_node$accessibility2,_node$readonly2,_node$static2,_node$declare2,_node$definite,_node$readonly3,_node$typeAnnotation2,_node$accessibility3,_node$decorators3,_node$override2,_node$optional4,_node$id,_node$abstract,_node$declare3,_node$decorators4,_node$implements,_node$superTypeArgume,_node$typeParameters2,_node$declare4,_node$definite2,_node$const,_node$declare5,_node$computed,_node$qualifier,_node$options,_node$declare6,_node$extends,_node$optional5,_node$readonly4,_node$declare7,_node$global,_node$const2,_node$in,_node$out;switch(node.type){case"ExpressionStatement":(_node$directive=node.directive)!=null?_node$directive:node.directive=void 0;return;case"RestElement":node.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(_node$decorators=node.decorators)!=null?_node$decorators:node.decorators=[];(_node$optional=node.optional)!=null?_node$optional:node.optional=false;(_node$typeAnnotation=node.typeAnnotation)!=null?_node$typeAnnotation:node.typeAnnotation=void 0;return;case"TSParameterProperty":(_node$accessibility=node.accessibility)!=null?_node$accessibility:node.accessibility=void 0;(_node$decorators2=node.decorators)!=null?_node$decorators2:node.decorators=[];(_node$override=node.override)!=null?_node$override:node.override=false;(_node$readonly=node.readonly)!=null?_node$readonly:node.readonly=false;(_node$static=node.static)!=null?_node$static:node.static=false;return;case"TSEmptyBodyFunctionExpression":node.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":(_node$declare=node.declare)!=null?_node$declare:node.declare=false;(_node$returnType=node.returnType)!=null?_node$returnType:node.returnType=void 0;(_node$typeParameters=node.typeParameters)!=null?_node$typeParameters:node.typeParameters=void 0;return;case"Property":(_node$optional2=node.optional)!=null?_node$optional2:node.optional=false;return;case"TSMethodSignature":case"TSPropertySignature":(_node$optional3=node.optional)!=null?_node$optional3:node.optional=false;case"TSIndexSignature":(_node$accessibility2=node.accessibility)!=null?_node$accessibility2:node.accessibility=void 0;(_node$readonly2=node.readonly)!=null?_node$readonly2:node.readonly=false;(_node$static2=node.static)!=null?_node$static2:node.static=false;return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(_node$declare2=node.declare)!=null?_node$declare2:node.declare=false;(_node$definite=node.definite)!=null?_node$definite:node.definite=false;(_node$readonly3=node.readonly)!=null?_node$readonly3:node.readonly=false;(_node$typeAnnotation2=node.typeAnnotation)!=null?_node$typeAnnotation2:node.typeAnnotation=void 0;case"TSAbstractMethodDefinition":case"MethodDefinition":(_node$accessibility3=node.accessibility)!=null?_node$accessibility3:node.accessibility=void 0;(_node$decorators3=node.decorators)!=null?_node$decorators3:node.decorators=[];(_node$override2=node.override)!=null?_node$override2:node.override=false;(_node$optional4=node.optional)!=null?_node$optional4:node.optional=false;return;case"ClassExpression":(_node$id=node.id)!=null?_node$id:node.id=null;case"ClassDeclaration":(_node$abstract=node.abstract)!=null?_node$abstract:node.abstract=false;(_node$declare3=node.declare)!=null?_node$declare3:node.declare=false;(_node$decorators4=node.decorators)!=null?_node$decorators4:node.decorators=[];(_node$implements=node.implements)!=null?_node$implements:node.implements=[];(_node$superTypeArgume=node.superTypeArguments)!=null?_node$superTypeArgume:node.superTypeArguments=void 0;(_node$typeParameters2=node.typeParameters)!=null?_node$typeParameters2:node.typeParameters=void 0;return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(_node$declare4=node.declare)!=null?_node$declare4:node.declare=false;return;case"VariableDeclarator":(_node$definite2=node.definite)!=null?_node$definite2:node.definite=false;return;case"TSEnumDeclaration":(_node$const=node.const)!=null?_node$const:node.const=false;(_node$declare5=node.declare)!=null?_node$declare5:node.declare=false;return;case"TSEnumMember":(_node$computed=node.computed)!=null?_node$computed:node.computed=false;return;case"TSImportType":(_node$qualifier=node.qualifier)!=null?_node$qualifier:node.qualifier=null;(_node$options=node.options)!=null?_node$options:node.options=null;return;case"TSInterfaceDeclaration":(_node$declare6=node.declare)!=null?_node$declare6:node.declare=false;(_node$extends=node.extends)!=null?_node$extends:node.extends=[];return;case"TSMappedType":(_node$optional5=node.optional)!=null?_node$optional5:node.optional=false;(_node$readonly4=node.readonly)!=null?_node$readonly4:node.readonly=void 0;return;case"TSModuleDeclaration":(_node$declare7=node.declare)!=null?_node$declare7:node.declare=false;(_node$global=node.global)!=null?_node$global:node.global=node.kind==="global";return;case"TSTypeParameter":(_node$const2=node.const)!=null?_node$const2:node.const=false;(_node$in=node.in)!=null?_node$in:node.in=false;(_node$out=node.out)!=null?_node$out:node.out=false;return}}chStartsBindingIdentifierAndNotRelationalOperator(ch,pos){if(isIdentifierStart(ch)){keywordAndTSRelationalOperator.lastIndex=pos;if(keywordAndTSRelationalOperator.test(this.input)){const endCh=this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex);if(!isIdentifierChar(endCh)&&endCh!==92){return false}}return true}else if(ch===92){return true}else{return false}}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){const next=this.nextTokenInLineStart();const nextCh=this.codePointAtPos(next);return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh,next)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){const next=this.nextTokenInLineStart();const nextCh=this.codePointAtPos(next);return this.chStartsBindingIdentifier(nextCh,next)||nextCh===34||nextCh===39}};function isPossiblyLiteralEnum(expression){if(expression.type!=="MemberExpression")return false;const{computed,property}=expression;if(computed&&property.type!=="StringLiteral"&&(property.type!=="TemplateLiteral"||property.expressions.length>0)){return false}return isUncomputedMemberExpressionChain(expression.object)}function isValidAmbientConstInitializer(expression,estree2){var _expression$extra;const{type}=expression;if((_expression$extra=expression.extra)!=null&&_expression$extra.parenthesized){return false}if(estree2){if(type==="Literal"){const{value}=expression;if(typeof value==="string"||typeof value==="boolean"){return true}}}else{if(type==="StringLiteral"||type==="BooleanLiteral"){return true}}if(isNumber(expression,estree2)||isNegativeNumber(expression,estree2)){return true}if(type==="TemplateLiteral"&&expression.expressions.length===0){return true}if(isPossiblyLiteralEnum(expression)){return true}return false}function isNumber(expression,estree2){if(estree2){return expression.type==="Literal"&&(typeof expression.value==="number"||"bigint"in expression)}return expression.type==="NumericLiteral"||expression.type==="BigIntLiteral"}function isNegativeNumber(expression,estree2){if(expression.type==="UnaryExpression"){const{operator,argument}=expression;if(operator==="-"&&isNumber(argument,estree2)){return true}}return false}function isUncomputedMemberExpressionChain(expression){if(expression.type==="Identifier")return true;if(expression.type!=="MemberExpression"||expression.computed){return false}return isUncomputedMemberExpressionChain(expression.object)}var PlaceholderErrors=ParseErrorEnum`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."});var placeholders=superClass=>class PlaceholdersParserMixin extends superClass{parsePlaceholder(expectedNode){if(this.match(133)){const node=this.startNode();this.next();this.assertNoSpace();node.name=super.parseIdentifier(true);this.assertNoSpace();this.expect(133);return this.finishPlaceholder(node,expectedNode)}}finishPlaceholder(node,expectedNode){let placeholder2=node;if(!placeholder2.expectedNode||!placeholder2.type){placeholder2=this.finishNode(placeholder2,"Placeholder")}placeholder2.expectedNode=expectedNode;return placeholder2}getTokenFromCode(code2){if(code2===37&&this.input.charCodeAt(this.state.pos+1)===37){this.finishOp(133,2)}else{super.getTokenFromCode(code2)}}parseExprAtom(refExpressionErrors){return this.parsePlaceholder("Expression")||super.parseExprAtom(refExpressionErrors)}parseIdentifier(liberal){return this.parsePlaceholder("Identifier")||super.parseIdentifier(liberal)}checkReservedWord(word,startLoc,checkKeywords,isBinding){if(word!==void 0){super.checkReservedWord(word,startLoc,checkKeywords,isBinding)}}cloneIdentifier(node){const cloned=super.cloneIdentifier(node);if(cloned.type==="Placeholder"){cloned.expectedNode=node.expectedNode}return cloned}cloneStringLiteral(node){if(node.type==="Placeholder"){return this.cloneIdentifier(node)}return super.cloneStringLiteral(node)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(type,disallowCallExpression,isParenthesized,binding){return type==="Placeholder"||super.isValidLVal(type,disallowCallExpression,isParenthesized,binding)}toAssignable(node,isLHS){if(node&&node.type==="Placeholder"&&node.expectedNode==="Expression"){node.expectedNode="Pattern"}else{super.toAssignable(node,isLHS)}}chStartsBindingIdentifier(ch,pos){if(super.chStartsBindingIdentifier(ch,pos)){return true}const next=this.nextTokenStart();if(this.input.charCodeAt(next)===37&&this.input.charCodeAt(next+1)===37){return true}return false}verifyBreakContinue(node,isBreak){var _node$label;if(((_node$label=node.label)==null?void 0:_node$label.type)==="Placeholder")return;super.verifyBreakContinue(node,isBreak)}parseExpressionStatement(node,expr){var _expr$extra;if(expr.type!=="Placeholder"||(_expr$extra=expr.extra)!=null&&_expr$extra.parenthesized){return super.parseExpressionStatement(node,expr)}if(this.match(14)){const stmt=node;stmt.label=this.finishPlaceholder(expr,"Identifier");this.next();stmt.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration();return this.finishNode(stmt,"LabeledStatement")}this.semicolon();const stmtPlaceholder=node;stmtPlaceholder.name=expr.name;return this.finishPlaceholder(stmtPlaceholder,"Statement")}parseBlock(allowDirectives,createNewLexicalScope,afterBlockParse){return this.parsePlaceholder("BlockStatement")||super.parseBlock(allowDirectives,createNewLexicalScope,afterBlockParse)}parseFunctionId(requireId){return this.parsePlaceholder("Identifier")||super.parseFunctionId(requireId)}parseClass(node,isStatement,optionalId){const type=isStatement?"ClassDeclaration":"ClassExpression";this.next();const oldStrict=this.state.strict;const placeholder2=this.parsePlaceholder("Identifier");if(placeholder2){if(this.match(81)||this.match(133)||this.match(5)){node.id=placeholder2}else if(optionalId||!isStatement){node.id=null;node.body=this.finishPlaceholder(placeholder2,"ClassBody");return this.finishNode(node,type)}else{throw this.raise(PlaceholderErrors.ClassNameIsRequired,this.state.startLoc)}}else{this.parseClassId(node,isStatement,optionalId)}super.parseClassSuper(node);node.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!node.superClass,oldStrict);return this.finishNode(node,type)}parseExport(node,decorators){const placeholder2=this.parsePlaceholder("Identifier");if(!placeholder2)return super.parseExport(node,decorators);const node2=node;if(!this.isContextual(98)&&!this.match(12)){node2.specifiers=[];node2.source=null;node2.declaration=this.finishPlaceholder(placeholder2,"Declaration");return this.finishNode(node2,"ExportNamedDeclaration")}this.expectPlugin("exportDefaultFrom");const specifier=this.startNode();specifier.exported=placeholder2;node2.specifiers=[this.finishNode(specifier,"ExportDefaultSpecifier")];return super.parseExport(node2,decorators)}isExportDefaultSpecifier(){if(this.match(65)){const next=this.nextTokenStart();if(this.isUnparsedContextual(next,"from")){if(this.input.startsWith(tokenLabelName(133),this.nextTokenStartSince(next+4))){return true}}}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(node,maybeDefaultIdentifier){var _specifiers;if((_specifiers=node.specifiers)!=null&&_specifiers.length){return true}return super.maybeParseExportDefaultSpecifier(node,maybeDefaultIdentifier)}checkExport(node){const{specifiers}=node;if(specifiers!=null&&specifiers.length){node.specifiers=specifiers.filter(node2=>node2.exported.type==="Placeholder")}super.checkExport(node);node.specifiers=specifiers}parseImport(node){const placeholder2=this.parsePlaceholder("Identifier");if(!placeholder2)return super.parseImport(node);node.specifiers=[];if(!this.isContextual(98)&&!this.match(12)){node.source=this.finishPlaceholder(placeholder2,"StringLiteral");this.semicolon();return this.finishNode(node,"ImportDeclaration")}const specifier=this.startNodeAtNode(placeholder2);specifier.local=placeholder2;node.specifiers.push(this.finishNode(specifier,"ImportDefaultSpecifier"));if(this.eat(12)){const hasStarImport=this.maybeParseStarImportSpecifier(node);if(!hasStarImport)this.parseNamedImportSpecifiers(node)}this.expectContextual(98);node.source=this.parseImportSource();this.semicolon();return this.finishNode(node,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){if(this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)){this.raise(PlaceholderErrors.UnexpectedSpace,this.state.lastTokEndLoc)}}};var v8intrinsic=superClass=>class V8IntrinsicMixin extends superClass{parseV8Intrinsic(){if(this.match(54)){const v8IntrinsicStartLoc=this.state.startLoc;const node=this.startNode();this.next();if(tokenIsIdentifier(this.state.type)){const name=this.parseIdentifierName();const identifier=this.createIdentifier(node,name);this.castNodeTo(identifier,"V8IntrinsicIdentifier");if(this.match(10)){return identifier}}this.unexpected(v8IntrinsicStartLoc)}}parseExprAtom(refExpressionErrors){return this.parseV8Intrinsic()||super.parseExprAtom(refExpressionErrors)}};var PIPELINE_PROPOSALS=["minimal","fsharp","hack","smart"];var TOPIC_TOKENS=["^^","@@","^","%","#"];function validatePlugins(pluginsMap){if(pluginsMap.has("decorators")){if(pluginsMap.has("decorators-legacy")){throw new Error("Cannot use the decorators and decorators-legacy plugin together")}const decoratorsBeforeExport=pluginsMap.get("decorators").decoratorsBeforeExport;if(decoratorsBeforeExport!=null&&typeof decoratorsBeforeExport!=="boolean"){throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.")}const allowCallParenthesized=pluginsMap.get("decorators").allowCallParenthesized;if(allowCallParenthesized!=null&&typeof allowCallParenthesized!=="boolean"){throw new Error("'allowCallParenthesized' must be a boolean.")}}if(pluginsMap.has("flow")&&pluginsMap.has("typescript")){throw new Error("Cannot combine flow and typescript plugins.")}if(pluginsMap.has("placeholders")&&pluginsMap.has("v8intrinsic")){throw new Error("Cannot combine placeholders and v8intrinsic plugins.")}if(pluginsMap.has("pipelineOperator")){var _pluginsMap$get2;const proposal=pluginsMap.get("pipelineOperator").proposal;if(!PIPELINE_PROPOSALS.includes(proposal)){const proposalList=PIPELINE_PROPOSALS.map(p=>`"${p}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`)}if(proposal==="hack"){var _pluginsMap$get;if(pluginsMap.has("placeholders")){throw new Error("Cannot combine placeholders plugin and Hack-style pipes.")}if(pluginsMap.has("v8intrinsic")){throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.")}const topicToken=pluginsMap.get("pipelineOperator").topicToken;if(!TOPIC_TOKENS.includes(topicToken)){const tokenList=TOPIC_TOKENS.map(t=>`"${t}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`)}if(topicToken==="#"&&((_pluginsMap$get=pluginsMap.get("recordAndTuple"))==null?void 0:_pluginsMap$get.syntaxType)==="hash"){throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",pluginsMap.get("recordAndTuple")])}\`.`)}}else if(proposal==="smart"&&((_pluginsMap$get2=pluginsMap.get("recordAndTuple"))==null?void 0:_pluginsMap$get2.syntaxType)==="hash"){throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",pluginsMap.get("recordAndTuple")])}\`.`)}}if(pluginsMap.has("moduleAttributes")){if(pluginsMap.has("deprecatedImportAssert")||pluginsMap.has("importAssertions")){throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.")}const moduleAttributesVersionPluginOption=pluginsMap.get("moduleAttributes").version;if(moduleAttributesVersionPluginOption!=="may-2020"){throw new Error("The 'moduleAttributes' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is 'may-2020'.")}}if(pluginsMap.has("importAssertions")){if(pluginsMap.has("deprecatedImportAssert")){throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.")}}if(pluginsMap.has("deprecatedImportAssert"));else if(pluginsMap.has("importAttributes")&&pluginsMap.get("importAttributes").deprecatedAssertSyntax){pluginsMap.set("deprecatedImportAssert",{})}if(pluginsMap.has("recordAndTuple")){const syntaxType=pluginsMap.get("recordAndTuple").syntaxType;if(syntaxType!=null){const RECORD_AND_TUPLE_SYNTAX_TYPES=["hash","bar"];if(!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)){throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+RECORD_AND_TUPLE_SYNTAX_TYPES.map(p=>`'${p}'`).join(", "))}}}if(pluginsMap.has("asyncDoExpressions")&&!pluginsMap.has("doExpressions")){const error51=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");error51.missingPlugins="doExpressions";throw error51}if(pluginsMap.has("optionalChainingAssign")&&pluginsMap.get("optionalChainingAssign").version!=="2023-07"){throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.")}if(pluginsMap.has("discardBinding")&&pluginsMap.get("discardBinding").syntaxType!=="void"){throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}}var mixinPlugins={estree,jsx,flow,typescript,v8intrinsic,placeholders};var mixinPluginNames=Object.keys(mixinPlugins);var ExpressionParser=class extends LValParser{checkProto(prop,isRecord7,sawProto,refExpressionErrors){if(prop.type==="SpreadElement"||this.isObjectMethod(prop)||prop.computed||prop.shorthand){return sawProto}const key=prop.key;const name=key.type==="Identifier"?key.name:key.value;if(name==="__proto__"){if(isRecord7){this.raise(Errors.RecordNoProto,key);return true}if(sawProto){if(refExpressionErrors){if(refExpressionErrors.doubleProtoLoc===null){refExpressionErrors.doubleProtoLoc=key.loc.start}}else{this.raise(Errors.DuplicateProto,key)}}return true}return sawProto}shouldExitDescending(expr,potentialArrowAt){return expr.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(expr.start)===potentialArrowAt}getExpression(){this.enterInitialScopes();this.nextToken();if(this.match(140)){throw this.raise(Errors.ParseExpressionEmptyInput,this.state.startLoc)}const expr=this.parseExpression();if(!this.match(140)){throw this.raise(Errors.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)})}this.finalizeRemainingComments();expr.comments=this.comments;expr.errors=this.state.errors;if(this.optionFlags&256){expr.tokens=this.tokens}return expr}parseExpression(disallowIn,refExpressionErrors){if(disallowIn){return this.disallowInAnd(()=>this.parseExpressionBase(refExpressionErrors))}return this.allowInAnd(()=>this.parseExpressionBase(refExpressionErrors))}parseExpressionBase(refExpressionErrors){const startLoc=this.state.startLoc;const expr=this.parseMaybeAssign(refExpressionErrors);if(this.match(12)){const node=this.startNodeAt(startLoc);node.expressions=[expr];while(this.eat(12)){node.expressions.push(this.parseMaybeAssign(refExpressionErrors))}this.toReferencedList(node.expressions);return this.finishNode(node,"SequenceExpression")}return expr}parseMaybeAssignDisallowIn(refExpressionErrors,afterLeftParse){return this.disallowInAnd(()=>this.parseMaybeAssign(refExpressionErrors,afterLeftParse))}parseMaybeAssignAllowIn(refExpressionErrors,afterLeftParse){return this.allowInAnd(()=>this.parseMaybeAssign(refExpressionErrors,afterLeftParse))}setOptionalParametersError(refExpressionErrors){refExpressionErrors.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(refExpressionErrors,afterLeftParse){const startLoc=this.state.startLoc;const isYield=this.isContextual(108);if(isYield){if(this.prodParam.hasYield){this.next();let left2=this.parseYield(startLoc);if(afterLeftParse){left2=afterLeftParse.call(this,left2,startLoc)}return left2}}let ownExpressionErrors;if(refExpressionErrors){ownExpressionErrors=false}else{refExpressionErrors=new ExpressionErrors;ownExpressionErrors=true}const{type}=this.state;if(type===10||tokenIsIdentifier(type)){this.state.potentialArrowAt=this.state.start}let left=this.parseMaybeConditional(refExpressionErrors);if(afterLeftParse){left=afterLeftParse.call(this,left,startLoc)}if(tokenIsAssignment(this.state.type)){const node=this.startNodeAt(startLoc);const operator=this.state.value;node.operator=operator;if(this.match(29)){this.toAssignable(left,true);node.left=left;const startIndex=startLoc.index;if(refExpressionErrors.doubleProtoLoc!=null&&refExpressionErrors.doubleProtoLoc.index>=startIndex){refExpressionErrors.doubleProtoLoc=null}if(refExpressionErrors.shorthandAssignLoc!=null&&refExpressionErrors.shorthandAssignLoc.index>=startIndex){refExpressionErrors.shorthandAssignLoc=null}if(refExpressionErrors.privateKeyLoc!=null&&refExpressionErrors.privateKeyLoc.index>=startIndex){this.checkDestructuringPrivate(refExpressionErrors);refExpressionErrors.privateKeyLoc=null}if(refExpressionErrors.voidPatternLoc!=null&&refExpressionErrors.voidPatternLoc.index>=startIndex){refExpressionErrors.voidPatternLoc=null}}else{node.left=left}this.next();node.right=this.parseMaybeAssign();this.checkLVal(left,this.finishNode(node,"AssignmentExpression"),void 0,void 0,void 0,void 0,operator==="||="||operator==="&&="||operator==="??=");return node}else if(ownExpressionErrors){this.checkExpressionErrors(refExpressionErrors,true)}if(isYield){const{type:type2}=this.state;const startsExpr2=this.hasPlugin("v8intrinsic")?tokenCanStartExpression(type2):tokenCanStartExpression(type2)&&!this.match(54);if(startsExpr2&&!this.isAmbiguousPrefixOrIdentifier()){this.raiseOverwrite(Errors.YieldNotInGeneratorFunction,startLoc);return this.parseYield(startLoc)}}return left}parseMaybeConditional(refExpressionErrors){const startLoc=this.state.startLoc;const potentialArrowAt=this.state.potentialArrowAt;const expr=this.parseExprOps(refExpressionErrors);if(this.shouldExitDescending(expr,potentialArrowAt)){return expr}return this.parseConditional(expr,startLoc,refExpressionErrors)}parseConditional(expr,startLoc,refExpressionErrors){if(this.eat(17)){const node=this.startNodeAt(startLoc);node.test=expr;node.consequent=this.parseMaybeAssignAllowIn();this.expect(14);node.alternate=this.parseMaybeAssign();return this.finishNode(node,"ConditionalExpression")}return expr}parseMaybeUnaryOrPrivate(refExpressionErrors){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(refExpressionErrors)}parseExprOps(refExpressionErrors){const startLoc=this.state.startLoc;const potentialArrowAt=this.state.potentialArrowAt;const expr=this.parseMaybeUnaryOrPrivate(refExpressionErrors);if(this.shouldExitDescending(expr,potentialArrowAt)){return expr}return this.parseExprOp(expr,startLoc,-1)}parseExprOp(left,leftStartLoc,minPrec){if(this.isPrivateName(left)){const value=this.getPrivateNameSV(left);if(minPrec>=tokenOperatorPrecedence(58)||!this.prodParam.hasIn||!this.match(58)){this.raise(Errors.PrivateInExpectedIn,left,{identifierName:value})}this.classScope.usePrivateName(value,left.loc.start)}const op=this.state.type;if(tokenIsOperator(op)&&(this.prodParam.hasIn||!this.match(58))){let prec=tokenOperatorPrecedence(op);if(prec>minPrec){if(op===39){this.expectPlugin("pipelineOperator");if(this.state.inFSharpPipelineDirectBody){return left}this.checkPipelineAtInfixOperator(left,leftStartLoc)}const node=this.startNodeAt(leftStartLoc);node.left=left;node.operator=this.state.value;const logical=op===41||op===42;const coalesce=op===40;if(coalesce){prec=tokenOperatorPrecedence(42)}this.next();if(op===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])){if(this.state.type===96&&this.prodParam.hasAwait){throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody,this.state.startLoc)}}node.right=this.parseExprOpRightExpr(op,prec);const finishedNode=this.finishNode(node,logical||coalesce?"LogicalExpression":"BinaryExpression");const nextOp=this.state.type;if(coalesce&&(nextOp===41||nextOp===42)||logical&&nextOp===40){throw this.raise(Errors.MixingCoalesceWithLogical,this.state.startLoc)}return this.parseExprOp(finishedNode,leftStartLoc,minPrec)}}return left}parseExprOpRightExpr(op,prec){const startLoc=this.state.startLoc;switch(op){case 39:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>{return this.parseHackPipeBody()});case"fsharp":return this.withSoloAwaitPermittingContext(()=>{return this.parseFSharpPipelineBody(prec)})}if(this.getPluginOption("pipelineOperator","proposal")==="smart"){return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(108)){throw this.raise(Errors.PipeBodyIsTighter,this.state.startLoc)}return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op,prec),startLoc)})}default:return this.parseExprOpBaseRightExpr(op,prec)}}parseExprOpBaseRightExpr(op,prec){const startLoc=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),startLoc,tokenIsRightAssociative(op)?prec-1:prec)}parseHackPipeBody(){var _body$extra;const{startLoc}=this.state;const body=this.parseMaybeAssign();const requiredParentheses=UnparenthesizedPipeBodyDescriptions.has(body.type);if(requiredParentheses&&!((_body$extra=body.extra)!=null&&_body$extra.parenthesized)){this.raise(Errors.PipeUnparenthesizedBody,startLoc,{type:body.type})}if(!this.topicReferenceWasUsedInCurrentContext()){this.raise(Errors.PipeTopicUnused,startLoc)}return body}checkExponentialAfterUnary(node){if(this.match(57)){this.raise(Errors.UnexpectedTokenUnaryExponentiation,node.argument)}}parseMaybeUnary(refExpressionErrors,sawUnary){const startLoc=this.state.startLoc;const isAwait=this.isContextual(96);if(isAwait&&this.recordAwaitIfAllowed()){this.next();const expr2=this.parseAwait(startLoc);if(!sawUnary)this.checkExponentialAfterUnary(expr2);return expr2}const update=this.match(34);const node=this.startNode();if(tokenIsPrefix(this.state.type)){node.operator=this.state.value;node.prefix=true;if(this.match(72)){this.expectPlugin("throwExpressions")}const isDelete=this.match(89);this.next();node.argument=this.parseMaybeUnary(null,true);this.checkExpressionErrors(refExpressionErrors,true);if(this.state.strict&&isDelete){const arg=node.argument;if(arg.type==="Identifier"){this.raise(Errors.StrictDelete,node)}else if(this.hasPropertyAsPrivateName(arg)){this.raise(Errors.DeletePrivateField,node)}}if(!update){if(!sawUnary){this.checkExponentialAfterUnary(node)}return this.finishNode(node,"UnaryExpression")}}const expr=this.parseUpdate(node,update,refExpressionErrors);if(isAwait){const{type}=this.state;const startsExpr2=this.hasPlugin("v8intrinsic")?tokenCanStartExpression(type):tokenCanStartExpression(type)&&!this.match(54);if(startsExpr2&&!this.isAmbiguousPrefixOrIdentifier()){this.raiseOverwrite(Errors.AwaitNotInAsyncContext,startLoc);return this.parseAwait(startLoc)}}return expr}parseUpdate(node,update,refExpressionErrors){if(update){const updateExpressionNode=node;this.checkLVal(updateExpressionNode.argument,this.finishNode(updateExpressionNode,"UpdateExpression"));return node}const startLoc=this.state.startLoc;let expr=this.parseExprSubscripts(refExpressionErrors);if(this.checkExpressionErrors(refExpressionErrors,false))return expr;while(tokenIsPostfix(this.state.type)&&!this.canInsertSemicolon()){const node2=this.startNodeAt(startLoc);node2.operator=this.state.value;node2.prefix=false;node2.argument=expr;this.next();this.checkLVal(expr,expr=this.finishNode(node2,"UpdateExpression"))}return expr}parseExprSubscripts(refExpressionErrors){const startLoc=this.state.startLoc;const potentialArrowAt=this.state.potentialArrowAt;const expr=this.parseExprAtom(refExpressionErrors);if(this.shouldExitDescending(expr,potentialArrowAt)){return expr}return this.parseSubscripts(expr,startLoc)}parseSubscripts(base,startLoc,noCalls){const state={optionalChainMember:false,maybeAsyncArrow:this.atPossibleAsyncArrow(base),stop:false};do{base=this.parseSubscript(base,startLoc,noCalls,state);state.maybeAsyncArrow=false}while(!state.stop);return base}parseSubscript(base,startLoc,noCalls,state){const{type}=this.state;if(!noCalls&&type===15){return this.parseBind(base,startLoc,noCalls,state)}else if(tokenIsTemplate(type)){return this.parseTaggedTemplateExpression(base,startLoc,state)}let optional2=false;if(type===18){if(noCalls){this.raise(Errors.OptionalChainingNoNew,this.state.startLoc);if(this.lookaheadCharCode()===40){return this.stopParseSubscript(base,state)}}state.optionalChainMember=optional2=true;this.next()}if(!noCalls&&this.match(10)){return this.parseCoverCallAndAsyncArrowHead(base,startLoc,state,optional2)}else{const computed=this.eat(0);if(computed||optional2||this.eat(16)){return this.parseMember(base,startLoc,state,computed,optional2)}else{return this.stopParseSubscript(base,state)}}}stopParseSubscript(base,state){state.stop=true;return base}parseMember(base,startLoc,state,computed,optional2){const node=this.startNodeAt(startLoc);node.object=base;node.computed=computed;if(computed){node.property=this.parseExpression();this.expect(3)}else if(this.match(139)){if(base.type==="Super"){this.raise(Errors.SuperPrivateField,startLoc)}this.classScope.usePrivateName(this.state.value,this.state.startLoc);node.property=this.parsePrivateName()}else{node.property=this.parseIdentifier(true)}if(state.optionalChainMember){node.optional=optional2;return this.finishNode(node,"OptionalMemberExpression")}else{return this.finishNode(node,"MemberExpression")}}parseBind(base,startLoc,noCalls,state){const node=this.startNodeAt(startLoc);node.object=base;this.next();node.callee=this.parseNoCallExpr();state.stop=true;return this.parseSubscripts(this.finishNode(node,"BindExpression"),startLoc,noCalls)}parseCoverCallAndAsyncArrowHead(base,startLoc,state,optional2){const oldMaybeInArrowParameters=this.state.maybeInArrowParameters;let refExpressionErrors=null;this.state.maybeInArrowParameters=true;this.next();const node=this.startNodeAt(startLoc);node.callee=base;const{maybeAsyncArrow,optionalChainMember}=state;if(maybeAsyncArrow){this.expressionScope.enter(newAsyncArrowScope());refExpressionErrors=new ExpressionErrors}if(optionalChainMember){node.optional=optional2}if(optional2){node.arguments=this.parseCallExpressionArguments()}else{node.arguments=this.parseCallExpressionArguments(base.type!=="Super",node,refExpressionErrors)}let finishedNode=this.finishCallExpression(node,optionalChainMember);if(maybeAsyncArrow&&this.shouldParseAsyncArrow()&&!optional2){state.stop=true;this.checkDestructuringPrivate(refExpressionErrors);this.expressionScope.validateAsPattern();this.expressionScope.exit();finishedNode=this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc),finishedNode)}else{if(maybeAsyncArrow){this.checkExpressionErrors(refExpressionErrors,true);this.expressionScope.exit()}this.toReferencedArguments(finishedNode)}this.state.maybeInArrowParameters=oldMaybeInArrowParameters;return finishedNode}toReferencedArguments(node,isParenthesizedExpr){this.toReferencedListDeep(node.arguments,isParenthesizedExpr)}parseTaggedTemplateExpression(base,startLoc,state){const node=this.startNodeAt(startLoc);node.tag=base;node.quasi=this.parseTemplate(true);if(state.optionalChainMember){this.raise(Errors.OptionalChainingNoTemplate,startLoc)}return this.finishNode(node,"TaggedTemplateExpression")}atPossibleAsyncArrow(base){return base.type==="Identifier"&&base.name==="async"&&this.state.lastTokEndLoc.index===base.end&&!this.canInsertSemicolon()&&base.end-base.start===5&&this.offsetToSourcePos(base.start)===this.state.potentialArrowAt}finishCallExpression(node,optional2){if(node.callee.type==="Import"){if(node.arguments.length===0||node.arguments.length>2){this.raise(Errors.ImportCallArity,node)}else{for(const arg of node.arguments){if(arg.type==="SpreadElement"){this.raise(Errors.ImportCallSpreadArgument,arg)}}}}return this.finishNode(node,optional2?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(allowPlaceholder,nodeForExtra,refExpressionErrors){const elts=[];let first=true;const oldInFSharpPipelineDirectBody=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=false;while(!this.eat(11)){if(first){first=false}else{this.expect(12);if(this.match(11)){if(nodeForExtra){this.addTrailingCommaExtraToNode(nodeForExtra)}this.next();break}}elts.push(this.parseExprListItem(11,false,refExpressionErrors,allowPlaceholder))}this.state.inFSharpPipelineDirectBody=oldInFSharpPipelineDirectBody;return elts}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(node,call){var _call$extra;this.resetPreviousNodeTrailingComments(call);this.expect(19);this.parseArrowExpression(node,call.arguments,true,(_call$extra=call.extra)==null?void 0:_call$extra.trailingCommaLoc);if(call.innerComments){setInnerComments(node,call.innerComments)}if(call.callee.trailingComments){setInnerComments(node,call.callee.trailingComments)}return node}parseNoCallExpr(){const startLoc=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),startLoc,true)}parseExprAtom(refExpressionErrors){let node;let decorators=null;const{type}=this.state;switch(type){case 79:return this.parseSuper();case 83:node=this.startNode();this.next();if(this.match(16)){return this.parseImportMetaPropertyOrPhaseCall(node)}if(this.match(10)){if(this.optionFlags&512){return this.parseImportCall(node)}else{return this.finishNode(node,"Import")}}else{this.raise(Errors.UnsupportedImport,this.state.lastTokStartLoc);return this.finishNode(node,"Import")}case 78:node=this.startNode();this.next();return this.finishNode(node,"ThisExpression");case 90:{return this.parseDo(this.startNode(),false)}case 56:case 31:{this.readRegexp();return this.parseRegExpLiteral(this.state.value)}case 135:return this.parseNumericLiteral(this.state.value);case 136:return this.parseBigIntLiteral(this.state.value);case 134:return this.parseStringLiteral(this.state.value);case 84:return this.parseNullLiteral();case 85:return this.parseBooleanLiteral(true);case 86:return this.parseBooleanLiteral(false);case 10:{const canBeArrow=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(canBeArrow)}case 0:{return this.parseArrayLike(3,false,refExpressionErrors)}case 5:{return this.parseObjectLike(8,false,false,refExpressionErrors)}case 68:return this.parseFunctionOrFunctionSent();case 26:decorators=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(decorators,this.startNode()),false);case 77:return this.parseNewOrNewTarget();case 25:case 24:return this.parseTemplate(false);case 15:{node=this.startNode();this.next();node.object=null;const callee=node.callee=this.parseNoCallExpr();if(callee.type==="MemberExpression"){return this.finishNode(node,"BindExpression")}else{throw this.raise(Errors.UnsupportedBind,callee)}}case 139:{this.raise(Errors.PrivateInExpectedIn,this.state.startLoc,{identifierName:this.state.value});return this.parsePrivateName()}case 33:{return this.parseTopicReferenceThenEqualsSign(54,"%")}case 32:{return this.parseTopicReferenceThenEqualsSign(44,"^")}case 37:case 38:{return this.parseTopicReference("hack")}case 44:case 54:case 27:{const pipeProposal=this.getPluginOption("pipelineOperator","proposal");if(pipeProposal){return this.parseTopicReference(pipeProposal)}throw this.unexpected()}case 47:{const lookaheadCh=this.input.codePointAt(this.nextTokenStart());if(isIdentifierStart(lookaheadCh)||lookaheadCh===62){throw this.expectOnePlugin(["jsx","flow","typescript"])}throw this.unexpected()}default:if(type===137){return this.parseDecimalLiteral(this.state.value)}else if(type===2||type===1){return this.parseArrayLike(this.state.type===2?4:3,true)}else if(type===6||type===7){return this.parseObjectLike(this.state.type===6?9:8,false,true)}if(tokenIsIdentifier(type)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123){return this.parseModuleExpression()}const canBeArrow=this.state.potentialArrowAt===this.state.start;const containsEsc=this.state.containsEsc;const id=this.parseIdentifier();if(!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()){const{type:type2}=this.state;if(type2===68){this.resetPreviousNodeTrailingComments(id);this.next();return this.parseAsyncFunctionExpression(this.startNodeAtNode(id))}else if(tokenIsIdentifier(type2)){if(canBeArrow&&this.lookaheadCharCode()===61){return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id))}else{return id}}else if(type2===90){this.resetPreviousNodeTrailingComments(id);return this.parseDo(this.startNodeAtNode(id),true)}}if(canBeArrow&&this.match(19)&&!this.canInsertSemicolon()){this.next();return this.parseArrowExpression(this.startNodeAtNode(id),[id],false)}return id}else{throw this.unexpected()}}}parseTopicReferenceThenEqualsSign(topicTokenType,topicTokenValue){const pipeProposal=this.getPluginOption("pipelineOperator","proposal");if(pipeProposal){this.state.type=topicTokenType;this.state.value=topicTokenValue;this.state.pos--;this.state.end--;this.state.endLoc=createPositionWithColumnOffset(this.state.endLoc,-1);return this.parseTopicReference(pipeProposal)}throw this.unexpected()}parseTopicReference(pipeProposal){const node=this.startNode();const startLoc=this.state.startLoc;const tokenType=this.state.type;this.next();return this.finishTopicReference(node,startLoc,pipeProposal,tokenType)}finishTopicReference(node,startLoc,pipeProposal,tokenType){if(this.testTopicReferenceConfiguration(pipeProposal,startLoc,tokenType)){if(pipeProposal==="hack"){if(!this.topicReferenceIsAllowedInCurrentContext()){this.raise(Errors.PipeTopicUnbound,startLoc)}this.registerTopicReference();return this.finishNode(node,"TopicReference")}else{if(!this.topicReferenceIsAllowedInCurrentContext()){this.raise(Errors.PrimaryTopicNotAllowed,startLoc)}this.registerTopicReference();return this.finishNode(node,"PipelinePrimaryTopicReference")}}else{throw this.raise(Errors.PipeTopicUnconfiguredToken,startLoc,{token:tokenLabelName(tokenType)})}}testTopicReferenceConfiguration(pipeProposal,startLoc,tokenType){switch(pipeProposal){case"hack":{return this.hasPlugin(["pipelineOperator",{topicToken:tokenLabelName(tokenType)}])}case"smart":return tokenType===27;default:throw this.raise(Errors.PipeTopicRequiresHackPipes,startLoc)}}parseAsyncArrowUnaryFunction(node){this.prodParam.enter(functionFlags(true,this.prodParam.hasYield));const params=[this.parseIdentifier()];this.prodParam.exit();if(this.hasPrecedingLineBreak()){this.raise(Errors.LineTerminatorBeforeArrow,this.state.curPosition())}this.expect(19);return this.parseArrowExpression(node,params,true)}parseDo(node,isAsync){this.expectPlugin("doExpressions");if(isAsync){this.expectPlugin("asyncDoExpressions")}node.async=isAsync;this.next();const oldLabels=this.state.labels;this.state.labels=[];if(isAsync){this.prodParam.enter(2);node.body=this.parseBlock();this.prodParam.exit()}else{node.body=this.parseBlock()}this.state.labels=oldLabels;return this.finishNode(node,"DoExpression")}parseSuper(){const node=this.startNode();this.next();if(this.match(10)&&!this.scope.allowDirectSuper){if(!(this.optionFlags&16)){this.raise(Errors.SuperNotAllowed,node)}}else if(!this.scope.allowSuper){if(!(this.optionFlags&16)){this.raise(Errors.UnexpectedSuper,node)}}if(!this.match(10)&&!this.match(0)&&!this.match(16)){this.raise(Errors.UnsupportedSuper,node)}return this.finishNode(node,"Super")}parsePrivateName(){const node=this.startNode();const id=this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc,1));const name=this.state.value;this.next();node.id=this.createIdentifier(id,name);return this.finishNode(node,"PrivateName")}parseFunctionOrFunctionSent(){const node=this.startNode();this.next();if(this.prodParam.hasYield&&this.match(16)){const meta3=this.createIdentifier(this.startNodeAtNode(node),"function");this.next();if(this.match(103)){this.expectPlugin("functionSent")}else if(!this.hasPlugin("functionSent")){this.unexpected()}return this.parseMetaProperty(node,meta3,"sent")}return this.parseFunction(node)}parseMetaProperty(node,meta3,propertyName){node.meta=meta3;const containsEsc=this.state.containsEsc;node.property=this.parseIdentifier(true);if(node.property.name!==propertyName||containsEsc){this.raise(Errors.UnsupportedMetaProperty,node.property,{target:meta3.name,onlyValidPropertyName:propertyName})}return this.finishNode(node,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(node){this.next();if(this.isContextual(105)||this.isContextual(97)){const isSource=this.isContextual(105);this.expectPlugin(isSource?"sourcePhaseImports":"deferredImportEvaluation");this.next();node.phase=isSource?"source":"defer";return this.parseImportCall(node)}else{const id=this.createIdentifierAt(this.startNodeAtNode(node),"import",this.state.lastTokStartLoc);if(this.isContextual(101)){if(!this.inModule){this.raise(Errors.ImportMetaOutsideModule,id)}this.sawUnambiguousESM=true}return this.parseMetaProperty(node,id,"meta")}}parseLiteralAtNode(value,type,node){this.addExtra(node,"rawValue",value);this.addExtra(node,"raw",this.input.slice(this.offsetToSourcePos(node.start),this.state.end));node.value=value;this.next();return this.finishNode(node,type)}parseLiteral(value,type){const node=this.startNode();return this.parseLiteralAtNode(value,type,node)}parseStringLiteral(value){return this.parseLiteral(value,"StringLiteral")}parseNumericLiteral(value){return this.parseLiteral(value,"NumericLiteral")}parseBigIntLiteral(value){return this.parseLiteral(value,"BigIntLiteral")}parseDecimalLiteral(value){return this.parseLiteral(value,"DecimalLiteral")}parseRegExpLiteral(value){const node=this.startNode();this.addExtra(node,"raw",this.input.slice(this.offsetToSourcePos(node.start),this.state.end));node.pattern=value.pattern;node.flags=value.flags;this.next();return this.finishNode(node,"RegExpLiteral")}parseBooleanLiteral(value){const node=this.startNode();node.value=value;this.next();return this.finishNode(node,"BooleanLiteral")}parseNullLiteral(){const node=this.startNode();this.next();return this.finishNode(node,"NullLiteral")}parseParenAndDistinguishExpression(canBeArrow){const startLoc=this.state.startLoc;let val;this.next();this.expressionScope.enter(newArrowHeadScope());const oldMaybeInArrowParameters=this.state.maybeInArrowParameters;const oldInFSharpPipelineDirectBody=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=true;this.state.inFSharpPipelineDirectBody=false;const innerStartLoc=this.state.startLoc;const exprList=[];const refExpressionErrors=new ExpressionErrors;let first=true;let spreadStartLoc;let optionalCommaStartLoc;while(!this.match(11)){if(first){first=false}else{this.expect(12,refExpressionErrors.optionalParametersLoc===null?null:refExpressionErrors.optionalParametersLoc);if(this.match(11)){optionalCommaStartLoc=this.state.startLoc;break}}if(this.match(21)){const spreadNodeStartLoc=this.state.startLoc;spreadStartLoc=this.state.startLoc;exprList.push(this.parseParenItem(this.parseRestBinding(),spreadNodeStartLoc));if(!this.checkCommaAfterRest(41)){break}}else{exprList.push(this.parseMaybeAssignAllowInOrVoidPattern(11,refExpressionErrors,this.parseParenItem))}}const innerEndLoc=this.state.lastTokEndLoc;this.expect(11);this.state.maybeInArrowParameters=oldMaybeInArrowParameters;this.state.inFSharpPipelineDirectBody=oldInFSharpPipelineDirectBody;let arrowNode=this.startNodeAt(startLoc);if(canBeArrow&&this.shouldParseArrow(exprList)&&(arrowNode=this.parseArrow(arrowNode))){this.checkDestructuringPrivate(refExpressionErrors);this.expressionScope.validateAsPattern();this.expressionScope.exit();this.parseArrowExpression(arrowNode,exprList,false);return arrowNode}this.expressionScope.exit();if(!exprList.length){this.unexpected(this.state.lastTokStartLoc)}if(optionalCommaStartLoc)this.unexpected(optionalCommaStartLoc);if(spreadStartLoc)this.unexpected(spreadStartLoc);this.checkExpressionErrors(refExpressionErrors,true);this.toReferencedListDeep(exprList,true);if(exprList.length>1){val=this.startNodeAt(innerStartLoc);val.expressions=exprList;this.finishNode(val,"SequenceExpression");this.resetEndLocation(val,innerEndLoc)}else{val=exprList[0]}return this.wrapParenthesis(startLoc,val)}wrapParenthesis(startLoc,expression){if(!(this.optionFlags&1024)){this.addExtra(expression,"parenthesized",true);this.addExtra(expression,"parenStart",startLoc.index);this.takeSurroundingComments(expression,startLoc.index,this.state.lastTokEndLoc.index);return expression}const parenExpression=this.startNodeAt(startLoc);parenExpression.expression=expression;return this.finishNode(parenExpression,"ParenthesizedExpression")}shouldParseArrow(params){return!this.canInsertSemicolon()}parseArrow(node){if(this.eat(19)){return node}}parseParenItem(node,startLoc){return node}parseNewOrNewTarget(){const node=this.startNode();this.next();if(this.match(16)){const meta3=this.createIdentifier(this.startNodeAtNode(node),"new");this.next();const metaProp=this.parseMetaProperty(node,meta3,"target");if(!this.scope.allowNewTarget){this.raise(Errors.UnexpectedNewTarget,metaProp)}return metaProp}return this.parseNew(node)}parseNew(node){this.parseNewCallee(node);if(this.eat(10)){const args=this.parseExprList(11);this.toReferencedList(args);node.arguments=args}else{node.arguments=[]}return this.finishNode(node,"NewExpression")}parseNewCallee(node){const isImport=this.match(83);const callee=this.parseNoCallExpr();node.callee=callee;if(isImport&&(callee.type==="Import"||callee.type==="ImportExpression")){this.raise(Errors.ImportCallNotNewExpression,callee)}}parseTemplateElement(isTagged){const{start,startLoc,end,value}=this.state;const elemStart=start+1;const elem=this.startNodeAt(createPositionWithColumnOffset(startLoc,1));if(value===null){if(!isTagged){this.raise(Errors.InvalidEscapeSequenceTemplate,createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos,1))}}const isTail=this.match(24);const endOffset=isTail?-1:-2;const elemEnd=end+endOffset;elem.value={raw:this.input.slice(elemStart,elemEnd).replace(/\r\n?/g,"\n"),cooked:value===null?null:value.slice(1,endOffset)};elem.tail=isTail;this.next();const finishedNode=this.finishNode(elem,"TemplateElement");this.resetEndLocation(finishedNode,createPositionWithColumnOffset(this.state.lastTokEndLoc,endOffset));return finishedNode}parseTemplate(isTagged){const node=this.startNode();let curElt=this.parseTemplateElement(isTagged);const quasis=[curElt];const substitutions=[];while(!curElt.tail){substitutions.push(this.parseTemplateSubstitution());this.readTemplateContinuation();quasis.push(curElt=this.parseTemplateElement(isTagged))}node.expressions=substitutions;node.quasis=quasis;return this.finishNode(node,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(close,isPattern,isRecord7,refExpressionErrors){if(isRecord7){this.expectPlugin("recordAndTuple")}const oldInFSharpPipelineDirectBody=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=false;let sawProto=false;let first=true;const node=this.startNode();node.properties=[];this.next();while(!this.match(close)){if(first){first=false}else{this.expect(12);if(this.match(close)){this.addTrailingCommaExtraToNode(node);break}}let prop;if(isPattern){prop=this.parseBindingProperty()}else{prop=this.parsePropertyDefinition(refExpressionErrors);sawProto=this.checkProto(prop,isRecord7,sawProto,refExpressionErrors)}if(isRecord7&&!this.isObjectProperty(prop)&&prop.type!=="SpreadElement"){this.raise(Errors.InvalidRecordProperty,prop)}if(prop.shorthand){this.addExtra(prop,"shorthand",true)}node.properties.push(prop)}this.next();this.state.inFSharpPipelineDirectBody=oldInFSharpPipelineDirectBody;let type="ObjectExpression";if(isPattern){type="ObjectPattern"}else if(isRecord7){type="RecordExpression"}return this.finishNode(node,type)}addTrailingCommaExtraToNode(node){this.addExtra(node,"trailingComma",this.state.lastTokStartLoc.index);this.addExtra(node,"trailingCommaLoc",this.state.lastTokStartLoc,false)}maybeAsyncOrAccessorProp(prop){return!prop.computed&&prop.key.type==="Identifier"&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))}parsePropertyDefinition(refExpressionErrors){let decorators=[];if(this.match(26)){if(this.hasPlugin("decorators")){this.raise(Errors.UnsupportedPropertyDecorator,this.state.startLoc)}while(this.match(26)){decorators.push(this.parseDecorator())}}const prop=this.startNode();let isAsync=false;let isAccessor=false;let startLoc;if(this.match(21)){if(decorators.length)this.unexpected();return this.parseSpread()}if(decorators.length){prop.decorators=decorators;decorators=[]}prop.method=false;if(refExpressionErrors){startLoc=this.state.startLoc}let isGenerator=this.eat(55);this.parsePropertyNamePrefixOperator(prop);const containsEsc=this.state.containsEsc;this.parsePropertyName(prop,refExpressionErrors);if(!isGenerator&&!containsEsc&&this.maybeAsyncOrAccessorProp(prop)){const{key}=prop;const keyName=key.name;if(keyName==="async"&&!this.hasPrecedingLineBreak()){isAsync=true;this.resetPreviousNodeTrailingComments(key);isGenerator=this.eat(55);this.parsePropertyName(prop)}if(keyName==="get"||keyName==="set"){isAccessor=true;this.resetPreviousNodeTrailingComments(key);prop.kind=keyName;if(this.match(55)){isGenerator=true;this.raise(Errors.AccessorIsGenerator,this.state.curPosition(),{kind:keyName});this.next()}this.parsePropertyName(prop)}}return this.parseObjPropValue(prop,startLoc,isGenerator,isAsync,false,isAccessor,refExpressionErrors)}getGetterSetterExpectedParamCount(method){return method.kind==="get"?0:1}getObjectOrClassMethodParams(method){return method.params}checkGetterSetterParams(method){var _params;const paramCount=this.getGetterSetterExpectedParamCount(method);const params=this.getObjectOrClassMethodParams(method);if(params.length!==paramCount){this.raise(method.kind==="get"?Errors.BadGetterArity:Errors.BadSetterArity,method)}if(method.kind==="set"&&((_params=params[params.length-1])==null?void 0:_params.type)==="RestElement"){this.raise(Errors.BadSetterRestParameter,method)}}parseObjectMethod(prop,isGenerator,isAsync,isPattern,isAccessor){if(isAccessor){const finishedProp=this.parseMethod(prop,isGenerator,false,false,false,"ObjectMethod");this.checkGetterSetterParams(finishedProp);return finishedProp}if(isAsync||isGenerator||this.match(10)){if(isPattern)this.unexpected();prop.kind="method";prop.method=true;return this.parseMethod(prop,isGenerator,isAsync,false,false,"ObjectMethod")}}parseObjectProperty(prop,startLoc,isPattern,refExpressionErrors){prop.shorthand=false;if(this.eat(14)){prop.value=isPattern?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,refExpressionErrors);return this.finishObjectProperty(prop)}if(!prop.computed&&prop.key.type==="Identifier"){this.checkReservedWord(prop.key.name,prop.key.loc.start,true,false);if(isPattern){prop.value=this.parseMaybeDefault(startLoc,this.cloneIdentifier(prop.key))}else if(this.match(29)){const shorthandAssignLoc=this.state.startLoc;if(refExpressionErrors!=null){if(refExpressionErrors.shorthandAssignLoc===null){refExpressionErrors.shorthandAssignLoc=shorthandAssignLoc}}else{this.raise(Errors.InvalidCoverInitializedName,shorthandAssignLoc)}prop.value=this.parseMaybeDefault(startLoc,this.cloneIdentifier(prop.key))}else{prop.value=this.cloneIdentifier(prop.key)}prop.shorthand=true;return this.finishObjectProperty(prop)}}finishObjectProperty(node){return this.finishNode(node,"ObjectProperty")}parseObjPropValue(prop,startLoc,isGenerator,isAsync,isPattern,isAccessor,refExpressionErrors){const node=this.parseObjectMethod(prop,isGenerator,isAsync,isPattern,isAccessor)||this.parseObjectProperty(prop,startLoc,isPattern,refExpressionErrors);if(!node)this.unexpected();return node}parsePropertyName(prop,refExpressionErrors){if(this.eat(0)){prop.computed=true;prop.key=this.parseMaybeAssignAllowIn();this.expect(3)}else{const{type,value}=this.state;let key;if(tokenIsKeywordOrIdentifier(type)){key=this.parseIdentifier(true)}else{switch(type){case 135:key=this.parseNumericLiteral(value);break;case 134:key=this.parseStringLiteral(value);break;case 136:key=this.parseBigIntLiteral(value);break;case 139:{const privateKeyLoc=this.state.startLoc;if(refExpressionErrors!=null){if(refExpressionErrors.privateKeyLoc===null){refExpressionErrors.privateKeyLoc=privateKeyLoc}}else{this.raise(Errors.UnexpectedPrivateField,privateKeyLoc)}key=this.parsePrivateName();break}default:if(type===137){key=this.parseDecimalLiteral(value);break}this.unexpected()}}prop.key=key;if(type!==139){prop.computed=false}}}initFunction(node,isAsync){node.id=null;node.generator=false;node.async=isAsync}parseMethod(node,isGenerator,isAsync,isConstructor,allowDirectSuper,type,inClassScope=false){this.initFunction(node,isAsync);node.generator=isGenerator;this.scope.enter(514|16|(inClassScope?576:0)|(allowDirectSuper?32:0));this.prodParam.enter(functionFlags(isAsync,node.generator));this.parseFunctionParams(node,isConstructor);const finishedNode=this.parseFunctionBodyAndFinish(node,type,true);this.prodParam.exit();this.scope.exit();return finishedNode}parseArrayLike(close,isTuple,refExpressionErrors){if(isTuple){this.expectPlugin("recordAndTuple")}const oldInFSharpPipelineDirectBody=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=false;const node=this.startNode();this.next();node.elements=this.parseExprList(close,!isTuple,refExpressionErrors,node);this.state.inFSharpPipelineDirectBody=oldInFSharpPipelineDirectBody;return this.finishNode(node,isTuple?"TupleExpression":"ArrayExpression")}parseArrowExpression(node,params,isAsync,trailingCommaLoc){this.scope.enter(514|4);let flags=functionFlags(isAsync,false);if(!this.match(5)&&this.prodParam.hasIn){flags|=8}this.prodParam.enter(flags);this.initFunction(node,isAsync);const oldMaybeInArrowParameters=this.state.maybeInArrowParameters;if(params){this.state.maybeInArrowParameters=true;this.setArrowFunctionParameters(node,params,trailingCommaLoc)}this.state.maybeInArrowParameters=false;this.parseFunctionBody(node,true);this.prodParam.exit();this.scope.exit();this.state.maybeInArrowParameters=oldMaybeInArrowParameters;return this.finishNode(node,"ArrowFunctionExpression")}setArrowFunctionParameters(node,params,trailingCommaLoc){this.toAssignableList(params,trailingCommaLoc,false);node.params=params}parseFunctionBodyAndFinish(node,type,isMethod=false){this.parseFunctionBody(node,false,isMethod);return this.finishNode(node,type)}parseFunctionBody(node,allowExpression,isMethod=false){const isExpression=allowExpression&&!this.match(5);this.expressionScope.enter(newExpressionScope());if(isExpression){node.body=this.parseMaybeAssign();this.checkParams(node,false,allowExpression,false)}else{const oldStrict=this.state.strict;const oldLabels=this.state.labels;this.state.labels=[];this.prodParam.enter(this.prodParam.currentFlags()|4);node.body=this.parseBlock(true,false,hasStrictModeDirective=>{const nonSimple=!this.isSimpleParamList(node.params);if(hasStrictModeDirective&&nonSimple){this.raise(Errors.IllegalLanguageModeDirective,(node.kind==="method"||node.kind==="constructor")&&!!node.key?node.key.loc.end:node)}const strictModeChanged=!oldStrict&&this.state.strict;this.checkParams(node,!this.state.strict&&!allowExpression&&!isMethod&&!nonSimple,allowExpression,strictModeChanged);if(this.state.strict&&node.id){this.checkIdentifier(node.id,65,strictModeChanged)}});this.prodParam.exit();this.state.labels=oldLabels}this.expressionScope.exit()}isSimpleParameter(node){return node.type==="Identifier"}isSimpleParamList(params){for(let i=0,len=params.length;i<len;i++){if(!this.isSimpleParameter(params[i]))return false}return true}checkParams(node,allowDuplicates,isArrowFunction,strictModeChanged=true){const checkClashes=!allowDuplicates&&new Set;const formalParameters={type:"FormalParameters"};for(const param of node.params){this.checkLVal(param,formalParameters,5,checkClashes,strictModeChanged)}}parseExprList(close,allowEmpty,refExpressionErrors,nodeForExtra){const elts=[];let first=true;while(!this.eat(close)){if(first){first=false}else{this.expect(12);if(this.match(close)){if(nodeForExtra){this.addTrailingCommaExtraToNode(nodeForExtra)}this.next();break}}elts.push(this.parseExprListItem(close,allowEmpty,refExpressionErrors))}return elts}parseExprListItem(close,allowEmpty,refExpressionErrors,allowPlaceholder){let elt;if(this.match(12)){if(!allowEmpty){this.raise(Errors.UnexpectedToken,this.state.curPosition(),{unexpected:","})}elt=null}else if(this.match(21)){const spreadNodeStartLoc=this.state.startLoc;elt=this.parseParenItem(this.parseSpread(refExpressionErrors),spreadNodeStartLoc)}else if(this.match(17)){this.expectPlugin("partialApplication");if(!allowPlaceholder){this.raise(Errors.UnexpectedArgumentPlaceholder,this.state.startLoc)}const node=this.startNode();this.next();elt=this.finishNode(node,"ArgumentPlaceholder")}else{elt=this.parseMaybeAssignAllowInOrVoidPattern(close,refExpressionErrors,this.parseParenItem)}return elt}parseIdentifier(liberal){const node=this.startNode();const name=this.parseIdentifierName(liberal);return this.createIdentifier(node,name)}createIdentifier(node,name){node.name=name;node.loc.identifierName=name;return this.finishNode(node,"Identifier")}createIdentifierAt(node,name,endLoc){node.name=name;node.loc.identifierName=name;return this.finishNodeAt(node,"Identifier",endLoc)}parseIdentifierName(liberal){let name;const{startLoc,type}=this.state;if(tokenIsKeywordOrIdentifier(type)){name=this.state.value}else{this.unexpected()}const tokenIsKeyword2=tokenKeywordOrIdentifierIsKeyword(type);if(liberal){if(tokenIsKeyword2){this.replaceToken(132)}}else{this.checkReservedWord(name,startLoc,tokenIsKeyword2,false)}this.next();return name}checkReservedWord(word,startLoc,checkKeywords,isBinding){if(word.length>10){return}if(!canBeReservedWord(word)){return}if(checkKeywords&&isKeyword(word)){this.raise(Errors.UnexpectedKeyword,startLoc,{keyword:word});return}const reservedTest=!this.state.strict?isReservedWord:isBinding?isStrictBindReservedWord:isStrictReservedWord;if(reservedTest(word,this.inModule)){this.raise(Errors.UnexpectedReservedWord,startLoc,{reservedWord:word});return}else if(word==="yield"){if(this.prodParam.hasYield){this.raise(Errors.YieldBindingIdentifier,startLoc);return}}else if(word==="await"){if(this.prodParam.hasAwait){this.raise(Errors.AwaitBindingIdentifier,startLoc);return}if(this.scope.inStaticBlock){this.raise(Errors.AwaitBindingIdentifierInStaticBlock,startLoc);return}this.expressionScope.recordAsyncArrowParametersError(startLoc)}else if(word==="arguments"){if(this.scope.inClassAndNotInNonArrowFunction){this.raise(Errors.ArgumentsInClass,startLoc);return}}}recordAwaitIfAllowed(){const isAwaitAllowed=this.prodParam.hasAwait;if(isAwaitAllowed&&!this.scope.inFunction){this.state.hasTopLevelAwait=true}return isAwaitAllowed}parseAwait(startLoc){const node=this.startNodeAt(startLoc);this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter,node);if(this.eat(55)){this.raise(Errors.ObsoleteAwaitStar,node)}if(!this.scope.inFunction&&!(this.optionFlags&1)){if(this.isAmbiguousPrefixOrIdentifier()){this.ambiguousScriptDifferentAst=true}else{this.sawUnambiguousESM=true}}if(!this.state.soloAwait){node.argument=this.parseMaybeUnary(null,true)}return this.finishNode(node,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return true;const{type}=this.state;return type===53||type===10||type===0||tokenIsTemplate(type)||type===102&&!this.state.containsEsc||type===138||type===56||this.hasPlugin("v8intrinsic")&&type===54}parseYield(startLoc){const node=this.startNodeAt(startLoc);this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter,node);let delegating=false;let argument=null;if(!this.hasPrecedingLineBreak()){delegating=this.eat(55);switch(this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!delegating)break;default:argument=this.parseMaybeAssign()}}node.delegate=delegating;node.argument=argument;return this.finishNode(node,"YieldExpression")}parseImportCall(node){this.next();node.source=this.parseMaybeAssignAllowIn();node.options=null;if(this.eat(12)){if(!this.match(11)){node.options=this.parseMaybeAssignAllowIn();if(this.eat(12)){this.addTrailingCommaExtraToNode(node.options);if(!this.match(11)){do{this.parseMaybeAssignAllowIn()}while(this.eat(12)&&!this.match(11));this.raise(Errors.ImportCallArity,node)}}}else{this.addTrailingCommaExtraToNode(node.source)}}this.expect(11);return this.finishNode(node,"ImportExpression")}checkPipelineAtInfixOperator(left,leftStartLoc){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){if(left.type==="SequenceExpression"){this.raise(Errors.PipelineHeadSequenceExpression,leftStartLoc)}}}parseSmartPipelineBodyInStyle(childExpr,startLoc){if(this.isSimpleReference(childExpr)){const bodyNode=this.startNodeAt(startLoc);bodyNode.callee=childExpr;return this.finishNode(bodyNode,"PipelineBareFunction")}else{const bodyNode=this.startNodeAt(startLoc);this.checkSmartPipeTopicBodyEarlyErrors(startLoc);bodyNode.expression=childExpr;return this.finishNode(bodyNode,"PipelineTopicExpression")}}isSimpleReference(expression){switch(expression.type){case"MemberExpression":return!expression.computed&&this.isSimpleReference(expression.object);case"Identifier":return true;default:return false}}checkSmartPipeTopicBodyEarlyErrors(startLoc){if(this.match(19)){throw this.raise(Errors.PipelineBodyNoArrow,this.state.startLoc)}if(!this.topicReferenceWasUsedInCurrentContext()){this.raise(Errors.PipelineTopicUnused,startLoc)}}withTopicBindingContext(callback){const outerContextTopicState=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return callback()}finally{this.state.topicContext=outerContextTopicState}}withSmartMixTopicForbiddingContext(callback){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){const outerContextTopicState=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return callback()}finally{this.state.topicContext=outerContextTopicState}}else{return callback()}}withSoloAwaitPermittingContext(callback){const outerContextSoloAwaitState=this.state.soloAwait;this.state.soloAwait=true;try{return callback()}finally{this.state.soloAwait=outerContextSoloAwaitState}}allowInAnd(callback){const flags=this.prodParam.currentFlags();const prodParamToSet=8&~flags;if(prodParamToSet){this.prodParam.enter(flags|8);try{return callback()}finally{this.prodParam.exit()}}return callback()}disallowInAnd(callback){const flags=this.prodParam.currentFlags();const prodParamToClear=8&flags;if(prodParamToClear){this.prodParam.enter(flags&~8);try{return callback()}finally{this.prodParam.exit()}}return callback()}registerTopicReference(){this.state.topicContext.maxTopicIndex=0}topicReferenceIsAllowedInCurrentContext(){return this.state.topicContext.maxNumOfResolvableTopics>=1}topicReferenceWasUsedInCurrentContext(){return this.state.topicContext.maxTopicIndex!=null&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(prec){const startLoc=this.state.startLoc;this.state.potentialArrowAt=this.state.start;const oldInFSharpPipelineDirectBody=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=true;const ret=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),startLoc,prec);this.state.inFSharpPipelineDirectBody=oldInFSharpPipelineDirectBody;return ret}parseModuleExpression(){this.expectPlugin("moduleBlocks");const node=this.startNode();this.next();if(!this.match(5)){this.unexpected(null,5)}const program=this.startNodeAt(this.state.endLoc);this.next();const revertScopes=this.initializeScopes(true);this.enterInitialScopes();try{node.body=this.parseProgram(program,8,"module")}finally{revertScopes()}return this.finishNode(node,"ModuleExpression")}parseVoidPattern(refExpressionErrors){this.expectPlugin("discardBinding");const node=this.startNode();if(refExpressionErrors!=null){refExpressionErrors.voidPatternLoc=this.state.startLoc}this.next();return this.finishNode(node,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(close,refExpressionErrors,afterLeftParse){if(refExpressionErrors!=null&&this.match(88)){const nextCode=this.lookaheadCharCode();if(nextCode===44||nextCode===(close===3?93:close===8?125:41)||nextCode===61){return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(refExpressionErrors))}}return this.parseMaybeAssignAllowIn(refExpressionErrors,afterLeftParse)}parsePropertyNamePrefixOperator(prop){}};var loopLabel={kind:1};var switchLabel={kind:2};var loneSurrogate=/[\uD800-\uDFFF]/u;var keywordRelationalOperator=/in(?:stanceof)?/y;function babel7CompatTokens(tokens2,input,startIndex){for(let i=0;i<tokens2.length;i++){const token2=tokens2[i];const{type}=token2;if(typeof type==="number"){if(type===139){const{loc,start,value,end}=token2;const hashEndPos=start+1;const hashEndLoc=createPositionWithColumnOffset(loc.start,1);tokens2.splice(i,1,new Token({type:getExportedToken(27),value:"#",start,end:hashEndPos,startLoc:loc.start,endLoc:hashEndLoc}),new Token({type:getExportedToken(132),value,start:hashEndPos,end,startLoc:hashEndLoc,endLoc:loc.end}));i++;continue}if(tokenIsTemplate(type)){const{loc,start,value,end}=token2;const backquoteEnd=start+1;const backquoteEndLoc=createPositionWithColumnOffset(loc.start,1);let startToken;if(input.charCodeAt(start-startIndex)===96){startToken=new Token({type:getExportedToken(22),value:"`",start,end:backquoteEnd,startLoc:loc.start,endLoc:backquoteEndLoc})}else{startToken=new Token({type:getExportedToken(8),value:"}",start,end:backquoteEnd,startLoc:loc.start,endLoc:backquoteEndLoc})}let templateValue,templateElementEnd,templateElementEndLoc,endToken;if(type===24){templateElementEnd=end-1;templateElementEndLoc=createPositionWithColumnOffset(loc.end,-1);templateValue=value===null?null:value.slice(1,-1);endToken=new Token({type:getExportedToken(22),value:"`",start:templateElementEnd,end,startLoc:templateElementEndLoc,endLoc:loc.end})}else{templateElementEnd=end-2;templateElementEndLoc=createPositionWithColumnOffset(loc.end,-2);templateValue=value===null?null:value.slice(1,-2);endToken=new Token({type:getExportedToken(23),value:"${",start:templateElementEnd,end,startLoc:templateElementEndLoc,endLoc:loc.end})}tokens2.splice(i,1,startToken,new Token({type:getExportedToken(20),value:templateValue,start:backquoteEnd,end:templateElementEnd,startLoc:backquoteEndLoc,endLoc:templateElementEndLoc}),endToken);i+=2;continue}token2.type=getExportedToken(type)}}return tokens2}var StatementParser=class extends ExpressionParser{parseTopLevel(file2,program){file2.program=this.parseProgram(program,140,this.options.sourceType==="module"?"module":"script");file2.comments=this.comments;if(this.optionFlags&256){file2.tokens=babel7CompatTokens(this.tokens,this.input,this.startIndex)}return this.finishNode(file2,"File")}parseProgram(program,end,sourceType){program.sourceType=sourceType;program.interpreter=this.parseInterpreterDirective();this.parseBlockBody(program,true,true,end);if(this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0){for(const[localName,at]of Array.from(this.scope.undefinedExports)){this.raise(Errors.ModuleExportUndefined,at,{localName})}}this.addExtra(program,"topLevelAwait",this.state.hasTopLevelAwait)}let finishedProgram;if(end===140){finishedProgram=this.finishNode(program,"Program")}else{finishedProgram=this.finishNodeAt(program,"Program",createPositionWithColumnOffset(this.state.startLoc,-1))}return finishedProgram}stmtToDirective(stmt){const directive=this.castNodeTo(stmt,"Directive");const directiveLiteral=this.castNodeTo(stmt.expression,"DirectiveLiteral");const expressionValue=directiveLiteral.value;const raw=this.input.slice(this.offsetToSourcePos(directiveLiteral.start),this.offsetToSourcePos(directiveLiteral.end));const val=directiveLiteral.value=raw.slice(1,-1);this.addExtra(directiveLiteral,"raw",raw);this.addExtra(directiveLiteral,"rawValue",val);this.addExtra(directiveLiteral,"expressionValue",expressionValue);directive.value=directiveLiteral;delete stmt.expression;return directive}parseInterpreterDirective(){if(!this.match(28)){return null}const node=this.startNode();node.value=this.state.value;this.next();return this.finishNode(node,"InterpreterDirective")}isLet(){if(!this.isContextual(100)){return false}return this.hasFollowingBindingAtom()}isUsing(){if(!this.isContextual(107)){return false}return this.nextTokenIsIdentifierOnSameLine()}isForUsing(){if(!this.isContextual(107)){return false}const next=this.nextTokenInLineStart();const nextCh=this.codePointAtPos(next);if(this.isUnparsedContextual(next,"of")){const nextCharAfterOf=this.lookaheadCharCodeSince(next+2);if(nextCharAfterOf!==61&&nextCharAfterOf!==58&&nextCharAfterOf!==59){return false}}if(this.chStartsBindingIdentifier(nextCh,next)||this.isUnparsedContextual(next,"void")){return true}return false}nextTokenIsIdentifierOnSameLine(){const next=this.nextTokenInLineStart();const nextCh=this.codePointAtPos(next);return this.chStartsBindingIdentifier(nextCh,next)}isAwaitUsing(){if(!this.isContextual(96)){return false}let next=this.nextTokenInLineStart();if(this.isUnparsedContextual(next,"using")){next=this.nextTokenInLineStartSince(next+5);const nextCh=this.codePointAtPos(next);if(this.chStartsBindingIdentifier(nextCh,next)){return true}}return false}chStartsBindingIdentifier(ch,pos){if(isIdentifierStart(ch)){keywordRelationalOperator.lastIndex=pos;if(keywordRelationalOperator.test(this.input)){const endCh=this.codePointAtPos(keywordRelationalOperator.lastIndex);if(!isIdentifierChar(endCh)&&endCh!==92){return false}}return true}else if(ch===92){return true}else{return false}}chStartsBindingPattern(ch){return ch===91||ch===123}hasFollowingBindingAtom(){const next=this.nextTokenStart();const nextCh=this.codePointAtPos(next);return this.chStartsBindingPattern(nextCh)||this.chStartsBindingIdentifier(nextCh,next)}hasInLineFollowingBindingIdentifierOrBrace(){const next=this.nextTokenInLineStart();const nextCh=this.codePointAtPos(next);return nextCh===123||this.chStartsBindingIdentifier(nextCh,next)}allowsUsing(){return(this.scope.inModule||!this.scope.inTopLevel)&&!this.scope.inBareCaseStatement}parseModuleItem(){return this.parseStatementLike(1|2|4|8)}parseStatementListItem(){return this.parseStatementLike(2|4|(!this.options.annexB||this.state.strict?0:8))}parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction=false){let flags=0;if(this.options.annexB&&!this.state.strict){flags|=4;if(allowLabeledFunction){flags|=8}}return this.parseStatementLike(flags)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(flags){let decorators=null;if(this.match(26)){decorators=this.parseDecorators(true)}return this.parseStatementContent(flags,decorators)}parseStatementContent(flags,decorators){const startType=this.state.type;const node=this.startNode();const allowDeclaration=!!(flags&2);const allowFunctionDeclaration=!!(flags&4);const topLevel=flags&1;switch(startType){case 60:return this.parseBreakContinueStatement(node,true);case 63:return this.parseBreakContinueStatement(node,false);case 64:return this.parseDebuggerStatement(node);case 90:return this.parseDoWhileStatement(node);case 91:return this.parseForStatement(node);case 68:if(this.lookaheadCharCode()===46)break;if(!allowFunctionDeclaration){this.raise(this.state.strict?Errors.StrictFunction:this.options.annexB?Errors.SloppyFunctionAnnexB:Errors.SloppyFunction,this.state.startLoc)}return this.parseFunctionStatement(node,false,!allowDeclaration&&allowFunctionDeclaration);case 80:if(!allowDeclaration)this.unexpected();return this.parseClass(this.maybeTakeDecorators(decorators,node),true);case 69:return this.parseIfStatement(node);case 70:return this.parseReturnStatement(node);case 71:return this.parseSwitchStatement(node);case 72:return this.parseThrowStatement(node);case 73:return this.parseTryStatement(node);case 96:if(this.isAwaitUsing()){if(!this.allowsUsing()){this.raise(Errors.UnexpectedUsingDeclaration,node)}else if(!allowDeclaration){this.raise(Errors.UnexpectedLexicalDeclaration,node)}else if(!this.recordAwaitIfAllowed()){this.raise(Errors.AwaitUsingNotInAsyncContext,node)}this.next();return this.parseVarStatement(node,"await using")}break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace()){break}if(!this.allowsUsing()){this.raise(Errors.UnexpectedUsingDeclaration,this.state.startLoc)}else if(!allowDeclaration){this.raise(Errors.UnexpectedLexicalDeclaration,this.state.startLoc)}return this.parseVarStatement(node,"using");case 100:{if(this.state.containsEsc){break}const next=this.nextTokenStart();const nextCh=this.codePointAtPos(next);if(nextCh!==91){if(!allowDeclaration&&this.hasFollowingLineBreak())break;if(!this.chStartsBindingIdentifier(nextCh,next)&&nextCh!==123){break}}}case 75:{if(!allowDeclaration){this.raise(Errors.UnexpectedLexicalDeclaration,this.state.startLoc)}}case 74:{const kind=this.state.value;return this.parseVarStatement(node,kind)}case 92:return this.parseWhileStatement(node);case 76:return this.parseWithStatement(node);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(node);case 83:{const nextTokenCharCode=this.lookaheadCharCode();if(nextTokenCharCode===40||nextTokenCharCode===46){break}}case 82:{if(!(this.optionFlags&8)&&!topLevel){this.raise(Errors.UnexpectedImportExport,this.state.startLoc)}this.next();let result2;if(startType===83){result2=this.parseImport(node)}else{result2=this.parseExport(node,decorators)}this.assertModuleNodeAllowed(result2);return result2}default:{if(this.isAsyncFunction()){if(!allowDeclaration){this.raise(Errors.AsyncFunctionInSingleStatementContext,this.state.startLoc)}this.next();return this.parseFunctionStatement(node,true,!allowDeclaration&&allowFunctionDeclaration)}}}const maybeName=this.state.value;const expr=this.parseExpression();if(tokenIsIdentifier(startType)&&expr.type==="Identifier"&&this.eat(14)){return this.parseLabeledStatement(node,maybeName,expr,flags)}else{return this.parseExpressionStatement(node,expr,decorators)}}assertModuleNodeAllowed(node){if(!(this.optionFlags&8)&&!this.inModule){this.raise(Errors.ImportOutsideModule,node)}}decoratorsEnabledBeforeExport(){if(this.hasPlugin("decorators-legacy"))return true;return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==false}maybeTakeDecorators(maybeDecorators,classNode,exportNode){if(maybeDecorators){var _classNode$decorators;if((_classNode$decorators=classNode.decorators)!=null&&_classNode$decorators.length){if(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!=="boolean"){this.raise(Errors.DecoratorsBeforeAfterExport,classNode.decorators[0])}classNode.decorators.unshift(...maybeDecorators)}else{classNode.decorators=maybeDecorators}this.resetStartLocationFromNode(classNode,maybeDecorators[0]);if(exportNode)this.resetStartLocationFromNode(exportNode,classNode)}return classNode}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(allowExport){const decorators=[];do{decorators.push(this.parseDecorator())}while(this.match(26));if(this.match(82)){if(!allowExport){this.unexpected()}if(!this.decoratorsEnabledBeforeExport()){this.raise(Errors.DecoratorExportClass,this.state.startLoc)}}else if(!this.canHaveLeadingDecorator()){throw this.raise(Errors.UnexpectedLeadingDecorator,this.state.startLoc)}return decorators}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);const node=this.startNode();this.next();if(this.hasPlugin("decorators")){const startLoc=this.state.startLoc;let expr;if(this.match(10)){const startLoc2=this.state.startLoc;this.next();expr=this.parseExpression();this.expect(11);expr=this.wrapParenthesis(startLoc2,expr);const paramsStartLoc=this.state.startLoc;node.expression=this.parseMaybeDecoratorArguments(expr,startLoc2);if(this.getPluginOption("decorators","allowCallParenthesized")===false&&node.expression!==expr){this.raise(Errors.DecoratorArgumentsOutsideParentheses,paramsStartLoc)}}else{expr=this.parseIdentifier(false);while(this.eat(16)){const node2=this.startNodeAt(startLoc);node2.object=expr;if(this.match(139)){this.classScope.usePrivateName(this.state.value,this.state.startLoc);node2.property=this.parsePrivateName()}else{node2.property=this.parseIdentifier(true)}node2.computed=false;expr=this.finishNode(node2,"MemberExpression")}node.expression=this.parseMaybeDecoratorArguments(expr,startLoc)}}else{node.expression=this.parseExprSubscripts()}return this.finishNode(node,"Decorator")}parseMaybeDecoratorArguments(expr,startLoc){if(this.eat(10)){const node=this.startNodeAt(startLoc);node.callee=expr;node.arguments=this.parseCallExpressionArguments();this.toReferencedList(node.arguments);return this.finishNode(node,"CallExpression")}return expr}parseBreakContinueStatement(node,isBreak){this.next();if(this.isLineTerminator()){node.label=null}else{node.label=this.parseIdentifier();this.semicolon()}this.verifyBreakContinue(node,isBreak);return this.finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}verifyBreakContinue(node,isBreak){let i;for(i=0;i<this.state.labels.length;++i){const lab=this.state.labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind===1)){break}if(node.label&&isBreak)break}}if(i===this.state.labels.length){const type=isBreak?"BreakStatement":"ContinueStatement";this.raise(Errors.IllegalBreakContinue,node,{type})}}parseDebuggerStatement(node){this.next();this.semicolon();return this.finishNode(node,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);const val=this.parseExpression();this.expect(11);return val}parseDoWhileStatement(node){this.next();this.state.labels.push(loopLabel);node.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement());this.state.labels.pop();this.expect(92);node.test=this.parseHeaderExpression();this.eat(13);return this.finishNode(node,"DoWhileStatement")}parseForStatement(node){this.next();this.state.labels.push(loopLabel);let awaitAt=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()){awaitAt=this.state.startLoc;this.next()}this.scope.enter(0);this.expect(10);if(this.match(13)){if(awaitAt!==null){this.unexpected(awaitAt)}return this.parseFor(node,null)}const startsWithLet=this.isContextual(100);{const startsWithAwaitUsing=this.isAwaitUsing();const starsWithUsingDeclaration=startsWithAwaitUsing||this.isForUsing();const isLetOrUsing=startsWithLet&&this.hasFollowingBindingAtom()||starsWithUsingDeclaration;if(this.match(74)||this.match(75)||isLetOrUsing){const initNode=this.startNode();let kind;if(startsWithAwaitUsing){kind="await using";if(!this.recordAwaitIfAllowed()){this.raise(Errors.AwaitUsingNotInAsyncContext,this.state.startLoc)}this.next()}else{kind=this.state.value}this.next();this.parseVar(initNode,true,kind);const init2=this.finishNode(initNode,"VariableDeclaration");const isForIn=this.match(58);if(isForIn&&starsWithUsingDeclaration){this.raise(Errors.ForInUsing,init2)}if((isForIn||this.isContextual(102))&&init2.declarations.length===1){return this.parseForIn(node,init2,awaitAt)}if(awaitAt!==null){this.unexpected(awaitAt)}return this.parseFor(node,init2)}}const startsWithAsync=this.isContextual(95);const refExpressionErrors=new ExpressionErrors;const init=this.parseExpression(true,refExpressionErrors);const isForOf=this.isContextual(102);if(isForOf){if(startsWithLet){this.raise(Errors.ForOfLet,init)}if(awaitAt===null&&startsWithAsync&&init.type==="Identifier"){this.raise(Errors.ForOfAsync,init)}}if(isForOf||this.match(58)){this.checkDestructuringPrivate(refExpressionErrors);this.toAssignable(init,true);const type=isForOf?"ForOfStatement":"ForInStatement";this.checkLVal(init,{type});return this.parseForIn(node,init,awaitAt)}else{this.checkExpressionErrors(refExpressionErrors,true)}if(awaitAt!==null){this.unexpected(awaitAt)}return this.parseFor(node,init)}parseFunctionStatement(node,isAsync,isHangingDeclaration){this.next();return this.parseFunction(node,1|(isHangingDeclaration?2:0)|(isAsync?8:0))}parseIfStatement(node){this.next();node.test=this.parseHeaderExpression();node.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration();node.alternate=this.eat(66)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null;return this.finishNode(node,"IfStatement")}parseReturnStatement(node){if(!this.prodParam.hasReturn){this.raise(Errors.IllegalReturn,this.state.startLoc)}this.next();if(this.isLineTerminator()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")}parseSwitchStatement(node){this.next();node.discriminant=this.parseHeaderExpression();const cases=node.cases=[];this.expect(5);this.state.labels.push(switchLabel);this.scope.enter(256);let cur;for(let sawDefault;!this.match(8);){if(this.match(61)||this.match(65)){const isCase=this.match(61);if(cur)this.finishNode(cur,"SwitchCase");cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raise(Errors.MultipleDefaultsInSwitch,this.state.lastTokStartLoc)}sawDefault=true;cur.test=null}this.expect(14)}else{if(cur){cur.consequent.push(this.parseStatementListItem())}else{this.unexpected()}}}this.scope.exit();if(cur)this.finishNode(cur,"SwitchCase");this.next();this.state.labels.pop();return this.finishNode(node,"SwitchStatement")}parseThrowStatement(node){this.next();if(this.hasPrecedingLineBreak()){this.raise(Errors.NewlineAfterThrow,this.state.lastTokEndLoc)}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")}parseCatchClauseParam(){const param=this.parseBindingAtom();this.scope.enter(this.options.annexB&&param.type==="Identifier"?8:0);this.checkLVal(param,{type:"CatchClause"},9);return param}parseTryStatement(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.match(62)){const clause=this.startNode();this.next();if(this.match(10)){this.expect(10);clause.param=this.parseCatchClauseParam();this.expect(11)}else{clause.param=null;this.scope.enter(0)}clause.body=this.withSmartMixTopicForbiddingContext(()=>this.parseBlock(false,false));this.scope.exit();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(67)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(Errors.NoCatchOrFinally,node)}return this.finishNode(node,"TryStatement")}parseVarStatement(node,kind,allowMissingInitializer=false){this.next();this.parseVar(node,false,kind,allowMissingInitializer);this.semicolon();return this.finishNode(node,"VariableDeclaration")}parseWhileStatement(node){this.next();node.test=this.parseHeaderExpression();this.state.labels.push(loopLabel);node.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement());this.state.labels.pop();return this.finishNode(node,"WhileStatement")}parseWithStatement(node){if(this.state.strict){this.raise(Errors.StrictWith,this.state.startLoc)}this.next();node.object=this.parseHeaderExpression();node.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement());return this.finishNode(node,"WithStatement")}parseEmptyStatement(node){this.next();return this.finishNode(node,"EmptyStatement")}parseLabeledStatement(node,maybeName,expr,flags){for(const label of this.state.labels){if(label.name===maybeName){this.raise(Errors.LabelRedeclaration,expr,{labelName:maybeName})}}const kind=tokenIsLoop(this.state.type)?1:this.match(71)?2:null;for(let i=this.state.labels.length-1;i>=0;i--){const label=this.state.labels[i];if(label.statementStart===node.start){label.statementStart=this.sourceToOffsetPos(this.state.start);label.kind=kind}else{break}}this.state.labels.push({name:maybeName,kind,statementStart:this.sourceToOffsetPos(this.state.start)});node.body=flags&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(true):this.parseStatement();this.state.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")}parseExpressionStatement(node,expr,decorators){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")}parseBlock(allowDirectives=false,createNewLexicalScope=true,afterBlockParse){const node=this.startNode();if(allowDirectives){this.state.strictErrors.clear()}this.expect(5);if(createNewLexicalScope){this.scope.enter(0)}this.parseBlockBody(node,allowDirectives,false,8,afterBlockParse);if(createNewLexicalScope){this.scope.exit()}return this.finishNode(node,"BlockStatement")}isValidDirective(stmt){return stmt.type==="ExpressionStatement"&&stmt.expression.type==="StringLiteral"&&!stmt.expression.extra.parenthesized}parseBlockBody(node,allowDirectives,topLevel,end,afterBlockParse){const body=node.body=[];const directives=node.directives=[];this.parseBlockOrModuleBlockBody(body,allowDirectives?directives:void 0,topLevel,end,afterBlockParse)}parseBlockOrModuleBlockBody(body,directives,topLevel,end,afterBlockParse){const oldStrict=this.state.strict;let hasStrictModeDirective=false;let parsedNonDirective=false;while(!this.match(end)){const stmt=topLevel?this.parseModuleItem():this.parseStatementListItem();if(directives&&!parsedNonDirective){if(this.isValidDirective(stmt)){const directive=this.stmtToDirective(stmt);directives.push(directive);if(!hasStrictModeDirective&&directive.value.value==="use strict"){hasStrictModeDirective=true;this.setStrict(true)}continue}parsedNonDirective=true;this.state.strictErrors.clear()}body.push(stmt)}afterBlockParse==null||afterBlockParse.call(this,hasStrictModeDirective);if(!oldStrict){this.setStrict(false)}this.next()}parseFor(node,init){node.init=init;this.semicolon(false);node.test=this.match(13)?null:this.parseExpression();this.semicolon(false);node.update=this.match(11)?null:this.parseExpression();this.expect(11);node.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement());this.scope.exit();this.state.labels.pop();return this.finishNode(node,"ForStatement")}parseForIn(node,init,awaitAt){const isForIn=this.match(58);this.next();if(isForIn){if(awaitAt!==null)this.unexpected(awaitAt)}else{node.await=awaitAt!==null}if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||!this.options.annexB||this.state.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(Errors.ForInOfLoopInitializer,init,{type:isForIn?"ForInStatement":"ForOfStatement"})}if(init.type==="AssignmentPattern"){this.raise(Errors.InvalidLhs,init,{ancestor:{type:"ForStatement"}})}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssignAllowIn();this.expect(11);node.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement());this.scope.exit();this.state.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")}parseVar(node,isFor,kind,allowMissingInitializer=false){const declarations=node.declarations=[];node.kind=kind;for(;;){const decl=this.startNode();this.parseVarId(decl,kind);decl.init=!this.eat(29)?null:isFor?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn();if(decl.init===null&&!allowMissingInitializer){if(decl.id.type!=="Identifier"&&!(isFor&&(this.match(58)||this.isContextual(102)))){this.raise(Errors.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"})}else if((kind==="const"||kind==="using"||kind==="await using")&&!(this.match(58)||this.isContextual(102))){this.raise(Errors.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind})}}declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(12))break}return node}parseVarId(decl,kind){const id=this.parseBindingAtom();if(kind==="using"||kind==="await using"){if(id.type==="ArrayPattern"||id.type==="ObjectPattern"){this.raise(Errors.UsingDeclarationHasBindingPattern,id.loc.start)}}else{if(id.type==="VoidPattern"){this.raise(Errors.UnexpectedVoidPattern,id.loc.start)}}this.checkLVal(id,{type:"VariableDeclarator"},kind==="var"?5:8201);decl.id=id}parseAsyncFunctionExpression(node){return this.parseFunction(node,8)}parseFunction(node,flags=0){const hangingDeclaration=flags&2;const isDeclaration=!!(flags&1);const requireId=isDeclaration&&!(flags&4);const isAsync=!!(flags&8);this.initFunction(node,isAsync);if(this.match(55)){if(hangingDeclaration){this.raise(Errors.GeneratorInSingleStatementContext,this.state.startLoc)}this.next();node.generator=true}if(isDeclaration){node.id=this.parseFunctionId(requireId)}const oldMaybeInArrowParameters=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=false;this.scope.enter(514);this.prodParam.enter(functionFlags(isAsync,node.generator));if(!isDeclaration){node.id=this.parseFunctionId()}this.parseFunctionParams(node,false);this.withSmartMixTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(node,isDeclaration?"FunctionDeclaration":"FunctionExpression")});this.prodParam.exit();this.scope.exit();if(isDeclaration&&!hangingDeclaration){this.registerFunctionStatementId(node)}this.state.maybeInArrowParameters=oldMaybeInArrowParameters;return node}parseFunctionId(requireId){return requireId||tokenIsIdentifier(this.state.type)?this.parseIdentifier():null}parseFunctionParams(node,isConstructor){this.expect(10);this.expressionScope.enter(newParameterDeclarationScope());node.params=this.parseBindingList(11,41,2|(isConstructor?4:0));this.expressionScope.exit()}registerFunctionStatementId(node){if(!node.id)return;this.scope.declareName(node.id.name,!this.options.annexB||this.state.strict||node.generator||node.async?this.scope.treatFunctionsAsVar?5:8201:17,node.id.loc.start)}parseClass(node,isStatement,optionalId){this.next();const oldStrict=this.state.strict;this.state.strict=true;this.parseClassId(node,isStatement,optionalId);this.parseClassSuper(node);node.body=this.parseClassBody(!!node.superClass,oldStrict);return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(29)||this.match(13)||this.match(8)}isClassMethod(){return this.match(10)}nameIsConstructor(key){return key.type==="Identifier"&&key.name==="constructor"||key.type==="StringLiteral"&&key.value==="constructor"}isNonstaticConstructor(method){return!method.computed&&!method.static&&this.nameIsConstructor(method.key)}parseClassBody(hadSuperClass,oldStrict){this.classScope.enter();const state={hadConstructor:false,hadSuperClass};let decorators=[];const classBody=this.startNode();classBody.body=[];this.expect(5);this.withSmartMixTopicForbiddingContext(()=>{while(!this.match(8)){if(this.eat(13)){if(decorators.length>0){throw this.raise(Errors.DecoratorSemicolon,this.state.lastTokEndLoc)}continue}if(this.match(26)){decorators.push(this.parseDecorator());continue}const member=this.startNode();if(decorators.length){member.decorators=decorators;this.resetStartLocationFromNode(member,decorators[0]);decorators=[]}this.parseClassMember(classBody,member,state);if(member.kind==="constructor"&&member.decorators&&member.decorators.length>0){this.raise(Errors.DecoratorConstructor,member)}}});this.state.strict=oldStrict;this.next();if(decorators.length){throw this.raise(Errors.TrailingDecorator,this.state.startLoc)}this.classScope.exit();return this.finishNode(classBody,"ClassBody")}parseClassMemberFromModifier(classBody,member){const key=this.parseIdentifier(true);if(this.isClassMethod()){const method=member;method.kind="method";method.computed=false;method.key=key;method.static=false;this.pushClassMethod(classBody,method,false,false,false,false);return true}else if(this.isClassProperty()){const prop=member;prop.computed=false;prop.key=key;prop.static=false;classBody.body.push(this.parseClassProperty(prop));return true}this.resetPreviousNodeTrailingComments(key);return false}parseClassMember(classBody,member,state){const isStatic=this.isContextual(106);if(isStatic){if(this.parseClassMemberFromModifier(classBody,member)){return}if(this.eat(5)){this.parseClassStaticBlock(classBody,member);return}}this.parseClassMemberWithIsStatic(classBody,member,state,isStatic)}parseClassMemberWithIsStatic(classBody,member,state,isStatic){const publicMethod=member;const privateMethod=member;const publicProp=member;const privateProp=member;const accessorProp=member;const method=publicMethod;const publicMember=publicMethod;member.static=isStatic;this.parsePropertyNamePrefixOperator(member);if(this.eat(55)){method.kind="method";const isPrivateName=this.match(139);this.parseClassElementName(method);this.parsePostMemberNameModifiers(method);if(isPrivateName){this.pushClassPrivateMethod(classBody,privateMethod,true,false);return}if(this.isNonstaticConstructor(publicMethod)){this.raise(Errors.ConstructorIsGenerator,publicMethod.key)}this.pushClassMethod(classBody,publicMethod,true,false,false,false);return}const isContextual=!this.state.containsEsc&&tokenIsIdentifier(this.state.type);const key=this.parseClassElementName(member);const maybeContextualKw=isContextual?key.name:null;const isPrivate=this.isPrivateName(key);const maybeQuestionTokenStartLoc=this.state.startLoc;this.parsePostMemberNameModifiers(publicMember);if(this.isClassMethod()){method.kind="method";if(isPrivate){this.pushClassPrivateMethod(classBody,privateMethod,false,false);return}const isConstructor=this.isNonstaticConstructor(publicMethod);let allowsDirectSuper=false;if(isConstructor){publicMethod.kind="constructor";if(state.hadConstructor&&!this.hasPlugin("typescript")){this.raise(Errors.DuplicateConstructor,key)}if(isConstructor&&this.hasPlugin("typescript")&&member.override){this.raise(Errors.OverrideOnConstructor,key)}state.hadConstructor=true;allowsDirectSuper=state.hadSuperClass}this.pushClassMethod(classBody,publicMethod,false,false,isConstructor,allowsDirectSuper)}else if(this.isClassProperty()){if(isPrivate){this.pushClassPrivateProperty(classBody,privateProp)}else{this.pushClassProperty(classBody,publicProp)}}else if(maybeContextualKw==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(key);const isGenerator=this.eat(55);if(publicMember.optional){this.unexpected(maybeQuestionTokenStartLoc)}method.kind="method";const isPrivate2=this.match(139);this.parseClassElementName(method);this.parsePostMemberNameModifiers(publicMember);if(isPrivate2){this.pushClassPrivateMethod(classBody,privateMethod,isGenerator,true)}else{if(this.isNonstaticConstructor(publicMethod)){this.raise(Errors.ConstructorIsAsync,publicMethod.key)}this.pushClassMethod(classBody,publicMethod,isGenerator,true,false,false)}}else if((maybeContextualKw==="get"||maybeContextualKw==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(key);method.kind=maybeContextualKw;const isPrivate2=this.match(139);this.parseClassElementName(publicMethod);if(isPrivate2){this.pushClassPrivateMethod(classBody,privateMethod,false,false)}else{if(this.isNonstaticConstructor(publicMethod)){this.raise(Errors.ConstructorIsAccessor,publicMethod.key)}this.pushClassMethod(classBody,publicMethod,false,false,false,false)}this.checkGetterSetterParams(publicMethod)}else if(maybeContextualKw==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors");this.resetPreviousNodeTrailingComments(key);const isPrivate2=this.match(139);this.parseClassElementName(publicProp);this.pushClassAccessorProperty(classBody,accessorProp,isPrivate2)}else if(this.isLineTerminator()){if(isPrivate){this.pushClassPrivateProperty(classBody,privateProp)}else{this.pushClassProperty(classBody,publicProp)}}else{this.unexpected()}}parseClassElementName(member){const{type,value}=this.state;if((type===132||type===134)&&member.static&&value==="prototype"){this.raise(Errors.StaticPrototype,this.state.startLoc)}if(type===139){if(value==="constructor"){this.raise(Errors.ConstructorClassPrivateField,this.state.startLoc)}const key=this.parsePrivateName();member.key=key;return key}this.parsePropertyName(member);return member.key}parseClassStaticBlock(classBody,member){var _member$decorators;this.scope.enter(576|128|16);const oldLabels=this.state.labels;this.state.labels=[];this.prodParam.enter(0);const body=member.body=[];this.parseBlockOrModuleBlockBody(body,void 0,false,8);this.prodParam.exit();this.scope.exit();this.state.labels=oldLabels;classBody.body.push(this.finishNode(member,"StaticBlock"));if((_member$decorators=member.decorators)!=null&&_member$decorators.length){this.raise(Errors.DecoratorStaticBlock,member)}}pushClassProperty(classBody,prop){if(!prop.computed&&this.nameIsConstructor(prop.key)){this.raise(Errors.ConstructorClassField,prop.key)}classBody.body.push(this.parseClassProperty(prop))}pushClassPrivateProperty(classBody,prop){const node=this.parseClassPrivateProperty(prop);classBody.body.push(node);this.classScope.declarePrivateName(this.getPrivateNameSV(node.key),0,node.key.loc.start)}pushClassAccessorProperty(classBody,prop,isPrivate){if(!isPrivate&&!prop.computed&&this.nameIsConstructor(prop.key)){this.raise(Errors.ConstructorClassField,prop.key)}const node=this.parseClassAccessorProperty(prop);classBody.body.push(node);if(isPrivate){this.classScope.declarePrivateName(this.getPrivateNameSV(node.key),0,node.key.loc.start)}}pushClassMethod(classBody,method,isGenerator,isAsync,isConstructor,allowsDirectSuper){classBody.body.push(this.parseMethod(method,isGenerator,isAsync,isConstructor,allowsDirectSuper,"ClassMethod",true))}pushClassPrivateMethod(classBody,method,isGenerator,isAsync){const node=this.parseMethod(method,isGenerator,isAsync,false,false,"ClassPrivateMethod",true);classBody.body.push(node);const kind=node.kind==="get"?node.static?6:2:node.kind==="set"?node.static?5:1:0;this.declareClassPrivateMethodInScope(node,kind)}declareClassPrivateMethodInScope(node,kind){this.classScope.declarePrivateName(this.getPrivateNameSV(node.key),kind,node.key.loc.start)}parsePostMemberNameModifiers(methodOrProp){}parseClassPrivateProperty(node){this.parseInitializer(node);this.semicolon();return this.finishNode(node,"ClassPrivateProperty")}parseClassProperty(node){this.parseInitializer(node);this.semicolon();return this.finishNode(node,"ClassProperty")}parseClassAccessorProperty(node){this.parseInitializer(node);this.semicolon();return this.finishNode(node,"ClassAccessorProperty")}parseInitializer(node){this.scope.enter(576|16);this.expressionScope.enter(newExpressionScope());this.prodParam.enter(0);node.value=this.eat(29)?this.parseMaybeAssignAllowIn():null;this.expressionScope.exit();this.prodParam.exit();this.scope.exit()}parseClassId(node,isStatement,optionalId,bindingType=8331){if(tokenIsIdentifier(this.state.type)){node.id=this.parseIdentifier();if(isStatement){this.declareNameFromIdentifier(node.id,bindingType)}}else{if(optionalId||!isStatement){node.id=null}else{throw this.raise(Errors.MissingClassName,this.state.startLoc)}}}parseClassSuper(node){node.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(node,decorators){const maybeDefaultIdentifier=this.parseMaybeImportPhase(node,true);const hasDefault=this.maybeParseExportDefaultSpecifier(node,maybeDefaultIdentifier);const parseAfterDefault=!hasDefault||this.eat(12);const hasStar=parseAfterDefault&&this.eatExportStar(node);const hasNamespace=hasStar&&this.maybeParseExportNamespaceSpecifier(node);const parseAfterNamespace=parseAfterDefault&&(!hasNamespace||this.eat(12));const isFromRequired=hasDefault||hasStar;if(hasStar&&!hasNamespace){if(hasDefault)this.unexpected();if(decorators){throw this.raise(Errors.UnsupportedDecoratorExport,node)}this.parseExportFrom(node,true);this.sawUnambiguousESM=true;return this.finishNode(node,"ExportAllDeclaration")}const hasSpecifiers=this.maybeParseExportNamedSpecifiers(node);if(hasDefault&&parseAfterDefault&&!hasStar&&!hasSpecifiers){this.unexpected(null,5)}if(hasNamespace&&parseAfterNamespace){this.unexpected(null,98)}let hasDeclaration;if(isFromRequired||hasSpecifiers){hasDeclaration=false;if(decorators){throw this.raise(Errors.UnsupportedDecoratorExport,node)}this.parseExportFrom(node,isFromRequired)}else{hasDeclaration=this.maybeParseExportDeclaration(node)}if(isFromRequired||hasSpecifiers||hasDeclaration){var _node2$declaration;const node2=node;this.checkExport(node2,true,false,!!node2.source);if(((_node2$declaration=node2.declaration)==null?void 0:_node2$declaration.type)==="ClassDeclaration"){this.maybeTakeDecorators(decorators,node2.declaration,node2)}else if(decorators){throw this.raise(Errors.UnsupportedDecoratorExport,node)}this.sawUnambiguousESM=true;return this.finishNode(node2,"ExportNamedDeclaration")}if(this.eat(65)){const node2=node;const decl=this.parseExportDefaultExpression();node2.declaration=decl;if(decl.type==="ClassDeclaration"){this.maybeTakeDecorators(decorators,decl,node2)}else if(decorators){throw this.raise(Errors.UnsupportedDecoratorExport,node)}this.checkExport(node2,true,true);this.sawUnambiguousESM=true;return this.finishNode(node2,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(node){return this.eat(55)}maybeParseExportDefaultSpecifier(node,maybeDefaultIdentifier){if(maybeDefaultIdentifier||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",maybeDefaultIdentifier==null?void 0:maybeDefaultIdentifier.loc.start);const id=maybeDefaultIdentifier||this.parseIdentifier(true);const specifier=this.startNodeAtNode(id);specifier.exported=id;node.specifiers=[this.finishNode(specifier,"ExportDefaultSpecifier")];return true}return false}maybeParseExportNamespaceSpecifier(node){if(this.isContextual(93)){var _ref,_ref$specifiers;(_ref$specifiers=(_ref=node).specifiers)!=null?_ref$specifiers:_ref.specifiers=[];const specifier=this.startNodeAt(this.state.lastTokStartLoc);this.next();specifier.exported=this.parseModuleExportName();node.specifiers.push(this.finishNode(specifier,"ExportNamespaceSpecifier"));return true}return false}maybeParseExportNamedSpecifiers(node){if(this.match(5)){const node2=node;if(!node2.specifiers)node2.specifiers=[];const isTypeExport=node2.exportKind==="type";node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));node2.source=null;if(this.hasPlugin("importAssertions")){node2.assertions=[]}else{node2.attributes=[]}node2.declaration=null;return true}return false}maybeParseExportDeclaration(node){if(this.shouldParseExportDeclaration()){node.specifiers=[];node.source=null;if(this.hasPlugin("importAssertions")){node.assertions=[]}else{node.attributes=[]}node.declaration=this.parseExportDeclaration(node);return true}return false}isAsyncFunction(){if(!this.isContextual(95))return false;const next=this.nextTokenInLineStart();return this.isUnparsedContextual(next,"function")}parseExportDefaultExpression(){const expr=this.startNode();if(this.match(68)){this.next();return this.parseFunction(expr,1|4)}else if(this.isAsyncFunction()){this.next();this.next();return this.parseFunction(expr,1|4|8)}if(this.match(80)){return this.parseClass(expr,true,true)}if(this.match(26)){if(this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")===true){this.raise(Errors.DecoratorBeforeExport,this.state.startLoc)}return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false),this.startNode()),true,true)}if(this.match(75)||this.match(74)||this.isLet()||this.isUsing()||this.isAwaitUsing()){throw this.raise(Errors.UnsupportedDefaultExport,this.state.startLoc)}const res=this.parseMaybeAssignAllowIn();this.semicolon();return res}parseExportDeclaration(node){if(this.match(80)){const node2=this.parseClass(this.startNode(),true,false);return node2}return this.parseStatementListItem()}isExportDefaultSpecifier(){const{type}=this.state;if(tokenIsIdentifier(type)){if(type===95&&!this.state.containsEsc||type===100){return false}if((type===130||type===129)&&!this.state.containsEsc){const next2=this.nextTokenStart();const nextChar=this.input.charCodeAt(next2);if(nextChar===123||this.chStartsBindingIdentifier(nextChar,next2)&&!this.input.startsWith("from",next2)){this.expectOnePlugin(["flow","typescript"]);return false}}}else if(!this.match(65)){return false}const next=this.nextTokenStart();const hasFrom=this.isUnparsedContextual(next,"from");if(this.input.charCodeAt(next)===44||tokenIsIdentifier(this.state.type)&&hasFrom){return true}if(this.match(65)&&hasFrom){const nextAfterFrom=this.input.charCodeAt(this.nextTokenStartSince(next+4));return nextAfterFrom===34||nextAfterFrom===39}return false}parseExportFrom(node,expect){if(this.eatContextual(98)){node.source=this.parseImportSource();this.checkExport(node);this.maybeParseImportAttributes(node);this.checkJSONModuleImport(node)}else if(expect){this.unexpected()}this.semicolon()}shouldParseExportDeclaration(){const{type}=this.state;if(type===26){this.expectOnePlugin(["decorators","decorators-legacy"]);if(this.hasPlugin("decorators")){if(this.getPluginOption("decorators","decoratorsBeforeExport")===true){this.raise(Errors.DecoratorBeforeExport,this.state.startLoc)}return true}}if(this.isUsing()){this.raise(Errors.UsingDeclarationExport,this.state.startLoc);return true}if(this.isAwaitUsing()){this.raise(Errors.UsingDeclarationExport,this.state.startLoc);return true}return type===74||type===75||type===68||type===80||this.isLet()||this.isAsyncFunction()}checkExport(node,checkNames,isDefault,isFrom){if(checkNames){var _node$specifiers;if(isDefault){this.checkDuplicateExports(node,"default");if(this.hasPlugin("exportDefaultFrom")){var _declaration$extra;const declaration=node.declaration;if(declaration.type==="Identifier"&&declaration.name==="from"&&declaration.end-declaration.start===4&&!((_declaration$extra=declaration.extra)!=null&&_declaration$extra.parenthesized)){this.raise(Errors.ExportDefaultFromAsIdentifier,declaration)}}}else if((_node$specifiers=node.specifiers)!=null&&_node$specifiers.length){for(const specifier of node.specifiers){const{exported}=specifier;const exportName=exported.type==="Identifier"?exported.name:exported.value;this.checkDuplicateExports(specifier,exportName);if(!isFrom&&specifier.local){const{local}=specifier;if(local.type!=="Identifier"){this.raise(Errors.ExportBindingIsString,specifier,{localName:local.value,exportName})}else{this.checkReservedWord(local.name,local.loc.start,true,false);this.scope.checkLocalExport(local)}}}}else if(node.declaration){const decl=node.declaration;if(decl.type==="FunctionDeclaration"||decl.type==="ClassDeclaration"){const{id}=decl;if(!id)throw new Error("Assertion failure");this.checkDuplicateExports(node,id.name)}else if(decl.type==="VariableDeclaration"){for(const declaration of decl.declarations){this.checkDeclaration(declaration.id)}}}}}checkDeclaration(node){if(node.type==="Identifier"){this.checkDuplicateExports(node,node.name)}else if(node.type==="ObjectPattern"){for(const prop of node.properties){this.checkDeclaration(prop)}}else if(node.type==="ArrayPattern"){for(const elem of node.elements){if(elem){this.checkDeclaration(elem)}}}else if(node.type==="ObjectProperty"){this.checkDeclaration(node.value)}else if(node.type==="RestElement"){this.checkDeclaration(node.argument)}else if(node.type==="AssignmentPattern"){this.checkDeclaration(node.left)}}checkDuplicateExports(node,exportName){if(this.exportedIdentifiers.has(exportName)){if(exportName==="default"){this.raise(Errors.DuplicateDefaultExport,node)}else{this.raise(Errors.DuplicateExport,node,{exportName})}}this.exportedIdentifiers.add(exportName)}parseExportSpecifiers(isInTypeExport){const nodes=[];let first=true;this.expect(5);while(!this.eat(8)){if(first){first=false}else{this.expect(12);if(this.eat(8))break}const isMaybeTypeOnly=this.isContextual(130);const isString2=this.match(134);const node=this.startNode();node.local=this.parseModuleExportName();nodes.push(this.parseExportSpecifier(node,isString2,isInTypeExport,isMaybeTypeOnly))}return nodes}parseExportSpecifier(node,isString2,isInTypeExport,isMaybeTypeOnly){if(this.eatContextual(93)){node.exported=this.parseModuleExportName()}else if(isString2){node.exported=this.cloneStringLiteral(node.local)}else if(!node.exported){node.exported=this.cloneIdentifier(node.local)}return this.finishNode(node,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){const result2=this.parseStringLiteral(this.state.value);const surrogate=loneSurrogate.exec(result2.value);if(surrogate){this.raise(Errors.ModuleExportNameHasLoneSurrogate,result2,{surrogateCharCode:surrogate[0].charCodeAt(0)})}return result2}return this.parseIdentifier(true)}isJSONModuleImport(node){if(node.assertions!=null){return node.assertions.some(({key,value})=>{return value.value==="json"&&(key.type==="Identifier"?key.name==="type":key.value==="type")})}return false}checkImportReflection(node){const{specifiers}=node;const singleBindingType=specifiers.length===1?specifiers[0].type:null;if(node.phase==="source"){if(singleBindingType!=="ImportDefaultSpecifier"){this.raise(Errors.SourcePhaseImportRequiresDefault,specifiers[0].loc.start)}}else if(node.phase==="defer"){if(singleBindingType!=="ImportNamespaceSpecifier"){this.raise(Errors.DeferImportRequiresNamespace,specifiers[0].loc.start)}}else if(node.module){var _node$assertions;if(singleBindingType!=="ImportDefaultSpecifier"){this.raise(Errors.ImportReflectionNotBinding,specifiers[0].loc.start)}if(((_node$assertions=node.assertions)==null?void 0:_node$assertions.length)>0){this.raise(Errors.ImportReflectionHasAssertion,specifiers[0].loc.start)}}}checkJSONModuleImport(node){if(this.isJSONModuleImport(node)&&node.type!=="ExportAllDeclaration"){const{specifiers}=node;if(specifiers!=null){const nonDefaultNamedSpecifier=specifiers.find(specifier=>{let imported;if(specifier.type==="ExportSpecifier"){imported=specifier.local}else if(specifier.type==="ImportSpecifier"){imported=specifier.imported}if(imported!==void 0){return imported.type==="Identifier"?imported.name!=="default":imported.value!=="default"}});if(nonDefaultNamedSpecifier!==void 0){this.raise(Errors.ImportJSONBindingNotDefault,nonDefaultNamedSpecifier.loc.start)}}}}isPotentialImportPhase(isExport){if(isExport)return false;return this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(node,isExport,phase2,loc){if(isExport){return}if(phase2==="module"){this.expectPlugin("importReflection",loc);node.module=true}else if(this.hasPlugin("importReflection")){node.module=false}if(phase2==="source"){this.expectPlugin("sourcePhaseImports",loc);node.phase="source"}else if(phase2==="defer"){this.expectPlugin("deferredImportEvaluation",loc);node.phase="defer"}else if(this.hasPlugin("sourcePhaseImports")){node.phase=null}}parseMaybeImportPhase(node,isExport){if(!this.isPotentialImportPhase(isExport)){this.applyImportPhase(node,isExport,null);return null}const phaseIdentifier=this.startNode();const phaseIdentifierName=this.parseIdentifierName(true);const{type}=this.state;const isImportPhase=tokenIsKeywordOrIdentifier(type)?type!==98||this.lookaheadCharCode()===102:type!==12;if(isImportPhase){this.applyImportPhase(node,isExport,phaseIdentifierName,phaseIdentifier.loc.start);return null}else{this.applyImportPhase(node,isExport,null);return this.createIdentifier(phaseIdentifier,phaseIdentifierName)}}isPrecedingIdImportPhase(phase2){const{type}=this.state;return tokenIsIdentifier(type)?type!==98||this.lookaheadCharCode()===102:type!==12}parseImport(node){if(this.match(134)){return this.parseImportSourceAndAttributes(node)}return this.parseImportSpecifiersAndAfter(node,this.parseMaybeImportPhase(node,false))}parseImportSpecifiersAndAfter(node,maybeDefaultIdentifier){node.specifiers=[];const hasDefault=this.maybeParseDefaultImportSpecifier(node,maybeDefaultIdentifier);const parseNext=!hasDefault||this.eat(12);const hasStar=parseNext&&this.maybeParseStarImportSpecifier(node);if(parseNext&&!hasStar)this.parseNamedImportSpecifiers(node);this.expectContextual(98);return this.parseImportSourceAndAttributes(node)}parseImportSourceAndAttributes(node){var _node$specifiers2;(_node$specifiers2=node.specifiers)!=null?_node$specifiers2:node.specifiers=[];node.source=this.parseImportSource();this.maybeParseImportAttributes(node);this.checkImportReflection(node);this.checkJSONModuleImport(node);this.semicolon();this.sawUnambiguousESM=true;return this.finishNode(node,"ImportDeclaration")}parseImportSource(){if(!this.match(134))this.unexpected();return this.parseExprAtom()}parseImportSpecifierLocal(node,specifier,type){specifier.local=this.parseIdentifier();node.specifiers.push(this.finishImportSpecifier(specifier,type))}finishImportSpecifier(specifier,type,bindingType=8201){this.checkLVal(specifier.local,{type},bindingType);return this.finishNode(specifier,type)}parseImportAttributes(){this.expect(5);const attrs=[];const attrNames=new Set;do{if(this.match(8)){break}const node=this.startNode();const keyName=this.state.value;if(attrNames.has(keyName)){this.raise(Errors.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:keyName})}attrNames.add(keyName);if(this.match(134)){node.key=this.parseStringLiteral(keyName)}else{node.key=this.parseIdentifier(true)}this.expect(14);if(!this.match(134)){throw this.raise(Errors.ModuleAttributeInvalidValue,this.state.startLoc)}node.value=this.parseStringLiteral(this.state.value);attrs.push(this.finishNode(node,"ImportAttribute"))}while(this.eat(12));this.expect(8);return attrs}parseModuleAttributes(){const attrs=[];const attributes=new Set;do{const node=this.startNode();node.key=this.parseIdentifier(true);if(node.key.name!=="type"){this.raise(Errors.ModuleAttributeDifferentFromType,node.key)}if(attributes.has(node.key.name)){this.raise(Errors.ModuleAttributesWithDuplicateKeys,node.key,{key:node.key.name})}attributes.add(node.key.name);this.expect(14);if(!this.match(134)){throw this.raise(Errors.ModuleAttributeInvalidValue,this.state.startLoc)}node.value=this.parseStringLiteral(this.state.value);attrs.push(this.finishNode(node,"ImportAttribute"))}while(this.eat(12));return attrs}maybeParseImportAttributes(node){let attributes;var useWith=false;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40){return}this.next();if(this.hasPlugin("moduleAttributes")){attributes=this.parseModuleAttributes();this.addExtra(node,"deprecatedWithLegacySyntax",true)}else{attributes=this.parseImportAttributes()}useWith=true}else if(this.isContextual(94)&&!this.hasPrecedingLineBreak()){if(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")){this.raise(Errors.ImportAttributesUseAssert,this.state.startLoc)}if(!this.hasPlugin("importAssertions")){this.addExtra(node,"deprecatedAssertSyntax",true)}this.next();attributes=this.parseImportAttributes()}else{attributes=[]}if(!useWith&&this.hasPlugin("importAssertions")){node.assertions=attributes}else{node.attributes=attributes}}maybeParseDefaultImportSpecifier(node,maybeDefaultIdentifier){if(maybeDefaultIdentifier){const specifier=this.startNodeAtNode(maybeDefaultIdentifier);specifier.local=maybeDefaultIdentifier;node.specifiers.push(this.finishImportSpecifier(specifier,"ImportDefaultSpecifier"));return true}else if(tokenIsKeywordOrIdentifier(this.state.type)){this.parseImportSpecifierLocal(node,this.startNode(),"ImportDefaultSpecifier");return true}return false}maybeParseStarImportSpecifier(node){if(this.match(55)){const specifier=this.startNode();this.next();this.expectContextual(93);this.parseImportSpecifierLocal(node,specifier,"ImportNamespaceSpecifier");return true}return false}parseNamedImportSpecifiers(node){let first=true;this.expect(5);while(!this.eat(8)){if(first){first=false}else{if(this.eat(14)){throw this.raise(Errors.DestructureNamedImport,this.state.startLoc)}this.expect(12);if(this.eat(8))break}const specifier=this.startNode();const importedIsString=this.match(134);const isMaybeTypeOnly=this.isContextual(130);specifier.imported=this.parseModuleExportName();const importSpecifier=this.parseImportSpecifier(specifier,importedIsString,node.importKind==="type"||node.importKind==="typeof",isMaybeTypeOnly,void 0);node.specifiers.push(importSpecifier)}}parseImportSpecifier(specifier,importedIsString,isInTypeOnlyImport,isMaybeTypeOnly,bindingType){if(this.eatContextual(93)){specifier.local=this.parseIdentifier()}else{const{imported}=specifier;if(importedIsString){throw this.raise(Errors.ImportBindingIsString,specifier,{importName:imported.value})}this.checkReservedWord(imported.name,specifier.loc.start,true,true);if(!specifier.local){specifier.local=this.cloneIdentifier(imported)}}return this.finishImportSpecifier(specifier,"ImportSpecifier",bindingType)}isThisParam(param){return param.type==="Identifier"&&param.name==="this"}};var Parser=class extends StatementParser{constructor(options,input,pluginsMap){const normalizedOptions=getOptions(options);super(normalizedOptions,input);this.options=normalizedOptions;this.initializeScopes();this.plugins=pluginsMap;this.filename=normalizedOptions.sourceFilename;this.startIndex=normalizedOptions.startIndex;let optionFlags=0;if(normalizedOptions.allowAwaitOutsideFunction){optionFlags|=1}if(normalizedOptions.allowReturnOutsideFunction){optionFlags|=2}if(normalizedOptions.allowImportExportEverywhere){optionFlags|=8}if(normalizedOptions.allowSuperOutsideMethod){optionFlags|=16}if(normalizedOptions.allowUndeclaredExports){optionFlags|=64}if(normalizedOptions.allowNewTargetOutsideFunction){optionFlags|=4}if(normalizedOptions.allowYieldOutsideFunction){optionFlags|=32}if(normalizedOptions.ranges){optionFlags|=128}if(normalizedOptions.tokens){optionFlags|=256}if(normalizedOptions.createImportExpressions){optionFlags|=512}if(normalizedOptions.createParenthesizedExpressions){optionFlags|=1024}if(normalizedOptions.errorRecovery){optionFlags|=2048}if(normalizedOptions.attachComment){optionFlags|=4096}if(normalizedOptions.annexB){optionFlags|=8192}this.optionFlags=optionFlags}getScopeHandler(){return ScopeHandler}parse(){this.enterInitialScopes();const file2=this.startNode();const program=this.startNode();this.nextToken();file2.errors=null;const result2=this.parseTopLevel(file2,program);result2.errors=this.state.errors;result2.comments.length=this.state.commentsLen;return result2}};function parse5(input,options){var _options;if(((_options=options)==null?void 0:_options.sourceType)==="unambiguous"){options=Object.assign({},options);try{options.sourceType="module";const parser=getParser(options,input);const ast=parser.parse();if(parser.sawUnambiguousESM){return ast}if(parser.ambiguousScriptDifferentAst){try{options.sourceType="script";return getParser(options,input).parse()}catch(_unused){}}else{ast.program.sourceType="script"}return ast}catch(moduleError){try{options.sourceType="script";return getParser(options,input).parse()}catch(_unused2){}throw moduleError}}else{return getParser(options,input).parse()}}function parseExpression2(input,options){const parser=getParser(options,input);if(parser.options.strictMode){parser.state.strict=true}return parser.getExpression()}function generateExportedTokenTypes(internalTokenTypes){const tokenTypes2={};for(const typeName of Object.keys(internalTokenTypes)){tokenTypes2[typeName]=getExportedToken(internalTokenTypes[typeName])}return tokenTypes2}var tokTypes=generateExportedTokenTypes(tt);function getParser(options,input){let cls=Parser;const pluginsMap=new Map;if(options!=null&&options.plugins){for(const plugin of options.plugins){let name,opts;if(typeof plugin==="string"){name=plugin}else{[name,opts]=plugin}if(!pluginsMap.has(name)){pluginsMap.set(name,opts||{})}}validatePlugins(pluginsMap);cls=getParserClass(pluginsMap)}return new cls(options,input,pluginsMap)}var parserClassCache=new Map;function getParserClass(pluginsMap){const pluginList=[];for(const name of mixinPluginNames){if(pluginsMap.has(name)){pluginList.push(name)}}const key=pluginList.join("|");let cls=parserClassCache.get(key);if(!cls){cls=Parser;for(const plugin of pluginList){cls=mixinPlugins[plugin](cls)}parserClassCache.set(key,cls)}return cls}exports.parse=parse5;exports.parseExpression=parseExpression2;exports.tokTypes=tokTypes}});async function*reverseJsonlLines(handle,size,chunkSize=256*1024){if(!Number.isSafeInteger(size)||size<0||!Number.isSafeInteger(chunkSize)||chunkSize<1)throw new RangeError("Invalid JSONL snapshot size or chunk size");let cursor=size;const fragments=[];while(cursor>0){const start=Math.max(0,cursor-chunkSize);const bytes=Buffer.allocUnsafe(cursor-start);let filled=0;while(filled<bytes.length){const{bytesRead}=await handle.read(bytes,filled,bytes.length-filled,start+filled);if(bytesRead===0)throw new Error("JSONL snapshot was truncated during read");filled+=bytesRead}let end=bytes.length;for(let separator=bytes.lastIndexOf(10,end-1);separator>=0;separator=end===0?-1:bytes.lastIndexOf(10,end-1)){const suffix=bytes.subarray(separator+1,end);const line=fragments.length===0?suffix:Buffer.concat([suffix,...fragments.reverse()]);fragments.length=0;yield decodeLine(line);end=separator}if(end>0)fragments.push(bytes.subarray(0,end));cursor=start}if(fragments.length>0)yield decodeLine(Buffer.concat(fragments.reverse()));else if(size>0)yield""}function decodeLine(bytes){return(bytes.at(-1)===13?bytes.subarray(0,-1):bytes).toString("utf8")}var init_reverse_jsonl_lines=__esm({"../costs/src/reverse-jsonl-lines.ts"(){"use strict"}});import{open as open2}from"node:fs/promises";import{homedir}from"node:os";import{isAbsolute as isAbsolute3,join,relative as relative3,resolve as resolve4,sep as sep2}from"node:path";function sameCodexTokenSnapshot(left,right){return left!==null&&left.input===right.input&&left.cached_input===right.cached_input&&(left.cache_write_input??null)===(right.cache_write_input??null)&&left.output===right.output&&left.reasoning===right.reasoning&&left.total===right.total}function normalizeCodexPath(path){return path.replace(/\\/g,"/").toLowerCase()}function sessionDayRoots(sessionsRoot,now=new Date){const roots2=[];for(const offset of[0,1,2]){const date5=new Date(now);date5.setDate(now.getDate()-offset);roots2.push(join(sessionsRoot,"sessions",String(date5.getFullYear()),String(date5.getMonth()+1).padStart(2,"0"),String(date5.getDate()).padStart(2,"0")))}return roots2}async function recentCodexSessionFiles(sessionsRoot,now){const filesystem=new WorkspaceFileSystem(sessionsRoot);const files=(await Promise.all(sessionDayRoots(sessionsRoot,now??new Date).map(async absoluteRoot=>{const relativeRoot=absoluteRoot.replace(`${filesystem.root}\\`,"").replace(`${filesystem.root}/`,"");try{return await filesystem.listFiles(relativeRoot,".jsonl")}catch{return[]}}))).flat().sort();return{filesystem,files}}async function codexSessionFilesForWorkspace(workspaceRoot,options={}){const sessionsRoot=options.sessionsRoot??join(homedir(),".codex");const{filesystem,files:recentFiles}=await recentCodexSessionFiles(sessionsRoot,options.now);const transcriptRequested=hasTranscriptPath(options.transcriptPath);const transcriptPath=explicitTranscriptSessionPath(sessionsRoot,options.transcriptPath);if(options.sessionPaths!==void 0&&transcriptRequested){throw new Error("Codex transcript path cannot be combined with sessionPaths")}const explicitFiles=transcriptRequested?transcriptPath===null?[]:[transcriptPath]:options.sessionPaths??[];for(const path of explicitFiles){if(!/^sessions\/\d{4}\/\d{2}\/\d{2}\/[A-Za-z0-9._-]+\.jsonl$/u.test(path)){throw new Error(`Invalid explicit Codex session path: ${path}`)}}const files=transcriptRequested||explicitFiles.length>0?[...new Set(explicitFiles)].sort():recentFiles;const requestedThreadIds=new Set([options.threadId,...options.threadIds??[],...(options.invocations??[]).map(item=>item.threadId)].filter(value=>typeof value==="string"&&value.trim().length>0));const requestedAgentPath=normalizedText(options.agentPath);const requestedParentThreadId=normalizedText(options.parentThreadId);const candidates=transcriptRequested||requestedThreadIds.size===0||requestedAgentPath!==null||requestedParentThreadId!==null?files:files.filter(path=>[...requestedThreadIds].some(threadId=>path.includes(threadId)));if(candidates.length===0)return{filesystem,files:[]};const workspace=normalizeCodexPath(workspaceRoot);const matches=await Promise.all(candidates.map(async path=>{const identity=await readCodexSessionIdentity(filesystem,path);return identity!==null&&normalizeCodexPath(identity.cwd)===workspace&&(requestedAgentPath!==null?identity.agentPath===requestedAgentPath&&(requestedParentThreadId===null||identity.parentThreadId===requestedParentThreadId):requestedParentThreadId!==null?identity.parentThreadId===requestedParentThreadId:requestedThreadIds.size===0||identity.sessionId!==null&&requestedThreadIds.has(identity.sessionId))?path:null}));return{filesystem,files:matches.filter(path=>path!==null)}}function hasTranscriptPath(transcriptPath){return typeof transcriptPath==="string"&&transcriptPath.trim().length>0}function explicitTranscriptSessionPath(sessionsRoot,transcriptPath){if(transcriptPath===void 0||transcriptPath===null||transcriptPath.trim()===""){return null}if(transcriptPath.length>4096||!isAbsolute3(transcriptPath))return null;const root=resolve4(sessionsRoot);const candidate=resolve4(transcriptPath);const path=relative3(root,candidate).replace(/\\/g,"/");if(path===""||path===".."||path.startsWith(`..${sep2}`)||path.startsWith("../")||!/^sessions\/\d{4}\/\d{2}\/\d{2}\/[A-Za-z0-9._-]+\.jsonl$/u.test(path)){return null}return path}async function listActiveCodexInvocations(workspaceRoot,options={}){const sessionsRoot=options.sessionsRoot??join(homedir(),".codex");const{filesystem,files}=await codexSessionFilesForWorkspace(workspaceRoot,{...options,sessionsRoot});const requestedThreadIds=new Set([options.threadId,...options.threadIds??[],...(options.invocations??[]).map(item=>item.threadId)].filter(threadId=>typeof threadId==="string"&&threadId.length>0));const candidateFiles=files;const workspace=normalizeCodexPath(workspaceRoot);const activeInvocations=[];for(const path of candidateFiles){const active=await activeCodexInvocationFromSession(filesystem,path,workspace,requestedThreadIds);if(active!==null)activeInvocations.push(active)}return activeInvocations.sort((left,right)=>(right.startedAt??"").localeCompare(left.startedAt??""))}async function findActiveCodexInvocation(workspaceRoot,options={}){return(await listActiveCodexInvocations(workspaceRoot,options))[0]??null}async function listCodexInvocationLifecycles(workspaceRoot,options={}){const sessionsRoot=options.sessionsRoot??join(homedir(),".codex");const{filesystem,files}=await codexSessionFilesForWorkspace(workspaceRoot,{...options,sessionsRoot});const requestedThreadIds=new Set([options.threadId,...options.threadIds??[]].filter(threadId=>typeof threadId==="string"&&threadId.length>0));const candidateFiles=files;const workspace=normalizeCodexPath(workspaceRoot);const requestedTurnIds=new Set([options.turnId,...options.turnIds??[]].filter(turnId=>typeof turnId==="string"&&turnId.length>0));const lifecycles=(await Promise.all(candidateFiles.map(path=>{const turnsForPath=new Set((options.invocations??[]).filter(item=>path.includes(item.threadId)).map(item=>item.turnId));return codexInvocationLifecyclesFromSession(filesystem,path,workspace,requestedThreadIds,turnsForPath.size>0?turnsForPath:requestedTurnIds)}))).flat();return lifecycles.filter(item=>(requestedTurnIds.size===0||requestedTurnIds.has(item.turnId))&&(requestedThreadIds.size===0||requestedThreadIds.has(item.sessionId))).sort((left,right)=>(right.finishedAt??right.startedAt??"").localeCompare(left.finishedAt??left.startedAt??""))}async function listCodexInvocationReconciliationActivity(workspaceRoot,options={}){const{invocations:_invocations,turnId:_turnId,turnIds:_turnIds,...sessionOptions}=options;const allLifecycles=await listCodexInvocationLifecycles(workspaceRoot,{...sessionOptions,threadIds:[...options.threadIds??[],...(options.invocations??[]).map(item=>item.threadId)]});const requested=new Set((options.invocations??[]).map(item=>`${item.threadId}:${item.turnId}`));const lifecycles=requested.size===0?allLifecycles:allLifecycles.filter(item=>requested.has(`${item.sessionId}:${item.turnId}`));const latestBySession=new Map;for(const lifecycle of allLifecycles){const previous=latestBySession.get(lifecycle.sessionId);const occurredAt=lifecycle.finishedAt??lifecycle.startedAt??"";const previousAt=previous?.finishedAt??previous?.startedAt??"";if(previous===void 0||occurredAt>previousAt)latestBySession.set(lifecycle.sessionId,lifecycle)}const activeInvocations=[...latestBySession.values()].filter(item=>item.status==="active").map(item=>({sessionId:item.sessionId,turnId:item.turnId,sessionPath:item.sessionPath,startedAt:item.startedAt,userMessage:null,model:null,reasoningEffort:null,serviceTier:null,observedAt:item.observedAt}));return{lifecycles,activeInvocations}}async function codexInvocationLifecyclesFromSession(filesystem,path,workspace,requestedThreadIds,requestedTurnIds){const handle=await open2(filesystem.resolve(path),"r");try{const metadata2=await handle.stat();const firstBytes=Buffer.allocUnsafe(Math.min(metadata2.size,64*1024));await handle.read(firstBytes,0,firstBytes.length,0);const sessionRecord=firstBytes.toString("utf8").split(/\r?\n/).map(parseCodexRecord).find(record3=>record3?.type==="session_meta");const sessionPayload=sessionRecord?.payload??null;const spawn4=subagentSpawn(sessionPayload);const sessionId=spawn4!==null&&typeof sessionPayload?.id==="string"?sessionPayload.id:typeof sessionPayload?.session_id==="string"?sessionPayload.session_id:typeof sessionPayload?.id==="string"?sessionPayload.id:null;const agentPath=normalizedText(sessionPayload?.agent_path)??normalizedText(spawn4?.agent_path);const parentThreadId=normalizedText(sessionPayload?.parent_thread_id)??normalizedText(spawn4?.parent_thread_id);const agentRole=normalizedText(sessionPayload?.agent_role)??normalizedText(spawn4?.agent_role);const agentNickname=normalizedText(sessionPayload?.agent_nickname)??normalizedText(spawn4?.agent_nickname);if(sessionId===null||typeof sessionPayload?.cwd!=="string"||normalizeCodexPath(sessionPayload.cwd)!==workspace||requestedThreadIds.size>0&&!requestedThreadIds.has(sessionId)){return[]}const byTurn=new Map;const completed=new Map;let observedAt=null;for await(const line of reverseJsonlLines(handle,metadata2.size)){const record3=parseCodexRecord(line);if(observedAt===null&&typeof record3?.timestamp==="string"){observedAt=record3.timestamp}const payload=record3?.payload??null;const turnId=typeof payload?.turn_id==="string"?payload.turn_id:null;if(turnId===null||requestedTurnIds.size>0&&!requestedTurnIds.has(turnId)){continue}if(payload?.type==="turn_aborted"){completed.set(turnId,{at:typeof record3?.timestamp==="string"?record3.timestamp:null,status:payload.reason==="cancelled"?"cancelled":payload.reason==="interrupted"?"interrupted":"failed"})}else if(payload?.type==="task_complete"){completed.set(turnId,{at:typeof record3?.timestamp==="string"?record3.timestamp:null,status:payload.status==="cancelled"?"cancelled":payload.status==="interrupted"?"interrupted":payload.status==="failed"||payload.error!==void 0?"failed":"completed"})}else if(payload?.type==="task_started"&&!byTurn.has(turnId)){const terminal=completed.get(turnId);byTurn.set(turnId,{sessionId,turnId,sessionPath:path,agentPath,parentThreadId,agentRole,agentNickname,status:terminal?.status??"active",startedAt:typeof record3?.timestamp==="string"?record3.timestamp:null,finishedAt:terminal?.at??null,observedAt})}if(requestedTurnIds.size>0&&[...requestedTurnIds].every(id=>byTurn.has(id)))break}for(const[turnId,terminal]of completed){if(byTurn.has(turnId))continue;byTurn.set(turnId,{sessionId,turnId,sessionPath:path,agentPath,parentThreadId,agentRole,agentNickname,status:terminal.status,startedAt:null,finishedAt:terminal.at,observedAt})}return[...byTurn.values()]}finally{await handle.close()}}async function activeCodexInvocationFromSession(filesystem,path,workspace,requestedThreadIds){const identity=await readCodexSessionIdentity(filesystem,path);if(identity===null||identity.sessionId===null||normalizeCodexPath(identity.cwd)!==workspace||requestedThreadIds.size>0&&!requestedThreadIds.has(identity.sessionId)){return null}const handle=await open2(filesystem.resolve(path),"r");try{const metadata2=await handle.stat();let userMessage=null;let model=null;let reasoningEffort=null;let serviceTier=null;let observedAt=null;for await(const line of reverseJsonlLines(handle,metadata2.size)){const record3=parseCodexRecord(line);const payload=record3?.payload??null;if(observedAt===null&&typeof record3?.timestamp==="string"){observedAt=record3.timestamp}if(record3?.type==="turn_context"){if(typeof payload?.model==="string")model=payload.model;if(typeof payload?.effort==="string")reasoningEffort=payload.effort;if(typeof payload?.service_tier==="string")serviceTier=payload.service_tier}const settings=optionalRecord(payload?.thread_settings);if(record3?.type==="thread_settings_applied"||payload?.type==="thread_settings_applied"){if(typeof settings?.model==="string")model=settings.model;if(typeof settings?.reasoning_effort==="string")reasoningEffort=settings.reasoning_effort;if(typeof settings?.service_tier==="string")serviceTier=settings.service_tier}if(payload?.type==="user_message"&&userMessage===null){userMessage=typeof payload.message==="string"?payload.message.trim()||null:null}if(payload?.type==="task_complete")return null;if(payload?.type==="task_started"&&typeof payload.turn_id==="string"){return{sessionId:identity.sessionId,turnId:payload.turn_id,sessionPath:path,startedAt:typeof record3?.timestamp==="string"?record3.timestamp:null,userMessage,model,reasoningEffort,serviceTier,observedAt}}}return null}finally{await handle.close()}}async function readCodexSessionIdentity(filesystem,path){if(!await filesystem.exists(path))return null;const absolutePath=filesystem.resolve(path);const cached2=sessionIdentityCache.get(absolutePath);if(cached2!==void 0)return cached2;const handle=await open2(absolutePath,"r");try{const metadata2=await handle.stat();const firstBytes=Buffer.allocUnsafe(Math.min(metadata2.size,64*1024));await handle.read(firstBytes,0,firstBytes.length,0);const session=firstBytes.toString("utf8").split(/\r?\n/).map(parseCodexRecord).find(record3=>record3?.type==="session_meta");const payload=session?.payload??null;const spawn4=subagentSpawn(payload);const sessionId=spawn4!==null&&typeof payload?.id==="string"?payload.id:typeof payload?.session_id==="string"?payload.session_id:typeof payload?.id==="string"?payload.id:null;const identity=typeof payload?.cwd!=="string"?null:{sessionId,cwd:payload.cwd,agentPath:normalizedText(payload.agent_path)??normalizedText(spawn4?.agent_path),parentThreadId:normalizedText(payload.parent_thread_id)??normalizedText(spawn4?.parent_thread_id),agentRole:normalizedText(payload.agent_role)??normalizedText(spawn4?.agent_role),agentNickname:normalizedText(payload.agent_nickname)??normalizedText(spawn4?.agent_nickname)};sessionIdentityCache.set(absolutePath,identity);return identity}finally{await handle.close()}}function subagentSpawn(payload){const source=optionalRecord(payload?.source);const subagent=optionalRecord(source?.subagent);return optionalRecord(subagent?.thread_spawn)}function optionalRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:null}function normalizedText(value){return typeof value==="string"&&value.trim().length>0?value.trim():null}function parseCodexRecord(line){if(line.length===0)return null;try{const parsed=JSON.parse(line);if(typeof parsed!=="object"||parsed===null)return null;const record3=parsed;return{type:record3.type,timestamp:record3.timestamp,payload:typeof record3.payload==="object"&&record3.payload!==null?record3.payload:null}}catch{return null}}var sessionIdentityCache;var init_codex_session_activity=__esm({"../costs/src/codex-session-activity.ts"(){"use strict";init_src();init_reverse_jsonl_lines();sessionIdentityCache=new Map}});function inferProvider(model,client,agent){const lower=`${model} ${client} ${agent}`.toLowerCase();if(lower.includes("claude")||lower.includes("anthropic"))return"anthropic";if(lower.includes("gpt")||lower.includes("openai")||lower.includes("codex"))return"openai";return null}function calculateTokenPrice(input){const cacheWriteInputTokens=input.inputIncludesCacheWrites?input.cacheWriteInputTokens??0:0;const uncachedInputTokens=Math.max(input.inputTokens-input.cachedInputTokens-cacheWriteInputTokens,0);const inputUsd=roundCurrency(uncachedInputTokens/1e6*input.inputRate*input.inputMultiplier);const cachedInputUsd=input.cachedInputTokens===0?0:input.cachedInputRate===null?null:roundCurrency(input.cachedInputTokens/1e6*input.cachedInputRate*input.inputMultiplier);const cacheWriteInputUsd=input.cacheWriteInputTokens===null||input.cacheWriteInputTokens===void 0?null:input.cacheWriteInputTokens===0?0:input.cacheWriteInputRate===null||input.cacheWriteInputRate===void 0?null:roundCurrency(input.cacheWriteInputTokens/1e6*input.cacheWriteInputRate*input.inputMultiplier);const outputUsd=roundCurrency(input.outputTokens/1e6*input.outputRate*input.outputMultiplier);const reasoningUsd=0;return{inputUsd,cachedInputUsd,cacheWriteInputUsd,outputUsd,reasoningUsd}}var roundCurrency;var init_pricing_math=__esm({"../costs/src/pricing-math.ts"(){"use strict";roundCurrency=value=>Math.round(value*1e6)/1e6}});var init_invocation_summary_aggregation=__esm({"../costs/src/invocation-summary-aggregation.ts"(){"use strict"}});function aggregateSegmentUsage(segment2){return{input:sumComplete(segment2.loops.map(loop=>loop.usage.input)),cached_input:sumComplete(segment2.loops.map(loop=>loop.usage.cached_input)),cache_write_input:sumComplete(segment2.loops.map(loop=>loop.usage.cache_write_input??null)),output:sumComplete(segment2.loops.map(loop=>loop.usage.output)),reasoning:sumComplete(segment2.loops.map(loop=>loop.usage.reasoning)),total:sumComplete(segment2.loops.map(loop=>{if(loop.usage.total!==null)return loop.usage.total;return loop.usage.input!==null&&loop.usage.output!==null?loop.usage.input+loop.usage.output:null})),source:"provider_reported"}}function cumulativeUsageDelta(previous,current){const resetEpoch=previous!==null&&["input","cached_input","cache_write_input","output","reasoning","total"].some(component=>typeof previous[component]==="number"&&typeof current[component]==="number"&&current[component]<previous[component]);if(resetEpoch)return current;const delta=component=>{const value=current[component];if(typeof value!=="number")return null;const baseline=previous?.[component];if(typeof baseline!=="number")return value;return value>=baseline?value-baseline:value};return{input:delta("input"),cached_input:delta("cached_input"),cache_write_input:delta("cache_write_input"),output:delta("output"),reasoning:delta("reasoning"),total:delta("total"),source:"provider_reported"}}function tokenUsageFromUnknown(value){if(typeof value!=="object"||value===null)return null;const usage=value;return{input:finiteToken(usage.input_tokens),cached_input:finiteToken(usage.cached_input_tokens),cache_write_input:finiteToken(usage.cache_write_input_tokens),output:finiteToken(usage.output_tokens),reasoning:finiteToken(usage.reasoning_output_tokens),total:finiteToken(usage.total_tokens),source:"provider_reported"}}function tokenUsageFromCodexRecord(value){return tokenUsageFromUnknown(value)}function finiteToken(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?value:null}function hasObservedTokenDelta(usage){return[usage.input,usage.cached_input,usage.cache_write_input,usage.output,usage.reasoning,usage.total].some(value=>typeof value==="number"&&value>0)}function sumComplete(values){return values.length>0&&values.every(value=>value!==null)?values.reduce((sum,value)=>sum+(value??0),0):null}var init_segment_usage=__esm({"../costs/src/segment-usage.ts"(){"use strict"}});var init_run_telemetry=__esm({"../costs/src/run-telemetry.ts"(){"use strict"}});var init_telemetry_repository=__esm({"../costs/src/telemetry-repository.ts"(){"use strict";init_src2()}});function normalizeBilledFact(input){const legacy2=input.billed_amount===void 0;return{amount:legacy2?input.observed_cost_usd:input.billed_amount??null,currency:legacy2?null:input.billed_currency??null,provenance:legacy2?"legacy_unverified":input.billed_provenance??"unavailable",source_id:legacy2?null:input.billed_source_id??null,billed_at:legacy2?null:input.billed_at??null}}function normalizeBaselineBilledFact(input){const legacy2=input.baseline_billed_amount===void 0;return{amount:legacy2?input.baseline_observed_cost_usd:input.baseline_billed_amount??null,currency:legacy2?null:input.baseline_billed_currency??null,provenance:legacy2?"legacy_unverified":input.baseline_billed_provenance??"unavailable",source_id:legacy2?null:input.baseline_billed_source_id??null,billed_at:legacy2?null:input.baseline_billed_at??null}}var init_task_cohort_billed_facts=__esm({"../costs/src/task-cohort-billed-facts.ts"(){"use strict"}});function hasObservedContextComparison(input){return input.context_budget_tokens!==null&&input.context_budget_tokens!==void 0&&input.cached_context_tokens!==null&&input.cached_context_tokens!==void 0&&input.baseline_context_budget_tokens!==null&&input.baseline_context_budget_tokens!==void 0&&input.baseline_cached_context_tokens!==null&&input.baseline_cached_context_tokens!==void 0}function hasDeclaredEquivalence(input){return typeof input.equivalence_evidence_id==="string"&&input.equivalence_evidence_id.trim().length>0&&typeof input.baseline_equivalence_evidence_id==="string"&&input.baseline_equivalence_evidence_id.trim().length>0}function hasVerifiedEquivalence(input){return hasDeclaredEquivalence(input)&&input.equivalence_evidence_verified===true&&input.baseline_equivalence_evidence_verified===true}var init_task_cohort_dimensions=__esm({"../costs/src/task-cohort-dimensions.ts"(){"use strict"}});function collectCompletedTaskCostCohortV2(input){const zoneValid=isTimeZone(input.timezone);const start=parseInstant(input.interval.start);const end=parseInstant(input.interval.end);const exclusions=[];const intervalCandidates=[...input.tasks].sort((a,b)=>a.task_id.localeCompare(b.task_id)).filter(task=>{if(!task.completed){exclusions.push({task_id:task.task_id,reason:"not_completed"});return false}const completedAt=task.completed_at===null?null:parseInstant(task.completed_at);if(!zoneValid||start===null||end===null||completedAt===null){exclusions.push({task_id:task.task_id,reason:"invalid_timestamp"});return false}if(completedAt<start||completedAt>end){exclusions.push({task_id:task.task_id,reason:"outside_interval"});return false}return true});const candidates=terminalAttempts(intervalCandidates,exclusions);const baselineIdentities=new Set(candidates.map(task=>JSON.stringify([task.baseline_task_id,task.baseline_attempt_id,task.baseline_equivalence_id,task.equivalence_evidence_id,task.baseline_equivalence_evidence_id,task.baseline_billed_amount,task.baseline_billed_currency,task.baseline_billed_provenance,task.baseline_billed_source_id,task.baseline_billed_at])));const baselineConsistent=candidates.length>0&&baselineIdentities.size===1;const tasks=candidates.map(task=>{const normalized=normalizeBilledFact(task);const baselineFact=normalizeBaselineBilledFact(task);const cohort=completedTaskCostCohortV2({...task,observed_cost_usd:normalized.amount,baseline_observed_cost_usd:baselineFact.amount});const qualityFailed=task.quality_score!==null&&task.quality_floor!==null&&task.quality_score<task.quality_floor;const equivalenceEvidenceStatus=hasVerifiedEquivalence(task)?"verified":hasDeclaredEquivalence(task)?"declared_unverified":"unavailable";return{...cohort,completed_at:task.completed_at,attempt:task.attempt,model:task.model,reasoning_effort:task.reasoning_effort,equivalence_evidence_id:task.equivalence_evidence_id??null,equivalence_evidence_status:equivalenceEvidenceStatus,baseline_equivalence_evidence_id:task.baseline_equivalence_evidence_id??null,context_budget_tokens:task.context_budget_tokens??null,cached_context_tokens:task.cached_context_tokens??null,baseline_context_budget_tokens:task.baseline_context_budget_tokens??null,baseline_cached_context_tokens:task.baseline_cached_context_tokens??null,billed_amount:normalized.amount,billed_currency:normalized.currency,billed_provenance:normalized.provenance,billed_source_id:normalized.source_id,billed_at:normalized.billed_at,baseline_billed_amount:baselineFact.amount,baseline_billed_currency:baselineFact.currency,baseline_billed_provenance:baselineFact.provenance,baseline_billed_source_id:baselineFact.source_id,baseline_billed_at:baselineFact.billed_at,status:task.attempt===null||task.attempt_id===null||task.attempt_id===void 0||task.baseline_task_id===null||task.baseline_attempt_id===null||task.baseline_attempt_id===void 0||!baselineConsistent||task.equivalence_key!==input.equivalence_key||input.equivalence_key===void 0||input.equivalence_key===null||task.baseline_equivalence_id!==input.equivalence_key||!hasVerifiedEquivalence(task)||task.model===null||task.reasoning_effort===null||task.rework_count===null||!isComparableBilledFact(normalized)||!isComparableBilledFact(baselineFact)||qualityFailed?"unavailable":cohort.status}});for(const task of tasks.filter(task2=>task2.status==="unavailable")){const qualityFailed=task.quality_score!==null&&task.quality_floor!==null&&task.quality_score<task.quality_floor;exclusions.push(!baselineConsistent?{task_id:task.task_id,reason:"baseline_mismatch",field:"baseline_identity"}:qualityFailed?{task_id:task.task_id,reason:"quality_failed",field:"quality_score"}:{task_id:task.task_id,reason:"incomplete_comparison",field:task.equivalence_evidence_status!=="verified"?"equivalence_evidence":task.billed_provenance!=="observed"||task.billed_currency!=="USD"||task.billed_source_id===null||task.billed_at===null||parseInstant(task.billed_at)===null?"billed_fact":"baseline_billed_fact",provenance:task.billed_provenance})}const available=tasks.length>0&&tasks.every(task=>task.status==="available");const ratio=covered=>tasks.length===0?null:covered/tasks.length;const sum=values=>values.some(value=>value===null)?null:values.reduce((total,value)=>total+(value??0),0);const observed=available?sum(tasks.map(task=>task.observed_cost_usd)):null;const baseline=available?sum(tasks.map(task=>task.baseline_observed_cost_usd)):null;return{timezone:input.timezone,interval:input.interval,status:available?"available":"unavailable",population:{completed_in_interval:intervalCandidates.length,included:available?tasks.length:0,excluded:exclusions.length},tasks,exclusions,summary:{observed_cost_usd:observed,baseline_observed_cost_usd:baseline,cost_delta_usd:observed===null||baseline===null?null:baseline-observed,savings_percent:observed===null||baseline===null||baseline<=0?null:(baseline-observed)/baseline*100,rework_count:available?sum(tasks.map(task=>task.rework_count)):null},coverage:{eligible:candidates.length,comparable:tasks.filter(task=>task.status==="available").length,candidate_billed:{covered:tasks.filter(task=>task.billed_provenance==="observed"&&task.billed_currency==="USD"&&task.billed_source_id!==null&&task.billed_at!==null&&parseInstant(task.billed_at)!==null).length,ratio:ratio(tasks.filter(task=>task.billed_provenance==="observed"&&task.billed_currency==="USD"&&task.billed_source_id!==null&&task.billed_at!==null&&parseInstant(task.billed_at)!==null).length)},baseline_billed:{covered:tasks.filter(task=>task.baseline_billed_provenance==="observed"&&task.baseline_billed_currency==="USD"&&task.baseline_billed_source_id!==null&&task.baseline_billed_at!==null&&parseInstant(task.baseline_billed_at)!==null).length,ratio:ratio(tasks.filter(task=>task.baseline_billed_provenance==="observed"&&task.baseline_billed_currency==="USD"&&task.baseline_billed_source_id!==null&&task.baseline_billed_at!==null&&parseInstant(task.baseline_billed_at)!==null).length)},quality:{covered:tasks.filter(task=>task.quality_score!==null&&task.quality_floor!==null&&task.quality_score>=task.quality_floor).length,ratio:ratio(tasks.filter(task=>task.quality_score!==null&&task.quality_floor!==null&&task.quality_score>=task.quality_floor).length)},required_dimensions:{covered:tasks.filter(task=>task.attempt!==null&&task.model!==null&&task.reasoning_effort!==null&&task.rework_count!==null).length,ratio:ratio(tasks.filter(task=>task.attempt!==null&&task.model!==null&&task.reasoning_effort!==null&&task.rework_count!==null).length)},equivalence_evidence:{covered:tasks.filter(task=>task.equivalence_evidence_status==="verified").length,ratio:ratio(tasks.filter(task=>task.equivalence_evidence_status==="verified").length)},context:{covered:tasks.filter(task=>hasObservedContextComparison(task)).length,ratio:ratio(tasks.filter(task=>hasObservedContextComparison(task)).length)}}}}function isComparableBilledFact(fact){return fact.amount!==null&&fact.amount>=0&&fact.currency==="USD"&&fact.provenance==="observed"&&fact.source_id!==null&&fact.billed_at!==null&&parseInstant(fact.billed_at)!==null}function terminalAttempts(tasks,exclusions){const selected=new Map;for(const task of[...tasks].sort((left,right)=>left.task_id.localeCompare(right.task_id)||(right.attempt??-1)-(left.attempt??-1)||String(right.completed_at).localeCompare(String(left.completed_at)))){if(!selected.has(task.task_id))selected.set(task.task_id,task);else exclusions.push({task_id:task.task_id,reason:"duplicate_attempt",field:"attempt"})}return[...selected.values()].sort((left,right)=>left.task_id.localeCompare(right.task_id))}function parseInstant(value){const match=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))$/.exec(value);if(match===null)return null;const year=Number(match[1]);const month=Number(match[2]);const day=Number(match[3]);const hour=Number(match[4]);const minute=Number(match[5]);const second=Number(match[6]);const offsetHour=match[8]===void 0?0:Number(match[8]);const offsetMinute=match[9]===void 0?0:Number(match[9]);const days=month>=1&&month<=12?new Date(Date.UTC(year,month,0)).getUTCDate():0;if(day<1||day>days||hour>23||minute>59||second>59||offsetHour>23||offsetMinute>59)return null;const instant=Date.parse(value);return Number.isFinite(instant)?instant:null}function isTimeZone(value){try{new Intl.DateTimeFormat("en-US",{timeZone:value});return true}catch{return false}}function completedTaskCostCohortV2(input){const observedCost=input.observed_cost_usd;const baselineCost=input.baseline_observed_cost_usd;const comparable=input.completed&&input.baseline_task_id!==null&&input.baseline_equivalence_id!==null&&observedCost!==null&&baselineCost!==null&&baselineCost>0&&input.quality_score!==null&&input.quality_floor!==null&&input.quality_score>=input.quality_floor;return{task_id:input.task_id,baseline_task_id:input.baseline_task_id,baseline_equivalence_id:input.baseline_equivalence_id,status:comparable?"available":"unavailable",observed_cost_usd:observedCost,baseline_observed_cost_usd:baselineCost,cost_delta_usd:comparable&&baselineCost!==null&&observedCost!==null?baselineCost-observedCost:null,savings_percent:comparable&&baselineCost!==null&&observedCost!==null?(baselineCost-observedCost)/baselineCost*100:null,quality_score:input.quality_score,quality_floor:input.quality_floor,rework_count:input.rework_count}}function aggregateRunV2Usage(input,scopeId=null){const runs=uniqueRuns(input).filter(run=>scopeId===null||matchesScope(run,scopeId));const usage=uniqueEffectiveUsage(runs);return{scope_id:scopeId,run_count:runs.length,run_coverage:{usage:runCoverage(runs,run=>run.effective_usage_records.length>0),tokens:runCoverage(runs,run=>run.effective_usage_records.some(event=>tokenTotal(event)!==null)),usd:runCoverage(runs,run=>run.effective_usage_records.some(event=>event.cost.usd!==null)),brl:runCoverage(runs,run=>run.effective_usage_records.some(event=>event.cost.brl!==null))},attribution:{attributed_runs:runs.filter(run=>run.run.attribution_status==="attributed").length,legacy_unattributed_runs:runs.filter(run=>run.run.attribution_status==="legacy_unattributed").length},conversation:usageBucket(usage.filter(({event})=>event.phase==="conversation")),planning:usageBucket(usage.filter(({event})=>event.phase==="planning")),execution:usageBucket(usage.filter(({event})=>event.phase==="execution")),total:usageBucket(usage),work_types:{new:usageBucket(usage.filter(({run})=>run.run.work_type==="new")),rework:usageBucket(usage.filter(({run})=>run.run.work_type==="rework"))},cohorts:{v2_live:usageBucket(usage.filter(({run})=>run.run.attribution_status==="attributed")),legacy_imported:usageBucket(usage.filter(({run})=>run.run.attribution_status==="legacy_unattributed"))}}}function runCoverage(runs,known2){const knownRuns=runs.filter(known2).length;const unknownRuns=runs.length-knownRuns;return{known_runs:knownRuns,unknown_runs:unknownRuns,complete:unknownRuns===0,coverage_ratio:runs.length===0?1:knownRuns/runs.length}}function uniqueRuns(input){const byId2=new Map;for(const run of input){const existing=byId2.get(run.run.run_id);if(existing!==void 0){if(JSON.stringify(existing.records)!==JSON.stringify(run.records)){throw new Error(`Divergent duplicate Run V2 fold: ${run.run.run_id}`)}continue}byId2.set(run.run.run_id,run)}return[...byId2.values()]}function uniqueEffectiveUsage(runs){const byEventId=new Map;for(const run of runs){for(const event of run.effective_usage_records){const existing=byEventId.get(event.event_id);if(existing!==void 0){if(JSON.stringify(existing.event)!==JSON.stringify(event)){throw new Error(`Divergent duplicate usage event: ${event.event_id}`)}continue}byEventId.set(event.event_id,{run,event})}}return[...byEventId.values()]}function matchesScope(run,scopeId){return[run.run.run_id,run.run.conversation_id,run.run.execution_id,run.run.task_id,run.run.spec_id,run.run.prd_id,run.run.change_id].includes(scopeId)}function usageBucket(usage){const events=usage.map(({event})=>event);const totals=events.map(event=>tokenTotal(event));const tokenValues={input:events.map(event=>event.tokens.input),cached_input:events.map(event=>event.tokens.cached_input),output:events.map(event=>event.tokens.output),reasoning:events.map(event=>event.tokens.reasoning),total:totals};const costValues={usd:events.map(event=>event.cost.usd),brl:events.map(event=>event.cost.brl)};return{usage_event_count:events.length,tokens:{input:observedSum(events.map(event=>event.tokens.input)),cached_input:observedSum(events.map(event=>event.tokens.cached_input)),output:observedSum(events.map(event=>event.tokens.output)),reasoning:observedSum(events.map(event=>event.tokens.reasoning)),total:observedSum(totals)},cost:{usd:observedSum(events.map(event=>event.cost.usd)),brl:observedSum(events.map(event=>event.cost.brl))},coverage:{events:events.length,tokens:totals.filter(value=>value!==null).length,usd:events.filter(event=>event.cost.usd!==null).length,brl:events.filter(event=>event.cost.brl!==null).length},known:{tokens:{input:knownMetric(tokenValues.input),cached_input:knownMetric(tokenValues.cached_input),output:knownMetric(tokenValues.output),reasoning:knownMetric(tokenValues.reasoning),total:knownMetric(tokenValues.total)},cost:{usd:knownMetric(costValues.usd),brl:knownMetric(costValues.brl)}}}}function knownMetric(values){const known2=values.filter(value=>value!==null);const unknown2=values.length-known2.length;return{known_sum:known2.reduce((sum,value)=>sum+value,0),unknown_event_count:unknown2,complete:unknown2===0,coverage_ratio:values.length===0?1:known2.length/values.length}}function tokenTotal(event){if(event.tokens.total!==null)return event.tokens.total;const{input,output:output2}=event.tokens;if(input===null||output2===null)return null;return input+output2}function observedSum(values){const observed=values.filter(value=>value!==null);if(observed.length===0)return null;return observed.reduce((total,value)=>total+value,0)}var init_v2=__esm({"../costs/src/v2.ts"(){"use strict";init_task_cohort_billed_facts();init_task_cohort_dimensions()}});function parseCompletedTaskCostCohortCollectionInputV2(input){const parsed=completedTaskCostCohortCollectionInputV2Schema.parse(input);const common={timezone:parsed.timezone,interval:parsed.interval,tasks:parsed.tasks};return parsed.equivalence_key===void 0?common:{...common,equivalence_key:parsed.equivalence_key}}var nullableNonNegativeNumber,taskSchema,completedTaskCostCohortCollectionInputV2Schema;var init_task_cost_cohort_input=__esm({"../costs/src/task-cost-cohort-input.ts"(){"use strict";init_zod();nullableNonNegativeNumber=external_exports.number().finite().nonnegative().nullable();taskSchema=external_exports.object({task_id:external_exports.string().min(1),completed:external_exports.boolean(),completed_at:external_exports.string().min(1).nullable(),attempt:external_exports.number().int().nonnegative().nullable(),attempt_id:external_exports.string().min(1).nullable().optional(),equivalence_key:external_exports.string().min(1).nullable().optional(),equivalence_evidence_id:external_exports.string().min(1).nullable().optional(),baseline_equivalence_evidence_id:external_exports.string().min(1).nullable().optional(),model:external_exports.string().min(1).nullable(),reasoning_effort:external_exports.enum(["low","medium","high","xhigh"]).nullable(),baseline_task_id:external_exports.string().min(1).nullable(),baseline_attempt_id:external_exports.string().min(1).nullable().optional(),baseline_equivalence_id:external_exports.string().min(1).nullable(),observed_cost_usd:nullableNonNegativeNumber,baseline_observed_cost_usd:nullableNonNegativeNumber,quality_score:nullableNonNegativeNumber,quality_floor:nullableNonNegativeNumber,rework_count:external_exports.number().int().nonnegative().nullable(),context_budget_tokens:external_exports.number().int().nonnegative().nullable().optional(),cached_context_tokens:external_exports.number().int().nonnegative().nullable().optional(),baseline_context_budget_tokens:external_exports.number().int().nonnegative().nullable().optional(),baseline_cached_context_tokens:external_exports.number().int().nonnegative().nullable().optional(),billed_amount:nullableNonNegativeNumber.optional(),billed_currency:external_exports.string().min(1).nullable().optional(),billed_provenance:external_exports.enum(["observed","inferred","unavailable"]).nullable().optional(),billed_source_id:external_exports.string().min(1).nullable().optional(),billed_at:external_exports.string().min(1).nullable().optional(),baseline_billed_amount:nullableNonNegativeNumber.optional(),baseline_billed_currency:external_exports.string().min(1).nullable().optional(),baseline_billed_provenance:external_exports.enum(["observed","inferred","unavailable"]).nullable().optional(),baseline_billed_source_id:external_exports.string().min(1).nullable().optional(),baseline_billed_at:external_exports.string().min(1).nullable().optional()}).strict();completedTaskCostCohortCollectionInputV2Schema=external_exports.object({timezone:external_exports.string().min(1),interval:external_exports.object({start:external_exports.string().min(1),end:external_exports.string().min(1)}).strict(),equivalence_key:external_exports.string().min(1).nullable().optional(),tasks:external_exports.array(taskSchema)}).strict()}});var init_model_calls_v3=__esm({"../costs/src/model-calls-v3.ts"(){"use strict"}});import{createHash as createHash9}from"node:crypto";function isCanonicalInvocationSummary(value){if(!record2(value)||!keys(value,SUMMARY_KEYS)||typeof value.summary_hash!=="string")return false;const{summary_hash,...unsigned}=value;const coverageFields=value.quantitative_coverage;const metrics=value.quantitative_metrics;const time3=value.time;return value.schema_version===1&&typeof value.agent_invocation_id==="string"&&value.agent_invocation_id.length>0&&typeof value.root_agent_invocation_id==="string"&&value.root_agent_invocation_id.length>0&&nullableString(value.parent_agent_invocation_id)&&(value.invocation_kind==="orchestrator"||value.invocation_kind==="delegated")&&integer2(value.delegation_depth)&&nullableString(value.execution_id)&&nullableString(value.task_id)&&nullableString(value.spec_id)&&nullableString(value.prd_id)&&nullableString(value.change_id)&&typeof value.run_id==="string"&&value.run_id.length>0&&nullableString(value.zaip_agent)&&nullableString(value.phase)&&nullableString(value.purpose)&&(value.developer_identity===null||record2(value.developer_identity)&&typeof value.developer_identity.account_id==="string"&&typeof value.developer_identity.login_snapshot==="string")&&timestamp(value.occurred_at)&&(value.status===null||value.status==="completed"||value.status==="failed"||value.status==="cancelled")&&coverage(value.coverage)&&nullableInteger(value.llm_call_count)&&integer2(value.source_event_count)&&typeof value.source_hash==="string"&&/^[a-f0-9]{64}$/.test(value.source_hash)&&cost(value.historical_cost)&&record2(coverageFields)&&keys(coverageFields,["tokens","llm_call_count","latency_ms","duration_ms"])&&Object.values(coverageFields).every(coverage)&&record2(metrics)&&keys(metrics,["tokens_total","llm_call_count","estimated_usd","estimated_brl","duration_ms","latency_ms"])&&Object.values(metrics).every(metric)&&record2(time3)&&keys(time3,["duration_ms","latency_ms","source_latest_at","source_lag_ms"])&&nullableNonNegativeNumber2(time3.duration_ms)&&nullableNonNegativeNumber2(time3.latency_ms)&&timestamp(time3.source_latest_at)&&nullableNonNegativeNumber2(time3.source_lag_ms)&&Array.isArray(value.usage_segments)&&value.usage_segments.every(segment)&&createHash9("sha256").update(JSON.stringify(unsigned)).digest("hex")===summary_hash}var keys,record2,nullableString,integer2,nullableInteger,nullableNonNegativeNumber2,nullablePositiveNumber,coverage,timestamp,cost,token,metric,segment,SUMMARY_KEYS;var init_invocation_summary_validation=__esm({"../costs/src/invocation-summary-validation.ts"(){"use strict";keys=(value,expected)=>Object.keys(value).sort().join("\0")===[...expected].sort().join("\0");record2=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);nullableString=value=>value===null||typeof value==="string";integer2=value=>typeof value==="number"&&Number.isSafeInteger(value)&&value>=0;nullableInteger=value=>value===null||integer2(value);nullableNonNegativeNumber2=value=>value===null||typeof value==="number"&&Number.isFinite(value)&&value>=0;nullablePositiveNumber=value=>value===null||typeof value==="number"&&Number.isFinite(value)&&value>0;coverage=value=>value==="complete"||value==="partial"||value==="unavailable";timestamp=value=>typeof value==="string"&&Number.isFinite(Date.parse(value));cost=value=>value===null||record2(value)&&keys(value,["estimated_usd","estimated_brl","fx_rate","pricing_model","pricing_source","input_usd","cached_input_usd","output_usd","reasoning_usd"])&&nullableNonNegativeNumber2(value.estimated_usd)&&nullableNonNegativeNumber2(value.estimated_brl)&&nullablePositiveNumber(value.fx_rate)&&nullableString(value.pricing_model)&&nullableString(value.pricing_source)&&nullableNonNegativeNumber2(value.input_usd)&&nullableNonNegativeNumber2(value.cached_input_usd)&&nullableNonNegativeNumber2(value.output_usd)&&nullableNonNegativeNumber2(value.reasoning_usd);token=value=>record2(value)&&keys(value,["input","cached_input","output","reasoning","total"])&&nullableInteger(value.input)&&nullableInteger(value.cached_input)&&nullableInteger(value.output)&&nullableInteger(value.reasoning)&&nullableInteger(value.total);metric=value=>record2(value)&&keys(value,["known_sum","unknown_count","total_count","complete","coverage_ratio"])&&nullableNonNegativeNumber2(value.known_sum)&&integer2(value.unknown_count)&&integer2(value.total_count)&&integer2(value.complete)&&typeof value.coverage_ratio==="number"&&value.coverage_ratio>=0&&value.coverage_ratio<=1;segment=value=>record2(value)&&keys(value,["provider","model","service_tier","reasoning_effort","coverage","event_count","tokens","historical_cost"])&&nullableString(value.provider)&&nullableString(value.model)&&nullableString(value.service_tier)&&nullableString(value.reasoning_effort)&&coverage(value.coverage)&&integer2(value.event_count)&&token(value.tokens)&&cost(value.historical_cost);SUMMARY_KEYS=["schema_version","agent_invocation_id","root_agent_invocation_id","parent_agent_invocation_id","invocation_kind","delegation_depth","execution_id","task_id","spec_id","prd_id","change_id","run_id","zaip_agent","phase","purpose","developer_identity","occurred_at","status","coverage","llm_call_count","source_event_count","source_hash","historical_cost","quantitative_coverage","quantitative_metrics","time","usage_segments","summary_hash"]}});import{createHash as createHash10}from"node:crypto";function compactInvocationTelemetry(events){if(events.length===0)throw new Error("Cannot compact an empty invocation");const first=events[0];if(first===void 0)throw new Error("Cannot compact an empty invocation");const identity=first.correlation.agent_invocation_id;if(events.some(event=>event.correlation.agent_invocation_id!==identity)){throw new Error("Telemetry compaction requires exactly one agent invocation")}if(events.some(event=>event.correlation.execution_id!==first.correlation.execution_id||event.correlation.task_id!==first.correlation.task_id||event.correlation.spec_id!==first.correlation.spec_id||event.correlation.prd_id!==first.correlation.prd_id||event.correlation.change_id!==first.correlation.change_id||event.correlation.run_id!==first.correlation.run_id||event.correlation.zaip_agent!==first.correlation.zaip_agent||event.correlation.phase!==first.correlation.phase||event.correlation.purpose!==first.correlation.purpose||!sameDeveloperIdentity(event.correlation.developer_identity??null,first.correlation.developer_identity??null))){throw new Error("Telemetry compaction requires stable invocation correlation")}const source=new Set;for(const event of events){if(source.has(event.source_event_key))throw new Error(`Duplicate telemetry source key: ${event.source_event_key}`);source.add(event.source_event_key)}const usage=events.filter(event=>event.event_kind==="usage"&&event.tokens!==null);const bySegment=new Map;for(const event of usage){const key=JSON.stringify([event.provider,event.model,event.runtime.service_tier,event.runtime.reasoning_effort,event.coverage,event.historical_cost]);bySegment.set(key,[...bySegment.get(key)??[],event])}const usage_segments=[...bySegment.values()].flatMap(segment2=>{const firstSegment=segment2[0];if(firstSegment===void 0)return[];const tokens2=segment2.flatMap(event=>event.tokens===null?[]:[event.tokens]);return[{provider:firstSegment.provider,model:firstSegment.model,service_tier:firstSegment.runtime.service_tier,reasoning_effort:firstSegment.runtime.reasoning_effort,coverage:coverageOf(segment2),event_count:segment2.length,tokens:sumTokens(tokens2),historical_cost:aggregateCost(segment2.map(event=>event.historical_cost))}]});const terminal=events.filter(event=>event.event_kind==="terminal"||event.event_kind==="error").at(-1);const historical_cost=aggregateCost(usage.map(event=>event.historical_cost));const aggregateTokens=sumTokens(usage.flatMap(event=>event.tokens===null?[]:[event.tokens]));const unsigned={schema_version:1,agent_invocation_id:identity,root_agent_invocation_id:first.correlation.root_agent_invocation_id,parent_agent_invocation_id:first.correlation.parent_agent_invocation_id,invocation_kind:first.correlation.invocation_kind,delegation_depth:first.correlation.delegation_depth,execution_id:first.correlation.execution_id,task_id:first.correlation.task_id,spec_id:first.correlation.spec_id,prd_id:first.correlation.prd_id,change_id:first.correlation.change_id,run_id:first.correlation.run_id,zaip_agent:first.correlation.zaip_agent,phase:first.correlation.phase,purpose:first.correlation.purpose,developer_identity:first.correlation.developer_identity??null,occurred_at:latestSourceAt(events),status:terminal?.status??null,coverage:coverageOf(events),llm_call_count:usage.length===0?null:usage.length,source_event_count:events.length,source_hash:hash2([...source].sort().join("\n")),historical_cost,quantitative_coverage:{tokens:usage.length===0?"unavailable":coverageOf(usage),llm_call_count:usage.length===0?"unavailable":coverageOf(usage),latency_ms:terminal===void 0?"unavailable":terminal.latency_ms===null?"unavailable":terminal.coverage,duration_ms:terminal===void 0?"unavailable":terminal.duration_ms===null?"unavailable":terminal.coverage},quantitative_metrics:{tokens_total:metric2(aggregateTokens.total),llm_call_count:metric2(usage.length===0?null:usage.length),estimated_usd:metric2(historical_cost?.estimated_usd??null),estimated_brl:metric2(historical_cost?.estimated_brl??null),duration_ms:metric2(terminal?.duration_ms??null),latency_ms:metric2(terminal?.latency_ms??null)},time:{duration_ms:terminal?.duration_ms??null,latency_ms:terminal?.latency_ms??null,source_latest_at:latestSourceAt(events),source_lag_ms:sourceLagMs(events)},usage_segments};return{...unsigned,summary_hash:hash2(JSON.stringify(unsigned))}}function sameDeveloperIdentity(left,right){if(left===void 0||right===void 0)return left===right;if(left===null||right===null)return left===right;return left.provider===right.provider&&left.account_id===right.account_id}function buildMonthlyManifest(summaries){const unique2=new Map(summaries.map(summary=>[summary.agent_invocation_id,summary]));const values=[...unique2.values()].sort((a,b)=>a.occurred_at.localeCompare(b.occurred_at));const unsigned={schema_version:1,summary_count:values.length,from:values[0]?.occurred_at??null,to:values.at(-1)?.occurred_at??null,summary_hashes:values.map(summary=>summary.summary_hash),coverage:{complete:values.filter(v=>v.coverage==="complete").length,partial:values.filter(v=>v.coverage==="partial").length,unavailable:values.filter(v=>v.coverage==="unavailable").length},quantitative_coverage:{tokens:coverageCounts(values.map(value=>value.quantitative_coverage.tokens)),llm_call_count:coverageCounts(values.map(value=>value.quantitative_coverage.llm_call_count)),latency_ms:coverageCounts(values.map(value=>value.quantitative_coverage.latency_ms)),duration_ms:coverageCounts(values.map(value=>value.quantitative_coverage.duration_ms))},quantitative_metrics:aggregateMetrics(values.map(value=>value.quantitative_metrics)),time:{duration_ms:sumNullable(values.map(value=>value.time.duration_ms)),latency_ms:sumNullable(values.map(value=>value.time.latency_ms)),source_latest_at:values.map(value=>value.time.source_latest_at).sort().at(-1)??null,source_lag_ms:maxNullable(values.map(value=>value.time.source_lag_ms))}};return{...unsigned,manifest_hash:hash2(JSON.stringify(unsigned))}}function coverageOf(events){return events.some(event=>event.coverage==="unavailable")?"unavailable":events.some(event=>event.coverage==="partial")?"partial":"complete"}function sumTokens(values){const sum=field=>values.every(value=>value[field]!==null)?values.reduce((total,value)=>total+(value[field]??0),0):null;return{input:sum("input"),cached_input:sum("cached_input"),output:sum("output"),reasoning:sum("reasoning"),total:sum("total")}}function hash2(value){return createHash10("sha256").update(value).digest("hex")}function aggregateCost(values){if(values.length===0||values.some(value=>value===null))return null;const observed=values.filter(value=>value!==null);const sum=field=>observed.every(value=>value[field]!==null)?observed.reduce((total,value)=>total+(value[field]??0),0):null;const first=observed[0];if(first===void 0||observed.some(value=>value.fx_rate!==first.fx_rate||value.pricing_model!==first.pricing_model||value.pricing_source!==first.pricing_source))return null;return{estimated_usd:sum("estimated_usd"),estimated_brl:sum("estimated_brl"),fx_rate:first.fx_rate,pricing_model:first.pricing_model,pricing_source:first.pricing_source,input_usd:sum("input_usd"),cached_input_usd:sum("cached_input_usd"),output_usd:sum("output_usd"),reasoning_usd:sum("reasoning_usd")}}function coverageCounts(values){return{complete:values.filter(value=>value==="complete").length,partial:values.filter(value=>value==="partial").length,unavailable:values.filter(value=>value==="unavailable").length}}function sumNullable(values){return values.every(value=>value!==null)?values.reduce((total,value)=>total+(value??0),0):null}function maxNullable(values){const known2=values.filter(value=>value!==null);return known2.length===0||known2.length!==values.length?null:Math.max(...known2)}function sourceLagMs(events){const lags=events.map(event=>event.source_occurred_at===null?null:Date.parse(event.captured_at)-Date.parse(event.source_occurred_at));return lags.every(lag=>lag!==null&&Number.isFinite(lag))?Math.max(...lags):null}function latestSourceAt(events){const latest=events.map(event=>event.source_occurred_at??event.captured_at).sort().at(-1);if(latest===void 0)throw new Error("Cannot compact an empty invocation");return latest}function metric2(value){return{known_sum:value,unknown_count:value===null?1:0,total_count:1,complete:value===null?0:1,coverage_ratio:value===null?0:1}}function mergeMetrics(values){const total_count=values.reduce((total,value)=>total+value.total_count,0);const unknown_count=values.reduce((total,value)=>total+value.unknown_count,0);const complete=values.reduce((total,value)=>total+value.complete,0);const known2=values.map(value=>value.known_sum).filter(value=>value!==null);return{known_sum:known2.length===0?null:known2.reduce((total,value)=>total+value,0),unknown_count,total_count,complete,coverage_ratio:total_count===0?0:complete/total_count}}function aggregateMetrics(values){return{tokens_total:mergeMetrics(values.map(value=>value.tokens_total)),llm_call_count:mergeMetrics(values.map(value=>value.llm_call_count)),estimated_usd:mergeMetrics(values.map(value=>value.estimated_usd)),estimated_brl:mergeMetrics(values.map(value=>value.estimated_brl)),duration_ms:mergeMetrics(values.map(value=>value.duration_ms)),latency_ms:mergeMetrics(values.map(value=>value.latency_ms))}}var init_invocation_ledger=__esm({"../costs/src/invocation-ledger.ts"(){"use strict";init_invocation_summary_validation()}});var init_invocation_manifest_page=__esm({"../costs/src/invocation-manifest-page.ts"(){"use strict"}});var init_historical_developer_attribution=__esm({"../costs/src/historical-developer-attribution.ts"(){"use strict"}});function summarizeObservedSourceTiming(events){const intervals=events.flatMap(event=>{const duration4=observedInterval(event.source_started_at,event.source_finished_at);return duration4===null?[]:[{phase:event.phase??"unavailable",duration:duration4}]});const phaseNames=new Set(events.map(event=>event.phase??"unavailable"));const by_phase={};for(const phase2 of phaseNames){const phaseEvents=events.filter(event=>(event.phase??"unavailable")===phase2);const values=intervals.filter(interval=>interval.phase===phase2).map(interval=>interval.duration);by_phase[phase2]=metric3(values,phaseEvents.length)}return{aggregation:"sum_of_observed_intervals",total_interval_count:events.length,source_interval:metric3(intervals.map(interval=>interval.duration),events.length),by_phase,ttft_ms:null}}function metric3(values,eventCount){return{duration_ms:values.length===0?null:values.reduce((sum,value)=>sum+value,0),coverage:values.length===0?"unavailable":values.length===eventCount?"complete":"partial",observed_interval_count:values.length}}function observedInterval(start,finish){if(start===null||start===void 0||finish===null||finish===void 0)return null;const startedAt=Date.parse(start);const finishedAt=Date.parse(finish);return Number.isFinite(startedAt)&&Number.isFinite(finishedAt)&&finishedAt>=startedAt?finishedAt-startedAt:null}var init_observed_source_timing=__esm({"../costs/src/observed-source-timing.ts"(){"use strict"}});import{homedir as homedir2}from"node:os";import{join as join2}from"node:path";function roundCurrency2(value){return Math.round(value*1e6)/1e6}function unavailableCost(input,model){return{estimated_usd:null,estimated_brl:null,fx_rate:input.fxRate?.rate??null,pricing_model:model?.id??null,pricing_source:model?.source_label??null,pricing_source_url:model?.source_url??null,pricing_catalog_updated_at:model===null?null:input.catalog.updated_at,input_usd:null,cached_input_usd:null,cache_write_input_usd:null,output_usd:null,reasoning_usd:null}}function estimateUsageCost(input){const provider=input.provider??inferProvider(input.model,"","");const normalizedModel=input.model.toLowerCase();const matchesPricingIdentity=identity=>{const normalizedIdentity=identity.toLowerCase();if(normalizedModel===normalizedIdentity)return true;const suffix=normalizedModel.slice(normalizedIdentity.length);return suffix.startsWith("@")||suffix.startsWith(":")||suffix.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(suffix)};const lookup=input.catalog.models.find(model=>matchesPricingIdentity(model.id)||model.aliases.some(alias=>matchesPricingIdentity(alias)));if(!lookup||provider!==null&&lookup.provider!==provider){return unavailableCost(input,null)}const cachedInput=input.usage.cached_input;const inputTokens=input.usage.input;const outputTokens=input.usage.output;if(inputTokens===null||cachedInput===null||outputTokens===null){return unavailableCost(input,lookup)}const reasoningTokens=input.usage.reasoning??0;const hasLongContextUplift=lookup.long_context_threshold_tokens!==null&&(input.usage.input??0)>lookup.long_context_threshold_tokens;const inputMultiplier=hasLongContextUplift?lookup.long_context_input_multiplier:1;const outputMultiplier=hasLongContextUplift?lookup.long_context_output_multiplier:1;const priority2=input.serviceTier==="priority"||input.serviceTier==="fast";if(priority2&&hasLongContextUplift&&!lookup.priority_long_context_supported){return unavailableCost(input,lookup)}const inputRate=priority2?lookup.priority_input_per_million_usd??null:lookup.input_per_million_usd;const outputRate=priority2?lookup.priority_output_per_million_usd??null:lookup.output_per_million_usd;if(inputRate===null||outputRate===null){return unavailableCost(input,lookup)}const cacheWriteInputRate=priority2?lookup.priority_cache_write_input_per_million_usd??null:lookup.cache_write_input_per_million_usd??null;const cacheWriteInputTokens=input.usage.cache_write_input??null;const{inputUsd,cachedInputUsd,cacheWriteInputUsd,outputUsd,reasoningUsd}=calculateTokenPrice({inputTokens,cachedInputTokens:cachedInput,cacheWriteInputTokens,inputIncludesCacheWrites:lookup.provider==="openai",outputTokens,reasoningTokens,inputRate,cachedInputRate:priority2?lookup.priority_cached_input_per_million_usd??null:lookup.cached_input_per_million_usd,cacheWriteInputRate,outputRate,reasoningRate:priority2?lookup.priority_reasoning_per_million_usd??null:lookup.reasoning_per_million_usd,inputMultiplier,outputMultiplier});if(cachedInputUsd===null||lookup.provider==="openai"&&cacheWriteInputTokens!==null&&cacheWriteInputTokens>inputTokens||cacheWriteInputRate!==null&&cacheWriteInputTokens===null||cacheWriteInputRate===null&&(cacheWriteInputTokens??0)>0){return unavailableCost(input,lookup)}const totalUsd=roundCurrency2(inputUsd+cachedInputUsd+(cacheWriteInputUsd??0)+outputUsd+reasoningUsd);const totalBrl=input.fxRate===null||input.fxRate===void 0?null:roundCurrency2(totalUsd*input.fxRate.rate);return{estimated_usd:totalUsd,estimated_brl:totalBrl,fx_rate:input.fxRate?.rate??null,pricing_model:lookup.id,pricing_source:lookup.source_label,pricing_source_url:lookup.source_url,pricing_catalog_updated_at:input.catalog.updated_at,input_usd:inputUsd,cached_input_usd:cachedInputUsd,cache_write_input_usd:cacheWriteInputUsd,output_usd:outputUsd,reasoning_usd:reasoningUsd}}function codexModelFromRecord(record3,payload){if(record3.type==="turn_context"&&payload&&typeof payload.model==="string"){return payload.model}if(record3.type==="thread_settings_applied"&&payload){const threadSettings=typeof payload.thread_settings==="object"&&payload.thread_settings!==null?payload.thread_settings:null;if(threadSettings&&typeof threadSettings.model==="string")return threadSettings.model}return null}function codexRuntimeFromRecord(record3,payload){if(record3.type==="turn_context"&&payload){return{reasoningEffort:typeof payload.effort==="string"?payload.effort:null,serviceTier:typeof payload.service_tier==="string"?payload.service_tier:null}}if((record3.type==="thread_settings_applied"||payload?.type==="thread_settings_applied")&&payload){const settings=typeof payload.thread_settings==="object"&&payload.thread_settings!==null?payload.thread_settings:null;return{reasoningEffort:typeof settings?.reasoning_effort==="string"?settings.reasoning_effort:null,serviceTier:typeof settings?.service_tier==="string"?settings.service_tier:null}}return null}function segmentTimestampValue(value){if(value===null)return null;const parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}function chooseNewestSegment(segments2){return[...segments2].sort((left,right)=>(left.finishedAt??left.startedAt??"").localeCompare(right.finishedAt??right.startedAt??"")).at(-1)??null}function chooseSegmentAfter(segments2,startedAfter){const threshold=segmentTimestampValue(startedAfter);if(threshold===null)return chooseNewestSegment(segments2);const candidates=segments2.map(segment2=>{const startedAt=segmentTimestampValue(segment2.startedAt);const finishedAt=segmentTimestampValue(segment2.finishedAt);const overlapsThreshold=startedAt!==null&&startedAt>=threshold||startedAt!==null&&finishedAt!==null&&startedAt<=threshold&&finishedAt>=threshold;const firstRelevantAt=startedAt!==null&&startedAt>=threshold?startedAt:finishedAt!==null&&finishedAt>=threshold?finishedAt:null;return{segment:segment2,overlapsThreshold,firstRelevantAt}}).filter(entry2=>entry2.overlapsThreshold&&entry2.firstRelevantAt!==null).sort((left,right)=>{if(left.firstRelevantAt!==right.firstRelevantAt){return(left.firstRelevantAt??Number.MAX_SAFE_INTEGER)-(right.firstRelevantAt??Number.MAX_SAFE_INTEGER)}return(left.segment.finishedAt??left.segment.startedAt??"").localeCompare(right.segment.finishedAt??right.segment.startedAt??"")});return candidates[0]?.segment??chooseNewestSegment(segments2)}async function listRecentCodexSegments(workspaceRoot,existingSegmentKeys,options={}){const sessionsRoot=options.sessionsRoot??join2(homedir2(),".codex");const{filesystem:sessionsFilesystem,files}=await codexSessionFilesForWorkspace(workspaceRoot,{...options,sessionsRoot});const workspace=normalizeCodexPath(workspaceRoot);const segments2=[];for(const path of files){if(!await sessionsFilesystem.exists(path))continue;const fileSegmentStart=segments2.length;let canonicalSessionMetaSeen=false;let workspaceMatches=false;let sessionId=null;let current=null;let segmentIndex=0;let cycleIndex=0;let activeModel=null;let activeReasoningEffort=null;let activeServiceTier=null;let activeAgentPath=null;let activeParentThreadId=null;let latestCumulativeUsage=null;let latestIncrementalUsage=null;const lines=(await sessionsFilesystem.readText(path)).split(/\r?\n/).filter(Boolean);for(const line of lines){let parsed;try{parsed=JSON.parse(line)}catch{continue}if(typeof parsed!=="object"||parsed===null)continue;const record3=parsed;const payload="payload"in record3&&typeof record3.payload==="object"&&record3.payload!==null?record3.payload:null;if(record3.type==="session_meta"&&payload&&typeof payload.cwd==="string"){const source=typeof payload.source==="object"&&payload.source!==null?payload.source:null;const subagent=typeof source?.subagent==="object"&&source.subagent!==null?source.subagent:null;const spawn4=typeof subagent?.thread_spawn==="object"&&subagent.thread_spawn!==null?subagent.thread_spawn:null;const observedSessionId=spawn4!==null&&typeof payload.id==="string"?payload.id:typeof payload.session_id==="string"?payload.session_id:typeof payload.id==="string"?payload.id:null;const observedAgentPath=typeof payload.agent_path==="string"?payload.agent_path:typeof spawn4?.agent_path==="string"?spawn4.agent_path:null;const observedParentThreadId=typeof payload.parent_thread_id==="string"?payload.parent_thread_id:typeof spawn4?.parent_thread_id==="string"?spawn4.parent_thread_id:null;if(canonicalSessionMetaSeen){segments2.splice(fileSegmentStart);current=null;segmentIndex=0;cycleIndex=0;latestCumulativeUsage=null;latestIncrementalUsage=null;continue}canonicalSessionMetaSeen=true;sessionId=observedSessionId;activeAgentPath=observedAgentPath;activeParentThreadId=observedParentThreadId;const agentPathMatches=options.agentPath===void 0||options.agentPath===null||activeAgentPath===options.agentPath;const parentMatches=options.parentThreadId===void 0||options.parentThreadId===null||activeParentThreadId===options.parentThreadId;const threadMatches=options.agentPath!==void 0&&options.agentPath!==null?true:options.threadId===void 0||options.threadId===null||sessionId===options.threadId;workspaceMatches=normalizeCodexPath(payload.cwd)===workspace&&agentPathMatches&&parentMatches&&threadMatches;continue}if(!workspaceMatches)continue;const exactModel=codexModelFromRecord(record3,payload);if(exactModel!==null){activeModel=exactModel;if(current)current.model=exactModel}const exactRuntime=codexRuntimeFromRecord(record3,payload);if(exactRuntime!==null){if(exactRuntime.reasoningEffort!==null)activeReasoningEffort=exactRuntime.reasoningEffort;if(exactRuntime.serviceTier!==null)activeServiceTier=exactRuntime.serviceTier;if(current){current.reasoningEffort=activeReasoningEffort;current.serviceTier=activeServiceTier}}if(!payload||typeof payload.type!=="string")continue;const at=typeof record3.timestamp==="string"?record3.timestamp:null;if(payload.type==="task_started"){latestIncrementalUsage=null;segmentIndex+=1;cycleIndex=0;current={segmentKey:`${normalizeCodexPath(path)}#${segmentIndex}`,sessionPath:path,sessionId,turnId:typeof payload.turn_id==="string"?payload.turn_id:null,startedAt:at,finishedAt:null,terminalType:null,model:activeModel,reasoningEffort:activeReasoningEffort,serviceTier:activeServiceTier,loops:[]};continue}if(payload.type==="token_count"){const info=typeof payload.info==="object"&&payload.info!==null?payload.info:null;const cumulative=tokenUsageFromCodexRecord(info?.total_token_usage);const incremental=tokenUsageFromCodexRecord(info?.last_token_usage);if(cumulative===null&&incremental===null)continue;const previousCumulative=latestCumulativeUsage;if(cumulative!==null)latestCumulativeUsage=cumulative;if(!current)continue;const tokenUsage=cumulative===null?incremental!==null&&sameCodexTokenSnapshot(latestIncrementalUsage,incremental)?null:incremental:cumulativeUsageDelta(previousCumulative,cumulative);if(cumulative===null&&incremental!==null)latestIncrementalUsage=incremental;if(tokenUsage===null||!hasObservedTokenDelta(tokenUsage))continue;cycleIndex+=1;current.loops.push({cycleIndex,timestamp:at,model:activeModel??current.model,usage:tokenUsage});continue}const observedTerminal=payload.type==="task_complete"||payload.type==="turn_aborted"&&payload.reason==="interrupted";const terminalMatchesCurrentTurn=current!==null&&typeof payload.turn_id==="string"&&payload.turn_id===current.turnId;if(observedTerminal&&current&&terminalMatchesCurrentTurn){current.finishedAt=at;current.terminalType=payload.type==="task_complete"?"task_complete":"turn_aborted";if(current.loops.length>0&&!existingSegmentKeys.has(current.segmentKey)){segments2.push(current)}current=null}}if(current&&current.loops.length>0&&!existingSegmentKeys.has(current.segmentKey)){segments2.push(current)}}return segments2}async function findLatestCodexSegment(workspaceRoot,existingSegmentKeys,options={}){const discovered=await listRecentCodexSegments(workspaceRoot,existingSegmentKeys,options);const segments2=options.turnId===void 0||options.turnId===null?discovered:discovered.filter(segment2=>segment2.turnId===options.turnId);const terminalSegments=options.requireTaskComplete?segments2.filter(segment2=>segment2.terminalType==="task_complete"):segments2;if(options.turnId!==void 0&&options.turnId!==null){return chooseNewestSegment(terminalSegments)}return options.startedAfter?chooseSegmentAfter(terminalSegments,options.startedAfter):chooseNewestSegment(terminalSegments)}var timestamp2,pricingModelSchema,pricingCatalogSchema,fxRateSchema,persistedTokenUsageSchema,runCostSummarySchema,runTelemetrySummarySchema,runEventSchema,cycleEventSchema,PricingRepository;var init_src2=__esm({"../costs/src/index.ts"(){"use strict";init_zod();init_codex_session_activity();init_pricing_math();init_invocation_summary_aggregation();init_segment_usage();init_codex_session_activity();init_run_telemetry();init_telemetry_repository();init_v2();init_task_cost_cohort_input();init_model_calls_v3();init_invocation_ledger();init_segment_usage();init_invocation_manifest_page();init_invocation_summary_aggregation();init_historical_developer_attribution();init_observed_source_timing();timestamp2=external_exports.string().datetime({offset:true}).or(external_exports.string().datetime());pricingModelSchema=external_exports.object({id:external_exports.string().min(1),provider:external_exports.enum(["openai","anthropic"]),aliases:external_exports.array(external_exports.string().min(1)).default([]),input_per_million_usd:external_exports.number().nonnegative(),cached_input_per_million_usd:external_exports.number().nonnegative().nullable().default(null),cache_write_input_per_million_usd:external_exports.number().nonnegative().nullable().optional(),output_per_million_usd:external_exports.number().nonnegative(),reasoning_per_million_usd:external_exports.number().nonnegative().nullable().default(null),priority_input_per_million_usd:external_exports.number().nonnegative().nullable().optional(),priority_cached_input_per_million_usd:external_exports.number().nonnegative().nullable().optional(),priority_cache_write_input_per_million_usd:external_exports.number().nonnegative().nullable().optional(),priority_output_per_million_usd:external_exports.number().nonnegative().nullable().optional(),priority_reasoning_per_million_usd:external_exports.number().nonnegative().nullable().optional(),reasoning_billed_separately:external_exports.boolean().default(false),long_context_threshold_tokens:external_exports.number().int().positive().nullable().default(null),long_context_input_multiplier:external_exports.number().positive().default(1),long_context_output_multiplier:external_exports.number().positive().default(1),priority_long_context_supported:external_exports.boolean().default(false),source_label:external_exports.string().min(1),source_url:external_exports.string().url(),notes:external_exports.array(external_exports.string()).default([])}).strict();pricingCatalogSchema=external_exports.object({schema_version:external_exports.literal(1),updated_at:timestamp2,source:external_exports.string().min(1),disclaimer:external_exports.string().min(1),models:external_exports.array(pricingModelSchema)}).strict();fxRateSchema=external_exports.object({schema_version:external_exports.literal(1),base:external_exports.literal("USD"),quote:external_exports.literal("BRL"),rate:external_exports.number().positive(),as_of:timestamp2,source_label:external_exports.string().min(1),source_url:external_exports.string().url()}).strict();persistedTokenUsageSchema=external_exports.object({input:external_exports.number().int().nonnegative().nullable(),cached_input:external_exports.number().int().nonnegative().nullable().default(null),cache_write_input:external_exports.number().int().nonnegative().nullable().optional(),output:external_exports.number().int().nonnegative().nullable(),reasoning:external_exports.number().int().nonnegative().nullable(),total:external_exports.number().int().nonnegative().nullable().default(null),source:external_exports.preprocess(value=>value==="client"?"provider_reported":value,external_exports.enum(["provider_reported","estimated","unavailable"]))}).strict();runCostSummarySchema=external_exports.object({estimated_usd:external_exports.number().nonnegative().nullable(),estimated_brl:external_exports.number().nonnegative().nullable(),fx_rate:external_exports.number().positive().nullable(),pricing_model:external_exports.string().nullable(),pricing_source:external_exports.string().nullable(),pricing_source_url:external_exports.string().url().nullable().optional(),pricing_catalog_updated_at:timestamp2.nullable().optional(),input_usd:external_exports.number().nonnegative().nullable().default(null),cached_input_usd:external_exports.number().nonnegative().nullable().default(null),cache_write_input_usd:external_exports.number().nonnegative().nullable().optional(),output_usd:external_exports.number().nonnegative().nullable().default(null),reasoning_usd:external_exports.number().nonnegative().nullable().default(null)}).strict();runTelemetrySummarySchema=external_exports.object({cycle_count:external_exports.number().int().nonnegative().nullable(),source:external_exports.enum(["repository","local-codex","manual","unavailable"]),segment_key:external_exports.string().nullable()}).strict();runEventSchema=external_exports.object({schema_version:external_exports.literal(1),recorded_at:timestamp2,run_id:external_exports.string().startsWith("RUN-"),task_id:external_exports.string().startsWith("TASK-"),spec_id:external_exports.string().nullable(),change_id:external_exports.string().nullable(),task_title:external_exports.string().nullable(),task_status:external_exports.string().nullable(),client:external_exports.string().min(1),agent:external_exports.string().min(1),provider:external_exports.enum(["openai","anthropic"]).nullable(),model:external_exports.string().min(1),status:external_exports.enum(["running","completed","failed"]),started_at:timestamp2,finished_at:timestamp2.nullable(),duration_ms:external_exports.number().int().nonnegative().nullable(),token_usage:persistedTokenUsageSchema,estimated_cost:runCostSummarySchema,telemetry:runTelemetrySummarySchema,source_segment_key:external_exports.string().nullable()}).strict();cycleEventSchema=external_exports.object({schema_version:external_exports.literal(1),recorded_at:timestamp2,run_id:external_exports.string().startsWith("RUN-"),task_id:external_exports.string().startsWith("TASK-"),cycle_index:external_exports.number().int().nonnegative(),provider:external_exports.enum(["openai","anthropic"]).nullable(),model:external_exports.string().min(1),timestamp:timestamp2,source:external_exports.enum(["local-codex","manual"]),source_segment_key:external_exports.string().nullable(),token_usage:persistedTokenUsageSchema,estimated_cost:runCostSummarySchema}).strict();PricingRepository=class{constructor(filesystem,modelsPath=".agents/config/pricing/models.json",fxBasePath=".agents/config/pricing/fx"){this.filesystem=filesystem;this.modelsPath=modelsPath;this.fxBasePath=fxBasePath}filesystem;modelsPath;fxBasePath;async readCatalog(){try{return pricingCatalogSchema.parse(JSON.parse(await this.filesystem.readText(this.modelsPath)))}catch(error51){if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT"){return pricingCatalogSchema.parse({schema_version:1,updated_at:new Date().toISOString(),source:"missing-local-pricing",disclaimer:"Tabela de pre\xC3\xA7os ausente no workspace.",models:[]})}throw error51}}async readLatestFxRate(){const currentPath=`${this.fxBasePath}/current-usd-brl.json`;try{return fxRateSchema.parse(JSON.parse(await this.filesystem.readText(currentPath)))}catch{}const paths=[...await this.filesystem.listFiles(this.fxBasePath,".json")].sort().reverse();for(const path of paths){try{return fxRateSchema.parse(JSON.parse(await this.filesystem.readText(path)))}catch{}}return null}async writeCurrentFxRate(rate){const value=fxRateSchema.parse({schema_version:1,base:"USD",quote:"BRL",rate,as_of:new Date().toISOString(),source_label:"Dashboard manual override",source_url:"https://www.bcb.gov.br/"});await this.filesystem.writeTextAtomic(`${this.fxBasePath}/current-usd-brl.json`,`${JSON.stringify(value,null,2)}
99
99
  `);return value}}}});function matchesAttributionRecovery(started,recovery){return started.entrypoint==="task"&&started.execution_id!==null&&started.task_id!==null&&started.change_id===null&&recovery.execution_id===started.execution_id&&recovery.task_id===started.task_id}var timestamp3,runAttributionRecoveredV2Schema;var init_run_v2_attribution_recovery=__esm({"../decisions/src/run-v2-attribution-recovery.ts"(){"use strict";init_zod();timestamp3=external_exports.string().datetime({offset:true}).or(external_exports.string().datetime());runAttributionRecoveredV2Schema=external_exports.object({schema_version:external_exports.literal(2),event_id:external_exports.string().min(1).max(200),run_id:external_exports.string().startsWith("RUN-"),sequence:external_exports.number().int().positive(),occurred_at:timestamp3,type:external_exports.literal("run.attribution.recovered"),phase:external_exports.literal("execution"),execution_id:external_exports.string().startsWith("EXEC-"),task_id:external_exports.string().startsWith("TASK-"),change_id:external_exports.string().startsWith("CHG-")}).strict()}});function isModelCallCoveragePromotion(existing,candidate){return existing.coverage==="partial"&&candidate.coverage==="complete"&&existing.call_id===candidate.call_id&&existing.agent_invocation_id===candidate.agent_invocation_id&&existing.source_call_key===candidate.source_call_key&&JSON.stringify(existing.tokens)===JSON.stringify(candidate.tokens)}function isAllowedPostTerminalUsage(record3,finished,usageById){const observedTimingOnly=record3.type==="usage.recorded"&&record3.retrospective_correction===true&&record3.activity_kind==="retrospective_observed_timing"&&record3.supersedes_event_id===null&&record3.phase===finished.phase&&record3.source_segment_key!==null&&record3.source_started_at!==void 0&&record3.source_finished_at!==void 0&&Date.parse(record3.source_finished_at)>=Date.parse(record3.source_started_at)&&record3.source_occurred_at===record3.source_finished_at&&record3.tokens.source==="unavailable"&&[record3.tokens.input,record3.tokens.cached_input,record3.tokens.output,record3.tokens.reasoning,record3.tokens.total,record3.cost.usd,record3.cost.brl,record3.cost.fx_rate,record3.provider,record3.model].every(value=>value===null);if(observedTimingOnly)return true;return record3.type==="usage.recorded"&&record3.retrospective_correction===true&&record3.activity_kind==="retrospective_local_remeasurement"&&record3.supersedes_event_id!==null&&usageById.has(record3.supersedes_event_id)&&record3.phase===finished.phase}function sameModelSelection(record3,input){return(input.eventId===void 0||input.eventId===record3.event_id)&&(input.occurredAt===void 0||input.occurredAt===record3.occurred_at)&&JSON.stringify(record3.requested)===JSON.stringify(input.requested)&&JSON.stringify(record3.selection)===JSON.stringify(input.selection)}function sameProviderInvocation(record3,input){return(input.eventId===void 0||input.eventId===record3.event_id)&&(input.occurredAt===void 0||input.occurredAt===record3.occurred_at)&&record3.status===input.status&&record3.latency_ms===input.latencyMs&&JSON.stringify(record3.effective)===JSON.stringify(input.effective)}function assertForwardPhase(current,next){const order2={conversation:0,planning:1,execution:2};if(order2[next]<order2[current])throw new Error(`Run V2 phase cannot move backward from ${current} to ${next}`)}var init_run_v2_guards=__esm({"../decisions/src/run-v2-guards.ts"(){"use strict"}});import{posix as posix2}from"node:path";function decisionBody(decision){const alternatives=decision.alternatives.map(item=>`- ${item}`).join("\n")||"Nenhuma.";const consequences=decision.consequences.map(item=>`- ${item}`).join("\n")||"Nenhuma.";return`# ${decision.title}
@@ -418,21 +418,21 @@ import { createHash, randomUUID } from "node:crypto";
418
418
  import { spawn } from "node:child_process";
419
419
  import { dirname, isAbsolute, relative, resolve } from "node:path";
420
420
  import { fileURLToPath } from "node:url";
421
- const root = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
422
- const local = resolve(root, ".local/hooks");
421
+ const hookRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
422
+ let root = hookRoot, local;
423
423
  const deadline = Date.now() + 8000;
424
424
  const readChunkBytes = 1024 * 1024, maxLineBytes = 8 * 1024 * 1024, maxReadBytes = 16 * 1024 * 1024;
425
425
  const hash = value => createHash("sha256").update(value).digest("hex");
426
426
  const parse = value => { try { return JSON.parse(value); } catch { return null; } };
427
427
  const text = value => typeof value === "string" && value.length > 0 && value.length <= 4096 ? value : null;
428
- const inside = path => { const p = relative(root, resolve(path)); return p === "" || (!p.startsWith("..") && !isAbsolute(p)); };
428
+ const inside = (path, base = root) => { const p = relative(base, resolve(path)); return p === "" || (!p.startsWith("..") && !isAbsolute(p)); };
429
429
  let raw = ""; for await (const chunk of process.stdin) raw += chunk;
430
430
  const event = parse(raw), session = text(event?.session_id), turn = text(event?.turn_id);
431
431
  let receipt, receiptPath, lease;
432
432
  function reply(pending = false) {
433
433
  const result = { hookSpecificOutput: { hookEventName: "Stop" } };
434
434
  // One continuation at most. Persistent failures remain an explicit durable pending event.
435
- if (pending && event?.stop_hook_active !== true) Object.assign(result, { decision: "block", reason: "ZAIP closure or telemetry is pending. Retry this exact turn using its durable Stop receipt; do not report Task completion before canonical closure." });
435
+ if (pending && event?.stop_hook_active !== true) Object.assign(result, { decision: "block", reason: receipt?.error === "owned_task_active" ? "ZAIP owned Task is still executing or verifying. Continue this turn, inspect every launched process by fresh PID/session status, collect terminal exit and output, and resume from any failure. Never claim a process is still running from stale state." : "ZAIP closure or telemetry is pending. Retry this exact turn using its durable Stop receipt; do not report Task completion before canonical closure." });
436
436
  writeSync(1, JSON.stringify(result) + "\n");
437
437
  }
438
438
  async function save(path, value) {
@@ -532,9 +532,35 @@ function call(cli, args, path) {
532
532
  child.once("error", () => finish(1)); child.once("close", code => finish(code ?? 1));
533
533
  });
534
534
  }
535
+ function gitWorktrees() {
536
+ return new Promise(done => {
537
+ const child = spawn("git", ["-C", hookRoot, "worktree", "list", "--porcelain"], { cwd: hookRoot, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
538
+ let out = "", settled = false;
539
+ const finish = value => { if (settled) return; settled = true; clearTimeout(timer); done(value); };
540
+ const timer = setTimeout(() => { child.kill(); finish([hookRoot]); }, Math.min(1500, Math.max(100, deadline - Date.now() - 6500)));
541
+ child.stdout.on("data", data => { out = (out + String(data)).slice(0, 1048576); });
542
+ child.once("error", () => finish([hookRoot]));
543
+ child.once("close", code => finish(code === 0 ? [...new Set(out.split(/\r?\n/).filter(line => line.startsWith("worktree ")).map(line => resolve(line.slice(9))).concat(hookRoot))] : [hookRoot]));
544
+ });
545
+ }
546
+ async function selectWorkspace(correlationKey, worktrees) {
547
+ const matches = [];
548
+ for (const candidate of worktrees.slice(0, 256)) {
549
+ const correlation = parse(await readFile(resolve(candidate, ".local/codex-telemetry-spool/v1/correlations", correlationKey + ".json"), "utf8").catch(() => ""));
550
+ if (correlation?.schema_version === 1 && correlation.thread_id === session && correlation.turn_id === turn && correlation.agent_path === null && typeof correlation.run_id === "string") matches.push(candidate);
551
+ }
552
+ if (matches.length > 1) throw new Error("workspace_correlation_ambiguous");
553
+ return matches[0] ?? hookRoot;
554
+ }
535
555
  try {
556
+ if (event?.hook_event_name !== "Stop" || !session || !turn || !text(event.cwd)) { reply(); process.exit(0); }
557
+ const worktrees = await gitWorktrees();
558
+ if (!worktrees.some(candidate => inside(event.cwd, candidate))) { reply(); process.exit(0); }
559
+ const correlationKey = hash(JSON.stringify(["codex", session, turn, null, null]));
560
+ root = await selectWorkspace(correlationKey, worktrees);
561
+ local = resolve(root, ".local/hooks");
536
562
  const config = await readFile(resolve(root, ".agents/config/project.yaml"), "utf8");
537
- if (event?.hook_event_name !== "Stop" || !session || !turn || !text(event.cwd) || !inside(event.cwd) || !/zaip:\s*\r?\n\s*enabled:\s*true\s*(?:\r?\n|$)/.test(config)) { reply(); process.exit(0); }
563
+ if (!/zaip:\s*\r?\n\s*enabled:\s*true\s*(?:\r?\n|$)/.test(config)) { reply(); process.exit(0); }
538
564
  await mkdir(local, { recursive: true });
539
565
  receiptPath = resolve(local, "stop-" + hash(JSON.stringify([session, turn])) + ".json");
540
566
  lease = await acquire(receiptPath + ".lock");
@@ -548,7 +574,6 @@ try {
548
574
  for (const delay of [0, 250, 750]) { if (delay) await new Promise(r => setTimeout(r, delay)); status = await terminal(text(event.transcript_path)); if (status) break; }
549
575
  if (!status) throw new Error("transcript_pending");
550
576
  const cli = resolve(root, ".agents/runtime/bin/zaip.mjs");
551
- const correlationKey = hash(JSON.stringify(["codex", session, turn, null, null]));
552
577
  const correlation = parse(await readFile(resolve(root, ".local/codex-telemetry-spool/v1/correlations", correlationKey + ".json"), "utf8").catch(() => ""));
553
578
  let intake;
554
579
  if (correlation?.schema_version === 1 && correlation.thread_id === session && correlation.turn_id === turn && correlation.agent_path === null && typeof correlation.run_id === "string") {
@@ -561,6 +586,12 @@ try {
561
586
  const run = intake?.run?.run_id;
562
587
  if (typeof run !== "string" || (intake.task !== null && typeof intake.task?.id !== "string")) throw new Error("start_pending");
563
588
  receipt.run_id = run; await save(receiptPath, receipt);
589
+ if (intake.task !== null && status === "completed" && event?.stop_hook_active !== true) {
590
+ const shown = await call(cli, ["task", "show", intake.task.id], text(event.transcript_path));
591
+ const taskStatus = parse(shown.out)?.task?.status;
592
+ if (shown.code !== 0 || typeof taskStatus !== "string") throw new Error("task_state_pending");
593
+ if (["executing", "verifying"].includes(taskStatus)) throw new Error("owned_task_active");
594
+ }
564
595
  const result = await call(cli, ["subagent", "reconcile-stop", "--session", session, "--turn", turn], text(event.transcript_path));
565
596
  const outcome = parse(result.out);
566
597
  const terminalStates = ["completed", "blocked", "failed", "cancelled"];
@@ -1839,7 +1870,7 @@ ${message.content}`).join("\n\n");const contract=[`Agent: ${invocation.agent_id}
1839
1870
 
1840
1871
  ${messages}
1841
1872
  `}function resumeId(token2,provider){if(token2===null)return null;const prefix=`${provider}:`;if(!token2.startsWith(prefix)||token2.length===prefix.length){throw new Error(`Invalid ${provider} checkpoint token`)}return token2.slice(prefix.length)}function checkpointId(provider,sessionId){const normalized=sessionId.toUpperCase().replace(/[^A-Z0-9-]/g,"-");return`CHK-${provider.toUpperCase()}-${normalized}`}function unavailableUsage(){return{input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_tokens:0,source:"unavailable"}}function nonnegativeInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:0}function asOptionalRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:null}var ClaudeRuntimeProtocol=class{constructor(now=()=>new Date().toISOString()){this.now=now}now;prepare(invocation){const sessionId=resumeId(invocation.resume_from,"claude");const args=["--print","--output-format","stream-json","--verbose","--model",invocation.model,"--effort",invocation.reasoning_effort,...sessionId===null?[]:["--resume",sessionId]];const translator=new ClaudeEventTranslator(invocation,this.now);return{args,stdin:renderInvocationPrompt(invocation),translate:value=>translator.translate(value),finish:()=>[]}}};var ClaudeEventTranslator=class extends NativeProtocolEmitter{#assistantUsage=null;translate(value){const passthrough=this.passthrough(value);if(passthrough!==null)return passthrough;const record3=asRecord(value,"Claude event");const type=requiredString(record3,"type");if(type==="system")return this.system(record3);if(type==="assistant")return this.assistant(record3);if(type==="user")return this.user(record3);if(type==="result")return this.result(record3);if(type==="stream_event")return[];return[]}system(record3){if(record3.subtype!=="init")return[];return this.start("claude",requiredString(record3,"session_id"))}assistant(record3){const message=asRecord(record3.message,"Claude assistant message");const content=contentBlocks(message.content,"Claude assistant content");const events=[];for(const block2 of content){const type=requiredString(block2,"type");if(type==="text")events.push(...this.output(requiredString(block2,"text")));if(type==="tool_use"){events.push(...this.toolRequested(requiredString(block2,"id"),requiredString(block2,"name"),block2.input??{}))}}if(message.usage!==void 0){this.#assistantUsage=addUsage(this.#assistantUsage,runtimeUsage(message.usage,"cache_read_input_tokens"));events.push(...this.updateUsage(this.#assistantUsage))}return events}user(record3){const message=asRecord(record3.message,"Claude user message");const events=[];for(const block2 of contentBlocks(message.content,"Claude user content")){if(block2.type==="tool_result"){events.push(...this.toolCompleted(requiredString(block2,"tool_use_id"),block2.content??null))}}return events}result(record3){const isError=record3.is_error===true||record3.subtype!=="success";if(isError){const message=optionalString(record3.result)??errorMessage(record3.errors);return this.fail(message,optionalString(record3.subtype))}const providerUsage=record3.usage===void 0?null:runtimeUsage(record3.usage,"cache_read_input_tokens");return this.complete(optionalString(record3.result),maximumUsage(this.#assistantUsage,providerUsage))}};function contentBlocks(value,label){if(!Array.isArray(value))throw new Error(`${label} must be an array`);return value.map(block2=>asRecord(block2,label))}function errorMessage(value){if(!Array.isArray(value))return"Claude reported an unknown error";const messages=value.map(item=>optionalString(item)).filter(item=>item!==null);return messages.join("; ")||"Claude reported an unknown error"}function addUsage(previous,current){if(previous===null)return current;return{input_tokens:previous.input_tokens+current.input_tokens,cached_input_tokens:previous.cached_input_tokens+current.cached_input_tokens,output_tokens:previous.output_tokens+current.output_tokens,reasoning_tokens:previous.reasoning_tokens+current.reasoning_tokens,source:"provider"}}function maximumUsage(left,right){if(left===null)return right;if(right===null)return left;return{input_tokens:Math.max(left.input_tokens,right.input_tokens),cached_input_tokens:Math.max(left.cached_input_tokens,right.cached_input_tokens),output_tokens:Math.max(left.output_tokens,right.output_tokens),reasoning_tokens:Math.max(left.reasoning_tokens,right.reasoning_tokens),source:"provider"}}var CodexRuntimeProtocol=class{constructor(now=()=>new Date().toISOString()){this.now=now}now;prepare(invocation){const threadId=resumeId(invocation.resume_from,"codex");const args=threadId===null?["exec","--json","--model",invocation.model,"--config",`model_reasoning_effort=${JSON.stringify(invocation.reasoning_effort)}`,"-"]:["exec","resume",threadId,"--json","--model",invocation.model,"--config",`model_reasoning_effort=${JSON.stringify(invocation.reasoning_effort)}`,"-"];const translator=new CodexEventTranslator(invocation,this.now);return{args,stdin:renderInvocationPrompt(invocation),translate:value=>translator.translate(value),finish:()=>translator.finish()}}};var CodexEventTranslator=class extends NativeProtocolEmitter{#pendingError=null;#requestedTools=new Set;translate(value){const passthrough=this.passthrough(value);if(passthrough!==null)return passthrough;const record3=asRecord(value,"Codex event");const type=requiredString(record3,"type");if(type==="thread.started"){return this.start("codex",requiredString(record3,"thread_id"))}if(type==="turn.started")return[];if(type==="item.started")return this.itemStarted(asRecord(record3.item,"Codex item"));if(type==="item.completed")return this.itemCompleted(asRecord(record3.item,"Codex item"));if(type==="item.updated")return[];if(type==="turn.completed"){return this.complete(null,runtimeUsage(record3.usage,"cached_input_tokens"))}if(type==="turn.failed"){const error51=asRecord(record3.error,"Codex turn error");return this.fail(requiredString(error51,"message"),optionalString(error51.code))}if(type==="error"){this.#pendingError=optionalString(record3.message)??"Codex reported an unknown error";return[]}return[]}finish(){if(this.#pendingError!==null&&this.started&&!this.terminal){return this.fail(this.#pendingError)}return[]}itemStarted(item){const kind=requiredString(item,"type");if(!isToolItem(kind))return[];const callId=requiredString(item,"id");this.#requestedTools.add(callId);return this.toolRequested(callId,toolName(kind,item),toolArguments(kind,item))}itemCompleted(item){const kind=requiredString(item,"type");if(kind==="agent_message")return this.output(requiredString(item,"text"));if(!isToolItem(kind))return[];const callId=requiredString(item,"id");const events=this.#requestedTools.delete(callId)?[]:this.toolRequested(callId,toolName(kind,item),toolArguments(kind,item));events.push(...this.toolCompleted(callId,toolOutput(kind,item)));return events}};function isToolItem(kind){return kind==="command_execution"||kind==="file_change"||kind==="mcp_tool_call"||kind==="web_search"}function toolName(kind,item){if(kind==="command_execution")return"command_execution";if(kind==="file_change")return"file_change";if(kind==="web_search")return"web_search";const server=optionalString(item.server);const tool=optionalString(item.tool)??optionalString(item.name)??"unknown";return server===null?tool:`${server}.${tool}`}function toolArguments(kind,item){if(kind==="command_execution")return{command:item.command};if(kind==="file_change")return{changes:item.changes??item.files??[]};if(kind==="web_search")return{query:item.query};return item.arguments??item.input??{}}function toolOutput(kind,item){if(kind==="command_execution"){return{output:item.aggregated_output??item.output??"",exit_code:item.exit_code??null,status:item.status??null}}if(kind==="file_change")return item.changes??item.files??item.status??null;return item.result??item.output??item.error??null}init_agent_runtime();import{spawn}from"node:child_process";import{realpath as realpath3}from"node:fs/promises";import{isAbsolute as isAbsolute2,relative as relative2}from"node:path";import{createInterface}from"node:readline";var secretKey=/(?:authorization|password|secret|token|api[_-]?key|credential)/i;var secretValue=/(?:Bearer\s+[A-Za-z0-9._~+/-]+=*|sk-[A-Za-z0-9_-]{8,}|gh[opsu]_[A-Za-z0-9_]{8,})/g;function redactInvocation(invocation){return{...invocation,input:{...invocation.input,messages:invocation.input.messages.map(message=>({...message,content:redactText(message.content)}))},metadata:Object.fromEntries(Object.entries(invocation.metadata).map(([key,value])=>[key,secretKey.test(key)?"[REDACTED]":redactText(value)]))}}function redactText(value){return value.replace(secretValue,"[REDACTED]")}var NodeRuntimeProcessFactory=class{constructor(options){this.options=options;this.#commands=new Set(options.allowedCommands.map(normalizeCommand));this.#environmentKeys=new Set(options.allowedEnvironmentKeys)}options;#commands;#environmentKeys;async start(request,signal){if(!this.#commands.has(normalizeCommand(request.command))){throw new Error(`Runtime command is not allowlisted: ${request.command}`)}for(const key of Object.keys(request.environment)){if(!this.#environmentKeys.has(key)){throw new Error(`Runtime environment key is not allowlisted: ${key}`)}}const cwd=await this.#workingDirectory(request.cwd);const child=spawn(request.command,[...request.args],{cwd,env:{...this.options.baseEnvironment,...request.environment},shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const cancel=async()=>{if(child.exitCode===null&&child.signalCode===null)child.kill()};const abort=()=>void cancel();signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted===true)await cancel();child.stdin.on("error",()=>void 0);child.stdin.end(request.stdin);const maxStderrBytes=this.options.maxStderrBytes??65536;let stderr="";child.stderr.setEncoding("utf8");child.stderr.on("data",chunk=>{if(stderr.length<maxStderrBytes){stderr+=chunk.slice(0,maxStderrBytes-stderr.length)}});const lines=this.#lines(child,signal,abort,()=>stderr);return{lines,cancel:async()=>cancel()}}async#workingDirectory(candidate){if(candidate===void 0){throw new Error("Runtime working root must be explicit")}const cwd=await realpath3(candidate);const roots2=await Promise.all(this.options.allowedWorkingRoots.map(root=>realpath3(root)));if(!roots2.some(root=>isWithin(root,cwd))){throw new Error(`Runtime working root is not allowlisted: ${cwd}`)}return cwd}async*#lines(child,signal,abort,stderr){const reader=createInterface({input:child.stdout,crlfDelay:Infinity});const maxLineBytes=this.options.maxLineBytes??1048576;try{for await(const line of reader){if(Buffer.byteLength(line,"utf8")>maxLineBytes){child.kill();throw new Error(`Runtime output line exceeds ${maxLineBytes} bytes`)}yield line}const{code,childSignal}=await childExit(child);if(code!==0){const detail=redactText(stderr().trim());throw new Error(`Runtime process failed (${childSignal??String(code)})${detail===""?"":`: ${detail}`}`)}}finally{reader.close();signal?.removeEventListener("abort",abort)}}};function childExit(child){if(child.exitCode!==null||child.signalCode!==null){return Promise.resolve({code:child.exitCode,childSignal:child.signalCode})}return new Promise((resolve20,reject)=>{child.once("error",reject);child.once("close",(code,childSignal)=>resolve20({code,childSignal}))})}function isWithin(root,candidate){const path=relative2(root,candidate);return path===""||!isAbsolute2(path)&&path!==".."&&!path.startsWith(`..\\`)&&!path.startsWith("../")}function normalizeCommand(command){return process.platform==="win32"?command.toLowerCase():command}init_agent_runtime();var DISABLED_FEATURES=["shell_tool","unified_exec","code_mode_host","apps","plugins","multi_agent","browser_use","browser_use_external","in_app_browser","computer_use","image_generation","workspace_dependencies","artifact","hooks","goals","skill_search","skill_mcp_dependency_install"];function assertAstraDiagnosticEnvelope(invocation){if(invocation.model!=="gpt-6-astra")return;if(invocation.metadata.astra_mode!=="diagnostic"||invocation.metadata.role!=="diagnostic"||invocation.agent_id!=="agent-orchestrator"||!/^TASK-[A-Z0-9-]+$/.test(invocation.metadata.task_id??"")||!/^[1-3]$/.test(invocation.metadata.astra_cycle??"")||invocation.reasoning_effort!=="high"||invocation.resume_from!==null||invocation.input.tools.length!==0||invocation.input.response_format!=="json"||invocation.budget.max_tool_calls!==0||invocation.budget.timeout_ms===null||invocation.budget.timeout_ms>18e4||invocation.budget.max_output_tokens>8e3){throw new Error("Astra requires a reserved, fresh, high-only diagnostic envelope")}if(Buffer.byteLength(JSON.stringify(invocation.input),"utf8")>48e3){throw new Error("Astra diagnostic evidence exceeds the 48000-byte input envelope")}}async function constrainAstraCodexRequest(factory,request,signal){const disabled=DISABLED_FEATURES.flatMap(feature=>["--disable",feature]);const inspection=await factory.start({...request,args:["--disable","plugins","--disable","apps","mcp","list","--json"],stdin:""},signal);const cancel=()=>{void inspection.cancel("timeout").catch(()=>void 0)};signal.addEventListener("abort",cancel,{once:true});let raw="";try{if(signal.aborted){await inspection.cancel("timeout");throw new Error("Astra configuration inspection aborted")}for await(const line of inspection.lines){raw+=`${line}
1842
- `;if(Buffer.byteLength(raw,"utf8")>1048576){await inspection.cancel("budget");throw new Error("Astra configuration inspection exceeded its size limit")}}}finally{signal.removeEventListener("abort",cancel)}if(signal.aborted)throw new Error("Astra configuration inspection aborted");let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("Astra configuration inspection could not verify MCP isolation")}if(!Array.isArray(parsed)){throw new Error("Astra configuration inspection returned an unsupported schema")}const names=[];for(const server of parsed){if(typeof server!=="object"||server===null||typeof server.name!=="string"||!/^[A-Za-z0-9_.-]{1,200}$/.test(server.name))throw new Error("Astra configuration inspection returned an invalid MCP identity");names.push(server.name)}const mcpOverrides=[...new Set(names)].flatMap(name=>["--config",`mcp_servers.${JSON.stringify(name)}.enabled=false`]);return{...request,args:[...request.args.slice(0,-1),"--strict-config","--sandbox","read-only","--ephemeral","--config",'approval_policy="never"',"--config",'web_search="disabled"',"--config","tools.view_image=false","--config","project_doc_max_bytes=0",...disabled,...mcpOverrides,"-"]}}init_src();function isAutonomyInvocation(invocation){return invocation.metadata.autonomy_policy==="autonomy-v1"}function assertAutonomyEnvelope(invocation){const preset=autonomyPresetSchema.parse(invocation.metadata.autonomy_preset);const source=invocation.metadata.source;const role=invocation.metadata.role;if(!["task","spec","prd"].includes(source??"")||!["builder","verifier","finalizer","diagnostic"].includes(role??""))throw new Error("Invalid autonomy process identity");const ordinal=Number(invocation.metadata.replan);assertAutonomyModel({preset,source,role:role==="diagnostic"?"replanner":role==="builder"?"executor":role==="verifier"?"reviewer":"finalizer",model:invocation.model,reasoning_effort:invocation.reasoning_effort,manual_selection:false,replan:ordinal});if(invocation.budget.timeout_ms!==null)throw new Error("Autonomy-v1 does not abandon attempts by elapsed time");if(role!=="diagnostic")return;const expected=replanModel(preset,ordinal);if(invocation.model!==expected.model||invocation.reasoning_effort!==expected.reasoning_effort||invocation.agent_id!=="agent-orchestrator"||!/^TASK-[A-Z0-9-]+$/.test(invocation.metadata.task_id??"")||invocation.resume_from!==null||invocation.input.tools.length!==0||invocation.budget.max_tool_calls!==0||invocation.input.response_format!=="json"||invocation.budget.max_output_tokens>8e3||Buffer.byteLength(JSON.stringify(invocation.input),"utf8")>48e3)throw new Error("Invalid fresh read-only autonomy replan envelope")}var RuntimeCapabilityError=class extends Error{constructor(capability,requested){super(`Runtime does not support requested ${capability}: ${requested}`);this.capability=capability;this.requested=requested;this.name="RuntimeCapabilityError"}capability;requested;code="RUNTIME_CAPABILITY_UNSUPPORTED"};var ProcessAgentRuntime=class{constructor(processFactory,options){this.processFactory=processFactory;this.options=options;this.#capabilities=runtimeCapabilitiesSchema.parse(options.capabilities)}processFactory;options;#sessions=new Map;#capabilities;async capabilities(){return this.#capabilities}async*invoke(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,false);yield*this.#execute(invocation,signal)}async*resume(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,true);yield*this.#execute(invocation,signal)}async cancel(candidate){const cancellation=runtimeCancellationSchema.parse(candidate);if(!this.#capabilities.cancellation)throw new Error("Runtime does not support cancellation");const session=this.#sessions.get(cancellation.invocation_id);if(session!==void 0)await session.cancel(cancellation.reason)}async*#execute(invocation,signal){throwIfRuntimeAborted(signal);if(this.#sessions.has(invocation.invocation_id)){throw new Error(`Invocation already active: ${invocation.invocation_id}`)}const controller=new AbortController;let cancellationReason="user";const relayAbort=()=>controller.abort(signal?.reason??new Error("Runtime aborted"));signal?.addEventListener("abort",relayAbort,{once:true});const timeout=invocation.budget.timeout_ms===null?null:setTimeout(()=>{cancellationReason="timeout";controller.abort(new Error(`Runtime timeout exceeded: ${invocation.budget.timeout_ms}ms`))},invocation.budget.timeout_ms);const aborted2=abortRejection(controller.signal);const redacted=redactInvocation(invocation);const protocol=(this.options.protocol??zaipJsonlProtocol).prepare(redacted,this.options.args);let request={command:this.options.command,args:protocol.args,stdin:protocol.stdin,environment:{...this.options.environment},...this.options.workingDirectory===void 0?{}:{cwd:typeof this.options.workingDirectory==="function"?this.options.workingDirectory(invocation):this.options.workingDirectory}};let session;let iterator;try{if(isAutonomyInvocation(invocation)&&invocation.metadata.role!=="diagnostic"){request={...request,args:[...request.args.slice(0,-1),"--disable","multi_agent","-"]}}if(isAutonomyInvocation(invocation)?invocation.metadata.role==="diagnostic":invocation.model==="gpt-6-astra"){request=await Promise.race([constrainAstraCodexRequest(this.processFactory,request,controller.signal),aborted2])}session=await Promise.race([this.processFactory.start(request,controller.signal),aborted2]);this.#sessions.set(invocation.invocation_id,session);controller.signal.addEventListener("abort",()=>void session?.cancel(cancellationReason),{once:true});if(controller.signal.aborted)await session.cancel(cancellationReason);const events=[];let toolCalls=0;iterator=session.lines[Symbol.asyncIterator]();while(true){const next=await Promise.race([iterator.next(),aborted2]);if(next.done===true)break;for(const translated of protocol.translate(JSON.parse(next.value))){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}}for(const translated of protocol.finish()){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}validateRuntimeEventStream(invocation,events)}finally{if(timeout!==null)clearTimeout(timeout);signal?.removeEventListener("abort",relayAbort);await iterator?.return?.();this.#sessions.delete(invocation.invocation_id)}}#negotiate(invocation,resuming){if(isAutonomyInvocation(invocation))assertAutonomyEnvelope(invocation);else assertAstraDiagnosticEnvelope(invocation);if(isAutonomyInvocation(invocation)&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires the Codex process protocol")}if(invocation.model==="gpt-6-astra"&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("Astra requires the constrained Codex diagnostic process protocol")}if(!this.#capabilities.models.includes(invocation.model)){throw new RuntimeCapabilityError("model",invocation.model)}if(!this.#capabilities.reasoning_efforts.includes(invocation.reasoning_effort)){throw new RuntimeCapabilityError("reasoning_effort",invocation.reasoning_effort)}if(!this.#capabilities.velocities.includes(invocation.velocity)){throw new RuntimeCapabilityError("velocity",invocation.velocity)}if(invocation.input.tools.length>0&&!this.#capabilities.tool_calls){throw new RuntimeCapabilityError("tool_calls","enabled")}if(invocation.input.response_format==="json"&&!this.#capabilities.structured_output){throw new RuntimeCapabilityError("structured_output","json")}if(resuming&&(!this.#capabilities.resume||invocation.resume_from===null)){throw new RuntimeCapabilityError("resume",invocation.resume_from??"missing-checkpoint")}}};function abortRejection(signal){return new Promise((_,reject)=>{const fail=()=>reject(signal.reason??new Error("Runtime aborted"));if(signal.aborted)fail();else signal.addEventListener("abort",fail,{once:true})})}async function enforceRuntimeBudget(invocation,event,currentToolCalls,session){const toolCalls=currentToolCalls+(event.type==="tool.requested"?1:0);if(toolCalls>invocation.budget.max_tool_calls){await session.cancel("budget");throw new Error(`Runtime tool-call budget exceeded: ${toolCalls}/${invocation.budget.max_tool_calls}`)}if((event.type==="usage.updated"||event.type==="invocation.completed")&&event.usage.output_tokens>invocation.budget.max_output_tokens){await session.cancel("budget");throw new Error(`Runtime output-token budget exceeded: ${event.usage.output_tokens}/${invocation.budget.max_output_tokens}`)}return toolCalls}function codexRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new CodexRuntimeProtocol,capabilities:providerCapabilities("codex",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function claudeRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new ClaudeRuntimeProtocol,capabilities:providerCapabilities("claude",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function providerCapabilities(provider,models){return{provider,models:[...models],reasoning_efforts:provider==="codex"?["low","medium","high","xhigh"]:["low","medium","high"],velocities:["standard"],streaming:true,cancellation:true,checkpointing:true,resume:true,tool_calls:true,structured_output:true,max_parallel_invocations:4}}init_src();import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";import{createHash as createHash5}from"node:crypto";var REQUIRED_PROFILE_CAPABILITIES=["explicit-lifecycle-ids","context-budget","independent-review","mcp-stdio","deny-by-default"];var APPLICABLE_AGENT_PATHS={codex:".agents/config/clients/codex/agents",claude:".claude/agents",antigravity:".antigravity/agents",gemini:".gemini/agents",cursor:".cursor/agents",copilot:".github/agents",generic:".zaip/agents"};var APPLICABLE_AGENT_SUFFIXES={codex:".toml",claude:".md"};function validateProfileCatalog(catalog){const findings=[];const ids=new Set;for(const profile of catalog.profiles){if(ids.has(profile.id))findings.push(`duplicate:${profile.id}`);ids.add(profile.id);for(const capability of REQUIRED_PROFILE_CAPABILITIES){if(!["native","emulated","unsupported"].includes(profile.capabilities[capability])){findings.push(`missing:${profile.id}:${capability}`)}}for(const path of[profile.guidance_path,profile.agent_path,profile.mcp_config_path]){if(path.length===0||path.includes(".."))findings.push(`unsafe-path:${profile.id}`)}if(profile.agent_path!==APPLICABLE_AGENT_PATHS[profile.id]){findings.push(`inapplicable-agent-path:${profile.id}:${profile.agent_path}`)}}for(const client of["codex","claude","antigravity","gemini","cursor","copilot","generic"]){if(!ids.has(client))findings.push(`missing-client:${client}`)}const semantic=catalog.profiles.map(profile=>({id:profile.id,capabilities:profile.capabilities})).sort((left,right)=>left.id.localeCompare(right.id));return{valid:findings.length===0,findings:findings.sort(),semantic_hash:digest2(stableJson2(semantic))}}async function validateConfiguredProfileAgentPaths(catalog,enabledClients,filesystem){const parity=validateProfileCatalog(catalog);const findings=[...parity.findings];for(const client of["codex","claude"]){if(!enabledClients[client])continue;const profile=catalog.profiles.find(candidate=>candidate.id===client);if(profile===void 0){findings.push(`missing-client:${client}`);continue}try{if(!await filesystem.exists(profile.agent_path)){findings.push(`missing-agent-path:${client}:${profile.agent_path}`);continue}const profiles=await filesystem.listFiles(profile.agent_path,APPLICABLE_AGENT_SUFFIXES[client]);if(profiles.length===0){findings.push(`empty-agent-path:${client}:${profile.agent_path}`)}}catch{findings.push(`inapplicable-agent-path:${client}:${profile.agent_path}`)}}return{valid:findings.length===0,findings:[...new Set(findings)].sort(),semantic_hash:parity.semantic_hash}}function stableJson2(value){return JSON.stringify(sortValue3(value),null,2)}function sortValue3(value){if(Array.isArray(value))return value.map(sortValue3);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,item])=>[key,sortValue3(item)]))}return value}function digest2(value){return createHash5("sha256").update(value).digest("hex")}var execFileAsync2=promisify2(execFile2);import{execFile as execFile3}from"node:child_process";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3);var ADAPTERS_VERSION="3.5.0";var USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);var CLAUDE_SETTINGS=`{
1873
+ `;if(Buffer.byteLength(raw,"utf8")>1048576){await inspection.cancel("budget");throw new Error("Astra configuration inspection exceeded its size limit")}}}finally{signal.removeEventListener("abort",cancel)}if(signal.aborted)throw new Error("Astra configuration inspection aborted");let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("Astra configuration inspection could not verify MCP isolation")}if(!Array.isArray(parsed)){throw new Error("Astra configuration inspection returned an unsupported schema")}const names=[];for(const server of parsed){if(typeof server!=="object"||server===null||typeof server.name!=="string"||!/^[A-Za-z0-9_.-]{1,200}$/.test(server.name))throw new Error("Astra configuration inspection returned an invalid MCP identity");names.push(server.name)}const mcpOverrides=[...new Set(names)].flatMap(name=>["--config",`mcp_servers.${JSON.stringify(name)}.enabled=false`]);return{...request,args:[...request.args.slice(0,-1),"--strict-config","--sandbox","read-only","--ephemeral","--config",'approval_policy="never"',"--config",'web_search="disabled"',"--config","tools.view_image=false","--config","project_doc_max_bytes=0",...disabled,...mcpOverrides,"-"]}}init_src();function isAutonomyInvocation(invocation){return invocation.metadata.autonomy_policy==="autonomy-v1"}function assertAutonomyEnvelope(invocation){const preset=autonomyPresetSchema.parse(invocation.metadata.autonomy_preset);const source=invocation.metadata.source;const role=invocation.metadata.role;if(!["task","spec","prd"].includes(source??"")||!["builder","verifier","finalizer","diagnostic"].includes(role??""))throw new Error("Invalid autonomy process identity");const ordinal=Number(invocation.metadata.replan);assertAutonomyModel({preset,source,role:role==="diagnostic"?"replanner":role==="builder"?"executor":role==="verifier"?"reviewer":"finalizer",model:invocation.model,reasoning_effort:invocation.reasoning_effort,manual_selection:false,replan:ordinal});if(invocation.budget.timeout_ms!==null)throw new Error("Autonomy-v1 does not abandon attempts by elapsed time");if(role!=="diagnostic")return;const expected=replanModel(preset,ordinal);if(invocation.model!==expected.model||invocation.reasoning_effort!==expected.reasoning_effort||invocation.agent_id!=="agent-orchestrator"||!/^TASK-[A-Z0-9-]+$/.test(invocation.metadata.task_id??"")||invocation.resume_from!==null||invocation.input.tools.length!==0||invocation.budget.max_tool_calls!==0||invocation.input.response_format!=="json"||invocation.budget.max_output_tokens>8e3||Buffer.byteLength(JSON.stringify(invocation.input),"utf8")>48e3)throw new Error("Invalid fresh read-only autonomy replan envelope")}var RuntimeCapabilityError=class extends Error{constructor(capability,requested){super(`Runtime does not support requested ${capability}: ${requested}`);this.capability=capability;this.requested=requested;this.name="RuntimeCapabilityError"}capability;requested;code="RUNTIME_CAPABILITY_UNSUPPORTED"};var ProcessAgentRuntime=class{constructor(processFactory,options){this.processFactory=processFactory;this.options=options;this.#capabilities=runtimeCapabilitiesSchema.parse(options.capabilities)}processFactory;options;#sessions=new Map;#capabilities;async capabilities(){return this.#capabilities}async*invoke(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,false);yield*this.#execute(invocation,signal)}async*resume(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,true);yield*this.#execute(invocation,signal)}async cancel(candidate){const cancellation=runtimeCancellationSchema.parse(candidate);if(!this.#capabilities.cancellation)throw new Error("Runtime does not support cancellation");const session=this.#sessions.get(cancellation.invocation_id);if(session!==void 0)await session.cancel(cancellation.reason)}async*#execute(invocation,signal){throwIfRuntimeAborted(signal);if(this.#sessions.has(invocation.invocation_id)){throw new Error(`Invocation already active: ${invocation.invocation_id}`)}const controller=new AbortController;let cancellationReason="user";const relayAbort=()=>controller.abort(signal?.reason??new Error("Runtime aborted"));signal?.addEventListener("abort",relayAbort,{once:true});const timeout=invocation.budget.timeout_ms===null?null:setTimeout(()=>{cancellationReason="timeout";controller.abort(new Error(`Runtime timeout exceeded: ${invocation.budget.timeout_ms}ms`))},invocation.budget.timeout_ms);const aborted2=abortRejection(controller.signal);const redacted=redactInvocation(invocation);const protocol=(this.options.protocol??zaipJsonlProtocol).prepare(redacted,this.options.args);let request={command:this.options.command,args:protocol.args,stdin:protocol.stdin,environment:{...this.options.environment},...this.options.workingDirectory===void 0?{}:{cwd:typeof this.options.workingDirectory==="function"?this.options.workingDirectory(invocation):this.options.workingDirectory}};let session;let iterator;try{if(isAutonomyInvocation(invocation)&&invocation.metadata.role!=="diagnostic"){request={...request,args:[...request.args.slice(0,-1),"--disable","multi_agent","-"]}}if(isAutonomyInvocation(invocation)?invocation.metadata.role==="diagnostic":invocation.model==="gpt-6-astra"){request=await Promise.race([constrainAstraCodexRequest(this.processFactory,request,controller.signal),aborted2])}session=await Promise.race([this.processFactory.start(request,controller.signal),aborted2]);this.#sessions.set(invocation.invocation_id,session);controller.signal.addEventListener("abort",()=>void session?.cancel(cancellationReason),{once:true});if(controller.signal.aborted)await session.cancel(cancellationReason);const events=[];let toolCalls=0;iterator=session.lines[Symbol.asyncIterator]();while(true){const next=await Promise.race([iterator.next(),aborted2]);if(next.done===true)break;for(const translated of protocol.translate(JSON.parse(next.value))){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}}for(const translated of protocol.finish()){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}validateRuntimeEventStream(invocation,events)}finally{if(timeout!==null)clearTimeout(timeout);signal?.removeEventListener("abort",relayAbort);await iterator?.return?.();this.#sessions.delete(invocation.invocation_id)}}#negotiate(invocation,resuming){if(isAutonomyInvocation(invocation))assertAutonomyEnvelope(invocation);else assertAstraDiagnosticEnvelope(invocation);if(isAutonomyInvocation(invocation)&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires the Codex process protocol")}if(invocation.model==="gpt-6-astra"&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("Astra requires the constrained Codex diagnostic process protocol")}if(!this.#capabilities.models.includes(invocation.model)){throw new RuntimeCapabilityError("model",invocation.model)}if(!this.#capabilities.reasoning_efforts.includes(invocation.reasoning_effort)){throw new RuntimeCapabilityError("reasoning_effort",invocation.reasoning_effort)}if(!this.#capabilities.velocities.includes(invocation.velocity)){throw new RuntimeCapabilityError("velocity",invocation.velocity)}if(invocation.input.tools.length>0&&!this.#capabilities.tool_calls){throw new RuntimeCapabilityError("tool_calls","enabled")}if(invocation.input.response_format==="json"&&!this.#capabilities.structured_output){throw new RuntimeCapabilityError("structured_output","json")}if(resuming&&(!this.#capabilities.resume||invocation.resume_from===null)){throw new RuntimeCapabilityError("resume",invocation.resume_from??"missing-checkpoint")}}};function abortRejection(signal){return new Promise((_,reject)=>{const fail=()=>reject(signal.reason??new Error("Runtime aborted"));if(signal.aborted)fail();else signal.addEventListener("abort",fail,{once:true})})}async function enforceRuntimeBudget(invocation,event,currentToolCalls,session){const toolCalls=currentToolCalls+(event.type==="tool.requested"?1:0);if(toolCalls>invocation.budget.max_tool_calls){await session.cancel("budget");throw new Error(`Runtime tool-call budget exceeded: ${toolCalls}/${invocation.budget.max_tool_calls}`)}if((event.type==="usage.updated"||event.type==="invocation.completed")&&event.usage.output_tokens>invocation.budget.max_output_tokens){await session.cancel("budget");throw new Error(`Runtime output-token budget exceeded: ${event.usage.output_tokens}/${invocation.budget.max_output_tokens}`)}return toolCalls}function codexRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new CodexRuntimeProtocol,capabilities:providerCapabilities("codex",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function claudeRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new ClaudeRuntimeProtocol,capabilities:providerCapabilities("claude",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function providerCapabilities(provider,models){return{provider,models:[...models],reasoning_efforts:provider==="codex"?["low","medium","high","xhigh"]:["low","medium","high"],velocities:["standard"],streaming:true,cancellation:true,checkpointing:true,resume:true,tool_calls:true,structured_output:true,max_parallel_invocations:4}}init_src();import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";import{createHash as createHash5}from"node:crypto";var REQUIRED_PROFILE_CAPABILITIES=["explicit-lifecycle-ids","context-budget","independent-review","mcp-stdio","deny-by-default"];var APPLICABLE_AGENT_PATHS={codex:".agents/config/clients/codex/agents",claude:".claude/agents",antigravity:".antigravity/agents",gemini:".gemini/agents",cursor:".cursor/agents",copilot:".github/agents",generic:".zaip/agents"};var APPLICABLE_AGENT_SUFFIXES={codex:".toml",claude:".md"};function validateProfileCatalog(catalog){const findings=[];const ids=new Set;for(const profile of catalog.profiles){if(ids.has(profile.id))findings.push(`duplicate:${profile.id}`);ids.add(profile.id);for(const capability of REQUIRED_PROFILE_CAPABILITIES){if(!["native","emulated","unsupported"].includes(profile.capabilities[capability])){findings.push(`missing:${profile.id}:${capability}`)}}for(const path of[profile.guidance_path,profile.agent_path,profile.mcp_config_path]){if(path.length===0||path.includes(".."))findings.push(`unsafe-path:${profile.id}`)}if(profile.agent_path!==APPLICABLE_AGENT_PATHS[profile.id]){findings.push(`inapplicable-agent-path:${profile.id}:${profile.agent_path}`)}}for(const client of["codex","claude","antigravity","gemini","cursor","copilot","generic"]){if(!ids.has(client))findings.push(`missing-client:${client}`)}const semantic=catalog.profiles.map(profile=>({id:profile.id,capabilities:profile.capabilities})).sort((left,right)=>left.id.localeCompare(right.id));return{valid:findings.length===0,findings:findings.sort(),semantic_hash:digest2(stableJson2(semantic))}}async function validateConfiguredProfileAgentPaths(catalog,enabledClients,filesystem){const parity=validateProfileCatalog(catalog);const findings=[...parity.findings];for(const client of["codex","claude"]){if(!enabledClients[client])continue;const profile=catalog.profiles.find(candidate=>candidate.id===client);if(profile===void 0){findings.push(`missing-client:${client}`);continue}try{if(!await filesystem.exists(profile.agent_path)){findings.push(`missing-agent-path:${client}:${profile.agent_path}`);continue}const profiles=await filesystem.listFiles(profile.agent_path,APPLICABLE_AGENT_SUFFIXES[client]);if(profiles.length===0){findings.push(`empty-agent-path:${client}:${profile.agent_path}`)}}catch{findings.push(`inapplicable-agent-path:${client}:${profile.agent_path}`)}}return{valid:findings.length===0,findings:[...new Set(findings)].sort(),semantic_hash:parity.semantic_hash}}function stableJson2(value){return JSON.stringify(sortValue3(value),null,2)}function sortValue3(value){if(Array.isArray(value))return value.map(sortValue3);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,item])=>[key,sortValue3(item)]))}return value}function digest2(value){return createHash5("sha256").update(value).digest("hex")}var execFileAsync2=promisify2(execFile2);import{execFile as execFile3}from"node:child_process";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3);var ADAPTERS_VERSION="3.6.0";var USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);var CLAUDE_SETTINGS=`{
1843
1874
  "permissions": {
1844
1875
  "allow": [],
1845
1876
  "deny": []
@@ -2015,7 +2046,7 @@ statusMessage = "Finalizing ZAIP subagent Run"
2015
2046
  `," catalysts","\u0643\u0631\u0647","\uB0BC","=z","\xE8h","\u0412\u0421"," \u0AAB\u0AC7\u0AB0"," \u5927\u91D1"," conocidas"," Vold"," #-}\n\n"," \u5929\u5929\u4E2D\u5F69\u7968\u817E\u8BAF"," Kyiv"," \u06AB\u0631"," \u0632\u0627\u0626\u062F","ipsoid","brightness","*>(&"," \u0C95\u0CBE\u0CAE"," Federaalka"," \u0436\u044B\u0446\u0446\u0451"," santos","\u2018zbekiston","roog"," Lourdes"," claridad"," occasione"," \u4E3E\u62A5","\u044A\u044F\u0441","gross"," \u5E0C","\u05D9\u05D9\u05E2\u05DF"," \u0561\u0580\u0587","\u0435\u0447\u043D\u044B\u0445","\u5A31\u4E50\u5F69\u7968\u6CE8\u518C"," torsdag"," k\xE9o"," kisim","buyers","\u043F\u0430\u043B",".Merge"," Cursos"," \uB300\uC2E0"," \u0645\u0627\u064A"," jur\xEDdicas","\u6A21\u677F","\u0438\u043B\u0430\u043A","muy","\u03BD\u03BF\u03BC\u03B1"," cuadros"," \u0AA6\u0AC7\u0AB6\u0AAE\u0ABE\u0A82","\u0441\u0442\u0440\u0438"," \u062F\u0648\u062F","niejszych","Renderable"," \u670B\u514B","\u03C3\u03B1\u03B9"," Promotional",".Completed"," \u043A\u0430\u043D\u0446"," d\xE9ten"," m\xF5ned","(goal"," hugging"," L\xEBtz"," yaba"," enigmatic"," \u041A\u0440\u0430\u0441\u043D\u043E\u0434\u0430\u0440"," v\xE4nt"," \xE9l\xE9gant"," europeu"," Shelton"," Hombre","aher","exclusive",'">%'," gabi","visional"," est\xE9s"," ge\xEFntegre"," \u043F\u043E\u043B\u0443\u0447\u0438\u043B\u043E\u0441\u044C"," RIS","\u30CB\u30F3\u30B0","\u09BF\u09DF\u09BE\u09A8","Covered"," letos"," \u043A\u0430\u0442\u0430\u043B\u043E\u0433","\u0301s"," Garfield","Generators","(vc","\u0C46\u0C02\u0C2C\u0C30\u0C4D","\u09BE\u09B0\u09CD\u09B8"," \u06CB\u0627\u0642\u062A\u0649","\u1E63i\u1E63\u1EB9",`']?>"`," taamatut",".poster"," \u043F\u0440\u044B\u043C"," enlever","edf"," \u10D9\u10D8\u10D7\u10EE\u10D5"," \u043F\u0438\u0442\u043E\u043C","?>\n\n\n","/banner","\u093F\u0930\u0939\u0947\u0915\u093E"," contrari",".discovery"," gui",".false","\u3055\u308C\u3066\u3044\u307E\u3059"," Lettre"," percentual"," ibn","\u4E0D\u4EC5"," storyteller","Ontario","maks","\u03BB\u03B5\u03C2"," tett"," kapcsolat"," \u043C\u0443\u0430\u0439"," \u056F\u0578\u0582\u0576\u0565\u0576"," Warp","\u8A2D\u5099","\u2019aider","Indice"," \u7406","ituen",";TZID"," kusema"," Slick","\u05E0\u05D9\u05D4\u05D5"," inhale"," umgehen"," \u06A9\u0627\u0628"," przeci"," \u0493\u0430\u0441\u044B\u0440"," adn"," wardrobes"," Tg","_linux"," pm"," \u0433\u043B\u0430\u0432\u043D\u044B\u043C"," \u0441\u0430\u049B\u0442\u0430\u0443"," \u0631\u062D\u0644\u0629",'"]],\n'," par\xE7"," \u0437\u0430\u0435\u043C"," {/",".tell","\u03C3\u03B1\u03BC\u03B5"," Reveal","\u092C\u0948"," belirt"," wholeheartedly","nostic","k\xE9ho","lika","\\Traits"," kalor","Worst","\u0432\u0430\u044E\u0446\u0446\u0430",".gold","PIRED"," gratifying","(IService"," vuod"," hv\xF8r"," lichaams","rack"," discriminator"," \u0C35\u0C1A\u0C4D\u0C1A\u0C47","Eles"," inhibitory"," \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440"," leute","-Friday","Servidor",".PUBLIC"," \u09A6\u09BF\u09A8\u09C7"," \u0434\u04E9\u0440"," kleurr"," \u0440\u0430\u04B3"," F\xE9lix"," Burmese"," jahr",[158,225,131,152,225,131,160,225,131,152,225,131,161,225,131,158],"\u0941\u0915\u094B","Healing"," zahtev","ptable","\u0437\u0432"," \u0643\u064A\u0644\u0648"," \u5929\u5929\u4E2D\u5F69\u7968\u5145\u503C"," trovato","%);\n"," \u062A\u0634\u064A\u0631"," gamut","\u7238\u7238"," \u0645\u0642\u0627\u0644","\u2019artiste","-nowrap","-readable"," virar","Yer","Hasher","}}],\n","(mt"," izraz","Gir"," haum","\u0435\u043C\u043E\u043D"," \u10D6\u10DD\u10D2\u10D8"," Debido"," ctrl",".office","servo","-visible"," \u05EA\u05D5\u05D3\u05D4"," remorse","amiin","Kaz"," BOR"," Airports"," postagem"," saha","Kurz"," Einkaufs"," schlech"," sedation"," leaflet","tris"," pitk\xE4","\u5362"," aj\xE1n","\u0632\u064A\u0627\u0621"," \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u044F"," cognit","\u0430\u043D\u0430\u043C","/About"," \u0447\u0435\u0441\u0442\u044C","\u0161ni"," Process"," Pkw"," Vap","\u5BB9\u91CF",' }}"><'," (!["," Burgundy"," taws"," Bays"," langleb","pret\xE9"," strenuous"," Ebenso","\xE1vamos","\u2019esper"," \u044F\u0441\u043D\u043E"," \u092A\u0941\u0923"," \u067E\u0631\u0645\u062E\u062A"," \u624B\u673A\u7248\u5929\u5929\u4E2D\u5F69\u7968","-mouth","(Route"," precej"," \u063A\u0630\u0627\u06CC\u06CC","riffe"," \uC81C\uC8FC","ancis"," AGR"," \u0440\u0435\u0437\u043A\u043E"," teatral",[32,230,166]," shortening"," \u05D5\u05D4\u05E8"," Raising"," "," traurig","\u0259zi","persoon"," bygger"," exerce"," PDE"," Skilled"," k\xE6r","\u0438\u0440\u043E\u0432\u043A\u0443"," WOR"," Tepp","bakan"," Reactor"," reuni\xF3"," SBM"," nasil"," \u4E07\u5229","_Invalid"," uygulan"," vider"," \u0C2A\u0C4D\u0C30\u0C1A"," \u0438\u043D\u0434\u0435\u043A\u0441"," contatos"," \u0441\u0442\u0435\u043F\u0435\u043D\u044C","_you","ordinateur","\u4E0A\u7EBF"," couvrir"," ruso",".softmax"," \u0628\u0631\u0634\u0644\u0648\u0646\u0629","\u0D24\u0D4D\u0D24\u0D3F\u0D28\u0D41"," \u0AB5\u0ABF\u0A97\u0AA4\u0ACB"," Pixabay"," phi\xEAn"," BENEF","\u0637\u0627"," wyj\u0105tk","resar"," nabi"," podp"," \u09B6\u09BE\u09B9"," saavad"," Equivalent"," etree","\u6276\u8D2B","Cuda","\u06CC\u06A9\u0627\u0631"," ballast"," SAE","trizes"," detaine","\u2019ir"," ta\xFDdan","\u0413\u0410","\u04AD\u0435\u0438"," \u05D5\u05DC\u05E2","-With","ARRIER"," meek"," \u067E\u0631\u0648\u0646","'autant","posti","_reserved","\u0430\u043A\u0441","\uC564"," NICE"," \u0627\u0644\u062C\u0645\u0647\u0648\u0631"," erzielt"," gecontrole","\u0561\u0581\u0578\u0582\u0574\u0568"," \u043E\u043C\u0430","\u300B\u3002\n\n","ADVERTISEMENT"," curricula"," Au\xDF","LEGE"," \u0440\u0456\u0448\u0435\u043D\u043D\u044F"," comandos"," \u05DC\u05D4\u05DB","\u0431\u0440\u0435","osive","Fond"," aislamiento","_relu"," TSR"," Linien"," rame"," Envelope"," injectable","licenses"," drehen","Dak","f\xF8rer"," \u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F"," Numerical"," myaka"," vzt"," whakata"," St\xE4rke","gha"," \u05DC\u05E4\u05EA"," pomme"," daa","-painted","\u6765\u4E5F","IRIT","-ang"," trhu","!important","Faq"," B\xFCnd","\u0CBF\u0CB8\u0CC1\u0CA4\u0CCD\u0CA4\u0CA6\u0CC6"," Spitz"," taky","Decompiler",")':","liegenden"," at\u1EB9","\uFF0C\u4F8B\u5982","\xF6hnt"," \u0907\u0932\u093E\u0915\u0947"," tiltak"," tangu"," \u0CAC\u0CB0\u0CC1\u0CA4\u0CCD\u0CA4","nske"," \u0635\u0646\u0627\u06CC\u0639"," \u092A\u0941\u0930\u093E\u0928\u0947","getwijfeld"," Accredited","\u2019nde","\u043B\u043E\u0433\u043E"," microp"," svog","_due","\u043B\u043E\u0449\u0430\u0434"," Dorn"," \u0C9A\u0CBF\u0C95\u0CBF\u0CA4\u0CCD\u0CB8\u0CC6"," \u0A28\u0A3E"," \u05E4\u05E0\u05D9"," ger\xE7ekten"," \u0440\u0430\u0437\u0432\u0435\u0434","\xE9pe"," hsv"," Clearwater"," naq","\u62C9\u7279"," d\xE9tour","_Length"," Zodra"," casualty"," zusammensch"," mandi"," \u10E8\u10D4\u10E1\u10D0\u10EB\u10DA\u10D4\u10D1\u10D4\u10DA\u10D8\u10D0"," Travels","atika"," \u0BA8\u0BC0\u0BA4","\u092E\u0924\u0940"," presentamos"," hinged"," Rotor"," \u10EC\u10E7\u10D0\u10DA","N\xED"," sexvideo"," \u043A\u0440\u0438\u0442\u0435\u0440","-Shabaab"," \uACF5\uC5F0","_population"," Aziz","\u7089"," \u05D9\u05DC\u05D3"," kaban"," d\xE9put\xE9"," trembling","\u3001\u7B2C"," \u0639\u0627\u0645\u0627\u064B"," Bayesian"," \u9875\u9762","\u09BE\u0981\u0993"," Etat"," ge\xE7irmek"," \u0411\u04B1",".effects","APK"," gwamnatin"," sujeitos"," \u0CB8\u0CBE\u0C97"," \u092C\u091C\u093E\u092F",[32,240,159,141]," \u0628\u062F\u0627"," Racer","zky"," \u6E58","argando"," \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439"," Christensen"," \u0576\u0577\u0565\u0581"," Emery",".ber"," \u043E\u0493\u043E\u0437"," \u0633\u0644\u0637\u0627\u0646","pt\u0103m"," \u0627\u0644\u0631\u062D\u064A\u0645"," \u05D7\u05D5\u05D1\u05D4","\u10D0\u10E1\u10D0"," neuze"," \u10E1\u10D8\u10E7\u10D5\u10D0\u10E0\u10E3\u10DA"," aeroport","servez"," neug"," \u0D2A\u0D30\u0D3F\u0D36\u0D40\u0D32"," responsabilit\xE9s","\u0131kl\u0131"," \u10D0\u10DC\u10D2\u10D0\u10E0\u10D8\u10E8",".Then","_annotations"," \u092E\u093E\u0924\u094D\u0930\u0948"," Normandy"," zusamment","/render"," participaram","gemeinschaft"," maayo",".Attach",".Mag"," \u0441\u043E\u043B\u04B3\u043E\u0438","Cartesian",".Pull"," articulation"," tair","_Surface","ptious"," \u4F01\u4E1A","int\xE4\xE4n"," \u056A\u0578\u0572\u0578\u057E\u0580\u0564\u056B","_coupon","\u03B9\u03BA\u03B7"," egingo"," p\u016Bnaewele","\uCC0D"," CDL",'"|'," \u0633\u0631\u0686"," item's"," chronology"," facelift"," sturd"," Mathieu","occur","jubl",' ".\n',"\u0639\u062F\u0644"," "," PIT"," \u0627\u0644\u062C\u0648"," \u091A\u0932\u0940","_Master","Treas","UPLOAD"," publicou"," Devin"," categorize"," Rik"," proqram"," \u043E\u0442\u0432\u0435\u0442\u0430"," \u10E1\u10D0\u10DA"," \u0E21\u0E01\u0E23\u0E32\u0E04\u0E21"," simplifying"," \u5A01\u5C3C\u65AF\u4EBA"," \u0413\u0430\u0433\u0440\u0430"," \u0B8E\u0BA9\u0BCD\u0BB1\u0BC1\u0BAE\u0BCD"," \u0AAE\u0A82","/\r\n\r\n"," pagando"," murderous",".Workflow","ietan","\u0CAD\u0CCD\u0CAF","\u0108","(anim","?!?!",'\\"");\n'," !!!!!"," Calibration"," \n",'("-");\n',"\u0430\u043B\u0430\u0440\u0430"," Pian","\u10D0\u10DB\u10EA"," intl"," \u0645\u06AA\u0645\u0644","######"," taifa"," \u0634\u0647\u0627\u062F"," elevados","i\xF0is","whose"," dhim"," peripherals","\u0E24\u0E28\u0E08\u0E34\u0E01\u0E32\u0E22\u0E19",".party"," kreative","igeach","Batis"," Cem"," symmetrical"," \u0628\u0631\u0627\u064A","TEAM"," sess\xF5es"," \u0443\u0447\u0430\u0441\u0442\u0432"," CANCEL"," mowing"," \u0412\u0438\u043A\u0438\u043F",' ?>">\r\n'," odmah","_HINT"," erstaun"," nachhaltig","\u10D0\u10E0\u10DD\u10D3","imende","\u0E17\u0E35\u0E48\u0E08\u0E30"," Meetup"," \u0639\u0644\u0627\u0642\u0648\u06BA","angaje","_angles"," \u0C0F\u0C30\u0C4D\u0C2A\u0C3E\u0C1F\u0C41"," metodolog\xEDa","'https"," orgullo","\u0BBF\u0BA9\u0BBF\u0BAE"," sredstva"," geringer"," \u0443\u0439\u0493\u0443\u0440\u043B\u0430\u0440\u0493\u0430","\\[","\u30AB\u30EB"," \u05E7\u05D0\u05B7"," glossary"," manifesta\xE7\xF5es","\u10D4\u10DC\u10E2\u10D4\u10D1\u10D8"," agricoles"," stuffs"," \u0998\u099F\u09A8\u09BE\u09DF"," \u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442","\u17B6\u179C"," \u0420\u0430\u0439","\u05D5\u05D2\u05DE\u05D0"," h\xF3n"," \u0939\u093F\u0930","zins"," speelgoed","\uD55C\uB2E4\uACE0","\u0D41\u0D15\u0D4D\u0D24"," Persia","\uFF20\u304A\u30FC\u3077\u3093","lygyny\u0148"," nida"," austral","\u04EF\u0437\u0438"," Residency"," \u0444\u043E\u043D\u0434\u0430"," jurk","\\CMS"," dermatologist","\u8B77\u58EB","Namun"," Territories"," \u0635\u0627\u062F\u0631\u0627\u062A","Tours"," \u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442\u0441\u044F"," bambino"," robustness"," secondly"," \u80A1\u7968"," guestrooms"," \u0642\u0628\u0636","\u0D4D\u0D30\u0D2E"," sonucu"," h\u01A1i"," consiga"," schneiden","Adults","anggih","ERTA","akty","PRISE"," \u043A\u0440\u0430\u0441\u0438\u0432\u043E"," JL"," aaqqissu"," \u0686\u06CC\u0641","\u0CA3\u0CA6\u0CB2\u0CCD\u0CB2\u0CBF","Subdivision","\u05D9\u05E6\u05D8"," Vorstellungen"," \u043C\u0443\u0437\u044B\u043A\u0443"," dr\xFCcken","\u043E\u0440\u0432"," swimmer","\u043D\u0435\u0441\u0442"," tr\xE4n","Dennis"," yerde","ioiga"," m\xFCq"," onderhand"," \uBD84\uC704"," \u0161koly","\u5929\u5929\u4E2D\u5956","cuando","(Storage","teriors"," chills"," prossimo","_shuffle",".MINUTE"," \u0561\u057C\u0561\u057B\u0576\u0578\u0580\u0564","\uC790\uB9AC","\uB8F8","\u0446\u0438\u0434"," uruh","sjed"," \u0444\u0438\u0437\u0438\u0447\u0435\u0441\u043A\u0438\u0445","ijakan"," seguem","Locks","-elles","\u6F58"," forl","#aa"," Aka"," \u0E40\u0E01\u0E2D\u0E23\u0E4C"," zviri"," \u057D\u056B\u0580\u0578\u0582\u0574"," Analytical","idro","\u0627\u0626\u0646\u0627","\u05E0\u05E2\u05E8","Exercises",",np"," AUS","INET","\u7A81\u51FA"," pr\xE9sentant"," \u0D0E\u0D1F\u0D41\u0D24\u0D4D\u0D24"," \u0D2C\u0D46"," \u0442\u044F\u0445"," urspr\xFCnglich","richter"," Proverbs"," szk"," Worked"," \uC5C6\uC5B4"," zbir"," aanu"," Erotiske"," luctus","\u043B\u0438\u043C\u0438","chapper"," Myself","\u2014even"," Showtime","\u300F\uFF08"," impedit","\u4E3B\u4F53",".firebaseio"," \u0628\u0631\u062F\u0627\u0634\u062A","Acad"," \u0627\u0644\u0625\u0631\u0647\u0627\u0628","avirus","\u10D4\u10D8\u10DA"," Stellar"," sobrem","ofanira","Kommentare"," completas"," ouverts",".them"," rigidity"," \u098F\u09B8\u09C7\u099B\u09C7"," \u0430\u0434\u0430\u043C\u043D\u044B\u04A3"," \u591A\u4E50"," Ilha"," \u05E8\u05E4\u05D5\u05D0"," c\xE9n","(categories"," \xFAdaj","\u0A3F\u0A17","chtung"," caop","uleke"," \u0628\u0631\u0642\u0631\u0627\u0631"," \u0648\u0642\u0648\u0639"," muv","\u043D\u0456\u0448"," Staffing"," Palavra"," PARAMETERS"," gallwch"," Auteur"," frivol"," settimane"," enclave"," osvoj","leszt"," \u0648\u0627\u0636\u062D\u0629","\u05D5\u05D1\u05D9"," PRESIDENT","amam","\u6A79","\u0E2A\u0E39\u0E15\u0E23"," \u0C35\u0C47\u0C32","-chave"," qu\u1EA3ng","\u4E08\u592B"," PCP","Drops","Sucursal","MOQ"," \u043E\u0441\u0432\u0456"," \u043A\u04AF\u0442\u04D9\u0440","mouseenter"," Diving","n\xE1v"," \u0497\u04D9\u0440"," ====","ismet","straight"," \u0438\u0434\u0430\u0440"," mniej","\u03A0\u03B1"," \u0906\u0932\u094B",'(".");\n'," balt","verschluss"," \u0939\u093E\u0932\u0924","insp","_HEADERS"," \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442","\u0161kega","ussions","Booked"," fudge","bbc"," grasas"," \u0432\u0430\u04A1\u044B\u0442\u0442\u0430"," \u10D8\u10D2\u10D8\u10D5\u10D4"," tablo"," TIG"," \u0995\u09AE\u09BF\u09B6"," Ajust"," devas"," aktiviert"," \u04B3\u0430\u043B"," \u0635\u0646\u0627","-mailadres","-reading"," \uD0C0\uC785"," hainbat"," pot\u0159","\u0909\u0924\u094D\u0924\u0930"," \u0681\u0644"," \u0986\u09AB"," \u0569\u0565\u056F","Automatically"," \u05D3\u05D0\u05B7\u05E8","Caches"," pulsa"," TOT","\u6700\u65B0\u8BC4\u8BBA","umsum"," bich","etop"," \u0A86\u0AAA\u0AA3","myp"," \u092C\u094B\u0932\u0947"," Ruhr","Pinned","\u064A\u064B\u0627","\u66FE\u9053\u4EBA"," \u0E0B\u0E37\u0E49\u0E2D"," \xFCcret"," \u049B\u043E\u0493\u0430\u043C\u0434\u044B\u049B"," eyelashes","-PCR"," \u0645\u0627\u062F\u0631"," inil"," nwany\u1ECB"," syringe"," Avent"," \u0633\u064A\u0627\u0633\u0629"," wyposa\u017C","_www",">d",".Emp"," s\xF2nraichte",".future","\u8D8A\u6765\u8D8A"," thair","izungumza"," \u0441\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435"," dictatorship","(Change"," hikers","\u0CBE\u0C82\u0CA4\u0CB0"," \u0431\u0438\u043B\u0434\u04AF\u0440\u0433\u04D9\u043D","\u10DB\u10E7\u10DD\u10E4"," \u0458\u0430\u0432","edent"," disproportionately","\u0CBE\u0CA6\u0CCD"," newfound","\u70ED\u4E45\u4E45\u7CBE\u54C1"," Accordion"," \u062E\u0628\u0631\u064A"," Wesen","\u2019eo"," cortical","\u88C5\u5907"," Weiterbildung","Unnamed"," Pach"," collaborator","Kansas"," \u0648\u0645\u0633\u062A"," conscientious"," \u043C\u0430\u049B\u043E\u043C\u043E\u0442\u0438"," \u0633\u0647\u0644\u0629","|required","ploit","Carga"," \u0433\u0430\u0437\u0440\u044B\u043D","_take"," schild"," tides","/lounge"," \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447","invalidate",".Creator"," deilige","\u221E","ramin"," WRONG"," \u0A97\u0ACD\u0AB0\u0ABE\u0AAE"," \u0570\u0561\u0574\u0578\u0566"," karde"," \u015Bred","pakken","\u3011!\u3010"," \u03C0\u03B1\u03C1\u03BF\u03C5\u03C3\u03B9\u03AC","\u09C1\u09B7\u09CD\u099F"," broom","\u091C\u094D\u091C"," \u0AAC\u0AA8\u0ABE\u0AB5\u0AB5\u0ABE","\u043F\u0435\u0440\u0430\u0442\u043E\u0440"," \u092C\u094D\u0932\u0949\u0917","\u09C7\u09B0\u09C7","Quartz","felder"," tests"," \u0441\u0443\u0440\u0433"," curate","ULSE"," shida","uitary"," \uC774\uC0C1\uC758"," vell"," ored"," amado","_hdl","(sync"," \u0646\u06A9\u0631\u062F","\uFF45"," Valuable"," nh\u1ECDr\u1ECD"," Brokerage","\u05E1\u05D8\u05DF"," \u0930\u094B\u0932"," boleto","\u3002\u3053\u306E","\u09B9\u09A8"," malaman"," egentligen","\u04AF\u0433\u04AF","\uFF0C\u5168\u56FD","<arr"," broadcasters","\u300C\u3042"," \u1ECDw\u1ECD"," wijs","identify"," maduras"," \u0915\u0930\u094D\u092E\u091A\u093E\u0930"," pitanju"," paligid"," Ergo"," bancada"," smarty"," damu","\u0113ji","f\xF6rder","disposed","<Usuario"," \u10D2\u10DB"," s\xE4l","-stars"," garoto","ANGLES"," \u0CAA\u0CB0\u0CBF\u0CB6"," \u0D38\u0D4D\u0D35\u0D3E\u0D17\u0D24"," ingev","gled"," gha"," Gug","VOC"," \u067E\u0648\u0681"," ethically","\u05D9\u05D9\u05D8\u05E2\u05E8"," \u10EA\u10D4\u10DC\u10E2\u10E0"," \u043E\u0431\u0440"," \u09A4\u09BE\u0981\u09A6\u09C7\u09B0"," \u0417\u0435\u043B\u0435\u043D"," symptomatic"," piz","penetr"," \u0627\u0644\u0645\u0633\u0631","lir","\u041F\u041E","\u5367"," \u05D2\u05E2\u05D2"," \u0C38\u0C3F\u0C26\u0C4D\u0C27"," Mahjong","azelo"," r\xE9alisateur","oboye","ykes","\uFF1F\uFF01"," caros"," LIS","alar\u0131n\u0131n"," ozbil","tekij"," \u05E9\u05D9\u05E0\u05D5\u05D9"," absurdo"," m\xFC\u0259ll"," hopped"," \u05D4\u05D7\u05E8"," \u044F\u0439\u0446\u0430"," buttery"," Worse"," HALF"," tiap","\u0A28\u0A4D\u0A39\u0A3E\u0A02"," attirer"," anledning","abing"," Converted"," feugiat"," \u0D06\u0D24\u0D4D\u0D2E","onesa","oghi"," \u0447\u044B\u043D\u0430\u043C","=center"," tch"," bem\xFC"," Empfang","/span"," piccoli","ecos"," \u043B\u0435\u0447\u0435\u043D\u0438\u0438"," ireland","Bref","\u6C27","agext","\u65E5\u306B"," \u042F\u043A\u0449\u043E"," Yoo"," ohnehin","\u6C11\u4E3B"," wohnen"," \u0433\u043E\u0440\u043E\u0434\u0441\u043A\u043E\u0439"," \u043E\u043A\u0435"," \u03B5\u03B2\u03B4\u03BF"," \u041F\u0440\u043E\u0432"," epo","\u0578\u0582\u0562"," BUF"," \u0909\u0928\u092E\u0947\u0902"," fot\xF3grafo"," M\xE9dico"," tider","ffin","_visibility"," \u0645\u0635\u0637\u0641"," Thunderbird"," \u0C89\u0CB3"," Bello"," k\xFCnst"," compet\xEAncias"," \u064A\u0634\u0639\u0631"," \u0627\u0644\u0628\u0648\u0644","\u0E2A\u0E27\u0E19"," fscanf","\xEDdios"," \uC608\uBC29"," \u06AF\u0632\u06CC\u0646\u0647","Loved"," igbesi"," \u0421\u043E\u0444"," \u092E\u0941\u0938\u094D\u0932\u093F\u092E",'"\u05D5',"\u{1F495}","\u05D9\u05DE\u05D5\u05DD",".dem","warna","cri"," \u062A\u0635\u0628\u062D","'effet"," handlebars"," Diretor","ditch","\u06A9\u0631\u0627"," \u4F17\u946B","\u0631\u0628\u064A\u0646"," gereal","/octet"," coroutine"," kindje","-Key"," \u0627\u0644\u062A\u0646\u0641\u064A\u0630\u064A"," miesi\u0119","\u30B7\u30EA\u30FC\u30BA","\u0E32\u0E23\u0E35","orados"," brzo","\u064A\u0645\u064A\u0646"," verwerking"," \u092D\u092F","cree"," Naughty"," ISC","\u0E31\u0E08\u0E08","\u0435\u043B\u0434\u0435"," chaleureux"," tieto"," Ger\xE4ten"," \u0440\u04D9\u0445"," ktor\xED","\xC1rea"," \u062C\u0644\u0648\u06AF\u06CC\u0631\u06CC"," \u0430\u0442\u0430\u043A","\u05D1\u05E8\u05D9\u05E7","\xED\u0161","_RPC"," abaz","hipster"," ansatte"," foret","komfort"," Disponible"," FOREIGN","\u03B4\u03AC"," sensitiv","Zj","\u10D0\u10E8\u10D0\u10E3\u10DA"," Adviser","_secure","(album"," forcibly"," Adsense"," Authenticate"," \u0CB5\u0CC8\u0CB0","]]]","\u2219"," confirma\xE7\xE3o"," hierzu","(Symbol"," Nadia"," marki"," \u5E97","\u5904\u5206"," itlog"," shughuli","\u5A31\u4E50\u5E73\u53F0\u4E3B\u7BA1","Dorm","()},\n"," m\u1EF9"," \u0642\u0648\u0645\u064A"," fili"," gebeurtenissen"," considere"," descubre","omod","\u066C"," Einladung","TIN"," ganhos",".gv"," distrik","Masc","-feed","\xE7iligi"," nnyo"," \u043C\u04AF\u0448"," Concello"," \u092C\u093F\u0932\u094D\u0915\u0941\u0932","_pas","\u0CC3\u0CB9"," weich","acor","\u10DD\u10D1\u10D0\u10D6\u10D4","career","_xlim"," \u0445\u043E\u0447\u0430"," saludables"," Sobald","\u0BCD\u0B95\u0BC1"," runaway"," civilized","ANTI"," hatta","\u0648\u0627\u0644\u06CC","\xD1A"," mmol","bane","innu"," glaubt"," c\u1EA5u"," Wannan"," \u056C\u0561\u0575\u0576"," \u0441\u0430\u0431\u0430\u049B","atawag"," commercialization"," kuele","hik"," \u043F\u0440\u043E\u0448\u043B\u043E"," seules","_trait","obyl","iiii","shirts","-IV","\u0947\u0930\u0940","polar","\u011Fiz","(friend"," crip"," \u5929\u5929\u4E2D\u5F69\u7968\u4E0D\u80FD\u4E70"," appreciating","@n"," sensores","\u09BE\u099E\u09CD\u099A","instantiate","_nv","ulnerability","\u0165a\u017E"," prosecute","\xE9in"," scrapbook","\u2019innovation"," faigofie"," DOB","vrije","\u0D19\u0D4D\u0D19\u0D3F","\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u043C"," marquee"," complains"," \u0576\u0577\u0561\u0576\u0561\u056F\u0578\u0582\u0574"," papir","]]\r\n","R\xE9sum\xE9"," \u0628\u0627\u0644\u0631\u064A\u0627\u0636"," \u5F35"," \u0627\u0644\u0639\u0645\u064A\u0644","addons"," Damian"," \u0D38\u0D28\u0D4D\u0D24"," motorway","\u0BB0\u0BBF\u0BB2\u0BCD"," uppsk"," industriais"," impregn","Hence"," wasm","\u03C4\u03AE\u03BC\u03B1\u03C4\u03B1"," uile"," eiser"," heutzutage"," \u0440\u0443\u0441\u0438\u0439\u04D9","ocannabino"," \u0916\u0941\u0932\u0947"," "," poka",".xxx"," regione"," \u0CAE\u0C9F\u0CCD\u0C9F"," Boxer","addition"," \u09B8\u09AC\u099A\u09C7\u09DF\u09C7","Cheque"," \u0448\u043E","Topo","datatable"," \u0437\u0438\u0434"," schaut"," h\u1EE5"," vesz"," adhart"," \u0441\u043B\u043E\u0432\u043D\u043E","(authentication"," \uB178\uB3D9"," Calabria","av\u4E0D\u5361\u514D\u8D39\u64AD\u653E"," wcze\u015Bniej"," grenade"," GBR"," \u06AF\u0633\u062A"," itk"," \u0907\u0932\u0947\u0915\u094D\u091F\u094D\u0930"," rady","(exchange"," aerodynamic"," kuo","ademic","yly"," \u6EE1\u5802","Privileges","\u04AD\u0430\u043A","\u603B\u4F53",".shader"," parent's","\u0434\u0430\u0440\u0430"," dn\xED"," Feiert"," graphi"," auge","\uFFFC"," Lisp","apatalk","_rooms"," \u0986\u099A"," Arbitration"," luxuri"," \u0438\u0440\u0430"," Konzentr"," CRS","amalama"," Proton","Appartement"," \u09AA\u09BE\u09B9"," aliquet"," eksister","\u09C0\u09A6"," alapj\xE1n","Medication","donald","\u03C1\u03B3\u03AC\u03BD","\u10D4\u10DC\u10D8\u10DA\u10D8"," atrak"," Suppressant"," \xE1udio"," dipercaya","\u516C\u7F51"," m\u011Bs"," \u043F\u0440\u0438\u0447\u0438\u043D\u0430\u043C","killer"," \u0431\u0435\u0439\u0497\u0438\u04A3","_ros"," Haitian","-Produ"," \u7F8E\u570B","toq"," kolem"," determina\xE7\xE3o"," karto"," \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B"," \u0AAD\u0ABE\u0AB0\u0AA4\u0AAE\u0ABE\u0A82"," \u043C\u0443\u0441\u0443\u043B\u043C\u0430\u043D","etsk"," \u0645\u0627\u0643\u064A\u0646\u0629"," \u0924\u0901","imur",'()=="'," \u0C38\u0C02\u0C16\u0C4D\u0C2F"," detectable","\u093F\u092E\u093E\u0917"," \uC9C0\uB3C4"," erhe","retweeted"," constitui"," turista",'("");'," ')\r\n","\u0435\u0441\u0442\u0456"," chocolade","}!","\u0A15\u0A40"," \u0440\u0438\u0441\u043A\u0430","QObject"," \u062C\u0631\u0645"," mesmerizing",")...\n\n"," \u0D1A\u0D30\u0D3F\u0D24\u0D4D\u0D30","\u0E40\u0E0A\u0E35\u0E22\u0E07","\u043B\u0430\u0442\u0443","-\u1ECD","[]={"," \u0906\u0908\u092A\u0940"," meubels"," notif"," basiert"," Bangor"," N\u011B"," \u0C85\u0CA8\u0CCD\u0CA8"," thu\xEA"," yap\u0131","falz"," Documento","\u3001\u526F"," \u043F\u0440\u0438\u043D\u0438\u043C","\u0442\u04AF\u0441\u0442\u0456\u043A","\u0E40\u0E02\u0E49\u0E32\u0E2A"," Purchased"," \u0442\u04E9\u0440\u04E9\u043B"," Camper"," \u05DC\u05DE\u05E1"," \u0635\u0627\u062D"," ELF"," Mariners"," startled"," relentlessly"," \u718A","SNS","-Euro","\u043D\u0430\u043A\u0438","?.."," Clap",":J"," valable","=(-"," \u0630\u0627\u062A\u0647"," faili","\u0442\u0435\u0440\u0430"," \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435","\u672C\u91D1"," Secretario"," \u04E9\u043A\u04AF\u043B"," \u0A85\u0AAD\u0ABF\u0AA8\u0AC7","\u0443\u043C\u0435\u043D\u0442\u044B"," partik","Inclus","\xEDvio","\u0E42\u0E0A","\u0CA4\u0CBF\u0CAF","\u062E\u0648\u0627\u0647\u062F"," Filmes"," Yusuf","\u307E\u3041"," melhorias"," storico","richment"," entret"," \u062C\u0645\u0639\u064A\u0629","\u0646\u062F\u0631\u064A\u0629","-Claude"," el\xE4","\u043F\u0440\u043E\u0441\u0442","Slices","\u0AAA\u0A95\u0AA1","\u05DB\u05E0\u05D5\u05DF"," \u0391\u03B8\u03AE",":start","meh"," cracker","\u5728\u7EBF\u7CBE\u54C1\u89C6\u9891"," g\xEAn"," \u064A\u0639\u0637\u064A"," Schulter","listas","QRCode","IFUL"," \u0434\u043E\u0447\u044C","_signup"," Sunni"," \u10E3\u10EE",".hyper"," solides"," \u0D07\u0D02\u0D17\u0D4D\u0D32"," Bisa"," \u0CB0\u0CBE\u0CB7\u0CCD\u0C9F\u0CCD\u0CB0\u0CC0\u0CAF","\u30B9\u30BF\u30C3\u30D5","icont","Millions","bulas","yzda","\u30C6\u30FC\u30DE","\u0D31\u0D23","\u0178","ZU","\u0ABE\u0AA8\u0ACD\u0AB8","\u0131s\u0131yla"," intervju","\uFF09,","Graw"," causada"," conveyors","\u0446\u0438\u044F\u0442\u0430"," roulant"," \u0C2A\u0C30\u0C41\u0C17"," Boga","(inplace","SEMB"," \u0E23\u0E30\u0E1A\u0E1A"," assuring","achael"," t\xE1mogat"," eleitor"," \u057A\u0561\u057F\u0565\u0580\u0561\u0566\u0574\u056B"," ulim","\u05D5\u05E8\u05D0"," \u017Eivljenje","igia"," Gers"," \u062A\u0635\u0627\u0648\u06CC\u0631","Loans"," \u0445\u0443\u0441\u0443\u0441","\u0B1B","izacja","Puerto","\u3001\u5B89\u5168"," ;\n//",".euler",".Vehicle"," isit"," Britannica","_perf"," connective"," nitorinaa"," MUL",'")+"',"embo"," Reck"," Redes"," Kontext","hpp"," reply"," glaucoma","issani"," \u0648\u0631\u0681\u06D0","\u0635\u0631\u064A","garh","ovan\xFDch","determ"," \u0430\u0499"," \u0C24\u0C2F"," })\r\n\r\n","\u0D15\u0D4D\u0D15\u0D41\u0D28\u0D4D\u0D28"," baton","\u0430\u049B\u04D9\u0435\u0438"," \u10D4\u10E0\u10D7\u10DB\u10D0\u10DC\u10D4\u10D7\u10E1","####\n","H\xE4r"," \u041C\u0435\u043C","-CON"," Resurrection"," \u041A\u0440"," llegar\xE1"," Europe's"," Melo"," cherchent"," prawa"," clustered"," \u09B8\u09BE\u0995\u09CD\u09B7"," lounging"," \u0565\u0580\u056F\u0580\u0576\u0565\u0580\u056B"," \u0441\u043E\u0440\u0442\u0430","(flat"," blockade"," \u0445\u04E9\u0433\u0436"," \u0E41\u0E19"," kruis"," \u0644\u0645\u0633","\u0D2A\u0D4D\u0D2A\u0D46\u0D1F\u0D41\u0D24\u0D4D\u0D24\u0D3F\u0D2F"," odz"," \u4E45\u4E45\u70ED","hava"," Flesh"," l\u1EC5"," dilute"," unfor"," Attempts","decltype","ambisa"," gedeelt"," mangas"," kojeg"," jaunes"," JNI","\u05DE\u05E2\u05D8"," masculin","qqaat"," pll","alphabet"," \u0B8E\u0BA9\u0BCD\u0BAA\u0BA4\u0BC8"," geringe"," \u0633\u0648\u0631\u06CC"," Inspirations","aviest"," relata"," nack"," tejidos"," indikator","dop"," Schwanz","owani"," terasa","\u0651\u0649"," FMI"," kusho"," \u0D2A\u0D34"," \u6052\u4E00"," \u017Eene"," skb","adwy"," agencias","\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD"," intersects"," emoz"," royaume"," (),\n"," \u6A2A","BCC"," eof",":grid","\u0C97\u0CBE\u0C97\u0CBF","\u0D3E\u0D2F\u0D4D","Pret"," incre\xEDbles","ulto"," overlijden","(relative"," bbq"," ac\xFAst",":file"," Moran"," \u0442\u0430\u0440\u0438","uentes"," vorgenommen"," gegarande"," refurbishment","Ficha","\u045B\u0443"," DOJ","_CITY","\u0434\u04E3"," \u0622\u0634","\u043A\u0443\u043D\u0430\u043D\u0434\u0430"," cando"," izquierdo"," \u062D\u06CC"," aparat"," hamster"," \u0A9B\u0ACB\u0AA1","amphetamine"," \u0985\u09B8\u09CD\u09A4","itera"," \u4E9A\u6D32\u65E5\u97E9","(Html","\u8BA4\u8BC6"," Invisalign"," fasilitas","\u0637\u0648\u0631\u0629","\u1010\u1031\u102C\u1037"," \u0D15\u0D25\u0D3E\u0D2A\u0D3E\u0D24\u0D4D\u0D30"," localisation"," \u0443\u0431\u0440\u0430\u0442\u044C","omsnitt"," \u0CAE\u0CBE\u0CA1\u0CBF\u0C95\u0CCA\u0C82\u0CA1"," \u0448\u0430\u0430\u0440\u0434"," \u043F\u0440\u0438\u0431\u044B\u043B\u0438"," \uC624\uB978"," bpm","\u52D5\u756B"," luncheon"," \u043A\u0438\u0442\u043E\u0431",".exercise","'effect"," bezwaar","ovania"," \u091B\u094B\u095C","acyjne","oglio","\u5085"," quake"," zata"," remuneration"," onderzoekers","_IMETHOD"," disagreements"," handi","Hm","Acceptance"," entwickelte"," ndim"," doctrina","\u0443\u0440\u044B\u0441"," \u092D\u093E\u0935\u0928\u093E"," \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0435\u0439"," homofile","\u043C\u044B\u0439"," izgled","qml","<il"," novella","\u0E15\u0E2D\u0E1A"," thi\u1EC7u"," beheren"," \u03C0\u03BB\u03B5\u03C5"," esigenze","\u0BCA\u0B9F"," crot"," \u0645\u0639\u062A\u0628\u0631","\uC624\uAE30","itiers","Thirty"," rano"," \u0D21\u0D4D\u0D30"," recombinant","_EST","\u0561\u0576\u0577","[result","Christine","\u4E0D\u5361\u65E0\u7801"," \u0437\u0430\u0447\u0430\u0441\u0442"," \u0437\u0430\u0445\u043E\u0442","\u0561\u0576\u0564\u0561\u056F","\u1010\u103D\u1000\u103A"," dialogs","_AI"," \u5E02","lisi","-highlight"," stun","\u0111ena"," adoptar"," wanem"," halde"," bigint"," Adu"," profesjonal"," Wondershare"," murdering","ASHION"," instalada"," laborat\xF3rio","airport","(Logger"," aangeven"," Bahkan","cutta","\xF3viles"," pilares","\u0441\u0435\u043D\u0434\u0456"," \u0D1C\u0D3F\u0D32\u0D4D\u0D32\u0D2F\u0D3F\u0D32\u0D46"," \uC624\uB798","ADORES"," motivatie",".EMAIL","$temp","\u6B27\u7F8E\u65E5\u97E9","erms","\u03BB\u03C9\u03C3\u03B7"," hoofdstad","A\xF1"," spokoj","/accounts"," crates"," Verpflicht"," fant\xE1stica"," fracaso"," \u0627\u0644\u0631\u0627\u0628\u0639\u0629"," vacunas","brates","PRIMARY"," conforms","\u03BA\u03C5"," \u043F\u043B\u0430\u043D\u044B","acd"," \u0123"," rohe"," conserving","\u0628\u06BE","\u0442\u0438\u043B\u0438"," \u062D\u06CC\u0631","\u0BBF\u0BAF\u0BC7"," \uC624\uB958"," \u03C0\u03BF\u03C3"," \u0AB8\u0A82\u0AAA\u0AB0\u0ACD\u0A95"," \uBBFC\uC8FC"," \u043A\u0435\u043D\u04D9",":web"," subterr","processors","tensorflow"," confirmou","Horas","\u0561\u0563\u0561\u0570"," Formatting","_similarity","(Movie"," assimilation","\u80FD\u4E70\u5417"," \u03C0\u03BF\u03C4\u03AD"," Duarte"," kurulu\u015F","STANDARD"," HERO"," blinded","-------------------------------------------------------------------------\n"," So"," sonidos"," \uC788\uC74C"," JSP"," Tcx"," Castelo"," Linking"," enquire","amano","Feet","Walter"," \u0633\u0648\u0621","hooter"," Fabian","ungele","\u0648\u0645\u062A\u0631"," \u0B8F\u0BB1\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F"," creativo","OGA"," Apro","endidos","cris"," FARM"," Goldco",",{\n"," N\xF3"," natus"," \u03C0\u03C1\u03CC\u03B3\u03C1\u03B1\u03BC\u03BC\u03B1","Plano","\u17B6\u1798\u17BD\u1799","thawi","\u0928\u093F\u0915"," \u0C28\u0C3F\u0C30\u0C4D\u0C2E\u0C3E\u0C24","hetseng","\u636E\u4E86\u89E3"," constamment","ew\u0121"," Atari"," \u06AA\u0627"," g\xF6sterm","\u529B\u5EA6","\xE9ralement"," \u0445\u0430\u043B\u044B\u049B\u0430\u0440\u0430\u043B\u044B\u049B"," \u0443\u0434\u043E\u0432\u043E\u043B\u044C\u0441\u0442\u0432\u0438\u0435\u043C","-too"," Kartoff"," \u03B3\u03BD\u03CE","\u2019ay"," \u09B8\u0995\u09CD\u09B7\u09AE"," ponu"," shoved"," \u0433\u0435\u043A\u0442"," lefatsheng"," \u0BA8\u0B9F\u0BB5\u0B9F"," \u0441\u0442\u0440\u0430\u0442\u0435\u0433\u0438\u0438","BEC"," interesser"," JMS","\u0936\u094D\u0930\u0947\u0937\u094D\u0920","\u4E92\u52A8"," QUESTIONS"," marts"," Appreciation","Linejoin"," \uB4F1\uC7A5"," Mileage"," Tuna"," escreve","Fizz"," uya"," \u0A86\u0A82\u0AA4","\u09AF\u09BC\u09C7\u09B0"," record\xF3"," olje"," sitere","ymmen"," diaphragm"," etdiyi"," \u05D3\u05D5\u05DC\u05E8"," ')'"," Cassidy","\u09BE\u09A8\u09CD\u09A1","ulados","\uFF09\n\n\n"," Beaumont","\u044C\u044B\u0440"," zhv"," DASH","\u044B\u0432\u0430\u0435\u0442"," hoid"," entertainers"," Texto","advies"," kezel\xE9s"," papill"," \u0639\u0628\u0627\u0631\u062A"," \u0627\u0644\u0648\u062B"," \u0432\u0430\u0436\u043D\u044B\u0445"," \u0623\u062D\u062F\u0627\u062B","-budget"," \u05D8\u05D5\u05D8",".scalar"," \u0631\u0633\u0645\u06CC"," Waxaan","@\\","\u03BA\u03CC\u03C3"," levi"," \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C"," boq","\u1789\u17D2\u1787"," perig"," afwijk"," Parma","etem"," regelgeving","\uC774\uBA74"," ausgesprochen","('.');\n","_written","(toggle"," aumentado"," jornais","\u5C24\u7269"," \u043D\u0430\u043C\u043E\u044F\u043D","\u0648\u062F\u0631","Whit"," livelli",".PNG"," Ignite"," IIS","ajen"," letten"," shoppen"," \u0907\u0924\u0928\u0947","markup"," bsp"," promessa"," \u0CAA\u0CCD\u0CB0\u0CB6\u0CCD\u0CA8"," Sabah"," Com\xE9rcio","amanzi"," Ausbau",".Dto","\u0446\u0438\u043D"," multaj"," historii"," orale"," \u0639\u0627\u0644\u0645\u064A","\u0415\u0421"," liest"," afzonder"," compacto"," \u092C\u0940\u092E\u093E\u0930\u0940"," \u043E\u043F\u0446\u0438"," \u0441\u043A\u043B\u0430\u0434\u044B"," usamos"," \u0635\u0641\u0631","_Email"," \uBC18\uB4DC\uC2DC","\u05D9\u05E4\u05D5\u05E9"," \u0917\u0941\u091C\u0930\u093E\u0924"," \u03B4\u03B7\u03BC\u03CC"," Shrine",".claim"," \u0441\u043B\u043E\u0442"," ak\u0101"," \u062E\u0648\u0627\u0647\u06CC\u062F","wiritsidwa","utinut"," r\xE9tro"," iter"," TALK"," \u05D4\u05DB\u05E8","ziemy"," \u0442\u0443\u0443","\u0E1E\u0E23\u0E49\u0E2D\u0E21"," Sparrow","orium"," kaikke"," \u0648\u0627\u062E"," \u0437\u0440\u0430\u0431\u0456\u0446\u044C"," \u0436\u04D9","-Mit","\u10E1\u10D8"," produkt\xF3w","UIC"," n\xE1\xE0","-growth"," trolling","neqarpoq","_mapper","Delimited"," \u0438\u043D\u0442\u0435\u043B\u043B\u0435\u043A\u0442\u0443","cerias"," Nour","\u514D\u8D39\u65E0\u7801","\u0628\u0627\u0639\u0629"," center"," Teenage"," Entwicklungen"," transt","usche"," interoperability"," \u0E40\u0E2A\u0E37\u0E49\u0E2D"," Daphne"," Finest"," Silverado","Laundry"," o\u011F"," Lis\xE4\xE4"," Harding"," \u0437\u0443\u0440\u0430\u0433"," exploratory"," weerstand"," newsroom","\u0C3E\u0C32\u0C40\u0C35\u0C41\u0C21\u0C4D"," coriander"," \u0CAA\u0CCD\u0CB0\u0CAE"," Formel"," comrades","Praise","\u09CD\u09AF\u09BE\u09B8","-launch","'\xE9volution"," \u0627\u0644\u0643\u0634\u0641","ippaa"," \u0637\u0641\u0644","\u0E23\u0E31\u0E48\u0E07\u0E40\u0E28"," Wilaya"," atentos",".rdf","designation","_USED","[ip"," criticizing"," legitimately"," \u578B"," succulent","zerano","\uB044"," gu\xE9r"," \u043F\u0440\u043E\u0445\u043E\u0434\u044F\u0442"," CALLBACK"," ressembl"," uncontrolled","-floating"," Auctions"," predictors"," t\xF3c"," \u0B8E\u0B9F\u0BC1\u0BA4\u0BCD\u0BA4"," \u043C\u044B\u043D\u0434\u0430\u0439"," glatt","aturbate"," differed"," panes"," \u0438\u043C\u0440\u04EF\u0437"," \u0627\u062F\u0628","FIELDS","shock","\u0627\u0639\u064A"," wrongdoing","\u092A\u094D\u0930\u0926\u0947\u0936"," degelijk"," funcs"," \u05D0\u05D2","/location","(gs"," ogled","\u044F\u043B\u043E","Chez"," fede","-ounce"," rhyw"," \u0644\u0642\u0628","\u043E\u0445\u043E\u0436\u0438\u0435"," trzy"," veoma","=o"," brook"," OCI"," \u062A\u0628\u062F\u06CC\u0644\u06CC"," \uC548\uC815"," crackdown","tweets","\u53EA\u6709\u7CBE\u54C1","ippage"," versos","wijze"," ki\u015Filer"," deoarece"," tilfred"," \u0627\u0644\u0645\u0646\u0627\u0641\u0633"," propensity","!!)\n","OLVE"," \u044D\u0441\u0435\u043F","\u0CBF\u0CAE\u0CBE\u0CA8","_submission"," Hoc"," \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435"," sjed"," \u0C35\u0C46\u0C02\u0C15","\u0631\u0648\u0628\u0627\u062A","b\xE9s"," \uC6D0\uD558\uB294"," Switching"," experimented","uoja","IODevice"," \u041B\u0443\u0447\u0448\u0435"," przyk\u0142ad"," \uBAA8\uC2B5\uC744"," \u91CD\u5E86\u65F6\u65F6\u5F69\u5F69"," Peyton"," \u0916\u0947\u0924\u0940"," confeccion","(shell"," \u0438\u0433\u0440\u043E\u0432\u044B\u0445"," \u05D4\u05D2\u05D5\u05E3"," \u043E\u0431\u0449\u0438\u0439","_languages","emask"," hitters","kamera"," acreage"," `_","<Device","\u010Dkom"," \u0CA6\u0CC7\u0CB5\u0CB8\u0CCD\u0CA5"," potrebe"," sonras\u0131"," b\xE4st"," jornalistas","ussing"," laboris"," Reconstruction","\u0ABE\u0AA3\u0ABE"," \u0130nsan"," \u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03B7\u03C1\u03B9\u03C3","/MS","arczy"," PPO","illuunniit","Titel"," uchel"," p\xE9trole"," \u0639\u0627\u062C"," caafima","\u0ABE\u0AB3\u0ACB"," \u05D4\u05DE\u05E9\u05EA"," VARIABLES","\u0161oant\u0161o"," \u057E\u0565\u0580\u0561\u0570","-awareness"," poseen"," \u043C\u0438\u0441\u0442"," Deutschmark"," \u0C2E\u0C40\u0C21\u0C3F\u0C2F\u0C3E\u0C32\u0C4B","\u06D5\u062A\u0643"," estaduais"," vertu","Investor","mmert"," supervising"," Rect",'":[],\r\n',"arnermik","BURG"," O\xF9"," \u0625\u0644\u0643\u062A\u0631","ddangos",'"${'," Wehr"," pr\xEDpade"," \u0421\u043E\u043D\u044B\u043C\u0435\u043D"," inuiaqatigi"," \u5317\u4EAC\u8D5B\u8F66\u6295\u6CE8"," \u041C\u0412\u0414"," s\xE9paration","Interestingly"," \u0414\u041E","\u0438\u043D\u0430\u0439","setzt"," praxis"," \u0430\u0440\u043C\u0438\u0438","ccd","\u0440\u0438\u0441\u0442\u0430","\u0C95\u0CCD\u0CA4\u0CBF"," g\xE2"," Reglamento","Detroit"," Kendrick"," \u09A6\u09C7\u0996\u09BF","\u5B98\u7F51\u767B\u5F55"," h\xFCk\xFC","Dose","vura"," TInt"," Khr"," \u0432\u0430\u0442",".creation"," \u0642\u0644\u064A\u0644\u0629"," mgbanwe"," il\u1ECD","\u0435\u043D\u0437\u0438","bfd","\uFF0C\u4F1A"," diverted","cristo"," \u0441\u0442\u0435\u0440","ospels","(_('",".checkout"," \uC800\uB294","\u7E8C"," \u0AAC\u0ABF\u0AB2","(Security","usalema"," \u624E"," CTS"," refrigerated"," \u0998\u09F0",'=?",'," reflector","continuous"," gepland","\u0924\u093F\u0939\u093E\u0938"," ba\u015Flan","\u0E20\u0E32\u0E1E\u0E31\u0E19\u0E18\u0E4C"," preocupado"," unum","st\u0101"," \u0434\u0430\u04BD\u0430"," Deve"," Novi"," gr\xE9","\u5173\u8054","awed"," elliptical"," kras"," \u05D1\u05D0\u05B7\u05E7\u05D5\u05DE\u05E2\u05DF","kep","\u0AB5\u0ACD\u0AAF"," eyewitness"," \u0627\u0644\u062F\u0631\u0627\u0633\u064A","abee"," \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F"," Ortalama"," estabelece"," \u6210\u90FD"," sariling"," strapped"," \u0644\u062A\u0639"," quelcon","\u041F\u043E\u0437"," \u0540\u0561\u0575\u0561\u057D\u057F\u0561\u0576\u0568",")var","ltf"," }):"," \u0437\u043D\u0430\u0439"," H\u1EA3i",".Hex"," obdob\xED","pham","[module"," zette","\u5F69\u7968\u5A31\u4E50\u6CE8\u518C"," desean"," habia"," vissen"," \u041F\u043B\u0430\u043D"," resolveu",'"display',"\u094D\u092F\u093E\u0915"," \u05E9\u05E1","elerinde","\u4E09\u7801","onomies"," GEL","anfan","m\xFCr"," voorbereid"," empiez"," \u064A\u062C\u062F"," \u03C0\u03B5\u03C1\u03AF\u03C0\u03BF\u03C5"," \u0938\u0942\u0930\u094D\u092F"," Cliquez"," \u30AC","neider","\u5A31\u4E50\u5E73\u53F0\u5F00\u6237"," Ony"," Maaari"," aufreg"," \u0A9A\u0AC1\u0A95"," TYPO","weist"," \u0909\u0926\u094D\u0927","\u0BC1\u0BAE\u0BBE\u0BA9","roepen"," \u0441\u0441\u044B\u043B\u043A\u0430"," \u0BAE\u0B9F\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"," vady"," onderzocht","\u0ABF\u0AAF\u0AB0","Entreprise"," hashmap","\u0493\u043E\u043D\u0438"," Wilkinson","\u3000\u672C","/right"," \u043F\u0440\u044B\u0439",'."_'," hormona","hebb","Romans"," \u092E\u0941\u0926\u093E"," \u0938\u094D\u091F\u094D\u0930"," aet","\u3000\u4E09","\xB4\u30FB"," keyed"," anim\xE9"," Patti","_sampling","kx","ardige","\u0438\u0440\u0443\u044F"," argentinos"," \xFAd","hunter"," Dalka","\u0561\u0576\u0575\u0578\u0582\u0569"," \u0907\u0902\u0938\u094D\u091F","_IMAGES","\u010Dn\xFDch"," serif","shim",".):"," Griechen"," sheen",".tagext","Cadastrar"," leedahay"," \u043A\u0430\u043C\u0441\u044B\u0437"," Shemale","\u103B\u1016\u1005\u1039","Dropbox",".billing","\u0432\u0438\u0437"," \u0920\u093E\u0915"," membri","oodu","anyisa","lur"," \u0630\u06C1"," Afurika"," sexuels"," podpis"," \u0C9F\u0CC6"," kerajaan","beras","=session"," \u0E2B\u0E19\u0E49\u0E32"," Bung"," Jumat","_dense"," \u0689\u0644\u06D0","\u0443\u0449\u0438\u0439"," \u0D39\u0D46",";)\n"," Joke"," \u05D4\u05E1\u05EA"," \u0915\u0930\u0947\u0917\u0940"," \u0C2A\u0C4D\u0C30\u0C35","\u3001\u65E5\u672C"," Aver","\xE4v\xE4\xE4","PLI"," Fiverr","ilyen"," \u10E7\u10DD\u10D5\u10D4\u10DA\u10D3\u10E6"," violences","amisesta"," hablado"," \u0928\u093F\u0930\u0940"," ASIC"," \u0C35\u0C3E\u0C30\u0C3F\u0C15\u0C3F","aka\u02BBi","{}\\"," -->\r\n\r\n"," molestie"," m\xF5\xF5","\u4E8B\u52A1","\u0442\u0435\u0440\u0434\u0456\u04A3"," yaliy"," reverted"," capaciteit","wedstrijd"," vsebuje"," \u0C24\u0C4A\u0C32\u0C3F","g\u0259r","_secondary"," psicol\xF3gico","\xE1rn\xED"," iechyd","icatie","iversaire"," \u10E4\u10DD\u10E2\u10DD"," met\xE0"," Terraria"," teklifler",");\r\n\r\n/"," best\xE4tigen"," luy\u1EC7n"," iib","\u0442\u0443\u0440\u0430\u0442\u04D9","indx","Reconnect","\u0C42\u0C1C"," presentada"," veres","\u016Fst"," kugirango","\u5EF7","Mons"," \uAD00\uB9AC\uC790"," \u0433\u0430\u0441\u0442",".wave"," \u05D4\u05E1\u05E8\u05D8","uzzo"," \u0441\u043E\u0431\u0441\u0442\u0432\u0435\u043D\u043D\u043E\u0433\u043E"," \u0627\u0644\u0645\u0639\u0627\u0631\u0636\u0629"," misura","\u0443\u043C\u0435\u043D"," Clermont"," parmesan","(Paths"," gereden","drawable"," fiables"," Regione","-\u05D4"," Ii"," Koe"," yaran","-look","adag","apay"," nab\xEDz\xED"," bester"," \u0627\u0632\u062F","istorical"," \u6842"," \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u044C","\u0561\u056F\u0578\u0582\u0574\u0562","\u0958"," \u4F5B"," \u06AA\u0646\u062F\u0627"," riveting","\u0AC7\u0AB2\u0AC1\u0A82"," finca"," \u09B6\u09CD\u09B0\u09AE","\u10DD\u10E0\u10EC"," crossings","__.'/"," warped"," Mar\xE7o"," Civilization"," \u0648\u0627\u0644\u0645\u062F","\u0627\u0636\u0629"," bancaria"," h\u1EADu","amiut","_AUTHOR"," JQuery"," riport","Usd","sko",".AD"," araba"," lecturers","cand","COMING"," ymlaen","\u0E02\u0E49\u0E2D\u0E07"," Palestina"," Ukw"," asters"," Aucun",'"For',"\xE0ries"," forage"," \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6","Joel"," yata"," habituales"," \u03BC\u03BF\u03C1","\u09CC\u09B6","\u547B\u541F","stede"," fabricar"," \u057D\u057A\u0561\u0576","ONTO","!*\\\n","ficie","\u2019annonce"," \uAF43"," \u043A\u0438\u04A3","\u1021\u1005"," diminution","\u062B\u0645\u0627\u0631\u0627\u062A"," H\xE9r","\u0451\u043D\u043D\u044B\u0445"," Gouvernement","TOK"," \u0A26\u0A30"," d\xE9cennies","\u043A\u043E\u043D\u0442"," Hrvatskoj"," \u044D\u043C\u043D\u0435"," JAM"," \u092E\u0917","\u06AB\u064A"," braided","Rainbow","stake","ij\xE3o"," favoris"," DHS"," \u09AA\u09BE\u09A8\u09BF"," rapproche","\u0643\u0634\u0641","\u0627\u0641\u0627\u062A","+\u5929\u5929\u4E2D\u5F69\u7968"," stoi"," zwi\u0119ks"," y\u0131l\u0131","\u2019abandi","_executor",".randrange"," LDS","_TM"," \u1ECDl\u1ECD","r\xE9tiens","}}\\"," Zwecke"," \u0627\u0646\u062A\u06C1\u0627\u0626\u06CC","\u0AA4\u0ABF\u0A95","\u094C\u0924"," mo\u017Eemo"," pr\xE9l"," verticale"," Adem","\u8FDB\u884C\u4E86"," salarios"," veu"," apareci\xF3"," \u10D5\u10D8\u10E7\u10D0\u10D5\u10D8","\u062A\u0648\u0631"," Papel"," \u057A\u0561\u0570\u056B\u0576"," \u0414\u0443\u043C\u0430"," \u0644\u0628\u0639\u0636",' ?"'," gosh","Donnell","ljive"," \uACBD\uCC30","joins","heated","/poly"," \u0458\u0435\u0440","Rtc"," dauern","\u094D\u0932\u0947"," \u0628\u062F\u0627\u0646","eyen"," spool","_sta","_TILE","\xE9diteur","Spike","wandle"," m\xE9id"," incentivar"," deelnemen"," lim\xF3n"," prendra","\u0412\u044B\u0441"," muddo"," \u0562\u0561\u0576\u0561\u056F\u0581"," DZ"," \u0D24\u0D40\u0D2F"," operator","\u6703\u54E1"," \u0623\u0639\u0631\u0641"," Wherever"," \u0425\u043E\u043B","\u0932\u094B\u0915"," Risks"," \u05D7\u05D2"," d\xFCzg\xFCn"," przeb"," \u0AAB\u0ACD\u0AB2"," cringe"," klient\xF3w"," smrti","arpa","\u0ABE\u0AAF\u0AA4"," d\xE9bats","titor"," \u0E40\u0E23\u0E37\u0E48\u0E2D\u0E07","\u0438\u0440\u044B"," \u041F\u0430\u043B","ellaan"," flwyddyn"," \u041E\u0433"," Tron"," fwrite"," philanthrop","trate"," \u0627\u0644\u0643\u0627\u0645\u0644","Publicidade"," roommates"," adulta","\u9A6C\u514B"," \u092B\u093E\u092F\u0926\u093E"," silhouettes","\u79D1\u5B66\u9662"," p\xE1s","\u0C30\u0C15\u0C41","urlijke"," engine"," \u0444\u0430\u0440\u0437",' ",\r\n'," HGH"," \u0431\u0440\u044E"," aangen"," haem","-serving"," rosas"," Dowladda","!/"," correspondente"," \u0627\u0644\u0623\u062F\u0627\u0621","\u0986\u0997"," pokra\u010D","functie"," possiamo",".jfree"," endlaka","sg\xE1l"," spezialisiert"," guzti"," forklift"," nofoaga"," Bartlett","-debug"," feina","\u0631\u0648\u0642"," \u05D1\u05D4\u05D7\u05DC\u05D8"," nascer"," geeks","iliy","_seek","_IRQHandler","\u05DE\u05E6\u05D0"," chinhu"," understandably"," k\xE4y"," Darth"," \uC81C\uACF5\uD569\uB2C8\uB2E4"," \u090F\u0915\u094D\u091F"," \u0633\u0643"," \u06CC\u0627\u0641\u062A\u0647"," totalit\xE9"," nens"," CROSS","_trials","\u0441\u0442\u044D\u0440"," wnd","\u535A\u5F69\u516C\u53F8"," okuf"," verdwenen","\u05D9\u05D3\u05D6\u05E9","/Templates"," \u091A\u0932\u0924\u093E"," aangekond"," beschermd","gevoel"," \u0438\u0447\u0438\u043D\u0434\u0435"," d\xE9licieux","?|","_SIDE","estat"," multas","eig"," \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C"," Satell","varna",".transforms"," Surveys"," impetus"," nakita"," auditions","xiang"," mjini","Shortest","(ord"," \u10DE\u10E0\u10D0\u10E5\u10E2","artuss","\u043F\u0440\u043E","umpulan"," aqu\xF2"," \u10D4\u10D7","owatt","Putting","\u663C","Cambio"," duration","_frac","_plate","Buenas","\xF8ring"," disseram","Customized"," \u0448\u0443\u0434\u0430\u043D\u0438"," consequ\xEAncia"," unloaded",".\u0B8E"," \u7235\u58EB"," prefere"," apparition"," vermijden","\u0AC0\u0AA0","\u7ECF\u5178\u4E09\u7EA7"," \u0938\u0947\u0915\u094D\u0938"," T\u0101",",'.","_aug","\\Array","Readonly","Applicants"," capelli","prd"," captar"," \u0627\u0644\u062A\u0636","rosi","Gob"," \u015Bwiata","nelly"," Conde"," bijk"," \u5929\u5929\u4E50\u8D2D\u5F69\u7968","Chen"," Gaelic"," cuentos"," \u0627\u06CC\u0645\u0627\u0646","-independent","GAR"," \u0432\u0456\u0439\u0441\u044C"," concili","(.)","sels"," \u043A\u04AF\u0440\u04D9"," solte","Phen"," zuz"," quandu","UMIN"," \u056F\u0561\u056D"," Supra","\u3001\u540D\u7121\u3057"," \u05D7\u05D9\u05DC"," masquer"," \u043D\u043E\u0432\u0438\u0447"," augment\xE9","\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0439",".practice"," pasien"," \u015Bwiad"," caretaker","army"," inspiraci\xF3n"," \u0C89\u0CA4\u0CCD\u0CAA","\u10EC\u10E3\u10EE"," aktivitas","_PLAN"," bhaineann","ugbo","\u0995\u09CD\u09B8"," \u0626\u0627\u062F","bier"," protested"," \u0935\u093F\u0930\u093E\u091F"," \u0440\u0430\u0441\u0445\u043E\u0434\u043E\u0432"," ...\n\n\n"," ffur","-All","Constru","Retrieved"," incr\xEDveis"," \u0438\u043C\u043A\u043E"," foliga"," Balanced","\u1021\u101E"," schlechten"," \u03B1\u03BB\u03BB\u03B1\u03B3"," \u0436\u0430\u0441\u0430\u043F"," S\u01A1n","\u0438\u0440\u0430\u0438","\u10D8\u10DC\u10D4"," milioane","EMU","\u2019\xE9viter"," hyr"," encontre"," hallar"," tablas","_Long","<Cell"," interacted"," figsize"," \u10D6\u10E6"," \u0447\u043E\u0432\u0435\u043A"," Codigo"," dedica\xE7\xE3o"," stolet"," Orten","Philip"," \xE9mission","\u0E32\u0E2B\u0E25\u0E35"," bearbeiten"," mierda","holde","\u0443\u0432\u0430\u0432","<Component"," WPA","\u05E6\u05D9\u05DC\u05D5\u05DD","SSA"," Allies"," B\xE1r","_mer","_SMS"," \u0918\u0942\u092E"," Fixtures"," Bask"," \u5F90"," tradu\xE7\xE3o","blicke"," hammered"," \u0441\u04AF\u043F"," \u0431\u0438\u0433","olu\xE7\xE3o"," electricians","\u0631\u06CC\u0634\u0646"," pitsaaner"," cier"," Receita","\u9EBB\u5C06"," \u0437\u0430\u043A\u043E\u043D\u043E\u0434\u0430\u0442\u0435\u043B\u044C\u0441\u0442\u0432\u0430"," \u10DE\u10D0\u10E1\u10E3\u10EE\u10D8\u10E1\u10DB\u10D2","-operated","\u0D4A\u0D2A\u0D4D\u0D2A\u0D02"," hassles","\u093E\u0924\u0930","\u0430\u043D\u0430\u0433\u0430\u0440\u0430","\u05E0\u05D8\u05E8","Japgolly"," doeleinden"," \u043F\u0435\u0440\u0435\u0439\u0442\u0438"," temsil"," ol\xEDmp"," Spazier"," \u0627\u0644\u0633\u0645\u0627"," pressione"," fiscais","l\u0259rini"," abode"," tantric","()],","rello"," \u0437\u0430\u0447\u0430\u0441\u0442\u0443\u044E","\u5FAE\u8F6F\u96C5\u9ED1","\u0633\u0631\u0627\u0626\u064A\u0644\u064A\u0629"," uitzending","flok"," escult"," Cerro"," is\xE6r"," kobiet","uree","\u0C95\u0CCA","encha"," adhesives"," paura","\u30C3\u30D4\u30F3\u30B0","\u0E27\u0E31\u0E22"," names"," slimmer","milk"," \u0A95\u0AB0\u0AA4\u0AC0"," Cim"," \u0441\u0432\u044F\u0437\u0430\u043D","\u200C\u0C28\u0C4D"," Chauff"," vingers","\u0430\u0446\u0430\u0440\u0442"," webcast",".notice"," m\u1EB7c","Passengers"," \u05E4\u05BC\u05E8\u05D0\u05B8\u05D3\u05D5\u05E7\u05D8\u05DF","\u0430\u043C\u0435\u0442\u0440"," VBA"," \u0440\u0430\u0437\u0432\u0438\u0432\u0430\u0435\u0442\u0441\u044F","])));\n"," surfers"," \u05DE\u05EA\u05D0\u05D9\u05DD","')):\n",".apk","\u1EDBm"," \u05D4\u05DE\u05D6"," brincar"," AMOLED"," nate"," ayaan"," phosphorylation"," \u0985\u09AA\u09C7\u0995\u09CD\u09B7"," Eats"," Converse","\u094D\u092F\u0942\u091F\u0930","Traveler","inggi","\u05D5\u05E8\u05D2"," almoh"," \u0625\u0641\u0631\u064A\u0642\u064A\u0627"," Magazin"," Arme","\u0E23\u0E01\u0E34\u0E08"," a\u015Fk","-lines"," \u0627\u0644\u0623\u0645\u0627\u0643\u0646","\u516C\u5E73"," kv\xE4ll"," mlx"," \u092E\u0928\u094D\u0924\u094D\u0930\u0940","\u10D0\u10D5\u10D8\u10D0"," teks"," lumea"," legyen"," zwing"," boost"," J\xFA","\u5F69\u7968\u8BBA\u575B"," \u0434\u044D"," \u043E\u0448\u0438\u0431\u043E\u043A","\u0561\u056F\u0561\u0576\u056B","\u0E24\u0E29\u0E20\u0E32\u0E04\u0E21","ebwa"," tipu"," domini"," Gurgaon","combat"," Resist"," \u0930\u094B\u091C\u0917\u093E\u0930","strategie","\u0A17\u0A40","(locator","MONTH"," atlik"," \uB79C","\u0627\u0644\u0633\u064A"," rzecz"," W\xE4"," deportivos"," Facilit","-able"," evitare"," thong"," \u6D3B","\uBB34\uB8CC"," mace"," Extraordinary","\u0927\u093E"," konflik"," livelihoods"," \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u043E\u0432"," kuitenkaan","\u5E78\u8FD0\u98DE\u8247","Corpus"," besch\xE4d"," \u05D3\u05D5\u05D3"," dentant"," nweta"," heath"," \u0936\u0941\u0915\u094D\u0930\u092C\u093E\u0930"," mnemonic",".Filters",`','".$`," \u0905\u0938\u094D\u0924","isite"," asawa","\u5E74\u6708"," gotas"," \u0C2A\u0C28\u0C3F\u0C1A","Dek"," Pact","'agence","fei\xE7o"," B\xF6yle","venteen","notif"," \u0410\u043D\u0434\u0440\u0435\u0439","\u591A\u5E74","mittedly","\u8CA1\u5E03"," \u043A\u043E\u043C\u043F\u0430\u043A\u0442","trk","\u0928\u094D\u0926\u094D\u0930\u0940\u092F"," miesto"," Kait"," \u0CAC\u0CB8"," spec"," Injector"," logarith","entions"," \u0447\u0435\u043B","Collateral"," confes","\u093F\u0939\u0930"," sufri\xF3","CRI"," tuge","urllib"," k\u013C"," verpleeg"," application's","(Constructor","\u09BE\u09B2\u09BE"," vulputate"," \u043E\u043F\u0443\u0445"," Nordrhein","allage","\xEDsimas","ornado","\u0438\u0434\u0435\u0440","m\xE9nyek","Qua"," pelicula","\uC131\uACFC","\u3011-"," hemi"," touristes"," absentee"," Nether",".PAGE"," i\u015Fg\xE4r"," efectivos"," saav"," ","flashdata"," sembler"," ikuku"," \u099F\u09BE\u0987"," \u201D\n","\u5F69\u7968\u5E73\u53F0\u5F00\u6237","\u65C1",".\u0413","uckles"," \u0627\u0644\u062E\u0627\u0631","\u0432\u043E\u043B\u044C"," \u043D\u0435\u0432\u043E\u0437\u043C\u043E\u0436",".gradient"," ebile"," Athlete"," \u0442\u04B1\u0440\u0493\u0430\u043D"," Syrie",".processing"," Consultancy"," thrills","\u0642\u0631\u0627\u0621","(varargin","k\xFCnfte"," \u5F6D","-knit","riedenheit"," t\xE4nka","']//","udies","hacer"," Th\xE9\xE2tre","av\u7535\u5F71"," Armada","-techn","ibris","veli"," razloga","-Hop"," \u05DE\u05D7\u05D3\u05E9"," Bloggers"," controversies"," \u0C1A\u0C30\u0C4D\u0C2F"," \u0D2A\u0D4D\u0D30\u0D2E\u0D41\u0D16","_unc","werfen"," \u043B\u043E\u043C"," \u043F\u043E\u043A\u0443\u043F\u0430\u0442\u0435\u043B\u0435\u0439"," \u0433\u043B\u0430\u0437\u0430\u043C\u0438"," \u05D1\u05E2\u05D5\u05D3"," nanot"," ws"," \u043A\u0435\u0437\u0434\u0435\u0441","):("," Produit","Aircraft","iffen"," patrones"," par\xE2metros","Cursos"," cocos"];var bpe=c0.concat(c1);c0.length=0;c1.length=0;var o200k_base_default=bpe;var ALL_SPECIAL_TOKENS="all";var DEFAULT_MERGE_CACHE_SIZE=1e5;var isAscii=codePoint=>codePoint<=127;var HIGH_SURROGATE_START=55296;var HIGH_SURROGATE_END=56319;function endsWithIncompleteUtfPairSurrogate(string5){if(string5.length===0)return false;const lastCharCode=string5.charCodeAt(string5.length-1);return lastCharCode>=HIGH_SURROGATE_START&&lastCharCode<=HIGH_SURROGATE_END}function isValidUTF8(bytes){let i=0;while(i<bytes.length){const byte1=bytes[i];let numBytes=0;let codePoint=0;if(byte1<=127){numBytes=1;codePoint=byte1}else if((byte1&224)===192){numBytes=2;codePoint=byte1&31;if(byte1<=193)return false}else if((byte1&240)===224){numBytes=3;codePoint=byte1&15}else if((byte1&248)===240){numBytes=4;codePoint=byte1&7;if(byte1>244)return false}else{return false}if(i+numBytes>bytes.length)return false;for(let j=1;j<numBytes;j++){const byte=bytes[i+j];if(byte===void 0||(byte&192)!==128)return false;codePoint=codePoint<<6|byte&63}if(numBytes===2&&codePoint<128)return false;if(numBytes===3&&codePoint<2048)return false;if(numBytes===4&&codePoint<65536)return false;if(codePoint>=55296&&codePoint<=57343)return false;if(codePoint>1114111)return false;i+=numBytes}return true}var textDecoder=new TextDecoder("utf8",{fatal:false});function tryConvertToString(arr){if(!isValidUTF8(arr)){return void 0}return textDecoder.decode(arr)}function compareUint8Arrays(a,b){const len=Math.min(a.length,b.length);for(let i=0;i<len;i++){if(a[i]!==b[i]){return a[i]-b[i]}}return a.length-b.length}function getMaxValueFromMap(map2){let max=0;map2.forEach(val=>{max=Math.max(max,val)});return max}function escapeRegExp2(string5){return string5.replace(/[$()*+.?[\\\]^{|}]/g,"\\$&")}function getSpecialTokenRegex(tokens2){const escapedTokens=[...tokens2].map(escapeRegExp2);const inner=escapedTokens.join("|");return new RegExp(`(${inner})`)}var emptyBuffer=new Uint8Array(0);var decoder=new TextDecoder("utf8");var BytePairEncodingCore=class{mergeableBytePairRankCount;bytePairRankDecoder;bytePairNonUtfRankDecoder=new Map;bytePairNonUtfSortedEncoder;bytePairStringRankEncoder;tokenSplitRegex;specialTokensEncoder;specialTokensDecoder;specialTokenPatternRegex;textEncoder=new TextEncoder;mergeCache;mergeCacheSize;constructor({bytePairRankDecoder,specialTokensEncoder,tokenSplitRegex,mergeCacheSize=DEFAULT_MERGE_CACHE_SIZE}){this.bytePairRankDecoder=bytePairRankDecoder;this.bytePairStringRankEncoder=new Map;this.mergeCacheSize=mergeCacheSize;if(mergeCacheSize>0){this.mergeCache=new Map}this.mergeableBytePairRankCount=Object.keys(bytePairRankDecoder).length;const binaryLookup=[];bytePairRankDecoder.forEach((value,rank)=>{if(typeof value==="string"){this.bytePairStringRankEncoder.set(value,rank);return}const byteArray=new Uint8Array(value);binaryLookup.push([byteArray,rank]);this.bytePairNonUtfRankDecoder.set(rank,byteArray)});this.bytePairNonUtfSortedEncoder=binaryLookup.sort((a,b)=>compareUint8Arrays(a[0],b[0]));this.specialTokensEncoder=specialTokensEncoder??new Map;this.specialTokensDecoder=specialTokensEncoder?new Map([...specialTokensEncoder].map(([key,value])=>[value,key])):new Map;this.tokenSplitRegex=tokenSplitRegex;const escapedSpecialTokens=[...this.specialTokensEncoder.keys()].map(escapeRegExp2);const allSpecialTokensRegex=escapedSpecialTokens.join("|");try{this.specialTokenPatternRegex=new RegExp(allSpecialTokensRegex,"y")}catch{throw new Error("Invalid regular expression pattern.")}}setMergeCacheSize(newSize){if(this.mergeCacheSize===0&&newSize>0){this.mergeCache=new Map}this.mergeCacheSize=newSize;if(newSize===0){this.mergeCache=void 0}}clearMergeCache(){this.mergeCache?.clear()}*encodeNativeGenerator(text,allowedSpecial){let startIndex=0;let lastTokenLength=0;while(true){const nextSpecialMatch=this.findNextSpecialToken(text,allowedSpecial,startIndex);const nextSpecialStartIndex=nextSpecialMatch?.[0];const endIndex=nextSpecialStartIndex??text.length;const textBeforeSpecial=startIndex===0&&endIndex===text.length?text:text.slice(startIndex,endIndex);for(const[match]of textBeforeSpecial.matchAll(this.tokenSplitRegex)){const token2=this.getBpeRankFromString(match);if(token2!==void 0){lastTokenLength=1;yield[token2];continue}const tokens2=this.bytePairEncode(match);lastTokenLength=tokens2.length;yield tokens2}if(nextSpecialStartIndex!==void 0){const specialToken=nextSpecialMatch[1];const specialTokenValue=this.specialTokensEncoder.get(specialToken);if(specialTokenValue===void 0){throw new Error(`Special token "${specialToken}" is not in the special token encoder.`)}yield[specialTokenValue];startIndex=nextSpecialStartIndex+specialToken.length;lastTokenLength=1}else{break}}return lastTokenLength}encodeNative(text,allowedSpecial){let startIndex=0;const tokensArray=[];while(true){const nextSpecialMatch=this.findNextSpecialToken(text,allowedSpecial,startIndex);const nextSpecialStartIndex=nextSpecialMatch?.[0];const endIndex=nextSpecialStartIndex??text.length;const textBeforeSpecial=startIndex===0&&endIndex===text.length?text:text.slice(startIndex,endIndex);for(const[match]of textBeforeSpecial.matchAll(this.tokenSplitRegex)){const token2=this.getBpeRankFromString(match);if(token2!==void 0){tokensArray.push(token2);continue}const tokens2=this.bytePairEncode(match);tokensArray.push(...tokens2)}if(nextSpecialStartIndex!==void 0){const specialToken=nextSpecialMatch[1];const specialTokenValue=this.specialTokensEncoder.get(specialToken);if(specialTokenValue===void 0){throw new Error(`Special token "${specialToken}" is not in the special token encoder.`)}tokensArray.push(specialTokenValue);startIndex=nextSpecialStartIndex+specialToken.length}else{break}}return tokensArray}countNative(text,allowedSpecial){let startIndex=0;let tokensCount=0;while(true){const nextSpecialMatch=this.findNextSpecialToken(text,allowedSpecial,startIndex);const nextSpecialStartIndex=nextSpecialMatch?.[0];const endIndex=nextSpecialStartIndex??text.length;const textBeforeSpecial=startIndex===0&&endIndex===text.length?text:text.slice(startIndex,endIndex);for(const[match]of textBeforeSpecial.matchAll(this.tokenSplitRegex)){const token2=this.getBpeRankFromString(match);if(token2!==void 0){tokensCount++;continue}const tokens2=this.bytePairEncode(match);tokensCount+=tokens2.length}if(nextSpecialStartIndex!==void 0){const specialToken=nextSpecialMatch[1];const specialTokenValue=this.specialTokensEncoder.get(specialToken);if(specialTokenValue===void 0){throw new Error(`Special token "${specialToken}" is not in the special token encoder.`)}tokensCount++;startIndex=nextSpecialStartIndex+specialToken.length}else{break}}return tokensCount}*decodeNativeGenerator(tokens2){for(const token2 of tokens2){const tokenBytes=this.tryDecodeToken(token2);if(tokenBytes){yield tokenBytes}}}decodeNative(tokens2){let decoded="";let intBuffer=emptyBuffer;for(const token2 of tokens2){const tokenBytes=this.tryDecodeToken(token2);if(tokenBytes===void 0){throw new Error(`Token ${token2} is not in the byte pair encoder.`)}if(typeof tokenBytes==="string"){if(intBuffer!==emptyBuffer){decoded+=decoder.decode(intBuffer,{stream:true});intBuffer=emptyBuffer}decoded+=tokenBytes}else{const newBuffer=new Uint8Array(intBuffer.length+tokenBytes.length);newBuffer.set(intBuffer);newBuffer.set(tokenBytes,intBuffer.length);intBuffer=newBuffer}}if(intBuffer!==emptyBuffer){decoded+=decoder.decode(intBuffer,{stream:true})}return decoded}async*decodeNativeAsyncIterable(tokens2){for await(const token2 of tokens2){const tokenBytesOrString=this.tryDecodeToken(token2);if(tokenBytesOrString){yield tokenBytesOrString}}}getBpeRankFromString(key){return this.bytePairStringRankEncoder.get(key)}getBpeRankFromStringOrThrow(key){const value=this.getBpeRankFromString(key);if(value===void 0){throw new Error(`The byte-pair encoding does not contain a value for: ${key}`)}return value}getBpeRankFromBytes(key){const keyAsString=tryConvertToString(key);if(keyAsString!==void 0){return this.getBpeRankFromString(keyAsString)}const index=this.binarySearch(key);if(index!==-1){return this.bytePairNonUtfSortedEncoder[index][1]}return void 0}getBpeRankFromBytesOrThrow(key){const value=this.getBpeRankFromBytes(key);if(value===void 0){throw new Error(`The byte-pair encoding does not contain a value for: ${key.toString()}`)}return value}binarySearch(key){let low=0;let high=this.bytePairNonUtfSortedEncoder.length-1;while(low<=high){const mid=low+high>>>1;const midKey=this.bytePairNonUtfSortedEncoder[mid][0];let cmp=0;const maxLength=Math.min(midKey.length,key.length);for(let i=0;i<maxLength;i++){cmp=midKey[i]-key[i];if(cmp!==0)break}if(cmp===0){cmp=midKey.length-key.length}if(cmp===0){return mid}if(cmp<0){low=mid+1}else{high=mid-1}}return-1}findNextSpecialToken(text,allowedSpecial,startIndex){let searchIndex=startIndex;while(true){this.specialTokenPatternRegex.lastIndex=searchIndex;const nextSpecialMatch=this.specialTokenPatternRegex.exec(text);if(!nextSpecialMatch){return void 0}const specialToken=nextSpecialMatch[0];if(allowedSpecial?.has(specialToken)){const specialTokenStartIndex=nextSpecialMatch.index+searchIndex;return[specialTokenStartIndex,specialToken]}searchIndex=nextSpecialMatch.index+searchIndex+1}}tryDecodeToken(tokenRank){const value=this.bytePairRankDecoder[tokenRank];if(typeof value==="string"){return value}if(typeof value==="object"){const fromBinary=this.bytePairNonUtfRankDecoder.get(tokenRank);if(fromBinary){return fromBinary}}return this.specialTokensDecoder.get(tokenRank)}addToMergeCache(key,value){if(!this.mergeCache)return;if(this.mergeCache.size>=this.mergeCacheSize){const firstKey=this.mergeCache.keys().next().value;this.mergeCache.delete(firstKey)}this.mergeCache.set(key,value)}bytePairEncode(input){if(input.length===1&&isAscii(input.codePointAt(0))){return[this.getBpeRankFromStringOrThrow(input)]}if(this.mergeCache?.has(input)){const result3=this.mergeCache.get(input);this.mergeCache.delete(input);this.mergeCache.set(input,result3);return result3}const inputBytes=this.textEncoder.encode(input);const result2=this.bytePairMerge(inputBytes);this.addToMergeCache(input,result2);return result2}bytePairMerge(piece){const starts=[];const ranks=[];const getRank=(startIndex,pairStart=starts[startIndex],pairEnd=starts[startIndex+2])=>{if(pairEnd===void 0){return Number.POSITIVE_INFINITY}const key=piece.subarray(pairStart,pairEnd);const rank=this.getBpeRankFromBytes(key);return rank??Number.POSITIVE_INFINITY};for(let i=0;i<=piece.length;i++){starts.push(i);if(i<piece.length-1){ranks.push(getRank(i,i,i+2))}else{ranks.push(Number.POSITIVE_INFINITY)}}while(starts.length>1){let lowestRank=Number.POSITIVE_INFINITY;let lowestPartitionIndex=-1;for(let i=0;i<ranks.length-1;i++){const rank=ranks[i];if(rank<lowestRank){lowestRank=rank;lowestPartitionIndex=i}}if(lowestRank===Number.POSITIVE_INFINITY||lowestPartitionIndex===-1){break}starts.splice(lowestPartitionIndex+1,1);ranks.splice(lowestPartitionIndex,1);ranks[lowestPartitionIndex]=getRank(lowestPartitionIndex);if(lowestPartitionIndex>0){ranks[lowestPartitionIndex-1]=getRank(lowestPartitionIndex-1)}}const output2=[];for(let i=0;i<starts.length-1;i++){const pairStart=starts[i];const pairEnd=starts[i+1];const bpeValue=this.getBpeRankFromBytesOrThrow(piece.subarray(pairStart,pairEnd));output2.push(bpeValue)}return output2}};var MESSAGE_TOKEN_OVERHEAD=3;var MESSAGE_NAME_TOKEN_OVERHEAD=1;var FUNCTION_ROLE_TOKEN_DISCOUNT=2;var FUNCTION_CALL_METADATA_TOKEN_OVERHEAD=3;var FUNCTION_DEFINITION_TOKEN_OVERHEAD=9;var COMPLETION_REQUEST_TOKEN_OVERHEAD=3;var FUNCTION_CALL_NAME_TOKEN_OVERHEAD=4;var FUNCTION_CALL_NONE_TOKEN_OVERHEAD=1;var SYSTEM_FUNCTION_TOKEN_DEDUCTION=4;var NEWLINE="\n";function countMessageTokens(message,countStringTokens){let tokens2=0;if(message.role){tokens2+=countStringTokens(message.role)}if(message.content){tokens2+=countStringTokens(message.content)}if(message.name){tokens2+=countStringTokens(message.name)+MESSAGE_NAME_TOKEN_OVERHEAD}if(message.function_call){const{name,arguments:args}=message.function_call;if(name){tokens2+=countStringTokens(name)}if(args){tokens2+=countStringTokens(args)}tokens2+=FUNCTION_CALL_METADATA_TOKEN_OVERHEAD}tokens2+=MESSAGE_TOKEN_OVERHEAD;if(message.role==="function"){tokens2-=FUNCTION_ROLE_TOKEN_DISCOUNT}return tokens2}function formatObjectProperties(obj,indent,formatType){if(!obj.properties){return""}const lines=[];const requiredParams=new Set(obj.required??[]);const indentString=" ".repeat(indent);for(const[name,param]of Object.entries(obj.properties)){if(param.description&&indent<2){lines.push(`${indentString}// ${param.description}`)}const isRequired=requiredParams.has(name);const formattedType=formatType(param,indent);lines.push(`${indentString}${name}${isRequired?"":"?"}: ${formattedType},`)}return lines.join("\n")}function formatFunctionType(param,indent){switch(param.type){case"string":return param.enum?.map(value=>JSON.stringify(value)).join(" | ")??"string";case"integer":case"number":return param.enum?.map(value=>`${value}`).join(" | ")??"number";case"boolean":return"boolean";case"null":return"null";case"array":return param.items?`${formatFunctionType(param.items,indent)}[]`:"any[]";case"object":{const inner=formatObjectProperties(param,indent+2,formatFunctionType);const closingIndent=" ".repeat(indent);return`{
2016
2047
  ${inner}
2017
2048
  ${closingIndent}}`}default:return"any"}}function formatFunctionDefinitions(functions){const lines=["namespace functions {",""];for(const fn of functions){if(fn.description){lines.push(`// ${fn.description}`)}const{parameters}=fn;const properties=parameters?.properties;if(!parameters||!properties||Object.keys(properties).length===0){lines.push(`type ${fn.name} = () => any;`)}else{lines.push(`type ${fn.name} = (_: {`);const formattedProperties=formatObjectProperties(parameters,0,formatFunctionType);if(formattedProperties.length>0){lines.push(formattedProperties)}lines.push("}) => any;")}lines.push("")}lines.push("} // namespace functions");return lines.join("\n")}function estimateTokensInFunctions(functions,countStringTokens){const formatted=formatFunctionDefinitions(functions);let tokens2=countStringTokens(formatted);tokens2+=FUNCTION_DEFINITION_TOKEN_OVERHEAD;return tokens2}function padSystemMessage(message,hasFunctions,isSystemPadded){if(!hasFunctions||isSystemPadded||message.role!=="system"){return message}if(!message.content||message.content.endsWith(NEWLINE)){return message}return{...message,content:`${message.content}${NEWLINE}`}}function computeChatCompletionTokenCount(request,countStringTokens){const{messages,functions,function_call:functionCall}=request;const hasFunctions=Boolean(functions&&functions.length>0);let paddedSystem=false;let total=0;for(const message of messages){const messageToCount=padSystemMessage(message,hasFunctions,paddedSystem);if(messageToCount!==message&&message.role==="system"){paddedSystem=true}else if(message.role==="system"&&hasFunctions&&!paddedSystem){paddedSystem=true}total+=countMessageTokens(messageToCount,countStringTokens)}total+=COMPLETION_REQUEST_TOKEN_OVERHEAD;if(hasFunctions&&functions){total+=estimateTokensInFunctions(functions,countStringTokens);if(messages.some(message=>message.role==="system")){total-=SYSTEM_FUNCTION_TOKEN_DEDUCTION}}if(functionCall&&functionCall!=="auto"){if(functionCall==="none"){total+=FUNCTION_CALL_NONE_TOKEN_OVERHEAD}else if(typeof functionCall==="object"&&functionCall.name){total+=countStringTokens(functionCall.name)+FUNCTION_CALL_NAME_TOKEN_OVERHEAD}}return total}var chatEnabledModels=["chatgpt-4o-latest","codex-mini-latest","computer-use-preview","computer-use-preview-2025-03-11","gpt-3.5","gpt-3.5-0301","gpt-3.5-turbo","gpt-3.5-turbo-0125","gpt-3.5-turbo-0613","gpt-3.5-turbo-1106","gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-instruct","gpt-4","gpt-4-0125-preview","gpt-4-0314","gpt-4-0613","gpt-4-1106-preview","gpt-4-1106-vision-preview","gpt-4-32k","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-audio-preview-2025-06-03","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4o-mini-audio-preview","gpt-4o-mini-audio-preview-2024-12-17","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-5","gpt-5-2025-08-07","gpt-5-chat-latest","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-audio","gpt-audio-2025-08-28","gpt-audio-mini","gpt-audio-mini-2025-10-06","gpt-oss-120b","gpt-oss-20b","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","o1-preview","o1-preview-2024-09-12","o1-pro","o1-pro-2025-03-19","o3","o3-2025-04-16","o3-deep-research","o3-deep-research-2025-06-26","o3-mini","o3-mini-2025-01-31","o3-pro","o3-pro-2025-06-10","o4-mini","o4-mini-2025-04-16","o4-mini-deep-research","o4-mini-deep-research-2025-06-26"];var modelsMap_exports={};__export(modelsMap_exports,{cl100k_base:()=>cl100k_base,o200k_base:()=>o200k_base,o200k_harmony:()=>o200k_harmony,p50k_base:()=>p50k_base,p50k_edit:()=>p50k_edit,r50k_base:()=>r50k_base});var p50k_base=["text-davinci-002","text-davinci-003","code-davinci-001","code-davinci-002","davinci-codex","code-cushman-001","code-cushman-002","cushman-codex"];var r50k_base=["text-ada-001","text-babbage-001","text-curie-001","text-davinci-001","ada","babbage","curie","davinci","code-search-ada-code-001","code-search-ada-text-001","text-similarity-ada-001","text-search-ada-doc-001","text-search-ada-query-001","text-similarity-babbage-001","text-search-babbage-doc-001","text-search-babbage-query-001","code-search-babbage-code-001","code-search-babbage-text-001","text-similarity-curie-001","text-search-curie-doc-001","text-search-curie-query-001","text-similarity-davinci-001","text-search-davinci-doc-001","text-search-davinci-query-001"];var p50k_edit=["code-davinci-edit-001","text-davinci-edit-001"];var cl100k_base=["gpt-3.5","gpt-3.5-0301","gpt-3.5-turbo","gpt-3.5-turbo-0125","gpt-3.5-turbo-0613","gpt-3.5-turbo-1106","gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-instruct","gpt-4","gpt-4-0125-preview","gpt-4-0314","gpt-4-0613","gpt-4-1106-preview","gpt-4-1106-vision-preview","gpt-4-32k","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","text-embedding-3-large","text-embedding-3-small","text-embedding-ada-002","babbage-002","davinci-002"];var o200k_base=[];var o200k_harmony=["gpt-oss-20b","gpt-oss-120b"];var EndOfText="<|endoftext|>";var FimPrefix="<|fim_prefix|>";var FimMiddle="<|fim_middle|>";var FimSuffix="<|fim_suffix|>";var ImStart="<|im_start|>";var ImEnd="<|im_end|>";var ImSep="<|im_sep|>";var EndOfPrompt="<|endofprompt|>";var HarmonyStartOfText="<|startoftext|>";var HarmonyStart="<|start|>";var HarmonyEnd="<|end|>";var HarmonyMessage="<|message|>";var HarmonyChannel="<|channel|>";var HarmonyReturn="<|return|>";var HarmonyConstrain="<|constrain|>";var HarmonyCall="<|call|>";var o200k_base2="o200k_base";var DEFAULT_ENCODING=o200k_base2;var modelToEncodingMap=Object.fromEntries(Object.entries(modelsMap_exports).flatMap(([encodingName,models])=>models.map(modelName=>[modelName,encodingName])));var gpt3params={messageSeparator:"\n",roleSeparator:"\n"};var gpt4params={messageSeparator:"",roleSeparator:ImSep};var chatModelParams=Object.fromEntries(chatEnabledModels.flatMap(modelName=>modelName.startsWith("gpt-3.5")?[[modelName,gpt3params]]:[[modelName,gpt4params]]));var R50K_TOKEN_SPLIT_REGEX=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu");var CONTRACTION_SUFFIX_PATTERN=String.raw`'(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`;var OPTIONAL_CONTRACTION_SUFFIX=String.raw`(?:${CONTRACTION_SUFFIX_PATTERN})?`;var CL100K_TOKEN_SPLIT_PATTERN=String.raw`${CONTRACTION_SUFFIX_PATTERN}|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s+$|\s*[\r\n]|\s+(?!\S)|\s`;var CL100K_TOKEN_SPLIT_REGEX=new RegExp(CL100K_TOKEN_SPLIT_PATTERN,"gu");var O200K_TOKEN_SPLIT_PATTERN=String.raw`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+${OPTIONAL_CONTRACTION_SUFFIX}|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*${OPTIONAL_CONTRACTION_SUFFIX}|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`;var O200K_TOKEN_SPLIT_REGEX=new RegExp(O200K_TOKEN_SPLIT_PATTERN,"gu");function Cl100KBase(bytePairRankDecoder){const specialTokenMapping=new Map([[EndOfText,100257],[FimPrefix,100258],[FimMiddle,100259],[FimSuffix,100260],[ImStart,100264],[ImEnd,100265],[ImSep,100266],[EndOfPrompt,100276]]);return{tokenSplitRegex:CL100K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}var O200K_BASE_SPECIAL_TOKEN_ENTRIES=[[EndOfText,199999],[FimPrefix,2e5],[FimMiddle,200001],[FimSuffix,200002],[ImStart,200003],[ImEnd,200004],[ImSep,200005],[EndOfPrompt,200006]];var createO200KSpecialTokenMap=()=>new Map(O200K_BASE_SPECIAL_TOKEN_ENTRIES);function O200KBase(bytePairRankDecoder){return{tokenSplitRegex:O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:createO200KSpecialTokenMap()}}var RESERVED_TOKEN_RANGE_START=200013;var RESERVED_TOKEN_RANGE_END=201088;var STATIC_SPECIAL_TOKEN_ENTRIES=[[HarmonyStartOfText,199998],[EndOfText,199999],["<|reserved_200000|>",2e5],["<|reserved_200001|>",200001],[HarmonyReturn,200002],[HarmonyConstrain,200003],["<|reserved_200004|>",200004],[HarmonyChannel,200005],[HarmonyStart,200006],[HarmonyEnd,200007],[HarmonyMessage,200008],["<|reserved_200009|>",200009],["<|reserved_200010|>",200010],["<|reserved_200011|>",200011],[HarmonyCall,200012]];function O200KHarmony(bytePairRankDecoder){const specialTokensEncoder=new Map(STATIC_SPECIAL_TOKEN_ENTRIES);for(let tokenId=RESERVED_TOKEN_RANGE_START;tokenId<RESERVED_TOKEN_RANGE_END;tokenId+=1){specialTokensEncoder.set(`<|reserved_${tokenId}|>`,tokenId)}specialTokensEncoder.set(EndOfPrompt,200018);return{tokenSplitRegex:O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder,chatFormatter:"harmony"}}function P50KBase(bytePairRankDecoder){return{expectedVocabularySize:50281,tokenSplitRegex:R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[EndOfText,50256]])}}function P50KEdit(bytePairRankDecoder){const specialTokenMapping=new Map([[EndOfText,50256],[FimPrefix,50281],[FimMiddle,50282],[FimSuffix,50283]]);return{tokenSplitRegex:R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}function R50KBase(bytePairRankDecoder){return{expectedVocabularySize:50257,tokenSplitRegex:R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[EndOfText,50256]])}}function getEncodingParams(encodingName,getMergeableRanks){const mergeableBytePairRanks=getMergeableRanks(encodingName);switch(encodingName.toLowerCase()){case"r50k_base":return R50KBase(mergeableBytePairRanks);case"p50k_base":return P50KBase(mergeableBytePairRanks);case"p50k_edit":return P50KEdit(mergeableBytePairRanks);case"cl100k_base":return Cl100KBase(mergeableBytePairRanks);case"o200k_base":return O200KBase(mergeableBytePairRanks);case"o200k_harmony":return O200KHarmony(mergeableBytePairRanks);default:throw new Error(`Unknown encoding name: ${encodingName}`)}}var GptEncoding=class _GptEncoding{static EndOfPrompt=EndOfPrompt;static EndOfText=EndOfText;static FimMiddle=FimMiddle;static FimPrefix=FimPrefix;static FimSuffix=FimSuffix;modelName;modelSpec;bytePairEncodingCoreProcessor;specialTokensEncoder;specialTokensSet;allSpecialTokenRegex;defaultSpecialTokenConfig;chatFormatter;countChatCompletionTokens;vocabularySize;constructor({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,expectedVocabularySize,modelName,modelSpec,chatFormatter,...rest}){this.specialTokensEncoder=specialTokensEncoder;this.specialTokensSet=new Set(this.specialTokensEncoder.keys());this.allSpecialTokenRegex=getSpecialTokenRegex(this.specialTokensSet);this.bytePairEncodingCoreProcessor=new BytePairEncodingCore({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,...rest});this.defaultSpecialTokenConfig=this.processSpecialTokens();const maxTokenValue=Math.max(mergeableBytePairRanks.length-1,getMaxValueFromMap(specialTokensEncoder));this.vocabularySize=this.bytePairEncodingCoreProcessor.mergeableBytePairRankCount+specialTokensEncoder.size;if(expectedVocabularySize!==void 0){if(this.vocabularySize!==expectedVocabularySize){throw new Error("The number of mergeable tokens and special tokens must be equal to expectedVocabularySize.")}if(maxTokenValue!==expectedVocabularySize-1){throw new Error(`The model encodings are invalid. The maximum token value must be equal to expectedVocabularySize - 1. Currently ${maxTokenValue}, expected ${expectedVocabularySize-1}`)}}this.encode=this.encode.bind(this);this.decode=this.decode.bind(this);this.encodeGenerator=this.encodeGenerator.bind(this);this.decodeGenerator=this.decodeGenerator.bind(this);this.decodeAsyncGenerator=this.decodeAsyncGenerator.bind(this);this.decodeAsync=this.decodeAsync.bind(this);this.isWithinTokenLimit=this.isWithinTokenLimit.bind(this);this.encodeChat=this.encodeChat.bind(this);this.encodeChatGenerator=this.encodeChatGenerator.bind(this);this.countTokens=this.countTokens.bind(this);this.setMergeCacheSize=this.setMergeCacheSize.bind(this);this.clearMergeCache=this.clearMergeCache.bind(this);this.estimateCost=this.estimateCost.bind(this);if(modelSpec?.supported_features?.includes("function_calling")){this.countChatCompletionTokens=this.countChatCompletionTokensInternal.bind(this)}this.modelName=modelName;this.modelSpec=modelSpec;this.chatFormatter=chatFormatter??"chatml"}*encodeHarmonyChatGenerator(chat,encodeOptions){const harmonyStart=this.specialTokensEncoder.get(HarmonyStart);const harmonyMessage=this.specialTokensEncoder.get(HarmonyMessage);const harmonyEnd=this.specialTokensEncoder.get(HarmonyEnd);const harmonyReturn=this.specialTokensEncoder.get(HarmonyReturn);const harmonyCall=this.specialTokensEncoder.get(HarmonyCall);const harmonyChannel=this.specialTokensEncoder.get(HarmonyChannel);const harmonyConstrain=this.specialTokensEncoder.get(HarmonyConstrain);if(harmonyStart===void 0||harmonyMessage===void 0||harmonyEnd===void 0||harmonyReturn===void 0||harmonyCall===void 0||harmonyChannel===void 0||harmonyConstrain===void 0){throw new Error("Harmony chat format requires dedicated special tokens.")}const encodeHeaderText=text=>text.length>0?this.encode(text):[];const resolveTerminatorToken=terminator=>{switch(terminator){case"<|return|>":return harmonyReturn;case"<|call|>":return harmonyCall;case"<|end|>":default:return harmonyEnd}};for(const message of chat){if(message.content===void 0){throw new Error("Content must be defined for all messages.")}const roleOrName=message.name??message.role??"user";yield[harmonyStart];yield encodeHeaderText(roleOrName);const recipientInRole=message.recipient&&(message.recipientPlacement==="role"||!message.channel);const recipientInChannel=message.recipient&&!recipientInRole;if(recipientInRole){yield encodeHeaderText(` to=${message.recipient}`)}if(message.channel){yield[harmonyChannel];yield encodeHeaderText(message.channel);if(recipientInChannel){yield encodeHeaderText(` to=${message.recipient}`)}}if(message.constraint){yield[harmonyConstrain];yield encodeHeaderText(message.constraint)}yield[harmonyMessage];yield*this.encodeGenerator(message.content,encodeOptions);yield[resolveTerminatorToken(message.terminator)]}const assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0){yield[harmonyStart];yield encodeHeaderText(assistantPrime)}}static getEncodingApi(encodingName,getMergeableRanks){const modelParams=getEncodingParams(encodingName,getMergeableRanks);return new _GptEncoding(modelParams)}static getEncodingApiForModel(modelName,getMergeableRanks,modelSpec){const encodingName=modelToEncodingMap[modelName]??DEFAULT_ENCODING;const modelParams=getEncodingParams(encodingName,getMergeableRanks);return new _GptEncoding({...modelParams,modelName,modelSpec})}processSpecialTokens({allowedSpecial,disallowedSpecial}={}){let regexPattern;if(allowedSpecial===ALL_SPECIAL_TOKENS||allowedSpecial?.has(ALL_SPECIAL_TOKENS)){allowedSpecial=new Set(this.specialTokensSet);const allowedSpecialSet=allowedSpecial;if(disallowedSpecial===ALL_SPECIAL_TOKENS){throw new Error('allowedSpecial and disallowedSpecial cannot both be set to "all".')}if(typeof disallowedSpecial==="object"){disallowedSpecial.forEach(val=>allowedSpecialSet.delete(val))}else{disallowedSpecial=new Set}}if(!disallowedSpecial||disallowedSpecial===ALL_SPECIAL_TOKENS||disallowedSpecial.has(ALL_SPECIAL_TOKENS)){disallowedSpecial=new Set(this.specialTokensSet);const disallowedSpecialSet=disallowedSpecial;if(allowedSpecial?.size){allowedSpecial.forEach(val=>disallowedSpecialSet.delete(val));disallowedSpecial.forEach(val=>allowedSpecial.delete(val));if(disallowedSpecial.size>0){regexPattern=getSpecialTokenRegex(disallowedSpecial)}}else{regexPattern=this.allSpecialTokenRegex}}return{allowedSpecial,regexPattern}}encodeGenerator(lineToEncode,encodeOptions){const specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){const match=lineToEncode.match(specialTokenConfig.regexPattern);if(match!==null){throw new Error(`Disallowed special token found: ${match[0]}`)}}return this.bytePairEncodingCoreProcessor.encodeNativeGenerator(lineToEncode,specialTokenConfig.allowedSpecial)}encode(lineToEncode,encodeOptions){const specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){const match=lineToEncode.match(specialTokenConfig.regexPattern);if(match!==null){throw new Error(`Disallowed special token found: ${match[0]}`)}}return this.bytePairEncodingCoreProcessor.encodeNative(lineToEncode,specialTokenConfig.allowedSpecial)}*encodeChatGenerator(chat,model=this.modelName,encodeOptions){if(!model){throw new Error("Model name must be provided either during initialization or passed in to the method.")}const params=chatModelParams[model];if(!params){throw new Error(`Model '${model}' does not support chat.`)}if(this.chatFormatter==="harmony"){yield*this.encodeHarmonyChatGenerator(chat,encodeOptions);return}const chatStartToken=this.specialTokensEncoder.get(ImStart);const chatEndToken=this.specialTokensEncoder.get(ImEnd);if(chatStartToken===void 0||chatEndToken===void 0){throw new Error(`Model '${model}' does not support chat.`)}const allowedSpecial=new Set([ImSep]);const{messageSeparator,roleSeparator}=params;const encodedMessageSeparator=messageSeparator.length>0?this.encode(messageSeparator):[];const encodedRoleSeparator=roleSeparator.length>0?this.encode(roleSeparator,{allowedSpecial}):[];const nameCache=new Map;for(const{role="system",name=role,content}of chat){if(content===void 0){throw new Error("Content must be defined for all messages.")}yield[chatStartToken];const encodedName=nameCache.get(name)??this.encode(name);nameCache.set(name,encodedName);yield encodedName;if(encodedRoleSeparator.length>0){yield encodedRoleSeparator}yield*this.encodeGenerator(content,encodeOptions);yield[chatEndToken];yield encodedMessageSeparator}const assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0){yield[chatStartToken];yield*this.encodeGenerator(assistantPrime,encodeOptions)}if(encodedRoleSeparator.length>0){yield encodedRoleSeparator}}encodeChat(chat,model=this.modelName,encodeOptions){return[...this.encodeChatGenerator(chat,model,encodeOptions)].flat()}isWithinTokenLimit(input,tokenLimit,encodeOptions){const tokenGenerator=typeof input==="string"?this.encodeGenerator(input,encodeOptions):this.encodeChatGenerator(input,void 0,encodeOptions);let count=0;for(const tokens2 of tokenGenerator){count+=tokens2.length;if(count>tokenLimit){return false}}return count}countTokens(input,encodeOptions){if(typeof input==="string"){const specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){const match=input.match(specialTokenConfig.regexPattern);if(match!==null){throw new Error(`Disallowed special token found: ${match[0]}`)}}return this.bytePairEncodingCoreProcessor.countNative(input,specialTokenConfig.allowedSpecial)}const tokenGenerator=this.encodeChatGenerator(input,void 0,encodeOptions);let count=0;for(const tokens2 of tokenGenerator){count+=tokens2.length}return count}countStringTokens(text){if(!text){return 0}return this.bytePairEncodingCoreProcessor.countNative(text)}countChatCompletionTokensInternal(request){return computeChatCompletionTokenCount(request,text=>this.countStringTokens(text))}setMergeCacheSize(size){this.bytePairEncodingCoreProcessor.setMergeCacheSize(size)}clearMergeCache(){this.bytePairEncodingCoreProcessor.clearMergeCache()}decode(inputTokensToDecode){return this.bytePairEncodingCoreProcessor.decodeNative(inputTokensToDecode)}*decodeGenerator(inputTokensToDecode){const decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeGenerator(inputTokensToDecode);let buffer="";for(const decodedPart of decodedByteGenerator){buffer+=typeof decodedPart==="string"?decodedPart:decoder.decode(decodedPart,{stream:true});if(buffer.length===0||endsWithIncompleteUtfPairSurrogate(buffer)){continue}else{yield buffer;buffer=""}}if(buffer.length>0){yield buffer}}async*decodeAsyncGenerator(inputTokensToDecode){const decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode);let buffer="";for await(const decodedPart of decodedByteGenerator){buffer+=typeof decodedPart==="string"?decodedPart:decoder.decode(decodedPart,{stream:true});if(buffer.length===0||endsWithIncompleteUtfPairSurrogate(buffer)){continue}else{yield buffer;buffer=""}}if(buffer.length>0){yield buffer}}async decodeAsync(inputTokensToDecode){const decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode);let buffer="";for await(const decodedPart of decodedByteGenerator){buffer+=typeof decodedPart==="string"?decodedPart:decoder.decode(decodedPart,{stream:true})}return buffer}estimateCost(tokenCount,modelSpec=this.modelSpec){if(!modelSpec){throw new Error("Model spec must be provided either during initialization or passed in to the method.")}if(!modelSpec.price_data){throw new Error(`No cost information available for model: ${modelSpec.name}`)}const priceDataPerMillion=modelSpec.price_data;const result2={};const millionTokens=tokenCount/1e6;if(priceDataPerMillion.main){result2.main={input:priceDataPerMillion.main.input&&priceDataPerMillion.main.input*millionTokens,output:priceDataPerMillion.main.output&&priceDataPerMillion.main.output*millionTokens,cached_input:priceDataPerMillion.main.cached_input&&priceDataPerMillion.main.cached_input*millionTokens,cached_output:priceDataPerMillion.main.cached_output&&priceDataPerMillion.main.cached_output*millionTokens}}if(priceDataPerMillion.batch){result2.batch={input:priceDataPerMillion.batch.input&&priceDataPerMillion.batch.input*millionTokens,output:priceDataPerMillion.batch.output&&priceDataPerMillion.batch.output*millionTokens,cached_input:priceDataPerMillion.batch.cached_input&&priceDataPerMillion.batch.cached_input*millionTokens,cached_output:priceDataPerMillion.batch.cached_output&&priceDataPerMillion.batch.cached_output*millionTokens}}return result2}};var api=GptEncoding.getEncodingApi("o200k_base",()=>o200k_base_default);var{decode:decode3,decodeAsyncGenerator,decodeGenerator,encode:encode3,encodeGenerator,isWithinTokenLimit,countTokens,encodeChat,encodeChatGenerator,vocabularySize,setMergeCacheSize,clearMergeCache,estimateCost}=api;function scanSecrets(path,content){const patterns=[["private-key",/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/],["aws-access-key",/\bAKIA[0-9A-Z]{16}\b/],["github-token",/\bgh[ps]_[A-Za-z0-9]{30,}\b/],["generic-secret",/(?:api[_-]?key|secret|token|password)\s*[:=]\s*["'][^"'\s]{12,}["']/i]];const findings=[];for(const[kind,pattern]of patterns){const match=content.match(pattern);if(match?.index!==void 0){findings.push({path,line:content.slice(0,match.index).split("\n").length,kind})}}return findings}var ContextPackBuildError=class extends Error{constructor(findings){super(`Context pack rejected: ${findings.map(finding3=>`${finding3.rule}:${finding3.path}`).join(", ")}`);this.findings=findings}findings;name="ContextPackBuildError"};function validateContextPack(pack){const findings=[];if(pack.estimatedTokens>pack.budget){findings.push({rule:"budget",path:"context-pack",message:"Token budget exceeded"})}const included=new Set(pack.items.map(item=>item.path));const criticalMissing=new Set(pack.diagnostics.filter(diagnostic=>diagnostic.code==="critical-missing").map(diagnostic=>diagnostic.path));for(const diagnostic of pack.diagnostics){if(diagnostic.code==="critical-missing"){findings.push({rule:"critical-missing",path:diagnostic.path,message:diagnostic.message})}}for(const reference of pack.unresolvedRequiredReferences){findings.push({rule:"required-reference-missing",path:reference,message:"Lifecycle Requirement or Acceptance Criterion does not resolve in the selected Requirements"})}for(const path of pack.requiredFiles){if(!included.has(path)&&!criticalMissing.has(path)){const omission=pack.omissions.find(candidate=>candidate.path===path);findings.push({rule:"critical-omitted",path,message:omission?.reason==="required-budget-exceeded"?"Required context does not fit the pack budget; increase the budget or reduce required context.":"Required context invariant was omitted"})}}for(const item of pack.items){for(const secret of scanSecrets(item.path,item.content)){findings.push({rule:"secret",path:item.path,message:`${secret.kind}:${secret.line}`})}}return findings}function assertNoSecrets(path,content){const findings=scanSecrets(path,content);if(findings.length>0){throw new ContextPackBuildError(findings.map(finding3=>({rule:"secret",path:finding3.path,message:`${finding3.kind}:${finding3.line}`})))}}var CONTEXT_ROLES=["orchestrator","builder","reviewer","integrator","auditor"];var CONTEXT_PHASES=["conversation","definition","planning","execution","verification","evidence"];function inferContextPhase(query){const normalized=query.replace(/\b(?:AC|REQ|RULE)-[A-Z0-9-]+\b/gi," ").toLowerCase();if(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+\b/i.test(query))return"execution";if(/^\s*(?:(?:por favor|please)[,\s]+)?(?:(?:pode|quero|preciso)\s+)?(?:crie|criar|create)\b/.test(normalized)){return"execution"}if(/\b(?:implement|implemente|implementar|c[oó]digo|code|codificar|corrija|corrigir|desenvolva|desenvolver)\b/.test(normalized)){return"execution"}if(/(?:^|\s)(?:[\w.-]+\/)+[\w.-]+\.[a-z0-9]+\b/i.test(query))return"definition";if(/\b(evidence|evidencia|evidencias|audit|auditoria)\b/.test(normalized))return"evidence";if(/\b(verify|verification|review|test|verificar|revisao|teste)\b/.test(normalized)){return"verification"}if(/\b(execute|execution|run|executar|execucao)\b/.test(normalized))return"execution";if(/\b(plan|planning|spec|planeje|planejar|planejamento)\b/.test(normalized))return"planning";return"conversation"}function contextProfileReason(path,role,phase2){const normalized=path.toLowerCase();const rolePatterns={orchestrator:/(?:project\.yaml|agents\/catalog|tasks|executions|specs|prds)/,builder:/(?:\/src\/|\.test\.|requirements|rules|task|change)/,reviewer:/(?:\.test\.|review|evidence|requirements|task|change)/,integrator:/(?:package\.json|lock|integration|e2e|execution|change)/,auditor:/(?:evidence|decision|run|audit|requirement|test|review)/};const phasePatterns={conversation:/^$/,definition:/(?:prd|requirement|project\.yaml)/,planning:/(?:spec|change|architecture|plan)/,execution:/(?:task|execution|\/src\/|command)/,verification:/(?:test|review|eval|check)/,evidence:/(?:evidence|decision|run|result|trace)/};const matchesRole=rolePatterns[role].test(normalized);const matchesPhase=phasePatterns[phase2].test(normalized);if(matchesRole&&matchesPhase)return`role:${role}+phase:${phase2}`;if(matchesRole)return`role:${role}`;if(matchesPhase)return`phase:${phase2}`;return null}init_src();function parseRuleMetadata(content){const raw=parseRuleDocument(content).metadata;return{id:raw.id,load:raw.load,globs:raw.globs,priority:raw.priority,maxContextTokens:raw.max_context_tokens,requires:raw.requires,triggers:raw.triggers,phases:raw.phases,domains:raw.domains}}function selectRulePaths(entries,targetPaths,query,phase2){const rules=entries.filter(entry2=>entry2.path.startsWith(".agents/rules/")&&entry2.path.endsWith(".md")).map(entry2=>({path:entry2.path,metadata:parseRuleMetadata(entry2.content)}));assertUniqueRuleIds(rules);assertRuleDependencies(rules);const selected=new Set;const requiredByPhase=phase2==="execution"?new Set(["RULE-WORKFLOW","RULE-RUN-LIFECYCLE-CLOSURE"]):phase2==="planning"?new Set(["RULE-WORKFLOW"]):new Set;const conversational=phase2==="conversation";const normalizedQuery=normalizeRuleText(query);for(const rule of rules){const metadata2=rule.metadata;const applies=matchesRuleId(metadata2.id,normalizedQuery)||metadata2.load==="always"||requiredByPhase.has(metadata2.id)||metadata2.load==="file_match"&&metadata2.globs.some(glob=>targetPaths.some(path=>globMatches(glob,path)))||metadata2.load==="auto"&&appliesRuleMetadata(metadata2,normalizedQuery,phase2,conversational);if(applies)selected.add(rule.path)}let changed=true;while(changed){changed=false;for(const rule of rules.filter(candidate=>selected.has(candidate.path))){for(const requirement of rule.metadata.requires){const required2=rules.find(candidate=>candidate.metadata.id===requirement);if(required2===void 0){throw new Error(`Rule ${rule.metadata.id} requires missing Rule ${requirement}`)}if(!selected.has(required2.path)){selected.add(required2.path);changed=true}}}}return[...selected].sort(comparePaths2)}function normalizeRuleText(value){return` ${value.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g," ").trim()} `}function hasWholePhrase(query,phrase){const normalized=normalizeRuleText(phrase).trim();return normalized.length>0&&query.includes(` ${normalized} `)}function matchesRuleId(id,query){return hasWholePhrase(query,id)}function appliesRuleMetadata(metadata2,normalizedQuery,phase2,conversational){if(metadata2.phases.length>0&&(phase2===void 0||!metadata2.phases.includes(phase2))){return false}const domainMatches=metadata2.domains.length===0||metadata2.domains.some(domain2=>hasWholePhrase(normalizedQuery,domain2));if(metadata2.triggers.length>0){return domainMatches&&metadata2.triggers.some(trigger=>hasWholePhrase(normalizedQuery,trigger))}if(metadata2.domains.length>0)return domainMatches;return!conversational&&metadata2.id.replace(/^RULE-/,"").split("-").some(term=>term.length>3&&hasWholePhrase(normalizedQuery,term))}function assertUniqueRuleIds(rules){const pathsById=new Map;for(const rule of rules){const existing=pathsById.get(rule.metadata.id);if(existing!==void 0){throw new Error(`Duplicate Rule id ${rule.metadata.id}: ${existing}, ${rule.path}`)}pathsById.set(rule.metadata.id,rule.path)}}function assertRuleDependencies(rules){const byId2=new Map(rules.map(rule=>[rule.metadata.id,rule]));for(const rule of rules){for(const required2 of rule.metadata.requires){if(!byId2.has(required2))throw new Error(`Rule ${rule.metadata.id} requires missing Rule ${required2}`)}}const visiting=new Set;const visited=new Set;const visit=(id,trail)=>{if(visiting.has(id))throw new Error(`Rule prerequisite cycle: ${[...trail,id].join(" -> ")}`);if(visited.has(id))return;visiting.add(id);for(const required2 of byId2.get(id)?.metadata.requires??[])visit(required2,[...trail,id]);visiting.delete(id);visited.add(id)};for(const id of byId2.keys())visit(id,[])}function globMatches(glob,path){const expression=glob.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__ZAIP_GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/__ZAIP_GLOBSTAR__/g,".*");return new RegExp(`^${expression}$`).test(path)}function comparePaths2(left,right){if(left<right)return-1;if(left>right)return 1;return 0}init_src();import{createHash as createHash6}from"node:crypto";function contextRoleForAgent(agent){const value=agent.toLowerCase();if(/(?:finalizer|reviewer|verifier)/.test(value))return"reviewer";if(/(?:auditor|security)/.test(value))return"auditor";if(/(?:integrator)/.test(value))return"integrator";if(/(?:builder|backend|frontend|developer|executor)/.test(value))return"builder";return"orchestrator"}function projectConfigForContext(source,role,phase2){const value=parseYaml(source);const config2=value!==null&&typeof value==="object"?value:{};const record3=key=>{const candidate=config2[key];return candidate!==null&&typeof candidate==="object"?candidate:{}};const zaip=record3("zaip");const execution=record3("execution");const model=record3("model_orchestration");const assurance=record3("assurance");const includeStack=phase2==="planning"||phase2==="execution"||role==="builder";return{source:{path:".agents/config/project.yaml",sha256:createHash6("sha256").update(source).digest("hex"),schema_version:typeof config2.schema_version==="number"?config2.schema_version:null},projection:true,role,phase:phase2,zaip_enabled:typeof zaip.enabled==="boolean"?zaip.enabled:null,authority:{execution:Object.keys(execution).length?execution:null,model_orchestration:Object.keys(model).length?model:null},lifecycle:{assurance:Object.keys(assurance).length?assurance:null},stack:includeStack?config2.stack??null:null}}import{createHash as createHash7}from"node:crypto";var contextHandoffSchema={parse(value){assertHandoffStructure(value);return value}};function validateContextHandoff(handoff){contextHandoffSchema.parse(handoff);const findings=[];const selected=handoff.context.reduce((sum,item)=>sum+item.estimated_tokens,0);if(selected!==handoff.budget.selected_tokens||selected>handoff.budget.max_tokens){findings.push({code:"budget",message:"Selected context does not match the declared budget"})}const expectedSource=handoff.budget.observed_input_tokens!==null?"provider-uncached-input":handoff.budget.observable_context_tokens!==null?"observable-context-fallback":"unavailable";if(handoff.budget.measurement_source!==expectedSource){findings.push({code:"measurement",message:`Measurement source must be ${expectedSource}`})}for(const value of[...handoff.invariants,...handoff.decisions,...handoff.evidence,...handoff.progress.completed,...handoff.progress.pending,handoff.progress.next_action,handoff.progress.blocker??""]){if(containsSecret(value)){findings.push({code:"secret",message:"Secret-like content is forbidden in handoff"});break}}return findings}function handoffHash(handoff){return createHash7("sha256").update(stableJson3(handoff)).digest("hex")}function compactContextHandoff(input){const handoff={...input,requirements:[...new Set(input.requirements)].sort(),acceptance_criteria:[...new Set(input.acceptance_criteria)].sort(),invariants:[...new Set(input.invariants)].sort(),context:[...input.context].sort((left,right)=>left.path.localeCompare(right.path)),compaction:input.compaction};contextHandoffSchema.parse(handoff);const findings=validateContextHandoff(handoff);if(findings.length>0)throw new Error(`Invalid ContextHandoff: ${findings.map(item=>item.code).join(",")}`);return handoff}function verifyCompactionHandshake(previous,next){const findings=[...validateContextHandoff(next)];if(next.revision!==previous.revision+1||next.compaction.previous_hash!==handoffHash(previous)){findings.push({code:"compaction",message:"Compaction revision/hash handshake is invalid"})}if(stableJson3(next.anchors)!==stableJson3(previous.anchors)){findings.push({code:"anchor",message:"Compaction cannot change lifecycle anchors"})}for(const[label,required2,present]of[["requirement",previous.requirements,next.requirements],["acceptance criterion",previous.acceptance_criteria,next.acceptance_criteria],["invariant",previous.invariants,next.invariants],["evidence",previous.evidence,next.evidence]]){const omitted=required2.filter(value=>!present.includes(value));if(omitted.length>0){findings.push({code:"required-context",message:`Compaction omitted ${label}: ${omitted.join(", ")}`})}}const preserved=new Set(next.compaction.preserved_invariants);if(previous.invariants.some(invariant=>!preserved.has(invariant))){findings.push({code:"compaction",message:"Preserved invariant acknowledgement is incomplete"})}return findings}function containsSecret(value){return/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\bAKIA[0-9A-Z]{16}\b|\bgh[ps]_[A-Za-z0-9]{20,}\b|\bsk-[A-Za-z0-9_-]{8,}\b)/.test(value)}function assertHandoffStructure(value){if(!isRecord4(value)||value.schema_version!==1)throw new Error("Invalid handoff schema");if(!isString(value.handoff_id)||!/^HANDOFF-[A-Z0-9-]+$/.test(value.handoff_id)){throw new Error("Invalid handoff id")}if(!isPositiveInteger(value.revision)||!isDateTime(value.created_at)){throw new Error("Invalid handoff revision or timestamp")}if(!isRecord4(value.anchors))throw new Error("Invalid handoff anchors");for(const key of["change_id","task_id","execution_id","run_id"]){if(!isLifecycleId(value.anchors[key]))throw new Error(`Invalid anchor: ${key}`)}for(const key of["prd_id","spec_id"]){if(value.anchors[key]!==null&&!isLifecycleId(value.anchors[key])){throw new Error(`Invalid anchor: ${key}`)}}for(const[label,candidate,required2]of[["requirements",value.requirements,true],["acceptance_criteria",value.acceptance_criteria,true],["invariants",value.invariants,true],["decisions",value.decisions,false],["evidence",value.evidence,false]]){if(!isUniqueStringArray(candidate,required2))throw new Error(`Invalid ${label}`)}if(!isRecord4(value.progress)||!isUniqueStringArray(value.progress.completed,false)||!isUniqueStringArray(value.progress.pending,false)||!isString(value.progress.next_action)||value.progress.blocker!==null&&!isString(value.progress.blocker)){throw new Error("Invalid handoff progress")}if(!Array.isArray(value.context)||value.context.some(item=>!isRecord4(item)||!isString(item.path)||!isString(item.sha256)||!/^[a-f0-9]{64}$/.test(item.sha256)||!isNonNegativeInteger(item.estimated_tokens)||!isString(item.reason))){throw new Error("Invalid selected context")}if(!isRecord4(value.budget)||!isPositiveInteger(value.budget.max_tokens)||!isNonNegativeInteger(value.budget.selected_tokens)||!isNullableNonNegativeInteger(value.budget.observed_input_tokens)||!isNullableNonNegativeInteger(value.budget.observable_context_tokens)||!["provider-uncached-input","observable-context-fallback","unavailable"].includes(String(value.budget.measurement_source))){throw new Error("Invalid handoff budget")}if(!isRecord4(value.compaction)||value.compaction.previous_hash!==null&&(!isString(value.compaction.previous_hash)||!/^[a-f0-9]{64}$/.test(value.compaction.previous_hash))||!isUniqueStringArray(value.compaction.preserved_invariants,false)){throw new Error("Invalid compaction handshake")}}function isRecord4(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function isString(value){return typeof value==="string"&&value.length>0}function isDateTime(value){return isString(value)&&Number.isFinite(Date.parse(value))}function isLifecycleId(value){return isString(value)&&/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+$/.test(value)}function isPositiveInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>0}function isNonNegativeInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0}function isNullableNonNegativeInteger(value){return value===null||isNonNegativeInteger(value)}function isUniqueStringArray(value,required2){return Array.isArray(value)&&(!required2||value.length>0)&&value.every(isString)&&new Set(value).size===value.length}function stableJson3(value){return JSON.stringify(sortValue4(value))}function sortValue4(value){if(Array.isArray(value))return value.map(sortValue4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,item])=>[key,sortValue4(item)]))}return value}var IGNORED_SEGMENTS=[".git","node_modules","dist","coverage","examples","fixtures","local",".local","release","_ref",".turbo"];var TEXT_EXTENSIONS=[".ts",".tsx",".js",".jsx",".json",".yaml",".yml",".md",".css",".html",".mjs",".toml",".ps1"];var V2_CRITICAL_FILES=[".agents/config/project.yaml",".agents/rules/core.md"];var V1_CRITICAL_FILES=[".agents/manifest.yaml",".agents/constitution.md"];async function inventory(filesystem){return(await inventoryWithDiagnostics(filesystem)).entries}async function inventoryWithDiagnostics(filesystem){const snapshot=await createInventorySnapshot(filesystem);return{entries:snapshot.entries.map(toInventoryEntry),diagnostics:snapshot.diagnostics}}async function createInventorySnapshot(filesystem,query=""){const discovery=await discoverInventoryPaths(filesystem,query);return readInventoryPaths(filesystem,discovery.paths,discovery.criticalFiles)}async function discoverInventoryPaths(filesystem,query=""){const criticalFiles=await resolveCriticalFiles(filesystem);const git5=new ShellGit(filesystem.root);let gitPaths=[];if(await git5.isRepository()){const[tracked,status]=await Promise.all([git5.trackedFiles(),git5.status()]);gitPaths=[...tracked,...status.map(entry2=>entry2.path)]}const sourcePaths=gitPaths.length>0?gitPaths:await filesystem.listFiles(".");const relationPaths=await resolveRelationPaths(filesystem,query);const paths=[...new Set([...sourcePaths,...criticalFiles,...relationPaths])].filter(path=>!IGNORED_SEGMENTS.some(segment2=>path.split("/").includes(segment2))).filter(path=>relationPaths.includes(path)||!isTransientContextPath(path,query)).filter(path=>TEXT_EXTENSIONS.some(extension=>path.endsWith(extension))).sort(comparePaths3);return{paths,criticalFiles,relationPaths}}async function readInventoryPaths(filesystem,paths,criticalFiles){const scanned=await Promise.all(paths.map(async path=>{try{const content=await filesystem.readText(path);return{...inventoryEntry(path,content),content}}catch(error51){if(!isNodeError2(error51)||error51.code!=="ENOENT")throw error51;const critical=criticalFiles.includes(path);return{code:critical?"critical-missing":"missing-file",path,message:critical?"Required context invariant is missing from the working tree":"Git path is absent from the working tree and was skipped"}}}));return{entries:scanned.filter(isInventorySnapshotEntry),diagnostics:scanned.filter(isInventoryDiagnostic),criticalFiles}}async function buildRepositoryMap(filesystem){const snapshot=await createInventorySnapshot(filesystem);return snapshot.entries.map(entry2=>{const content=entry2.content;return{path:entry2.path,module:entry2.path.match(/(?:^|\/)modules\/([^/]+)/)?.[1]??null,imports:importMap(entry2.path,content),symbols:exportedSymbols(content),sddLinks:[...new Set(content.match(/\b(?:SPEC|CHG|TASK|RUN|REQ|AC|EVIDENCE|DEC-(?:HUMAN|AI))-[A-Z0-9-]+/g)??[])].sort()}})}async function buildContextPack(filesystem,query,budget=8e3,options={}){if(!Number.isSafeInteger(budget)||budget<=0){throw new ContextPackBuildError([{rule:"budget",path:"context-pack",message:"Token budget must be a positive integer"}])}const role=options.role??"orchestrator";const phase2=options.phase??inferContextPhase(query);const conversational=phase2==="conversation";const terms=tokenize(query);const discovery=await discoverInventoryPaths(filesystem,query);const candidatePaths=discovery.paths.filter(path=>discovery.criticalFiles.includes(path)||discovery.relationPaths.includes(path)||path.startsWith(".agents/rules/")||path.startsWith(".agents/requirements/")||terms.some(term=>path.toLowerCase().includes(term)));const snapshot=await readInventoryPaths(filesystem,candidatePaths,discovery.criticalFiles);const entries=snapshot.entries;const relationIds=entries.filter(entry2=>discovery.relationPaths.includes(entry2.path)).flatMap(entry2=>entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]);const relationalQuery=[query,...new Set(relationIds)].join(" ");const likelyPaths=entries.filter(entry2=>terms.some(term=>entry2.path.toLowerCase().includes(term))).map(entry2=>entry2.path);const selectedRules=selectRulePaths(entries,conversational?[]:likelyPaths,query,phase2);const selectedRequirements=selectRequirementsFromSnapshot(entries,relationalQuery,conversational);const requiredReferences=[...new Set(relationIds)].sort();const resolvedReferences=new Set(entries.filter(entry2=>selectedRequirements.includes(entry2.path)).flatMap(entry2=>entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]));const unresolvedRequiredReferences=requiredReferences.filter(reference=>!resolvedReferences.has(reference));const requiredFiles=[...new Set([...snapshot.criticalFiles,...discovery.relationPaths,...selectedRules,...selectedRequirements])].sort(comparePaths3);const ruleBudgetFindings=entries.filter(entry2=>selectedRules.includes(entry2.path)).flatMap(entry2=>{const metadata2=parseRuleMetadata(entry2.content);const tokens2=estimateTokens(entry2.content);return tokens2<=metadata2.maxContextTokens?[]:[{rule:"rule-budget",path:entry2.path,message:`Rule needs ${tokens2} tokens but declares ${metadata2.maxContextTokens}; increase its declared budget with headroom or shorten the Rule.`}]});if(ruleBudgetFindings.length>0)throw new ContextPackBuildError(ruleBudgetFindings);const eligibleEntries=entries.filter(entry2=>snapshot.criticalFiles.includes(entry2.path)||discovery.relationPaths.includes(entry2.path)||selectedRules.includes(entry2.path)||selectedRequirements.includes(entry2.path)||!conversational&&!entry2.path.startsWith(".agents/rules/")&&!entry2.path.startsWith(".agents/requirements/")&&isDomainPathAllowed(entry2.path,terms));const candidates=eligibleEntries.map(entry2=>{const content=entry2.content;const reasons=[];let score=0;if(snapshot.criticalFiles.includes(entry2.path)||selectedRules.includes(entry2.path)||selectedRequirements.includes(entry2.path)){score+=1e4;reasons.push("critical-rule")}if(discovery.relationPaths.includes(entry2.path)){score+=9e3;reasons.push("active-relation")}const profileReason=contextProfileReason(entry2.path,role,phase2);if(profileReason!==null){score+=200;reasons.push(profileReason)}const searchable=`${entry2.path}
2018
- ${content}`.toLowerCase();for(const term of terms){if(entry2.path.toLowerCase().includes(term)){score+=25;reasons.push(`path:${term}`)}const matches=searchable.split(term).length-1;if(matches>0){score+=Math.min(20,matches);reasons.push(`content:${term}`)}}const sddMatches=content.match(/\b(?:SPEC|CHG|TASK|REQ|AC|DEC-(?:HUMAN|AI))-[A-Z0-9-]+/g)??[];if(sddMatches.some(id=>query.toUpperCase().includes(id))){score+=500;reasons.push("sdd-link")}return{...entry2,content,score,estimatedTokens:estimateTokens(content),reasons}});candidates.sort((left,right)=>{const requiredDelta=Number(requiredFiles.includes(right.path))-Number(requiredFiles.includes(left.path));return requiredDelta||right.score-left.score||comparePaths3(left.path,right.path)});const items=[];const omissions=discovery.paths.filter(path=>!candidatePaths.includes(path)).map(path=>({path,reason:"not-candidate",required:requiredFiles.includes(path)}));let used=0;for(const candidate of candidates){if(candidate.score===0){omissions.push({path:candidate.path,reason:"zero-score",required:requiredFiles.includes(candidate.path)});continue}if(used+candidate.estimatedTokens>budget){omissions.push({path:candidate.path,reason:requiredFiles.includes(candidate.path)?"required-budget-exceeded":"budget-exceeded",required:requiredFiles.includes(candidate.path)});continue}assertNoSecrets(candidate.path,candidate.content);items.push(candidate);used+=candidate.estimatedTokens}const pack={query,role,phase:phase2,budget,estimatedTokens:used,discoveredFiles:discovery.paths.length,readFiles:candidatePaths.length,tokenSource:"estimated",layers:measureContextLayers(items),items,omitted:omissions.map(omission=>omission.path),omissions,criticalFiles:snapshot.criticalFiles,requiredFiles,requiredReferences,unresolvedRequiredReferences,selectedRules,selectedRequirements,diagnostics:snapshot.diagnostics};const findings=validateContextPack(pack);if((options.failClosed??true)&&findings.length>0){throw new ContextPackBuildError(findings)}return pack}function measureContextLayers(items){const totals={framework:0,product:0,lifecycle:0};for(const item of items)totals[contextLayer(item.path)]+=item.estimatedTokens;return Object.keys(totals).map(layer=>({layer,estimatedTokens:totals[layer]}))}function selectRequirementsFromSnapshot(entries,query,conversational=false){const terms=tokenize(query);const queryUpper=query.toUpperCase();if(conversational){return entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).filter(entry2=>(entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]).some(id=>queryUpper.includes(id))).map(entry2=>entry2.path).sort(comparePaths3)}const scored=entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).map(entry2=>{const path=entry2.path.toLowerCase();const header=entry2.content.split(/\r?\n/).filter(line=>/^(?:id|area|title):|^#\s/.test(line)).join("\n").toLowerCase();const searchable=entry2.content.toLowerCase();const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];const explicitMatches=ids.filter(id=>queryUpper.includes(id)).length;const pathMatches=terms.filter(term=>path.includes(term)).length;const headerMatches=terms.filter(term=>header.includes(term)).length;const contentMatches=terms.reduce((total,term)=>total+Math.min(5,searchable.split(term).length-1),0);const structuralScore=explicitMatches*1e3+pathMatches*100+headerMatches*30;return{entry:entry2,structuralScore,score:structuralScore+contentMatches}}).filter(({score})=>score>0).sort((left,right)=>right.score-left.score||comparePaths3(left.entry.path,right.entry.path));const explicit=scored.filter(({entry:entry2})=>{const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];return ids.some(id=>queryUpper.includes(id))});if(explicit.length>0)return explicit.map(({entry:entry2})=>entry2.path);const structural=scored.filter(({structuralScore})=>structuralScore>0);return(structural.length>0?structural.slice(0,3):scored.slice(0,1)).map(({entry:entry2})=>entry2.path)}function importMap(path,content){if(!/\.[cm]?[jt]sx?$/.test(path))return[];const pattern=/(?:^|\n)\s*import\s+(?:type\s+)?(?:[^"'\n]*?\s+from\s+)?["']([^"']+)["']/g;return[...content.matchAll(pattern)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function estimateTokens(content){return encode3(content,{disallowedSpecial:new Set}).length}function exportedSymbols(content){return[...content.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:class|function|interface|type|const|let|var|enum)\s+([A-Za-z_$][\w$]*)/g)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function inventoryEntry(path,content){return{path,bytes:Buffer.byteLength(content),lines:content.length===0?0:content.split("\n").length,sha256:createHash8("sha256").update(content).digest("hex")}}function toInventoryEntry(entry2){return{path:entry2.path,bytes:entry2.bytes,lines:entry2.lines,sha256:entry2.sha256}}function isInventorySnapshotEntry(value){return"content"in value}function isInventoryDiagnostic(value){return"code"in value}async function resolveCriticalFiles(filesystem){const hasV2=await filesystem.exists(V2_CRITICAL_FILES[0])||await filesystem.exists(V2_CRITICAL_FILES[1]);if(hasV2)return V2_CRITICAL_FILES;const hasV1=await filesystem.exists(V1_CRITICAL_FILES[0])||await filesystem.exists(V1_CRITICAL_FILES[1]);return hasV1?V1_CRITICAL_FILES:V2_CRITICAL_FILES}function isTransientContextPath(path,query=""){if(isExplicitProjectionRequest(path,query))return false;return path.startsWith(".local/")||path.startsWith(".agents/generated/")||path.startsWith(".agents/records/")||path.startsWith(".agents/data/")||path.startsWith(".codex/")||path.startsWith(".claude/")||path.startsWith("public-cli/")||path.startsWith("public-cli/packages/cli/templates/")||/(?:^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/.test(path)}function isExplicitProjectionRequest(path,query){const projectionRoot=[".codex/",".claude/","public-cli/"].find(root=>path.startsWith(root));if(projectionRoot===void 0)return false;const normalized=query.replace(/\\/g,"/").toLowerCase();return normalized.includes(path.toLowerCase())||normalized.includes(projectionRoot)}function contextLayer(path){if(path.startsWith(".agents/records/"))return"lifecycle";if(path.startsWith(".agents/"))return"framework";return"product"}async function resolveRelationPaths(filesystem,query){const explicitIds=new Set(query.toUpperCase().match(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+/g)??[]);if(explicitIds.size===0)return[];let layout=null;try{layout=await loadWorkspaceLayout(filesystem)}catch{layout=null}const paths=[];for(const id of explicitIds){const kind=kindFromId(id);if(kind===null)continue;if(layout?.supports(kind)){const path=await resolveArtifactReadPath(filesystem,layout,kind,id);if(path!==null){paths.push(path);continue}}const fallback=v3RelationPath(kind,id);if(fallback!==null&&await filesystem.exists(fallback)){paths.push(fallback);continue}if(explicitIds.has(id)){throw new Error(`Explicit lifecycle context path does not resolve: ${id}`)}}return paths}function v3RelationPath(kind,id){const match=id.match(/^[A-Z]+-(\d{4})-(\d{2})-/);if(match===null)return null;const[,year,month]=match;const roots2={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};const base=`.agents/records/${roots2[kind]}/${year}/${month}`;if(kind==="change")return`${base}/${id}/change.md`;if(kind==="execution")return`${base}/${id}/execution.md`;if(kind==="run")return`${base}/${id}.jsonl`;return`${base}/${id}.md`}function kindFromId(id){if(id.startsWith("PRD-"))return"prd";if(id.startsWith("SPEC-"))return"spec";if(id.startsWith("CHG-"))return"change";if(id.startsWith("TASK-"))return"task";if(id.startsWith("EXEC-"))return"execution";if(id.startsWith("RUN-"))return"run";return null}function isNodeError2(error51){return error51 instanceof Error&&"code"in error51}function comparePaths3(left,right){if(left<right)return-1;if(left>right)return 1;return 0}function tokenize(query){const stopWords=new Set(["active"]);const lexicalQuery=query.replace(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+\b/gi," ");return[...new Set(lexicalQuery.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(term=>term.length>2&&!stopWords.has(term)))]}function isDomainPathAllowed(path,terms){if(path.startsWith("analysis/")){const analysisTerms=new Set(["audit","auditoria","analise","analysis","verificacao","relatorio"]);return terms.some(term=>analysisTerms.has(term))}if(!path.startsWith(".agents/design/"))return true;const designTerms=new Set(["design","visual","interface","frontend","catalog","storybook"]);return terms.some(term=>designTerms.has(term))}init_src();init_src2();init_src3();init_src();var EVAL_VERSION="3.5.0";async function persistEvalReport(filesystem,report,shortName="offline-suite"){const id=createId("EVAL",shortName);const{year,month}=datedIdParts(id);const path=`.agents/evals/results/${year}/${month}/${id}.json`;const persisted={id,version:EVAL_VERSION,generated_at:new Date().toISOString(),report};await filesystem.writeTextAtomic(path,`${JSON.stringify(persisted,null,2)}
2049
+ ${content}`.toLowerCase();for(const term of terms){if(entry2.path.toLowerCase().includes(term)){score+=25;reasons.push(`path:${term}`)}const matches=searchable.split(term).length-1;if(matches>0){score+=Math.min(20,matches);reasons.push(`content:${term}`)}}const sddMatches=content.match(/\b(?:SPEC|CHG|TASK|REQ|AC|DEC-(?:HUMAN|AI))-[A-Z0-9-]+/g)??[];if(sddMatches.some(id=>query.toUpperCase().includes(id))){score+=500;reasons.push("sdd-link")}return{...entry2,content,score,estimatedTokens:estimateTokens(content),reasons}});candidates.sort((left,right)=>{const requiredDelta=Number(requiredFiles.includes(right.path))-Number(requiredFiles.includes(left.path));return requiredDelta||right.score-left.score||comparePaths3(left.path,right.path)});const items=[];const omissions=discovery.paths.filter(path=>!candidatePaths.includes(path)).map(path=>({path,reason:"not-candidate",required:requiredFiles.includes(path)}));let used=0;for(const candidate of candidates){if(candidate.score===0){omissions.push({path:candidate.path,reason:"zero-score",required:requiredFiles.includes(candidate.path)});continue}if(used+candidate.estimatedTokens>budget){omissions.push({path:candidate.path,reason:requiredFiles.includes(candidate.path)?"required-budget-exceeded":"budget-exceeded",required:requiredFiles.includes(candidate.path)});continue}assertNoSecrets(candidate.path,candidate.content);items.push(candidate);used+=candidate.estimatedTokens}const pack={query,role,phase:phase2,budget,estimatedTokens:used,discoveredFiles:discovery.paths.length,readFiles:candidatePaths.length,tokenSource:"estimated",layers:measureContextLayers(items),items,omitted:omissions.map(omission=>omission.path),omissions,criticalFiles:snapshot.criticalFiles,requiredFiles,requiredReferences,unresolvedRequiredReferences,selectedRules,selectedRequirements,diagnostics:snapshot.diagnostics};const findings=validateContextPack(pack);if((options.failClosed??true)&&findings.length>0){throw new ContextPackBuildError(findings)}return pack}function measureContextLayers(items){const totals={framework:0,product:0,lifecycle:0};for(const item of items)totals[contextLayer(item.path)]+=item.estimatedTokens;return Object.keys(totals).map(layer=>({layer,estimatedTokens:totals[layer]}))}function selectRequirementsFromSnapshot(entries,query,conversational=false){const terms=tokenize(query);const queryUpper=query.toUpperCase();if(conversational){return entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).filter(entry2=>(entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]).some(id=>queryUpper.includes(id))).map(entry2=>entry2.path).sort(comparePaths3)}const scored=entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).map(entry2=>{const path=entry2.path.toLowerCase();const header=entry2.content.split(/\r?\n/).filter(line=>/^(?:id|area|title):|^#\s/.test(line)).join("\n").toLowerCase();const searchable=entry2.content.toLowerCase();const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];const explicitMatches=ids.filter(id=>queryUpper.includes(id)).length;const pathMatches=terms.filter(term=>path.includes(term)).length;const headerMatches=terms.filter(term=>header.includes(term)).length;const contentMatches=terms.reduce((total,term)=>total+Math.min(5,searchable.split(term).length-1),0);const structuralScore=explicitMatches*1e3+pathMatches*100+headerMatches*30;return{entry:entry2,structuralScore,score:structuralScore+contentMatches}}).filter(({score})=>score>0).sort((left,right)=>right.score-left.score||comparePaths3(left.entry.path,right.entry.path));const explicit=scored.filter(({entry:entry2})=>{const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];return ids.some(id=>queryUpper.includes(id))});if(explicit.length>0)return explicit.map(({entry:entry2})=>entry2.path);const structural=scored.filter(({structuralScore})=>structuralScore>0);return(structural.length>0?structural.slice(0,3):scored.slice(0,1)).map(({entry:entry2})=>entry2.path)}function importMap(path,content){if(!/\.[cm]?[jt]sx?$/.test(path))return[];const pattern=/(?:^|\n)\s*import\s+(?:type\s+)?(?:[^"'\n]*?\s+from\s+)?["']([^"']+)["']/g;return[...content.matchAll(pattern)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function estimateTokens(content){return encode3(content,{disallowedSpecial:new Set}).length}function exportedSymbols(content){return[...content.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:class|function|interface|type|const|let|var|enum)\s+([A-Za-z_$][\w$]*)/g)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function inventoryEntry(path,content){return{path,bytes:Buffer.byteLength(content),lines:content.length===0?0:content.split("\n").length,sha256:createHash8("sha256").update(content).digest("hex")}}function toInventoryEntry(entry2){return{path:entry2.path,bytes:entry2.bytes,lines:entry2.lines,sha256:entry2.sha256}}function isInventorySnapshotEntry(value){return"content"in value}function isInventoryDiagnostic(value){return"code"in value}async function resolveCriticalFiles(filesystem){const hasV2=await filesystem.exists(V2_CRITICAL_FILES[0])||await filesystem.exists(V2_CRITICAL_FILES[1]);if(hasV2)return V2_CRITICAL_FILES;const hasV1=await filesystem.exists(V1_CRITICAL_FILES[0])||await filesystem.exists(V1_CRITICAL_FILES[1]);return hasV1?V1_CRITICAL_FILES:V2_CRITICAL_FILES}function isTransientContextPath(path,query=""){if(isExplicitProjectionRequest(path,query))return false;return path.startsWith(".local/")||path.startsWith(".agents/generated/")||path.startsWith(".agents/records/")||path.startsWith(".agents/data/")||path.startsWith(".codex/")||path.startsWith(".claude/")||path.startsWith("public-cli/")||path.startsWith("public-cli/packages/cli/templates/")||/(?:^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/.test(path)}function isExplicitProjectionRequest(path,query){const projectionRoot=[".codex/",".claude/","public-cli/"].find(root=>path.startsWith(root));if(projectionRoot===void 0)return false;const normalized=query.replace(/\\/g,"/").toLowerCase();return normalized.includes(path.toLowerCase())||normalized.includes(projectionRoot)}function contextLayer(path){if(path.startsWith(".agents/records/"))return"lifecycle";if(path.startsWith(".agents/"))return"framework";return"product"}async function resolveRelationPaths(filesystem,query){const explicitIds=new Set(query.toUpperCase().match(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+/g)??[]);if(explicitIds.size===0)return[];let layout=null;try{layout=await loadWorkspaceLayout(filesystem)}catch{layout=null}const paths=[];for(const id of explicitIds){const kind=kindFromId(id);if(kind===null)continue;if(layout?.supports(kind)){const path=await resolveArtifactReadPath(filesystem,layout,kind,id);if(path!==null){paths.push(path);continue}}const fallback=v3RelationPath(kind,id);if(fallback!==null&&await filesystem.exists(fallback)){paths.push(fallback);continue}if(explicitIds.has(id)){throw new Error(`Explicit lifecycle context path does not resolve: ${id}`)}}return paths}function v3RelationPath(kind,id){const match=id.match(/^[A-Z]+-(\d{4})-(\d{2})-/);if(match===null)return null;const[,year,month]=match;const roots2={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};const base=`.agents/records/${roots2[kind]}/${year}/${month}`;if(kind==="change")return`${base}/${id}/change.md`;if(kind==="execution")return`${base}/${id}/execution.md`;if(kind==="run")return`${base}/${id}.jsonl`;return`${base}/${id}.md`}function kindFromId(id){if(id.startsWith("PRD-"))return"prd";if(id.startsWith("SPEC-"))return"spec";if(id.startsWith("CHG-"))return"change";if(id.startsWith("TASK-"))return"task";if(id.startsWith("EXEC-"))return"execution";if(id.startsWith("RUN-"))return"run";return null}function isNodeError2(error51){return error51 instanceof Error&&"code"in error51}function comparePaths3(left,right){if(left<right)return-1;if(left>right)return 1;return 0}function tokenize(query){const stopWords=new Set(["active"]);const lexicalQuery=query.replace(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+\b/gi," ");return[...new Set(lexicalQuery.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(term=>term.length>2&&!stopWords.has(term)))]}function isDomainPathAllowed(path,terms){if(path.startsWith("analysis/")){const analysisTerms=new Set(["audit","auditoria","analise","analysis","verificacao","relatorio"]);return terms.some(term=>analysisTerms.has(term))}if(!path.startsWith(".agents/design/"))return true;const designTerms=new Set(["design","visual","interface","frontend","catalog","storybook"]);return terms.some(term=>designTerms.has(term))}init_src();init_src2();init_src3();init_src();var EVAL_VERSION="3.6.0";async function persistEvalReport(filesystem,report,shortName="offline-suite"){const id=createId("EVAL",shortName);const{year,month}=datedIdParts(id);const path=`.agents/evals/results/${year}/${month}/${id}.json`;const persisted={id,version:EVAL_VERSION,generated_at:new Date().toISOString(),report};await filesystem.writeTextAtomic(path,`${JSON.stringify(persisted,null,2)}
2019
2050
  `);return{id,path}}function runEvalSuite(cases,profile){const results=cases.map(testCase=>{const startedAt=performance.now();const findings=testCase.validator==="cqrs"?validateCqrs(testCase.units,profile):validateArchitecture(testCase.units,profile);const actualRules=[...new Set(findings.map(item=>item.rule))].sort();const expectedRules=[...testCase.expectedRules].sort();return{id:testCase.id,passed:JSON.stringify(actualRules)===JSON.stringify(expectedRules),expectedRules,actualRules,durationMs:Math.max(0,performance.now()-startedAt)}});return{passed:results.every(result2=>result2.passed),offline:true,cases:results}}function guardDiff(changedFiles,ledgerFiles){const canonicalChanges=changedFiles.filter(path=>!path.startsWith(".agents/"));return canonicalChanges.filter(path=>!ledgerFiles.includes(path)).map(path=>({rule:"untracked-diff",message:`${path} is not present in the active task ledger`}))}var BUILTIN_EVAL_CASES=[{id:"domain-rejects-framework",units:[{path:"src/modules/a/domain/entity.ts",content:'import { Hono } from "hono";'}],expectedRules:["domain-framework-dependency"]},{id:"query-rejects-write",units:[{path:"src/modules/a/application/queries/get.query.ts",content:"export const get = (port: WritePort) => port.save({});"}],expectedRules:["query-side-effect","query-write-port"],validator:"cqrs"},{id:"pure-query-passes",units:[{path:"src/modules/a/application/queries/get.query.ts",content:"export const get = (port: ReadPort) => port.find();"}],expectedRules:[],validator:"cqrs"}];function scanInfrastructureSecurity(path,content){const findings=[];if(/\.ya?ml$/.test(path)&&/(?:privileged:\s*true|network_mode:\s*["']?host)/i.test(content)){findings.push({rule:"docker-unsafe-isolation",path})}if(/\.tf$/.test(path)&&/(?:cidr_blocks|source_ranges)\s*=\s*\[[^\]]*["']0\.0\.0\.0\/0/i.test(content)){findings.push({rule:"terraform-public-ingress",path})}if(/\.sql$/.test(path)&&/GRANT\s+ALL(?:\s+PRIVILEGES)?[\s\S]*\sTO\s+(?:PUBLIC|\w+)/i.test(content)){findings.push({rule:"sql-overprivileged-grant",path})}return findings}function runCategoryEval(category){if(category==="architecture"){return runEvalSuite(BUILTIN_EVAL_CASES.filter(item=>item.id.includes("domain")))}if(category==="cqrs"){return runEvalSuite(BUILTIN_EVAL_CASES.filter(item=>!item.id.includes("domain")))}const startedAt=performance.now();let passed=false;let actualRules=[];let expectedRules=[];if(category==="specs"){expectedRules=["untracked-diff"];actualRules=guardDiff(["src/new.ts"],[]).map(item=>item.rule);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="security"){expectedRules=["generic-secret"];actualRules=scanSecrets("fixture.ts",'const token = "definitely-not-a-real-secret"').map(item=>item.kind);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="infrastructure"){expectedRules=["docker-unsafe-isolation","terraform-public-ingress","sql-overprivileged-grant"];actualRules=[...scanInfrastructureSecurity("compose.yaml","services:\n app:\n privileged: true"),...scanInfrastructureSecurity("main.tf",'ingress { cidr_blocks = ["0.0.0.0/0"] }'),...scanInfrastructureSecurity("grant.sql","GRANT ALL PRIVILEGES ON app TO PUBLIC;")].map(item=>item.rule);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="adapters"){const files=adapterFiles(process.cwd());actualRules=files.map(file2=>file2.path);expectedRules=[...actualRules];passed=files.length>0&&new Set(files.map(file2=>file2.path)).size===files.length&&files.every(file2=>file2.content.includes("zaip-managed"))}else if(category==="context"){actualRules=[String(estimateTokens("12345678"))];expectedRules=[...actualRules];passed=Number(actualRules[0])>0}return{passed,offline:true,cases:[{id:`${category}-builtin`,passed,expectedRules,actualRules,durationMs:performance.now()-startedAt}]}}function runAllCategoryEvals(){const categories=["specs","architecture","cqrs","security","infrastructure","adapters","context"];const reports=categories.map(runCategoryEval);return{passed:reports.every(report=>report.passed),offline:true,cases:reports.flatMap(report=>report.cases)}}init_src4();init_src5();init_src();function output(value,json2,error51=false){const text=json2||typeof value!=="string"?`${JSON.stringify(value,null,2)}
2020
2051
  `:`${value}
2021
2052
  `;(error51?process.stderr:process.stdout).write(text)}var ACTIVATION_COMMANDS=new Set(["enable","disable","status"]);var DISABLED_MAINTENANCE_COMMANDS=new Set(["setup","upgrade","doctor","adapters","architecture","cqrs","modules","profile","migrate","version"]);function isActivationCommand(area){return ACTIVATION_COMMANDS.has(area)}async function runActivationCommand(area,filesystem,json2){if(!await filesystem.exists(PROJECT_CONFIG_PATH)){const result2={installed:false,enabled:null,config_path:PROJECT_CONFIG_PATH,message:"ZAIP-AIOS project configuration was not found."};output(result2,json2,area!=="status");return area==="status"?0:6}const repository2=new ProjectConfigRepository(filesystem);const config2=await repository2.read();if(area==="status"){output({installed:true,enabled:isZaipEnabled(config2),configured:config2.zaip?.enabled??null,config_path:PROJECT_CONFIG_PATH},json2);return 0}const enabled=area==="enable";await repository2.write({...config2,zaip:{enabled}});output({installed:true,enabled,config_path:PROJECT_CONFIG_PATH,message:enabled?"ZAIP-AIOS enabled.":"ZAIP-AIOS disabled."},json2);return 0}async function isZaipCliDisabled(filesystem){if(!await filesystem.exists(PROJECT_CONFIG_PATH))return false;return!isZaipEnabled(await new ProjectConfigRepository(filesystem).read())}function isDisabledMaintenanceCommand(area){return DISABLED_MAINTENANCE_COMMANDS.has(area)}async function handleZaipActivation(area,filesystem,json2){if(isActivationCommand(area))return runActivationCommand(area,filesystem,json2);if(isDisabledMaintenanceCommand(area)||!await isZaipCliDisabled(filesystem))return null;output({enabled:false,error:"ZAIP-AIOS is disabled for this project. Run `zaip enable` to reactivate it."},json2,true);return 6}init_cli_arguments();async function sourceUnits(filesystem){const frameworkSource=await filesystem.exists("package.json")&&JSON.parse(await filesystem.readText("package.json")).name==="@zaip-ai/aios";const entries=(await inventory(filesystem)).filter(({path})=>frameworkSource||!/^\.agents\/(?:dashboard|design)\//.test(path));const aliasesForSource2=workspaceImportAliases(await Promise.all(entries.filter(({path})=>/(?:^|\/)(?:package|tsconfig(?:\.[^/]+)?)\.json$/.test(path)&&!isGeneratedSourcePath(path)).map(async({path})=>({path,content:await filesystem.readText(path)}))));const files=entries.filter(entry2=>/\.[cm]?[jt]sx?$/.test(entry2.path));const productionFiles=files.filter(entry2=>!/(?:^|\/)(?:tests?|__tests__)(?:\/|$)|\.(?:test|spec)(?:-support)?\.[cm]?[jt]sx?$/.test(entry2.path)&&!/(?:^|\/)scripts\/test-[^/]+\.[cm]?[jt]s$/.test(entry2.path)&&!isGeneratedSourcePath(entry2.path));return Promise.all(productionFiles.map(async({path})=>{const aliases=aliasesForSource2(path);return{path,content:await filesystem.readText(path),...aliases.length>0?{importAliases:aliases}:{}}}))}function configuredArchitectureProfile(projectConfig2){const architecture=projectConfig2?.stack.overrides.architecture;const aliases=isRecord5(architecture)?architecture.import_aliases:void 0;if(aliases!==void 0&&!Array.isArray(aliases))throw new Error("Invalid architecture import_aliases: expected an array");const configured=(aliases??[]).map((value,index)=>parseImportAlias(value,index));for(const[index,{prefix}]of configured.entries()){if(configured.some((alias,other)=>other!==index&&alias.prefix.startsWith(prefix))){throw new Error(`Invalid architecture import_aliases: ambiguous prefix ${prefix}`)}}if(projectConfig2?.stack.id!==SUPABASE_EDGE_PROFILE.id)return{...TYPESCRIPT_PROFILE,importAliases:configured};const resolution=resolveSupabaseProfile({id:SUPABASE_EDGE_PROFILE.id,...isRecord5(architecture)&&architecture.deno_json!==void 0?{deno_json:architecture.deno_json}:isRecord5(architecture)&&architecture.deno_import_map!==void 0?{deno_import_map:architecture.deno_import_map}:{}});if(!resolution.profile.supported){throw new Error(`Invalid Supabase architecture profile: ${resolution.diagnostics.join("; ")}`)}return{...resolution.profile,importAliases:configured}}function parseImportAlias(value,index){if(!isRecord5(value)||typeof value.prefix!=="string"||typeof value.target!=="string"){throw new Error(`Invalid architecture import_aliases[${index}]: expected prefix and target strings`)}if(value.prefix.length===0||value.target.length===0){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must not be empty`)}if(!value.prefix.endsWith("/")||!value.target.endsWith("/")){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must end with /`)}if(/\s/.test(value.prefix)||/\s/.test(value.target)){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must not contain whitespace`)}if(value.target.startsWith("/")||value.target.startsWith("\\")||/^[A-Za-z]:/.test(value.target)||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value.target)||value.target.split(/[\\/]/).includes("..")){throw new Error(`Invalid architecture import_aliases[${index}]: target must be a workspace-relative path`)}return{prefix:value.prefix,target:value.target}}function isGeneratedSourcePath(path){return/(?:^|\/)dist\//.test(path)||path.startsWith(".agents/runtime/bin/")||path.startsWith("public-cli/")||path===".agents/dashboard/packages/local-runtime/server.mjs"}function isRecord5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function generateBoard(tasks){const states=["planned","executing","verifying","blocked","completed"];return`# Task board
@@ -2076,7 +2107,7 @@ V1 state converted to V2 with source fingerprint \`${fingerprint.sha256}\`.`})),
2076
2107
  `));let archivedCapabilities=0;let promotedSpecs=0;for(const capability of capabilities){const legacyId=requiredString2(capability.metadata.id,`${capability.path}:id`);const promotion=promotions.find(candidate=>candidate.legacy_spec_id===legacyId);if(promotion===void 0){archivedCapabilities+=1;const relative14=capability.path.replace(/^\.agents\/specs\/capabilities\//,"");operations.push(bytesOperation("archive","capability",capability.path,capability.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/capabilities/${relative14}`,capability.bytes));findings.push({severity:"info",code:"capability-archived-not-promoted",path:capability.path,message:`${legacyId} remains legacy evidence; no DeliverySpec was created.`});continue}promotedSpecs+=1;const promotedRequirementIds=requirementIdsFromCapability(capability.body);const promotedStatus=deliverySpecStatus(capability.metadata.status);const promoted={schema_version:2,id:promotion.delivery_spec_id,prd_id:null,revision:1,title:stringOr(capability.metadata.title,legacyId),status:promotedStatus,objective:bodySection(capability.body,"Purpose")||bodySection(capability.body,"Prop\xF3sito")||stringOr(capability.metadata.title,legacyId),included_scope:[],excluded_scope:[],requirement_ids:promotedRequirementIds,acceptance_ids:promotedRequirementIds.map(id=>`AC-${id.replace(/^REQ-/,"")}`),prepared_plan:null,created_at:migrationTimestamp,updated_at:migrationTimestamp};operations.push(textOperation("convert","spec",capability.path,capability.sha256,v2EntityPath2("specs",promotion.delivery_spec_id,`${promotion.delivery_spec_id}.md`),serializeMarkdown({metadata:promoted,body:`${provenanceBody(capability.body,capability.path,capability.sha256)}
2077
2108
  - Promotion authorized by: \`${promotion.authorized_by}\``})))}const project=asRecord2(manifest.project,"manifest.project");const profile=asRecord2(manifest.profile,"manifest.profile");const agents=Array.isArray(manifest.agents)?manifest.agents:[];const managedEmptyPaths=[".agents/requirements/.gitkeep",".agents/skills/.gitkeep",".agents/data/prds/.gitkeep",".agents/data/specs/.gitkeep",".agents/data/changes/.gitkeep",".agents/data/tasks/.gitkeep",".agents/data/executions/.gitkeep",".agents/data/runs/.gitkeep"];const legacyManagedPaths=await readLegacyManagedPaths(filesystem);const v2RuleIds=new Set(DEFAULT_V2_MANAGED_FILES.filter(file2=>file2.path.startsWith(".agents/rules/")).map(file2=>parseRuleDocument(file2.content).metadata.id));for(const source of fingerprint.files.filter(file2=>/^\.agents\/rules\/[^/]+\.md$/.test(file2.path))){if(legacyManagedPaths.has(source.path))continue;const content=await filesystem.readText(source.path);const rule=parseRuleDocument(content);if(v2RuleIds.has(rule.metadata.id)){throw new Error(`Project Rule id collides with a ZAIP Rule during migration: ${rule.metadata.id}`)}v2RuleIds.add(rule.metadata.id)}const existingManagedFiles=await readManagedFiles(filesystem);const managedFiles={...Object.fromEntries(Object.entries(existingManagedFiles).filter(([path])=>!path.startsWith(".agents/rules/"))),...Object.fromEntries(managedEmptyPaths.map(path=>[path,sha2562("")]))};for(const file2 of DEFAULT_V2_MANAGED_FILES){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);try{if(file2.path.startsWith(".agents/rules/"))parseRuleDocument(current);else parseRequirementDocument(current);continue}catch{const source=fingerprint.files.find(candidate=>candidate.path===file2.path);if(source===void 0)throw new Error(`Governance source missing: ${file2.path}`);managedFiles[file2.path]=sha2562(file2.content);operations.push(textOperation("convert","config",file2.path,source.sha256,file2.path,file2.content));continue}}managedFiles[file2.path]=sha2562(file2.content);operations.push(textOperation("convert","config",null,null,file2.path,file2.content))}for(const path of managedEmptyPaths){operations.push(textOperation("convert","config",null,null,path,""))}const cleanupPaths=fingerprint.files.map(file2=>file2.path).filter(path=>!path.startsWith(".agents/rules/")&&!path.startsWith(".agents/rules/project/")&&!path.startsWith(".agents/requirements/")&&!path.startsWith(".agents/skills/")).sort();const cleanupRoots=[".agents/specs",".agents/changes",".agents/tasks",".agents/decisions",".agents/runs",".agents/telemetry",".agents/evidence",".agents/generated",".agents/context",".agents/managed",".agents/project",".agents/evals",".agents/profiles",".agents/files"];const handledPaths=new Set(operations.filter(operation=>operation.source_path!==null).map(operation=>operation.source_path));for(const path of consumedTelemetryPaths)handledPaths.add(path);for(const path of cleanupPaths){if(handledPaths.has(path)||path.startsWith(".agents/generated/")||path.startsWith(".agents/context/")){continue}const source=fingerprint.files.find(file2=>file2.path===path);if(source===void 0)throw new Error(`Source disappeared while planning: ${path}`);const bytes=await readFile4(filesystem.resolve(path));operations.push(bytesOperation("archive","legacy",path,source.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/${sha2562(path).slice(0,24)}.archive`,bytes))}operations.push(textOperation("activate-config","config",".agents/manifest.yaml",manifestFile.sha256,".agents/config/project.yaml",serializeYaml({schema_version:1,zaip:{enabled:true},project:{id:requiredString2(project.id,"manifest.project.id"),name:requiredString2(project.name,"manifest.project.name"),timezone:stringOr(project.timezone,"America/Sao_Paulo")},stack:{id:stringOr(profile.id,"zaip-aios-stack"),overrides:{}},clients:{codex:agents.includes("codex"),claude:agents.includes("claude")},tracking:{enabled:true,currency:"BRL",storage_mode:"tracked_sanitized"}})),textOperation("activate-config","config",".agents/managed/files.json",fingerprint.files.find(file2=>file2.path===".agents/managed/files.json")?.sha256??null,".agents/config/framework.lock.yaml",serializeYaml({lock_version:2,framework:{version:stringOr(asRecord2(manifest.framework,"manifest.framework").version,"0.1.0"),distribution_sha256:null},layout:{version:2},resolved_profile:{id:stringOr(profile.id,"zaip-aios-stack"),sha256:null},managed_files:managedFiles})));const orderedOperations=operations.sort(operationOrder);const duplicateTarget=firstDuplicate(orderedOperations.map(operation=>operation.target_path));if(duplicateTarget!==null){throw new Error(`Migration plan contains duplicate target: ${duplicateTarget}`)}const withoutHash={schema_version:1,migration_id:migrationId,from_layout:1,to_layout:2,source_fingerprint:fingerprint,promotions,operations:orderedOperations,cleanup_paths:cleanupPaths,cleanup_roots:cleanupRoots,counts:{source_files:fingerprint.files.length,operations:orderedOperations.length,converted_changes:convertedChangeCount,converted_tasks:convertedTaskIds.size,converted_decisions:convertedDecisions,relocated_evidence:relocatedEvidence,converted_runs:convertedRuns,usage_records:usageRecords,archived_capabilities:archivedCapabilities,promoted_specs:promotedSpecs},findings};return{...withoutHash,plan_sha256:hashCanonical(withoutHash)}}import{createHash as createHash28}from"node:crypto";import{mkdir as mkdir2,readFile as readFile5,rename as rename2,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname4}from"node:path";var MigrationPlanHashError=class extends Error{name="MigrationPlanHashError"};var MigrationSourceDivergenceError=class extends Error{name="MigrationSourceDivergenceError"};var MigrationCollisionError=class extends Error{name="MigrationCollisionError"};async function applyV1ToV2Migration(filesystem,plan,expectedHash){assertPlanHash(plan,expectedHash);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath=`${stateRoot}/journal.json`;const inspected=await inspectTargets(filesystem,plan.operations);const journal=await readJournal(filesystem,journalPath);if(inspected.missing.length===0&&journal?.state==="completed"&&!await anyPathExists(filesystem,[...plan.cleanup_paths,...plan.cleanup_roots])){await persistMigrationPlan(filesystem,stateRoot,plan);return{migration_id:plan.migration_id,status:"noop",created:[],reused:inspected.identical,journal_path:journalPath}}if(journal?.state==="cleanup"||journal?.state==="completed"){await assertBackups(filesystem,stateRoot,plan.source_fingerprint);if(inspected.missing.length>0){throw new MigrationCollisionError(`Migration ${plan.migration_id} reached cleanup with missing V2 targets`)}for(const path of plan.cleanup_paths){await rm2(filesystem.resolve(path),{force:true})}for(const path of plan.cleanup_roots){await rm2(filesystem.resolve(path),{recursive:true,force:true})}await writeJournal(filesystem,journalPath,plan,"completed",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"applied",created:[],reused:inspected.identical,journal_path:journalPath}}else{await assertSourceFingerprint(filesystem,plan.source_fingerprint)}const ownedCreated=journal===null?inspected.missing:[...journal.created];const ownedReused=journal===null?inspected.identical:[...journal.reused];await persistMigrationPlan(filesystem,stateRoot,plan);await writeJournal(filesystem,journalPath,plan,"backing_up",ownedCreated,ownedReused);for(const source of plan.source_fingerprint.files){const sourceBytes=await readFile5(filesystem.resolve(source.path));const backupPath=`${stateRoot}/backup/${source.path}`;if(await filesystem.exists(backupPath)){const backupBytes=await readFile5(filesystem.resolve(backupPath));if(sha2565(backupBytes)!==source.sha256){throw new MigrationCollisionError(`Divergent migration backup: ${backupPath}`)}}else{await writeBytesAtomic(filesystem,backupPath,sourceBytes)}}await writeJournal(filesystem,journalPath,plan,"staging",ownedCreated,ownedReused);for(const operation of plan.operations){const stagePath=`${stateRoot}/staging/${operation.target_path}`;const bytes=Buffer.from(operation.content_base64,"base64");if(sha2565(bytes)!==operation.target_sha256){throw new MigrationPlanHashError(`Operation content hash does not match: ${operation.target_path}`)}if(await filesystem.exists(stagePath)){const staged=await readFile5(filesystem.resolve(stagePath));if(sha2565(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}}else{await writeBytesAtomic(filesystem,stagePath,bytes)}}await writeJournal(filesystem,journalPath,plan,"staged",ownedCreated,ownedReused);const created=[];const reused=new Set(inspected.identical);const ordinary=plan.operations.filter(operation=>operation.kind!=="activate-config");for(const operation of ordinary){const result2=await commitOperation(filesystem,stateRoot,operation);if(result2==="created")created.push(operation.target_path);else reused.add(operation.target_path)}await writeJournal(filesystem,journalPath,plan,"commit_started",ownedCreated,ownedReused);const configs=plan.operations.filter(operation=>operation.kind==="activate-config").sort((left,right)=>configOrder2(left.target_path)-configOrder2(right.target_path));if(configs.map(operation=>operation.target_path).join("|")!==".agents/config/project.yaml|.agents/config/framework.lock.yaml"){throw new MigrationPlanHashError("Migration activation must contain exactly both V2 config files")}for(const operation of configs){const result2=await commitOperation(filesystem,stateRoot,operation);if(result2==="created")created.push(operation.target_path);else reused.add(operation.target_path)}await writeJournal(filesystem,journalPath,plan,"cleanup",ownedCreated,ownedReused);for(const path of plan.cleanup_paths){await rm2(filesystem.resolve(path),{force:true})}for(const path of plan.cleanup_roots){await rm2(filesystem.resolve(path),{recursive:true,force:true})}await writeJournal(filesystem,journalPath,plan,"completed",ownedCreated,ownedReused);return{migration_id:plan.migration_id,status:created.length===0?"noop":"applied",created:created.sort(),reused:[...reused].sort(),journal_path:journalPath}}async function readPersistedMigrationPlan(filesystem,migrationId){if(!/^MIG-[A-Z0-9]+$/.test(migrationId))throw new Error(`Invalid migration id: ${migrationId}`);const path=`.local/migrations/${migrationId}/plan.json`;if(!await filesystem.exists(path))return null;const parsed=JSON.parse(await filesystem.readText(path));if(parsed.migration_id!==migrationId){throw new MigrationPlanHashError(`Persisted migration id does not match ${migrationId}`)}assertPlanHash(parsed,parsed.plan_sha256);return parsed}async function inspectV1ToV2Migration(filesystem,plan){assertPlanHash(plan,plan.plan_sha256);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath=`${stateRoot}/journal.json`;const[journal,targets]=await Promise.all([readJournal(filesystem,journalPath),inspectTargets(filesystem,plan.operations,true)]);let presentBackups=0;for(const source of plan.source_fingerprint.files){if(await filesystem.exists(`${stateRoot}/backup/${source.path}`))presentBackups+=1}let cleanupRemaining=0;for(const path of[...plan.cleanup_paths,...plan.cleanup_roots]){if(await filesystem.exists(path))cleanupRemaining+=1}return{migration_id:plan.migration_id,state:journal?.state??"not_started",journal_path:journalPath,targets:{identical:targets.identical.length,missing:targets.missing.length},backups:{present:presentBackups,expected:plan.source_fingerprint.files.length},cleanup_remaining:cleanupRemaining}}async function rollbackV1ToV2Migration(filesystem,plan,expectedHash=plan.plan_sha256){assertPlanHash(plan,expectedHash);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath=`${stateRoot}/journal.json`;const journal=await readJournal(filesystem,journalPath);if(journal===null)throw new Error(`Migration journal not found: ${journalPath}`);const targetInspection=await inspectTargets(filesystem,plan.operations,true);const backups=new Map;for(const source of plan.source_fingerprint.files){const backupPath=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(backupPath))throw new Error(`Migration backup is missing: ${backupPath}`);const backup=await readFile5(filesystem.resolve(backupPath));if(sha2565(backup)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${backupPath}`)}if(plan.cleanup_paths.includes(source.path)&&await filesystem.exists(source.path)){const current=await readFile5(filesystem.resolve(source.path));if(sha2565(current)!==source.sha256){throw new MigrationSourceDivergenceError(`V1 source changed after migration: ${source.path}`)}}backups.set(source.path,backup)}if(targetInspection.identical.length===0&&journal.state==="rolled_back"){return{migration_id:plan.migration_id,status:"noop",removed:[],restored:[],journal_path:journalPath}}await writeJournal(filesystem,journalPath,plan,"rolling_back",journal.created,journal.reused);const removed=[];const createdTargets=new Set(journal.created);for(const operation of[...plan.operations].sort((left,right)=>{const leftConfig=left.kind==="activate-config"?0:1;const rightConfig=right.kind==="activate-config"?0:1;return leftConfig-rightConfig||right.target_path.localeCompare(left.target_path)})){if(createdTargets.has(operation.target_path)&&await filesystem.exists(operation.target_path)){await rm2(filesystem.resolve(operation.target_path),{force:true});removed.push(operation.target_path)}}const restored=[];for(const[path,backup]of backups){if(plan.cleanup_paths.includes(path)&&!await filesystem.exists(path)){await writeBytesAtomic(filesystem,path,backup);restored.push(path)}}await writeJournal(filesystem,journalPath,plan,"rolled_back",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"rolled-back",removed:removed.sort(),restored:restored.sort(),journal_path:journalPath}}async function fingerprintV1Source2(filesystem){const paths=(await filesystem.listFiles(".agents")).filter(path=>!path.startsWith(".agents/config/")&&!path.startsWith(".agents/data/")).sort();const files=[];for(const path of paths){const bytes=await readFile5(filesystem.resolve(path));files.push({path,sha256:sha2565(bytes),size:bytes.byteLength})}return{sha256:hashCanonical3(files),files}}async function assertSourceFingerprint(filesystem,expected){const actual=await fingerprintV1Source2(filesystem);if(actual.sha256!==expected.sha256||JSON.stringify(actual.files)!==JSON.stringify(expected.files)){throw new MigrationSourceDivergenceError(`V1 source fingerprint changed: expected ${expected.sha256}, received ${actual.sha256}`)}}async function persistMigrationPlan(filesystem,stateRoot,plan){const path=`${stateRoot}/plan.json`;const existing=await readPersistedMigrationPlan(filesystem,plan.migration_id);if(existing!==null){if(existing.plan_sha256!==plan.plan_sha256||JSON.stringify(canonicalize4(existing))!==JSON.stringify(canonicalize4(plan))){throw new MigrationPlanHashError(`Persisted migration plan diverges: ${path}`)}return}await writeBytesAtomic(filesystem,path,Buffer.from(`${JSON.stringify(plan,null,2)}
2078
2109
  `,"utf8"))}function assertPlanHash(plan,expectedHash){const{plan_sha256:actualHash,...withoutHash}=plan;const calculated=hashCanonical3(withoutHash);if(actualHash!==calculated||actualHash!==expectedHash){throw new MigrationPlanHashError(`Migration plan hash mismatch: expected ${expectedHash}, calculated ${calculated}`)}}async function inspectTargets(filesystem,operations,allowMissing=false){const identical=[];const missing=[];for(const operation of operations){if(!await filesystem.exists(operation.target_path)){missing.push(operation.target_path);continue}const target=await readFile5(filesystem.resolve(operation.target_path));const targetHash=sha2565(target);if(targetHash!==operation.target_sha256&&operation.source_path===operation.target_path&&targetHash===operation.source_sha256){missing.push(operation.target_path);continue}if(targetHash!==operation.target_sha256){throw new MigrationCollisionError(`Divergent migration target: ${operation.target_path}`)}identical.push(operation.target_path)}if(!allowMissing&&identical.length+missing.length!==operations.length){throw new MigrationCollisionError("Unable to inspect every migration target")}return{identical:identical.sort(),missing:missing.sort()}}async function commitOperation(filesystem,stateRoot,operation){const stagePath=`${stateRoot}/staging/${operation.target_path}`;if(await filesystem.exists(operation.target_path)){const existing=await readFile5(filesystem.resolve(operation.target_path));const existingHash=sha2565(existing);if(existingHash===operation.target_sha256){await rm2(filesystem.resolve(stagePath),{force:true});return"reused"}if(operation.source_path===operation.target_path&&existingHash===operation.source_sha256){const staged2=await readFile5(filesystem.resolve(stagePath));if(sha2565(staged2)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}await rm2(filesystem.resolve(operation.target_path),{force:true});await rename2(filesystem.resolve(stagePath),filesystem.resolve(operation.target_path));return"created"}if(existingHash!==operation.target_sha256){throw new MigrationCollisionError(`Divergent migration target: ${operation.target_path}`)}}const staged=await readFile5(filesystem.resolve(stagePath));if(sha2565(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}const target=filesystem.resolve(operation.target_path);await mkdir2(dirname4(target),{recursive:true});if(await filesystem.exists(operation.target_path)){throw new MigrationCollisionError(`Migration target appeared during commit: ${operation.target_path}`)}await rename2(filesystem.resolve(stagePath),target);return"created"}async function readJournal(filesystem,path){if(!await filesystem.exists(path))return null;const parsed=JSON.parse(await filesystem.readText(path));return{...parsed,created:parsed.created??[],reused:parsed.reused??[]}}async function writeJournal(filesystem,path,plan,state,created=[],reused=[]){const journal={schema_version:1,migration_id:plan.migration_id,plan_sha256:plan.plan_sha256,source_sha256:plan.source_fingerprint.sha256,state,created:[...created].sort(),reused:[...reused].sort()};await writeBytesAtomic(filesystem,path,Buffer.from(`${JSON.stringify(journal,null,2)}
2079
- `,"utf8"))}async function assertBackups(filesystem,stateRoot,fingerprint){for(const source of fingerprint.files){const path=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(path)){throw new MigrationSourceDivergenceError(`Migration backup is missing: ${path}`)}const bytes=await readFile5(filesystem.resolve(path));if(sha2565(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths){for(const path of paths)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname4(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2565(bytes).slice(0,12)}.tmp`;await rm2(temporary,{force:true});await writeFile2(temporary,bytes,{flag:"wx"});if(await filesystem.exists(path))await rm2(target,{force:true});await rename2(temporary,target)}function configOrder2(path){if(path===".agents/config/project.yaml")return 0;if(path===".agents/config/framework.lock.yaml")return 1;return 2}function sha2565(value){return createHash28("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2565(JSON.stringify(canonicalize4(value)))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,nested])=>[key,canonicalize4(nested)]))}return value}var DISTRIBUTION_VERSION="3.5.0";async function verifyDistribution(filesystem){const checksumPath="checksums.sha256";if(!await filesystem.exists(checksumPath)){return{valid:false,invalid:[checksumPath]}}const lines=(await filesystem.readText(checksumPath)).split(/\r?\n/).filter(Boolean);const invalid=[];for(const line of lines){const match=line.match(/^([a-f0-9]{64}) {2}(.+)$/);if(!match?.[1]||!match[2]||!await filesystem.exists(match[2])){invalid.push(match?.[2]??line);continue}const actual=createHash29("sha256").update(await filesystem.readBytes(match[2])).digest("hex");if(actual!==match[1])invalid.push(match[2])}return{valid:invalid.length===0,invalid}}async function migrateProject(filesystem,dryRun=false){const path=".agents/manifest.yaml";const raw=parseYaml(await filesystem.readText(path));if(typeof raw==="object"&&raw!==null&&"schema_version"in raw){await new ManifestRepository(filesystem).read();return{from:1,to:1,changed:[],dryRun}}if(typeof raw!=="object"||raw===null||!("version"in raw)||!("project"in raw)){throw new Error("Unsupported legacy manifest; automatic migration is unsafe")}const legacy2=raw;if(legacy2.version!==1||typeof legacy2.project.name!=="string"){throw new Error("Unsupported legacy manifest version")}const migrated={schema_version:1,project:{id:typeof legacy2.project.id==="string"?legacy2.project.id:normalizeShortName(legacy2.project.name).toLowerCase(),name:legacy2.project.name,timezone:"America/Sao_Paulo"},framework:{version:DISTRIBUTION_VERSION},layout:{version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"},profile:{id:"zaip-aios-stack"},agents:["codex","claude"],paths:{specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}};if(!dryRun)await filesystem.writeTextAtomic(path,serializeYaml(migrated));return{from:0,to:1,changed:[path],dryRun}}async function upgradeDistribution(workspaceRoot,sourcePath,dryRun=false){const root=resolve5(workspaceRoot);const source=resolve5(root,sourcePath);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");const fromRoot=relative5(root,source);if(fromRoot===".."||fromRoot.startsWith("../")||fromRoot.startsWith("..\\")||isAbsolute5(fromRoot)){throw new Error("Upgrade source escapes workspace")}if(source===target||source.startsWith(`${target}\\`)||source.startsWith(`${target}/`)){throw new Error("Upgrade source must not be inside the active distribution")}const verification=await verifyDistribution(new WorkspaceFileSystem(source));if(!verification.valid){throw new Error(`Upgrade source checksum failed: ${verification.invalid.join(", ")}`)}if(dryRun)return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:true};await mkdir3(resolve5(root,".local/rollback"),{recursive:true});await rm3(backup,{recursive:true,force:true});const hadTarget=await new WorkspaceFileSystem(root).exists(".agents/runtime");if(hadTarget)await rename3(target,backup);try{await cp(source,target,{recursive:true,force:false,errorOnExist:true})}catch(error51){await rm3(target,{recursive:true,force:true});if(hadTarget)await rename3(backup,target);throw error51}return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:false}}async function rollbackDistribution(workspaceRoot){const root=resolve5(workspaceRoot);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");await rm3(target,{recursive:true,force:true});await rename3(backup,target)}async function doctorProject(filesystem){const findings=[];for(const path of[".agents/manifest.yaml",".agents/constitution.md","AGENTS.md","CLAUDE.md"]){if(!await filesystem.exists(path)){findings.push({severity:"error",path,message:"Required ZAIP-AIOS file is missing"})}}if(!await filesystem.exists(".git")){findings.push({severity:"warning",path:".git",message:"Git-native audit requires a Git repository"})}return findings}init_cli_arguments();import{createHash as createHash30}from"node:crypto";import{cp as cp2,lstat as lstat3,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname5,relative as relative6,resolve as resolve6,sep as sep4}from"node:path";var MANIFEST=".zaip-managed.json";async function planManagedAssetInstalls(distributionRoot,workspaceRoot){const[dashboard,design]=await Promise.all([planDashboardInstall(distributionRoot,workspaceRoot),planDesignInstall(distributionRoot,workspaceRoot)]);return{dashboard,design}}async function applyManagedAssetInstalls(plans){const[dashboard,design]=await Promise.all([applyDashboardInstall(plans.dashboard),applyDesignInstall(plans.design)]);return{dashboard,design}}async function planDashboardInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"dashboard")}async function planDesignInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"design")}async function planManagedAssetInstall(distributionRoot,workspaceRoot,asset){const source=resolve6(distributionRoot,asset);const destination=resolve6(workspaceRoot,`.agents/${asset}`);const sourceManifest=await readAndValidateManifest(source,asset);await assertManifestFiles(source,sourceManifest,asset);const sourceFiles=new Map(sourceManifest.files.map(file2=>[file2.path,file2.sha256]));const sourcePaths=[...sourceFiles.keys(),MANIFEST].sort();if(!await exists(destination)){return result(asset,source,destination,sourcePaths.map(path=>`.agents/${asset}/${path}`),[],[],[],false)}const currentManifestPath=resolve6(destination,MANIFEST);if(!await exists(currentManifestPath)){return result(asset,source,destination,[],[],[],[`.agents/${asset}`],false)}let currentManifest;try{currentManifest=await readAndValidateManifest(destination,asset)}catch{return result(asset,source,destination,[],[],[],[`.agents/${asset}/${MANIFEST}`],false)}const currentFiles=new Map(currentManifest.files.map(file2=>[file2.path,file2.sha256]));const conflicts=[];const actual=await relativeFiles(destination);const known2=new Set([...currentFiles.keys(),MANIFEST]);for(const path of actual){if(!known2.has(path))conflicts.push(`.agents/${asset}/${path}`)}for(const[path,expected]of currentFiles){const absolute=safeResolve(destination,path);if(!await exists(absolute)||await hashFile(absolute)!==expected){conflicts.push(`.agents/${asset}/${path}`)}}if(conflicts.length>0){return result(asset,source,destination,[],[],[],[...new Set(conflicts)].sort(),false)}const created=[];const updated=[];const existing=[];for(const[path,expected]of sourceFiles){const portable=`.agents/${asset}/${path}`;const current=currentFiles.get(path);if(current===void 0)created.push(portable);else if(current===expected)existing.push(portable);else updated.push(portable)}for(const path of currentFiles.keys()){if(!sourceFiles.has(path))updated.push(`.agents/${asset}/${path}`)}updated.push(`.agents/${asset}/${MANIFEST}`);return result(asset,source,destination,created,updated,existing,[],false)}async function applyDashboardInstall(plan){return applyManagedAssetInstall(plan)}async function applyDesignInstall(plan){return applyManagedAssetInstall(plan)}async function applyManagedAssetInstall(plan){if(plan.conflicts.length>0)throw new Error(`${plan.asset} install has unresolved conflicts`);const parent=dirname5(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve6(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve6(parent,`.${plan.asset}.zaip-old-${nonce}`);await mkdir4(parent,{recursive:true});await cp2(plan.source,staging,{recursive:true,errorOnExist:true,force:false});const hadDestination=await exists(plan.destination);try{if(hadDestination)await rename4(plan.destination,backup);await rename4(staging,plan.destination);if(hadDestination)await rm4(backup,{recursive:true,force:true})}catch(error51){await rm4(staging,{recursive:true,force:true});if(hadDestination&&await exists(backup)&&!await exists(plan.destination)){await rename4(backup,plan.destination)}throw error51}return{...plan,applied:true}}async function validateInstalledDashboard(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"dashboard")}async function validateInstalledDesign(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"design")}async function validateInstalledManagedAsset(workspaceRoot,asset){const root=resolve6(workspaceRoot,`.agents/${asset}`);if(!await exists(root)){return[{path:`.agents/${asset}`,message:`Managed ZAIP ${asset} is missing`}]}let manifest;try{manifest=await readAndValidateManifest(root,asset)}catch(error51){return[{path:`.agents/${asset}/${MANIFEST}`,message:error51 instanceof Error?error51.message:String(error51)}]}const findings=[];for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute)){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file is missing"})}else if(await hashFile(absolute)!==file2.sha256){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file checksum drift"})}}return findings}async function readAndValidateManifest(root,asset){const parsed=JSON.parse(await readFile6(resolve6(root,MANIFEST),"utf8"));if(typeof parsed!=="object"||parsed===null)throw new Error(`Invalid ${asset} manifest`);const value=parsed;if(value.schemaVersion!==1||typeof value.version!=="string"||!Array.isArray(value.files)){throw new Error(`Invalid ${asset} manifest fields`)}const seen=new Set;const files=value.files.map(entry2=>{if(typeof entry2!=="object"||entry2===null)throw new Error(`Invalid ${asset} file`);const file2=entry2;if(typeof file2.path!=="string"||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/.test(file2.sha256)){throw new Error(`Invalid ${asset} file fields`)}safeResolve(root,file2.path);if(seen.has(file2.path))throw new Error(`Duplicate ${asset} path: ${file2.path}`);seen.add(file2.path);return{path:file2.path,sha256:file2.sha256}});return{schemaVersion:1,version:value.version,files}}async function assertManifestFiles(root,manifest,asset){const actual=await relativeFiles(root);const expected=new Set([...manifest.files.map(file2=>file2.path),MANIFEST]);const extra=actual.filter(path=>!expected.has(path));if(extra.length>0)throw new Error(`Unmanaged ${asset} release files: ${extra.join(", ")}`);for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute))throw new Error(`${asset} release file missing: ${file2.path}`);if(await hashFile(absolute)!==file2.sha256){throw new Error(`${asset} release checksum mismatch: ${file2.path}`)}}}async function relativeFiles(root){const entries=await readdir2(root,{recursive:true,withFileTypes:true});return entries.filter(entry2=>entry2.isFile()).map(entry2=>relative6(root,resolve6(entry2.parentPath,entry2.name)).replaceAll("\\","/")).sort()}function safeResolve(root,portable){if(portable.length===0||portable.includes("\\")||portable.includes("\0")||portable.startsWith("/")||/^[A-Za-z]:/.test(portable)||portable.split("/").some(part=>part.length===0||part==="."||part==="..")){throw new Error(`Unsafe managed asset path: ${portable}`)}const destination=resolve6(root,portable);if(!destination.startsWith(`${resolve6(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash30("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat3(path).then(()=>true,error51=>{if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return false;throw error51})}function result(asset,source,destination,created,updated,existing,conflicts,applied){return{asset,source,destination,created:[...created].sort(),updated:[...new Set(updated)].sort(),existing:[...existing].sort(),conflicts:[...conflicts].sort(),applied}}import{basename,dirname as dirname6,resolve as resolve7}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDashboard(workspaceRoot)).map(finding3=>({severity:"error",code:"dashboard-drift",...finding3,state:"active"}))}async function designDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDesign(workspaceRoot)).map(finding3=>({severity:"error",code:"design-drift",...finding3,state:"active"}))}async function managedAssetDoctorFindings(executable,workspaceRoot,filesystem){if(executable!==void 0&&filesystem!==void 0){const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(await isFrameworkSourceWorkspace(filesystem,workspaceRoot,distributionRoot))return[]}return(await Promise.all([dashboardDoctorFindings(executable,workspaceRoot),designDoctorFindings(executable,workspaceRoot)])).flat()}async function isFrameworkSourceWorkspace(filesystem,root,distributionRoot){if(resolve7(root,".agents")!==distributionRoot||!await filesystem.exists("package.json")){return false}try{const manifest=JSON.parse(await filesystem.readText("package.json"));return manifest.name==="@zaip-ai/aios"}catch{return false}}async function frameworkSourceTemplateFiles(filesystem){const packagedAgentsRoot=basename(filesystem.root)===".agents";const roots2=packagedAgentsRoot?["config/agents","rules","requirements","skills","zaip-aios","tools"]:[".agents/rules",".agents/requirements",".agents/skills",".agents/zaip-aios",".agents/tools"];const paths=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths.map(async path=>({path:packagedAgentsRoot?`.agents/${path}`:path,content:await filesystem.readText(path)})))}init_lifecycle_manifest_commands();init_cli_arguments();async function readMigrationOptions(filesystem,parsed){const path=parsed.options.promotions;if(path===void 0)return{};const decoded=JSON.parse(await filesystem.readText(path));const promotions=Array.isArray(decoded)?decoded:typeof decoded==="object"&&decoded!==null&&"promotions"in decoded?decoded.promotions:void 0;if(!Array.isArray(promotions)){throw new UsageError("--promotions must point to a JSON array or an object containing a promotions array")}return{promotions}}function migrationPlanOutput(plan,verbose){const operationCounts=Object.fromEntries([...new Set(plan.operations.map(operation=>operation.category))].sort().map(category=>[category,plan.operations.filter(operation=>operation.category===category).length]));return{schema_version:plan.schema_version,migration_id:plan.migration_id,from_layout:plan.from_layout,to_layout:plan.to_layout,source_fingerprint:{sha256:plan.source_fingerprint.sha256,file_count:plan.source_fingerprint.files.length,total_bytes:plan.source_fingerprint.files.reduce((total,file2)=>total+file2.size,0)},promotions:plan.promotions,counts:plan.counts,operation_counts:operationCounts,findings:plan.findings,cleanup:{path_count:plan.cleanup_paths.length,roots:plan.cleanup_roots},plan_sha256:plan.plan_sha256,...verbose?{operations:plan.operations.map(({content_base64:_,...operation})=>operation),source_files:plan.source_fingerprint.files,cleanup_paths:plan.cleanup_paths}:{}}}init_src3();init_src4();init_src5();init_src();init_src5();import{createHash as createHash33}from"node:crypto";init_cli_arguments();function allocateInvocationBudget(input,children){if(input.policy.autonomy)return new Map(children.map(child=>[child.id,null]));const total=input.policy.max_total_invocations;const explicit=new Map(children.flatMap(child=>{const max=input.spec_execution_policies[child.spec_id]?.max_total_invocations;return max===void 0?[]:[[child.id,max]]}));if(total===null){return new Map(children.map(child=>[child.id,explicit.get(child.id)??null]))}const taskCountByChild=new Map;for(const task of input.tasks){if(task.child_execution_id===void 0)continue;taskCountByChild.set(task.child_execution_id,(taskCountByChild.get(task.child_execution_id)??0)+1)}const parentWeight=1+input.tasks.filter(task=>task.child_execution_id===void 0).length;const weights=children.filter(child=>!explicit.has(child.id)).map(child=>({id:child.id,weight:1+(taskCountByChild.get(child.id)??0)}));const reserved=[...explicit.values()].reduce((sum,value)=>sum+(value??0),0);if(total<parentWeight+children.length+reserved){throw new UsageError(`Global invocation budget ${total} cannot fund isolated SPEC budgets and the parent finalizer`)}const distributable=total-parentWeight-children.length-reserved;const totalWeight=parentWeight+weights.reduce((sum,item)=>sum+item.weight,0);return new Map([...children.filter(child=>explicit.has(child.id)).map(child=>[child.id,explicit.get(child.id)??null]),...weights.map(item=>[item.id,1+Math.floor(distributable*item.weight/totalWeight)])])}init_cli_arguments();function resolveExecutionRuntime(config2,limits={plan:1,provider:1,squad:1},source="task"){if(!config2.execution||config2.execution.runtime==="manual"||source==="interaction"||config2.execution.runtime==="managed"&&source==="task")return{runtime:"manual"};const autonomous=config2.execution.autonomous;if(config2.autonomy?.version===1&&autonomous.provider!=="codex"){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires Codex for managed execution. Select Codex; direct conversations remain available with the selected provider.")}const effectiveParallelism=Math.min(autonomous.max_parallelism,positiveLimit(limits.plan,"plan"),positiveLimit(limits.provider,"provider"),positiveLimit(limits.squad,"squad"));return{runtime:"autonomous",provider:autonomous.provider,model:autonomous.model,lease_ms:autonomous.lease_ms,effective_parallelism:effectiveParallelism,max_phase_attempts:autonomous.max_phase_attempts,max_total_invocations:autonomous.max_total_invocations}}function positiveLimit(value,label){if(!Number.isInteger(value)||value<1){throw new TypeError(`${label} parallelism must be a positive integer`)}return value}init_lifecycle_assurance_v2();init_src5();init_cli_arguments();init_run_hierarchy();import{createHash as createHash32}from"node:crypto";async function amendTaskScopes(parsed,filesystem,composition){requireOptions(parsed.options,["run","add-scopes","reason","expected-revision"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task amend-scopes requires a Task id");const{task}=await composition.tasks.read(id);const run=await composition.runs.read(parsed.options.run);if(run.status!=="running"||run.run.task_id!==id||run.run.change_id!==task.change_id||run.run.execution_kind!=="delivery"||run.run.agent!=="agent-orchestrator"||!["blocked","executing"].includes(task.status))throw new UsageError("Scope amendment requires this Task's active delivery orchestrator");const additions=[...new Set(csvOption(parsed.options["add-scopes"]))].sort();if(!additions.length||additions.some(scope=>scope.includes("\\")||scope.startsWith("/")||scope.includes(":")||scope.split("/").some(part=>part===".."||part==="."||part==="")||scope==="**"||scope==="*"))throw new UsageError("Scope amendments require explicit workspace-relative paths");const reason=parsed.options.reason?.trim();if(!reason)throw new UsageError("Scope amendment requires the authorized rework reason");const key=createHash32("sha256").update(JSON.stringify({task:id,run:run.run.run_id,additions,reason})).digest("hex").slice(0,24);const path=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework/scopes-${key}.json`;const exists3=await filesystem.exists(path);const receipt=exists3?JSON.parse(await filesystem.readText(path)):null;if(receipt?.next_scopes.every(scope=>task.write_scopes.includes(scope)))return{task,amendment_path:path,reused:true};if(activeDescendantRuns(run.run.run_id,await composition.runs.list()).length>0)throw new UsageError("Finish active descendants before changing the Task's write scopes");if(task.revision!==Number(parsed.options["expected-revision"])||receipt&&receipt.previous_revision!==task.revision)throw new UsageError("Task revision changed; inspect the current Task before amending scopes");const nextScopes=[...new Set([...task.write_scopes,...additions])];const next=taskV2Schema.parse({...task,revision:task.revision+1,write_scopes:nextScopes,updated_at:new Date().toISOString()});if(!exists3)await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:1,task_id:id,run_id:run.run.run_id,execution_id:run.run.execution_id,plan_hash:task.plan_hash,previous_revision:task.revision,previous_scopes:task.write_scopes,next_scopes:nextScopes,reason,occurred_at:next.updated_at},null,2)}
2110
+ `,"utf8"))}async function assertBackups(filesystem,stateRoot,fingerprint){for(const source of fingerprint.files){const path=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(path)){throw new MigrationSourceDivergenceError(`Migration backup is missing: ${path}`)}const bytes=await readFile5(filesystem.resolve(path));if(sha2565(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths){for(const path of paths)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname4(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2565(bytes).slice(0,12)}.tmp`;await rm2(temporary,{force:true});await writeFile2(temporary,bytes,{flag:"wx"});if(await filesystem.exists(path))await rm2(target,{force:true});await rename2(temporary,target)}function configOrder2(path){if(path===".agents/config/project.yaml")return 0;if(path===".agents/config/framework.lock.yaml")return 1;return 2}function sha2565(value){return createHash28("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2565(JSON.stringify(canonicalize4(value)))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,nested])=>[key,canonicalize4(nested)]))}return value}var DISTRIBUTION_VERSION="3.6.0";async function verifyDistribution(filesystem){const checksumPath="checksums.sha256";if(!await filesystem.exists(checksumPath)){return{valid:false,invalid:[checksumPath]}}const lines=(await filesystem.readText(checksumPath)).split(/\r?\n/).filter(Boolean);const invalid=[];for(const line of lines){const match=line.match(/^([a-f0-9]{64}) {2}(.+)$/);if(!match?.[1]||!match[2]||!await filesystem.exists(match[2])){invalid.push(match?.[2]??line);continue}const actual=createHash29("sha256").update(await filesystem.readBytes(match[2])).digest("hex");if(actual!==match[1])invalid.push(match[2])}return{valid:invalid.length===0,invalid}}async function migrateProject(filesystem,dryRun=false){const path=".agents/manifest.yaml";const raw=parseYaml(await filesystem.readText(path));if(typeof raw==="object"&&raw!==null&&"schema_version"in raw){await new ManifestRepository(filesystem).read();return{from:1,to:1,changed:[],dryRun}}if(typeof raw!=="object"||raw===null||!("version"in raw)||!("project"in raw)){throw new Error("Unsupported legacy manifest; automatic migration is unsafe")}const legacy2=raw;if(legacy2.version!==1||typeof legacy2.project.name!=="string"){throw new Error("Unsupported legacy manifest version")}const migrated={schema_version:1,project:{id:typeof legacy2.project.id==="string"?legacy2.project.id:normalizeShortName(legacy2.project.name).toLowerCase(),name:legacy2.project.name,timezone:"America/Sao_Paulo"},framework:{version:DISTRIBUTION_VERSION},layout:{version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"},profile:{id:"zaip-aios-stack"},agents:["codex","claude"],paths:{specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}};if(!dryRun)await filesystem.writeTextAtomic(path,serializeYaml(migrated));return{from:0,to:1,changed:[path],dryRun}}async function upgradeDistribution(workspaceRoot,sourcePath,dryRun=false){const root=resolve5(workspaceRoot);const source=resolve5(root,sourcePath);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");const fromRoot=relative5(root,source);if(fromRoot===".."||fromRoot.startsWith("../")||fromRoot.startsWith("..\\")||isAbsolute5(fromRoot)){throw new Error("Upgrade source escapes workspace")}if(source===target||source.startsWith(`${target}\\`)||source.startsWith(`${target}/`)){throw new Error("Upgrade source must not be inside the active distribution")}const verification=await verifyDistribution(new WorkspaceFileSystem(source));if(!verification.valid){throw new Error(`Upgrade source checksum failed: ${verification.invalid.join(", ")}`)}if(dryRun)return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:true};await mkdir3(resolve5(root,".local/rollback"),{recursive:true});await rm3(backup,{recursive:true,force:true});const hadTarget=await new WorkspaceFileSystem(root).exists(".agents/runtime");if(hadTarget)await rename3(target,backup);try{await cp(source,target,{recursive:true,force:false,errorOnExist:true})}catch(error51){await rm3(target,{recursive:true,force:true});if(hadTarget)await rename3(backup,target);throw error51}return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:false}}async function rollbackDistribution(workspaceRoot){const root=resolve5(workspaceRoot);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");await rm3(target,{recursive:true,force:true});await rename3(backup,target)}async function doctorProject(filesystem){const findings=[];for(const path of[".agents/manifest.yaml",".agents/constitution.md","AGENTS.md","CLAUDE.md"]){if(!await filesystem.exists(path)){findings.push({severity:"error",path,message:"Required ZAIP-AIOS file is missing"})}}if(!await filesystem.exists(".git")){findings.push({severity:"warning",path:".git",message:"Git-native audit requires a Git repository"})}return findings}init_cli_arguments();import{createHash as createHash30}from"node:crypto";import{cp as cp2,lstat as lstat3,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname5,relative as relative6,resolve as resolve6,sep as sep4}from"node:path";var MANIFEST=".zaip-managed.json";async function planManagedAssetInstalls(distributionRoot,workspaceRoot){const[dashboard,design]=await Promise.all([planDashboardInstall(distributionRoot,workspaceRoot),planDesignInstall(distributionRoot,workspaceRoot)]);return{dashboard,design}}async function applyManagedAssetInstalls(plans){const[dashboard,design]=await Promise.all([applyDashboardInstall(plans.dashboard),applyDesignInstall(plans.design)]);return{dashboard,design}}async function planDashboardInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"dashboard")}async function planDesignInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"design")}async function planManagedAssetInstall(distributionRoot,workspaceRoot,asset){const source=resolve6(distributionRoot,asset);const destination=resolve6(workspaceRoot,`.agents/${asset}`);const sourceManifest=await readAndValidateManifest(source,asset);await assertManifestFiles(source,sourceManifest,asset);const sourceFiles=new Map(sourceManifest.files.map(file2=>[file2.path,file2.sha256]));const sourcePaths=[...sourceFiles.keys(),MANIFEST].sort();if(!await exists(destination)){return result(asset,source,destination,sourcePaths.map(path=>`.agents/${asset}/${path}`),[],[],[],false)}const currentManifestPath=resolve6(destination,MANIFEST);if(!await exists(currentManifestPath)){return result(asset,source,destination,[],[],[],[`.agents/${asset}`],false)}let currentManifest;try{currentManifest=await readAndValidateManifest(destination,asset)}catch{return result(asset,source,destination,[],[],[],[`.agents/${asset}/${MANIFEST}`],false)}const currentFiles=new Map(currentManifest.files.map(file2=>[file2.path,file2.sha256]));const conflicts=[];const actual=await relativeFiles(destination);const known2=new Set([...currentFiles.keys(),MANIFEST]);for(const path of actual){if(!known2.has(path))conflicts.push(`.agents/${asset}/${path}`)}for(const[path,expected]of currentFiles){const absolute=safeResolve(destination,path);if(!await exists(absolute)||await hashFile(absolute)!==expected){conflicts.push(`.agents/${asset}/${path}`)}}if(conflicts.length>0){return result(asset,source,destination,[],[],[],[...new Set(conflicts)].sort(),false)}const created=[];const updated=[];const existing=[];for(const[path,expected]of sourceFiles){const portable=`.agents/${asset}/${path}`;const current=currentFiles.get(path);if(current===void 0)created.push(portable);else if(current===expected)existing.push(portable);else updated.push(portable)}for(const path of currentFiles.keys()){if(!sourceFiles.has(path))updated.push(`.agents/${asset}/${path}`)}updated.push(`.agents/${asset}/${MANIFEST}`);return result(asset,source,destination,created,updated,existing,[],false)}async function applyDashboardInstall(plan){return applyManagedAssetInstall(plan)}async function applyDesignInstall(plan){return applyManagedAssetInstall(plan)}async function applyManagedAssetInstall(plan){if(plan.conflicts.length>0)throw new Error(`${plan.asset} install has unresolved conflicts`);const parent=dirname5(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve6(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve6(parent,`.${plan.asset}.zaip-old-${nonce}`);await mkdir4(parent,{recursive:true});await cp2(plan.source,staging,{recursive:true,errorOnExist:true,force:false});const hadDestination=await exists(plan.destination);try{if(hadDestination)await rename4(plan.destination,backup);await rename4(staging,plan.destination);if(hadDestination)await rm4(backup,{recursive:true,force:true})}catch(error51){await rm4(staging,{recursive:true,force:true});if(hadDestination&&await exists(backup)&&!await exists(plan.destination)){await rename4(backup,plan.destination)}throw error51}return{...plan,applied:true}}async function validateInstalledDashboard(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"dashboard")}async function validateInstalledDesign(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"design")}async function validateInstalledManagedAsset(workspaceRoot,asset){const root=resolve6(workspaceRoot,`.agents/${asset}`);if(!await exists(root)){return[{path:`.agents/${asset}`,message:`Managed ZAIP ${asset} is missing`}]}let manifest;try{manifest=await readAndValidateManifest(root,asset)}catch(error51){return[{path:`.agents/${asset}/${MANIFEST}`,message:error51 instanceof Error?error51.message:String(error51)}]}const findings=[];for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute)){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file is missing"})}else if(await hashFile(absolute)!==file2.sha256){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file checksum drift"})}}return findings}async function readAndValidateManifest(root,asset){const parsed=JSON.parse(await readFile6(resolve6(root,MANIFEST),"utf8"));if(typeof parsed!=="object"||parsed===null)throw new Error(`Invalid ${asset} manifest`);const value=parsed;if(value.schemaVersion!==1||typeof value.version!=="string"||!Array.isArray(value.files)){throw new Error(`Invalid ${asset} manifest fields`)}const seen=new Set;const files=value.files.map(entry2=>{if(typeof entry2!=="object"||entry2===null)throw new Error(`Invalid ${asset} file`);const file2=entry2;if(typeof file2.path!=="string"||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/.test(file2.sha256)){throw new Error(`Invalid ${asset} file fields`)}safeResolve(root,file2.path);if(seen.has(file2.path))throw new Error(`Duplicate ${asset} path: ${file2.path}`);seen.add(file2.path);return{path:file2.path,sha256:file2.sha256}});return{schemaVersion:1,version:value.version,files}}async function assertManifestFiles(root,manifest,asset){const actual=await relativeFiles(root);const expected=new Set([...manifest.files.map(file2=>file2.path),MANIFEST]);const extra=actual.filter(path=>!expected.has(path));if(extra.length>0)throw new Error(`Unmanaged ${asset} release files: ${extra.join(", ")}`);for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute))throw new Error(`${asset} release file missing: ${file2.path}`);if(await hashFile(absolute)!==file2.sha256){throw new Error(`${asset} release checksum mismatch: ${file2.path}`)}}}async function relativeFiles(root){const entries=await readdir2(root,{recursive:true,withFileTypes:true});return entries.filter(entry2=>entry2.isFile()).map(entry2=>relative6(root,resolve6(entry2.parentPath,entry2.name)).replaceAll("\\","/")).sort()}function safeResolve(root,portable){if(portable.length===0||portable.includes("\\")||portable.includes("\0")||portable.startsWith("/")||/^[A-Za-z]:/.test(portable)||portable.split("/").some(part=>part.length===0||part==="."||part==="..")){throw new Error(`Unsafe managed asset path: ${portable}`)}const destination=resolve6(root,portable);if(!destination.startsWith(`${resolve6(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash30("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat3(path).then(()=>true,error51=>{if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return false;throw error51})}function result(asset,source,destination,created,updated,existing,conflicts,applied){return{asset,source,destination,created:[...created].sort(),updated:[...new Set(updated)].sort(),existing:[...existing].sort(),conflicts:[...conflicts].sort(),applied}}import{basename,dirname as dirname6,resolve as resolve7}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDashboard(workspaceRoot)).map(finding3=>({severity:"error",code:"dashboard-drift",...finding3,state:"active"}))}async function designDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDesign(workspaceRoot)).map(finding3=>({severity:"error",code:"design-drift",...finding3,state:"active"}))}async function managedAssetDoctorFindings(executable,workspaceRoot,filesystem){if(executable!==void 0&&filesystem!==void 0){const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(await isFrameworkSourceWorkspace(filesystem,workspaceRoot,distributionRoot))return[]}return(await Promise.all([dashboardDoctorFindings(executable,workspaceRoot),designDoctorFindings(executable,workspaceRoot)])).flat()}async function isFrameworkSourceWorkspace(filesystem,root,distributionRoot){if(resolve7(root,".agents")!==distributionRoot||!await filesystem.exists("package.json")){return false}try{const manifest=JSON.parse(await filesystem.readText("package.json"));return manifest.name==="@zaip-ai/aios"}catch{return false}}async function frameworkSourceTemplateFiles(filesystem){const packagedAgentsRoot=basename(filesystem.root)===".agents";const roots2=packagedAgentsRoot?["config/agents","rules","requirements","skills","zaip-aios","tools"]:[".agents/rules",".agents/requirements",".agents/skills",".agents/zaip-aios",".agents/tools"];const paths=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths.map(async path=>({path:packagedAgentsRoot?`.agents/${path}`:path,content:await filesystem.readText(path)})))}init_lifecycle_manifest_commands();init_cli_arguments();async function readMigrationOptions(filesystem,parsed){const path=parsed.options.promotions;if(path===void 0)return{};const decoded=JSON.parse(await filesystem.readText(path));const promotions=Array.isArray(decoded)?decoded:typeof decoded==="object"&&decoded!==null&&"promotions"in decoded?decoded.promotions:void 0;if(!Array.isArray(promotions)){throw new UsageError("--promotions must point to a JSON array or an object containing a promotions array")}return{promotions}}function migrationPlanOutput(plan,verbose){const operationCounts=Object.fromEntries([...new Set(plan.operations.map(operation=>operation.category))].sort().map(category=>[category,plan.operations.filter(operation=>operation.category===category).length]));return{schema_version:plan.schema_version,migration_id:plan.migration_id,from_layout:plan.from_layout,to_layout:plan.to_layout,source_fingerprint:{sha256:plan.source_fingerprint.sha256,file_count:plan.source_fingerprint.files.length,total_bytes:plan.source_fingerprint.files.reduce((total,file2)=>total+file2.size,0)},promotions:plan.promotions,counts:plan.counts,operation_counts:operationCounts,findings:plan.findings,cleanup:{path_count:plan.cleanup_paths.length,roots:plan.cleanup_roots},plan_sha256:plan.plan_sha256,...verbose?{operations:plan.operations.map(({content_base64:_,...operation})=>operation),source_files:plan.source_fingerprint.files,cleanup_paths:plan.cleanup_paths}:{}}}init_src3();init_src4();init_src5();init_src();init_src5();import{createHash as createHash33}from"node:crypto";init_cli_arguments();function allocateInvocationBudget(input,children){if(input.policy.autonomy)return new Map(children.map(child=>[child.id,null]));const total=input.policy.max_total_invocations;const explicit=new Map(children.flatMap(child=>{const max=input.spec_execution_policies[child.spec_id]?.max_total_invocations;return max===void 0?[]:[[child.id,max]]}));if(total===null){return new Map(children.map(child=>[child.id,explicit.get(child.id)??null]))}const taskCountByChild=new Map;for(const task of input.tasks){if(task.child_execution_id===void 0)continue;taskCountByChild.set(task.child_execution_id,(taskCountByChild.get(task.child_execution_id)??0)+1)}const parentWeight=1+input.tasks.filter(task=>task.child_execution_id===void 0).length;const weights=children.filter(child=>!explicit.has(child.id)).map(child=>({id:child.id,weight:1+(taskCountByChild.get(child.id)??0)}));const reserved=[...explicit.values()].reduce((sum,value)=>sum+(value??0),0);if(total<parentWeight+children.length+reserved){throw new UsageError(`Global invocation budget ${total} cannot fund isolated SPEC budgets and the parent finalizer`)}const distributable=total-parentWeight-children.length-reserved;const totalWeight=parentWeight+weights.reduce((sum,item)=>sum+item.weight,0);return new Map([...children.filter(child=>explicit.has(child.id)).map(child=>[child.id,explicit.get(child.id)??null]),...weights.map(item=>[item.id,1+Math.floor(distributable*item.weight/totalWeight)])])}init_cli_arguments();function resolveExecutionRuntime(config2,limits={plan:1,provider:1,squad:1},source="task"){if(!config2.execution||config2.execution.runtime==="manual"||source==="interaction"||config2.execution.runtime==="managed"&&source==="task")return{runtime:"manual"};const autonomous=config2.execution.autonomous;if(config2.autonomy?.version===1&&autonomous.provider!=="codex"){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires Codex for managed execution. Select Codex; direct conversations remain available with the selected provider.")}const effectiveParallelism=Math.min(autonomous.max_parallelism,positiveLimit(limits.plan,"plan"),positiveLimit(limits.provider,"provider"),positiveLimit(limits.squad,"squad"));return{runtime:"autonomous",provider:autonomous.provider,model:autonomous.model,lease_ms:autonomous.lease_ms,effective_parallelism:effectiveParallelism,max_phase_attempts:autonomous.max_phase_attempts,max_total_invocations:autonomous.max_total_invocations}}function positiveLimit(value,label){if(!Number.isInteger(value)||value<1){throw new TypeError(`${label} parallelism must be a positive integer`)}return value}init_lifecycle_assurance_v2();init_src5();init_cli_arguments();init_run_hierarchy();import{createHash as createHash32}from"node:crypto";async function amendTaskScopes(parsed,filesystem,composition){requireOptions(parsed.options,["run","add-scopes","reason","expected-revision"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task amend-scopes requires a Task id");const{task}=await composition.tasks.read(id);const run=await composition.runs.read(parsed.options.run);if(run.status!=="running"||run.run.task_id!==id||run.run.change_id!==task.change_id||run.run.execution_kind!=="delivery"||run.run.agent!=="agent-orchestrator"||!["blocked","executing"].includes(task.status))throw new UsageError("Scope amendment requires this Task's active delivery orchestrator");const additions=[...new Set(csvOption(parsed.options["add-scopes"]))].sort();if(!additions.length||additions.some(scope=>scope.includes("\\")||scope.startsWith("/")||scope.includes(":")||scope.split("/").some(part=>part===".."||part==="."||part==="")||scope==="**"||scope==="*"))throw new UsageError("Scope amendments require explicit workspace-relative paths");const reason=parsed.options.reason?.trim();if(!reason)throw new UsageError("Scope amendment requires the authorized rework reason");const key=createHash32("sha256").update(JSON.stringify({task:id,run:run.run.run_id,additions,reason})).digest("hex").slice(0,24);const path=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework/scopes-${key}.json`;const exists3=await filesystem.exists(path);const receipt=exists3?JSON.parse(await filesystem.readText(path)):null;if(receipt?.next_scopes.every(scope=>task.write_scopes.includes(scope)))return{task,amendment_path:path,reused:true};if(activeDescendantRuns(run.run.run_id,await composition.runs.list()).length>0)throw new UsageError("Finish active descendants before changing the Task's write scopes");if(task.revision!==Number(parsed.options["expected-revision"])||receipt&&receipt.previous_revision!==task.revision)throw new UsageError("Task revision changed; inspect the current Task before amending scopes");const nextScopes=[...new Set([...task.write_scopes,...additions])];const next=taskV2Schema.parse({...task,revision:task.revision+1,write_scopes:nextScopes,updated_at:new Date().toISOString()});if(!exists3)await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:1,task_id:id,run_id:run.run.run_id,execution_id:run.run.execution_id,plan_hash:task.plan_hash,previous_revision:task.revision,previous_scopes:task.write_scopes,next_scopes:nextScopes,reason,occurred_at:next.updated_at},null,2)}
2080
2111
  `);await composition.tasks.write(next);return{task:next,amendment_path:path,reused:false}}async function assertRecordedTaskScopeDelta(task,baseline,composition){if(JSON.stringify(task.write_scopes)===JSON.stringify(baseline))return;const directory2=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework`;const paths=await composition.filesystem.listFiles(directory2,".json");if(paths.length>128)throw new UsageError("Scope rework history requires explicit compaction review");const receipts=await Promise.all(paths.filter(path=>/\/scopes-[a-f0-9]+\.json$/.test(path)).map(async path=>JSON.parse(await composition.filesystem.readText(path))));let scopes=[...baseline];for(const receipt of receipts.sort((a,b)=>a.previous_revision-b.previous_revision)){if(receipt.schema_version!==1||receipt.task_id!==task.id||receipt.plan_hash!==task.plan_hash||!Number.isInteger(receipt.previous_revision)||receipt.previous_revision>=task.revision||JSON.stringify(receipt.previous_scopes)!==JSON.stringify(scopes)||!Array.isArray(receipt.next_scopes)||!scopes.every(scope=>receipt.next_scopes.includes(scope)))continue;const run=await composition.runs.read(receipt.run_id);if(run.run.task_id!==task.id||run.run.change_id!==task.change_id||run.run.execution_id!==receipt.execution_id||run.run.agent!=="agent-orchestrator")throw new UsageError("Scope rework receipt has incompatible ownership");scopes=receipt.next_scopes}if(JSON.stringify(task.write_scopes)!==JSON.stringify(scopes))throw new UsageError(`Native Task ${task.id} drifted from its PreparedPlan without a recorded scope rework`)}async function runAutonomousExecutionCommand(executionId,parsed,composition,driver,agentCatalog){const config2=composition.layout.projectConfig;if(config2===null)throw new UsageError("Autonomous execution requires project.yaml");const{execution}=await composition.executions.read(executionId);const configured=resolveExecutionRuntime(config2,void 0,execution.origin.type);if(configured.runtime==="manual"||parsed.flags.has("materialize-only")){return{mode:"manual",status:"materialized",execution,side_effects:false,artifact_path:composition.executions.path?.(executionId)}}if(driver===void 0){throw new UsageError("Autonomous provider protocol is not qualified; keep execution.runtime manual until clean-room qualification")}const capabilities=await driver.capabilities();const hostAuthenticationAvailable=configured.provider==="codex"?await driver.hostAuthenticationAttestation?.():false;if(configured.provider==="codex"&&hostAuthenticationAvailable!==true){throw new UsageError("Codex host authentication attestation is unavailable")}if(capabilities.provider!==configured.provider){throw new UsageError(`Configured provider ${configured.provider} does not match runtime ${capabilities.provider}`)}if(!capabilities.models.includes(configured.model)){throw new UsageError(`Configured model is not supported by runtime: ${configured.model}`)}let input=await buildAutonomousExecutionInput(composition,execution,{providerParallelism:capabilities.max_parallel_invocations,capabilities:{models:capabilities.models,reasoning_efforts:capabilities.reasoning_efforts,velocities:capabilities.velocities}},agentCatalog,{failurePolicy:parsed.flags.has("continue-independent")?"continue_independent":void 0,restartFailedState:parsed.flags.has("restart-failed-state"),recheckBlockedState:parsed.flags.has("recheck-blocked-state"),operationalContext:{host_authentication_available:hostAuthenticationAvailable===true,requires_remote_operation:parsed.flags.has("requires-remote-operation")}});const childExecutions=await materializePrdChildExecutions(composition,execution,input);if(childExecutions.length>0){const childBySpec=new Map(childExecutions.map(child=>[child.spec_id,child.id]));input={...input,tasks:input.tasks.map(task=>({...task,...task.commit?.spec_id===null||task.commit?.spec_id===void 0?{}:{child_execution_id:childBySpec.get(task.commit.spec_id)}}))};const budgetAllocation=allocateInvocationBudget(input,childExecutions);const candidates=await mapWithConcurrency(childExecutions,input.policy.max_parallelism,async child=>{const childExecution=(await composition.executions.read(child.id)).execution;const childInput=await buildAutonomousExecutionInput(composition,childExecution,{providerParallelism:capabilities.max_parallel_invocations,capabilities:{models:capabilities.models,reasoning_efforts:capabilities.reasoning_efforts,velocities:capabilities.velocities}},agentCatalog,{recheckBlockedState:parsed.flags.has("recheck-blocked-state")});const policy=input.spec_execution_policies[child.spec_id];if(policy?.cancelled===true){await composition.executions.transition(child.id,"cancelled","SPEC execution cancelled by its persisted policy");return{child_execution_id:child.id,spec_id:child.spec_id,status:"cancelled",handoff_worktree_path:null,handoff_commit:null,max_total_invocations:budgetAllocation.get(child.id)??null,finalizer_scope:policy.finalizer_scope,invocation_count:0}}const result3=await driver.execute({...childInput,spec_execution_policies:policy===void 0?{}:{[child.spec_id]:policy},policy:{...childInput.policy,max_parallelism:1,max_total_invocations:budgetAllocation.get(child.id)??null}});const status=result3.status==="completed"?"completed":result3.status==="failed"?"failed":"blocked";await composition.executions.transition(child.id,status,`Autonomous child ${status}`);return{child_execution_id:child.id,spec_id:child.spec_id,status,handoff_worktree_path:result3.state?.handoff_worktree_path??null,handoff_commit:result3.state?.handoff_commit??null,max_total_invocations:budgetAllocation.get(child.id)??null,finalizer_scope:policy?.finalizer_scope??"spec",invocation_count:result3.state?.invocation_count??0}});const consumedByChildren=candidates.reduce((total,candidate)=>total+candidate.invocation_count,0);input={...input,child_candidates:candidates.map(({invocation_count:_count,...candidate})=>candidate),policy:{...input.policy,max_total_invocations:input.policy.max_total_invocations===null?null:Math.max(1,input.policy.max_total_invocations-consumedByChildren)}}}const result2=await driver.execute(input);return{...result2,dependency_plan:dependencyPlan(input),child_executions:childExecutions}}async function materializePrdChildExecutions(composition,parent,input){if(parent.origin.type!=="prd")return[];const taskById=new Map(input.tasks.map(task=>[task.id,task]));const grouped=new Map;for(const task of input.tasks){const specId=task.commit?.spec_id??null;if(specId===null)continue;grouped.set(specId,[...grouped.get(specId)??[],task])}const children=[];for(const[specId,tasks]of[...grouped].sort(([left],[right])=>left.localeCompare(right))){const ids=new Set(tasks.map(task=>task.id));if(tasks.some(task=>task.depends_on.some(dependency=>!ids.has(dependency)||!taskById.has(dependency))))continue;const outsideTasks=input.tasks.filter(task=>!ids.has(task.id));if(tasks.some(task=>outsideTasks.some(outside2=>writeScopesOverlap(task.write_scopes,outside2.write_scopes)))){continue}const id=childExecutionId(parent.id,specId);const existing=await composition.executions.read(id).catch(()=>null);if(existing===null){const dag={nodes:parent.dag.nodes.filter(node=>ids.has(node.task_id)),topological_order:parent.dag.topological_order.filter(taskId=>ids.has(taskId))};await composition.executions.write({...parent,id,parent_execution_id:parent.id,client_turn_id:parent.client_turn_id??id,revision:1,origin:{type:"spec",spec_id:specId},status:"planned",status_reason:null,started_at:null,finished_at:null,result:null,dag,spec_execution_policies:input.spec_execution_policies[specId]===void 0?{}:{[specId]:input.spec_execution_policies[specId]}});await composition.executions.transition(id,"running")}await composition.executions.linkChildExecution(id,parent.id);children.push({id,spec_id:specId})}return children}function childExecutionId(parentExecutionId,specId){return`EXEC-CHILD-${createHash33("sha256").update(`${parentExecutionId}:${specId}`).digest("hex").slice(0,16).toUpperCase()}`}function writeScopesOverlap(left,right){return left.some(leftScope=>right.some(rightScope=>pathsOverlap(scopePrefix(leftScope),scopePrefix(rightScope))))}function scopePrefix(scope){const wildcard=scope.search(/[?*]/);return(wildcard<0?scope:scope.slice(0,wildcard)).replace(/\/+$/,"")}function pathsOverlap(left,right){return left.length===0||right.length===0||left===right||left.startsWith(`${right}/`)||right.startsWith(`${left}/`)}async function mapWithConcurrency(items,limit,worker){const results=new Array(items.length);let cursor=0;const runners=Array.from({length:Math.min(limit,items.length)},async()=>{while(cursor<items.length){const index=cursor++;const item=items[index];if(item!==void 0)results[index]=await worker(item)}});await Promise.all(runners);return results}async function buildAutonomousExecutionInput(composition,execution,limits,agentCatalog,overrides={}){const config2=composition.layout.projectConfig;if(config2===null)throw new UsageError("Autonomous execution requires project.yaml");const taskRecords=await Promise.all(execution.dag.topological_order.map(async taskId=>{const{task}=await composition.tasks.read(taskId);return task}));const preparedPlan=await composition.materializer.readPreparedPlan(execution.parent_execution_id??execution.id);const canonicalTasks=new Map(preparedPlan.blueprints.tasks.map(task=>[task.id,task]));const changes=await Promise.all([...new Set(execution.dag.nodes.map(node=>node.change_id))].map(async changeId=>(await composition.changes.read(changeId)).change));const referencedSpecIds=changes.flatMap(change=>change.source.type==="spec"?[change.source.spec_id]:change.source.type==="prd"&&change.source.spec_id!==null?[change.source.spec_id]:[]);const changeById=new Map(changes.map(change=>[change.id,change]));const manualOrder=await readManualWorkOrder(composition.filesystem);const runtime=resolveExecutionRuntime(config2,{plan:Math.min(execution.policy.max_parallelism,independentBranchLimit(taskRecords)),provider:limits.providerParallelism,squad:agentCatalog===void 0?1:Math.max(1,...agentCatalog.squads.map(squad=>squad.max_parallelism))},execution.origin.type);if(runtime.runtime!=="autonomous")throw new UsageError("Autonomous runtime is not enabled");const tasks=await Promise.all(taskRecords.map(async task=>{const ledger=composition.filesystem?await new FileRecoveryLedger(composition.filesystem).read(task.id):null;if(ledger&&!config2.autonomy&&!["completed","cancelled"].includes(task.status))throw new UsageError(`Task ${task.id} has a frozen autonomy ledger; restore project autonomy configuration before managed dispatch`);if(config2.autonomy&&(task.attempt_count??(task.started_at?1:0))>0&&!ledger&&!["completed","cancelled"].includes(task.status))throw new UsageError(`Task ${task.id} requires explicit task migrate-autonomy before managed dispatch; historical attempts cannot reset`);const baseline=canonicalTasks.get(task.id);if(baseline===void 0)throw new UsageError(`PreparedPlan is missing Task ${task.id}`);const change=changeById.get(task.change_id);if(change===void 0)throw new Error(`Task ${task.id} references an unreadable Change`);const source=change.source;return{id:task.id,...ledger?{autonomy:ledger}:{},change_id:task.change_id,title:task.title,objective:task.objective,risk:task.risk,priority:priorityNumber(task.priority),manual_order:manualOrderForTask(task.id,change.source,manualOrder),depends_on:[...task.depends_on],acceptance_ids:[...task.acceptance_ids],write_scopes:[...task.write_scopes],scope_receipt:await canonicalScopeReceipt(task,baseline.write_scopes,composition),assurance_contract:effectiveTaskAssurance(task,config2.assurance?.version===1?config2.assurance:{standard_depth:"auto",require_final_commit:false}).contract,...agentCatalog===void 0?{}:{builder:autonomousBuilderForTask(runtime.model,agentCatalog,task.write_scopes),...requiresAutonomousAudit(task)?{verifier:autonomousAuditorForTask(runtime.model,agentCatalog,task)}:{}},commit:{agent:runtime.provider.toUpperCase(),execution_id:execution.id,change_id:task.change_id,task_id:task.id,title:task.title,prd_id:source.type==="prd"?source.prd_id:null,spec_id:source.type==="spec"?source.spec_id:source.type==="prd"?source.spec_id:null},...task.runtime===void 0?{}:{runtime:task.runtime},...task.model_profile===void 0?{}:{model_profile:task.model_profile}}}));if(execution.origin.type==="interaction"){throw new Error(`Interaction Execution ${execution.id} cannot use the delivery runtime`)}return{mode:"autonomous",execution_id:execution.id,source:execution.origin.type,source_identity:{spec_id:execution.origin.type==="spec"?execution.origin.spec_id:null,prd_id:execution.origin.type==="prd"?execution.origin.prd_id:null},created_at:new Date(execution.created_at).toISOString(),...overrides.restartFailedState===true?{restart_failed_state:true}:{},...overrides.recheckBlockedState===true?{recheck_blocked_state:true}:{},host_capabilities:{models:[...limits.capabilities.models],reasoning_efforts:[...limits.capabilities.reasoning_efforts],velocities:[...limits.capabilities.velocities]},operational_context:{provider:runtime.provider,host_authentication_available:false,requires_external_provider:runtime.provider!=="codex",requires_remote_operation:false,...overrides.operationalContext},handoff_seed_paths:[...new Set([composition.layout.activePath("execution",execution.id),...execution.dag.nodes.flatMap(node=>[composition.layout.activePath("task",node.task_id),composition.layout.activePath("change",node.change_id)]),...execution.origin.type==="prd"?[composition.layout.activePath("prd",execution.origin.prd_id)]:execution.origin.type==="spec"?[composition.layout.activePath("spec",execution.origin.spec_id)]:[],...referencedSpecIds.map(specId=>composition.layout.activePath("spec",specId))])].sort(),policy:{...config2.autonomy?{autonomy:config2.autonomy}:{},failure_policy:overrides.failurePolicy??(config2.autonomy?"continue_independent":execution.policy.failure_policy),lease_ms:runtime.lease_ms,max_parallelism:runtime.effective_parallelism,max_operational_retries:execution.policy.max_operational_retries,max_repair_cycles_per_task:Math.min(3,execution.policy.max_repair_cycles_per_task),soft_cycles:execution.policy.soft_model_cycle_budget??24,...runtime.max_phase_attempts===void 0?{}:{max_phase_attempts:runtime.max_phase_attempts},max_execution_ms:null,max_invocation_ms:null,max_total_invocations:config2.autonomy?null:runtime.max_total_invocations===void 0?Math.max(1,tasks.length*30):runtime.max_total_invocations,max_stalled_cycles:3,...isAutomaticModelSource(execution,config2.model_orchestration)?{model_orchestration:config2.model_orchestration}:{},...execution.policy.runtime_defaults===void 0?{}:{execution_override:{model:execution.policy.runtime_defaults.model,reasoning_effort:execution.policy.runtime_defaults.reasoning_effort,velocity:execution.policy.runtime_defaults.velocity??"standard"}}},spec_execution_policies:execution.spec_execution_policies??{},agents:autonomousAgents(runtime.provider,runtime.model,agentCatalog),tasks}}async function readManualWorkOrder(filesystem){try{const parsed=JSON.parse(await filesystem.readText(".agents/dashboard/work-priority.json"));const ids=typeof parsed==="object"&&parsed!==null&&Array.isArray(parsed.item_ids)?parsed.item_ids:[];return new Map(ids.filter(id=>typeof id==="string").map((id,index)=>[id,index]))}catch{return new Map}}function manualOrderForTask(taskId,source,order2){return order2.get(taskId)??(source.spec_id?order2.get(source.spec_id):void 0)??(source.prd_id?order2.get(source.prd_id):void 0)??null}function independentBranchLimit(tasks){const selected=[];for(const task of tasks){if(task.depends_on.length>0||task.risk==="critical")continue;if(selected.some(candidate=>scopesOverlap2(candidate.write_scopes,task.write_scopes)))continue;selected.push(task)}return Math.max(1,selected.length)}function scopesOverlap2(left,right){return left.some(leftScope=>right.some(rightScope=>{const leftPrefix=leftScope.replace(/[?*].*$/,"").replace(/\/$/,"");const rightPrefix=rightScope.replace(/[?*].*$/,"").replace(/\/$/,"");return leftPrefix===""||rightPrefix===""||leftPrefix.startsWith(rightPrefix)||rightPrefix.startsWith(leftPrefix)}))}async function canonicalScopeReceipt(task,baseline,composition){await assertRecordedTaskScopeDelta(task,baseline,composition);const current=[...task.write_scopes];return{receipt_id:createHash33("sha256").update(JSON.stringify({task_id:task.id,plan_hash:task.plan_hash,revision:task.revision,scopes:current})).digest("hex"),current_scopes:current,delta_scopes:current.filter(scope=>!baseline.includes(scope))}}function dependencyPlan(input){return{failure_policy:input.policy.failure_policy,unconditioned:input.tasks.filter(task=>task.depends_on.length===0).map(task=>({task_id:task.id})),conditioned:input.tasks.filter(task=>task.depends_on.length>0).map(task=>({task_id:task.id,depends_on:[...task.depends_on]}))}}function isAutomaticModelSource(execution,config2){return config2?.mode==="auto"&&config2.automatic_sources.some(source=>source===execution.origin.type)}function autonomousAgents(provider,model,catalog){if(catalog===void 0){return{orchestrator:{id:`${provider}-orchestrator`,model},builder:{id:`${provider}-task-executor`,model,execution_eligibility:["delivery"]},verifier:{id:`${provider}-verifier`,model,tools:[]},finalizer:{id:`${provider}-execution-finalizer`,model}}}const orchestratorSelection=selectAgent(catalog,{role:"orchestrator",capability:"dag-orchestration"});const orchestrator=orchestratorSelection.agent;const builderSelection=selectAgentForWork(catalog,{role:"task-executor",capability:"task-delivery",scopes:[]});const builder=builderSelection.agent;const verifierSelection=selectAgent(catalog,{role:"reviewer",capability:"independent-review"});const verifier=verifierSelection.agent;const finalizerSelection=selectAgent(catalog,{role:"execution-finalizer",capability:"lifecycle-finalization"});const finalizer=finalizerSelection.agent;return{orchestrator:{id:orchestrator.id,model,capability:"dag-orchestration",selection_reasons:orchestratorSelection.reasons,soft_cycles:orchestrator.budget.soft_cycles,tools:orchestrator.tools,execution_eligibility:orchestrator.execution_eligibility},builder:{id:builder.id,model,capability:selectionCapability(builderSelection.reasons),selection_reasons:builderSelection.reasons,soft_cycles:builder.budget.soft_cycles,tools:builder.tools,execution_eligibility:builder.execution_eligibility},verifier:{id:verifier.id,model,capability:"independent-review",selection_reasons:verifierSelection.reasons,soft_cycles:verifier.budget.soft_cycles,tools:verifier.tools,execution_eligibility:verifier.execution_eligibility},finalizer:{id:finalizer.id,model,capability:"lifecycle-finalization",selection_reasons:finalizerSelection.reasons,soft_cycles:finalizer.budget.soft_cycles,tools:finalizer.tools,execution_eligibility:finalizer.execution_eligibility}}}function autonomousAuditorForTask(model,catalog,task){const capability=task.model_profile?.risk_signals.security_or_critical_data===true?"security-audit":"release-audit";const selection2=selectAgent(catalog,{role:"auditor",capability});const agent=selection2.agent;return{id:agent.id,model,capability,selection_reasons:selection2.reasons,soft_cycles:agent.budget.soft_cycles,tools:agent.tools,execution_eligibility:agent.execution_eligibility}}function requiresAutonomousAudit(task){const signals=task.model_profile?.risk_signals;return task.risk==="critical"||signals?.security_or_critical_data===true||signals?.broad_audit===true}function autonomousBuilderForTask(model,catalog,writeScopes){const selection2=selectAgentForWork(catalog,{role:"task-executor",capability:"task-delivery",scopes:writeScopes});const agent=selection2.agent;return{id:agent.id,model,capability:selectionCapability(selection2.reasons),selection_reasons:selection2.reasons,soft_cycles:agent.budget.soft_cycles,tools:agent.tools,execution_eligibility:agent.execution_eligibility}}function priorityNumber(priority2){return{low:1,medium:2,high:3,urgent:4}[priority2]}function selectionCapability(reasons){return reasons.find(reason=>reason.startsWith("capability:"))?.slice("capability:".length)??""}import{readdirSync,realpathSync,statSync}from"node:fs";import{homedir as homedir3}from"node:os";import{join as join3}from"node:path";init_src();init_src5();function astraDiagnosticContext(filesystem,build=buildContextPack){return async task=>{const query=["RULE-ASTRA-DIAGNOSTIC",...task.acceptance_ids].join(" ");const pack=await build(filesystem,query,16e3,{role:"orchestrator",phase:"planning",failClosed:true});const items=pack.items.filter(item=>pack.requiredFiles.includes(item.path));if(!items.some(item=>item.path===".agents/rules/astra-diagnostic.md"&&/\bRULE-ASTRA-DIAGNOSTIC\b/.test(item.content))){throw new Error("Astra diagnostic context is missing the canonical diagnostic Rule")}const present=new Set(items.flatMap(item=>item.content.match(/\b(?:AC|REQ)-[A-Z0-9-]+/g)??[]));if(!task.acceptance_ids.every(id=>present.has(id))){throw new Error("Astra diagnostic context is missing a governing Acceptance Criterion")}return items.map(({path,content})=>({path,content:path.startsWith(".agents/requirements/")?governingRequirementSections(content,task.acceptance_ids):content}))}}function governingRequirementSections(content,acceptanceIds){const sections=content.split(/(?=^## REQ-)/m);const governing=sections.slice(1).filter(section=>acceptanceIds.some(id=>new Set(section.match(/\bAC-[A-Z0-9-]+\b/g)??[]).has(id)));return governing.length===0?content:[sections[0],...governing].join("")}init_src();init_src3();init_src4();init_src5();init_src();init_src3();init_src6();import{createHash as createHash38}from"node:crypto";init_src3();import{createHash as createHash37}from"node:crypto";init_run_finalization_barrier();init_run_finalization_evidence_v2();init_run_lifecycle_reconciliation();async function reconcileTerminalOrchestratorRoot(root,candidates,composition,lifecycle){const decision=root.finalization_decision??null;const evidenceIds=decision===null?await passedTypedEvidenceIdsForRun(root,composition,candidates):decision.evidence_ids;const evidenceSatisfied=await hasPassedTypedEvidenceForRun(root,evidenceIds,composition,candidates);const barrier=assessRunFinalizationBarrier(root,candidates,evidenceSatisfied);const blockReason=finalizationBarrierBlockReason(barrier);const decisionEligible=decision!==null&&(decision.outcome!=="completed"||barrier.satisfied);const reconciliation=await reconcileFinishedRunLifecycle(root,composition,lifecycle,{requestedOutcome:decisionEligible?decision.outcome:"blocked",forceRequestedOutcome:!decisionEligible,summary:decisionEligible?decision.summary:blockReason??"Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked.",evidenceIds:decision?.evidence_ids??evidenceIds,changedFiles:decision?.changed_files??[],candidateRuns:candidates});return{status:"closed",parent_run_id:root.run.run_id,finalization_barrier:barrier,finalization_decision:decision,reconciliation}}init_run_conversation_v2();init_run_hierarchy();init_task_attempt();function closureReceiptPath(runId){return`.local/lifecycle-closure/${createHash37("sha256").update(runId).digest("hex")}.json`}async function reconcilePendingAncestorStops(child,composition,lifecycle){let parentId=child.run.parent_run_id;const seen=new Set;while(parentId!==null&&!seen.has(parentId)){seen.add(parentId);const parent=await composition.runs.read(parentId);const path=closureReceiptPath(parentId);if(await composition.filesystem.exists(path)){const receipt=JSON.parse(await composition.filesystem.readText(path));if(receipt.schema_version===1&&receipt.run_id===parentId&&receipt.task_id===parent.run.task_id&&receipt.execution_id===parent.run.execution_id&&receipt.state==="pending"&&["completed","failed","cancelled"].includes(receipt.terminal_status))await reconcileOrchestratorStop(parent,composition,lifecycle,receipt.terminal_status)}parentId=parent.run.parent_run_id}}async function reconcileOrchestratorStop(current,composition,lifecycle,terminalStatus2="completed"){return composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(current.run.run_id);const candidates=await composition.runs.list();if(candidates.some(candidate=>candidate.run.run_id!==fresh.run.run_id&&ownsLifecycleAttempt(candidate)&&candidate.run.task_id===fresh.run.task_id&&(fresh.run.task_id!==null||fresh.run.execution_id!==null&&candidate.run.execution_id===fresh.run.execution_id)&&Date.parse(candidate.run.occurred_at)>Date.parse(fresh.run.occurred_at)))return{status:"pending_newer_attempt",parent_run_id:fresh.run.run_id};const receiptPath=closureReceiptPath(fresh.run.run_id);const receipt={schema_version:1,run_id:fresh.run.run_id,task_id:fresh.run.task_id,execution_id:fresh.run.execution_id,terminal_status:fresh.finished?.status??terminalStatus2,state:"pending",recovery:"Replay the exact observed subagent stop; never reconcile unrelated open work"};await composition.filesystem.writeTextAtomic(receiptPath,`${JSON.stringify(receipt)}
2081
2112
  `);const active=activeDescendantRuns(fresh.run.run_id,candidates);if(active.length>0){return{status:"pending_descendants",parent_run_id:fresh.run.run_id,active_run_ids:active.map(candidate=>candidate.run.run_id)}}const settle=async(finished,all)=>{const result2=await reconcileTerminalOrchestratorRoot(finished,all,composition,lifecycle);await composition.filesystem.writeTextAtomic(receiptPath,`${JSON.stringify({...receipt,state:"reconciled"})}
2082
2113
  `);return{...result2,closure_receipt:receiptPath}};if(fresh.finished!==null)return settle(fresh,candidates);const sequence=fresh.records.length+1;await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(fresh.run.run_id,sequence),run_id:fresh.run.run_id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(fresh.records),status:terminalStatus2}));const finishedRoot=await composition.runs.read(fresh.run.run_id);return settle(finishedRoot,await composition.runs.list())})}init_task_attempt();init_lifecycle_v2();init_run_lifecycle_reconciliation();async function reconcileAutonomousCanonicalTask(workspaceRoot,input){if(workspaceRoot===void 0)return{observed:false,receipt_id:null};const fs=new WorkspaceFileSystem(workspaceRoot);const layout=await loadWorkspaceLayout(fs);const c=createV2Composition(fs,layout);const gate=new LifecycleV2Gate(fs,layout,c);const sidecarFs=new WorkspaceFileSystem(input.handoff_path);const sidecar=new RunV2Repository(sidecarFs,{storageMode:"tracked_sanitized",layout:await loadWorkspaceLayout(sidecarFs)});const observedRun=await sidecar.read(input.task_run_id);if(observedRun.finished===null||observedRun.run.task_id!==input.task_id||observedRun.run.execution_id!==input.execution_id||!ownsLifecycleAttempt(observedRun))throw new Error("Autonomous closure requires its exact observed terminal Task orchestrator");const observedStatus=observedRun.finished.status;return withLifecycleCanonicalMutationLock(fs,async()=>{const{task}=await c.tasks.read(input.task_id);const{execution}=await c.executions.read(input.execution_id);if(task.change_id!==observedRun.run.change_id||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id))throw new Error("Autonomous closure does not own the canonical Task/Execution");const receiptPath=`.local/autonomous-closure/${createHash38("sha256").update(JSON.stringify([input.execution_id,input.task_id,input.task_run_id])).digest("hex")}.json`;const receipt={schema_version:1,execution_id:input.execution_id,task_id:input.task_id,run_id:input.task_run_id,state:"pending",recovery:"Replay canonicalTaskClosure for this exact attempt after canonical Run/Gui/Evidence is available; do not import historical records or force completion"};await fs.writeTextAtomic(receiptPath,`${JSON.stringify(receipt)}
@@ -2154,4 +2185,4 @@ Autonomous execution: execution run ID [--materialize-only] [--continue-independ
2154
2185
  Direct delivery: conversation start or run start --direct-authorization HUMAN-REFERENCE; only an observed Task-scoped root, no fake executor; Gui and Evidence still required
2155
2186
  Explicit migration: task migrate-autonomy TASK --execution EXEC --expected-revision N --legacy-attempts N --legacy-replans N|unknown [--future-replans N|unlimited] --reason TEXT [--confirm]; unknown requires an explicit future grant; preview by default, preserves history and quota`}init_lifecycle_v2();import{spawn as spawn2}from"node:child_process";import{dirname as dirname15}from"node:path";async function taskLedger(repository2){const allTasks=await repository2.list();const activeChangeIds=new Set(allTasks.filter(task=>["executing","verifying"].includes(task.status)).map(task=>task.change));const tasks=allTasks.filter(task=>activeChangeIds.has(task.change)&&task.status!=="planned");const paths=new Set;for(const task of tasks){const{body}=await repository2.read(task.id);const section=body.match(/## Arquivos alterados\s+([\s\S]*?)(?=\n## |$)/)?.[1]??"";for(const match of section.matchAll(/^\s*-\s+`?([^`\n]+?)`?\s*$/gm)){if(match[1])paths.add(match[1].replace(/\\/g,"/"))}}return[...paths].sort()}async function taskLedgerV2(repository2,changed){const allTasks=await repository2.list();const activeChangeIds=new Set(allTasks.filter(task=>["executing","verifying","blocked"].includes(task.status)).map(task=>task.change_id));const changeTasks=allTasks.filter(task=>activeChangeIds.has(task.change_id)&&!["draft","planned","cancelled"].includes(task.status));const completedTasks=allTasks.filter(task=>task.result!==null);const paths=new Set([...changeTasks,...completedTasks].flatMap(task=>task.result?.changed_files??[]));const authorizedScopes=[...changeTasks.filter(task=>["executing","verifying","blocked"].includes(task.status)).flatMap(task=>task.write_scopes),...completedTasks.flatMap(task=>task.result?.changed_files??[])];for(const path of changed){if(authorizedScopes.some(scope=>workspaceScopeMatches(scope,path)))paths.add(path)}return[...paths].sort()}function runUiServer(serverPath,workspace){const child=spawn2(process.execPath,[serverPath],{cwd:dirname15(serverPath),env:{...process.env,ZAIP_WORKSPACE:workspace},stdio:"inherit",windowsHide:true});return new Promise((resolveExit,reject)=>{child.once("error",reject);child.once("exit",code=>resolveExit(code??1))})}init_lifecycle_manifest_commands();init_run_conversation_v2();init_cli_arguments();import{execFile as execFile18}from"node:child_process";import{lstat as lstat8,realpath as realpath9}from"node:fs/promises";import{basename as basename5,isAbsolute as isAbsolute10,relative as relative12,resolve as resolve17,sep as sep6}from"node:path";import{promisify as promisify18}from"node:util";var execFileAsync8=promisify18(execFile18);var shaPattern=/^[a-f0-9]{40}$/i;var canonicalMigrationPath=/^supabase\/migrations\/[A-Za-z0-9][A-Za-z0-9_.-]*\.sql$/;async function runSupabaseMigrationCommand(input){if(input.action!=="plan"&&input.action!=="validate"){throw new UsageError("supabase migration requires plan or validate")}const target=input.config?.supabase_migrations;if(target===void 0){throw new UsageError("supabase migration requires supabase_migrations in .agents/config/project.yaml")}const findings=await validateTarget(target.repository);const plan={repository_id:target.repository.id,configured_path:target.repository.path,required_branch:target.repository.branch,required_origin:target.repository.origin,hosted_applicator:target.hosted_applicator,applies_hosted_schema:false,required_evidence:["migration catalog entry","candidate SHA on beta","passed candidate checks","Supabase migration-history observation showing the same migration applied"]};if(input.action==="plan")return{valid:findings.length===0,mode:"plan",target:plan,findings};const evidencePath=input.parsed.options.evidence;if(evidencePath===void 0)throw new UsageError("supabase migration validate requires --evidence PATH");let evidence=null;try{evidence=parseEvidence(JSON.parse(await input.filesystem.readText(evidencePath)))}catch(error51){findings.push({code:"evidence-invalid",message:error51 instanceof Error?error51.message:"Migration evidence is invalid"})}if(evidence!==null&&findings.length===0){findings.push(...await validateEvidence(target.repository.path,evidence))}return{valid:findings.length===0,mode:"validate",target:plan,findings}}async function validateTarget(repository2){const findings=[];if(!isAbsolute10(repository2.path)||repository2.path.includes("\0")){return[{code:"target-path-invalid",message:"Migration target path must be absolute"}]}let target;try{target=await realpath9(repository2.path)}catch{return[{code:"target-path-unavailable",message:"Configured migration target is unavailable"}]}if(target.split(/[\\/]/).at(-1)!==repository2.id){findings.push({code:"target-identity-mismatch",message:"Target path basename does not match the configured repository id"})}const[branch,origin]=await Promise.all([git4(target,["branch","--show-current"]),git4(target,["remote","get-url","origin"])]);if(branch!==repository2.branch){findings.push({code:"target-branch-mismatch",message:"Migration target must be on branch beta"})}if(origin!==repository2.origin){findings.push({code:"target-origin-mismatch",message:"Migration target origin does not match configuration"})}return findings}async function validateEvidence(targetPath,evidence){const findings=[];if(!canonicalMigrationPath.test(evidence.migration.path)){return[{code:"migration-path-invalid",message:"Migration path must be a canonical supabase/migrations/*.sql path"}]}if(!basename5(evidence.migration.path).startsWith(evidence.migration.id)){findings.push({code:"migration-id-filename-mismatch",message:"Migration id must be the filename prefix"})}if(!shaPattern.test(evidence.candidate.sha)){findings.push({code:"candidate-sha-invalid",message:"Candidate SHA must be a full Git commit SHA"})}if(evidence.candidate.checks.length===0||evidence.candidate.checks.some(check2=>check2.status!=="passed")){findings.push({code:"candidate-checks-missing",message:"Candidate evidence requires one or more passed checks"})}if(evidence.applied.migration_id!==evidence.migration.id){findings.push({code:"applied-migration-mismatch",message:"Applied migration evidence must name the catalogued migration id"})}if(!Number.isFinite(Date.parse(evidence.applied.observed_at))){findings.push({code:"applied-observation-invalid",message:"Applied migration observation requires an ISO timestamp"})}if(findings.length>0)return findings;const target=await realpath9(targetPath);const migrationFile=resolve17(target,evidence.migration.path);if(!within(target,migrationFile)){return[{code:"migration-path-escape",message:"Migration path escapes the configured target"}]}try{const physicalMigrationFile=await realpath9(migrationFile);const status=await lstat8(migrationFile);if(status.isSymbolicLink()||!status.isFile()||!within(target,physicalMigrationFile)){findings.push({code:"migration-file-unsafe",message:"Migration file must be a regular non-symlink file inside the target"})}await git4(target,["ls-files","--error-unmatch","--",evidence.migration.path])}catch{findings.push({code:"migration-not-catalogued",message:"Migration file is absent from the target catalog"})}const head=await git4(target,["rev-parse","HEAD"]);if(head!==evidence.candidate.sha){findings.push({code:"candidate-sha-mismatch",message:"Candidate SHA must equal the current beta HEAD"})}try{const observedOriginBeta=await git4(target,["rev-parse","refs/remotes/origin/beta"]);if(observedOriginBeta!==evidence.candidate.sha){findings.push({code:"origin-beta-sha-mismatch",message:"Observed refs/remotes/origin/beta does not match the candidate SHA"})}else{findings.push({code:"origin-beta-unverified",message:"Observed origin/beta is local ref evidence only; fetch freshness and remote publication remain unverified"})}}catch{findings.push({code:"origin-beta-ref-unavailable",message:"refs/remotes/origin/beta is unavailable; remote publication is pending"})}try{const type=await git4(target,["cat-file","-t",`${evidence.candidate.sha}:${evidence.migration.path}`]);if(type!=="blob")throw new Error("candidate object is not a blob");await git4(target,["diff","--quiet","--",evidence.migration.path]);await git4(target,["diff","--cached","--quiet","--",evidence.migration.path])}catch{findings.push({code:"candidate-migration-unverified",message:"Candidate migration must be a tracked clean blob at the candidate SHA"})}return findings}function parseEvidence(value){if(typeof value!=="object"||value===null)throw new Error("Migration evidence must be an object");const record3=value;const migration=record3.migration;const candidate=record3.candidate;const applied=record3.applied;if(record3.schema_version!==1||migration===void 0||candidate===void 0||applied===void 0){throw new Error("Migration evidence must use schema_version 1 with migration, candidate and applied sections")}if(typeof migration.id!=="string"||typeof migration.path!=="string"||typeof candidate.sha!=="string"||!Array.isArray(candidate.checks)||typeof applied.migration_id!=="string"||applied.status!=="applied"||applied.source!=="supabase-migration-history"||applied.trust!=="unverified"||typeof applied.observed_at!=="string"){throw new Error("Migration evidence fields are incomplete or invalid; local observations are unverified")}if(!candidate.checks.every(check2=>typeof check2==="object"&&check2!==null&&typeof check2.id==="string"&&["passed","failed"].includes(String(check2.status)))){throw new Error("Candidate checks must each have id and passed or failed status")}return value}async function git4(cwd,args){const result2=await execFileAsync8("git",[...args],{cwd,windowsHide:true,encoding:"utf8"});return result2.stdout.trim()}function within(root,candidate){const path=relative12(root,candidate);return path===""||!path.startsWith(`..${sep6}`)&&path!==".."&&!isAbsolute10(path)}init_cli_arguments();import{lstat as lstat9,realpath as realpath10}from"node:fs/promises";import{isAbsolute as isAbsolute11,relative as relative13,resolve as resolve18,sep as sep7}from"node:path";async function assertToolWriteScope(root,scopes,requestedPath){if(!isCanonicalRelativePath(requestedPath)){throw new UsageError("Tool write path must be canonical and workspace-relative")}if(scopes.length===0||!scopes.some(scope=>scopeMatches2(scope,requestedPath))){throw new UsageError(`Tool write path is outside declared write scopes: ${requestedPath}`)}const physicalRoot=await realpath10(root);const target=resolve18(root,requestedPath);if(!within2(physicalRoot,target))throw new UsageError("Tool write path escapes workspace root");let ancestor=target;while(true){try{const status=await lstat9(ancestor);const physicalAncestor=await realpath10(ancestor);if(status.isSymbolicLink()||!within2(physicalRoot,physicalAncestor)){throw new UsageError("Tool write path escapes workspace through a symlink")}return}catch(error51){if(error51 instanceof UsageError)throw error51;if(!(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT"))throw error51;const parent=resolve18(ancestor,"..");if(parent===ancestor||!within2(resolve18(root),parent)){throw new UsageError("Tool write path has no contained existing ancestor")}ancestor=parent}}}async function copyWithinToolWriteScope(input){await assertToolWriteScope(input.root,input.scopes,input.to);await input.filesystem.writeTextAtomic(input.to,await input.filesystem.readText(input.from))}function isCanonicalRelativePath(value){return value.length>0&&!value.includes("\\")&&!value.includes(":")&&!value.includes("\0")&&!isAbsolute11(value)&&!value.startsWith("./")&&value.split("/").every(part=>part!==""&&part!=="."&&part!==".."&&!/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i.test(part))}function scopeMatches2(scope,path){if(!isCanonicalRelativePath(scope.replace(/\*+$/g,"placeholder")))return false;const normalized=scope.replace(/\/+$/,"");if(!normalized.includes("*"))return path===normalized||path.startsWith(`${normalized}/`);const expression=normalized.split("**").map(part=>part.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")).join(".*");return new RegExp(`^${expression}$`).test(path)}function within2(root,candidate){const fromRoot=relative13(root,candidate);return fromRoot===""||!fromRoot.startsWith(`..${sep7}`)&&fromRoot!==".."&&!isAbsolute11(fromRoot)}init_src();import{spawn as spawn3}from"node:child_process";async function runScopedVerification(filesystem,risk2){const changed=await new ShellGit(filesystem.root).status();const packageRoots=new Set;for(const entry2 of changed){const path=entry2.path.replace(/\\/g,"/");const match=path.match(/^(packages\/[^/]+|\.agents\/dashboard\/(?:apps|modules|packages|tests)\/[^/]+)/);if(match?.[1]!==void 0)packageRoots.add(`./${match[1]}`)}const commands=[];if(risk2==="critical")commands.push({name:"full-verify",command:"pnpm",args:["verify"]});else if(risk2==="standard"){commands.push({name:"encoding",command:"node",args:["scripts/validate-text-encoding.mjs"]},{name:"source-size",command:"node",args:["scripts/validate-source-size.mjs"]});for(const root of[...packageRoots].sort()){commands.push({name:`${root}:typecheck`,command:"pnpm",args:["--filter",root,"typecheck"]});commands.push({name:`${root}:test`,command:"pnpm",args:["--filter",root,"test"]})}}const lines=[];const checks=risk2==="lite"?[{name:"diff-only",passed:true,exit_code:0}]:[];const expectedChecks=checks.length+commands.length;for(const check2 of commands){const outcome=await runProcess2(check2.command,check2.args,filesystem.root);lines.push(`$ ${check2.command} ${check2.args.join(" ")}
2156
2187
  ${outcome.output}`);checks.push({name:check2.name,passed:outcome.code===0,exit_code:outcome.code});if(outcome.code!==0)break}const logPath=`.local/verify/${new Date().toISOString().replace(/[:.]/g,"-")}.log`;await filesystem.writeTextAtomic(logPath,`${lines.join("\n\n")}
2157
- `);return{passed:checks.length===expectedChecks&&checks.every(check2=>check2.passed),risk:risk2,changed_files:changed.length,checks,log_path:logPath}}async function runProcess2(command,args,cwd){return new Promise((resolveProcess,reject)=>{const executable=process.platform==="win32"&&command==="pnpm"?"pnpm.cmd":command;const child=spawn3(executable,args,{cwd,shell:process.platform==="win32",windowsHide:true});let output2="";child.stdout?.on("data",chunk=>output2+=String(chunk));child.stderr?.on("data",chunk=>output2+=String(chunk));child.once("error",reject);child.once("close",code=>resolveProcess({code:code??1,output:output2}))})}var CLI_VERSION="3.5.0";var CLI_DISPLAY_VERSION=CLI_VERSION.replace(/\.0$/,"");var EXIT2={success:0,error:1,usage:2,conformity:3,lifecycle:4,security:5,prerequisite:6};var execFileAsync9=promisify19(execFile19);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve19(parsed.options.workspace??cwd);const root=parsed.options.workspace===void 0?await new ShellGit(requestedRoot).repositoryRoot()??requestedRoot:requestedRoot;const filesystem=new WorkspaceFileSystem(root);const json2=parsed.flags.has("json");try{const[area,action]=parsed.positionals;if(area==="hook"&&action==="recover-stop"){requireOptions(parsed.options,["session","turn"]);const result2=await replayStopReceipt(filesystem,parsed.options.session,parsed.options.turn);output(result2,json2);return result2.state==="persisted"?EXIT2.success:EXIT2.lifecycle}if(area==="commit"){output(await runCommitPolicyCommand(root,parsed),json2);return EXIT2.success}if(area==="version"||parsed.flags.has("version")){output(json2?{version:CLI_VERSION}:CLI_DISPLAY_VERSION,json2);return EXIT2.success}if(area===void 0||area==="help"||parsed.flags.has("help")){output(HELP,json2);return area===void 0&&!parsed.flags.has("help")?EXIT2.usage:EXIT2.success}const activationExit=await handleZaipActivation(area,filesystem,json2);if(activationExit!==null)return activationExit;const distributionExit=await runDistributionCommand({area,action,parsed,filesystem,root,json:json2});if(distributionExit!==null)return distributionExit;if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="database"&&action==="migration"){const mode=parsed.positionals[2];if(mode!=="prepare"&&mode!=="submit")throw new UsageError("database migration requires prepare or submit");requireOptions(parsed.options,["database-repository","migration-path","description","tests","risk"]);if(!["compatible","destructive","permissions","incompatible"].includes(parsed.options.risk??""))throw new UsageError("--risk must be compatible, destructive, permissions, or incompatible");const migrationPath=parsed.options["migration-path"];const[source,sql,layout]=await Promise.all([verifiedMigrationSource(root),filesystem.readText(migrationPath),loadWorkspaceLayout(filesystem)]);const actualHash=createHash48("sha256").update(sql,"utf8").digest("hex");if(parsed.options["migration-sha256"]!==void 0&&parsed.options["migration-sha256"].toLowerCase()!==actualHash)throw new UsageError("--migration-sha256 does not match the migration file");const request=prepareMigrationRequest(layout.projectConfig,{source_repository:source.repository,source_sha:source.sha,source_identity_verified:true,database_repository:parsed.options["database-repository"],migration_path:migrationPath,migration_content_sha256:actualHash,description:parsed.options.description,sql,tests:parsed.options.tests.split(",").filter(Boolean),risk:parsed.options.risk});if(mode==="submit"){requireOptions(parsed.options,["request-head","database-worktree"]);const databaseWorktree=parsed.options["database-worktree"];const requestHead=parsed.options["request-head"];const[dbOrigin,headCommit]=await Promise.all([execFileAsync9("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync9("git",["rev-parse",requestHead],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true})]);const capturedHeadSha=headCommit.stdout.trim();if(!/^[a-f0-9]{40,64}$/i.test(capturedHeadSha))throw new UsageError("request head must resolve to a commit SHA");const blob=await execFileAsync9("git",["cat-file","blob",`${capturedHeadSha}:${migrationPath}`],{cwd:databaseWorktree,encoding:"buffer",windowsHide:true});const expectedDatabase=parsed.options["database-repository"];const originMatch=/^(?:git@github\.com:|https:\/\/github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\s*$/i.exec(dbOrigin.stdout.toString());if(originMatch?.[1]?.toLowerCase()!==expectedDatabase.toLowerCase())throw new UsageError("Database worktree origin does not exactly match --database-repository");if(createHash48("sha256").update(blob.stdout).digest("hex")!==actualHash)throw new UsageError("Request head migration blob does not match local migration SQL");const migrationConfig=layout.projectConfig?.supabase_migrations;if(migrationConfig===void 0)throw new UsageError("submit requires persisted supabase_migrations configuration");if(migrationConfig.repository.id!==expectedDatabase||migrationConfig.repository.path!==databaseWorktree||migrationConfig.repository.origin!==dbOrigin.stdout.trim())throw new UsageError("submit target and database worktree must exactly match persisted supabase_migrations.repository");assertMigrationRemoteSubmission({beta_integration_verified:migrationConfig.beta_integration_verified??false,paid_beta_provisioning_confirmed:migrationConfig.paid_beta_provisioning_confirmed??false,preview_policy:migrationConfig.preview_policy??"disabled"});const submission=await submitMigrationRequest(new GhMigrationPullRequestAdapter(databaseWorktree,requestHead,capturedHeadSha),expectedDatabase,request);output({mode,request,submission,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}output({mode,request,remote_submitted:false,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}if(area==="adapters"&&action==="build"){await buildAdapters(filesystem);output({built:true},json2);return EXIT2.success}if(area==="adapters"&&action==="check"){const result2=await checkAdapters(filesystem);output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="context"&&action==="inventory"){output(await inventory(filesystem),json2);return EXIT2.success}if(area==="context"&&["build","inspect"].includes(action??"")){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??parsed.positionals.slice(2).join(" ")),numberOption(parsed.options.budget,8e3));if(parsed.options.run!==void 0){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("context --run requires a modern workspace");await recordContextPackUsage(parsed.options.run,pack.estimatedTokens,createV2Composition(filesystem,layout))}output(contextPackView(parsed)==="compact"?compactContextPack(pack):pack,json2);return EXIT2.success}if(area==="context"&&action==="map"){output(await buildRepositoryMap(filesystem),json2);return EXIT2.success}if(area==="context"&&action==="agents"){try{const discovery=await resolveAgentDiscovery(filesystem,{...parsed.options.agent===void 0?{}:{agentId:parsed.options.agent}});output(parsed.options.agent===void 0?discovery:{source:discovery.source,provenance:discovery.provenance,selected:discovery.selected},json2);return EXIT2.success}catch(error51){if(error51 instanceof Error&&/agent/i.test(error51.message))throw new UsageError(error51.message);throw error51}}if(area==="context"&&action==="handoff"){output(contextHandoffForCommand(parsed),json2);return EXIT2.success}if(area==="context"&&action==="validate"){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??"active task"),numberOption(parsed.options.budget,8e3));const findings=validateContextPack(pack);output({valid:findings.length===0,estimatedTokens:pack.estimatedTokens,budget:pack.budget,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="manifest"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("lifecycle manifests require a modern workspace");output(await runLifecycleManifestMaintenance(action,parsed,filesystem,createV2Composition(filesystem,layout)),json2);return EXIT2.success}if(area==="cost"&&action==="cohort"){requireOptions(parsed.options,["input"]);output(await readCostCohortInput(filesystem,parsed.options.input),json2);return EXIT2.success}if(area==="verify"){if(!parsed.flags.has("changed")&&riskOption(parsed.options.risk)!=="critical"){throw new UsageError("verify requires --changed or --risk critical")}const result2=await runScopedVerification(filesystem,riskOption(parsed.options.risk));output(result2,json2);return result2.passed?EXIT2.success:EXIT2.conformity}if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="tool"&&action==="copy"){if(parsed.options.task===void 0||parsed.options.run===void 0){throw new UsageError("tool copy requires --task TASK --run RUN")}const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("tool copy requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const{run,status}=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());if(!["executing","verifying"].includes(task.status)||status!=="running"||run.task_id!==task.id||run.change_id!==task.change_id||run.execution_id!==executionId){throw new UsageError("tool copy requires an active Run linked to the declared Task")}const scopes=task.write_scopes;if(parsed.options.from===void 0||parsed.options.to===void 0||scopes.length===0){throw new UsageError("tool copy requires --from PATH --to PATH and Task write scopes")}await copyWithinToolWriteScope({filesystem,root,scopes,from:parsed.options.from,to:parsed.options.to});output({copied:true,to:parsed.options.to,scopes},json2);return EXIT2.success}if(["architecture","cqrs","modules"].includes(area)&&action==="validate"){const layout=await loadWorkspaceLayout(filesystem);const profile=configuredArchitectureProfile(layout.projectConfig);const units=await sourceUnits(filesystem);const findings=area==="cqrs"?validateCqrs(units,profile):area==="modules"?validateModules(units,profile):validateArchitecture(units,profile);output({valid:findings.length===0,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="profile"&&action==="validate"){if(parsed.options.path!==void 0){throw new UsageError("profile validate reads the configured stack in .agents/config/project.yaml; --path is no longer supported")}const configured=await loadWorkspaceLayout(filesystem);const projectConfig2=configured.projectConfig;const stack=projectConfig2?.stack;if(projectConfig2===null||stack===void 0){throw new UsageError("profile validate requires .agents/config/project.yaml")}const profile={id:stack.id,status:"supported",extensions:stack.extensions??[],defaults:{language:stack.language,api:stack.api,queryBuilder:stack.query_builder},workspaceLayout:2,conventions:{apps:stack.layout===void 0?void 0:{frontend:stack.layout.frontend,backend:stack.layout.backend,site:stack.layout.site},modules:stack.layout?.modules,packages:stack.layout?.packages,e2e:stack.layout?.e2e,source_limits:stack.source_limits},invariants:stack.invariants??[],commands:stack.commands};configuredArchitectureProfile(projectConfig2);const findings=[...validateProfileContract(profile)];const clientCatalog=parseYaml(await filesystem.readText(".agents/config/clients.yaml"));const clientPaths=await validateConfiguredProfileAgentPaths(clientCatalog,projectConfig2.clients,filesystem);findings.push(...clientPaths.findings.map(message=>({field:"clients",message})));output({valid:findings.length===0,profile:PROJECT_CONFIG_PATH,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="eval"&&["run","specs","architecture","cqrs","security","infrastructure","adapters","context"].includes(action??"")){const report=action==="run"?runAllCategoryEvals():runCategoryEval(action);const layout=await loadWorkspaceLayout(filesystem);const persisted=parsed.flags.has("no-write")?null:layout.version!==1?await persistEvalReportV2(filesystem,layout,report,action??"run",parsed):await persistEvalReport(filesystem,report,action??"run");output({...report,persisted},json2);return report.passed?EXIT2.success:EXIT2.conformity}if(V2_COMMAND_AREAS.has(area)){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){output(await runV2Command(area,action,parsed,filesystem,layout),json2);return EXIT2.success}if(["prd","execution","run-v2","plan"].includes(area)){throw new UsageError(`${area} requires a V2 workspace`)}if(!isLegacyReadOnlyCommand(area,action)){throw new UsageError("V1 lifecycle is read-only; use `migrate plan` and `migrate apply` before mutation")}}if(area==="change"&&action==="show"){output(await new ChangeRepository(filesystem).read(requiredPosition(parsed.positionals,2,"change id")),json2);return EXIT2.success}if(area==="change"&&action==="validate"){const result2=await new ChangeRepository(filesystem).validate(requiredPosition(parsed.positionals,2,"change id"));output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="spec"&&action==="show"){output(await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability")),json2);return EXIT2.success}if(area==="spec"&&action==="validate"){const result2=await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability"));output({valid:true,spec:result2.spec},json2);return EXIT2.success}if(area==="task"&&action==="list"){output(await new TaskRepository(filesystem).list(),json2);return EXIT2.success}if(area==="task"&&action==="next"){output(nextExecutableTasks(await new TaskRepository(filesystem).list()),json2);return EXIT2.success}if(area==="task"&&action==="show"){output(await new TaskRepository(filesystem).read(requiredEntityId(parsed,2,"task id")),json2);return EXIT2.success}if(area==="decision"&&action==="list"){output(await new DecisionRepository(filesystem).list(),json2);return EXIT2.success}if(area==="decision"&&action==="show"){const id=requiredPosition(parsed.positionals,2,"decision id");output(await new DecisionRepository(filesystem).read(id,id.startsWith("DEC-HUMAN-")?"human":"agent"),json2);return EXIT2.success}if(area==="run"&&action==="show"){output(await new RunRepository(filesystem).read(requiredPosition(parsed.positionals,2,"run id")),json2);return EXIT2.success}if(area==="generate"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){const tasks2=await new TaskV2Repository(filesystem,layout).list();output({generated:null,storage:"stdout",board:tasks2.map(task=>({id:task.id,title:task.title,status:task.status,priority:task.priority,artifact_path:layout.activePath("task",task.id)}))},json2);return EXIT2.success}const tasks=await new TaskRepository(filesystem).list();const board=generateBoard(tasks);output({generated:null,storage:"stdout",board},json2);return EXIT2.success}if(area==="guard"&&action==="diff"){const changed=await new ShellGit(root).changedFiles();const layout=await loadWorkspaceLayout(filesystem);const ledger=layout.version!==1?await taskLedgerV2(new TaskV2Repository(filesystem,layout),changed):await taskLedger(new TaskRepository(filesystem));const findings=guardDiff(changed,ledger);output({valid:findings.length===0,changed,ledger,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="ui"){const executable=process.argv[1];if(executable!==void 0){const executableRoot=resolve19(dirname16(executable),"..");const distributionRoot=basename6(executableRoot)===".agents"?executableRoot:resolve19(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename6(distributionRoot)===".agents"&&await new WorkspaceFileSystem(root).exists(".agents/dashboard/packages/local-runtime/start-dashboard.mjs")){output({url:"http://127.0.0.1:4317",security:"loopback-only"},json2);const code=await runUiServer(resolve19(root,".agents/dashboard/packages/local-runtime/start-dashboard.mjs"),root);return code}}output({command:"corepack pnpm dashboard:dev",sourceMode:true},json2);return EXIT2.success}throw new UsageError(`Unknown command: ${parsed.positionals.join(" ")}`)}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);output({error:message},json2,true);return error51 instanceof UsageError?EXIT2.usage:EXIT2.error}}function isLegacyReadOnlyCommand(area,action){const actions={spec:["show","validate"],change:["show","validate"],task:["list","next","show"],decision:["list","show"],run:["show"]};return actions[area]?.includes(action)??false}var HELP=helpText(CLI_DISPLAY_VERSION);var isMain=process.argv[1]!==void 0&&pathToFileURL(resolve19(process.argv[1])).href===import.meta.url;if(isMain)process.exitCode=await runCli(process.argv.slice(2));export{CLI_DISPLAY_VERSION,CLI_VERSION,EXIT2 as EXIT,runCli};
2188
+ `);return{passed:checks.length===expectedChecks&&checks.every(check2=>check2.passed),risk:risk2,changed_files:changed.length,checks,log_path:logPath}}async function runProcess2(command,args,cwd){return new Promise((resolveProcess,reject)=>{const executable=process.platform==="win32"&&command==="pnpm"?"pnpm.cmd":command;const child=spawn3(executable,args,{cwd,shell:process.platform==="win32",windowsHide:true});let output2="";child.stdout?.on("data",chunk=>output2+=String(chunk));child.stderr?.on("data",chunk=>output2+=String(chunk));child.once("error",reject);child.once("close",code=>resolveProcess({code:code??1,output:output2}))})}var CLI_VERSION="3.6.0";var CLI_DISPLAY_VERSION=CLI_VERSION.replace(/\.0$/,"");var EXIT2={success:0,error:1,usage:2,conformity:3,lifecycle:4,security:5,prerequisite:6};var execFileAsync9=promisify19(execFile19);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve19(parsed.options.workspace??cwd);const root=parsed.options.workspace===void 0?await new ShellGit(requestedRoot).repositoryRoot()??requestedRoot:requestedRoot;const filesystem=new WorkspaceFileSystem(root);const json2=parsed.flags.has("json");try{const[area,action]=parsed.positionals;if(area==="hook"&&action==="recover-stop"){requireOptions(parsed.options,["session","turn"]);const result2=await replayStopReceipt(filesystem,parsed.options.session,parsed.options.turn);output(result2,json2);return result2.state==="persisted"?EXIT2.success:EXIT2.lifecycle}if(area==="commit"){output(await runCommitPolicyCommand(root,parsed),json2);return EXIT2.success}if(area==="version"||parsed.flags.has("version")){output(json2?{version:CLI_VERSION}:CLI_DISPLAY_VERSION,json2);return EXIT2.success}if(area===void 0||area==="help"||parsed.flags.has("help")){output(HELP,json2);return area===void 0&&!parsed.flags.has("help")?EXIT2.usage:EXIT2.success}const activationExit=await handleZaipActivation(area,filesystem,json2);if(activationExit!==null)return activationExit;const distributionExit=await runDistributionCommand({area,action,parsed,filesystem,root,json:json2});if(distributionExit!==null)return distributionExit;if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="database"&&action==="migration"){const mode=parsed.positionals[2];if(mode!=="prepare"&&mode!=="submit")throw new UsageError("database migration requires prepare or submit");requireOptions(parsed.options,["database-repository","migration-path","description","tests","risk"]);if(!["compatible","destructive","permissions","incompatible"].includes(parsed.options.risk??""))throw new UsageError("--risk must be compatible, destructive, permissions, or incompatible");const migrationPath=parsed.options["migration-path"];const[source,sql,layout]=await Promise.all([verifiedMigrationSource(root),filesystem.readText(migrationPath),loadWorkspaceLayout(filesystem)]);const actualHash=createHash48("sha256").update(sql,"utf8").digest("hex");if(parsed.options["migration-sha256"]!==void 0&&parsed.options["migration-sha256"].toLowerCase()!==actualHash)throw new UsageError("--migration-sha256 does not match the migration file");const request=prepareMigrationRequest(layout.projectConfig,{source_repository:source.repository,source_sha:source.sha,source_identity_verified:true,database_repository:parsed.options["database-repository"],migration_path:migrationPath,migration_content_sha256:actualHash,description:parsed.options.description,sql,tests:parsed.options.tests.split(",").filter(Boolean),risk:parsed.options.risk});if(mode==="submit"){requireOptions(parsed.options,["request-head","database-worktree"]);const databaseWorktree=parsed.options["database-worktree"];const requestHead=parsed.options["request-head"];const[dbOrigin,headCommit]=await Promise.all([execFileAsync9("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync9("git",["rev-parse",requestHead],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true})]);const capturedHeadSha=headCommit.stdout.trim();if(!/^[a-f0-9]{40,64}$/i.test(capturedHeadSha))throw new UsageError("request head must resolve to a commit SHA");const blob=await execFileAsync9("git",["cat-file","blob",`${capturedHeadSha}:${migrationPath}`],{cwd:databaseWorktree,encoding:"buffer",windowsHide:true});const expectedDatabase=parsed.options["database-repository"];const originMatch=/^(?:git@github\.com:|https:\/\/github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\s*$/i.exec(dbOrigin.stdout.toString());if(originMatch?.[1]?.toLowerCase()!==expectedDatabase.toLowerCase())throw new UsageError("Database worktree origin does not exactly match --database-repository");if(createHash48("sha256").update(blob.stdout).digest("hex")!==actualHash)throw new UsageError("Request head migration blob does not match local migration SQL");const migrationConfig=layout.projectConfig?.supabase_migrations;if(migrationConfig===void 0)throw new UsageError("submit requires persisted supabase_migrations configuration");if(migrationConfig.repository.id!==expectedDatabase||migrationConfig.repository.path!==databaseWorktree||migrationConfig.repository.origin!==dbOrigin.stdout.trim())throw new UsageError("submit target and database worktree must exactly match persisted supabase_migrations.repository");assertMigrationRemoteSubmission({beta_integration_verified:migrationConfig.beta_integration_verified??false,paid_beta_provisioning_confirmed:migrationConfig.paid_beta_provisioning_confirmed??false,preview_policy:migrationConfig.preview_policy??"disabled"});const submission=await submitMigrationRequest(new GhMigrationPullRequestAdapter(databaseWorktree,requestHead,capturedHeadSha),expectedDatabase,request);output({mode,request,submission,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}output({mode,request,remote_submitted:false,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}if(area==="adapters"&&action==="build"){await buildAdapters(filesystem);output({built:true},json2);return EXIT2.success}if(area==="adapters"&&action==="check"){const result2=await checkAdapters(filesystem);output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="context"&&action==="inventory"){output(await inventory(filesystem),json2);return EXIT2.success}if(area==="context"&&["build","inspect"].includes(action??"")){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??parsed.positionals.slice(2).join(" ")),numberOption(parsed.options.budget,8e3));if(parsed.options.run!==void 0){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("context --run requires a modern workspace");await recordContextPackUsage(parsed.options.run,pack.estimatedTokens,createV2Composition(filesystem,layout))}output(contextPackView(parsed)==="compact"?compactContextPack(pack):pack,json2);return EXIT2.success}if(area==="context"&&action==="map"){output(await buildRepositoryMap(filesystem),json2);return EXIT2.success}if(area==="context"&&action==="agents"){try{const discovery=await resolveAgentDiscovery(filesystem,{...parsed.options.agent===void 0?{}:{agentId:parsed.options.agent}});output(parsed.options.agent===void 0?discovery:{source:discovery.source,provenance:discovery.provenance,selected:discovery.selected},json2);return EXIT2.success}catch(error51){if(error51 instanceof Error&&/agent/i.test(error51.message))throw new UsageError(error51.message);throw error51}}if(area==="context"&&action==="handoff"){output(contextHandoffForCommand(parsed),json2);return EXIT2.success}if(area==="context"&&action==="validate"){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??"active task"),numberOption(parsed.options.budget,8e3));const findings=validateContextPack(pack);output({valid:findings.length===0,estimatedTokens:pack.estimatedTokens,budget:pack.budget,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="manifest"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("lifecycle manifests require a modern workspace");output(await runLifecycleManifestMaintenance(action,parsed,filesystem,createV2Composition(filesystem,layout)),json2);return EXIT2.success}if(area==="cost"&&action==="cohort"){requireOptions(parsed.options,["input"]);output(await readCostCohortInput(filesystem,parsed.options.input),json2);return EXIT2.success}if(area==="verify"){if(!parsed.flags.has("changed")&&riskOption(parsed.options.risk)!=="critical"){throw new UsageError("verify requires --changed or --risk critical")}const result2=await runScopedVerification(filesystem,riskOption(parsed.options.risk));output(result2,json2);return result2.passed?EXIT2.success:EXIT2.conformity}if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="tool"&&action==="copy"){if(parsed.options.task===void 0||parsed.options.run===void 0){throw new UsageError("tool copy requires --task TASK --run RUN")}const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("tool copy requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const{run,status}=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());if(!["executing","verifying"].includes(task.status)||status!=="running"||run.task_id!==task.id||run.change_id!==task.change_id||run.execution_id!==executionId){throw new UsageError("tool copy requires an active Run linked to the declared Task")}const scopes=task.write_scopes;if(parsed.options.from===void 0||parsed.options.to===void 0||scopes.length===0){throw new UsageError("tool copy requires --from PATH --to PATH and Task write scopes")}await copyWithinToolWriteScope({filesystem,root,scopes,from:parsed.options.from,to:parsed.options.to});output({copied:true,to:parsed.options.to,scopes},json2);return EXIT2.success}if(["architecture","cqrs","modules"].includes(area)&&action==="validate"){const layout=await loadWorkspaceLayout(filesystem);const profile=configuredArchitectureProfile(layout.projectConfig);const units=await sourceUnits(filesystem);const findings=area==="cqrs"?validateCqrs(units,profile):area==="modules"?validateModules(units,profile):validateArchitecture(units,profile);output({valid:findings.length===0,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="profile"&&action==="validate"){if(parsed.options.path!==void 0){throw new UsageError("profile validate reads the configured stack in .agents/config/project.yaml; --path is no longer supported")}const configured=await loadWorkspaceLayout(filesystem);const projectConfig2=configured.projectConfig;const stack=projectConfig2?.stack;if(projectConfig2===null||stack===void 0){throw new UsageError("profile validate requires .agents/config/project.yaml")}const profile={id:stack.id,status:"supported",extensions:stack.extensions??[],defaults:{language:stack.language,api:stack.api,queryBuilder:stack.query_builder},workspaceLayout:2,conventions:{apps:stack.layout===void 0?void 0:{frontend:stack.layout.frontend,backend:stack.layout.backend,site:stack.layout.site},modules:stack.layout?.modules,packages:stack.layout?.packages,e2e:stack.layout?.e2e,source_limits:stack.source_limits},invariants:stack.invariants??[],commands:stack.commands};configuredArchitectureProfile(projectConfig2);const findings=[...validateProfileContract(profile)];const clientCatalog=parseYaml(await filesystem.readText(".agents/config/clients.yaml"));const clientPaths=await validateConfiguredProfileAgentPaths(clientCatalog,projectConfig2.clients,filesystem);findings.push(...clientPaths.findings.map(message=>({field:"clients",message})));output({valid:findings.length===0,profile:PROJECT_CONFIG_PATH,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="eval"&&["run","specs","architecture","cqrs","security","infrastructure","adapters","context"].includes(action??"")){const report=action==="run"?runAllCategoryEvals():runCategoryEval(action);const layout=await loadWorkspaceLayout(filesystem);const persisted=parsed.flags.has("no-write")?null:layout.version!==1?await persistEvalReportV2(filesystem,layout,report,action??"run",parsed):await persistEvalReport(filesystem,report,action??"run");output({...report,persisted},json2);return report.passed?EXIT2.success:EXIT2.conformity}if(V2_COMMAND_AREAS.has(area)){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){output(await runV2Command(area,action,parsed,filesystem,layout),json2);return EXIT2.success}if(["prd","execution","run-v2","plan"].includes(area)){throw new UsageError(`${area} requires a V2 workspace`)}if(!isLegacyReadOnlyCommand(area,action)){throw new UsageError("V1 lifecycle is read-only; use `migrate plan` and `migrate apply` before mutation")}}if(area==="change"&&action==="show"){output(await new ChangeRepository(filesystem).read(requiredPosition(parsed.positionals,2,"change id")),json2);return EXIT2.success}if(area==="change"&&action==="validate"){const result2=await new ChangeRepository(filesystem).validate(requiredPosition(parsed.positionals,2,"change id"));output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="spec"&&action==="show"){output(await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability")),json2);return EXIT2.success}if(area==="spec"&&action==="validate"){const result2=await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability"));output({valid:true,spec:result2.spec},json2);return EXIT2.success}if(area==="task"&&action==="list"){output(await new TaskRepository(filesystem).list(),json2);return EXIT2.success}if(area==="task"&&action==="next"){output(nextExecutableTasks(await new TaskRepository(filesystem).list()),json2);return EXIT2.success}if(area==="task"&&action==="show"){output(await new TaskRepository(filesystem).read(requiredEntityId(parsed,2,"task id")),json2);return EXIT2.success}if(area==="decision"&&action==="list"){output(await new DecisionRepository(filesystem).list(),json2);return EXIT2.success}if(area==="decision"&&action==="show"){const id=requiredPosition(parsed.positionals,2,"decision id");output(await new DecisionRepository(filesystem).read(id,id.startsWith("DEC-HUMAN-")?"human":"agent"),json2);return EXIT2.success}if(area==="run"&&action==="show"){output(await new RunRepository(filesystem).read(requiredPosition(parsed.positionals,2,"run id")),json2);return EXIT2.success}if(area==="generate"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){const tasks2=await new TaskV2Repository(filesystem,layout).list();output({generated:null,storage:"stdout",board:tasks2.map(task=>({id:task.id,title:task.title,status:task.status,priority:task.priority,artifact_path:layout.activePath("task",task.id)}))},json2);return EXIT2.success}const tasks=await new TaskRepository(filesystem).list();const board=generateBoard(tasks);output({generated:null,storage:"stdout",board},json2);return EXIT2.success}if(area==="guard"&&action==="diff"){const changed=await new ShellGit(root).changedFiles();const layout=await loadWorkspaceLayout(filesystem);const ledger=layout.version!==1?await taskLedgerV2(new TaskV2Repository(filesystem,layout),changed):await taskLedger(new TaskRepository(filesystem));const findings=guardDiff(changed,ledger);output({valid:findings.length===0,changed,ledger,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="ui"){const executable=process.argv[1];if(executable!==void 0){const executableRoot=resolve19(dirname16(executable),"..");const distributionRoot=basename6(executableRoot)===".agents"?executableRoot:resolve19(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename6(distributionRoot)===".agents"&&await new WorkspaceFileSystem(root).exists(".agents/dashboard/packages/local-runtime/start-dashboard.mjs")){output({url:"http://127.0.0.1:4317",security:"loopback-only"},json2);const code=await runUiServer(resolve19(root,".agents/dashboard/packages/local-runtime/start-dashboard.mjs"),root);return code}}output({command:"corepack pnpm dashboard:dev",sourceMode:true},json2);return EXIT2.success}throw new UsageError(`Unknown command: ${parsed.positionals.join(" ")}`)}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);output({error:message},json2,true);return error51 instanceof UsageError?EXIT2.usage:EXIT2.error}}function isLegacyReadOnlyCommand(area,action){const actions={spec:["show","validate"],change:["show","validate"],task:["list","next","show"],decision:["list","show"],run:["show"]};return actions[area]?.includes(action)??false}var HELP=helpText(CLI_DISPLAY_VERSION);var isMain=process.argv[1]!==void 0&&pathToFileURL(resolve19(process.argv[1])).href===import.meta.url;if(isMain)process.exitCode=await runCli(process.argv.slice(2));export{CLI_DISPLAY_VERSION,CLI_VERSION,EXIT2 as EXIT,runCli};