@yuanze_dev/tracker-miniprogram 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # Mini Program Click Text
2
+
3
+ Version 0.11.0 includes the runtime SDK and the Node.js 22 WXML preparation tool.
4
+ It adds optional `$text` to `$autocapture`; existing page fields are reused.
5
+
6
+ Install and lock this package, then keep the existing SDK initialization and
7
+ privacy activation flow. Registration wrappers must be installed in app.js
8
+ before Page or Component registration. Cold-compile and restart after upgrading.
9
+
10
+ ## Central Integration
11
+
12
+ Create `yuanze-text.config.json` in the developer tool project directory:
13
+
14
+ ```json
15
+ {
16
+ "sourceRoot": ".",
17
+ "outputRoot": ".yuanze-text",
18
+ "rules": [
19
+ { "file": "pages/index/index.wxml", "selector": ".entry", "textSelector": ".title" }
20
+ ]
21
+ }
22
+ ```
23
+
24
+ Rules only locate an existing label. Remove the example rule when unnecessary.
25
+ Add nonstandard runtime directories through the optional `include` array.
26
+ The default includes app files, pages, subpackages, components, utils, assets,
27
+ images, styles, behaviors and miniprogram_npm. Source symlinks are rejected.
28
+
29
+ Set `project.config.json` `miniprogramRoot` to `.yuanze-text/`.
30
+ Add the output directory to Git ignore. Run existing route generation, SDK
31
+ sync and npm component preparation before this tool:
32
+
33
+ ```sh
34
+ yuanze-miniprogram-text prepare
35
+ yuanze-miniprogram-text check
36
+ ```
37
+
38
+ Connect that same sequence to beforeCompile, beforePreview and beforeUpload.
39
+ For live editing run `yuanze-miniprogram-text watch` alongside the developer
40
+ tool. Hooks alone do not establish live synchronization. The developer tool
41
+ must allow hook execution. CI and manual upload commands must also run prepare
42
+ and check; a successful source-only compile does not validate this integration.
43
+
44
+ `analyze` reports static coverage without creating output or requiring a
45
+ changed miniprogramRoot. Device/preview/upload validation remains separate.
46
+ `check` rejects stale source, changed tool/config and modified generated files.
47
+ Generation preserves source WXML and callbacks and replaces only owned output.
48
+
49
+ ## Coverage
50
+
51
+ - Native tap, longpress and longtap with one simple label and optional icons.
52
+ - TDesign button simple slots and grid-item text properties, including bindings.
53
+ - Loop bindings at the interaction node retain their original scope.
54
+ - Central title-source rules for cards containing a title and a description.
55
+
56
+ Known TDesign adapters are resolved through usingComponents paths, including
57
+ aliases. Only generated grid-item metadata enables its custom click event.
58
+ Unknown custom click events, complex slots, descendant loops/conditions,
59
+ template composition and dynamic handler names need a separate adapter.
60
+ No input values or page/card body concatenation is performed.
61
+
62
+ The tool generates data-yz-capture, data-yz-owner, data-yz-text and optional
63
+ data-yz-adapter plus mark:yzOwner. The nearest owner handles bubbling; synchronous
64
+ forwarding uses one capture frame. Unmarked component internals remain silent.
65
+ Arbitrary asynchronous forwarding is outside this contract.
66
+
67
+ Manual exceptions can reuse an existing value in `data-yz-text="{{label}}"`.
68
+ Components also need `data-yz-capture="1"`. These reserved fields are excluded
69
+ from data-track business properties. Existing named-event suppression is kept.
70
+
71
+ Remote captureText/maxTextLength remain authoritative. The SDK snapshots before
72
+ the callback, preserves its result or exception, and discards the snapshot if
73
+ capture is deactivated during the callback. Sensitive/input regions and
74
+ data-sensitive/data-no-track/yz-no-track are excluded. The tool propagates
75
+ sensitive marks to descendants. Pure 4-8 digit labels are omitted; phone numbers,
76
+ email addresses and long numeric identifiers use existing redaction.
77
+
78
+ This tool targets native WXML. It does not establish Taro or web-view support.
@@ -0,0 +1,23 @@
1
+ @wxml/parser 0.4.0
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2021-present iChenLei<chenleicoder@gmail.com>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty;var __defProps=Object.defineProperties;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropDescs=Object.getOwnPropertyDescriptors||function(object){var descriptors={};var names=__getOwnPropNames(object);for(var index=0;index<names.length;index++){var key=names[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}if(__getOwnPropSymbols){var symbols=__getOwnPropSymbols(object);for(var index=0;index<symbols.length;index++){var key=symbols[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}}return descriptors};var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __pow=Math.pow;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var __spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b));var __objRest=(source,exclude)=>{var target={};for(var prop in source)if(__hasOwnProp.call(source,prop)&&exclude.indexOf(prop)<0)target[prop]=source[prop];if(source!=null&&__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(source)){if(exclude.indexOf(prop)<0&&__propIsEnum.call(source,prop))target[prop]=source[prop]}return target};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var __async=(__this,__arguments,generator)=>{return new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}};var rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}};var step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())})};var index_exports={};__export(index_exports,{SDK_NAME:()=>SDK_NAME2,SDK_VERSION:()=>SDK_VERSION2,SYSTEM_EVENTS:()=>SYSTEM_EVENTS,default:()=>index_default,dispose:()=>dispose,enableAutoTrack:()=>enableAutoTrack,flush:()=>flush,getTracker:()=>getTracker,identify:()=>identify,init:()=>init,installAutoTrack:()=>installAutoTrack,isSystemEvent:()=>isSystemEvent,refreshRemoteConfig:()=>refreshRemoteConfig,register:()=>register,reset:()=>reset,track:()=>track,trackTap:()=>trackTap,tracker:()=>tracker,wxEnvContext:()=>wxEnvContext,wxPersistence:()=>wxPersistence,wxSender:()=>wxSender,wxStorage:()=>wxStorage});module.exports=__toCommonJS(index_exports);function uuid(){const c=typeof globalThis==="undefined"?void 0:globalThis.crypto;if(typeof(c==null?void 0:c.randomUUID)==="function"){try{return c.randomUUID()}catch(e){}}if(typeof(c==null?void 0:c.getRandomValues)==="function"){try{const b2=c.getRandomValues(new Uint8Array(16));return formatUuid(b2)}catch(e){}}const b=new Uint8Array(16);for(let i=0;i<16;i+=1)b[i]=Math.floor(Math.random()*256);return formatUuid(b)}function formatUuid(b){b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=[];for(let i=0;i<16;i+=1){const value=b[i].toString(16);hex.push(value.length===1?`0${value}`:value)}const s=hex.join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function memoryStorage(){const m=new Map;return{get:k=>{var _a;return(_a=m.get(k))!=null?_a:null},set:(k,v)=>void m.set(k,v),remove:k=>void m.delete(k)}}function webStorage(){const mem=memoryStorage();let ls=null;try{ls=typeof localStorage!=="undefined"?localStorage:null}catch(e){ls=null}if(!ls)return mem;return{get(k){try{return ls.getItem(k)}catch(e){return mem.get(k)}},set(k,v){try{ls.setItem(k,v)}catch(e){mem.set(k,v)}},remove(k){try{ls.removeItem(k)}catch(e){mem.remove(k)}}}}var STORAGE_KEYS={anonymousId:"yz_anon",userId:"yz_uid",userUuid:"yz_user_uuid",session:"yz_session"};var SESSION_TIMEOUT_MS=30*60*1e3;var TOUCH_PERSIST_MS=60*1e3;function normalizeSnapshot(snapshot){var _a,_b,_c,_d,_e;const anonymousId=String((_a=snapshot==null?void 0:snapshot.anonymousId)!=null?_a:"").trim();const sessionId=String((_b=snapshot==null?void 0:snapshot.sessionId)!=null?_b:"").trim();const userId=String((_c=snapshot==null?void 0:snapshot.userId)!=null?_c:"").trim()||null;const userUuid=userId?String((_d=snapshot==null?void 0:snapshot.userUuid)!=null?_d:"").trim()||null:null;const distinctId=userId!=null?userId:anonymousId;const distinctIdType=userId?"user_id":"anonymous_id";if(!anonymousId||!sessionId)return null;if(String((_e=snapshot==null?void 0:snapshot.distinctId)!=null?_e:"").trim()!==distinctId)return null;if((snapshot==null?void 0:snapshot.distinctIdType)!==distinctIdType)return null;return{anonymousId,userId,userUuid,sessionId}}function dayKey(ts){const d=new Date(ts);const p=n=>n<10?`0${n}`:String(n);return`${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`}var Identity=class{constructor(store,now=Date.now,initialSnapshot){__publicField(this,"store",store);__publicField(this,"now",now);__publicField(this,"anonymousId");__publicField(this,"userId");__publicField(this,"userUuid");__publicField(this,"session");__publicField(this,"persistedAt");var _a;const initial=initialSnapshot?normalizeSnapshot(initialSnapshot):null;if(initial){this.anonymousId=initial.anonymousId;this.userId=initial.userId;this.userUuid=initial.userUuid;const at=this.now();this.session={id:initial.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot()}else{this.anonymousId=(_a=this.store.get(STORAGE_KEYS.anonymousId))!=null?_a:this.newAnonymousId();this.userId=this.store.get(STORAGE_KEYS.userId)||null;this.userUuid=this.store.get(STORAGE_KEYS.userUuid)||null;this.session=this.loadSession()}this.persistedAt=this.session.lastActive}persistSnapshot(){this.store.set(STORAGE_KEYS.anonymousId,this.anonymousId);if(this.userId)this.store.set(STORAGE_KEYS.userId,this.userId);else this.store.remove(STORAGE_KEYS.userId);if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session))}newAnonymousId(){const id=`anon_${uuid()}`;this.store.set(STORAGE_KEYS.anonymousId,id);return id}loadSession(){const raw=this.store.get(STORAGE_KEYS.session);if(raw){try{const s=JSON.parse(raw);if((s==null?void 0:s.id)&&typeof s.lastActive==="number"&&!this.expired(s,this.now()))return s}catch(e){}}return this.startSession(this.now())}expired(s,at){return at-s.lastActive>SESSION_TIMEOUT_MS||s.day!==dayKey(at)}startSession(at){const s={id:uuid(),lastActive:at,day:dayKey(at)};this.store.set(STORAGE_KEYS.session,JSON.stringify(s));this.persistedAt=at;return s}touch(){const at=this.now();if(this.expired(this.session,at)){this.session=this.startSession(at);return}this.session.lastActive=at;if(at-this.persistedAt>=TOUCH_PERSIST_MS){this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session));this.persistedAt=at}}identify(userId,options){var _a;const id=String(userId!=null?userId:"").trim();if(!id)return false;const userChanged=id!==this.userId;const uuidWasProvided=(options==null?void 0:options.userUuid)!==void 0;const nextUuid=uuidWasProvided?String((_a=options.userUuid)!=null?_a:"").trim()||null:this.userUuid;const uuidChanged=nextUuid!==this.userUuid;if(!userChanged&&!uuidChanged)return false;this.userId=id;this.store.set(STORAGE_KEYS.userId,id);this.userUuid=userChanged&&!uuidWasProvided?null:nextUuid;if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);return true}reset(anonymousId){this.userId=null;this.store.remove(STORAGE_KEYS.userId);this.userUuid=null;this.store.remove(STORAGE_KEYS.userUuid);const sharedAnonymousId=anonymousId==null?void 0:anonymousId.trim();if(sharedAnonymousId){this.anonymousId=sharedAnonymousId;this.store.set(STORAGE_KEYS.anonymousId,sharedAnonymousId)}else{this.anonymousId=this.newAnonymousId()}this.session=this.startSession(this.now())}snapshot(){var _a;return{distinctId:(_a=this.userId)!=null?_a:this.anonymousId,distinctIdType:this.userId?"user_id":"anonymous_id",anonymousId:this.anonymousId,userId:this.userId,userUuid:this.userUuid,sessionId:this.session.id}}applySnapshot(snapshot){const next=normalizeSnapshot(snapshot);if(!next)return false;const before=this.snapshot();if(before.userId!==null&&before.userId!==next.userId&&before.anonymousId===next.anonymousId)return false;const at=this.now();this.anonymousId=next.anonymousId;this.userId=next.userId;this.userUuid=next.userUuid;this.session={id:next.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot();this.persistedAt=at;const after=this.snapshot();return before.anonymousId!==after.anonymousId||before.userId!==after.userId||before.userUuid!==after.userUuid||before.sessionId!==after.sessionId}setAnonymousId(id){this.anonymousId=id;this.store.set(STORAGE_KEYS.anonymousId,id)}};var DB_NAME="yz_tracker";var STORE="queue";var DEFAULT_LIMIT=500;function openDb(dbName){return new Promise((resolve,reject)=>{const req=indexedDB.open(dbName,1);req.onupgradeneeded=()=>{const db=req.result;if(!db.objectStoreNames.contains(STORE)){db.createObjectStore(STORE,{keyPath:"eventId"}).createIndex("savedAt","savedAt")}};req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);req.onblocked=()=>reject(new Error("indexedDB blocked"))})}function indexedDbPersistence(opts={}){var _a,_b;if(typeof indexedDB==="undefined")return null;const dbName=(_a=opts.dbName)!=null?_a:DB_NAME;const limit=(_b=opts.limit)!=null?_b:DEFAULT_LIMIT;let dbPromise=null;const db=()=>{dbPromise!=null?dbPromise:dbPromise=openDb(dbName);return dbPromise};const write=fn=>__async(null,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readwrite");fn(tx.objectStore(STORE))}catch(e){}});return{load(){return __async(this,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readonly");const req=tx.objectStore(STORE).index("savedAt").getAll();const rows=yield new Promise((resolve,reject)=>{req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error)});return rows.map(r=>r.payload)}catch(e){return[]}})},add(records){void write(store=>{for(const r of records)store.put(r);const countReq=store.count();countReq.onsuccess=()=>{const over=countReq.result-limit;if(over<=0)return;let dropped=0;const cur=store.index("savedAt").openCursor();cur.onsuccess=()=>{const c=cur.result;if(!c||dropped>=over)return;c.delete();dropped+=1;c.continue()}}})},remove(eventIds){if(!eventIds.length)return;void write(store=>{for(const id of eventIds)store.delete(id)})}}}var SDK_NAME="@yuanze_dev/tracker";var SDK_VERSION="0.16.1";var PROTOCOL_VERSION=1;var MAX_BATCH_SIZE=50;var PLATFORMS=["web","pc","flutter","ios","android","miniprogram","backend","electron-renderer","electron-main","tauri-web","tauri-rust","node"];var documentPageInstanceId;function currentPageInstanceId(){if(typeof window==="undefined"||typeof document==="undefined")return void 0;documentPageInstanceId!=null?documentPageInstanceId:documentPageInstanceId=uuid();return documentPageInstanceId}var MAX_BACKOFF_MS=3e4;var Tracker=class{constructor(opts){__publicField(this,"queue",[]);__publicField(this,"timer",null);__publicField(this,"superProps",{});__publicField(this,"identity");__publicField(this,"persistence");__publicField(this,"send");__publicField(this,"endpoint");__publicField(this,"writeKey");__publicField(this,"platform");__publicField(this,"appVersion");__publicField(this,"sdkName");__publicField(this,"sdkVersion");__publicField(this,"maxBatch");__publicField(this,"flushMs");__publicField(this,"maxQueueSize");__publicField(this,"pageInstanceId");__publicField(this,"sessionAuthority");__publicField(this,"flushing",false);__publicField(this,"flushWaiters",[]);__publicField(this,"retryCount",0);__publicField(this,"configVersion",0);__publicField(this,"pageviewHandler",null);__publicField(this,"pageleaveHandler",null);__publicField(this,"diagnosticsBridge",null);__publicField(this,"disposeHandlers",[]);__publicField(this,"identityChangeHandlers",[]);var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k;this.endpoint=opts.endpoint;this.writeKey=opts.writeKey;this.platform=(_a=opts.platform)==null?void 0:_a.trim().toLowerCase();this.appVersion=opts.appVersion;this.sdkName=(_b=opts.sdkName)!=null?_b:SDK_NAME;this.sdkVersion=(_c=opts.sdkVersion)!=null?_c:SDK_VERSION;this.maxBatch=(_d=opts.maxBatch)!=null?_d:5;this.flushMs=(_e=opts.flushMs)!=null?_e:5e3;this.maxQueueSize=(_f=opts.maxQueueSize)!=null?_f:500;this.pageInstanceId=currentPageInstanceId();this.sessionAuthority=(_g=opts.sessionAuthority)!=null?_g:"local";this.send=(_h=opts.sender)!=null?_h:defaultFetchSender;this.identity=new Identity((_i=opts.storage)!=null?_i:webStorage(),Date.now,opts.initialIdentity);if(opts.distinctId&&!opts.initialIdentity)this.identity.setAnonymousId(opts.distinctId);this.superProps=__spreadValues({},(_j=opts.initialProperties)!=null?_j:{});this.persistence=opts.persistence===false?null:(_k=opts.persistence)!=null?_k:indexedDbPersistence({limit:this.maxQueueSize});void this.restore();if(this.platform&&PLATFORMS.indexOf(this.platform)<0){console.error(`[tracker] platform "${this.platform}" 不在受控端列表里,按端分析时这批数据会自成一端。可选值:${PLATFORMS.join(" / ")}(微信小程序是 miniprogram,不是 wechat)`)}if(typeof document!=="undefined"){const onVisibilityChange=()=>{if(document.visibilityState==="hidden")this.flush(true)};document.addEventListener("visibilitychange",onVisibilityChange);this.addDisposeHandler(()=>document.removeEventListener("visibilitychange",onVisibilityChange));if(typeof window!=="undefined"){const onPageHide=()=>this.flush(true);window.addEventListener("pagehide",onPageHide);this.addDisposeHandler(()=>window.removeEventListener("pagehide",onPageHide))}}}restore(){return __async(this,null,function*(){if(!this.persistence)return;const saved=yield this.persistence.load();const known=new Set(this.queue.map(e=>e.eventId));const revived=saved.filter(e=>(e==null?void 0:e.eventId)&&!known.has(e.eventId));if(!revived.length)return;this.queue.unshift(...revived);this.trim();void this.flush()})}register(props){for(const key of Object.keys(props))this.superProps[key]=props[key]}identify(id,options){const before=this.identity.snapshot();if(!this.identity.identify(id,options))return;this.enqueue("$identify",{});const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}reset(anonymousId){const before=this.identity.snapshot();this.identity.reset(anonymousId);const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}getDistinctId(){return this.identity.snapshot().distinctId}getAnonymousId(){return this.identity.snapshot().anonymousId}getSessionId(){return this.identity.snapshot().sessionId}getPageInstanceId(){return this.pageInstanceId}getIdentitySnapshot(){return this.identity.snapshot()}touchIdentity(){const before=this.identity.snapshot();if(this.sessionAuthority==="external")return before;this.identity.touch();const after=this.identity.snapshot();if(before.sessionId!==after.sessionId){for(const handler of this.identityChangeHandlers)handler(before,after)}return after}applyIdentitySnapshot(snapshot,options={}){const before=this.identity.snapshot();const changed=this.identity.applySnapshot(snapshot);if(!changed)return false;const after=this.identity.snapshot();const identityChanged=before.userId!==after.userId||before.userUuid!==after.userUuid;if(options.emitIdentify===true&&before.anonymousId===after.anonymousId&&after.userId!==null&&identityChanged){this.enqueue("$identify",{})}for(const handler of this.identityChangeHandlers)handler(before,after);return true}setConfigVersion(version){if(Number.isInteger(version)&&version>=0)this.configVersion=version}getConfigVersion(){return this.configVersion}get pending(){return this.queue.length}dispose(){if(this.timer){clearTimeout(this.timer);this.timer=null}this.diagnosticsBridge=null;for(const handler of this.disposeHandlers.splice(0))handler()}addDisposeHandler(handler){this.disposeHandlers.push(handler)}addIdentityChangeHandler(handler){this.identityChangeHandlers.push(handler);const remove=()=>{this.identityChangeHandlers=this.identityChangeHandlers.filter(candidate=>candidate!==handler)};this.addDisposeHandler(remove);return remove}setPageviewHandler(handler){this.pageviewHandler=handler}setPageleaveHandler(handler){this.pageleaveHandler=handler}setDiagnosticsBridge(bridge){this.diagnosticsBridge=bridge}captureException(error,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.captureException(error,options))!=null?_b:null}log(level,message,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.log(level,message,options))!=null?_b:null}flushDiagnostics(){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.flush())!=null?_b:Promise.resolve()}pageview(input){const url=typeof input==="string"?input:input==null?void 0:input.$url;if(this.pageviewHandler)this.pageviewHandler(url);else if(input&&typeof input==="object")this.track("$pageview",input);else if(url)this.track("$pageview",{$url:url})}pageleave(){var _a;(_a=this.pageleaveHandler)==null?void 0:_a.call(this)}track(name,properties){this.enqueue(name,properties!=null?properties:{})}trackUnsafe(name,properties={}){this.enqueue(name,properties)}captureAs(who,name,properties={},options={}){this.enqueue(name,properties,who,options)}enqueue(name,properties,override,options={}){var _a,_b,_c,_d;const who=override!=null?override:this.touchIdentity();const raw={eventId:(_a=options.eventId)!=null?_a:uuid(),eventName:name,distinctId:who.distinctId,distinctIdType:who.distinctIdType,anonymousId:who.anonymousId,userId:(_b=who.userId)!=null?_b:void 0,userUuid:(_c=who.userUuid)!=null?_c:void 0,sessionId:who.sessionId,pageInstanceId:this.pageInstanceId,platform:this.platform,appVersion:this.appVersion,clientTime:new Date().toISOString(),properties:__spreadProps(__spreadValues(__spreadValues({},this.superProps),properties),{$sdk_name:this.sdkName,$sdk_version:this.sdkVersion,$protocol_version:PROTOCOL_VERSION,$config_version:this.configVersion})};this.queue.push(raw);(_d=this.persistence)==null?void 0:_d.add([{eventId:raw.eventId,savedAt:Date.now(),payload:raw}]);this.trim();if(this.queue.length>=this.maxBatch)this.flush();else this.schedule()}trim(){var _a;const overflow=this.queue.length-this.maxQueueSize;if(overflow>0){const dropped=this.queue.splice(0,overflow);(_a=this.persistence)==null?void 0:_a.remove(dropped.map(e=>e.eventId));console.warn(`[tracker] 队列超过 ${this.maxQueueSize} 条,丢弃最旧的 ${overflow} 条`)}}schedule(delayMs=this.flushMs){if(this.timer)return;this.timer=setTimeout(()=>this.flush(),delayMs)}flush(unloading=false){return __async(this,null,function*(){var _a,_b;if(this.timer){clearTimeout(this.timer);this.timer=null}if(this.flushing&&!unloading){yield new Promise(resolve=>this.flushWaiters.push(resolve));if(this.queue.length>0)yield this.flush();return}if(this.queue.length===0)return;this.flushing=true;const batch=this.queue.splice(0,Math.min(MAX_BATCH_SIZE,this.queue.length));const body=JSON.stringify({events:batch,protocolVersion:PROTOCOL_VERSION});const headers={"Content-Type":"application/json","x-write-key":this.writeKey};try{yield this.send(this.endpoint,body,headers,unloading);(_a=this.persistence)==null?void 0:_a.remove(batch.map(e=>e.eventId));this.retryCount=0}catch(err){if((err==null?void 0:err.retryable)!==false){this.queue.unshift(...batch);this.trim();this.retryCount+=1}else{console.warn("[tracker] 丢弃一批(不可重试):",err==null?void 0:err.status);(_b=this.persistence)==null?void 0:_b.remove(batch.map(e=>e.eventId));this.retryCount=0}}finally{this.flushing=false;for(const resolve of this.flushWaiters.splice(0))resolve()}if(this.queue.length>0&&!unloading){this.schedule(Math.min(this.flushMs*__pow(2,this.retryCount),MAX_BACKOFF_MS))}})}};var defaultFetchSender=(endpoint,body,headers,keepalive)=>__async(null,null,function*(){const res=yield fetch(endpoint,{method:"POST",headers,body,keepalive});if(!res.ok){const e=new Error(`HTTP ${res.status}`);e.status=res.status;e.retryable=res.status>=500||res.status===429;throw e}});var DEFAULT_CAPTURE_SETTINGS={captureClicks:true,captureText:true,maxTextLength:64,sampleRate:1,allowSelectors:["a","button",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','input[type="submit"]','input[type="button"]',"summary"],denySelectors:["[data-no-track]",".yz-no-track"],captureHref:true,captureTitle:true,captureAriaLabel:true,captureRole:true,captureName:true,captureId:true,captureDataTestId:true,capturePageviews:true,capturePageleave:true,capturePageDuration:true,captureVisibleDuration:false};var bool=v=>typeof v==="boolean";var number=(v,min,max)=>typeof v==="number"&&Number.isFinite(v)&&v>=min&&v<=max;var strings=v=>Array.isArray(v)&&v.length<=50&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=256);var integer=(v,min,max)=>number(v,min,max)&&Number.isInteger(v);var stringList=(v,maxItems,maxLength)=>Array.isArray(v)&&v.length<=maxItems&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=maxLength);var object=v=>v&&typeof v==="object"&&!Array.isArray(v)?v:{};function isValidHttpsOrigin(value){if(typeof value!=="string")return false;try{const url=new URL(value);return url.protocol==="https:"&&url.origin===value}catch(e){return false}}function parseReplayConfig(input){var _a,_b,_c;if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const appVersions=object(settings.appVersions);const errorSampling=object(settings.errorSampling);const recording=object(settings.recording);const pages=object(settings.pages);const privacy=object(settings.privacy);const capture=object(settings.capture);const upload=object(settings.upload);const legacyQuota=object(settings.quota);const maxSessionBytes=(_a=settings.maxSessionBytes)!=null?_a:legacyQuota.maxSessionBytes;const uploadOrigins=(_b=raw.uploadOrigins)!=null?_b:[];const checkpointMaxBytes=(_c=recording.checkpointMaxBytes)!=null?_c:4*1024*1024;if(!bool(raw.enabled)||!bool(raw.supported)||raw.recorderKind!=="rrweb"||raw.replayFormat!=="rrweb-v1"||typeof raw.samplingSalt!=="string"||!stringList(uploadOrigins,10,512)||!uploadOrigins.every(isValidHttpsOrigin)||!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!bool(settings.enabled)||!bool(settings.emergencyDisabled)||!number(settings.sampleRate,0,1)||!stringList(appVersions.include,100,100)||!stringList(appVersions.exclude,100,100)||!bool(errorSampling.enabled)||errorSampling.mode!=="after-error"&&errorSampling.mode!=="rolling-buffer"||!integer(errorSampling.rollingBufferSeconds,5,120)||!integer(recording.maxSessionMinutes,1,720)||!integer(recording.maxEvents,100,2e6)||!integer(recording.chunkSeconds,2,60)||!integer(recording.chunkMaxBytes,64*1024,2*1024*1024)||!integer(checkpointMaxBytes,256*1024,16*1024*1024)||!integer(recording.checkpointSeconds,10,120)||!integer(recording.localQueueMaxBytes,1024*1024,200*1024*1024)||!integer(recording.stopAfterBackgroundMinutes,1,120)||!stringList(pages.include,50,512)||!stringList(pages.exclude,100,512)||!bool(privacy.maskAllInputs)||!stringList(privacy.maskSelectors,100,256)||!stringList(privacy.blockSelectors,100,256)||!stringList(privacy.redactUrlParams,100,100)||!bool(capture.canvas)||!bool(capture.inlineImages)||!bool(capture.collectFonts)||!bool(capture.crossOriginIframes)||!integer(upload.concurrency,1,6)||!integer(upload.timeoutSeconds,5,120)||!integer(upload.maxRetries,0,12)||!integer(upload.retryBaseMs,100,1e4)||!integer(upload.localRetryDays,1,30)||!integer(maxSessionBytes,1024*1024,2*1024*1024*1024))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,recorderKind:"rrweb",replayFormat:"rrweb-v1",uploadOrigins,samplingSalt:raw.samplingSalt,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{enabled:settings.enabled,emergencyDisabled:settings.emergencyDisabled,sampleRate:settings.sampleRate,appVersions:{include:appVersions.include,exclude:appVersions.exclude},errorSampling:{enabled:errorSampling.enabled,mode:errorSampling.mode,rollingBufferSeconds:errorSampling.rollingBufferSeconds},recording:{maxSessionMinutes:recording.maxSessionMinutes,maxEvents:recording.maxEvents,chunkSeconds:recording.chunkSeconds,chunkMaxBytes:recording.chunkMaxBytes,checkpointMaxBytes,checkpointSeconds:recording.checkpointSeconds,localQueueMaxBytes:recording.localQueueMaxBytes,stopAfterBackgroundMinutes:recording.stopAfterBackgroundMinutes},pages:{include:pages.include,exclude:pages.exclude},privacy:{maskAllInputs:privacy.maskAllInputs,maskSelectors:privacy.maskSelectors,blockSelectors:privacy.blockSelectors,redactUrlParams:privacy.redactUrlParams},capture:{canvas:capture.canvas,inlineImages:capture.inlineImages,collectFonts:capture.collectFonts,crossOriginIframes:capture.crossOriginIframes},upload:{concurrency:upload.concurrency,timeoutSeconds:upload.timeoutSeconds,maxRetries:upload.maxRetries,retryBaseMs:upload.retryBaseMs,localRetryDays:upload.localRetryDays},maxSessionBytes}}}var DIAGNOSTIC_LEVELS=new Set(["debug","info","warn","error","fatal"]);function parseDiagnosticsConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const errors=object(settings.errors);const logs=object(settings.logs);const context=object(settings.context);const upload=object(settings.upload);const privacy=object(settings.privacy);const levels=logs.levels;if(!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!bool(raw.enabled)||!bool(raw.supported)||typeof raw.endpointPath!=="string"||!raw.endpointPath.startsWith("/")||raw.endpointPath.length>512||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!number(errors.sampleRate,0,1)||!bool(errors.captureUnhandled)||!bool(errors.captureHandled)||!Array.isArray(levels)||levels.length>5||!levels.every(level=>typeof level==="string"&&DIAGNOSTIC_LEVELS.has(level))||new Set(levels).size!==levels.length||!number(logs.sampleRate,0,1)||!integer(context.windowSeconds,5,300)||!integer(context.maxEntries,10,200)||!integer(context.maxBytes,16*1024,1024*1024)||!integer(upload.batchSize,1,100)||!integer(upload.batchMaxBytes,16*1024,1024*1024)||!integer(upload.flushMs,500,6e4)||!integer(upload.timeoutMs,1e3,3e4)||!integer(upload.maxRetries,0,12)||!integer(upload.offlineMaxBytes,256*1024,50*1024*1024)||!integer(upload.offlineTtlHours,1,168)||!integer(privacy.maxMessageBytes,128,4096)||!integer(privacy.maxStackBytes,4096,256*1024)||!stringList(privacy.denyKeys,100,128)||!stringList(privacy.redactUrlParams,100,128))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,endpointPath:raw.endpointPath,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{errors:{sampleRate:errors.sampleRate,captureUnhandled:errors.captureUnhandled,captureHandled:errors.captureHandled},logs:{levels:[...levels],sampleRate:logs.sampleRate},context:{windowSeconds:context.windowSeconds,maxEntries:context.maxEntries,maxBytes:context.maxBytes},upload:{batchSize:upload.batchSize,batchMaxBytes:upload.batchMaxBytes,flushMs:upload.flushMs,timeoutMs:upload.timeoutMs,maxRetries:upload.maxRetries,offlineMaxBytes:upload.offlineMaxBytes,offlineTtlHours:upload.offlineTtlHours},privacy:{maxMessageBytes:privacy.maxMessageBytes,maxStackBytes:privacy.maxStackBytes,denyKeys:[...privacy.denyKeys],redactUrlParams:[...privacy.redactUrlParams]}}}}function parseRemoteConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const c=raw.config;if(!c||typeof c!=="object")return null;const config=c;const candidate={captureClicks:config.captureClicks,captureText:config.captureText,maxTextLength:config.maxTextLength,sampleRate:config.sampleRate,allowSelectors:config.allowSelectors,denySelectors:config.denySelectors,captureHref:config.captureHref,captureTitle:config.captureTitle===void 0?true:config.captureTitle,captureAriaLabel:config.captureAriaLabel,captureRole:config.captureRole,captureName:config.captureName,captureId:config.captureId,captureDataTestId:config.captureDataTestId,capturePageviews:config.capturePageviews,capturePageleave:config.capturePageleave,capturePageDuration:config.capturePageDuration,captureVisibleDuration:config.captureVisibleDuration};const valid=bool(raw.enabled)&&number(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.schemaVersion)&&number(raw.configVersion,0,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.configVersion)&&typeof raw.platform==="string"&&number(raw.refreshIntervalSeconds,5,3600)&&bool(candidate.captureClicks)&&bool(candidate.captureText)&&number(candidate.maxTextLength,0,512)&&Number.isInteger(candidate.maxTextLength)&&number(candidate.sampleRate,0,1)&&strings(candidate.allowSelectors)&&strings(candidate.denySelectors)&&bool(candidate.captureHref)&&bool(candidate.captureTitle)&&bool(candidate.captureAriaLabel)&&bool(candidate.captureRole)&&bool(candidate.captureName)&&bool(candidate.captureId)&&bool(candidate.captureDataTestId)&&bool(candidate.capturePageviews)&&bool(candidate.capturePageleave)&&bool(candidate.capturePageDuration)&&bool(candidate.captureVisibleDuration);if(!valid)return null;const replay=parseReplayConfig(raw.replay);const diagnostics=parseDiagnosticsConfig(raw.diagnostics);return __spreadValues(__spreadValues({schemaVersion:raw.schemaVersion,configVersion:raw.configVersion,enabled:raw.enabled,platform:raw.platform,refreshIntervalSeconds:raw.refreshIntervalSeconds,config:candidate},raw.replay===void 0?{}:{replay}),raw.diagnostics===void 0?{}:{diagnostics})}function deriveConfigEndpoint(trackEndpoint){try{const base=typeof location!=="undefined"?location.href:void 0;const url=new URL(trackEndpoint,base);url.pathname=url.pathname.replace(/\/api\/v1\/track\/?$/,"/api/v1/config");url.search="";url.hash="";return url.toString()}catch(e){return trackEndpoint.replace(/\/api\/v1\/track\/?$/,"/api/v1/config")}}function coerceDatasetValue(raw){if(raw===void 0)return void 0;if(raw==="true")return true;if(raw==="false")return false;if(raw==="")return raw;const n=Number(raw);return Number.isFinite(n)&&String(n)===raw?n:raw}var wxSender=(endpoint,body,headers)=>new Promise((resolve,reject)=>{wx.request({url:endpoint,method:"POST",header:headers,data:body,timeout:1e4,success:res=>{if(res.statusCode>=200&&res.statusCode<300)return resolve();const e=new Error(`HTTP ${res.statusCode}`);e.status=res.statusCode;e.retryable=res.statusCode>=500||res.statusCode===429;reject(e)},fail:err=>{const e=new Error(err.errMsg);e.retryable=true;reject(e)}})});function wxStorage(){return{get(key){try{const v=wx.getStorageSync(key);return typeof v==="string"&&v?v:null}catch(e){return null}},set(key,value){try{wx.setStorageSync(key,value)}catch(e){}},remove(key){try{wx.removeStorageSync(key)}catch(e){}}}}var QUEUE_PREFIX="yz_q_";function imul32(a,b){if(typeof Math.imul==="function")return Math.imul(a,b);const ah=a>>>16&65535;const al=a&65535;const bh=b>>>16&65535;const bl=b&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0}function stableRuntimeHash(value){let hash=2166136261;for(let index=0;index<value.length;index+=1){hash^=value.charCodeAt(index);hash=imul32(hash,16777619)}return(hash>>>0).toString(16)}function storageNamespace(endpoint,writeKey){return`yz_mp_${stableRuntimeHash(`${endpoint}|${writeKey}`)}_`}function scopedWxStorage(endpoint,writeKey){const storage=wxStorage();const namespace=storageNamespace(endpoint,writeKey);return{get:key=>storage.get(namespace+key),set:(key,value)=>storage.set(namespace+key,value),remove:key=>storage.remove(namespace+key)}}function createWxPersistence(limit,queuePrefix){let known=-1;const keys=()=>{try{return wx.getStorageInfoSync().keys.filter(k=>k.slice(0,queuePrefix.length)===queuePrefix)}catch(e){return[]}};const readAll=()=>{const out=[];for(const k of keys()){try{const r=wx.getStorageSync(k);if(r==null?void 0:r.eventId)out.push(r)}catch(e){}}return out.sort((a,b)=>a.savedAt-b.savedAt)};return{load(){return __async(this,null,function*(){const all=readAll();known=all.length;return all.map(r=>r.payload)})},add(records){for(const r of records){try{wx.setStorageSync(queuePrefix+r.eventId,r)}catch(e){}}known=known<0?keys().length:known+records.length;if(known<=limit)return;const all=readAll();for(const r of all.slice(0,all.length-limit)){try{wx.removeStorageSync(queuePrefix+r.eventId)}catch(e){}}known=Math.min(all.length,limit)},remove(eventIds){for(const id of eventIds){try{wx.removeStorageSync(queuePrefix+id)}catch(e){}}if(known>0)known=Math.max(0,known-eventIds.length)}}}function wxPersistence(limit=500){return createWxPersistence(limit,QUEUE_PREFIX)}function scopedWxPersistence(endpoint,writeKey,limit=500){return createWxPersistence(limit,`${storageNamespace(endpoint,writeKey)}q_`)}function miniProgramDeviceType(deviceType,model){const normalized=deviceType==null?void 0:deviceType.trim().toLowerCase();if(normalized==="phone")return"mobile";if(normalized==="pad"||normalized==="tablet")return"tablet";if(normalized==="pc")return"desktop";const normalizedModel=model==null?void 0:model.trim();if(!normalizedModel)return null;if(/\b(?:ipad|tablet)\b/i.test(normalizedModel))return"tablet";if(/(?:^|[\s_-])pad(?:$|[\s_-])/i.test(normalizedModel))return"tablet";return null}function wxEnvContext(){try{const i=wx.getSystemInfoSync();const ctx={$runtime:"miniprogram"};const deviceType=miniProgramDeviceType(i.deviceType,i.model);if(deviceType)ctx.$device_type=deviceType;if(i.system)ctx.$os=i.system;if(i.model)ctx.$device_model=i.model;if(i.brand)ctx.$device_brand=i.brand;if(i.SDKVersion)ctx.$mp_sdk_version=i.SDKVersion;if(i.version)ctx.$wechat_version=i.version;return ctx}catch(e){return{$runtime:"miniprogram"}}}var SYSTEM_EVENTS=["$app_start","$app_foreground","$app_background","$pageview","$pageleave","$autocapture","$identify","$replay_diagnostic","$replay_focus","$experiment_exposure"];var isSystemEvent=name=>SYSTEM_EVENTS.includes(name);var SDK_NAME2="@yuanze_dev/tracker-miniprogram";var SDK_VERSION2="0.10.1";var instance=null;var captureSettings=DEFAULT_CAPTURE_SETTINGS;var captureEnabled=true;var configEtag;var configTimer=null;var configStorage=null;var configOptions=true;var configEndpoint="";var configWriteKey="";var configGeneration=0;var configRequest=null;function configCacheKey(writeKey){return`yz_capture_config_${stableRuntimeHash(writeKey)}_mini_program`}function applyRemoteConfig(payload){const runtime=autoTrackRuntimeSlot();if(runtime&&(payload.enabled!==captureEnabled||payload.config.capturePageviews!==captureSettings.capturePageviews||payload.config.capturePageleave!==captureSettings.capturePageleave||payload.config.capturePageDuration!==captureSettings.capturePageDuration||payload.config.captureVisibleDuration!==captureSettings.captureVisibleDuration)){advanceCaptureEpoch(runtime)}captureSettings=payload.config;captureEnabled=payload.enabled;instance==null?void 0:instance.setConfigVersion(payload.configVersion)}function loadCachedRemoteConfig(){try{const raw=configStorage==null?void 0:configStorage.get(configCacheKey(configWriteKey));if(!raw)return;const cached=JSON.parse(raw);const payload=parseRemoteConfig(cached.payload);if(!payload||payload.platform!=="mini-program")return;configEtag=cached.etag;applyRemoteConfig(payload)}catch(e){}}function refreshRemoteConfig(){if(configOptions===false||!configEndpoint||!configWriteKey)return Promise.resolve();if(configRequest)return configRequest;if(configTimer){clearTimeout(configTimer);configTimer=null}const options=typeof configOptions==="object"?configOptions:{};const generation=configGeneration;const endpoint=configEndpoint;const writeKey=configWriteKey;const storage=configStorage;const etag=configEtag;const request=new Promise(resolve=>{var _a,_b;let settled=false;const complete=()=>{var _a2;if(settled)return;settled=true;if(generation===configGeneration&&configOptions!==false){configTimer=setTimeout(()=>{void refreshRemoteConfig()},(_a2=options.refreshMs)!=null?_a2:45e3)}resolve()};try{const url=`${(_a=options.endpoint)!=null?_a:endpoint}?platform=mini-program`;wx.request({url,method:"GET",header:__spreadValues({"x-write-key":writeKey},etag?{"If-None-Match":etag}:{}),timeout:(_b=options.timeoutMs)!=null?_b:3e3,success:res=>{var _a2,_b2,_c;if(generation!==configGeneration)return;try{if(res.statusCode===304)return;if(res.statusCode<200||res.statusCode>=300)return;let data=res.data;if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){return}}const payload=parseRemoteConfig(data);if(!payload||payload.platform!=="mini-program")return;configEtag=(_c=(_a2=res.header)==null?void 0:_a2.ETag)!=null?_c:(_b2=res.header)==null?void 0:_b2.etag;storage==null?void 0:storage.set(configCacheKey(writeKey),JSON.stringify({etag:configEtag,savedAt:Date.now(),payload}));applyRemoteConfig(payload)}catch(e){}},fail:complete,complete})}catch(e){complete()}});const cleanup=()=>{if(configRequest===tracked)configRequest=null};const tracked=request.then(cleanup,cleanup);configRequest=tracked;return tracked}function dispose(){configGeneration+=1;if(configTimer){clearTimeout(configTimer);configTimer=null}configRequest=null;configOptions=false;configEndpoint="";configWriteKey="";configEtag=void 0;configStorage=null;captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;const current=instance;instance=null;current==null?void 0:current.dispose();disableOwnedAutoTrackRuntime()}function init(options){var _b;dispose();const _a=options,{envContext=true,persist=true,autoTrack=true,remoteConfig=true}=_a,rest=__objRest(_a,["envContext","persist","autoTrack","remoteConfig"]);configStorage=wxStorage();const identityStorage=scopedWxStorage(rest.endpoint,rest.writeKey);instance=new Tracker(__spreadProps(__spreadValues({},rest),{platform:"miniprogram",sdkName:SDK_NAME2,sdkVersion:SDK_VERSION2,sender:wxSender,storage:identityStorage,persistence:persist?scopedWxPersistence(rest.endpoint,rest.writeKey,(_b=rest.maxQueueSize)!=null?_b:500):false}));if(envContext)instance.register(wxEnvContext());captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;configEtag=void 0;configOptions=remoteConfig;configEndpoint=deriveConfigEndpoint(rest.endpoint);configWriteKey=rest.writeKey;if(remoteConfig!==false)loadCachedRemoteConfig();if(autoTrack)enableAutoTrack();else bindAutoTrackRuntime(false);if(remoteConfig!==false)void refreshRemoteConfig();return instance}function getTracker(){return instance}function ensure(){if(!instance)throw new Error("tracker 未初始化,请先在 app.js 里调用 init()");return instance}function track(name,properties={}){ensure().trackUnsafe(name,properties)}function register(props){ensure().register(props)}function identify(id,options){ensure().identify(id,options)}function reset(){ensure().reset()}function flush(){return ensure().flush()}function trackTap(e){var _a,_b;const ds=(_b=(_a=e==null?void 0:e.currentTarget)==null?void 0:_a.dataset)!=null?_b:{};const name=ds.track;if(typeof name!=="string"||!name)return;const props={};for(const k of Object.keys(ds)){if(k==="track")continue;const v=ds[k];props[k]=typeof v==="string"?coerceDatasetValue(v):v}instance==null?void 0:instance.trackUnsafe(name,props)}var AUTO_TRACK_RUNTIME_KEY="__yz_tracker_miniprogram_auto_track_runtime__";var MODULE_RUNTIME_OWNER={};var FALLBACK_RUNTIME_ROOT={};function runtimeRoot(){if(typeof globalThis!=="undefined"){return globalThis}if(typeof wx==="object"&&wx){return wx}return FALLBACK_RUNTIME_ROOT}function autoTrackRuntimeSlot(){var _a;return(_a=runtimeRoot()[AUTO_TRACK_RUNTIME_KEY])!=null?_a:null}function advanceCaptureEpoch(runtime){runtime.epoch=Number.isFinite(runtime.epoch)?runtime.epoch+1:1}function disableOwnedAutoTrackRuntime(){const runtime=autoTrackRuntimeSlot();if((runtime==null?void 0:runtime.owner)===MODULE_RUNTIME_OWNER&&runtime.enabled){runtime.enabled=false;advanceCaptureEpoch(runtime)}}function bindAutoTrackRuntime(enabled){var _a,_b;const root=runtimeRoot();const runtime=(_a=autoTrackRuntimeSlot())!=null?_a:{owner:null,enabled:false,epoch:0,disposeOwner:null,captureState:()=>({enabled:false,epoch:0,settings:DEFAULT_CAPTURE_SETTINGS}),captureInteraction:()=>void 0,track:()=>void 0,flush:()=>void 0,refresh:()=>void 0};if(runtime.owner&&runtime.owner!==MODULE_RUNTIME_OWNER){try{(_b=runtime.disposeOwner)==null?void 0:_b.call(runtime)}catch(e){}}if(!Number.isFinite(runtime.epoch))runtime.epoch=0;runtime.owner=MODULE_RUNTIME_OWNER;if(runtime.enabled!==enabled){runtime.enabled=enabled;advanceCaptureEpoch(runtime)}runtime.disposeOwner=dispose;runtime.captureState=()=>({enabled:runtime.enabled&&captureEnabled,epoch:runtime.epoch,settings:captureSettings});runtime.captureInteraction=(self,event)=>{if(runtime.enabled)captureInteraction(self,event)};runtime.track=(name,properties)=>{if(runtime.enabled)instance==null?void 0:instance.trackUnsafe(name,properties)};runtime.flush=()=>{if(runtime.enabled)void(instance==null?void 0:instance.flush(true))};runtime.refresh=()=>{if(runtime.enabled)void refreshRemoteConfig()};root[AUTO_TRACK_RUNTIME_KEY]=runtime;return runtime}var PAGE_LIFECYCLE_HOOKS=new Set(["onLoad","onShow","onReady","onHide","onUnload","onPullDownRefresh","onReachBottom","onShareAppMessage","onShareTimeline","onAddToFavorites","onPageScroll","onResize","onTabItemTap","onSaveExitState"]);var INTERACTION_WRAPPED="__yz_tracker_interaction_wrapped__";var LIFECYCLE_WRAPPED="__yz_tracker_lifecycle_wrapped__";function routeOf(self){var _a,_b;const direct=(_a=self==null?void 0:self.route)!=null?_a:self==null?void 0:self.__route__;if(direct)return direct;try{if(typeof getCurrentPages==="function"){const pages=getCurrentPages();const current=(_b=pages[pages.length-1])==null?void 0:_b.route;if(current)return current}}catch(e){}const componentPath=self==null?void 0:self.is;return componentPath?`miniprogram://component/${componentPath}`:"miniprogram://app"}var SENSITIVE_TARGET=/(?:^|[-_:])(captcha\d*|verify|verification|otp|password|passwd|credential)(?:$|[-_:])/i;var SENSITIVE_DATASET_KEYS=["sensitive","noTrack","yzSensitive","yzNoTrack","trackSensitive"];function isSensitiveInteraction(target){if(!target)return false;if(typeof target.id==="string"&&SENSITIVE_TARGET.test(target.id))return true;const dataset=target.dataset;return!!dataset&&SENSITIVE_DATASET_KEYS.some(key=>Object.prototype.hasOwnProperty.call(dataset,key))}function captureInteraction(self,event){var _a,_b;if(!captureEnabled||!captureSettings.captureClicks||!event)return;if(event.type!=="tap"&&event.type!=="longpress"&&event.type!=="longtap")return;const target=event.currentTarget;if(isSensitiveInteraction(target))return;const dataset=(_a=target==null?void 0:target.dataset)!=null?_a:{};if(typeof dataset.track==="string"&&dataset.track)return;const id=typeof(target==null?void 0:target.id)==="string"&&target.id?target.id:void 0;const route=routeOf(self);const componentPath=self==null?void 0:self.is;const pageRoute=(_b=self==null?void 0:self.route)!=null?_b:self==null?void 0:self.__route__;if(componentPath&&!pageRoute)return;instance==null?void 0:instance.track("$autocapture",__spreadValues({$tag:"miniprogram",$selector:id?`#${id}`:`miniprogram:${route}`,$url:route,$role:event.type==="tap"?"tap":"longpress"},id?{$element_id:id}:{}))}function wrapInteractionMethods(methods,runtime,ignored=new Set){for(const name of Object.keys(methods)){const value=methods[name];if(ignored.has(name)||typeof value!=="function")continue;if(value[INTERACTION_WRAPPED])continue;const wrapped=function(...args){try{return value.apply(this,args)}finally{try{runtime.captureInteraction(this,args[0])}catch(e){}}};Object.defineProperty(wrapped,INTERACTION_WRAPPED,{value:true});methods[name]=wrapped}}function wrapPageInteractions(options,runtime){wrapInteractionMethods(options,runtime,PAGE_LIFECYCLE_HOOKS)}function wrap(hooks,name,extra){const original=hooks[name];if(typeof original==="function"&&original[LIFECYCLE_WRAPPED])return;const wrapped=function(...args){try{extra(this,args)}catch(e){}return typeof original==="function"?original.apply(this,args):void 0};Object.defineProperty(wrapped,LIFECYCLE_WRAPPED,{value:true});hooks[name]=wrapped}function installAutoTrackRuntime(enabled){const runtime=bindAutoTrackRuntime(enabled);if(typeof Page==="function"&&!Page.__yzAutoTrack){const originalPage=Page;const patched=(options=>{const enteredAt=new WeakMap;try{wrap(options,"onShow",self=>{const capture=runtime.captureState();if(!capture.enabled||!capture.settings.capturePageviews)return;enteredAt.set(self,{at:Date.now(),epoch:capture.epoch});runtime.track("$pageview",{$url:routeOf(self)})});wrap(options,"onHide",self=>{const entry=enteredAt.get(self);if(!entry)return;enteredAt.delete(self);const capture=runtime.captureState();if(!capture.enabled||capture.epoch!==entry.epoch||!capture.settings.capturePageleave)return;runtime.track("$pageleave",__spreadValues({$url:routeOf(self)},capture.settings.capturePageDuration?{$duration_ms:Date.now()-entry.at}:{}))});wrap(options,"onUnload",self=>{const entry=enteredAt.get(self);if(!entry)return;enteredAt.delete(self);const capture=runtime.captureState();if(!capture.enabled||capture.epoch!==entry.epoch||!capture.settings.capturePageleave)return;runtime.track("$pageleave",__spreadValues({$url:routeOf(self)},capture.settings.capturePageDuration?{$duration_ms:Date.now()-entry.at}:{}))});wrapPageInteractions(options,runtime)}catch(e){}return originalPage(options)});for(const key of Object.keys(originalPage))patched[key]=originalPage[key];patched.__yzAutoTrack=true;try{Page=patched}catch(e){}}if(typeof App==="function"&&!App.__yzAutoTrack){const originalApp=App;const patched=(options=>{let launched=false;let foreground=false;let foregroundAt=Date.now();let foregroundEpoch=null;try{wrap(options,"onLaunch",(_self,args)=>{var _a;const launch=(_a=args[0])!=null?_a:{};const capture=runtime.captureState();launched=true;if(!capture.enabled){foreground=false;foregroundEpoch=null;return}foreground=true;foregroundAt=Date.now();foregroundEpoch=capture.epoch;runtime.track("$app_start",__spreadValues(__spreadValues({},typeof launch.scene==="number"?{$scene:launch.scene}:{}),typeof launch.path==="string"&&launch.path?{$path:launch.path}:{}))});wrap(options,"onHide",()=>{const capture=runtime.captureState();if(foreground&&capture.enabled&&foregroundEpoch===capture.epoch){runtime.track("$app_background",{$duration_ms:Math.max(0,Date.now()-foregroundAt),$state:"hidden"})}foreground=false;foregroundEpoch=null;runtime.flush()});wrap(options,"onShow",(_self,args)=>{var _a;const show=(_a=args[0])!=null?_a:{};const capture=runtime.captureState();if(!capture.enabled){foreground=false;foregroundEpoch=null;return}if(launched&&(!foreground||foregroundEpoch!==capture.epoch)){runtime.track("$app_foreground",__spreadProps(__spreadValues(__spreadValues({},typeof show.scene==="number"?{$scene:show.scene}:{}),typeof show.path==="string"&&show.path?{$path:show.path}:{}),{$previous_state:"hidden"}))}foreground=true;foregroundAt=Date.now();foregroundEpoch=capture.epoch;runtime.refresh()})}catch(e){}return originalApp(options)});for(const key of Object.keys(originalApp))patched[key]=originalApp[key];patched.__yzAutoTrack=true;try{App=patched}catch(e){}}}function installAutoTrack(){installAutoTrackRuntime(false)}function enableAutoTrack(){installAutoTrackRuntime(true)}var tracker={init,getTracker,track,register,identify,reset,flush,dispose,trackTap,installAutoTrack,enableAutoTrack,refreshRemoteConfig};var index_default=tracker;
1
+ "use strict";var __defProp=Object.defineProperty;var __defProps=Object.defineProperties;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropDescs=Object.getOwnPropertyDescriptors||function(object){var descriptors={};var names=__getOwnPropNames(object);for(var index=0;index<names.length;index++){var key=names[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}if(__getOwnPropSymbols){var symbols=__getOwnPropSymbols(object);for(var index=0;index<symbols.length;index++){var key=symbols[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}}return descriptors};var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __pow=Math.pow;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var __spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b));var __objRest=(source,exclude)=>{var target={};for(var prop in source)if(__hasOwnProp.call(source,prop)&&exclude.indexOf(prop)<0)target[prop]=source[prop];if(source!=null&&__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(source)){if(exclude.indexOf(prop)<0&&__propIsEnum.call(source,prop))target[prop]=source[prop]}return target};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var __async=(__this,__arguments,generator)=>{return new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}};var rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}};var step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())})};var index_exports={};__export(index_exports,{SDK_NAME:()=>SDK_NAME2,SDK_VERSION:()=>SDK_VERSION2,SYSTEM_EVENTS:()=>SYSTEM_EVENTS,default:()=>index_default,dispose:()=>dispose,enableAutoTrack:()=>enableAutoTrack,flush:()=>flush,getTracker:()=>getTracker,identify:()=>identify,init:()=>init,installAutoTrack:()=>installAutoTrack,isSystemEvent:()=>isSystemEvent,refreshRemoteConfig:()=>refreshRemoteConfig,register:()=>register,reset:()=>reset,track:()=>track,trackTap:()=>trackTap,tracker:()=>tracker,wxEnvContext:()=>wxEnvContext,wxPersistence:()=>wxPersistence,wxSender:()=>wxSender,wxStorage:()=>wxStorage});module.exports=__toCommonJS(index_exports);function uuid(){const c=typeof globalThis==="undefined"?void 0:globalThis.crypto;if(typeof(c==null?void 0:c.randomUUID)==="function"){try{return c.randomUUID()}catch(e){}}if(typeof(c==null?void 0:c.getRandomValues)==="function"){try{const b2=c.getRandomValues(new Uint8Array(16));return formatUuid(b2)}catch(e){}}const b=new Uint8Array(16);for(let i=0;i<16;i+=1)b[i]=Math.floor(Math.random()*256);return formatUuid(b)}function formatUuid(b){b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=[];for(let i=0;i<16;i+=1){const value=b[i].toString(16);hex.push(value.length===1?`0${value}`:value)}const s=hex.join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function memoryStorage(){const m=new Map;return{get:k=>{var _a;return(_a=m.get(k))!=null?_a:null},set:(k,v)=>void m.set(k,v),remove:k=>void m.delete(k)}}function webStorage(){const mem=memoryStorage();let ls=null;try{ls=typeof localStorage!=="undefined"?localStorage:null}catch(e){ls=null}if(!ls)return mem;return{get(k){try{return ls.getItem(k)}catch(e){return mem.get(k)}},set(k,v){try{ls.setItem(k,v)}catch(e){mem.set(k,v)}},remove(k){try{ls.removeItem(k)}catch(e){mem.remove(k)}}}}var STORAGE_KEYS={anonymousId:"yz_anon",userId:"yz_uid",userUuid:"yz_user_uuid",session:"yz_session"};var SESSION_TIMEOUT_MS=30*60*1e3;var TOUCH_PERSIST_MS=60*1e3;function normalizeSnapshot(snapshot){var _a,_b,_c,_d,_e;const anonymousId=String((_a=snapshot==null?void 0:snapshot.anonymousId)!=null?_a:"").trim();const sessionId=String((_b=snapshot==null?void 0:snapshot.sessionId)!=null?_b:"").trim();const userId=String((_c=snapshot==null?void 0:snapshot.userId)!=null?_c:"").trim()||null;const userUuid=userId?String((_d=snapshot==null?void 0:snapshot.userUuid)!=null?_d:"").trim()||null:null;const distinctId=userId!=null?userId:anonymousId;const distinctIdType=userId?"user_id":"anonymous_id";if(!anonymousId||!sessionId)return null;if(String((_e=snapshot==null?void 0:snapshot.distinctId)!=null?_e:"").trim()!==distinctId)return null;if((snapshot==null?void 0:snapshot.distinctIdType)!==distinctIdType)return null;return{anonymousId,userId,userUuid,sessionId}}function dayKey(ts){const d=new Date(ts);const p=n=>n<10?`0${n}`:String(n);return`${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`}var Identity=class{constructor(store,now=Date.now,initialSnapshot){__publicField(this,"store",store);__publicField(this,"now",now);__publicField(this,"anonymousId");__publicField(this,"userId");__publicField(this,"userUuid");__publicField(this,"session");__publicField(this,"persistedAt");var _a;const initial=initialSnapshot?normalizeSnapshot(initialSnapshot):null;if(initial){this.anonymousId=initial.anonymousId;this.userId=initial.userId;this.userUuid=initial.userUuid;const at=this.now();this.session={id:initial.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot()}else{this.anonymousId=(_a=this.store.get(STORAGE_KEYS.anonymousId))!=null?_a:this.newAnonymousId();this.userId=this.store.get(STORAGE_KEYS.userId)||null;this.userUuid=this.store.get(STORAGE_KEYS.userUuid)||null;this.session=this.loadSession()}this.persistedAt=this.session.lastActive}persistSnapshot(){this.store.set(STORAGE_KEYS.anonymousId,this.anonymousId);if(this.userId)this.store.set(STORAGE_KEYS.userId,this.userId);else this.store.remove(STORAGE_KEYS.userId);if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session))}newAnonymousId(){const id=`anon_${uuid()}`;this.store.set(STORAGE_KEYS.anonymousId,id);return id}loadSession(){const raw=this.store.get(STORAGE_KEYS.session);if(raw){try{const s=JSON.parse(raw);if((s==null?void 0:s.id)&&typeof s.lastActive==="number"&&!this.expired(s,this.now()))return s}catch(e){}}return this.startSession(this.now())}expired(s,at){return at-s.lastActive>SESSION_TIMEOUT_MS||s.day!==dayKey(at)}startSession(at){const s={id:uuid(),lastActive:at,day:dayKey(at)};this.store.set(STORAGE_KEYS.session,JSON.stringify(s));this.persistedAt=at;return s}touch(){const at=this.now();if(this.expired(this.session,at)){this.session=this.startSession(at);return}this.session.lastActive=at;if(at-this.persistedAt>=TOUCH_PERSIST_MS){this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session));this.persistedAt=at}}identify(userId,options){var _a;const id=String(userId!=null?userId:"").trim();if(!id)return false;const userChanged=id!==this.userId;const uuidWasProvided=(options==null?void 0:options.userUuid)!==void 0;const nextUuid=uuidWasProvided?String((_a=options.userUuid)!=null?_a:"").trim()||null:this.userUuid;const uuidChanged=nextUuid!==this.userUuid;if(!userChanged&&!uuidChanged)return false;this.userId=id;this.store.set(STORAGE_KEYS.userId,id);this.userUuid=userChanged&&!uuidWasProvided?null:nextUuid;if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);return true}reset(anonymousId){this.userId=null;this.store.remove(STORAGE_KEYS.userId);this.userUuid=null;this.store.remove(STORAGE_KEYS.userUuid);const sharedAnonymousId=anonymousId==null?void 0:anonymousId.trim();if(sharedAnonymousId){this.anonymousId=sharedAnonymousId;this.store.set(STORAGE_KEYS.anonymousId,sharedAnonymousId)}else{this.anonymousId=this.newAnonymousId()}this.session=this.startSession(this.now())}snapshot(){var _a;return{distinctId:(_a=this.userId)!=null?_a:this.anonymousId,distinctIdType:this.userId?"user_id":"anonymous_id",anonymousId:this.anonymousId,userId:this.userId,userUuid:this.userUuid,sessionId:this.session.id}}applySnapshot(snapshot){const next=normalizeSnapshot(snapshot);if(!next)return false;const before=this.snapshot();if(before.userId!==null&&before.userId!==next.userId&&before.anonymousId===next.anonymousId)return false;const at=this.now();this.anonymousId=next.anonymousId;this.userId=next.userId;this.userUuid=next.userUuid;this.session={id:next.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot();this.persistedAt=at;const after=this.snapshot();return before.anonymousId!==after.anonymousId||before.userId!==after.userId||before.userUuid!==after.userUuid||before.sessionId!==after.sessionId}setAnonymousId(id){this.anonymousId=id;this.store.set(STORAGE_KEYS.anonymousId,id)}};var DB_NAME="yz_tracker";var STORE="queue";var DEFAULT_LIMIT=500;function openDb(dbName){return new Promise((resolve,reject)=>{const req=indexedDB.open(dbName,1);req.onupgradeneeded=()=>{const db=req.result;if(!db.objectStoreNames.contains(STORE)){db.createObjectStore(STORE,{keyPath:"eventId"}).createIndex("savedAt","savedAt")}};req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);req.onblocked=()=>reject(new Error("indexedDB blocked"))})}function indexedDbPersistence(opts={}){var _a,_b;if(typeof indexedDB==="undefined")return null;const dbName=(_a=opts.dbName)!=null?_a:DB_NAME;const limit=(_b=opts.limit)!=null?_b:DEFAULT_LIMIT;let dbPromise=null;const db=()=>{dbPromise!=null?dbPromise:dbPromise=openDb(dbName);return dbPromise};const write=fn=>__async(null,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readwrite");fn(tx.objectStore(STORE))}catch(e){}});return{load(){return __async(this,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readonly");const req=tx.objectStore(STORE).index("savedAt").getAll();const rows=yield new Promise((resolve,reject)=>{req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error)});return rows.map(r=>r.payload)}catch(e){return[]}})},add(records){void write(store=>{for(const r of records)store.put(r);const countReq=store.count();countReq.onsuccess=()=>{const over=countReq.result-limit;if(over<=0)return;let dropped=0;const cur=store.index("savedAt").openCursor();cur.onsuccess=()=>{const c=cur.result;if(!c||dropped>=over)return;c.delete();dropped+=1;c.continue()}}})},remove(eventIds){if(!eventIds.length)return;void write(store=>{for(const id of eventIds)store.delete(id)})}}}var SDK_NAME="@yuanze_dev/tracker";var SDK_VERSION="0.16.2";var PROTOCOL_VERSION=1;var MAX_BATCH_SIZE=50;var PLATFORMS=["web","pc","flutter","ios","android","miniprogram","backend","electron-renderer","electron-main","tauri-web","tauri-rust","node"];var documentPageInstanceId;function currentPageInstanceId(){if(typeof window==="undefined"||typeof document==="undefined")return void 0;documentPageInstanceId!=null?documentPageInstanceId:documentPageInstanceId=uuid();return documentPageInstanceId}var MAX_BACKOFF_MS=3e4;var Tracker=class{constructor(opts){__publicField(this,"queue",[]);__publicField(this,"timer",null);__publicField(this,"superProps",{});__publicField(this,"identity");__publicField(this,"persistence");__publicField(this,"send");__publicField(this,"endpoint");__publicField(this,"writeKey");__publicField(this,"platform");__publicField(this,"appVersion");__publicField(this,"sdkName");__publicField(this,"sdkVersion");__publicField(this,"maxBatch");__publicField(this,"flushMs");__publicField(this,"maxQueueSize");__publicField(this,"pageInstanceId");__publicField(this,"sessionAuthority");__publicField(this,"flushing",false);__publicField(this,"flushWaiters",[]);__publicField(this,"retryCount",0);__publicField(this,"droppedEventCount",0);__publicField(this,"configVersion",0);__publicField(this,"pageviewHandler",null);__publicField(this,"pageleaveHandler",null);__publicField(this,"diagnosticsBridge",null);__publicField(this,"disposeHandlers",[]);__publicField(this,"identityChangeHandlers",[]);var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k;this.endpoint=opts.endpoint;this.writeKey=opts.writeKey;this.platform=(_a=opts.platform)==null?void 0:_a.trim().toLowerCase();this.appVersion=opts.appVersion;this.sdkName=(_b=opts.sdkName)!=null?_b:SDK_NAME;this.sdkVersion=(_c=opts.sdkVersion)!=null?_c:SDK_VERSION;this.maxBatch=(_d=opts.maxBatch)!=null?_d:5;this.flushMs=(_e=opts.flushMs)!=null?_e:5e3;this.maxQueueSize=(_f=opts.maxQueueSize)!=null?_f:500;this.pageInstanceId=currentPageInstanceId();this.sessionAuthority=(_g=opts.sessionAuthority)!=null?_g:"local";this.send=(_h=opts.sender)!=null?_h:defaultFetchSender;this.identity=new Identity((_i=opts.storage)!=null?_i:webStorage(),Date.now,opts.initialIdentity);if(opts.distinctId&&!opts.initialIdentity)this.identity.setAnonymousId(opts.distinctId);this.superProps=__spreadValues({},(_j=opts.initialProperties)!=null?_j:{});this.persistence=opts.persistence===false?null:(_k=opts.persistence)!=null?_k:indexedDbPersistence({limit:this.maxQueueSize});void this.restore();if(this.platform&&PLATFORMS.indexOf(this.platform)<0){console.error(`[tracker] platform "${this.platform}" 不在受控端列表里,按端分析时这批数据会自成一端。可选值:${PLATFORMS.join(" / ")}(微信小程序是 miniprogram,不是 wechat)`)}if(typeof document!=="undefined"){const onVisibilityChange=()=>{if(document.visibilityState==="hidden")this.flush(true)};document.addEventListener("visibilitychange",onVisibilityChange);this.addDisposeHandler(()=>document.removeEventListener("visibilitychange",onVisibilityChange));if(typeof window!=="undefined"){const onPageHide=()=>this.flush(true);window.addEventListener("pagehide",onPageHide);this.addDisposeHandler(()=>window.removeEventListener("pagehide",onPageHide))}}}restore(){return __async(this,null,function*(){if(!this.persistence)return;const saved=yield this.persistence.load();const known=new Set(this.queue.map(e=>e.eventId));const revived=saved.filter(e=>(e==null?void 0:e.eventId)&&!known.has(e.eventId));if(!revived.length)return;this.queue.unshift(...revived);this.trim();void this.flush()})}register(props){for(const key of Object.keys(props))this.superProps[key]=props[key]}identify(id,options){const before=this.identity.snapshot();if(!this.identity.identify(id,options))return;this.enqueue("$identify",{});const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}reset(anonymousId){const before=this.identity.snapshot();this.identity.reset(anonymousId);const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}getDistinctId(){return this.identity.snapshot().distinctId}getAnonymousId(){return this.identity.snapshot().anonymousId}getSessionId(){return this.identity.snapshot().sessionId}getPageInstanceId(){return this.pageInstanceId}getIdentitySnapshot(){return this.identity.snapshot()}touchIdentity(){const before=this.identity.snapshot();if(this.sessionAuthority==="external")return before;this.identity.touch();const after=this.identity.snapshot();if(before.sessionId!==after.sessionId){for(const handler of this.identityChangeHandlers)handler(before,after)}return after}applyIdentitySnapshot(snapshot,options={}){const before=this.identity.snapshot();const changed=this.identity.applySnapshot(snapshot);if(!changed)return false;const after=this.identity.snapshot();const identityChanged=before.userId!==after.userId||before.userUuid!==after.userUuid;if(options.emitIdentify===true&&before.anonymousId===after.anonymousId&&after.userId!==null&&identityChanged){this.enqueue("$identify",{})}for(const handler of this.identityChangeHandlers)handler(before,after);return true}setConfigVersion(version){if(Number.isInteger(version)&&version>=0)this.configVersion=version}getConfigVersion(){return this.configVersion}get pending(){return this.queue.length}get droppedEvents(){return this.droppedEventCount}dispose(){if(this.timer){clearTimeout(this.timer);this.timer=null}this.diagnosticsBridge=null;for(const handler of this.disposeHandlers.splice(0))handler()}addDisposeHandler(handler){this.disposeHandlers.push(handler)}addIdentityChangeHandler(handler){this.identityChangeHandlers.push(handler);const remove=()=>{this.identityChangeHandlers=this.identityChangeHandlers.filter(candidate=>candidate!==handler)};this.addDisposeHandler(remove);return remove}setPageviewHandler(handler){this.pageviewHandler=handler}setPageleaveHandler(handler){this.pageleaveHandler=handler}setDiagnosticsBridge(bridge){this.diagnosticsBridge=bridge}captureException(error,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.captureException(error,options))!=null?_b:null}log(level,message,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.log(level,message,options))!=null?_b:null}flushDiagnostics(){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.flush())!=null?_b:Promise.resolve()}pageview(input){const url=typeof input==="string"?input:input==null?void 0:input.$url;if(this.pageviewHandler)this.pageviewHandler(url);else if(input&&typeof input==="object")this.track("$pageview",input);else if(url)this.track("$pageview",{$url:url})}pageleave(){var _a;(_a=this.pageleaveHandler)==null?void 0:_a.call(this)}track(name,properties){this.enqueue(name,properties!=null?properties:{})}trackUnsafe(name,properties={}){this.enqueue(name,properties)}captureAs(who,name,properties={},options={}){this.enqueue(name,properties,who,options)}enqueue(name,properties,override,options={}){var _a,_b,_c,_d;const who=override!=null?override:this.touchIdentity();const raw={eventId:(_a=options.eventId)!=null?_a:uuid(),eventName:name,distinctId:who.distinctId,distinctIdType:who.distinctIdType,anonymousId:who.anonymousId,userId:(_b=who.userId)!=null?_b:void 0,userUuid:(_c=who.userUuid)!=null?_c:void 0,sessionId:who.sessionId,pageInstanceId:this.pageInstanceId,platform:this.platform,appVersion:this.appVersion,clientTime:new Date().toISOString(),properties:__spreadProps(__spreadValues(__spreadValues({},this.superProps),properties),{$sdk_name:this.sdkName,$sdk_version:this.sdkVersion,$protocol_version:PROTOCOL_VERSION,$config_version:this.configVersion})};this.queue.push(raw);(_d=this.persistence)==null?void 0:_d.add([{eventId:raw.eventId,savedAt:Date.now(),payload:raw}]);this.trim();if(this.queue.length>=this.maxBatch)this.flush();else this.schedule()}trim(){var _a;const overflow=this.queue.length-this.maxQueueSize;if(overflow>0){const dropped=this.queue.splice(0,overflow);this.droppedEventCount+=dropped.length;(_a=this.persistence)==null?void 0:_a.remove(dropped.map(e=>e.eventId));console.warn(`[tracker] 队列超过 ${this.maxQueueSize} 条,丢弃最旧的 ${overflow} 条`)}}schedule(delayMs=this.flushMs){if(this.timer)return;this.timer=setTimeout(()=>this.flush(),delayMs)}flush(unloading=false){return __async(this,null,function*(){var _a,_b;if(this.timer){clearTimeout(this.timer);this.timer=null}if(this.flushing&&!unloading){yield new Promise(resolve=>this.flushWaiters.push(resolve));if(this.queue.length>0)yield this.flush();return}if(this.queue.length===0)return;this.flushing=true;const batch=this.queue.splice(0,Math.min(MAX_BATCH_SIZE,this.queue.length));const body=JSON.stringify({events:batch,protocolVersion:PROTOCOL_VERSION});const headers={"Content-Type":"application/json","x-write-key":this.writeKey};try{yield this.send(this.endpoint,body,headers,unloading);(_a=this.persistence)==null?void 0:_a.remove(batch.map(e=>e.eventId));this.retryCount=0}catch(err){if((err==null?void 0:err.retryable)!==false){this.queue.unshift(...batch);this.trim();this.retryCount+=1}else{this.droppedEventCount+=batch.length;console.warn("[tracker] 丢弃一批(不可重试):",err==null?void 0:err.status);(_b=this.persistence)==null?void 0:_b.remove(batch.map(e=>e.eventId));this.retryCount=0}}finally{this.flushing=false;for(const resolve of this.flushWaiters.splice(0))resolve()}if(this.queue.length>0&&!unloading){this.schedule(Math.min(this.flushMs*__pow(2,this.retryCount),MAX_BACKOFF_MS))}})}};var defaultFetchSender=(endpoint,body,headers,keepalive)=>__async(null,null,function*(){const res=yield fetch(endpoint,{method:"POST",headers,body,keepalive});if(!res.ok){const e=new Error(`HTTP ${res.status}`);e.status=res.status;e.retryable=res.status>=500||res.status===429;throw e}});var DEFAULT_CAPTURE_SETTINGS={captureClicks:true,captureText:true,maxTextLength:64,sampleRate:1,allowSelectors:["a","button",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','input[type="submit"]','input[type="button"]',"summary"],denySelectors:["[data-no-track]",".yz-no-track"],captureHref:true,captureTitle:true,captureAriaLabel:true,captureRole:true,captureName:true,captureId:true,captureDataTestId:true,capturePageviews:true,capturePageleave:true,capturePageDuration:true,captureVisibleDuration:false};var bool=v=>typeof v==="boolean";var number=(v,min,max)=>typeof v==="number"&&Number.isFinite(v)&&v>=min&&v<=max;var strings=v=>Array.isArray(v)&&v.length<=50&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=256);var integer=(v,min,max)=>number(v,min,max)&&Number.isInteger(v);var stringList=(v,maxItems,maxLength)=>Array.isArray(v)&&v.length<=maxItems&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=maxLength);var object=v=>v&&typeof v==="object"&&!Array.isArray(v)?v:{};function isValidHttpsOrigin(value){if(typeof value!=="string")return false;try{const url=new URL(value);return url.protocol==="https:"&&url.origin===value}catch(e){return false}}function parseReplayConfig(input){var _a,_b,_c;if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const appVersions=object(settings.appVersions);const errorSampling=object(settings.errorSampling);const recording=object(settings.recording);const pages=object(settings.pages);const privacy=object(settings.privacy);const capture=object(settings.capture);const upload=object(settings.upload);const legacyQuota=object(settings.quota);const maxSessionBytes=(_a=settings.maxSessionBytes)!=null?_a:legacyQuota.maxSessionBytes;const uploadOrigins=(_b=raw.uploadOrigins)!=null?_b:[];const checkpointMaxBytes=(_c=recording.checkpointMaxBytes)!=null?_c:4*1024*1024;if(!bool(raw.enabled)||!bool(raw.supported)||raw.recorderKind!=="rrweb"||raw.replayFormat!=="rrweb-v1"||typeof raw.samplingSalt!=="string"||!stringList(uploadOrigins,10,512)||!uploadOrigins.every(isValidHttpsOrigin)||!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!bool(settings.enabled)||!bool(settings.emergencyDisabled)||!number(settings.sampleRate,0,1)||!stringList(appVersions.include,100,100)||!stringList(appVersions.exclude,100,100)||!bool(errorSampling.enabled)||errorSampling.mode!=="after-error"&&errorSampling.mode!=="rolling-buffer"||!integer(errorSampling.rollingBufferSeconds,5,120)||!integer(recording.maxSessionMinutes,1,720)||!integer(recording.maxEvents,100,2e6)||!integer(recording.chunkSeconds,2,60)||!integer(recording.chunkMaxBytes,64*1024,2*1024*1024)||!integer(checkpointMaxBytes,256*1024,16*1024*1024)||!integer(recording.checkpointSeconds,10,120)||!integer(recording.localQueueMaxBytes,1024*1024,200*1024*1024)||!integer(recording.stopAfterBackgroundMinutes,1,120)||!stringList(pages.include,50,512)||!stringList(pages.exclude,100,512)||!bool(privacy.maskAllInputs)||!stringList(privacy.maskSelectors,100,256)||!stringList(privacy.blockSelectors,100,256)||!stringList(privacy.redactUrlParams,100,100)||!bool(capture.canvas)||!bool(capture.inlineImages)||!bool(capture.collectFonts)||!bool(capture.crossOriginIframes)||!integer(upload.concurrency,1,6)||!integer(upload.timeoutSeconds,5,120)||!integer(upload.maxRetries,0,12)||!integer(upload.retryBaseMs,100,1e4)||!integer(upload.localRetryDays,1,30)||!integer(maxSessionBytes,1024*1024,2*1024*1024*1024))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,recorderKind:"rrweb",replayFormat:"rrweb-v1",uploadOrigins,samplingSalt:raw.samplingSalt,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{enabled:settings.enabled,emergencyDisabled:settings.emergencyDisabled,sampleRate:settings.sampleRate,appVersions:{include:appVersions.include,exclude:appVersions.exclude},errorSampling:{enabled:errorSampling.enabled,mode:errorSampling.mode,rollingBufferSeconds:errorSampling.rollingBufferSeconds},recording:{maxSessionMinutes:recording.maxSessionMinutes,maxEvents:recording.maxEvents,chunkSeconds:recording.chunkSeconds,chunkMaxBytes:recording.chunkMaxBytes,checkpointMaxBytes,checkpointSeconds:recording.checkpointSeconds,localQueueMaxBytes:recording.localQueueMaxBytes,stopAfterBackgroundMinutes:recording.stopAfterBackgroundMinutes},pages:{include:pages.include,exclude:pages.exclude},privacy:{maskAllInputs:privacy.maskAllInputs,maskSelectors:privacy.maskSelectors,blockSelectors:privacy.blockSelectors,redactUrlParams:privacy.redactUrlParams},capture:{canvas:capture.canvas,inlineImages:capture.inlineImages,collectFonts:capture.collectFonts,crossOriginIframes:capture.crossOriginIframes},upload:{concurrency:upload.concurrency,timeoutSeconds:upload.timeoutSeconds,maxRetries:upload.maxRetries,retryBaseMs:upload.retryBaseMs,localRetryDays:upload.localRetryDays},maxSessionBytes}}}var DIAGNOSTIC_LEVELS=new Set(["debug","info","warn","error","fatal"]);function parseDiagnosticsConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const errors=object(settings.errors);const logs=object(settings.logs);const context=object(settings.context);const upload=object(settings.upload);const privacy=object(settings.privacy);const levels=logs.levels;if(!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!bool(raw.enabled)||!bool(raw.supported)||typeof raw.endpointPath!=="string"||!raw.endpointPath.startsWith("/")||raw.endpointPath.length>512||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!number(errors.sampleRate,0,1)||!bool(errors.captureUnhandled)||!bool(errors.captureHandled)||!Array.isArray(levels)||levels.length>5||!levels.every(level=>typeof level==="string"&&DIAGNOSTIC_LEVELS.has(level))||new Set(levels).size!==levels.length||!number(logs.sampleRate,0,1)||!integer(context.windowSeconds,5,300)||!integer(context.maxEntries,10,200)||!integer(context.maxBytes,16*1024,1024*1024)||!integer(upload.batchSize,1,100)||!integer(upload.batchMaxBytes,16*1024,1024*1024)||!integer(upload.flushMs,500,6e4)||!integer(upload.timeoutMs,1e3,3e4)||!integer(upload.maxRetries,0,12)||!integer(upload.offlineMaxBytes,256*1024,50*1024*1024)||!integer(upload.offlineTtlHours,1,168)||!integer(privacy.maxMessageBytes,128,4096)||!integer(privacy.maxStackBytes,4096,256*1024)||!stringList(privacy.denyKeys,100,128)||!stringList(privacy.redactUrlParams,100,128))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,endpointPath:raw.endpointPath,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{errors:{sampleRate:errors.sampleRate,captureUnhandled:errors.captureUnhandled,captureHandled:errors.captureHandled},logs:{levels:[...levels],sampleRate:logs.sampleRate},context:{windowSeconds:context.windowSeconds,maxEntries:context.maxEntries,maxBytes:context.maxBytes},upload:{batchSize:upload.batchSize,batchMaxBytes:upload.batchMaxBytes,flushMs:upload.flushMs,timeoutMs:upload.timeoutMs,maxRetries:upload.maxRetries,offlineMaxBytes:upload.offlineMaxBytes,offlineTtlHours:upload.offlineTtlHours},privacy:{maxMessageBytes:privacy.maxMessageBytes,maxStackBytes:privacy.maxStackBytes,denyKeys:[...privacy.denyKeys],redactUrlParams:[...privacy.redactUrlParams]}}}}function parseRemoteConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const c=raw.config;if(!c||typeof c!=="object")return null;const config=c;const candidate={captureClicks:config.captureClicks,captureText:config.captureText,maxTextLength:config.maxTextLength,sampleRate:config.sampleRate,allowSelectors:config.allowSelectors,denySelectors:config.denySelectors,captureHref:config.captureHref,captureTitle:config.captureTitle===void 0?true:config.captureTitle,captureAriaLabel:config.captureAriaLabel,captureRole:config.captureRole,captureName:config.captureName,captureId:config.captureId,captureDataTestId:config.captureDataTestId,capturePageviews:config.capturePageviews,capturePageleave:config.capturePageleave,capturePageDuration:config.capturePageDuration,captureVisibleDuration:config.captureVisibleDuration};const valid=bool(raw.enabled)&&number(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.schemaVersion)&&number(raw.configVersion,0,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.configVersion)&&typeof raw.platform==="string"&&number(raw.refreshIntervalSeconds,5,3600)&&bool(candidate.captureClicks)&&bool(candidate.captureText)&&number(candidate.maxTextLength,0,512)&&Number.isInteger(candidate.maxTextLength)&&number(candidate.sampleRate,0,1)&&strings(candidate.allowSelectors)&&strings(candidate.denySelectors)&&bool(candidate.captureHref)&&bool(candidate.captureTitle)&&bool(candidate.captureAriaLabel)&&bool(candidate.captureRole)&&bool(candidate.captureName)&&bool(candidate.captureId)&&bool(candidate.captureDataTestId)&&bool(candidate.capturePageviews)&&bool(candidate.capturePageleave)&&bool(candidate.capturePageDuration)&&bool(candidate.captureVisibleDuration);if(!valid)return null;const replay=parseReplayConfig(raw.replay);const diagnostics=parseDiagnosticsConfig(raw.diagnostics);return __spreadValues(__spreadValues({schemaVersion:raw.schemaVersion,configVersion:raw.configVersion,enabled:raw.enabled,platform:raw.platform,refreshIntervalSeconds:raw.refreshIntervalSeconds,config:candidate},raw.replay===void 0?{}:{replay}),raw.diagnostics===void 0?{}:{diagnostics})}function deriveConfigEndpoint(trackEndpoint){try{const base=typeof location!=="undefined"?location.href:void 0;const url=new URL(trackEndpoint,base);url.pathname=url.pathname.replace(/\/api\/v1\/track\/?$/,"/api/v1/config");url.search="";url.hash="";return url.toString()}catch(e){return trackEndpoint.replace(/\/api\/v1\/track\/?$/,"/api/v1/config")}}var SENSITIVE_TEXT=/(\d[\d\s-]{9,}\d)|([\w.+-]+@[\w-]+\.[\w.]+)|(\d{15,19})/g;function sanitizeText(input,maxLength=64){return input.replace(/\s+/g," ").trim().replace(SENSITIVE_TEXT,"[redacted]").slice(0,maxLength)}function coerceDatasetValue(raw){if(raw===void 0)return void 0;if(raw==="true")return true;if(raw==="false")return false;if(raw==="")return raw;const n=Number(raw);return Number.isFinite(n)&&String(n)===raw?n:raw}var wxSender=(endpoint,body,headers)=>new Promise((resolve,reject)=>{wx.request({url:endpoint,method:"POST",header:headers,data:body,timeout:1e4,success:res=>{if(res.statusCode>=200&&res.statusCode<300)return resolve();const e=new Error(`HTTP ${res.statusCode}`);e.status=res.statusCode;e.retryable=res.statusCode>=500||res.statusCode===429;reject(e)},fail:err=>{const e=new Error(err.errMsg);e.retryable=true;reject(e)}})});function wxStorage(){return{get(key){try{const v=wx.getStorageSync(key);return typeof v==="string"&&v?v:null}catch(e){return null}},set(key,value){try{wx.setStorageSync(key,value)}catch(e){}},remove(key){try{wx.removeStorageSync(key)}catch(e){}}}}var QUEUE_PREFIX="yz_q_";function imul32(a,b){if(typeof Math.imul==="function")return Math.imul(a,b);const ah=a>>>16&65535;const al=a&65535;const bh=b>>>16&65535;const bl=b&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0}function stableRuntimeHash(value){let hash=2166136261;for(let index=0;index<value.length;index+=1){hash^=value.charCodeAt(index);hash=imul32(hash,16777619)}return(hash>>>0).toString(16)}function storageNamespace(endpoint,writeKey){return`yz_mp_${stableRuntimeHash(`${endpoint}|${writeKey}`)}_`}function scopedWxStorage(endpoint,writeKey){const storage=wxStorage();const namespace=storageNamespace(endpoint,writeKey);return{get:key=>storage.get(namespace+key),set:(key,value)=>storage.set(namespace+key,value),remove:key=>storage.remove(namespace+key)}}function createWxPersistence(limit,queuePrefix){let known=-1;const keys=()=>{try{return wx.getStorageInfoSync().keys.filter(k=>k.slice(0,queuePrefix.length)===queuePrefix)}catch(e){return[]}};const readAll=()=>{const out=[];for(const k of keys()){try{const r=wx.getStorageSync(k);if(r==null?void 0:r.eventId)out.push(r)}catch(e){}}return out.sort((a,b)=>a.savedAt-b.savedAt)};return{load(){return __async(this,null,function*(){const all=readAll();known=all.length;return all.map(r=>r.payload)})},add(records){for(const r of records){try{wx.setStorageSync(queuePrefix+r.eventId,r)}catch(e){}}known=known<0?keys().length:known+records.length;if(known<=limit)return;const all=readAll();for(const r of all.slice(0,all.length-limit)){try{wx.removeStorageSync(queuePrefix+r.eventId)}catch(e){}}known=Math.min(all.length,limit)},remove(eventIds){for(const id of eventIds){try{wx.removeStorageSync(queuePrefix+id)}catch(e){}}if(known>0)known=Math.max(0,known-eventIds.length)}}}function wxPersistence(limit=500){return createWxPersistence(limit,QUEUE_PREFIX)}function scopedWxPersistence(endpoint,writeKey,limit=500){return createWxPersistence(limit,`${storageNamespace(endpoint,writeKey)}q_`)}function miniProgramDeviceType(deviceType,model){const normalized=deviceType==null?void 0:deviceType.trim().toLowerCase();if(normalized==="phone")return"mobile";if(normalized==="pad"||normalized==="tablet")return"tablet";if(normalized==="pc")return"desktop";const normalizedModel=model==null?void 0:model.trim();if(!normalizedModel)return null;if(/\b(?:ipad|tablet)\b/i.test(normalizedModel))return"tablet";if(/(?:^|[\s_-])pad(?:$|[\s_-])/i.test(normalizedModel))return"tablet";return null}function wxEnvContext(){try{const i=wx.getSystemInfoSync();const ctx={$runtime:"miniprogram"};const deviceType=miniProgramDeviceType(i.deviceType,i.model);if(deviceType)ctx.$device_type=deviceType;if(i.system)ctx.$os=i.system;if(i.model)ctx.$device_model=i.model;if(i.brand)ctx.$device_brand=i.brand;if(i.SDKVersion)ctx.$mp_sdk_version=i.SDKVersion;if(i.version)ctx.$wechat_version=i.version;return ctx}catch(e){return{$runtime:"miniprogram"}}}var SYSTEM_EVENTS=["$app_start","$app_foreground","$app_background","$pageview","$pageleave","$autocapture","$identify","$replay_diagnostic","$replay_focus","$experiment_exposure"];var isSystemEvent=name=>SYSTEM_EVENTS.includes(name);var SDK_NAME2="@yuanze_dev/tracker-miniprogram";var SDK_VERSION2="0.11.1";var instance=null;var captureSettings=DEFAULT_CAPTURE_SETTINGS;var captureEnabled=true;var configEtag;var configTimer=null;var configStorage=null;var configOptions=true;var configEndpoint="";var configWriteKey="";var configGeneration=0;var configRequest=null;function configCacheKey(writeKey){return`yz_capture_config_${stableRuntimeHash(writeKey)}_mini_program`}function applyRemoteConfig(payload){const runtime=autoTrackRuntimeSlot();if(runtime&&(payload.enabled!==captureEnabled||payload.config.capturePageviews!==captureSettings.capturePageviews||payload.config.capturePageleave!==captureSettings.capturePageleave||payload.config.capturePageDuration!==captureSettings.capturePageDuration||payload.config.captureVisibleDuration!==captureSettings.captureVisibleDuration)){advanceCaptureEpoch(runtime)}captureSettings=payload.config;captureEnabled=payload.enabled;instance==null?void 0:instance.setConfigVersion(payload.configVersion)}function loadCachedRemoteConfig(){try{const raw=configStorage==null?void 0:configStorage.get(configCacheKey(configWriteKey));if(!raw)return;const cached=JSON.parse(raw);const payload=parseRemoteConfig(cached.payload);if(!payload||payload.platform!=="mini-program")return;configEtag=cached.etag;applyRemoteConfig(payload)}catch(e){}}function refreshRemoteConfig(){if(configOptions===false||!configEndpoint||!configWriteKey)return Promise.resolve();if(configRequest)return configRequest;if(configTimer){clearTimeout(configTimer);configTimer=null}const options=typeof configOptions==="object"?configOptions:{};const generation=configGeneration;const endpoint=configEndpoint;const writeKey=configWriteKey;const storage=configStorage;const etag=configEtag;const request=new Promise(resolve=>{var _a,_b;let settled=false;const complete=()=>{var _a2;if(settled)return;settled=true;if(generation===configGeneration&&configOptions!==false){configTimer=setTimeout(()=>{void refreshRemoteConfig()},(_a2=options.refreshMs)!=null?_a2:45e3)}resolve()};try{const url=`${(_a=options.endpoint)!=null?_a:endpoint}?platform=mini-program`;wx.request({url,method:"GET",header:__spreadValues({"x-write-key":writeKey},etag?{"If-None-Match":etag}:{}),timeout:(_b=options.timeoutMs)!=null?_b:3e3,success:res=>{var _a2,_b2,_c;if(generation!==configGeneration)return;try{if(res.statusCode===304)return;if(res.statusCode<200||res.statusCode>=300)return;let data=res.data;if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){return}}const payload=parseRemoteConfig(data);if(!payload||payload.platform!=="mini-program")return;configEtag=(_c=(_a2=res.header)==null?void 0:_a2.ETag)!=null?_c:(_b2=res.header)==null?void 0:_b2.etag;storage==null?void 0:storage.set(configCacheKey(writeKey),JSON.stringify({etag:configEtag,savedAt:Date.now(),payload}));applyRemoteConfig(payload)}catch(e){}},fail:complete,complete})}catch(e){complete()}});const cleanup=()=>{if(configRequest===tracked)configRequest=null};const tracked=request.then(cleanup,cleanup);configRequest=tracked;return tracked}function dispose(){configGeneration+=1;if(configTimer){clearTimeout(configTimer);configTimer=null}configRequest=null;configOptions=false;configEndpoint="";configWriteKey="";configEtag=void 0;configStorage=null;captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;const current=instance;instance=null;current==null?void 0:current.dispose();disableOwnedAutoTrackRuntime()}function init(options){var _b;dispose();const _a=options,{envContext=true,persist=true,autoTrack=true,remoteConfig=true}=_a,rest=__objRest(_a,["envContext","persist","autoTrack","remoteConfig"]);configStorage=wxStorage();const identityStorage=scopedWxStorage(rest.endpoint,rest.writeKey);instance=new Tracker(__spreadProps(__spreadValues({},rest),{platform:"miniprogram",sdkName:SDK_NAME2,sdkVersion:SDK_VERSION2,sender:wxSender,storage:identityStorage,persistence:persist?scopedWxPersistence(rest.endpoint,rest.writeKey,(_b=rest.maxQueueSize)!=null?_b:500):false}));if(envContext)instance.register(wxEnvContext());captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;configEtag=void 0;configOptions=remoteConfig;configEndpoint=deriveConfigEndpoint(rest.endpoint);configWriteKey=rest.writeKey;if(remoteConfig!==false)loadCachedRemoteConfig();if(autoTrack)enableAutoTrack();else bindAutoTrackRuntime(false);if(remoteConfig!==false)void refreshRemoteConfig();return instance}function getTracker(){return instance}function ensure(){if(!instance)throw new Error("tracker 未初始化,请先在 app.js 里调用 init()");return instance}function track(name,properties={}){ensure().trackUnsafe(name,properties)}function register(props){ensure().register(props)}function identify(id,options){ensure().identify(id,options)}function reset(){ensure().reset()}function flush(){return ensure().flush()}function trackTap(e){var _a,_b;const ds=(_b=(_a=e==null?void 0:e.currentTarget)==null?void 0:_a.dataset)!=null?_b:{};const name=ds.track;if(typeof name!=="string"||!name)return;const props={};for(const k of Object.keys(ds)){if(k==="track"||TEXT_METADATA_KEYS.has(k))continue;const v=ds[k];props[k]=typeof v==="string"?coerceDatasetValue(v):v}instance==null?void 0:instance.trackUnsafe(name,props)}var TEXT_METADATA_KEYS=new Set(["yzCapture","yzOwner","yzText","yzAdapter"]);var AUTO_TRACK_RUNTIME_KEY="__yz_tracker_miniprogram_auto_track_runtime__";var MODULE_RUNTIME_OWNER={};var FALLBACK_RUNTIME_ROOT={};function runtimeRoot(){if(typeof globalThis!=="undefined"){return globalThis}if(typeof wx==="object"&&wx){return wx}return FALLBACK_RUNTIME_ROOT}function autoTrackRuntimeSlot(){var _a;return(_a=runtimeRoot()[AUTO_TRACK_RUNTIME_KEY])!=null?_a:null}function advanceCaptureEpoch(runtime){runtime.epoch=Number.isFinite(runtime.epoch)?runtime.epoch+1:1}function disableOwnedAutoTrackRuntime(){const runtime=autoTrackRuntimeSlot();if((runtime==null?void 0:runtime.owner)===MODULE_RUNTIME_OWNER&&runtime.enabled){runtime.enabled=false;advanceCaptureEpoch(runtime)}}function bindAutoTrackRuntime(enabled){var _a,_b;const root=runtimeRoot();const runtime=(_a=autoTrackRuntimeSlot())!=null?_a:{owner:null,enabled:false,epoch:0,interactionDepth:0,disposeOwner:null,captureState:()=>({enabled:false,epoch:0,settings:DEFAULT_CAPTURE_SETTINGS}),captureInteraction:()=>void 0,invokeInteraction:(self,args,method)=>method.apply(self,args),track:()=>void 0,flush:()=>void 0,refresh:()=>void 0};if(runtime.owner&&runtime.owner!==MODULE_RUNTIME_OWNER){try{(_b=runtime.disposeOwner)==null?void 0:_b.call(runtime)}catch(e){}}if(!Number.isFinite(runtime.epoch))runtime.epoch=0;if(!Number.isFinite(runtime.interactionDepth))runtime.interactionDepth=0;runtime.owner=MODULE_RUNTIME_OWNER;if(runtime.enabled!==enabled){runtime.enabled=enabled;advanceCaptureEpoch(runtime)}runtime.disposeOwner=dispose;runtime.captureState=()=>({enabled:runtime.enabled&&captureEnabled,epoch:runtime.epoch,settings:captureSettings});runtime.captureInteraction=(self,event)=>{if(runtime.enabled&&runtime.interactionDepth===0)captureInteraction(self,event)};runtime.invokeInteraction=(self,args,method)=>{var _a2,_b2;if(runtime.interactionDepth>0)return method.apply(self,args);let unmarkedComponent=false;try{const context=self;const dataset=(_b2=(_a2=args[0])==null?void 0:_a2.currentTarget)==null?void 0:_b2.dataset;unmarkedComponent=!!(context==null?void 0:context.is)&&!context.route&&!context.__route__&&(dataset==null?void 0:dataset.yzCapture)!=="1"&&(dataset==null?void 0:dataset.yzCapture)!==1}catch(e){}if(unmarkedComponent)return method.apply(self,args);const epoch=runtime.epoch;const owner=runtime.owner;let properties;try{if(runtime.enabled){properties=snapshotInteraction(self,args[0])}}catch(e){}runtime.interactionDepth+=1;try{return method.apply(self,args)}finally{runtime.interactionDepth-=1;try{if(properties&&runtime.enabled&&runtime.epoch===epoch&&runtime.owner===owner&&captureEnabled&&captureSettings.captureClicks){if(!captureSettings.captureText)delete properties.$text;else if(typeof properties.$text==="string"){const text=sanitizeText(properties.$text,captureSettings.maxTextLength);if(text)properties.$text=text;else delete properties.$text}instance==null?void 0:instance.track("$autocapture",properties)}}catch(e){}}};runtime.track=(name,properties)=>{if(runtime.enabled)instance==null?void 0:instance.trackUnsafe(name,properties)};runtime.flush=()=>{if(runtime.enabled)void(instance==null?void 0:instance.flush(true))};runtime.refresh=()=>{if(runtime.enabled)void refreshRemoteConfig()};root[AUTO_TRACK_RUNTIME_KEY]=runtime;return runtime}var PAGE_LIFECYCLE_HOOKS=new Set(["onLoad","onShow","onReady","onHide","onUnload","onPullDownRefresh","onReachBottom","onShareAppMessage","onShareTimeline","onAddToFavorites","onPageScroll","onResize","onTabItemTap","onSaveExitState"]);var INTERACTION_WRAPPED="__yz_tracker_interaction_wrapped__";var LIFECYCLE_WRAPPED="__yz_tracker_lifecycle_wrapped__";function routeOf(self){var _a,_b;const direct=(_a=self==null?void 0:self.route)!=null?_a:self==null?void 0:self.__route__;if(direct)return direct;try{if(typeof getCurrentPages==="function"){const pages=getCurrentPages();const current=(_b=pages[pages.length-1])==null?void 0:_b.route;if(current)return current}}catch(e){}const componentPath=self==null?void 0:self.is;return componentPath?`miniprogram://component/${componentPath}`:"miniprogram://app"}var SENSITIVE_TARGET=/(?:^|[-_:])(captcha\d*|verify|verification|otp|password|passwd|credential)(?:$|[-_:])/i;var SENSITIVE_DATASET_KEYS=["sensitive","noTrack","yzSensitive","yzNoTrack","trackSensitive"];function isSensitiveInteraction(target){if(!target)return false;if(typeof target.id==="string"&&SENSITIVE_TARGET.test(target.id))return true;const dataset=target.dataset;return!!dataset&&SENSITIVE_DATASET_KEYS.some(key=>Object.prototype.hasOwnProperty.call(dataset,key))}function snapshotInteraction(self,event){var _a,_b,_c;if(!captureEnabled||!captureSettings.captureClicks||!event)return;const target=event.currentTarget;if(isSensitiveInteraction(target))return;const dataset=(_a=target==null?void 0:target.dataset)!=null?_a:{};const generated=dataset.yzCapture==="1"||dataset.yzCapture===1;const adaptedClick=generated&&dataset.yzAdapter==="tdesign-grid-item"&&event.type==="click";if(event.type!=="tap"&&event.type!=="longpress"&&event.type!=="longtap"&&!adaptedClick)return;const mark=event.mark;if(mark&&(Object.prototype.hasOwnProperty.call(mark,"yzSensitive")||typeof mark.yzNamed==="string"&&mark.yzNamed))return;if(generated&&typeof(mark==null?void 0:mark.yzOwner)==="string"&&mark.yzOwner!==dataset.yzOwner)return;if(typeof dataset.track==="string"&&dataset.track)return;const id=typeof(target==null?void 0:target.id)==="string"&&target.id?target.id:void 0;const route=routeOf(self);const componentPath=self==null?void 0:self.is;const pageRoute=(_b=self==null?void 0:self.route)!=null?_b:self==null?void 0:self.__route__;if(componentPath&&!pageRoute&&!generated)return;let text;if(captureSettings.captureText&&captureSettings.maxTextLength>0){const raw=(_c=dataset.yzText)!=null?_c:mark==null?void 0:mark.yzText;if(typeof raw==="string"&&raw.length<=4096&&!/^\d{4,8}$/.test(raw.trim())){text=sanitizeText(raw,captureSettings.maxTextLength)||void 0}}return __spreadValues(__spreadValues({$tag:"miniprogram",$selector:id?`#${id}`:`miniprogram:${route}`,$url:route,$role:event.type==="tap"||adaptedClick?"tap":"longpress"},id?{$element_id:id}:{}),text?{$text:text}:{})}function captureInteraction(self,event){const properties=snapshotInteraction(self,event);if(properties)instance==null?void 0:instance.track("$autocapture",properties)}function wrapInteractionMethods(methods,runtime,ignored=new Set){for(const name of Object.keys(methods)){const value=methods[name];if(ignored.has(name)||typeof value!=="function")continue;if(value[INTERACTION_WRAPPED])continue;const wrapped=function(...args){return runtime.invokeInteraction(this,args,value)};Object.defineProperty(wrapped,INTERACTION_WRAPPED,{value:true});methods[name]=wrapped}}function wrapPageInteractions(options,runtime){wrapInteractionMethods(options,runtime,PAGE_LIFECYCLE_HOOKS)}function wrap(hooks,name,extra){const original=hooks[name];if(typeof original==="function"&&original[LIFECYCLE_WRAPPED])return;const wrapped=function(...args){try{extra(this,args)}catch(e){}return typeof original==="function"?original.apply(this,args):void 0};Object.defineProperty(wrapped,LIFECYCLE_WRAPPED,{value:true});hooks[name]=wrapped}function installAutoTrackRuntime(enabled){const runtime=bindAutoTrackRuntime(enabled);if(typeof Page==="function"&&!Page.__yzAutoTrack){const originalPage=Page;const patched=(options=>{const enteredAt=new WeakMap;try{wrap(options,"onShow",self=>{const capture=runtime.captureState();if(!capture.enabled||!capture.settings.capturePageviews)return;enteredAt.set(self,{at:Date.now(),epoch:capture.epoch});runtime.track("$pageview",{$url:routeOf(self)})});wrap(options,"onHide",self=>{const entry=enteredAt.get(self);if(!entry)return;enteredAt.delete(self);const capture=runtime.captureState();if(!capture.enabled||capture.epoch!==entry.epoch||!capture.settings.capturePageleave)return;runtime.track("$pageleave",__spreadValues({$url:routeOf(self)},capture.settings.capturePageDuration?{$duration_ms:Date.now()-entry.at}:{}))});wrap(options,"onUnload",self=>{const entry=enteredAt.get(self);if(!entry)return;enteredAt.delete(self);const capture=runtime.captureState();if(!capture.enabled||capture.epoch!==entry.epoch||!capture.settings.capturePageleave)return;runtime.track("$pageleave",__spreadValues({$url:routeOf(self)},capture.settings.capturePageDuration?{$duration_ms:Date.now()-entry.at}:{}))});wrapPageInteractions(options,runtime)}catch(e){}return originalPage(options)});for(const key of Object.keys(originalPage))patched[key]=originalPage[key];patched.__yzAutoTrack=true;try{Page=patched}catch(e){}}if(typeof Component==="function"&&!Component.__yzTextTrack){const originalComponent=Component;const patched=(options=>{try{if(options.methods&&typeof options.methods==="object"){wrapInteractionMethods(options.methods,runtime)}}catch(e){}return originalComponent(options)});for(const key of Object.keys(originalComponent))patched[key]=originalComponent[key];patched.__yzTextTrack=true;try{Component=patched}catch(e){}}if(typeof App==="function"&&!App.__yzAutoTrack){const originalApp=App;const patched=(options=>{let launched=false;let foreground=false;let foregroundAt=Date.now();let foregroundEpoch=null;try{wrap(options,"onLaunch",(_self,args)=>{var _a;const launch=(_a=args[0])!=null?_a:{};const capture=runtime.captureState();launched=true;if(!capture.enabled){foreground=false;foregroundEpoch=null;return}foreground=true;foregroundAt=Date.now();foregroundEpoch=capture.epoch;runtime.track("$app_start",__spreadValues(__spreadValues({},typeof launch.scene==="number"?{$scene:launch.scene}:{}),typeof launch.path==="string"&&launch.path?{$path:launch.path}:{}))});wrap(options,"onHide",()=>{const capture=runtime.captureState();if(foreground&&capture.enabled&&foregroundEpoch===capture.epoch){runtime.track("$app_background",{$duration_ms:Math.max(0,Date.now()-foregroundAt),$state:"hidden"})}foreground=false;foregroundEpoch=null;runtime.flush()});wrap(options,"onShow",(_self,args)=>{var _a;const show=(_a=args[0])!=null?_a:{};const capture=runtime.captureState();if(!capture.enabled){foreground=false;foregroundEpoch=null;return}if(launched&&(!foreground||foregroundEpoch!==capture.epoch)){runtime.track("$app_foreground",__spreadProps(__spreadValues(__spreadValues({},typeof show.scene==="number"?{$scene:show.scene}:{}),typeof show.path==="string"&&show.path?{$path:show.path}:{}),{$previous_state:"hidden"}))}foreground=true;foregroundAt=Date.now();foregroundEpoch=capture.epoch;runtime.refresh()})}catch(e){}return originalApp(options)});for(const key of Object.keys(originalApp))patched[key]=originalApp[key];patched.__yzAutoTrack=true;try{App=patched}catch(e){}}}function installAutoTrack(){installAutoTrackRuntime(false)}function enableAutoTrack(){installAutoTrackRuntime(true)}var tracker={init,getTracker,track,register,identify,reset,flush,dispose,trackTap,installAutoTrack,enableAutoTrack,refreshRemoteConfig};var index_default=tracker;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_lib=__commonJS({"../../node_modules/.pnpm/@wxml+parser@0.4.0/node_modules/@wxml/parser/lib/index.js"(exports,module){(function(global2,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global2=typeof globalThis!=="undefined"?globalThis:global2||self,factory(global2.wxmlParser={}))})(exports,(function(exports2){"use strict";var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}var api$1={};var version={};Object.defineProperty(version,"__esModule",{value:true});version.VERSION=void 0;version.VERSION="9.0.2";var parser={};var api={};var __spreadArray=commonjsGlobal&&commonjsGlobal.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};Object.defineProperty(api,"__esModule",{value:true});api.toFastProperties=api.timer=api.peek=api.isES2015MapSupported=api.PRINT_WARNING=api.PRINT_ERROR=api.packArray=api.IDENTITY=api.NOOP=api.merge=api.groupBy=api.defaults=api.assignNoOverwrite=api.assign=api.zipObject=api.sortBy=api.indexOf=api.some=api.difference=api.every=api.isObject=api.isRegExp=api.isArray=api.partial=api.uniq=api.compact=api.reduce=api.findAll=api.find=api.cloneObj=api.cloneArr=api.contains=api.has=api.pick=api.reject=api.filter=api.dropRight=api.drop=api.isFunction=api.isUndefined=api.isString=api.forEach=api.last=api.first=api.flatten=api.map=api.mapValues=api.values=api.keys=api.isEmpty=void 0;api.upperFirst=void 0;function isEmpty(arr){return arr&&arr.length===0}api.isEmpty=isEmpty;function keys$2(obj){if(obj===void 0||obj===null){return[]}return Object.keys(obj)}api.keys=keys$2;function values(obj){var vals=[];var keys2=Object.keys(obj);for(var i=0;i<keys2.length;i++){vals.push(obj[keys2[i]])}return vals}api.values=values;function mapValues(obj,callback){var result=[];var objKeys=keys$2(obj);for(var idx=0;idx<objKeys.length;idx++){var currKey=objKeys[idx];result.push(callback.call(null,obj[currKey],currKey))}return result}api.mapValues=mapValues;function map$1(arr,callback){var result=[];for(var idx=0;idx<arr.length;idx++){result.push(callback.call(null,arr[idx],idx))}return result}api.map=map$1;function flatten$1(arr){var result=[];for(var idx=0;idx<arr.length;idx++){var currItem=arr[idx];if(Array.isArray(currItem)){result=result.concat(flatten$1(currItem))}else{result.push(currItem)}}return result}api.flatten=flatten$1;function first$2(arr){return isEmpty(arr)?void 0:arr[0]}api.first=first$2;function last(arr){var len=arr&&arr.length;return len?arr[len-1]:void 0}api.last=last;function forEach(collection,iteratorCallback){if(Array.isArray(collection)){for(var i=0;i<collection.length;i++){iteratorCallback.call(null,collection[i],i)}}else if(isObject$1(collection)){var colKeys=keys$2(collection);for(var i=0;i<colKeys.length;i++){var key=colKeys[i];var value=collection[key];iteratorCallback.call(null,value,key)}}else{throw Error("non exhaustive match")}}api.forEach=forEach;function isString(item){return typeof item==="string"}api.isString=isString;function isUndefined(item){return item===void 0}api.isUndefined=isUndefined;function isFunction$1(item){return item instanceof Function}api.isFunction=isFunction$1;function drop(arr,howMuch){if(howMuch===void 0){howMuch=1}return arr.slice(howMuch,arr.length)}api.drop=drop;function dropRight(arr,howMuch){if(howMuch===void 0){howMuch=1}return arr.slice(0,arr.length-howMuch)}api.dropRight=dropRight;function filter(arr,predicate){var result=[];if(Array.isArray(arr)){for(var i=0;i<arr.length;i++){var item=arr[i];if(predicate.call(null,item)){result.push(item)}}}return result}api.filter=filter;function reject(arr,predicate){return filter(arr,function(item){return!predicate(item)})}api.reject=reject;function pick$2(obj,predicate){var keys2=Object.keys(obj);var result={};for(var i=0;i<keys2.length;i++){var currKey=keys2[i];var currItem=obj[currKey];if(predicate(currItem)){result[currKey]=currItem}}return result}api.pick=pick$2;function has(obj,prop){if(isObject$1(obj)){return obj.hasOwnProperty(prop)}return false}api.has=has;function contains(arr,item){return find(arr,function(currItem){return currItem===item})!==void 0?true:false}api.contains=contains;function cloneArr(arr){var newArr=[];for(var i=0;i<arr.length;i++){newArr.push(arr[i])}return newArr}api.cloneArr=cloneArr;function cloneObj(obj){var clonedObj={};for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){clonedObj[key]=obj[key]}}return clonedObj}api.cloneObj=cloneObj;function find(arr,predicate){for(var i=0;i<arr.length;i++){var item=arr[i];if(predicate.call(null,item)){return item}}return void 0}api.find=find;function findAll(arr,predicate){var found=[];for(var i=0;i<arr.length;i++){var item=arr[i];if(predicate.call(null,item)){found.push(item)}}return found}api.findAll=findAll;function reduce(arrOrObj,iterator,initial){var isArr=Array.isArray(arrOrObj);var vals=isArr?arrOrObj:values(arrOrObj);var objKeys=isArr?[]:keys$2(arrOrObj);var accumulator=initial;for(var i=0;i<vals.length;i++){accumulator=iterator.call(null,accumulator,vals[i],isArr?i:objKeys[i])}return accumulator}api.reduce=reduce;function compact(arr){return reject(arr,function(item){return item===null||item===void 0})}api.compact=compact;function uniq(arr,identity2){if(identity2===void 0){identity2=function(item){return item}}var identities=[];return reduce(arr,function(result,currItem){var currIdentity=identity2(currItem);if(contains(identities,currIdentity)){return result}else{identities.push(currIdentity);return result.concat(currItem)}},[])}api.uniq=uniq;function partial(func){var restArgs=[];for(var _i=1;_i<arguments.length;_i++){restArgs[_i-1]=arguments[_i]}var firstArg=[null];var allArgs=firstArg.concat(restArgs);return Function.bind.apply(func,allArgs)}api.partial=partial;function isArray$2(obj){return Array.isArray(obj)}api.isArray=isArray$2;function isRegExp(obj){return obj instanceof RegExp}api.isRegExp=isRegExp;function isObject$1(obj){return obj instanceof Object}api.isObject=isObject$1;function every(arr,predicate){for(var i=0;i<arr.length;i++){if(!predicate(arr[i],i)){return false}}return true}api.every=every;function difference(arr,values2){return reject(arr,function(item){return contains(values2,item)})}api.difference=difference;function some(arr,predicate){for(var i=0;i<arr.length;i++){if(predicate(arr[i])){return true}}return false}api.some=some;function indexOf(arr,value){for(var i=0;i<arr.length;i++){if(arr[i]===value){return i}}return-1}api.indexOf=indexOf;function sortBy$2(arr,orderFunc){var result=cloneArr(arr);result.sort(function(a,b){return orderFunc(a)-orderFunc(b)});return result}api.sortBy=sortBy$2;function zipObject(keys2,values2){if(keys2.length!==values2.length){throw Error("can't zipObject with different number of keys and values!")}var result={};for(var i=0;i<keys2.length;i++){result[keys2[i]]=values2[i]}return result}api.zipObject=zipObject;function assign(target){var sources=[];for(var _i=1;_i<arguments.length;_i++){sources[_i-1]=arguments[_i]}for(var i=0;i<sources.length;i++){var curSource=sources[i];var currSourceKeys=keys$2(curSource);for(var j=0;j<currSourceKeys.length;j++){var currKey=currSourceKeys[j];target[currKey]=curSource[currKey]}}return target}api.assign=assign;function assignNoOverwrite(target){var sources=[];for(var _i=1;_i<arguments.length;_i++){sources[_i-1]=arguments[_i]}for(var i=0;i<sources.length;i++){var curSource=sources[i];var currSourceKeys=keys$2(curSource);for(var j=0;j<currSourceKeys.length;j++){var currKey=currSourceKeys[j];if(!has(target,currKey)){target[currKey]=curSource[currKey]}}}return target}api.assignNoOverwrite=assignNoOverwrite;function defaults(){var sources=[];for(var _i=0;_i<arguments.length;_i++){sources[_i]=arguments[_i]}return assignNoOverwrite.apply(void 0,__spreadArray([{}],sources))}api.defaults=defaults;function groupBy(arr,groupKeyFunc){var result={};forEach(arr,function(item){var currGroupKey=groupKeyFunc(item);var currGroupArr=result[currGroupKey];if(currGroupArr){currGroupArr.push(item)}else{result[currGroupKey]=[item]}});return result}api.groupBy=groupBy;function merge(obj1,obj2){var result=cloneObj(obj1);var keys2=keys$2(obj2);for(var i=0;i<keys2.length;i++){var key=keys2[i];var value=obj2[key];result[key]=value}return result}api.merge=merge;function NOOP(){}api.NOOP=NOOP;function IDENTITY(item){return item}api.IDENTITY=IDENTITY;function packArray(holeyArr){var result=[];for(var i=0;i<holeyArr.length;i++){var orgValue=holeyArr[i];result.push(orgValue!==void 0?orgValue:void 0)}return result}api.packArray=packArray;function PRINT_ERROR(msg){if(console&&console.error){console.error("Error: "+msg)}}api.PRINT_ERROR=PRINT_ERROR;function PRINT_WARNING(msg){if(console&&console.warn){console.warn("Warning: "+msg)}}api.PRINT_WARNING=PRINT_WARNING;function isES2015MapSupported(){return typeof Map==="function"}api.isES2015MapSupported=isES2015MapSupported;function peek(arr){return arr[arr.length-1]}api.peek=peek;function timer(func){var start=new Date().getTime();var val=func();var end=new Date().getTime();var total=end-start;return{time:total,value:val}}api.timer=timer;function toFastProperties(toBecomeFast){function FakeConstructor(){}FakeConstructor.prototype=toBecomeFast;var fakeInstance=new FakeConstructor;function fakeAccess(){return typeof fakeInstance.bar}fakeAccess();fakeAccess();return toBecomeFast}api.toFastProperties=toFastProperties;function upperFirst(str){if(!str){return str}var firstChar=getCharacterFromCodePointAt(str,0);return firstChar.toUpperCase()+str.substring(firstChar.length)}api.upperFirst=upperFirst;var surrogatePairPattern=/[\uD800-\uDBFF][\uDC00-\uDFFF]/;function getCharacterFromCodePointAt(str,idx){var surrogatePairCandidate=str.substring(idx,idx+1);return surrogatePairPattern.test(surrogatePairCandidate)?surrogatePairCandidate:str[idx]}var follow={};var rest={};var gast_public={};var tokens_public={};var lexer_public={};var lexer={};var regexpToAst={exports:{}};(function(module2){(function(root2,factory){if(module2.exports){module2.exports=factory()}else{root2.regexpToAst=factory()}})(typeof self!=="undefined"?self:commonjsGlobal,function(){function RegExpParser(){}RegExpParser.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}};RegExpParser.prototype.restoreState=function(newState){this.idx=newState.idx;this.input=newState.input;this.groupIdx=newState.groupIdx};RegExpParser.prototype.pattern=function(input){this.idx=0;this.input=input;this.groupIdx=0;this.consumeChar("/");var value=this.disjunction();this.consumeChar("/");var flags={type:"Flags",loc:{begin:this.idx,end:input.length},global:false,ignoreCase:false,multiLine:false,unicode:false,sticky:false};while(this.isRegExpFlag()){switch(this.popChar()){case"g":addFlag(flags,"global");break;case"i":addFlag(flags,"ignoreCase");break;case"m":addFlag(flags,"multiLine");break;case"u":addFlag(flags,"unicode");break;case"y":addFlag(flags,"sticky");break}}if(this.idx!==this.input.length){throw Error("Redundant input: "+this.input.substring(this.idx))}return{type:"Pattern",flags,value,loc:this.loc(0)}};RegExpParser.prototype.disjunction=function(){var alts=[];var begin=this.idx;alts.push(this.alternative());while(this.peekChar()==="|"){this.consumeChar("|");alts.push(this.alternative())}return{type:"Disjunction",value:alts,loc:this.loc(begin)}};RegExpParser.prototype.alternative=function(){var terms=[];var begin=this.idx;while(this.isTerm()){terms.push(this.term())}return{type:"Alternative",value:terms,loc:this.loc(begin)}};RegExpParser.prototype.term=function(){if(this.isAssertion()){return this.assertion()}else{return this.atom()}};RegExpParser.prototype.assertion=function(){var begin=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(begin)};case"$":return{type:"EndAnchor",loc:this.loc(begin)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(begin)};case"B":return{type:"NonWordBoundary",loc:this.loc(begin)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var type;switch(this.popChar()){case"=":type="Lookahead";break;case"!":type="NegativeLookahead";break}ASSERT_EXISTS(type);var disjunction=this.disjunction();this.consumeChar(")");return{type,value:disjunction,loc:this.loc(begin)}}ASSERT_NEVER_REACH_HERE()};RegExpParser.prototype.quantifier=function(isBacktracking){var range;var begin=this.idx;switch(this.popChar()){case"*":range={atLeast:0,atMost:Infinity};break;case"+":range={atLeast:1,atMost:Infinity};break;case"?":range={atLeast:0,atMost:1};break;case"{":var atLeast=this.integerIncludingZero();switch(this.popChar()){case"}":range={atLeast,atMost:atLeast};break;case",":var atMost;if(this.isDigit()){atMost=this.integerIncludingZero();range={atLeast,atMost}}else{range={atLeast,atMost:Infinity}}this.consumeChar("}");break}if(isBacktracking===true&&range===void 0){return void 0}ASSERT_EXISTS(range);break}if(isBacktracking===true&&range===void 0){return void 0}ASSERT_EXISTS(range);if(this.peekChar(0)==="?"){this.consumeChar("?");range.greedy=false}else{range.greedy=true}range.type="Quantifier";range.loc=this.loc(begin);return range};RegExpParser.prototype.atom=function(){var atom;var begin=this.idx;switch(this.peekChar()){case".":atom=this.dotAll();break;case"\\":atom=this.atomEscape();break;case"[":atom=this.characterClass();break;case"(":atom=this.group();break}if(atom===void 0&&this.isPatternCharacter()){atom=this.patternCharacter()}ASSERT_EXISTS(atom);atom.loc=this.loc(begin);if(this.isQuantifier()){atom.quantifier=this.quantifier()}return atom};RegExpParser.prototype.dotAll=function(){this.consumeChar(".");return{type:"Set",complement:true,value:[cc("\n"),cc("\r"),cc("\u2028"),cc("\u2029")]}};RegExpParser.prototype.atomEscape=function(){this.consumeChar("\\");switch(this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}};RegExpParser.prototype.decimalEscapeAtom=function(){var value=this.positiveInteger();return{type:"GroupBackReference",value}};RegExpParser.prototype.characterClassEscape=function(){var set;var complement=false;switch(this.popChar()){case"d":set=digitsCharCodes;break;case"D":set=digitsCharCodes;complement=true;break;case"s":set=whitespaceCodes;break;case"S":set=whitespaceCodes;complement=true;break;case"w":set=wordCharCodes;break;case"W":set=wordCharCodes;complement=true;break}ASSERT_EXISTS(set);return{type:"Set",value:set,complement}};RegExpParser.prototype.controlEscapeAtom=function(){var escapeCode;switch(this.popChar()){case"f":escapeCode=cc("\f");break;case"n":escapeCode=cc("\n");break;case"r":escapeCode=cc("\r");break;case"t":escapeCode=cc(" ");break;case"v":escapeCode=cc("\v");break}ASSERT_EXISTS(escapeCode);return{type:"Character",value:escapeCode}};RegExpParser.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var letter=this.popChar();if(/[a-zA-Z]/.test(letter)===false){throw Error("Invalid ")}var letterCode=letter.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:letterCode}};RegExpParser.prototype.nulCharacterAtom=function(){this.consumeChar("0");return{type:"Character",value:cc("\0")}};RegExpParser.prototype.hexEscapeSequenceAtom=function(){this.consumeChar("x");return this.parseHexDigits(2)};RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom=function(){this.consumeChar("u");return this.parseHexDigits(4)};RegExpParser.prototype.identityEscapeAtom=function(){var escapedChar=this.popChar();return{type:"Character",value:cc(escapedChar)}};RegExpParser.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case"\n":case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var nextChar=this.popChar();return{type:"Character",value:cc(nextChar)}}};RegExpParser.prototype.characterClass=function(){var set=[];var complement=false;this.consumeChar("[");if(this.peekChar(0)==="^"){this.consumeChar("^");complement=true}while(this.isClassAtom()){var from=this.classAtom();var isFromSingleChar=from.type==="Character";if(isFromSingleChar&&this.isRangeDash()){this.consumeChar("-");var to=this.classAtom();var isToSingleChar=to.type==="Character";if(isToSingleChar){if(to.value<from.value){throw Error("Range out of order in character class")}set.push({from:from.value,to:to.value})}else{insertToSet(from.value,set);set.push(cc("-"));insertToSet(to.value,set)}}else{insertToSet(from.value,set)}}this.consumeChar("]");return{type:"Set",complement,value:set}};RegExpParser.prototype.classAtom=function(){switch(this.peekChar()){case"]":case"\n":case"\r":case"\u2028":case"\u2029":throw Error("TBD");case"\\":return this.classEscape();default:return this.classPatternCharacterAtom()}};RegExpParser.prototype.classEscape=function(){this.consumeChar("\\");switch(this.peekChar()){case"b":this.consumeChar("b");return{type:"Character",value:cc("\b")};case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}};RegExpParser.prototype.group=function(){var capturing=true;this.consumeChar("(");switch(this.peekChar(0)){case"?":this.consumeChar("?");this.consumeChar(":");capturing=false;break;default:this.groupIdx++;break}var value=this.disjunction();this.consumeChar(")");var groupAst={type:"Group",capturing,value};if(capturing){groupAst.idx=this.groupIdx}return groupAst};RegExpParser.prototype.positiveInteger=function(){var number=this.popChar();if(decimalPatternNoZero.test(number)===false){throw Error("Expecting a positive integer")}while(decimalPattern.test(this.peekChar(0))){number+=this.popChar()}return parseInt(number,10)};RegExpParser.prototype.integerIncludingZero=function(){var number=this.popChar();if(decimalPattern.test(number)===false){throw Error("Expecting an integer")}while(decimalPattern.test(this.peekChar(0))){number+=this.popChar()}return parseInt(number,10)};RegExpParser.prototype.patternCharacter=function(){var nextChar=this.popChar();switch(nextChar){case"\n":case"\r":case"\u2028":case"\u2029":case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":throw Error("TBD");default:return{type:"Character",value:cc(nextChar)}}};RegExpParser.prototype.isRegExpFlag=function(){switch(this.peekChar(0)){case"g":case"i":case"m":case"u":case"y":return true;default:return false}};RegExpParser.prototype.isRangeDash=function(){return this.peekChar()==="-"&&this.isClassAtom(1)};RegExpParser.prototype.isDigit=function(){return decimalPattern.test(this.peekChar(0))};RegExpParser.prototype.isClassAtom=function(howMuch){if(howMuch===void 0){howMuch=0}switch(this.peekChar(howMuch)){case"]":case"\n":case"\r":case"\u2028":case"\u2029":return false;default:return true}};RegExpParser.prototype.isTerm=function(){return this.isAtom()||this.isAssertion()};RegExpParser.prototype.isAtom=function(){if(this.isPatternCharacter()){return true}switch(this.peekChar(0)){case".":case"\\":case"[":case"(":return true;default:return false}};RegExpParser.prototype.isAssertion=function(){switch(this.peekChar(0)){case"^":case"$":return true;case"\\":switch(this.peekChar(1)){case"b":case"B":return true;default:return false}case"(":return this.peekChar(1)==="?"&&(this.peekChar(2)==="="||this.peekChar(2)==="!");default:return false}};RegExpParser.prototype.isQuantifier=function(){var prevState=this.saveState();try{return this.quantifier(true)!==void 0}catch(e){return false}finally{this.restoreState(prevState)}};RegExpParser.prototype.isPatternCharacter=function(){switch(this.peekChar()){case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":case"/":case"\n":case"\r":case"\u2028":case"\u2029":return false;default:return true}};RegExpParser.prototype.parseHexDigits=function(howMany){var hexString="";for(var i2=0;i2<howMany;i2++){var hexChar=this.popChar();if(hexDigitPattern.test(hexChar)===false){throw Error("Expecting a HexDecimal digits")}hexString+=hexChar}var charCode=parseInt(hexString,16);return{type:"Character",value:charCode}};RegExpParser.prototype.peekChar=function(howMuch){if(howMuch===void 0){howMuch=0}return this.input[this.idx+howMuch]};RegExpParser.prototype.popChar=function(){var nextChar=this.peekChar(0);this.consumeChar();return nextChar};RegExpParser.prototype.consumeChar=function(char){if(char!==void 0&&this.input[this.idx]!==char){throw Error("Expected: '"+char+"' but found: '"+this.input[this.idx]+"' at offset: "+this.idx)}if(this.idx>=this.input.length){throw Error("Unexpected end of input")}this.idx++};RegExpParser.prototype.loc=function(begin){return{begin,end:this.idx}};var hexDigitPattern=/[0-9a-fA-F]/;var decimalPattern=/[0-9]/;var decimalPatternNoZero=/[1-9]/;function cc(char){return char.charCodeAt(0)}function insertToSet(item,set){if(item.length!==void 0){item.forEach(function(subItem){set.push(subItem)})}else{set.push(item)}}function addFlag(flagObj,flagKey){if(flagObj[flagKey]===true){throw"duplicate flag "+flagKey}flagObj[flagKey]=true}function ASSERT_EXISTS(obj){if(obj===void 0){throw Error("Internal Error - Should never get here!")}}function ASSERT_NEVER_REACH_HERE(){throw Error("Internal Error - Should never get here!")}var i;var digitsCharCodes=[];for(i=cc("0");i<=cc("9");i++){digitsCharCodes.push(i)}var wordCharCodes=[cc("_")].concat(digitsCharCodes);for(i=cc("a");i<=cc("z");i++){wordCharCodes.push(i)}for(i=cc("A");i<=cc("Z");i++){wordCharCodes.push(i)}var whitespaceCodes=[cc(" "),cc("\f"),cc("\n"),cc("\r"),cc(" "),cc("\v"),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc("\u2028"),cc("\u2029"),cc(" "),cc(" "),cc(" "),cc("\uFEFF")];function BaseRegExpVisitor(){}BaseRegExpVisitor.prototype.visitChildren=function(node){for(var key in node){var child=node[key];if(node.hasOwnProperty(key)){if(child.type!==void 0){this.visit(child)}else if(Array.isArray(child)){child.forEach(function(subChild){this.visit(subChild)},this)}}}};BaseRegExpVisitor.prototype.visit=function(node){switch(node.type){case"Pattern":this.visitPattern(node);break;case"Flags":this.visitFlags(node);break;case"Disjunction":this.visitDisjunction(node);break;case"Alternative":this.visitAlternative(node);break;case"StartAnchor":this.visitStartAnchor(node);break;case"EndAnchor":this.visitEndAnchor(node);break;case"WordBoundary":this.visitWordBoundary(node);break;case"NonWordBoundary":this.visitNonWordBoundary(node);break;case"Lookahead":this.visitLookahead(node);break;case"NegativeLookahead":this.visitNegativeLookahead(node);break;case"Character":this.visitCharacter(node);break;case"Set":this.visitSet(node);break;case"Group":this.visitGroup(node);break;case"GroupBackReference":this.visitGroupBackReference(node);break;case"Quantifier":this.visitQuantifier(node);break}this.visitChildren(node)};BaseRegExpVisitor.prototype.visitPattern=function(node){};BaseRegExpVisitor.prototype.visitFlags=function(node){};BaseRegExpVisitor.prototype.visitDisjunction=function(node){};BaseRegExpVisitor.prototype.visitAlternative=function(node){};BaseRegExpVisitor.prototype.visitStartAnchor=function(node){};BaseRegExpVisitor.prototype.visitEndAnchor=function(node){};BaseRegExpVisitor.prototype.visitWordBoundary=function(node){};BaseRegExpVisitor.prototype.visitNonWordBoundary=function(node){};BaseRegExpVisitor.prototype.visitLookahead=function(node){};BaseRegExpVisitor.prototype.visitNegativeLookahead=function(node){};BaseRegExpVisitor.prototype.visitCharacter=function(node){};BaseRegExpVisitor.prototype.visitSet=function(node){};BaseRegExpVisitor.prototype.visitGroup=function(node){};BaseRegExpVisitor.prototype.visitGroupBackReference=function(node){};BaseRegExpVisitor.prototype.visitQuantifier=function(node){};return{RegExpParser,BaseRegExpVisitor,VERSION:"0.5.0"}})})(regexpToAst);var reg_exp={};var reg_exp_parser={};Object.defineProperty(reg_exp_parser,"__esModule",{value:true});reg_exp_parser.clearRegExpParserCache=reg_exp_parser.getRegExpAst=void 0;var regexp_to_ast_1=regexpToAst.exports;var regExpAstCache={};var regExpParser=new regexp_to_ast_1.RegExpParser;function getRegExpAst(regExp){var regExpStr=regExp.toString();if(regExpAstCache.hasOwnProperty(regExpStr)){return regExpAstCache[regExpStr]}else{var regExpAst=regExpParser.pattern(regExpStr);regExpAstCache[regExpStr]=regExpAst;return regExpAst}}reg_exp_parser.getRegExpAst=getRegExpAst;function clearRegExpParserCache(){regExpAstCache={}}reg_exp_parser.clearRegExpParserCache=clearRegExpParserCache;(function(exports3){var __extends2=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(exports3,"__esModule",{value:true});exports3.canMatchCharCode=exports3.firstCharOptimizedIndices=exports3.getOptimizedStartCodesIndices=exports3.failedOptimizationPrefixMsg=void 0;var regexp_to_ast_12=regexpToAst.exports;var utils_12=api;var reg_exp_parser_1=reg_exp_parser;var lexer_1=lexer;var complementErrorMessage="Complement Sets are not supported for first char optimization";exports3.failedOptimizationPrefixMsg='Unable to use "first char" lexer optimizations:\n';function getOptimizedStartCodesIndices(regExp,ensureOptimizations){if(ensureOptimizations===void 0){ensureOptimizations=false}try{var ast=reg_exp_parser_1.getRegExpAst(regExp);var firstChars=firstCharOptimizedIndices(ast.value,{},ast.flags.ignoreCase);return firstChars}catch(e){if(e.message===complementErrorMessage){if(ensureOptimizations){utils_12.PRINT_WARNING(""+exports3.failedOptimizationPrefixMsg+(" Unable to optimize: < "+regExp.toString()+" >\n")+" Complement Sets cannot be automatically optimized.\n This will disable the lexer's first char optimizations.\n See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.")}}else{var msgSuffix="";if(ensureOptimizations){msgSuffix="\n This will disable the lexer's first char optimizations.\n See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."}utils_12.PRINT_ERROR(exports3.failedOptimizationPrefixMsg+"\n"+(" Failed parsing: < "+regExp.toString()+" >\n")+(" Using the regexp-to-ast library version: "+regexp_to_ast_12.VERSION+"\n")+" Please open an issue at: https://github.com/bd82/regexp-to-ast/issues"+msgSuffix)}}return[]}exports3.getOptimizedStartCodesIndices=getOptimizedStartCodesIndices;function firstCharOptimizedIndices(ast,result,ignoreCase){switch(ast.type){case"Disjunction":for(var i=0;i<ast.value.length;i++){firstCharOptimizedIndices(ast.value[i],result,ignoreCase)}break;case"Alternative":var terms=ast.value;for(var i=0;i<terms.length;i++){var term=terms[i];switch(term.type){case"EndAnchor":case"GroupBackReference":case"Lookahead":case"NegativeLookahead":case"StartAnchor":case"WordBoundary":case"NonWordBoundary":continue}var atom=term;switch(atom.type){case"Character":addOptimizedIdxToResult(atom.value,result,ignoreCase);break;case"Set":if(atom.complement===true){throw Error(complementErrorMessage)}utils_12.forEach(atom.value,function(code){if(typeof code==="number"){addOptimizedIdxToResult(code,result,ignoreCase)}else{var range=code;if(ignoreCase===true){for(var rangeCode=range.from;rangeCode<=range.to;rangeCode++){addOptimizedIdxToResult(rangeCode,result,ignoreCase)}}else{for(var rangeCode=range.from;rangeCode<=range.to&&rangeCode<lexer_1.minOptimizationVal;rangeCode++){addOptimizedIdxToResult(rangeCode,result,ignoreCase)}if(range.to>=lexer_1.minOptimizationVal){var minUnOptVal=range.from>=lexer_1.minOptimizationVal?range.from:lexer_1.minOptimizationVal;var maxUnOptVal=range.to;var minOptIdx=lexer_1.charCodeToOptimizedIndex(minUnOptVal);var maxOptIdx=lexer_1.charCodeToOptimizedIndex(maxUnOptVal);for(var currOptIdx=minOptIdx;currOptIdx<=maxOptIdx;currOptIdx++){result[currOptIdx]=currOptIdx}}}}});break;case"Group":firstCharOptimizedIndices(atom.value,result,ignoreCase);break;default:throw Error("Non Exhaustive Match")}var isOptionalQuantifier=atom.quantifier!==void 0&&atom.quantifier.atLeast===0;if(atom.type==="Group"&&isWholeOptional(atom)===false||atom.type!=="Group"&&isOptionalQuantifier===false){break}}break;default:throw Error("non exhaustive match!")}return utils_12.values(result)}exports3.firstCharOptimizedIndices=firstCharOptimizedIndices;function addOptimizedIdxToResult(code,result,ignoreCase){var optimizedCharIdx=lexer_1.charCodeToOptimizedIndex(code);result[optimizedCharIdx]=optimizedCharIdx;if(ignoreCase===true){handleIgnoreCase(code,result)}}function handleIgnoreCase(code,result){var char=String.fromCharCode(code);var upperChar=char.toUpperCase();if(upperChar!==char){var optimizedCharIdx=lexer_1.charCodeToOptimizedIndex(upperChar.charCodeAt(0));result[optimizedCharIdx]=optimizedCharIdx}else{var lowerChar=char.toLowerCase();if(lowerChar!==char){var optimizedCharIdx=lexer_1.charCodeToOptimizedIndex(lowerChar.charCodeAt(0));result[optimizedCharIdx]=optimizedCharIdx}}}function findCode(setNode,targetCharCodes){return utils_12.find(setNode.value,function(codeOrRange){if(typeof codeOrRange==="number"){return utils_12.contains(targetCharCodes,codeOrRange)}else{var range_1=codeOrRange;return utils_12.find(targetCharCodes,function(targetCode){return range_1.from<=targetCode&&targetCode<=range_1.to})!==void 0}})}function isWholeOptional(ast){if(ast.quantifier&&ast.quantifier.atLeast===0){return true}if(!ast.value){return false}return utils_12.isArray(ast.value)?utils_12.every(ast.value,isWholeOptional):isWholeOptional(ast.value)}var CharCodeFinder=(function(_super){__extends2(CharCodeFinder2,_super);function CharCodeFinder2(targetCharCodes){var _this=_super.call(this)||this;_this.targetCharCodes=targetCharCodes;_this.found=false;return _this}CharCodeFinder2.prototype.visitChildren=function(node){if(this.found===true){return}switch(node.type){case"Lookahead":this.visitLookahead(node);return;case"NegativeLookahead":this.visitNegativeLookahead(node);return}_super.prototype.visitChildren.call(this,node)};CharCodeFinder2.prototype.visitCharacter=function(node){if(utils_12.contains(this.targetCharCodes,node.value)){this.found=true}};CharCodeFinder2.prototype.visitSet=function(node){if(node.complement){if(findCode(node,this.targetCharCodes)===void 0){this.found=true}}else{if(findCode(node,this.targetCharCodes)!==void 0){this.found=true}}};return CharCodeFinder2})(regexp_to_ast_12.BaseRegExpVisitor);function canMatchCharCode(charCodes,pattern){if(pattern instanceof RegExp){var ast=reg_exp_parser_1.getRegExpAst(pattern);var charCodeFinder=new CharCodeFinder(charCodes);charCodeFinder.visit(ast);return charCodeFinder.found}else{return utils_12.find(pattern,function(char){return utils_12.contains(charCodes,char.charCodeAt(0))})!==void 0}}exports3.canMatchCharCode=canMatchCharCode})(reg_exp);(function(exports3){var __extends2=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(exports3,"__esModule",{value:true});exports3.charCodeToOptimizedIndex=exports3.minOptimizationVal=exports3.buildLineBreakIssueMessage=exports3.LineTerminatorOptimizedTester=exports3.isShortPattern=exports3.isCustomPattern=exports3.cloneEmptyGroups=exports3.performWarningRuntimeChecks=exports3.performRuntimeChecks=exports3.addStickyFlag=exports3.addStartOfInput=exports3.findUnreachablePatterns=exports3.findModesThatDoNotExist=exports3.findInvalidGroupType=exports3.findDuplicatePatterns=exports3.findUnsupportedFlags=exports3.findStartOfInputAnchor=exports3.findEmptyMatchRegExps=exports3.findEndOfInputAnchor=exports3.findInvalidPatterns=exports3.findMissingPatterns=exports3.validatePatterns=exports3.analyzeTokenTypes=exports3.enableSticky=exports3.disableSticky=exports3.SUPPORT_STICKY=exports3.MODES=exports3.DEFAULT_MODE=void 0;var regexp_to_ast_12=regexpToAst.exports;var lexer_public_12=lexer_public;var utils_12=api;var reg_exp_1=reg_exp;var reg_exp_parser_1=reg_exp_parser;var PATTERN="PATTERN";exports3.DEFAULT_MODE="defaultMode";exports3.MODES="modes";exports3.SUPPORT_STICKY=typeof new RegExp("(?:)").sticky==="boolean";function disableSticky(){exports3.SUPPORT_STICKY=false}exports3.disableSticky=disableSticky;function enableSticky(){exports3.SUPPORT_STICKY=true}exports3.enableSticky=enableSticky;function analyzeTokenTypes(tokenTypes,options){options=utils_12.defaults(options,{useSticky:exports3.SUPPORT_STICKY,debug:false,safeMode:false,positionTracking:"full",lineTerminatorCharacters:["\r","\n"],tracer:function(msg,action){return action()}});var tracer=options.tracer;tracer("initCharCodeToOptimizedIndexMap",function(){initCharCodeToOptimizedIndexMap()});var onlyRelevantTypes;tracer("Reject Lexer.NA",function(){onlyRelevantTypes=utils_12.reject(tokenTypes,function(currType){return currType[PATTERN]===lexer_public_12.Lexer.NA})});var hasCustom=false;var allTransformedPatterns;tracer("Transform Patterns",function(){hasCustom=false;allTransformedPatterns=utils_12.map(onlyRelevantTypes,function(currType){var currPattern=currType[PATTERN];if(utils_12.isRegExp(currPattern)){var regExpSource=currPattern.source;if(regExpSource.length===1&&regExpSource!=="^"&&regExpSource!=="$"&&regExpSource!=="."&&!currPattern.ignoreCase){return regExpSource}else if(regExpSource.length===2&&regExpSource[0]==="\\"&&!utils_12.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],regExpSource[1])){return regExpSource[1]}else{return options.useSticky?addStickyFlag(currPattern):addStartOfInput(currPattern)}}else if(utils_12.isFunction(currPattern)){hasCustom=true;return{exec:currPattern}}else if(utils_12.has(currPattern,"exec")){hasCustom=true;return currPattern}else if(typeof currPattern==="string"){if(currPattern.length===1){return currPattern}else{var escapedRegExpString=currPattern.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&");var wrappedRegExp=new RegExp(escapedRegExpString);return options.useSticky?addStickyFlag(wrappedRegExp):addStartOfInput(wrappedRegExp)}}else{throw Error("non exhaustive match")}})});var patternIdxToType;var patternIdxToGroup;var patternIdxToLongerAltIdx;var patternIdxToPushMode;var patternIdxToPopMode;tracer("misc mapping",function(){patternIdxToType=utils_12.map(onlyRelevantTypes,function(currType){return currType.tokenTypeIdx});patternIdxToGroup=utils_12.map(onlyRelevantTypes,function(clazz){var groupName=clazz.GROUP;if(groupName===lexer_public_12.Lexer.SKIPPED){return void 0}else if(utils_12.isString(groupName)){return groupName}else if(utils_12.isUndefined(groupName)){return false}else{throw Error("non exhaustive match")}});patternIdxToLongerAltIdx=utils_12.map(onlyRelevantTypes,function(clazz){var longerAltType=clazz.LONGER_ALT;if(longerAltType){var longerAltIdx=utils_12.indexOf(onlyRelevantTypes,longerAltType);return longerAltIdx}});patternIdxToPushMode=utils_12.map(onlyRelevantTypes,function(clazz){return clazz.PUSH_MODE});patternIdxToPopMode=utils_12.map(onlyRelevantTypes,function(clazz){return utils_12.has(clazz,"POP_MODE")})});var patternIdxToCanLineTerminator;tracer("Line Terminator Handling",function(){var lineTerminatorCharCodes=getCharCodes(options.lineTerminatorCharacters);patternIdxToCanLineTerminator=utils_12.map(onlyRelevantTypes,function(tokType){return false});if(options.positionTracking!=="onlyOffset"){patternIdxToCanLineTerminator=utils_12.map(onlyRelevantTypes,function(tokType){if(utils_12.has(tokType,"LINE_BREAKS")){return tokType.LINE_BREAKS}else{if(checkLineBreaksIssues(tokType,lineTerminatorCharCodes)===false){return reg_exp_1.canMatchCharCode(lineTerminatorCharCodes,tokType.PATTERN)}}})}});var patternIdxToIsCustom;var patternIdxToShort;var emptyGroups;var patternIdxToConfig;tracer("Misc Mapping #2",function(){patternIdxToIsCustom=utils_12.map(onlyRelevantTypes,isCustomPattern);patternIdxToShort=utils_12.map(allTransformedPatterns,isShortPattern);emptyGroups=utils_12.reduce(onlyRelevantTypes,function(acc,clazz){var groupName=clazz.GROUP;if(utils_12.isString(groupName)&&!(groupName===lexer_public_12.Lexer.SKIPPED)){acc[groupName]=[]}return acc},{});patternIdxToConfig=utils_12.map(allTransformedPatterns,function(x,idx){return{pattern:allTransformedPatterns[idx],longerAlt:patternIdxToLongerAltIdx[idx],canLineTerminator:patternIdxToCanLineTerminator[idx],isCustom:patternIdxToIsCustom[idx],short:patternIdxToShort[idx],group:patternIdxToGroup[idx],push:patternIdxToPushMode[idx],pop:patternIdxToPopMode[idx],tokenTypeIdx:patternIdxToType[idx],tokenType:onlyRelevantTypes[idx]}})});var canBeOptimized=true;var charCodeToPatternIdxToConfig=[];if(!options.safeMode){tracer("First Char Optimization",function(){charCodeToPatternIdxToConfig=utils_12.reduce(onlyRelevantTypes,function(result,currTokType,idx){if(typeof currTokType.PATTERN==="string"){var charCode=currTokType.PATTERN.charCodeAt(0);var optimizedIdx=charCodeToOptimizedIndex(charCode);addToMapOfArrays(result,optimizedIdx,patternIdxToConfig[idx])}else if(utils_12.isArray(currTokType.START_CHARS_HINT)){var lastOptimizedIdx_1;utils_12.forEach(currTokType.START_CHARS_HINT,function(charOrInt){var charCode2=typeof charOrInt==="string"?charOrInt.charCodeAt(0):charOrInt;var currOptimizedIdx=charCodeToOptimizedIndex(charCode2);if(lastOptimizedIdx_1!==currOptimizedIdx){lastOptimizedIdx_1=currOptimizedIdx;addToMapOfArrays(result,currOptimizedIdx,patternIdxToConfig[idx])}})}else if(utils_12.isRegExp(currTokType.PATTERN)){if(currTokType.PATTERN.unicode){canBeOptimized=false;if(options.ensureOptimizations){utils_12.PRINT_ERROR(""+reg_exp_1.failedOptimizationPrefixMsg+(" Unable to analyze < "+currTokType.PATTERN.toString()+" > pattern.\n")+" The regexp unicode flag is not currently supported by the regexp-to-ast library.\n This will disable the lexer's first char optimizations.\n For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE")}}else{var optimizedCodes=reg_exp_1.getOptimizedStartCodesIndices(currTokType.PATTERN,options.ensureOptimizations);if(utils_12.isEmpty(optimizedCodes)){canBeOptimized=false}utils_12.forEach(optimizedCodes,function(code){addToMapOfArrays(result,code,patternIdxToConfig[idx])})}}else{if(options.ensureOptimizations){utils_12.PRINT_ERROR(""+reg_exp_1.failedOptimizationPrefixMsg+(" TokenType: <"+currTokType.name+"> is using a custom token pattern without providing <start_chars_hint> parameter.\n")+" This will disable the lexer's first char optimizations.\n For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE")}canBeOptimized=false}return result},[])})}tracer("ArrayPacking",function(){charCodeToPatternIdxToConfig=utils_12.packArray(charCodeToPatternIdxToConfig)});return{emptyGroups,patternIdxToConfig,charCodeToPatternIdxToConfig,hasCustom,canBeOptimized}}exports3.analyzeTokenTypes=analyzeTokenTypes;function validatePatterns(tokenTypes,validModesNames){var errors=[];var missingResult=findMissingPatterns(tokenTypes);errors=errors.concat(missingResult.errors);var invalidResult=findInvalidPatterns(missingResult.valid);var validTokenTypes=invalidResult.valid;errors=errors.concat(invalidResult.errors);errors=errors.concat(validateRegExpPattern(validTokenTypes));errors=errors.concat(findInvalidGroupType(validTokenTypes));errors=errors.concat(findModesThatDoNotExist(validTokenTypes,validModesNames));errors=errors.concat(findUnreachablePatterns(validTokenTypes));return errors}exports3.validatePatterns=validatePatterns;function validateRegExpPattern(tokenTypes){var errors=[];var withRegExpPatterns=utils_12.filter(tokenTypes,function(currTokType){return utils_12.isRegExp(currTokType[PATTERN])});errors=errors.concat(findEndOfInputAnchor(withRegExpPatterns));errors=errors.concat(findStartOfInputAnchor(withRegExpPatterns));errors=errors.concat(findUnsupportedFlags(withRegExpPatterns));errors=errors.concat(findDuplicatePatterns(withRegExpPatterns));errors=errors.concat(findEmptyMatchRegExps(withRegExpPatterns));return errors}function findMissingPatterns(tokenTypes){var tokenTypesWithMissingPattern=utils_12.filter(tokenTypes,function(currType){return!utils_12.has(currType,PATTERN)});var errors=utils_12.map(tokenTypesWithMissingPattern,function(currType){return{message:"Token Type: ->"+currType.name+"<- missing static 'PATTERN' property",type:lexer_public_12.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[currType]}});var valid=utils_12.difference(tokenTypes,tokenTypesWithMissingPattern);return{errors,valid}}exports3.findMissingPatterns=findMissingPatterns;function findInvalidPatterns(tokenTypes){var tokenTypesWithInvalidPattern=utils_12.filter(tokenTypes,function(currType){var pattern=currType[PATTERN];return!utils_12.isRegExp(pattern)&&!utils_12.isFunction(pattern)&&!utils_12.has(pattern,"exec")&&!utils_12.isString(pattern)});var errors=utils_12.map(tokenTypesWithInvalidPattern,function(currType){return{message:"Token Type: ->"+currType.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:lexer_public_12.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[currType]}});var valid=utils_12.difference(tokenTypes,tokenTypesWithInvalidPattern);return{errors,valid}}exports3.findInvalidPatterns=findInvalidPatterns;var end_of_input=/[^\\][\$]/;function findEndOfInputAnchor(tokenTypes){var EndAnchorFinder=(function(_super){__extends2(EndAnchorFinder2,_super);function EndAnchorFinder2(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.found=false;return _this}EndAnchorFinder2.prototype.visitEndAnchor=function(node){this.found=true};return EndAnchorFinder2})(regexp_to_ast_12.BaseRegExpVisitor);var invalidRegex=utils_12.filter(tokenTypes,function(currType){var pattern=currType[PATTERN];try{var regexpAst=reg_exp_parser_1.getRegExpAst(pattern);var endAnchorVisitor=new EndAnchorFinder;endAnchorVisitor.visit(regexpAst);return endAnchorVisitor.found}catch(e){return end_of_input.test(pattern.source)}});var errors=utils_12.map(invalidRegex,function(currType){return{message:"Unexpected RegExp Anchor Error:\n Token Type: ->"+currType.name+"<- static 'PATTERN' cannot contain end of input anchor '$'\n See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.",type:lexer_public_12.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[currType]}});return errors}exports3.findEndOfInputAnchor=findEndOfInputAnchor;function findEmptyMatchRegExps(tokenTypes){var matchesEmptyString=utils_12.filter(tokenTypes,function(currType){var pattern=currType[PATTERN];return pattern.test("")});var errors=utils_12.map(matchesEmptyString,function(currType){return{message:"Token Type: ->"+currType.name+"<- static 'PATTERN' must not match an empty string",type:lexer_public_12.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[currType]}});return errors}exports3.findEmptyMatchRegExps=findEmptyMatchRegExps;var start_of_input=/[^\\[][\^]|^\^/;function findStartOfInputAnchor(tokenTypes){var StartAnchorFinder=(function(_super){__extends2(StartAnchorFinder2,_super);function StartAnchorFinder2(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.found=false;return _this}StartAnchorFinder2.prototype.visitStartAnchor=function(node){this.found=true};return StartAnchorFinder2})(regexp_to_ast_12.BaseRegExpVisitor);var invalidRegex=utils_12.filter(tokenTypes,function(currType){var pattern=currType[PATTERN];try{var regexpAst=reg_exp_parser_1.getRegExpAst(pattern);var startAnchorVisitor=new StartAnchorFinder;startAnchorVisitor.visit(regexpAst);return startAnchorVisitor.found}catch(e){return start_of_input.test(pattern.source)}});var errors=utils_12.map(invalidRegex,function(currType){return{message:"Unexpected RegExp Anchor Error:\n Token Type: ->"+currType.name+"<- static 'PATTERN' cannot contain start of input anchor '^'\n See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.",type:lexer_public_12.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[currType]}});return errors}exports3.findStartOfInputAnchor=findStartOfInputAnchor;function findUnsupportedFlags(tokenTypes){var invalidFlags=utils_12.filter(tokenTypes,function(currType){var pattern=currType[PATTERN];return pattern instanceof RegExp&&(pattern.multiline||pattern.global)});var errors=utils_12.map(invalidFlags,function(currType){return{message:"Token Type: ->"+currType.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:lexer_public_12.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[currType]}});return errors}exports3.findUnsupportedFlags=findUnsupportedFlags;function findDuplicatePatterns(tokenTypes){var found=[];var identicalPatterns=utils_12.map(tokenTypes,function(outerType){return utils_12.reduce(tokenTypes,function(result,innerType){if(outerType.PATTERN.source===innerType.PATTERN.source&&!utils_12.contains(found,innerType)&&innerType.PATTERN!==lexer_public_12.Lexer.NA){found.push(innerType);result.push(innerType);return result}return result},[])});identicalPatterns=utils_12.compact(identicalPatterns);var duplicatePatterns=utils_12.filter(identicalPatterns,function(currIdenticalSet){return currIdenticalSet.length>1});var errors=utils_12.map(duplicatePatterns,function(setOfIdentical){var tokenTypeNames=utils_12.map(setOfIdentical,function(currType){return currType.name});var dupPatternSrc=utils_12.first(setOfIdentical).PATTERN;return{message:"The same RegExp pattern ->"+dupPatternSrc+"<-"+("has been used in all of the following Token Types: "+tokenTypeNames.join(", ")+" <-"),type:lexer_public_12.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:setOfIdentical}});return errors}exports3.findDuplicatePatterns=findDuplicatePatterns;function findInvalidGroupType(tokenTypes){var invalidTypes=utils_12.filter(tokenTypes,function(clazz){if(!utils_12.has(clazz,"GROUP")){return false}var group=clazz.GROUP;return group!==lexer_public_12.Lexer.SKIPPED&&group!==lexer_public_12.Lexer.NA&&!utils_12.isString(group)});var errors=utils_12.map(invalidTypes,function(currType){return{message:"Token Type: ->"+currType.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:lexer_public_12.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[currType]}});return errors}exports3.findInvalidGroupType=findInvalidGroupType;function findModesThatDoNotExist(tokenTypes,validModes){var invalidModes=utils_12.filter(tokenTypes,function(clazz){return clazz.PUSH_MODE!==void 0&&!utils_12.contains(validModes,clazz.PUSH_MODE)});var errors=utils_12.map(invalidModes,function(tokType){var msg="Token Type: ->"+tokType.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+tokType.PUSH_MODE+"<-which does not exist";return{message:msg,type:lexer_public_12.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[tokType]}});return errors}exports3.findModesThatDoNotExist=findModesThatDoNotExist;function findUnreachablePatterns(tokenTypes){var errors=[];var canBeTested=utils_12.reduce(tokenTypes,function(result,tokType,idx){var pattern=tokType.PATTERN;if(pattern===lexer_public_12.Lexer.NA){return result}if(utils_12.isString(pattern)){result.push({str:pattern,idx,tokenType:tokType})}else if(utils_12.isRegExp(pattern)&&noMetaChar(pattern)){result.push({str:pattern.source,idx,tokenType:tokType})}return result},[]);utils_12.forEach(tokenTypes,function(tokType,testIdx){utils_12.forEach(canBeTested,function(_a){var str=_a.str,idx=_a.idx,tokenType=_a.tokenType;if(testIdx<idx&&testTokenType(str,tokType.PATTERN)){var msg="Token: ->"+tokenType.name+"<- can never be matched.\n"+("Because it appears AFTER the Token Type ->"+tokType.name+"<-")+"in the lexer's definition.\nSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE";errors.push({message:msg,type:lexer_public_12.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[tokType,tokenType]})}})});return errors}exports3.findUnreachablePatterns=findUnreachablePatterns;function testTokenType(str,pattern){if(utils_12.isRegExp(pattern)){var regExpArray=pattern.exec(str);return regExpArray!==null&&regExpArray.index===0}else if(utils_12.isFunction(pattern)){return pattern(str,0,[],{})}else if(utils_12.has(pattern,"exec")){return pattern.exec(str,0,[],{})}else if(typeof pattern==="string"){return pattern===str}else{throw Error("non exhaustive match")}}function noMetaChar(regExp){var metaChars=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return utils_12.find(metaChars,function(char){return regExp.source.indexOf(char)!==-1})===void 0}function addStartOfInput(pattern){var flags=pattern.ignoreCase?"i":"";return new RegExp("^(?:"+pattern.source+")",flags)}exports3.addStartOfInput=addStartOfInput;function addStickyFlag(pattern){var flags=pattern.ignoreCase?"iy":"y";return new RegExp(""+pattern.source,flags)}exports3.addStickyFlag=addStickyFlag;function performRuntimeChecks(lexerDefinition,trackLines,lineTerminatorCharacters){var errors=[];if(!utils_12.has(lexerDefinition,exports3.DEFAULT_MODE)){errors.push({message:"A MultiMode Lexer cannot be initialized without a <"+exports3.DEFAULT_MODE+"> property in its definition\n",type:lexer_public_12.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE})}if(!utils_12.has(lexerDefinition,exports3.MODES)){errors.push({message:"A MultiMode Lexer cannot be initialized without a <"+exports3.MODES+"> property in its definition\n",type:lexer_public_12.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY})}if(utils_12.has(lexerDefinition,exports3.MODES)&&utils_12.has(lexerDefinition,exports3.DEFAULT_MODE)&&!utils_12.has(lexerDefinition.modes,lexerDefinition.defaultMode)){errors.push({message:"A MultiMode Lexer cannot be initialized with a "+exports3.DEFAULT_MODE+": <"+lexerDefinition.defaultMode+">which does not exist\n",type:lexer_public_12.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST})}if(utils_12.has(lexerDefinition,exports3.MODES)){utils_12.forEach(lexerDefinition.modes,function(currModeValue,currModeName){utils_12.forEach(currModeValue,function(currTokType,currIdx){if(utils_12.isUndefined(currTokType)){errors.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+currModeName+"> at index: <"+currIdx+">\n"),type:lexer_public_12.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})}})})}return errors}exports3.performRuntimeChecks=performRuntimeChecks;function performWarningRuntimeChecks(lexerDefinition,trackLines,lineTerminatorCharacters){var warnings=[];var hasAnyLineBreak=false;var allTokenTypes=utils_12.compact(utils_12.flatten(utils_12.mapValues(lexerDefinition.modes,function(tokTypes){return tokTypes})));var concreteTokenTypes=utils_12.reject(allTokenTypes,function(currType){return currType[PATTERN]===lexer_public_12.Lexer.NA});var terminatorCharCodes=getCharCodes(lineTerminatorCharacters);if(trackLines){utils_12.forEach(concreteTokenTypes,function(tokType){var currIssue=checkLineBreaksIssues(tokType,terminatorCharCodes);if(currIssue!==false){var message=buildLineBreakIssueMessage(tokType,currIssue);var warningDescriptor={message,type:currIssue.issue,tokenType:tokType};warnings.push(warningDescriptor)}else{if(utils_12.has(tokType,"LINE_BREAKS")){if(tokType.LINE_BREAKS===true){hasAnyLineBreak=true}}else{if(reg_exp_1.canMatchCharCode(terminatorCharCodes,tokType.PATTERN)){hasAnyLineBreak=true}}}})}if(trackLines&&!hasAnyLineBreak){warnings.push({message:"Warning: No LINE_BREAKS Found.\n This Lexer has been defined to track line and column information,\n But none of the Token Types can be identified as matching a line terminator.\n See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n for details.",type:lexer_public_12.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS})}return warnings}exports3.performWarningRuntimeChecks=performWarningRuntimeChecks;function cloneEmptyGroups(emptyGroups){var clonedResult={};var groupKeys=utils_12.keys(emptyGroups);utils_12.forEach(groupKeys,function(currKey){var currGroupValue=emptyGroups[currKey];if(utils_12.isArray(currGroupValue)){clonedResult[currKey]=[]}else{throw Error("non exhaustive match")}});return clonedResult}exports3.cloneEmptyGroups=cloneEmptyGroups;function isCustomPattern(tokenType){var pattern=tokenType.PATTERN;if(utils_12.isRegExp(pattern)){return false}else if(utils_12.isFunction(pattern)){return true}else if(utils_12.has(pattern,"exec")){return true}else if(utils_12.isString(pattern)){return false}else{throw Error("non exhaustive match")}}exports3.isCustomPattern=isCustomPattern;function isShortPattern(pattern){if(utils_12.isString(pattern)&&pattern.length===1){return pattern.charCodeAt(0)}else{return false}}exports3.isShortPattern=isShortPattern;exports3.LineTerminatorOptimizedTester={test:function(text){var len=text.length;for(var i=this.lastIndex;i<len;i++){var c=text.charCodeAt(i);if(c===10){this.lastIndex=i+1;return true}else if(c===13){if(text.charCodeAt(i+1)===10){this.lastIndex=i+2}else{this.lastIndex=i+1}return true}}return false},lastIndex:0};function checkLineBreaksIssues(tokType,lineTerminatorCharCodes){if(utils_12.has(tokType,"LINE_BREAKS")){return false}else{if(utils_12.isRegExp(tokType.PATTERN)){try{reg_exp_1.canMatchCharCode(lineTerminatorCharCodes,tokType.PATTERN)}catch(e){return{issue:lexer_public_12.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,errMsg:e.message}}return false}else if(utils_12.isString(tokType.PATTERN)){return false}else if(isCustomPattern(tokType)){return{issue:lexer_public_12.LexerDefinitionErrorType.CUSTOM_LINE_BREAK}}else{throw Error("non exhaustive match")}}}function buildLineBreakIssueMessage(tokType,details){if(details.issue===lexer_public_12.LexerDefinitionErrorType.IDENTIFY_TERMINATOR){return"Warning: unable to identify line terminator usage in pattern.\n"+(" The problem is in the <"+tokType.name+"> Token Type\n")+(" Root cause: "+details.errMsg+".\n")+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"}else if(details.issue===lexer_public_12.LexerDefinitionErrorType.CUSTOM_LINE_BREAK){return"Warning: A Custom Token Pattern should specify the <line_breaks> option.\n"+(" The problem is in the <"+tokType.name+"> Token Type\n")+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"}else{throw Error("non exhaustive match")}}exports3.buildLineBreakIssueMessage=buildLineBreakIssueMessage;function getCharCodes(charsOrCodes){var charCodes=utils_12.map(charsOrCodes,function(numOrString){if(utils_12.isString(numOrString)&&numOrString.length>0){return numOrString.charCodeAt(0)}else{return numOrString}});return charCodes}function addToMapOfArrays(map2,key,value){if(map2[key]===void 0){map2[key]=[value]}else{map2[key].push(value)}}exports3.minOptimizationVal=256;var charCodeToOptimizedIdxMap=[];function charCodeToOptimizedIndex(charCode){return charCode<exports3.minOptimizationVal?charCode:charCodeToOptimizedIdxMap[charCode]}exports3.charCodeToOptimizedIndex=charCodeToOptimizedIndex;function initCharCodeToOptimizedIndexMap(){if(utils_12.isEmpty(charCodeToOptimizedIdxMap)){charCodeToOptimizedIdxMap=new Array(65536);for(var i=0;i<65536;i++){charCodeToOptimizedIdxMap[i]=i>255?255+~~(i/255):i}}}})(lexer);var tokens={};(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.isTokenType=exports3.hasExtendingTokensTypesMapProperty=exports3.hasExtendingTokensTypesProperty=exports3.hasCategoriesProperty=exports3.hasShortKeyProperty=exports3.singleAssignCategoriesToksMap=exports3.assignCategoriesMapProp=exports3.assignCategoriesTokensProp=exports3.assignTokenDefaultProps=exports3.expandCategories=exports3.augmentTokenTypes=exports3.tokenIdxToClass=exports3.tokenShortNameIdx=exports3.tokenStructuredMatcherNoCategories=exports3.tokenStructuredMatcher=void 0;var utils_12=api;function tokenStructuredMatcher(tokInstance,tokConstructor){var instanceType=tokInstance.tokenTypeIdx;if(instanceType===tokConstructor.tokenTypeIdx){return true}else{return tokConstructor.isParent===true&&tokConstructor.categoryMatchesMap[instanceType]===true}}exports3.tokenStructuredMatcher=tokenStructuredMatcher;function tokenStructuredMatcherNoCategories(token,tokType){return token.tokenTypeIdx===tokType.tokenTypeIdx}exports3.tokenStructuredMatcherNoCategories=tokenStructuredMatcherNoCategories;exports3.tokenShortNameIdx=1;exports3.tokenIdxToClass={};function augmentTokenTypes(tokenTypes){var tokenTypesAndParents=expandCategories(tokenTypes);assignTokenDefaultProps(tokenTypesAndParents);assignCategoriesMapProp(tokenTypesAndParents);assignCategoriesTokensProp(tokenTypesAndParents);utils_12.forEach(tokenTypesAndParents,function(tokType){tokType.isParent=tokType.categoryMatches.length>0})}exports3.augmentTokenTypes=augmentTokenTypes;function expandCategories(tokenTypes){var result=utils_12.cloneArr(tokenTypes);var categories=tokenTypes;var searching=true;while(searching){categories=utils_12.compact(utils_12.flatten(utils_12.map(categories,function(currTokType){return currTokType.CATEGORIES})));var newCategories=utils_12.difference(categories,result);result=result.concat(newCategories);if(utils_12.isEmpty(newCategories)){searching=false}else{categories=newCategories}}return result}exports3.expandCategories=expandCategories;function assignTokenDefaultProps(tokenTypes){utils_12.forEach(tokenTypes,function(currTokType){if(!hasShortKeyProperty(currTokType)){exports3.tokenIdxToClass[exports3.tokenShortNameIdx]=currTokType;currTokType.tokenTypeIdx=exports3.tokenShortNameIdx++}if(hasCategoriesProperty(currTokType)&&!utils_12.isArray(currTokType.CATEGORIES)){currTokType.CATEGORIES=[currTokType.CATEGORIES]}if(!hasCategoriesProperty(currTokType)){currTokType.CATEGORIES=[]}if(!hasExtendingTokensTypesProperty(currTokType)){currTokType.categoryMatches=[]}if(!hasExtendingTokensTypesMapProperty(currTokType)){currTokType.categoryMatchesMap={}}})}exports3.assignTokenDefaultProps=assignTokenDefaultProps;function assignCategoriesTokensProp(tokenTypes){utils_12.forEach(tokenTypes,function(currTokType){currTokType.categoryMatches=[];utils_12.forEach(currTokType.categoryMatchesMap,function(val,key){currTokType.categoryMatches.push(exports3.tokenIdxToClass[key].tokenTypeIdx)})})}exports3.assignCategoriesTokensProp=assignCategoriesTokensProp;function assignCategoriesMapProp(tokenTypes){utils_12.forEach(tokenTypes,function(currTokType){singleAssignCategoriesToksMap([],currTokType)})}exports3.assignCategoriesMapProp=assignCategoriesMapProp;function singleAssignCategoriesToksMap(path,nextNode){utils_12.forEach(path,function(pathNode){nextNode.categoryMatchesMap[pathNode.tokenTypeIdx]=true});utils_12.forEach(nextNode.CATEGORIES,function(nextCategory){var newPath=path.concat(nextNode);if(!utils_12.contains(newPath,nextCategory)){singleAssignCategoriesToksMap(newPath,nextCategory)}})}exports3.singleAssignCategoriesToksMap=singleAssignCategoriesToksMap;function hasShortKeyProperty(tokType){return utils_12.has(tokType,"tokenTypeIdx")}exports3.hasShortKeyProperty=hasShortKeyProperty;function hasCategoriesProperty(tokType){return utils_12.has(tokType,"CATEGORIES")}exports3.hasCategoriesProperty=hasCategoriesProperty;function hasExtendingTokensTypesProperty(tokType){return utils_12.has(tokType,"categoryMatches")}exports3.hasExtendingTokensTypesProperty=hasExtendingTokensTypesProperty;function hasExtendingTokensTypesMapProperty(tokType){return utils_12.has(tokType,"categoryMatchesMap")}exports3.hasExtendingTokensTypesMapProperty=hasExtendingTokensTypesMapProperty;function isTokenType(tokType){return utils_12.has(tokType,"tokenTypeIdx")}exports3.isTokenType=isTokenType})(tokens);var lexer_errors_public={};Object.defineProperty(lexer_errors_public,"__esModule",{value:true});lexer_errors_public.defaultLexerErrorProvider=void 0;lexer_errors_public.defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(token){return"Unable to pop Lexer Mode after encountering Token ->"+token.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(fullText,startOffset,length,line,column){return"unexpected character: ->"+fullText.charAt(startOffset)+"<- at offset: "+startOffset+","+(" skipped "+length+" characters.")}};(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.Lexer=exports3.LexerDefinitionErrorType=void 0;var lexer_1=lexer;var utils_12=api;var tokens_12=tokens;var lexer_errors_public_1=lexer_errors_public;var reg_exp_parser_1=reg_exp_parser;(function(LexerDefinitionErrorType){LexerDefinitionErrorType[LexerDefinitionErrorType["MISSING_PATTERN"]=0]="MISSING_PATTERN";LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_PATTERN"]=1]="INVALID_PATTERN";LexerDefinitionErrorType[LexerDefinitionErrorType["EOI_ANCHOR_FOUND"]=2]="EOI_ANCHOR_FOUND";LexerDefinitionErrorType[LexerDefinitionErrorType["UNSUPPORTED_FLAGS_FOUND"]=3]="UNSUPPORTED_FLAGS_FOUND";LexerDefinitionErrorType[LexerDefinitionErrorType["DUPLICATE_PATTERNS_FOUND"]=4]="DUPLICATE_PATTERNS_FOUND";LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_GROUP_TYPE_FOUND"]=5]="INVALID_GROUP_TYPE_FOUND";LexerDefinitionErrorType[LexerDefinitionErrorType["PUSH_MODE_DOES_NOT_EXIST"]=6]="PUSH_MODE_DOES_NOT_EXIST";LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"]=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE";LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"]=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY";LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"]=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST";LexerDefinitionErrorType[LexerDefinitionErrorType["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"]=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED";LexerDefinitionErrorType[LexerDefinitionErrorType["SOI_ANCHOR_FOUND"]=11]="SOI_ANCHOR_FOUND";LexerDefinitionErrorType[LexerDefinitionErrorType["EMPTY_MATCH_PATTERN"]=12]="EMPTY_MATCH_PATTERN";LexerDefinitionErrorType[LexerDefinitionErrorType["NO_LINE_BREAKS_FLAGS"]=13]="NO_LINE_BREAKS_FLAGS";LexerDefinitionErrorType[LexerDefinitionErrorType["UNREACHABLE_PATTERN"]=14]="UNREACHABLE_PATTERN";LexerDefinitionErrorType[LexerDefinitionErrorType["IDENTIFY_TERMINATOR"]=15]="IDENTIFY_TERMINATOR";LexerDefinitionErrorType[LexerDefinitionErrorType["CUSTOM_LINE_BREAK"]=16]="CUSTOM_LINE_BREAK"})(exports3.LexerDefinitionErrorType||(exports3.LexerDefinitionErrorType={}));var DEFAULT_LEXER_CONFIG={deferDefinitionErrorsHandling:false,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:["\n","\r"],ensureOptimizations:false,safeMode:false,errorMessageProvider:lexer_errors_public_1.defaultLexerErrorProvider,traceInitPerf:false,skipValidations:false};Object.freeze(DEFAULT_LEXER_CONFIG);var Lexer2=(function(){function Lexer3(lexerDefinition,config){var _this=this;if(config===void 0){config=DEFAULT_LEXER_CONFIG}this.lexerDefinition=lexerDefinition;this.lexerDefinitionErrors=[];this.lexerDefinitionWarning=[];this.patternIdxToConfig={};this.charCodeToPatternIdxToConfig={};this.modes=[];this.emptyGroups={};this.config=void 0;this.trackStartLines=true;this.trackEndLines=true;this.hasCustom=false;this.canModeBeOptimized={};if(typeof config==="boolean"){throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported")}this.config=utils_12.merge(DEFAULT_LEXER_CONFIG,config);var traceInitVal=this.config.traceInitPerf;if(traceInitVal===true){this.traceInitMaxIdent=Infinity;this.traceInitPerf=true}else if(typeof traceInitVal==="number"){this.traceInitMaxIdent=traceInitVal;this.traceInitPerf=true}this.traceInitIndent=-1;this.TRACE_INIT("Lexer Constructor",function(){var actualDefinition;var hasOnlySingleMode=true;_this.TRACE_INIT("Lexer Config handling",function(){if(_this.config.lineTerminatorsPattern===DEFAULT_LEXER_CONFIG.lineTerminatorsPattern){_this.config.lineTerminatorsPattern=lexer_1.LineTerminatorOptimizedTester}else{if(_this.config.lineTerminatorCharacters===DEFAULT_LEXER_CONFIG.lineTerminatorCharacters){throw Error("Error: Missing <lineTerminatorCharacters> property on the Lexer config.\n For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS")}}if(config.safeMode&&config.ensureOptimizations){throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.')}_this.trackStartLines=/full|onlyStart/i.test(_this.config.positionTracking);_this.trackEndLines=/full/i.test(_this.config.positionTracking);if(utils_12.isArray(lexerDefinition)){actualDefinition={modes:{}};actualDefinition.modes[lexer_1.DEFAULT_MODE]=utils_12.cloneArr(lexerDefinition);actualDefinition[lexer_1.DEFAULT_MODE]=lexer_1.DEFAULT_MODE}else{hasOnlySingleMode=false;actualDefinition=utils_12.cloneObj(lexerDefinition)}});if(_this.config.skipValidations===false){_this.TRACE_INIT("performRuntimeChecks",function(){_this.lexerDefinitionErrors=_this.lexerDefinitionErrors.concat(lexer_1.performRuntimeChecks(actualDefinition,_this.trackStartLines,_this.config.lineTerminatorCharacters))});_this.TRACE_INIT("performWarningRuntimeChecks",function(){_this.lexerDefinitionWarning=_this.lexerDefinitionWarning.concat(lexer_1.performWarningRuntimeChecks(actualDefinition,_this.trackStartLines,_this.config.lineTerminatorCharacters))})}actualDefinition.modes=actualDefinition.modes?actualDefinition.modes:{};utils_12.forEach(actualDefinition.modes,function(currModeValue,currModeName){actualDefinition.modes[currModeName]=utils_12.reject(currModeValue,function(currTokType){return utils_12.isUndefined(currTokType)})});var allModeNames=utils_12.keys(actualDefinition.modes);utils_12.forEach(actualDefinition.modes,function(currModDef,currModName){_this.TRACE_INIT("Mode: <"+currModName+"> processing",function(){_this.modes.push(currModName);if(_this.config.skipValidations===false){_this.TRACE_INIT("validatePatterns",function(){_this.lexerDefinitionErrors=_this.lexerDefinitionErrors.concat(lexer_1.validatePatterns(currModDef,allModeNames))})}if(utils_12.isEmpty(_this.lexerDefinitionErrors)){tokens_12.augmentTokenTypes(currModDef);var currAnalyzeResult_1;_this.TRACE_INIT("analyzeTokenTypes",function(){currAnalyzeResult_1=lexer_1.analyzeTokenTypes(currModDef,{lineTerminatorCharacters:_this.config.lineTerminatorCharacters,positionTracking:config.positionTracking,ensureOptimizations:config.ensureOptimizations,safeMode:config.safeMode,tracer:_this.TRACE_INIT.bind(_this)})});_this.patternIdxToConfig[currModName]=currAnalyzeResult_1.patternIdxToConfig;_this.charCodeToPatternIdxToConfig[currModName]=currAnalyzeResult_1.charCodeToPatternIdxToConfig;_this.emptyGroups=utils_12.merge(_this.emptyGroups,currAnalyzeResult_1.emptyGroups);_this.hasCustom=currAnalyzeResult_1.hasCustom||_this.hasCustom;_this.canModeBeOptimized[currModName]=currAnalyzeResult_1.canBeOptimized}})});_this.defaultMode=actualDefinition.defaultMode;if(!utils_12.isEmpty(_this.lexerDefinitionErrors)&&!_this.config.deferDefinitionErrorsHandling){var allErrMessages=utils_12.map(_this.lexerDefinitionErrors,function(error){return error.message});var allErrMessagesString=allErrMessages.join("-----------------------\n");throw new Error("Errors detected in definition of Lexer:\n"+allErrMessagesString)}utils_12.forEach(_this.lexerDefinitionWarning,function(warningDescriptor){utils_12.PRINT_WARNING(warningDescriptor.message)});_this.TRACE_INIT("Choosing sub-methods implementations",function(){if(lexer_1.SUPPORT_STICKY){_this.chopInput=utils_12.IDENTITY;_this.match=_this.matchWithTest}else{_this.updateLastIndex=utils_12.NOOP;_this.match=_this.matchWithExec}if(hasOnlySingleMode){_this.handleModes=utils_12.NOOP}if(_this.trackStartLines===false){_this.computeNewColumn=utils_12.IDENTITY}if(_this.trackEndLines===false){_this.updateTokenEndLineColumnLocation=utils_12.NOOP}if(/full/i.test(_this.config.positionTracking)){_this.createTokenInstance=_this.createFullToken}else if(/onlyStart/i.test(_this.config.positionTracking)){_this.createTokenInstance=_this.createStartOnlyToken}else if(/onlyOffset/i.test(_this.config.positionTracking)){_this.createTokenInstance=_this.createOffsetOnlyToken}else{throw Error('Invalid <positionTracking> config option: "'+_this.config.positionTracking+'"')}if(_this.hasCustom){_this.addToken=_this.addTokenUsingPush;_this.handlePayload=_this.handlePayloadWithCustom}else{_this.addToken=_this.addTokenUsingMemberAccess;_this.handlePayload=_this.handlePayloadNoCustom}});_this.TRACE_INIT("Failed Optimization Warnings",function(){var unOptimizedModes=utils_12.reduce(_this.canModeBeOptimized,function(cannotBeOptimized,canBeOptimized,modeName){if(canBeOptimized===false){cannotBeOptimized.push(modeName)}return cannotBeOptimized},[]);if(config.ensureOptimizations&&!utils_12.isEmpty(unOptimizedModes)){throw Error("Lexer Modes: < "+unOptimizedModes.join(", ")+' > cannot be optimized.\n Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n Or inspect the console log for details on how to resolve these issues.')}});_this.TRACE_INIT("clearRegExpParserCache",function(){reg_exp_parser_1.clearRegExpParserCache()});_this.TRACE_INIT("toFastProperties",function(){utils_12.toFastProperties(_this)})})}Lexer3.prototype.tokenize=function(text,initialMode){if(initialMode===void 0){initialMode=this.defaultMode}if(!utils_12.isEmpty(this.lexerDefinitionErrors)){var allErrMessages=utils_12.map(this.lexerDefinitionErrors,function(error){return error.message});var allErrMessagesString=allErrMessages.join("-----------------------\n");throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n"+allErrMessagesString)}var lexResult=this.tokenizeInternal(text,initialMode);return lexResult};Lexer3.prototype.tokenizeInternal=function(text,initialMode){var _this=this;var i,j,matchAltImage,longerAltIdx,matchedImage,payload,altPayload,imageLength,group,tokType,newToken,errLength,msg,match;var orgText=text;var orgLength=orgText.length;var offset=0;var matchedTokensIndex=0;var guessedNumberOfTokens=this.hasCustom?0:Math.floor(text.length/10);var matchedTokens=new Array(guessedNumberOfTokens);var errors=[];var line=this.trackStartLines?1:void 0;var column=this.trackStartLines?1:void 0;var groups=lexer_1.cloneEmptyGroups(this.emptyGroups);var trackLines=this.trackStartLines;var lineTerminatorPattern=this.config.lineTerminatorsPattern;var currModePatternsLength=0;var patternIdxToConfig=[];var currCharCodeToPatternIdxToConfig=[];var modeStack=[];var emptyArray=[];Object.freeze(emptyArray);var getPossiblePatterns=void 0;function getPossiblePatternsSlow(){return patternIdxToConfig}function getPossiblePatternsOptimized(charCode){var optimizedCharIdx=lexer_1.charCodeToOptimizedIndex(charCode);var possiblePatterns=currCharCodeToPatternIdxToConfig[optimizedCharIdx];if(possiblePatterns===void 0){return emptyArray}else{return possiblePatterns}}var pop_mode=function(popToken){if(modeStack.length===1&&popToken.tokenType.PUSH_MODE===void 0){var msg_1=_this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken);errors.push({offset:popToken.startOffset,line:popToken.startLine!==void 0?popToken.startLine:void 0,column:popToken.startColumn!==void 0?popToken.startColumn:void 0,length:popToken.image.length,message:msg_1})}else{modeStack.pop();var newMode=utils_12.last(modeStack);patternIdxToConfig=_this.patternIdxToConfig[newMode];currCharCodeToPatternIdxToConfig=_this.charCodeToPatternIdxToConfig[newMode];currModePatternsLength=patternIdxToConfig.length;var modeCanBeOptimized=_this.canModeBeOptimized[newMode]&&_this.config.safeMode===false;if(currCharCodeToPatternIdxToConfig&&modeCanBeOptimized){getPossiblePatterns=getPossiblePatternsOptimized}else{getPossiblePatterns=getPossiblePatternsSlow}}};function push_mode(newMode){modeStack.push(newMode);currCharCodeToPatternIdxToConfig=this.charCodeToPatternIdxToConfig[newMode];patternIdxToConfig=this.patternIdxToConfig[newMode];currModePatternsLength=patternIdxToConfig.length;currModePatternsLength=patternIdxToConfig.length;var modeCanBeOptimized=this.canModeBeOptimized[newMode]&&this.config.safeMode===false;if(currCharCodeToPatternIdxToConfig&&modeCanBeOptimized){getPossiblePatterns=getPossiblePatternsOptimized}else{getPossiblePatterns=getPossiblePatternsSlow}}push_mode.call(this,initialMode);var currConfig;while(offset<orgLength){matchedImage=null;var nextCharCode=orgText.charCodeAt(offset);var chosenPatternIdxToConfig=getPossiblePatterns(nextCharCode);var chosenPatternsLength=chosenPatternIdxToConfig.length;for(i=0;i<chosenPatternsLength;i++){currConfig=chosenPatternIdxToConfig[i];var currPattern=currConfig.pattern;payload=null;var singleCharCode=currConfig.short;if(singleCharCode!==false){if(nextCharCode===singleCharCode){matchedImage=currPattern}}else if(currConfig.isCustom===true){match=currPattern.exec(orgText,offset,matchedTokens,groups);if(match!==null){matchedImage=match[0];if(match.payload!==void 0){payload=match.payload}}else{matchedImage=null}}else{this.updateLastIndex(currPattern,offset);matchedImage=this.match(currPattern,text,offset)}if(matchedImage!==null){longerAltIdx=currConfig.longerAlt;if(longerAltIdx!==void 0){var longerAltConfig=patternIdxToConfig[longerAltIdx];var longerAltPattern=longerAltConfig.pattern;altPayload=null;if(longerAltConfig.isCustom===true){match=longerAltPattern.exec(orgText,offset,matchedTokens,groups);if(match!==null){matchAltImage=match[0];if(match.payload!==void 0){altPayload=match.payload}}else{matchAltImage=null}}else{this.updateLastIndex(longerAltPattern,offset);matchAltImage=this.match(longerAltPattern,text,offset)}if(matchAltImage&&matchAltImage.length>matchedImage.length){matchedImage=matchAltImage;payload=altPayload;currConfig=longerAltConfig}}break}}if(matchedImage!==null){imageLength=matchedImage.length;group=currConfig.group;if(group!==void 0){tokType=currConfig.tokenTypeIdx;newToken=this.createTokenInstance(matchedImage,offset,tokType,currConfig.tokenType,line,column,imageLength);this.handlePayload(newToken,payload);if(group===false){matchedTokensIndex=this.addToken(matchedTokens,matchedTokensIndex,newToken)}else{groups[group].push(newToken)}}text=this.chopInput(text,imageLength);offset=offset+imageLength;column=this.computeNewColumn(column,imageLength);if(trackLines===true&&currConfig.canLineTerminator===true){var numOfLTsInMatch=0;var foundTerminator=void 0;var lastLTEndOffset=void 0;lineTerminatorPattern.lastIndex=0;do{foundTerminator=lineTerminatorPattern.test(matchedImage);if(foundTerminator===true){lastLTEndOffset=lineTerminatorPattern.lastIndex-1;numOfLTsInMatch++}}while(foundTerminator===true);if(numOfLTsInMatch!==0){line=line+numOfLTsInMatch;column=imageLength-lastLTEndOffset;this.updateTokenEndLineColumnLocation(newToken,group,lastLTEndOffset,numOfLTsInMatch,line,column,imageLength)}}this.handleModes(currConfig,pop_mode,push_mode,newToken)}else{var errorStartOffset=offset;var errorLine=line;var errorColumn=column;var foundResyncPoint=false;while(!foundResyncPoint&&offset<orgLength){orgText.charCodeAt(offset);text=this.chopInput(text,1);offset++;for(j=0;j<currModePatternsLength;j++){var currConfig_1=patternIdxToConfig[j];var currPattern=currConfig_1.pattern;var singleCharCode=currConfig_1.short;if(singleCharCode!==false){if(orgText.charCodeAt(offset)===singleCharCode){foundResyncPoint=true}}else if(currConfig_1.isCustom===true){foundResyncPoint=currPattern.exec(orgText,offset,matchedTokens,groups)!==null}else{this.updateLastIndex(currPattern,offset);foundResyncPoint=currPattern.exec(text)!==null}if(foundResyncPoint===true){break}}}errLength=offset-errorStartOffset;msg=this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText,errorStartOffset,errLength,errorLine,errorColumn);errors.push({offset:errorStartOffset,line:errorLine,column:errorColumn,length:errLength,message:msg})}}if(!this.hasCustom){matchedTokens.length=matchedTokensIndex}return{tokens:matchedTokens,groups,errors}};Lexer3.prototype.handleModes=function(config,pop_mode,push_mode,newToken){if(config.pop===true){var pushMode=config.push;pop_mode(newToken);if(pushMode!==void 0){push_mode.call(this,pushMode)}}else if(config.push!==void 0){push_mode.call(this,config.push)}};Lexer3.prototype.chopInput=function(text,length){return text.substring(length)};Lexer3.prototype.updateLastIndex=function(regExp,newLastIndex){regExp.lastIndex=newLastIndex};Lexer3.prototype.updateTokenEndLineColumnLocation=function(newToken,group,lastLTIdx,numOfLTsInMatch,line,column,imageLength){var lastCharIsLT,fixForEndingInLT;if(group!==void 0){lastCharIsLT=lastLTIdx===imageLength-1;fixForEndingInLT=lastCharIsLT?-1:0;if(!(numOfLTsInMatch===1&&lastCharIsLT===true)){newToken.endLine=line+fixForEndingInLT;newToken.endColumn=column-1+-fixForEndingInLT}}};Lexer3.prototype.computeNewColumn=function(oldColumn,imageLength){return oldColumn+imageLength};Lexer3.prototype.createTokenInstance=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return null};Lexer3.prototype.createOffsetOnlyToken=function(image,startOffset,tokenTypeIdx,tokenType){return{image,startOffset,tokenTypeIdx,tokenType}};Lexer3.prototype.createStartOnlyToken=function(image,startOffset,tokenTypeIdx,tokenType,startLine,startColumn){return{image,startOffset,startLine,startColumn,tokenTypeIdx,tokenType}};Lexer3.prototype.createFullToken=function(image,startOffset,tokenTypeIdx,tokenType,startLine,startColumn,imageLength){return{image,startOffset,endOffset:startOffset+imageLength-1,startLine,endLine:startLine,startColumn,endColumn:startColumn+imageLength-1,tokenTypeIdx,tokenType}};Lexer3.prototype.addToken=function(tokenVector,index,tokenToAdd){return 666};Lexer3.prototype.addTokenUsingPush=function(tokenVector,index,tokenToAdd){tokenVector.push(tokenToAdd);return index};Lexer3.prototype.addTokenUsingMemberAccess=function(tokenVector,index,tokenToAdd){tokenVector[index]=tokenToAdd;index++;return index};Lexer3.prototype.handlePayload=function(token,payload){};Lexer3.prototype.handlePayloadNoCustom=function(token,payload){};Lexer3.prototype.handlePayloadWithCustom=function(token,payload){if(payload!==null){token.payload=payload}};Lexer3.prototype.match=function(pattern,text,offset){return null};Lexer3.prototype.matchWithTest=function(pattern,text,offset){var found=pattern.test(text);if(found===true){return text.substring(offset,pattern.lastIndex)}return null};Lexer3.prototype.matchWithExec=function(pattern,text){var regExpArray=pattern.exec(text);return regExpArray!==null?regExpArray[0]:regExpArray};Lexer3.prototype.TRACE_INIT=function(phaseDesc,phaseImpl){if(this.traceInitPerf===true){this.traceInitIndent++;var indent=new Array(this.traceInitIndent+1).join(" ");if(this.traceInitIndent<this.traceInitMaxIdent){console.log(indent+"--> <"+phaseDesc+">")}var _a=utils_12.timer(phaseImpl),time=_a.time,value=_a.value;var traceMethod=time>10?console.warn:console.log;if(this.traceInitIndent<this.traceInitMaxIdent){traceMethod(indent+"<-- <"+phaseDesc+"> time: "+time+"ms")}this.traceInitIndent--;return value}else{return phaseImpl()}};Lexer3.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";Lexer3.NA=/NOT_APPLICABLE/;return Lexer3})();exports3.Lexer=Lexer2})(lexer_public);(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.tokenMatcher=exports3.createTokenInstance=exports3.EOF=exports3.createToken=exports3.hasTokenLabel=exports3.tokenName=exports3.tokenLabel=void 0;var utils_12=api;var lexer_public_12=lexer_public;var tokens_12=tokens;function tokenLabel(tokType){if(hasTokenLabel(tokType)){return tokType.LABEL}else{return tokType.name}}exports3.tokenLabel=tokenLabel;function tokenName(tokType){return tokType.name}exports3.tokenName=tokenName;function hasTokenLabel(obj){return utils_12.isString(obj.LABEL)&&obj.LABEL!==""}exports3.hasTokenLabel=hasTokenLabel;var PARENT="parent";var CATEGORIES="categories";var LABEL="label";var GROUP="group";var PUSH_MODE="push_mode";var POP_MODE="pop_mode";var LONGER_ALT="longer_alt";var LINE_BREAKS="line_breaks";var START_CHARS_HINT="start_chars_hint";function createToken2(config){return createTokenInternal(config)}exports3.createToken=createToken2;function createTokenInternal(config){var pattern=config.pattern;var tokenType={};tokenType.name=config.name;if(!utils_12.isUndefined(pattern)){tokenType.PATTERN=pattern}if(utils_12.has(config,PARENT)){throw"The parent property is no longer supported.\nSee: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details."}if(utils_12.has(config,CATEGORIES)){tokenType.CATEGORIES=config[CATEGORIES]}tokens_12.augmentTokenTypes([tokenType]);if(utils_12.has(config,LABEL)){tokenType.LABEL=config[LABEL]}if(utils_12.has(config,GROUP)){tokenType.GROUP=config[GROUP]}if(utils_12.has(config,POP_MODE)){tokenType.POP_MODE=config[POP_MODE]}if(utils_12.has(config,PUSH_MODE)){tokenType.PUSH_MODE=config[PUSH_MODE]}if(utils_12.has(config,LONGER_ALT)){tokenType.LONGER_ALT=config[LONGER_ALT]}if(utils_12.has(config,LINE_BREAKS)){tokenType.LINE_BREAKS=config[LINE_BREAKS]}if(utils_12.has(config,START_CHARS_HINT)){tokenType.START_CHARS_HINT=config[START_CHARS_HINT]}return tokenType}exports3.EOF=createToken2({name:"EOF",pattern:lexer_public_12.Lexer.NA});tokens_12.augmentTokenTypes([exports3.EOF]);function createTokenInstance(tokType,image,startOffset,endOffset,startLine,endLine,startColumn,endColumn){return{image,startOffset,endOffset,startLine,endLine,startColumn,endColumn,tokenTypeIdx:tokType.tokenTypeIdx,tokenType:tokType}}exports3.createTokenInstance=createTokenInstance;function tokenMatcher(token,tokType){return tokens_12.tokenStructuredMatcher(token,tokType)}exports3.tokenMatcher=tokenMatcher})(tokens_public);var __extends$6=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(gast_public,"__esModule",{value:true});gast_public.serializeProduction=gast_public.serializeGrammar=gast_public.Terminal=gast_public.Alternation=gast_public.RepetitionWithSeparator=gast_public.Repetition=gast_public.RepetitionMandatoryWithSeparator=gast_public.RepetitionMandatory=gast_public.Option=gast_public.Alternative=gast_public.Rule=gast_public.NonTerminal=gast_public.AbstractProduction=void 0;var utils_1$i=api;var tokens_public_1$2=tokens_public;var AbstractProduction=(function(){function AbstractProduction2(_definition){this._definition=_definition}Object.defineProperty(AbstractProduction2.prototype,"definition",{get:function(){return this._definition},set:function(value){this._definition=value},enumerable:false,configurable:true});AbstractProduction2.prototype.accept=function(visitor){visitor.visit(this);utils_1$i.forEach(this.definition,function(prod){prod.accept(visitor)})};return AbstractProduction2})();gast_public.AbstractProduction=AbstractProduction;var NonTerminal=(function(_super){__extends$6(NonTerminal2,_super);function NonTerminal2(options){var _this=_super.call(this,[])||this;_this.idx=1;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}Object.defineProperty(NonTerminal2.prototype,"definition",{get:function(){if(this.referencedRule!==void 0){return this.referencedRule.definition}return[]},set:function(definition){},enumerable:false,configurable:true});NonTerminal2.prototype.accept=function(visitor){visitor.visit(this)};return NonTerminal2})(AbstractProduction);gast_public.NonTerminal=NonTerminal;var Rule=(function(_super){__extends$6(Rule2,_super);function Rule2(options){var _this=_super.call(this,options.definition)||this;_this.orgText="";utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return Rule2})(AbstractProduction);gast_public.Rule=Rule;var Alternative=(function(_super){__extends$6(Alternative2,_super);function Alternative2(options){var _this=_super.call(this,options.definition)||this;_this.ignoreAmbiguities=false;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return Alternative2})(AbstractProduction);gast_public.Alternative=Alternative;var Option=(function(_super){__extends$6(Option2,_super);function Option2(options){var _this=_super.call(this,options.definition)||this;_this.idx=1;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return Option2})(AbstractProduction);gast_public.Option=Option;var RepetitionMandatory=(function(_super){__extends$6(RepetitionMandatory2,_super);function RepetitionMandatory2(options){var _this=_super.call(this,options.definition)||this;_this.idx=1;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return RepetitionMandatory2})(AbstractProduction);gast_public.RepetitionMandatory=RepetitionMandatory;var RepetitionMandatoryWithSeparator=(function(_super){__extends$6(RepetitionMandatoryWithSeparator2,_super);function RepetitionMandatoryWithSeparator2(options){var _this=_super.call(this,options.definition)||this;_this.idx=1;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return RepetitionMandatoryWithSeparator2})(AbstractProduction);gast_public.RepetitionMandatoryWithSeparator=RepetitionMandatoryWithSeparator;var Repetition=(function(_super){__extends$6(Repetition2,_super);function Repetition2(options){var _this=_super.call(this,options.definition)||this;_this.idx=1;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return Repetition2})(AbstractProduction);gast_public.Repetition=Repetition;var RepetitionWithSeparator=(function(_super){__extends$6(RepetitionWithSeparator2,_super);function RepetitionWithSeparator2(options){var _this=_super.call(this,options.definition)||this;_this.idx=1;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}return RepetitionWithSeparator2})(AbstractProduction);gast_public.RepetitionWithSeparator=RepetitionWithSeparator;var Alternation=(function(_super){__extends$6(Alternation2,_super);function Alternation2(options){var _this=_super.call(this,options.definition)||this;_this.idx=1;_this.ignoreAmbiguities=false;_this.hasPredicates=false;utils_1$i.assign(_this,utils_1$i.pick(options,function(v){return v!==void 0}));return _this}Object.defineProperty(Alternation2.prototype,"definition",{get:function(){return this._definition},set:function(value){this._definition=value},enumerable:false,configurable:true});return Alternation2})(AbstractProduction);gast_public.Alternation=Alternation;var Terminal=(function(){function Terminal2(options){this.idx=1;utils_1$i.assign(this,utils_1$i.pick(options,function(v){return v!==void 0}))}Terminal2.prototype.accept=function(visitor){visitor.visit(this)};return Terminal2})();gast_public.Terminal=Terminal;function serializeGrammar(topRules){return utils_1$i.map(topRules,serializeProduction)}gast_public.serializeGrammar=serializeGrammar;function serializeProduction(node){function convertDefinition(definition){return utils_1$i.map(definition,serializeProduction)}if(node instanceof NonTerminal){var serializedNonTerminal={type:"NonTerminal",name:node.nonTerminalName,idx:node.idx};if(utils_1$i.isString(node.label)){serializedNonTerminal.label=node.label}return serializedNonTerminal}else if(node instanceof Alternative){return{type:"Alternative",definition:convertDefinition(node.definition)}}else if(node instanceof Option){return{type:"Option",idx:node.idx,definition:convertDefinition(node.definition)}}else if(node instanceof RepetitionMandatory){return{type:"RepetitionMandatory",idx:node.idx,definition:convertDefinition(node.definition)}}else if(node instanceof RepetitionMandatoryWithSeparator){return{type:"RepetitionMandatoryWithSeparator",idx:node.idx,separator:serializeProduction(new Terminal({terminalType:node.separator})),definition:convertDefinition(node.definition)}}else if(node instanceof RepetitionWithSeparator){return{type:"RepetitionWithSeparator",idx:node.idx,separator:serializeProduction(new Terminal({terminalType:node.separator})),definition:convertDefinition(node.definition)}}else if(node instanceof Repetition){return{type:"Repetition",idx:node.idx,definition:convertDefinition(node.definition)}}else if(node instanceof Alternation){return{type:"Alternation",idx:node.idx,definition:convertDefinition(node.definition)}}else if(node instanceof Terminal){var serializedTerminal={type:"Terminal",name:node.terminalType.name,label:tokens_public_1$2.tokenLabel(node.terminalType),idx:node.idx};if(utils_1$i.isString(node.label)){serializedTerminal.terminalLabel=node.label}var pattern=node.terminalType.PATTERN;if(node.terminalType.PATTERN){serializedTerminal.pattern=utils_1$i.isRegExp(pattern)?pattern.source:pattern}return serializedTerminal}else if(node instanceof Rule){return{type:"Rule",name:node.name,orgText:node.orgText,definition:convertDefinition(node.definition)}}else{throw Error("non exhaustive match")}}gast_public.serializeProduction=serializeProduction;Object.defineProperty(rest,"__esModule",{value:true});rest.RestWalker=void 0;var utils_1$h=api;var gast_public_1$8=gast_public;var RestWalker=(function(){function RestWalker2(){}RestWalker2.prototype.walk=function(prod,prevRest){var _this=this;if(prevRest===void 0){prevRest=[]}utils_1$h.forEach(prod.definition,function(subProd,index){var currRest=utils_1$h.drop(prod.definition,index+1);if(subProd instanceof gast_public_1$8.NonTerminal){_this.walkProdRef(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.Terminal){_this.walkTerminal(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.Alternative){_this.walkFlat(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.Option){_this.walkOption(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.RepetitionMandatory){_this.walkAtLeastOne(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.RepetitionMandatoryWithSeparator){_this.walkAtLeastOneSep(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.RepetitionWithSeparator){_this.walkManySep(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.Repetition){_this.walkMany(subProd,currRest,prevRest)}else if(subProd instanceof gast_public_1$8.Alternation){_this.walkOr(subProd,currRest,prevRest)}else{throw Error("non exhaustive match")}})};RestWalker2.prototype.walkTerminal=function(terminal,currRest,prevRest){};RestWalker2.prototype.walkProdRef=function(refProd,currRest,prevRest){};RestWalker2.prototype.walkFlat=function(flatProd,currRest,prevRest){var fullOrRest=currRest.concat(prevRest);this.walk(flatProd,fullOrRest)};RestWalker2.prototype.walkOption=function(optionProd,currRest,prevRest){var fullOrRest=currRest.concat(prevRest);this.walk(optionProd,fullOrRest)};RestWalker2.prototype.walkAtLeastOne=function(atLeastOneProd,currRest,prevRest){var fullAtLeastOneRest=[new gast_public_1$8.Option({definition:atLeastOneProd.definition})].concat(currRest,prevRest);this.walk(atLeastOneProd,fullAtLeastOneRest)};RestWalker2.prototype.walkAtLeastOneSep=function(atLeastOneSepProd,currRest,prevRest){var fullAtLeastOneSepRest=restForRepetitionWithSeparator(atLeastOneSepProd,currRest,prevRest);this.walk(atLeastOneSepProd,fullAtLeastOneSepRest)};RestWalker2.prototype.walkMany=function(manyProd,currRest,prevRest){var fullManyRest=[new gast_public_1$8.Option({definition:manyProd.definition})].concat(currRest,prevRest);this.walk(manyProd,fullManyRest)};RestWalker2.prototype.walkManySep=function(manySepProd,currRest,prevRest){var fullManySepRest=restForRepetitionWithSeparator(manySepProd,currRest,prevRest);this.walk(manySepProd,fullManySepRest)};RestWalker2.prototype.walkOr=function(orProd,currRest,prevRest){var _this=this;var fullOrRest=currRest.concat(prevRest);utils_1$h.forEach(orProd.definition,function(alt){var prodWrapper=new gast_public_1$8.Alternative({definition:[alt]});_this.walk(prodWrapper,fullOrRest)})};return RestWalker2})();rest.RestWalker=RestWalker;function restForRepetitionWithSeparator(repSepProd,currRest,prevRest){var repSepRest=[new gast_public_1$8.Option({definition:[new gast_public_1$8.Terminal({terminalType:repSepProd.separator})].concat(repSepProd.definition)})];var fullRepSepRest=repSepRest.concat(currRest,prevRest);return fullRepSepRest}var first$1={};var gast={};var gast_visitor_public={};Object.defineProperty(gast_visitor_public,"__esModule",{value:true});gast_visitor_public.GAstVisitor=void 0;var gast_public_1$7=gast_public;var GAstVisitor=(function(){function GAstVisitor2(){}GAstVisitor2.prototype.visit=function(node){var nodeAny=node;switch(nodeAny.constructor){case gast_public_1$7.NonTerminal:return this.visitNonTerminal(nodeAny);case gast_public_1$7.Alternative:return this.visitAlternative(nodeAny);case gast_public_1$7.Option:return this.visitOption(nodeAny);case gast_public_1$7.RepetitionMandatory:return this.visitRepetitionMandatory(nodeAny);case gast_public_1$7.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(nodeAny);case gast_public_1$7.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(nodeAny);case gast_public_1$7.Repetition:return this.visitRepetition(nodeAny);case gast_public_1$7.Alternation:return this.visitAlternation(nodeAny);case gast_public_1$7.Terminal:return this.visitTerminal(nodeAny);case gast_public_1$7.Rule:return this.visitRule(nodeAny);default:throw Error("non exhaustive match")}};GAstVisitor2.prototype.visitNonTerminal=function(node){};GAstVisitor2.prototype.visitAlternative=function(node){};GAstVisitor2.prototype.visitOption=function(node){};GAstVisitor2.prototype.visitRepetition=function(node){};GAstVisitor2.prototype.visitRepetitionMandatory=function(node){};GAstVisitor2.prototype.visitRepetitionMandatoryWithSeparator=function(node){};GAstVisitor2.prototype.visitRepetitionWithSeparator=function(node){};GAstVisitor2.prototype.visitAlternation=function(node){};GAstVisitor2.prototype.visitTerminal=function(node){};GAstVisitor2.prototype.visitRule=function(node){};return GAstVisitor2})();gast_visitor_public.GAstVisitor=GAstVisitor;var __extends$5=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(gast,"__esModule",{value:true});gast.collectMethods=gast.DslMethodsCollectorVisitor=gast.getProductionDslName=gast.isBranchingProd=gast.isOptionalProd=gast.isSequenceProd=void 0;var utils_1$g=api;var gast_public_1$6=gast_public;var gast_visitor_public_1$2=gast_visitor_public;function isSequenceProd(prod){return prod instanceof gast_public_1$6.Alternative||prod instanceof gast_public_1$6.Option||prod instanceof gast_public_1$6.Repetition||prod instanceof gast_public_1$6.RepetitionMandatory||prod instanceof gast_public_1$6.RepetitionMandatoryWithSeparator||prod instanceof gast_public_1$6.RepetitionWithSeparator||prod instanceof gast_public_1$6.Terminal||prod instanceof gast_public_1$6.Rule}gast.isSequenceProd=isSequenceProd;function isOptionalProd(prod,alreadyVisited){if(alreadyVisited===void 0){alreadyVisited=[]}var isDirectlyOptional=prod instanceof gast_public_1$6.Option||prod instanceof gast_public_1$6.Repetition||prod instanceof gast_public_1$6.RepetitionWithSeparator;if(isDirectlyOptional){return true}if(prod instanceof gast_public_1$6.Alternation){return utils_1$g.some(prod.definition,function(subProd){return isOptionalProd(subProd,alreadyVisited)})}else if(prod instanceof gast_public_1$6.NonTerminal&&utils_1$g.contains(alreadyVisited,prod)){return false}else if(prod instanceof gast_public_1$6.AbstractProduction){if(prod instanceof gast_public_1$6.NonTerminal){alreadyVisited.push(prod)}return utils_1$g.every(prod.definition,function(subProd){return isOptionalProd(subProd,alreadyVisited)})}else{return false}}gast.isOptionalProd=isOptionalProd;function isBranchingProd(prod){return prod instanceof gast_public_1$6.Alternation}gast.isBranchingProd=isBranchingProd;function getProductionDslName(prod){if(prod instanceof gast_public_1$6.NonTerminal){return"SUBRULE"}else if(prod instanceof gast_public_1$6.Option){return"OPTION"}else if(prod instanceof gast_public_1$6.Alternation){return"OR"}else if(prod instanceof gast_public_1$6.RepetitionMandatory){return"AT_LEAST_ONE"}else if(prod instanceof gast_public_1$6.RepetitionMandatoryWithSeparator){return"AT_LEAST_ONE_SEP"}else if(prod instanceof gast_public_1$6.RepetitionWithSeparator){return"MANY_SEP"}else if(prod instanceof gast_public_1$6.Repetition){return"MANY"}else if(prod instanceof gast_public_1$6.Terminal){return"CONSUME"}else{throw Error("non exhaustive match")}}gast.getProductionDslName=getProductionDslName;var DslMethodsCollectorVisitor=(function(_super){__extends$5(DslMethodsCollectorVisitor2,_super);function DslMethodsCollectorVisitor2(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.separator="-";_this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]};return _this}DslMethodsCollectorVisitor2.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}};DslMethodsCollectorVisitor2.prototype.visitTerminal=function(terminal){var key=terminal.terminalType.name+this.separator+"Terminal";if(!utils_1$g.has(this.dslMethods,key)){this.dslMethods[key]=[]}this.dslMethods[key].push(terminal)};DslMethodsCollectorVisitor2.prototype.visitNonTerminal=function(subrule){var key=subrule.nonTerminalName+this.separator+"Terminal";if(!utils_1$g.has(this.dslMethods,key)){this.dslMethods[key]=[]}this.dslMethods[key].push(subrule)};DslMethodsCollectorVisitor2.prototype.visitOption=function(option){this.dslMethods.option.push(option)};DslMethodsCollectorVisitor2.prototype.visitRepetitionWithSeparator=function(manySep){this.dslMethods.repetitionWithSeparator.push(manySep)};DslMethodsCollectorVisitor2.prototype.visitRepetitionMandatory=function(atLeastOne){this.dslMethods.repetitionMandatory.push(atLeastOne)};DslMethodsCollectorVisitor2.prototype.visitRepetitionMandatoryWithSeparator=function(atLeastOneSep){this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep)};DslMethodsCollectorVisitor2.prototype.visitRepetition=function(many){this.dslMethods.repetition.push(many)};DslMethodsCollectorVisitor2.prototype.visitAlternation=function(or){this.dslMethods.alternation.push(or)};return DslMethodsCollectorVisitor2})(gast_visitor_public_1$2.GAstVisitor);gast.DslMethodsCollectorVisitor=DslMethodsCollectorVisitor;var collectorVisitor=new DslMethodsCollectorVisitor;function collectMethods(rule){collectorVisitor.reset();rule.accept(collectorVisitor);var dslMethods=collectorVisitor.dslMethods;collectorVisitor.reset();return dslMethods}gast.collectMethods=collectMethods;Object.defineProperty(first$1,"__esModule",{value:true});first$1.firstForTerminal=first$1.firstForBranching=first$1.firstForSequence=first$1.first=void 0;var utils_1$f=api;var gast_public_1$5=gast_public;var gast_1$2=gast;function first(prod){if(prod instanceof gast_public_1$5.NonTerminal){return first(prod.referencedRule)}else if(prod instanceof gast_public_1$5.Terminal){return firstForTerminal(prod)}else if(gast_1$2.isSequenceProd(prod)){return firstForSequence(prod)}else if(gast_1$2.isBranchingProd(prod)){return firstForBranching(prod)}else{throw Error("non exhaustive match")}}first$1.first=first;function firstForSequence(prod){var firstSet=[];var seq=prod.definition;var nextSubProdIdx=0;var hasInnerProdsRemaining=seq.length>nextSubProdIdx;var currSubProd;var isLastInnerProdOptional=true;while(hasInnerProdsRemaining&&isLastInnerProdOptional){currSubProd=seq[nextSubProdIdx];isLastInnerProdOptional=gast_1$2.isOptionalProd(currSubProd);firstSet=firstSet.concat(first(currSubProd));nextSubProdIdx=nextSubProdIdx+1;hasInnerProdsRemaining=seq.length>nextSubProdIdx}return utils_1$f.uniq(firstSet)}first$1.firstForSequence=firstForSequence;function firstForBranching(prod){var allAlternativesFirsts=utils_1$f.map(prod.definition,function(innerProd){return first(innerProd)});return utils_1$f.uniq(utils_1$f.flatten(allAlternativesFirsts))}first$1.firstForBranching=firstForBranching;function firstForTerminal(terminal){return[terminal.terminalType]}first$1.firstForTerminal=firstForTerminal;var constants={};Object.defineProperty(constants,"__esModule",{value:true});constants.IN=void 0;constants.IN="_~IN~_";var __extends$4=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(follow,"__esModule",{value:true});follow.buildInProdFollowPrefix=follow.buildBetweenProdsFollowPrefix=follow.computeAllProdsFollows=follow.ResyncFollowsWalker=void 0;var rest_1$1=rest;var first_1$1=first$1;var utils_1$e=api;var constants_1=constants;var gast_public_1$4=gast_public;var ResyncFollowsWalker=(function(_super){__extends$4(ResyncFollowsWalker2,_super);function ResyncFollowsWalker2(topProd){var _this=_super.call(this)||this;_this.topProd=topProd;_this.follows={};return _this}ResyncFollowsWalker2.prototype.startWalking=function(){this.walk(this.topProd);return this.follows};ResyncFollowsWalker2.prototype.walkTerminal=function(terminal,currRest,prevRest){};ResyncFollowsWalker2.prototype.walkProdRef=function(refProd,currRest,prevRest){var followName=buildBetweenProdsFollowPrefix(refProd.referencedRule,refProd.idx)+this.topProd.name;var fullRest=currRest.concat(prevRest);var restProd=new gast_public_1$4.Alternative({definition:fullRest});var t_in_topProd_follows=first_1$1.first(restProd);this.follows[followName]=t_in_topProd_follows};return ResyncFollowsWalker2})(rest_1$1.RestWalker);follow.ResyncFollowsWalker=ResyncFollowsWalker;function computeAllProdsFollows(topProductions){var reSyncFollows={};utils_1$e.forEach(topProductions,function(topProd){var currRefsFollow=new ResyncFollowsWalker(topProd).startWalking();utils_1$e.assign(reSyncFollows,currRefsFollow)});return reSyncFollows}follow.computeAllProdsFollows=computeAllProdsFollows;function buildBetweenProdsFollowPrefix(inner,occurenceInParent){return inner.name+occurenceInParent+constants_1.IN}follow.buildBetweenProdsFollowPrefix=buildBetweenProdsFollowPrefix;function buildInProdFollowPrefix(terminal){var terminalName=terminal.terminalType.name;return terminalName+terminal.idx+constants_1.IN}follow.buildInProdFollowPrefix=buildInProdFollowPrefix;var errors_public={};(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.defaultGrammarValidatorErrorProvider=exports3.defaultGrammarResolverErrorProvider=exports3.defaultParserErrorProvider=void 0;var tokens_public_12=tokens_public;var utils2=api;var utils_12=api;var gast_public_12=gast_public;var gast_12=gast;exports3.defaultParserErrorProvider={buildMismatchTokenMessage:function(_a){var expected=_a.expected,actual=_a.actual;_a.previous;_a.ruleName;var hasLabel=tokens_public_12.hasTokenLabel(expected);var expectedMsg=hasLabel?"--> "+tokens_public_12.tokenLabel(expected)+" <--":"token of type --> "+expected.name+" <--";var msg="Expecting "+expectedMsg+" but found --> '"+actual.image+"' <--";return msg},buildNotAllInputParsedMessage:function(_a){var firstRedundant=_a.firstRedundant;_a.ruleName;return"Redundant input, expecting EOF but found: "+firstRedundant.image},buildNoViableAltMessage:function(_a){var expectedPathsPerAlt=_a.expectedPathsPerAlt,actual=_a.actual;_a.previous;var customUserDescription=_a.customUserDescription;_a.ruleName;var errPrefix="Expecting: ";var actualText=utils_12.first(actual).image;var errSuffix="\nbut found: '"+actualText+"'";if(customUserDescription){return errPrefix+customUserDescription+errSuffix}else{var allLookAheadPaths=utils_12.reduce(expectedPathsPerAlt,function(result,currAltPaths){return result.concat(currAltPaths)},[]);var nextValidTokenSequences=utils_12.map(allLookAheadPaths,function(currPath){return"["+utils_12.map(currPath,function(currTokenType){return tokens_public_12.tokenLabel(currTokenType)}).join(", ")+"]"});var nextValidSequenceItems=utils_12.map(nextValidTokenSequences,function(itemMsg,idx){return" "+(idx+1)+". "+itemMsg});var calculatedDescription="one of these possible Token sequences:\n"+nextValidSequenceItems.join("\n");return errPrefix+calculatedDescription+errSuffix}},buildEarlyExitMessage:function(_a){var expectedIterationPaths=_a.expectedIterationPaths,actual=_a.actual,customUserDescription=_a.customUserDescription;_a.ruleName;var errPrefix="Expecting: ";var actualText=utils_12.first(actual).image;var errSuffix="\nbut found: '"+actualText+"'";if(customUserDescription){return errPrefix+customUserDescription+errSuffix}else{var nextValidTokenSequences=utils_12.map(expectedIterationPaths,function(currPath){return"["+utils_12.map(currPath,function(currTokenType){return tokens_public_12.tokenLabel(currTokenType)}).join(",")+"]"});var calculatedDescription="expecting at least one iteration which starts with one of these possible Token sequences::\n "+("<"+nextValidTokenSequences.join(" ,")+">");return errPrefix+calculatedDescription+errSuffix}}};Object.freeze(exports3.defaultParserErrorProvider);exports3.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(topLevelRule,undefinedRule){var msg="Invalid grammar, reference to a rule which is not defined: ->"+undefinedRule.nonTerminalName+"<-\ninside top level rule: ->"+topLevelRule.name+"<-";return msg}};exports3.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(topLevelRule,duplicateProds){function getExtraProductionArgument2(prod){if(prod instanceof gast_public_12.Terminal){return prod.terminalType.name}else if(prod instanceof gast_public_12.NonTerminal){return prod.nonTerminalName}else{return""}}var topLevelName=topLevelRule.name;var duplicateProd=utils_12.first(duplicateProds);var index=duplicateProd.idx;var dslName=gast_12.getProductionDslName(duplicateProd);var extraArgument=getExtraProductionArgument2(duplicateProd);var hasExplicitIndex=index>0;var msg="->"+dslName+(hasExplicitIndex?index:"")+"<- "+(extraArgument?"with argument: ->"+extraArgument+"<-":"")+"\n appears more than once ("+duplicateProds.length+" times) in the top level rule: ->"+topLevelName+"<-. \n For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";msg=msg.replace(/[ \t]+/g," ");msg=msg.replace(/\s\s+/g,"\n");return msg},buildNamespaceConflictError:function(rule){var errMsg="Namespace conflict found in grammar.\n"+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+rule.name+">.\n")+"To resolve this make sure each Terminal and Non-Terminal names are unique\nThis is easy to accomplish by using the convention that Terminal names start with an uppercase letter\nand Non-Terminal names start with a lower case letter.";return errMsg},buildAlternationPrefixAmbiguityError:function(options){var pathMsg=utils_12.map(options.prefixPath,function(currTok){return tokens_public_12.tokenLabel(currTok)}).join(", ");var occurrence=options.alternation.idx===0?"":options.alternation.idx;var errMsg="Ambiguous alternatives: <"+options.ambiguityIndices.join(" ,")+"> due to common lookahead prefix\n"+("in <OR"+occurrence+"> inside <"+options.topLevelRule.name+"> Rule,\n")+("<"+pathMsg+"> may appears as a prefix path in all these alternatives.\n")+"See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\nFor Further details.";return errMsg},buildAlternationAmbiguityError:function(options){var pathMsg=utils_12.map(options.prefixPath,function(currtok){return tokens_public_12.tokenLabel(currtok)}).join(", ");var occurrence=options.alternation.idx===0?"":options.alternation.idx;var currMessage="Ambiguous Alternatives Detected: <"+options.ambiguityIndices.join(" ,")+"> in <OR"+occurrence+">"+(" inside <"+options.topLevelRule.name+"> Rule,\n")+("<"+pathMsg+"> may appears as a prefix path in all these alternatives.\n");currMessage=currMessage+"See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\nFor Further details.";return currMessage},buildEmptyRepetitionError:function(options){var dslName=gast_12.getProductionDslName(options.repetition);if(options.repetition.idx!==0){dslName+=options.repetition.idx}var errMsg="The repetition <"+dslName+"> within Rule <"+options.topLevelRule.name+"> can never consume any tokens.\nThis could lead to an infinite loop.";return errMsg},buildTokenNameError:function(options){return"deprecated"},buildEmptyAlternationError:function(options){var errMsg="Ambiguous empty alternative: <"+(options.emptyChoiceIdx+1)+">"+(" in <OR"+options.alternation.idx+"> inside <"+options.topLevelRule.name+"> Rule.\n")+"Only the last alternative may be an empty alternative.";return errMsg},buildTooManyAlternativesError:function(options){var errMsg="An Alternation cannot have more than 256 alternatives:\n"+("<OR"+options.alternation.idx+"> inside <"+options.topLevelRule.name+"> Rule.\n has "+(options.alternation.definition.length+1)+" alternatives.");return errMsg},buildLeftRecursionError:function(options){var ruleName=options.topLevelRule.name;var pathNames=utils2.map(options.leftRecursionPath,function(currRule){return currRule.name});var leftRecursivePath=ruleName+" --> "+pathNames.concat([ruleName]).join(" --> ");var errMsg="Left Recursion found in grammar.\n"+("rule: <"+ruleName+"> can be invoked from itself (directly or indirectly)\n")+("without consuming any Tokens. The grammar path that causes this is: \n "+leftRecursivePath+"\n")+" To fix this refactor your grammar to remove the left recursion.\nsee: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.";return errMsg},buildInvalidRuleNameError:function(options){return"deprecated"},buildDuplicateRuleNameError:function(options){var ruleName;if(options.topLevelRule instanceof gast_public_12.Rule){ruleName=options.topLevelRule.name}else{ruleName=options.topLevelRule}var errMsg="Duplicate definition, rule: ->"+ruleName+"<- is already defined in the grammar: ->"+options.grammarName+"<-";return errMsg}}})(errors_public);var gast_resolver_public={};var resolver={};var __extends$3=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(resolver,"__esModule",{value:true});resolver.GastRefResolverVisitor=resolver.resolveGrammar=void 0;var parser_1$9=parser;var utils_1$d=api;var gast_visitor_public_1$1=gast_visitor_public;function resolveGrammar$1(topLevels,errMsgProvider){var refResolver=new GastRefResolverVisitor(topLevels,errMsgProvider);refResolver.resolveRefs();return refResolver.errors}resolver.resolveGrammar=resolveGrammar$1;var GastRefResolverVisitor=(function(_super){__extends$3(GastRefResolverVisitor2,_super);function GastRefResolverVisitor2(nameToTopRule,errMsgProvider){var _this=_super.call(this)||this;_this.nameToTopRule=nameToTopRule;_this.errMsgProvider=errMsgProvider;_this.errors=[];return _this}GastRefResolverVisitor2.prototype.resolveRefs=function(){var _this=this;utils_1$d.forEach(utils_1$d.values(this.nameToTopRule),function(prod){_this.currTopLevel=prod;prod.accept(_this)})};GastRefResolverVisitor2.prototype.visitNonTerminal=function(node){var ref=this.nameToTopRule[node.nonTerminalName];if(!ref){var msg=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,node);this.errors.push({message:msg,type:parser_1$9.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:node.nonTerminalName})}else{node.referencedRule=ref}};return GastRefResolverVisitor2})(gast_visitor_public_1$1.GAstVisitor);resolver.GastRefResolverVisitor=GastRefResolverVisitor;var checks={};var lookahead={};var interpreter={};var __extends$2=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(interpreter,"__esModule",{value:true});interpreter.nextPossibleTokensAfter=interpreter.possiblePathsFrom=interpreter.NextTerminalAfterAtLeastOneSepWalker=interpreter.NextTerminalAfterAtLeastOneWalker=interpreter.NextTerminalAfterManySepWalker=interpreter.NextTerminalAfterManyWalker=interpreter.AbstractNextTerminalAfterProductionWalker=interpreter.NextAfterTokenWalker=interpreter.AbstractNextPossibleTokensWalker=void 0;var rest_1=rest;var utils_1$c=api;var first_1=first$1;var gast_public_1$3=gast_public;var AbstractNextPossibleTokensWalker=(function(_super){__extends$2(AbstractNextPossibleTokensWalker2,_super);function AbstractNextPossibleTokensWalker2(topProd,path){var _this=_super.call(this)||this;_this.topProd=topProd;_this.path=path;_this.possibleTokTypes=[];_this.nextProductionName="";_this.nextProductionOccurrence=0;_this.found=false;_this.isAtEndOfPath=false;return _this}AbstractNextPossibleTokensWalker2.prototype.startWalking=function(){this.found=false;if(this.path.ruleStack[0]!==this.topProd.name){throw Error("The path does not start with the walker's top Rule!")}this.ruleStack=utils_1$c.cloneArr(this.path.ruleStack).reverse();this.occurrenceStack=utils_1$c.cloneArr(this.path.occurrenceStack).reverse();this.ruleStack.pop();this.occurrenceStack.pop();this.updateExpectedNext();this.walk(this.topProd);return this.possibleTokTypes};AbstractNextPossibleTokensWalker2.prototype.walk=function(prod,prevRest){if(prevRest===void 0){prevRest=[]}if(!this.found){_super.prototype.walk.call(this,prod,prevRest)}};AbstractNextPossibleTokensWalker2.prototype.walkProdRef=function(refProd,currRest,prevRest){if(refProd.referencedRule.name===this.nextProductionName&&refProd.idx===this.nextProductionOccurrence){var fullRest=currRest.concat(prevRest);this.updateExpectedNext();this.walk(refProd.referencedRule,fullRest)}};AbstractNextPossibleTokensWalker2.prototype.updateExpectedNext=function(){if(utils_1$c.isEmpty(this.ruleStack)){this.nextProductionName="";this.nextProductionOccurrence=0;this.isAtEndOfPath=true}else{this.nextProductionName=this.ruleStack.pop();this.nextProductionOccurrence=this.occurrenceStack.pop()}};return AbstractNextPossibleTokensWalker2})(rest_1.RestWalker);interpreter.AbstractNextPossibleTokensWalker=AbstractNextPossibleTokensWalker;var NextAfterTokenWalker=(function(_super){__extends$2(NextAfterTokenWalker2,_super);function NextAfterTokenWalker2(topProd,path){var _this=_super.call(this,topProd,path)||this;_this.path=path;_this.nextTerminalName="";_this.nextTerminalOccurrence=0;_this.nextTerminalName=_this.path.lastTok.name;_this.nextTerminalOccurrence=_this.path.lastTokOccurrence;return _this}NextAfterTokenWalker2.prototype.walkTerminal=function(terminal,currRest,prevRest){if(this.isAtEndOfPath&&terminal.terminalType.name===this.nextTerminalName&&terminal.idx===this.nextTerminalOccurrence&&!this.found){var fullRest=currRest.concat(prevRest);var restProd=new gast_public_1$3.Alternative({definition:fullRest});this.possibleTokTypes=first_1.first(restProd);this.found=true}};return NextAfterTokenWalker2})(AbstractNextPossibleTokensWalker);interpreter.NextAfterTokenWalker=NextAfterTokenWalker;var AbstractNextTerminalAfterProductionWalker=(function(_super){__extends$2(AbstractNextTerminalAfterProductionWalker2,_super);function AbstractNextTerminalAfterProductionWalker2(topRule,occurrence){var _this=_super.call(this)||this;_this.topRule=topRule;_this.occurrence=occurrence;_this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0};return _this}AbstractNextTerminalAfterProductionWalker2.prototype.startWalking=function(){this.walk(this.topRule);return this.result};return AbstractNextTerminalAfterProductionWalker2})(rest_1.RestWalker);interpreter.AbstractNextTerminalAfterProductionWalker=AbstractNextTerminalAfterProductionWalker;var NextTerminalAfterManyWalker=(function(_super){__extends$2(NextTerminalAfterManyWalker2,_super);function NextTerminalAfterManyWalker2(){return _super!==null&&_super.apply(this,arguments)||this}NextTerminalAfterManyWalker2.prototype.walkMany=function(manyProd,currRest,prevRest){if(manyProd.idx===this.occurrence){var firstAfterMany=utils_1$c.first(currRest.concat(prevRest));this.result.isEndOfRule=firstAfterMany===void 0;if(firstAfterMany instanceof gast_public_1$3.Terminal){this.result.token=firstAfterMany.terminalType;this.result.occurrence=firstAfterMany.idx}}else{_super.prototype.walkMany.call(this,manyProd,currRest,prevRest)}};return NextTerminalAfterManyWalker2})(AbstractNextTerminalAfterProductionWalker);interpreter.NextTerminalAfterManyWalker=NextTerminalAfterManyWalker;var NextTerminalAfterManySepWalker=(function(_super){__extends$2(NextTerminalAfterManySepWalker2,_super);function NextTerminalAfterManySepWalker2(){return _super!==null&&_super.apply(this,arguments)||this}NextTerminalAfterManySepWalker2.prototype.walkManySep=function(manySepProd,currRest,prevRest){if(manySepProd.idx===this.occurrence){var firstAfterManySep=utils_1$c.first(currRest.concat(prevRest));this.result.isEndOfRule=firstAfterManySep===void 0;if(firstAfterManySep instanceof gast_public_1$3.Terminal){this.result.token=firstAfterManySep.terminalType;this.result.occurrence=firstAfterManySep.idx}}else{_super.prototype.walkManySep.call(this,manySepProd,currRest,prevRest)}};return NextTerminalAfterManySepWalker2})(AbstractNextTerminalAfterProductionWalker);interpreter.NextTerminalAfterManySepWalker=NextTerminalAfterManySepWalker;var NextTerminalAfterAtLeastOneWalker=(function(_super){__extends$2(NextTerminalAfterAtLeastOneWalker2,_super);function NextTerminalAfterAtLeastOneWalker2(){return _super!==null&&_super.apply(this,arguments)||this}NextTerminalAfterAtLeastOneWalker2.prototype.walkAtLeastOne=function(atLeastOneProd,currRest,prevRest){if(atLeastOneProd.idx===this.occurrence){var firstAfterAtLeastOne=utils_1$c.first(currRest.concat(prevRest));this.result.isEndOfRule=firstAfterAtLeastOne===void 0;if(firstAfterAtLeastOne instanceof gast_public_1$3.Terminal){this.result.token=firstAfterAtLeastOne.terminalType;this.result.occurrence=firstAfterAtLeastOne.idx}}else{_super.prototype.walkAtLeastOne.call(this,atLeastOneProd,currRest,prevRest)}};return NextTerminalAfterAtLeastOneWalker2})(AbstractNextTerminalAfterProductionWalker);interpreter.NextTerminalAfterAtLeastOneWalker=NextTerminalAfterAtLeastOneWalker;var NextTerminalAfterAtLeastOneSepWalker=(function(_super){__extends$2(NextTerminalAfterAtLeastOneSepWalker2,_super);function NextTerminalAfterAtLeastOneSepWalker2(){return _super!==null&&_super.apply(this,arguments)||this}NextTerminalAfterAtLeastOneSepWalker2.prototype.walkAtLeastOneSep=function(atleastOneSepProd,currRest,prevRest){if(atleastOneSepProd.idx===this.occurrence){var firstAfterfirstAfterAtLeastOneSep=utils_1$c.first(currRest.concat(prevRest));this.result.isEndOfRule=firstAfterfirstAfterAtLeastOneSep===void 0;if(firstAfterfirstAfterAtLeastOneSep instanceof gast_public_1$3.Terminal){this.result.token=firstAfterfirstAfterAtLeastOneSep.terminalType;this.result.occurrence=firstAfterfirstAfterAtLeastOneSep.idx}}else{_super.prototype.walkAtLeastOneSep.call(this,atleastOneSepProd,currRest,prevRest)}};return NextTerminalAfterAtLeastOneSepWalker2})(AbstractNextTerminalAfterProductionWalker);interpreter.NextTerminalAfterAtLeastOneSepWalker=NextTerminalAfterAtLeastOneSepWalker;function possiblePathsFrom(targetDef,maxLength,currPath){if(currPath===void 0){currPath=[]}currPath=utils_1$c.cloneArr(currPath);var result=[];var i=0;function remainingPathWith(nextDef){return nextDef.concat(utils_1$c.drop(targetDef,i+1))}function getAlternativesForProd(definition){var alternatives=possiblePathsFrom(remainingPathWith(definition),maxLength,currPath);return result.concat(alternatives)}while(currPath.length<maxLength&&i<targetDef.length){var prod=targetDef[i];if(prod instanceof gast_public_1$3.Alternative){return getAlternativesForProd(prod.definition)}else if(prod instanceof gast_public_1$3.NonTerminal){return getAlternativesForProd(prod.definition)}else if(prod instanceof gast_public_1$3.Option){result=getAlternativesForProd(prod.definition)}else if(prod instanceof gast_public_1$3.RepetitionMandatory){var newDef=prod.definition.concat([new gast_public_1$3.Repetition({definition:prod.definition})]);return getAlternativesForProd(newDef)}else if(prod instanceof gast_public_1$3.RepetitionMandatoryWithSeparator){var newDef=[new gast_public_1$3.Alternative({definition:prod.definition}),new gast_public_1$3.Repetition({definition:[new gast_public_1$3.Terminal({terminalType:prod.separator})].concat(prod.definition)})];return getAlternativesForProd(newDef)}else if(prod instanceof gast_public_1$3.RepetitionWithSeparator){var newDef=prod.definition.concat([new gast_public_1$3.Repetition({definition:[new gast_public_1$3.Terminal({terminalType:prod.separator})].concat(prod.definition)})]);result=getAlternativesForProd(newDef)}else if(prod instanceof gast_public_1$3.Repetition){var newDef=prod.definition.concat([new gast_public_1$3.Repetition({definition:prod.definition})]);result=getAlternativesForProd(newDef)}else if(prod instanceof gast_public_1$3.Alternation){utils_1$c.forEach(prod.definition,function(currAlt){if(utils_1$c.isEmpty(currAlt.definition)===false){result=getAlternativesForProd(currAlt.definition)}});return result}else if(prod instanceof gast_public_1$3.Terminal){currPath.push(prod.terminalType)}else{throw Error("non exhaustive match")}i++}result.push({partialPath:currPath,suffixDef:utils_1$c.drop(targetDef,i)});return result}interpreter.possiblePathsFrom=possiblePathsFrom;function nextPossibleTokensAfter(initialDef,tokenVector,tokMatcher,maxLookAhead){var EXIT_NON_TERMINAL="EXIT_NONE_TERMINAL";var EXIT_NON_TERMINAL_ARR=[EXIT_NON_TERMINAL];var EXIT_ALTERNATIVE="EXIT_ALTERNATIVE";var foundCompletePath=false;var tokenVectorLength=tokenVector.length;var minimalAlternativesIndex=tokenVectorLength-maxLookAhead-1;var result=[];var possiblePaths=[];possiblePaths.push({idx:-1,def:initialDef,ruleStack:[],occurrenceStack:[]});while(!utils_1$c.isEmpty(possiblePaths)){var currPath=possiblePaths.pop();if(currPath===EXIT_ALTERNATIVE){if(foundCompletePath&&utils_1$c.last(possiblePaths).idx<=minimalAlternativesIndex){possiblePaths.pop()}continue}var currDef=currPath.def;var currIdx=currPath.idx;var currRuleStack=currPath.ruleStack;var currOccurrenceStack=currPath.occurrenceStack;if(utils_1$c.isEmpty(currDef)){continue}var prod=currDef[0];if(prod===EXIT_NON_TERMINAL){var nextPath={idx:currIdx,def:utils_1$c.drop(currDef),ruleStack:utils_1$c.dropRight(currRuleStack),occurrenceStack:utils_1$c.dropRight(currOccurrenceStack)};possiblePaths.push(nextPath)}else if(prod instanceof gast_public_1$3.Terminal){if(currIdx<tokenVectorLength-1){var nextIdx=currIdx+1;var actualToken=tokenVector[nextIdx];if(tokMatcher(actualToken,prod.terminalType)){var nextPath={idx:nextIdx,def:utils_1$c.drop(currDef),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPath)}}else if(currIdx===tokenVectorLength-1){result.push({nextTokenType:prod.terminalType,nextTokenOccurrence:prod.idx,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack});foundCompletePath=true}else{throw Error("non exhaustive match")}}else if(prod instanceof gast_public_1$3.NonTerminal){var newRuleStack=utils_1$c.cloneArr(currRuleStack);newRuleStack.push(prod.nonTerminalName);var newOccurrenceStack=utils_1$c.cloneArr(currOccurrenceStack);newOccurrenceStack.push(prod.idx);var nextPath={idx:currIdx,def:prod.definition.concat(EXIT_NON_TERMINAL_ARR,utils_1$c.drop(currDef)),ruleStack:newRuleStack,occurrenceStack:newOccurrenceStack};possiblePaths.push(nextPath)}else if(prod instanceof gast_public_1$3.Option){var nextPathWithout={idx:currIdx,def:utils_1$c.drop(currDef),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWithout);possiblePaths.push(EXIT_ALTERNATIVE);var nextPathWith={idx:currIdx,def:prod.definition.concat(utils_1$c.drop(currDef)),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWith)}else if(prod instanceof gast_public_1$3.RepetitionMandatory){var secondIteration=new gast_public_1$3.Repetition({definition:prod.definition,idx:prod.idx});var nextDef=prod.definition.concat([secondIteration],utils_1$c.drop(currDef));var nextPath={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPath)}else if(prod instanceof gast_public_1$3.RepetitionMandatoryWithSeparator){var separatorGast=new gast_public_1$3.Terminal({terminalType:prod.separator});var secondIteration=new gast_public_1$3.Repetition({definition:[separatorGast].concat(prod.definition),idx:prod.idx});var nextDef=prod.definition.concat([secondIteration],utils_1$c.drop(currDef));var nextPath={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPath)}else if(prod instanceof gast_public_1$3.RepetitionWithSeparator){var nextPathWithout={idx:currIdx,def:utils_1$c.drop(currDef),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWithout);possiblePaths.push(EXIT_ALTERNATIVE);var separatorGast=new gast_public_1$3.Terminal({terminalType:prod.separator});var nthRepetition=new gast_public_1$3.Repetition({definition:[separatorGast].concat(prod.definition),idx:prod.idx});var nextDef=prod.definition.concat([nthRepetition],utils_1$c.drop(currDef));var nextPathWith={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWith)}else if(prod instanceof gast_public_1$3.Repetition){var nextPathWithout={idx:currIdx,def:utils_1$c.drop(currDef),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWithout);possiblePaths.push(EXIT_ALTERNATIVE);var nthRepetition=new gast_public_1$3.Repetition({definition:prod.definition,idx:prod.idx});var nextDef=prod.definition.concat([nthRepetition],utils_1$c.drop(currDef));var nextPathWith={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWith)}else if(prod instanceof gast_public_1$3.Alternation){for(var i=prod.definition.length-1;i>=0;i--){var currAlt=prod.definition[i];var currAltPath={idx:currIdx,def:currAlt.definition.concat(utils_1$c.drop(currDef)),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(currAltPath);possiblePaths.push(EXIT_ALTERNATIVE)}}else if(prod instanceof gast_public_1$3.Alternative){possiblePaths.push({idx:currIdx,def:prod.definition.concat(utils_1$c.drop(currDef)),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack})}else if(prod instanceof gast_public_1$3.Rule){possiblePaths.push(expandTopLevelRule(prod,currIdx,currRuleStack,currOccurrenceStack))}else{throw Error("non exhaustive match")}}return result}interpreter.nextPossibleTokensAfter=nextPossibleTokensAfter;function expandTopLevelRule(topRule,currIdx,currRuleStack,currOccurrenceStack){var newRuleStack=utils_1$c.cloneArr(currRuleStack);newRuleStack.push(topRule.name);var newCurrOccurrenceStack=utils_1$c.cloneArr(currOccurrenceStack);newCurrOccurrenceStack.push(1);return{idx:currIdx,def:topRule.definition,ruleStack:newRuleStack,occurrenceStack:newCurrOccurrenceStack}}(function(exports3){var __extends2=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(exports3,"__esModule",{value:true});exports3.areTokenCategoriesNotUsed=exports3.isStrictPrefixOfPath=exports3.containsPath=exports3.getLookaheadPathsForOptionalProd=exports3.getLookaheadPathsForOr=exports3.lookAheadSequenceFromAlternatives=exports3.buildSingleAlternativeLookaheadFunction=exports3.buildAlternativesLookAheadFunc=exports3.buildLookaheadFuncForOptionalProd=exports3.buildLookaheadFuncForOr=exports3.getProdType=exports3.PROD_TYPE=void 0;var utils_12=api;var interpreter_12=interpreter;var rest_12=rest;var tokens_12=tokens;var gast_public_12=gast_public;var gast_visitor_public_12=gast_visitor_public;var PROD_TYPE;(function(PROD_TYPE2){PROD_TYPE2[PROD_TYPE2["OPTION"]=0]="OPTION";PROD_TYPE2[PROD_TYPE2["REPETITION"]=1]="REPETITION";PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY"]=2]="REPETITION_MANDATORY";PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY_WITH_SEPARATOR"]=3]="REPETITION_MANDATORY_WITH_SEPARATOR";PROD_TYPE2[PROD_TYPE2["REPETITION_WITH_SEPARATOR"]=4]="REPETITION_WITH_SEPARATOR";PROD_TYPE2[PROD_TYPE2["ALTERNATION"]=5]="ALTERNATION"})(PROD_TYPE=exports3.PROD_TYPE||(exports3.PROD_TYPE={}));function getProdType(prod){if(prod instanceof gast_public_12.Option){return PROD_TYPE.OPTION}else if(prod instanceof gast_public_12.Repetition){return PROD_TYPE.REPETITION}else if(prod instanceof gast_public_12.RepetitionMandatory){return PROD_TYPE.REPETITION_MANDATORY}else if(prod instanceof gast_public_12.RepetitionMandatoryWithSeparator){return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR}else if(prod instanceof gast_public_12.RepetitionWithSeparator){return PROD_TYPE.REPETITION_WITH_SEPARATOR}else if(prod instanceof gast_public_12.Alternation){return PROD_TYPE.ALTERNATION}else{throw Error("non exhaustive match")}}exports3.getProdType=getProdType;function buildLookaheadFuncForOr(occurrence,ruleGrammar,maxLookahead,hasPredicates,dynamicTokensEnabled,laFuncBuilder){var lookAheadPaths=getLookaheadPathsForOr(occurrence,ruleGrammar,maxLookahead);var tokenMatcher=areTokenCategoriesNotUsed(lookAheadPaths)?tokens_12.tokenStructuredMatcherNoCategories:tokens_12.tokenStructuredMatcher;return laFuncBuilder(lookAheadPaths,hasPredicates,tokenMatcher,dynamicTokensEnabled)}exports3.buildLookaheadFuncForOr=buildLookaheadFuncForOr;function buildLookaheadFuncForOptionalProd(occurrence,ruleGrammar,k,dynamicTokensEnabled,prodType,lookaheadBuilder){var lookAheadPaths=getLookaheadPathsForOptionalProd(occurrence,ruleGrammar,prodType,k);var tokenMatcher=areTokenCategoriesNotUsed(lookAheadPaths)?tokens_12.tokenStructuredMatcherNoCategories:tokens_12.tokenStructuredMatcher;return lookaheadBuilder(lookAheadPaths[0],tokenMatcher,dynamicTokensEnabled)}exports3.buildLookaheadFuncForOptionalProd=buildLookaheadFuncForOptionalProd;function buildAlternativesLookAheadFunc(alts,hasPredicates,tokenMatcher,dynamicTokensEnabled){var numOfAlts=alts.length;var areAllOneTokenLookahead=utils_12.every(alts,function(currAlt){return utils_12.every(currAlt,function(currPath){return currPath.length===1})});if(hasPredicates){return function(orAlts){var predicates=utils_12.map(orAlts,function(currAlt2){return currAlt2.GATE});for(var t=0;t<numOfAlts;t++){var currAlt=alts[t];var currNumOfPaths=currAlt.length;var currPredicate=predicates[t];if(currPredicate!==void 0&&currPredicate.call(this)===false){continue}nextPath:for(var j=0;j<currNumOfPaths;j++){var currPath=currAlt[j];var currPathLength=currPath.length;for(var i=0;i<currPathLength;i++){var nextToken=this.LA(i+1);if(tokenMatcher(nextToken,currPath[i])===false){continue nextPath}}return t}}return void 0}}else if(areAllOneTokenLookahead&&!dynamicTokensEnabled){var singleTokenAlts=utils_12.map(alts,function(currAlt){return utils_12.flatten(currAlt)});var choiceToAlt_1=utils_12.reduce(singleTokenAlts,function(result,currAlt,idx){utils_12.forEach(currAlt,function(currTokType){if(!utils_12.has(result,currTokType.tokenTypeIdx)){result[currTokType.tokenTypeIdx]=idx}utils_12.forEach(currTokType.categoryMatches,function(currExtendingType){if(!utils_12.has(result,currExtendingType)){result[currExtendingType]=idx}})});return result},[]);return function(){var nextToken=this.LA(1);return choiceToAlt_1[nextToken.tokenTypeIdx]}}else{return function(){for(var t=0;t<numOfAlts;t++){var currAlt=alts[t];var currNumOfPaths=currAlt.length;nextPath:for(var j=0;j<currNumOfPaths;j++){var currPath=currAlt[j];var currPathLength=currPath.length;for(var i=0;i<currPathLength;i++){var nextToken=this.LA(i+1);if(tokenMatcher(nextToken,currPath[i])===false){continue nextPath}}return t}}return void 0}}}exports3.buildAlternativesLookAheadFunc=buildAlternativesLookAheadFunc;function buildSingleAlternativeLookaheadFunction(alt,tokenMatcher,dynamicTokensEnabled){var areAllOneTokenLookahead=utils_12.every(alt,function(currPath){return currPath.length===1});var numOfPaths=alt.length;if(areAllOneTokenLookahead&&!dynamicTokensEnabled){var singleTokensTypes=utils_12.flatten(alt);if(singleTokensTypes.length===1&&utils_12.isEmpty(singleTokensTypes[0].categoryMatches)){var expectedTokenType=singleTokensTypes[0];var expectedTokenUniqueKey_1=expectedTokenType.tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===expectedTokenUniqueKey_1}}else{var choiceToAlt_2=utils_12.reduce(singleTokensTypes,function(result,currTokType,idx){result[currTokType.tokenTypeIdx]=true;utils_12.forEach(currTokType.categoryMatches,function(currExtendingType){result[currExtendingType]=true});return result},[]);return function(){var nextToken=this.LA(1);return choiceToAlt_2[nextToken.tokenTypeIdx]===true}}}else{return function(){nextPath:for(var j=0;j<numOfPaths;j++){var currPath=alt[j];var currPathLength=currPath.length;for(var i=0;i<currPathLength;i++){var nextToken=this.LA(i+1);if(tokenMatcher(nextToken,currPath[i])===false){continue nextPath}}return true}return false}}}exports3.buildSingleAlternativeLookaheadFunction=buildSingleAlternativeLookaheadFunction;var RestDefinitionFinderWalker=(function(_super){__extends2(RestDefinitionFinderWalker2,_super);function RestDefinitionFinderWalker2(topProd,targetOccurrence,targetProdType){var _this=_super.call(this)||this;_this.topProd=topProd;_this.targetOccurrence=targetOccurrence;_this.targetProdType=targetProdType;return _this}RestDefinitionFinderWalker2.prototype.startWalking=function(){this.walk(this.topProd);return this.restDef};RestDefinitionFinderWalker2.prototype.checkIsTarget=function(node,expectedProdType,currRest,prevRest){if(node.idx===this.targetOccurrence&&this.targetProdType===expectedProdType){this.restDef=currRest.concat(prevRest);return true}return false};RestDefinitionFinderWalker2.prototype.walkOption=function(optionProd,currRest,prevRest){if(!this.checkIsTarget(optionProd,PROD_TYPE.OPTION,currRest,prevRest)){_super.prototype.walkOption.call(this,optionProd,currRest,prevRest)}};RestDefinitionFinderWalker2.prototype.walkAtLeastOne=function(atLeastOneProd,currRest,prevRest){if(!this.checkIsTarget(atLeastOneProd,PROD_TYPE.REPETITION_MANDATORY,currRest,prevRest)){_super.prototype.walkOption.call(this,atLeastOneProd,currRest,prevRest)}};RestDefinitionFinderWalker2.prototype.walkAtLeastOneSep=function(atLeastOneSepProd,currRest,prevRest){if(!this.checkIsTarget(atLeastOneSepProd,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,currRest,prevRest)){_super.prototype.walkOption.call(this,atLeastOneSepProd,currRest,prevRest)}};RestDefinitionFinderWalker2.prototype.walkMany=function(manyProd,currRest,prevRest){if(!this.checkIsTarget(manyProd,PROD_TYPE.REPETITION,currRest,prevRest)){_super.prototype.walkOption.call(this,manyProd,currRest,prevRest)}};RestDefinitionFinderWalker2.prototype.walkManySep=function(manySepProd,currRest,prevRest){if(!this.checkIsTarget(manySepProd,PROD_TYPE.REPETITION_WITH_SEPARATOR,currRest,prevRest)){_super.prototype.walkOption.call(this,manySepProd,currRest,prevRest)}};return RestDefinitionFinderWalker2})(rest_12.RestWalker);var InsideDefinitionFinderVisitor=(function(_super){__extends2(InsideDefinitionFinderVisitor2,_super);function InsideDefinitionFinderVisitor2(targetOccurrence,targetProdType,targetRef){var _this=_super.call(this)||this;_this.targetOccurrence=targetOccurrence;_this.targetProdType=targetProdType;_this.targetRef=targetRef;_this.result=[];return _this}InsideDefinitionFinderVisitor2.prototype.checkIsTarget=function(node,expectedProdName){if(node.idx===this.targetOccurrence&&this.targetProdType===expectedProdName&&(this.targetRef===void 0||node===this.targetRef)){this.result=node.definition}};InsideDefinitionFinderVisitor2.prototype.visitOption=function(node){this.checkIsTarget(node,PROD_TYPE.OPTION)};InsideDefinitionFinderVisitor2.prototype.visitRepetition=function(node){this.checkIsTarget(node,PROD_TYPE.REPETITION)};InsideDefinitionFinderVisitor2.prototype.visitRepetitionMandatory=function(node){this.checkIsTarget(node,PROD_TYPE.REPETITION_MANDATORY)};InsideDefinitionFinderVisitor2.prototype.visitRepetitionMandatoryWithSeparator=function(node){this.checkIsTarget(node,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR)};InsideDefinitionFinderVisitor2.prototype.visitRepetitionWithSeparator=function(node){this.checkIsTarget(node,PROD_TYPE.REPETITION_WITH_SEPARATOR)};InsideDefinitionFinderVisitor2.prototype.visitAlternation=function(node){this.checkIsTarget(node,PROD_TYPE.ALTERNATION)};return InsideDefinitionFinderVisitor2})(gast_visitor_public_12.GAstVisitor);function initializeArrayOfArrays(size){var result=new Array(size);for(var i=0;i<size;i++){result[i]=[]}return result}function pathToHashKeys(path){var keys2=[""];for(var i=0;i<path.length;i++){var tokType=path[i];var longerKeys=[];for(var j=0;j<keys2.length;j++){var currShorterKey=keys2[j];longerKeys.push(currShorterKey+"_"+tokType.tokenTypeIdx);for(var t=0;t<tokType.categoryMatches.length;t++){var categoriesKeySuffix="_"+tokType.categoryMatches[t];longerKeys.push(currShorterKey+categoriesKeySuffix)}}keys2=longerKeys}return keys2}function isUniquePrefixHash(altKnownPathsKeys,searchPathKeys,idx){for(var currAltIdx=0;currAltIdx<altKnownPathsKeys.length;currAltIdx++){if(currAltIdx===idx){continue}var otherAltKnownPathsKeys=altKnownPathsKeys[currAltIdx];for(var searchIdx=0;searchIdx<searchPathKeys.length;searchIdx++){var searchKey=searchPathKeys[searchIdx];if(otherAltKnownPathsKeys[searchKey]===true){return false}}}return true}function lookAheadSequenceFromAlternatives(altsDefs,k){var partialAlts=utils_12.map(altsDefs,function(currAlt){return interpreter_12.possiblePathsFrom([currAlt],1)});var finalResult=initializeArrayOfArrays(partialAlts.length);var altsHashes=utils_12.map(partialAlts,function(currAltPaths){var dict={};utils_12.forEach(currAltPaths,function(item){var keys2=pathToHashKeys(item.partialPath);utils_12.forEach(keys2,function(currKey){dict[currKey]=true})});return dict});var newData=partialAlts;for(var pathLength=1;pathLength<=k;pathLength++){var currDataset=newData;newData=initializeArrayOfArrays(currDataset.length);var _loop_1=function(altIdx2){var currAltPathsAndSuffixes=currDataset[altIdx2];for(var currPathIdx=0;currPathIdx<currAltPathsAndSuffixes.length;currPathIdx++){var currPathPrefix=currAltPathsAndSuffixes[currPathIdx].partialPath;var suffixDef=currAltPathsAndSuffixes[currPathIdx].suffixDef;var prefixKeys=pathToHashKeys(currPathPrefix);var isUnique=isUniquePrefixHash(altsHashes,prefixKeys,altIdx2);if(isUnique||utils_12.isEmpty(suffixDef)||currPathPrefix.length===k){var currAltResult=finalResult[altIdx2];if(containsPath(currAltResult,currPathPrefix)===false){currAltResult.push(currPathPrefix);for(var j=0;j<prefixKeys.length;j++){var currKey=prefixKeys[j];altsHashes[altIdx2][currKey]=true}}}else{var newPartialPathsAndSuffixes=interpreter_12.possiblePathsFrom(suffixDef,pathLength+1,currPathPrefix);newData[altIdx2]=newData[altIdx2].concat(newPartialPathsAndSuffixes);utils_12.forEach(newPartialPathsAndSuffixes,function(item){var prefixKeys2=pathToHashKeys(item.partialPath);utils_12.forEach(prefixKeys2,function(key){altsHashes[altIdx2][key]=true})})}}};for(var altIdx=0;altIdx<currDataset.length;altIdx++){_loop_1(altIdx)}}return finalResult}exports3.lookAheadSequenceFromAlternatives=lookAheadSequenceFromAlternatives;function getLookaheadPathsForOr(occurrence,ruleGrammar,k,orProd){var visitor=new InsideDefinitionFinderVisitor(occurrence,PROD_TYPE.ALTERNATION,orProd);ruleGrammar.accept(visitor);return lookAheadSequenceFromAlternatives(visitor.result,k)}exports3.getLookaheadPathsForOr=getLookaheadPathsForOr;function getLookaheadPathsForOptionalProd(occurrence,ruleGrammar,prodType,k){var insideDefVisitor=new InsideDefinitionFinderVisitor(occurrence,prodType);ruleGrammar.accept(insideDefVisitor);var insideDef=insideDefVisitor.result;var afterDefWalker=new RestDefinitionFinderWalker(ruleGrammar,occurrence,prodType);var afterDef=afterDefWalker.startWalking();var insideFlat=new gast_public_12.Alternative({definition:insideDef});var afterFlat=new gast_public_12.Alternative({definition:afterDef});return lookAheadSequenceFromAlternatives([insideFlat,afterFlat],k)}exports3.getLookaheadPathsForOptionalProd=getLookaheadPathsForOptionalProd;function containsPath(alternative,searchPath){compareOtherPath:for(var i=0;i<alternative.length;i++){var otherPath=alternative[i];if(otherPath.length!==searchPath.length){continue}for(var j=0;j<otherPath.length;j++){var searchTok=searchPath[j];var otherTok=otherPath[j];var matchingTokens=searchTok===otherTok||otherTok.categoryMatchesMap[searchTok.tokenTypeIdx]!==void 0;if(matchingTokens===false){continue compareOtherPath}}return true}return false}exports3.containsPath=containsPath;function isStrictPrefixOfPath(prefix,other){return prefix.length<other.length&&utils_12.every(prefix,function(tokType,idx){var otherTokType=other[idx];return tokType===otherTokType||otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]})}exports3.isStrictPrefixOfPath=isStrictPrefixOfPath;function areTokenCategoriesNotUsed(lookAheadPaths){return utils_12.every(lookAheadPaths,function(singleAltPaths){return utils_12.every(singleAltPaths,function(singlePath){return utils_12.every(singlePath,function(token){return utils_12.isEmpty(token.categoryMatches)})})})}exports3.areTokenCategoriesNotUsed=areTokenCategoriesNotUsed})(lookahead);var __extends$1=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(checks,"__esModule",{value:true});checks.checkPrefixAlternativesAmbiguities=checks.validateSomeNonEmptyLookaheadPath=checks.validateTooManyAlts=checks.RepetionCollector=checks.validateAmbiguousAlternationAlternatives=checks.validateEmptyOrAlternative=checks.getFirstNoneTerminal=checks.validateNoLeftRecursion=checks.validateRuleIsOverridden=checks.validateRuleDoesNotAlreadyExist=checks.OccurrenceValidationCollector=checks.identifyProductionForDuplicates=checks.validateGrammar=void 0;var utils=api;var utils_1$b=api;var parser_1$8=parser;var gast_1$1=gast;var lookahead_1$3=lookahead;var interpreter_1$2=interpreter;var gast_public_1$2=gast_public;var gast_visitor_public_1=gast_visitor_public;function validateGrammar$1(topLevels,globalMaxLookahead,tokenTypes,errMsgProvider,grammarName){var duplicateErrors=utils.map(topLevels,function(currTopLevel){return validateDuplicateProductions(currTopLevel,errMsgProvider)});var leftRecursionErrors=utils.map(topLevels,function(currTopRule){return validateNoLeftRecursion(currTopRule,currTopRule,errMsgProvider)});var emptyAltErrors=[];var ambiguousAltsErrors=[];var emptyRepetitionErrors=[];if(utils_1$b.every(leftRecursionErrors,utils_1$b.isEmpty)){emptyAltErrors=utils_1$b.map(topLevels,function(currTopRule){return validateEmptyOrAlternative(currTopRule,errMsgProvider)});ambiguousAltsErrors=utils_1$b.map(topLevels,function(currTopRule){return validateAmbiguousAlternationAlternatives(currTopRule,globalMaxLookahead,errMsgProvider)});emptyRepetitionErrors=validateSomeNonEmptyLookaheadPath(topLevels,globalMaxLookahead,errMsgProvider)}var termsNamespaceConflictErrors=checkTerminalAndNoneTerminalsNameSpace(topLevels,tokenTypes,errMsgProvider);var tooManyAltsErrors=utils_1$b.map(topLevels,function(curRule){return validateTooManyAlts(curRule,errMsgProvider)});var duplicateRulesError=utils_1$b.map(topLevels,function(curRule){return validateRuleDoesNotAlreadyExist(curRule,topLevels,grammarName,errMsgProvider)});return utils.flatten(duplicateErrors.concat(emptyRepetitionErrors,leftRecursionErrors,emptyAltErrors,ambiguousAltsErrors,termsNamespaceConflictErrors,tooManyAltsErrors,duplicateRulesError))}checks.validateGrammar=validateGrammar$1;function validateDuplicateProductions(topLevelRule,errMsgProvider){var collectorVisitor2=new OccurrenceValidationCollector;topLevelRule.accept(collectorVisitor2);var allRuleProductions=collectorVisitor2.allProductions;var productionGroups=utils.groupBy(allRuleProductions,identifyProductionForDuplicates);var duplicates=utils.pick(productionGroups,function(currGroup){return currGroup.length>1});var errors=utils.map(utils.values(duplicates),function(currDuplicates){var firstProd=utils.first(currDuplicates);var msg=errMsgProvider.buildDuplicateFoundError(topLevelRule,currDuplicates);var dslName=gast_1$1.getProductionDslName(firstProd);var defError={message:msg,type:parser_1$8.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:topLevelRule.name,dslName,occurrence:firstProd.idx};var param=getExtraProductionArgument(firstProd);if(param){defError.parameter=param}return defError});return errors}function identifyProductionForDuplicates(prod){return gast_1$1.getProductionDslName(prod)+"_#_"+prod.idx+"_#_"+getExtraProductionArgument(prod)}checks.identifyProductionForDuplicates=identifyProductionForDuplicates;function getExtraProductionArgument(prod){if(prod instanceof gast_public_1$2.Terminal){return prod.terminalType.name}else if(prod instanceof gast_public_1$2.NonTerminal){return prod.nonTerminalName}else{return""}}var OccurrenceValidationCollector=(function(_super){__extends$1(OccurrenceValidationCollector2,_super);function OccurrenceValidationCollector2(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.allProductions=[];return _this}OccurrenceValidationCollector2.prototype.visitNonTerminal=function(subrule){this.allProductions.push(subrule)};OccurrenceValidationCollector2.prototype.visitOption=function(option){this.allProductions.push(option)};OccurrenceValidationCollector2.prototype.visitRepetitionWithSeparator=function(manySep){this.allProductions.push(manySep)};OccurrenceValidationCollector2.prototype.visitRepetitionMandatory=function(atLeastOne){this.allProductions.push(atLeastOne)};OccurrenceValidationCollector2.prototype.visitRepetitionMandatoryWithSeparator=function(atLeastOneSep){this.allProductions.push(atLeastOneSep)};OccurrenceValidationCollector2.prototype.visitRepetition=function(many){this.allProductions.push(many)};OccurrenceValidationCollector2.prototype.visitAlternation=function(or){this.allProductions.push(or)};OccurrenceValidationCollector2.prototype.visitTerminal=function(terminal){this.allProductions.push(terminal)};return OccurrenceValidationCollector2})(gast_visitor_public_1.GAstVisitor);checks.OccurrenceValidationCollector=OccurrenceValidationCollector;function validateRuleDoesNotAlreadyExist(rule,allRules,className,errMsgProvider){var errors=[];var occurrences=utils_1$b.reduce(allRules,function(result,curRule){if(curRule.name===rule.name){return result+1}return result},0);if(occurrences>1){var errMsg=errMsgProvider.buildDuplicateRuleNameError({topLevelRule:rule,grammarName:className});errors.push({message:errMsg,type:parser_1$8.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:rule.name})}return errors}checks.validateRuleDoesNotAlreadyExist=validateRuleDoesNotAlreadyExist;function validateRuleIsOverridden(ruleName,definedRulesNames,className){var errors=[];var errMsg;if(!utils.contains(definedRulesNames,ruleName)){errMsg="Invalid rule override, rule: ->"+ruleName+"<- cannot be overridden in the grammar: ->"+className+"<-as it is not defined in any of the super grammars ";errors.push({message:errMsg,type:parser_1$8.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName})}return errors}checks.validateRuleIsOverridden=validateRuleIsOverridden;function validateNoLeftRecursion(topRule,currRule,errMsgProvider,path){if(path===void 0){path=[]}var errors=[];var nextNonTerminals=getFirstNoneTerminal(currRule.definition);if(utils.isEmpty(nextNonTerminals)){return[]}else{var ruleName=topRule.name;var foundLeftRecursion=utils.contains(nextNonTerminals,topRule);if(foundLeftRecursion){errors.push({message:errMsgProvider.buildLeftRecursionError({topLevelRule:topRule,leftRecursionPath:path}),type:parser_1$8.ParserDefinitionErrorType.LEFT_RECURSION,ruleName})}var validNextSteps=utils.difference(nextNonTerminals,path.concat([topRule]));var errorsFromNextSteps=utils.map(validNextSteps,function(currRefRule){var newPath=utils.cloneArr(path);newPath.push(currRefRule);return validateNoLeftRecursion(topRule,currRefRule,errMsgProvider,newPath)});return errors.concat(utils.flatten(errorsFromNextSteps))}}checks.validateNoLeftRecursion=validateNoLeftRecursion;function getFirstNoneTerminal(definition){var result=[];if(utils.isEmpty(definition)){return result}var firstProd=utils.first(definition);if(firstProd instanceof gast_public_1$2.NonTerminal){result.push(firstProd.referencedRule)}else if(firstProd instanceof gast_public_1$2.Alternative||firstProd instanceof gast_public_1$2.Option||firstProd instanceof gast_public_1$2.RepetitionMandatory||firstProd instanceof gast_public_1$2.RepetitionMandatoryWithSeparator||firstProd instanceof gast_public_1$2.RepetitionWithSeparator||firstProd instanceof gast_public_1$2.Repetition){result=result.concat(getFirstNoneTerminal(firstProd.definition))}else if(firstProd instanceof gast_public_1$2.Alternation){result=utils.flatten(utils.map(firstProd.definition,function(currSubDef){return getFirstNoneTerminal(currSubDef.definition)}))}else if(firstProd instanceof gast_public_1$2.Terminal);else{throw Error("non exhaustive match")}var isFirstOptional=gast_1$1.isOptionalProd(firstProd);var hasMore=definition.length>1;if(isFirstOptional&&hasMore){var rest2=utils.drop(definition);return result.concat(getFirstNoneTerminal(rest2))}else{return result}}checks.getFirstNoneTerminal=getFirstNoneTerminal;var OrCollector=(function(_super){__extends$1(OrCollector2,_super);function OrCollector2(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.alternations=[];return _this}OrCollector2.prototype.visitAlternation=function(node){this.alternations.push(node)};return OrCollector2})(gast_visitor_public_1.GAstVisitor);function validateEmptyOrAlternative(topLevelRule,errMsgProvider){var orCollector=new OrCollector;topLevelRule.accept(orCollector);var ors=orCollector.alternations;var errors=utils.reduce(ors,function(errors2,currOr){var exceptLast=utils.dropRight(currOr.definition);var currErrors=utils.map(exceptLast,function(currAlternative,currAltIdx){var possibleFirstInAlt=interpreter_1$2.nextPossibleTokensAfter([currAlternative],[],null,1);if(utils.isEmpty(possibleFirstInAlt)){return{message:errMsgProvider.buildEmptyAlternationError({topLevelRule,alternation:currOr,emptyChoiceIdx:currAltIdx}),type:parser_1$8.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:topLevelRule.name,occurrence:currOr.idx,alternative:currAltIdx+1}}else{return null}});return errors2.concat(utils.compact(currErrors))},[]);return errors}checks.validateEmptyOrAlternative=validateEmptyOrAlternative;function validateAmbiguousAlternationAlternatives(topLevelRule,globalMaxLookahead,errMsgProvider){var orCollector=new OrCollector;topLevelRule.accept(orCollector);var ors=orCollector.alternations;ors=utils_1$b.reject(ors,function(currOr){return currOr.ignoreAmbiguities===true});var errors=utils.reduce(ors,function(result,currOr){var currOccurrence=currOr.idx;var actualMaxLookahead=currOr.maxLookahead||globalMaxLookahead;var alternatives=lookahead_1$3.getLookaheadPathsForOr(currOccurrence,topLevelRule,actualMaxLookahead,currOr);var altsAmbiguityErrors=checkAlternativesAmbiguities(alternatives,currOr,topLevelRule,errMsgProvider);var altsPrefixAmbiguityErrors=checkPrefixAlternativesAmbiguities(alternatives,currOr,topLevelRule,errMsgProvider);return result.concat(altsAmbiguityErrors,altsPrefixAmbiguityErrors)},[]);return errors}checks.validateAmbiguousAlternationAlternatives=validateAmbiguousAlternationAlternatives;var RepetionCollector=(function(_super){__extends$1(RepetionCollector2,_super);function RepetionCollector2(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.allProductions=[];return _this}RepetionCollector2.prototype.visitRepetitionWithSeparator=function(manySep){this.allProductions.push(manySep)};RepetionCollector2.prototype.visitRepetitionMandatory=function(atLeastOne){this.allProductions.push(atLeastOne)};RepetionCollector2.prototype.visitRepetitionMandatoryWithSeparator=function(atLeastOneSep){this.allProductions.push(atLeastOneSep)};RepetionCollector2.prototype.visitRepetition=function(many){this.allProductions.push(many)};return RepetionCollector2})(gast_visitor_public_1.GAstVisitor);checks.RepetionCollector=RepetionCollector;function validateTooManyAlts(topLevelRule,errMsgProvider){var orCollector=new OrCollector;topLevelRule.accept(orCollector);var ors=orCollector.alternations;var errors=utils.reduce(ors,function(errors2,currOr){if(currOr.definition.length>255){errors2.push({message:errMsgProvider.buildTooManyAlternativesError({topLevelRule,alternation:currOr}),type:parser_1$8.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:topLevelRule.name,occurrence:currOr.idx})}return errors2},[]);return errors}checks.validateTooManyAlts=validateTooManyAlts;function validateSomeNonEmptyLookaheadPath(topLevelRules,maxLookahead,errMsgProvider){var errors=[];utils_1$b.forEach(topLevelRules,function(currTopRule){var collectorVisitor2=new RepetionCollector;currTopRule.accept(collectorVisitor2);var allRuleProductions=collectorVisitor2.allProductions;utils_1$b.forEach(allRuleProductions,function(currProd){var prodType=lookahead_1$3.getProdType(currProd);var actualMaxLookahead=currProd.maxLookahead||maxLookahead;var currOccurrence=currProd.idx;var paths=lookahead_1$3.getLookaheadPathsForOptionalProd(currOccurrence,currTopRule,prodType,actualMaxLookahead);var pathsInsideProduction=paths[0];if(utils_1$b.isEmpty(utils_1$b.flatten(pathsInsideProduction))){var errMsg=errMsgProvider.buildEmptyRepetitionError({topLevelRule:currTopRule,repetition:currProd});errors.push({message:errMsg,type:parser_1$8.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:currTopRule.name})}})});return errors}checks.validateSomeNonEmptyLookaheadPath=validateSomeNonEmptyLookaheadPath;function checkAlternativesAmbiguities(alternatives,alternation,rule,errMsgProvider){var foundAmbiguousPaths=[];var identicalAmbiguities=utils_1$b.reduce(alternatives,function(result,currAlt,currAltIdx){if(alternation.definition[currAltIdx].ignoreAmbiguities===true){return result}utils_1$b.forEach(currAlt,function(currPath){var altsCurrPathAppearsIn=[currAltIdx];utils_1$b.forEach(alternatives,function(currOtherAlt,currOtherAltIdx){if(currAltIdx!==currOtherAltIdx&&lookahead_1$3.containsPath(currOtherAlt,currPath)&&alternation.definition[currOtherAltIdx].ignoreAmbiguities!==true){altsCurrPathAppearsIn.push(currOtherAltIdx)}});if(altsCurrPathAppearsIn.length>1&&!lookahead_1$3.containsPath(foundAmbiguousPaths,currPath)){foundAmbiguousPaths.push(currPath);result.push({alts:altsCurrPathAppearsIn,path:currPath})}});return result},[]);var currErrors=utils.map(identicalAmbiguities,function(currAmbDescriptor){var ambgIndices=utils_1$b.map(currAmbDescriptor.alts,function(currAltIdx){return currAltIdx+1});var currMessage=errMsgProvider.buildAlternationAmbiguityError({topLevelRule:rule,alternation,ambiguityIndices:ambgIndices,prefixPath:currAmbDescriptor.path});return{message:currMessage,type:parser_1$8.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:rule.name,occurrence:alternation.idx,alternatives:[currAmbDescriptor.alts]}});return currErrors}function checkPrefixAlternativesAmbiguities(alternatives,alternation,rule,errMsgProvider){var errors=[];var pathsAndIndices=utils_1$b.reduce(alternatives,function(result,currAlt,idx){var currPathsAndIdx=utils_1$b.map(currAlt,function(currPath){return{idx,path:currPath}});return result.concat(currPathsAndIdx)},[]);utils_1$b.forEach(pathsAndIndices,function(currPathAndIdx){var alternativeGast=alternation.definition[currPathAndIdx.idx];if(alternativeGast.ignoreAmbiguities===true){return}var targetIdx=currPathAndIdx.idx;var targetPath=currPathAndIdx.path;var prefixAmbiguitiesPathsAndIndices=utils_1$b.findAll(pathsAndIndices,function(searchPathAndIdx){return alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities!==true&&searchPathAndIdx.idx<targetIdx&&lookahead_1$3.isStrictPrefixOfPath(searchPathAndIdx.path,targetPath)});var currPathPrefixErrors=utils_1$b.map(prefixAmbiguitiesPathsAndIndices,function(currAmbPathAndIdx){var ambgIndices=[currAmbPathAndIdx.idx+1,targetIdx+1];var occurrence=alternation.idx===0?"":alternation.idx;var message=errMsgProvider.buildAlternationPrefixAmbiguityError({topLevelRule:rule,alternation,ambiguityIndices:ambgIndices,prefixPath:currAmbPathAndIdx.path});return{message,type:parser_1$8.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,ruleName:rule.name,occurrence,alternatives:ambgIndices}});errors=errors.concat(currPathPrefixErrors)});return errors}checks.checkPrefixAlternativesAmbiguities=checkPrefixAlternativesAmbiguities;function checkTerminalAndNoneTerminalsNameSpace(topLevels,tokenTypes,errMsgProvider){var errors=[];var tokenNames=utils_1$b.map(tokenTypes,function(currToken){return currToken.name});utils_1$b.forEach(topLevels,function(currRule){var currRuleName=currRule.name;if(utils_1$b.contains(tokenNames,currRuleName)){var errMsg=errMsgProvider.buildNamespaceConflictError(currRule);errors.push({message:errMsg,type:parser_1$8.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:currRuleName})}});return errors}Object.defineProperty(gast_resolver_public,"__esModule",{value:true});gast_resolver_public.validateGrammar=gast_resolver_public.resolveGrammar=void 0;var utils_1$a=api;var resolver_1=resolver;var checks_1$1=checks;var errors_public_1$1=errors_public;function resolveGrammar(options){options=utils_1$a.defaults(options,{errMsgProvider:errors_public_1$1.defaultGrammarResolverErrorProvider});var topRulesTable={};utils_1$a.forEach(options.rules,function(rule){topRulesTable[rule.name]=rule});return resolver_1.resolveGrammar(topRulesTable,options.errMsgProvider)}gast_resolver_public.resolveGrammar=resolveGrammar;function validateGrammar(options){options=utils_1$a.defaults(options,{errMsgProvider:errors_public_1$1.defaultGrammarValidatorErrorProvider});return checks_1$1.validateGrammar(options.rules,options.maxLookahead,options.tokenTypes,options.errMsgProvider,options.grammarName)}gast_resolver_public.validateGrammar=validateGrammar;var recoverable={};var exceptions_public={};var __extends=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(exceptions_public,"__esModule",{value:true});exceptions_public.EarlyExitException=exceptions_public.NotAllInputParsedException=exceptions_public.NoViableAltException=exceptions_public.MismatchedTokenException=exceptions_public.isRecognitionException=void 0;var utils_1$9=api;var MISMATCHED_TOKEN_EXCEPTION="MismatchedTokenException";var NO_VIABLE_ALT_EXCEPTION="NoViableAltException";var EARLY_EXIT_EXCEPTION="EarlyExitException";var NOT_ALL_INPUT_PARSED_EXCEPTION="NotAllInputParsedException";var RECOGNITION_EXCEPTION_NAMES=[MISMATCHED_TOKEN_EXCEPTION,NO_VIABLE_ALT_EXCEPTION,EARLY_EXIT_EXCEPTION,NOT_ALL_INPUT_PARSED_EXCEPTION];Object.freeze(RECOGNITION_EXCEPTION_NAMES);function isRecognitionException(error){return utils_1$9.contains(RECOGNITION_EXCEPTION_NAMES,error.name)}exceptions_public.isRecognitionException=isRecognitionException;var RecognitionException=(function(_super){__extends(RecognitionException2,_super);function RecognitionException2(message,token){var _newTarget=this.constructor;var _this=_super.call(this,message)||this;_this.token=token;_this.resyncedTokens=[];Object.setPrototypeOf(_this,_newTarget.prototype);if(Error.captureStackTrace){Error.captureStackTrace(_this,_this.constructor)}return _this}return RecognitionException2})(Error);var MismatchedTokenException=(function(_super){__extends(MismatchedTokenException2,_super);function MismatchedTokenException2(message,token,previousToken){var _this=_super.call(this,message,token)||this;_this.previousToken=previousToken;_this.name=MISMATCHED_TOKEN_EXCEPTION;return _this}return MismatchedTokenException2})(RecognitionException);exceptions_public.MismatchedTokenException=MismatchedTokenException;var NoViableAltException=(function(_super){__extends(NoViableAltException2,_super);function NoViableAltException2(message,token,previousToken){var _this=_super.call(this,message,token)||this;_this.previousToken=previousToken;_this.name=NO_VIABLE_ALT_EXCEPTION;return _this}return NoViableAltException2})(RecognitionException);exceptions_public.NoViableAltException=NoViableAltException;var NotAllInputParsedException=(function(_super){__extends(NotAllInputParsedException2,_super);function NotAllInputParsedException2(message,token){var _this=_super.call(this,message,token)||this;_this.name=NOT_ALL_INPUT_PARSED_EXCEPTION;return _this}return NotAllInputParsedException2})(RecognitionException);exceptions_public.NotAllInputParsedException=NotAllInputParsedException;var EarlyExitException=(function(_super){__extends(EarlyExitException2,_super);function EarlyExitException2(message,token,previousToken){var _this=_super.call(this,message,token)||this;_this.previousToken=previousToken;_this.name=EARLY_EXIT_EXCEPTION;return _this}return EarlyExitException2})(RecognitionException);exceptions_public.EarlyExitException=EarlyExitException;(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.attemptInRepetitionRecovery=exports3.Recoverable=exports3.InRuleRecoveryException=exports3.IN_RULE_RECOVERY_EXCEPTION=exports3.EOF_FOLLOW_KEY=void 0;var tokens_public_12=tokens_public;var utils_12=api;var exceptions_public_12=exceptions_public;var constants_12=constants;var parser_12=parser;exports3.EOF_FOLLOW_KEY={};exports3.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function InRuleRecoveryException(message){this.name=exports3.IN_RULE_RECOVERY_EXCEPTION;this.message=message}exports3.InRuleRecoveryException=InRuleRecoveryException;InRuleRecoveryException.prototype=Error.prototype;var Recoverable=(function(){function Recoverable2(){}Recoverable2.prototype.initRecoverable=function(config){this.firstAfterRepMap={};this.resyncFollows={};this.recoveryEnabled=utils_12.has(config,"recoveryEnabled")?config.recoveryEnabled:parser_12.DEFAULT_PARSER_CONFIG.recoveryEnabled;if(this.recoveryEnabled){this.attemptInRepetitionRecovery=attemptInRepetitionRecovery}};Recoverable2.prototype.getTokenToInsert=function(tokType){var tokToInsert=tokens_public_12.createTokenInstance(tokType,"",NaN,NaN,NaN,NaN,NaN,NaN);tokToInsert.isInsertedInRecovery=true;return tokToInsert};Recoverable2.prototype.canTokenTypeBeInsertedInRecovery=function(tokType){return true};Recoverable2.prototype.tryInRepetitionRecovery=function(grammarRule,grammarRuleArgs,lookAheadFunc,expectedTokType){var _this=this;var reSyncTokType=this.findReSyncTokenType();var savedLexerState=this.exportLexerState();var resyncedTokens=[];var passedResyncPoint=false;var nextTokenWithoutResync=this.LA(1);var currToken=this.LA(1);var generateErrorMessage=function(){var previousToken=_this.LA(0);var msg=_this.errorMessageProvider.buildMismatchTokenMessage({expected:expectedTokType,actual:nextTokenWithoutResync,previous:previousToken,ruleName:_this.getCurrRuleFullName()});var error=new exceptions_public_12.MismatchedTokenException(msg,nextTokenWithoutResync,_this.LA(0));error.resyncedTokens=utils_12.dropRight(resyncedTokens);_this.SAVE_ERROR(error)};while(!passedResyncPoint){if(this.tokenMatcher(currToken,expectedTokType)){generateErrorMessage();return}else if(lookAheadFunc.call(this)){generateErrorMessage();grammarRule.apply(this,grammarRuleArgs);return}else if(this.tokenMatcher(currToken,reSyncTokType)){passedResyncPoint=true}else{currToken=this.SKIP_TOKEN();this.addToResyncTokens(currToken,resyncedTokens)}}this.importLexerState(savedLexerState)};Recoverable2.prototype.shouldInRepetitionRecoveryBeTried=function(expectTokAfterLastMatch,nextTokIdx,notStuck){if(notStuck===false){return false}if(expectTokAfterLastMatch===void 0||nextTokIdx===void 0){return false}if(this.tokenMatcher(this.LA(1),expectTokAfterLastMatch)){return false}if(this.isBackTracking()){return false}if(this.canPerformInRuleRecovery(expectTokAfterLastMatch,this.getFollowsForInRuleRecovery(expectTokAfterLastMatch,nextTokIdx))){return false}return true};Recoverable2.prototype.getFollowsForInRuleRecovery=function(tokType,tokIdxInRule){var grammarPath=this.getCurrentGrammarPath(tokType,tokIdxInRule);var follows=this.getNextPossibleTokenTypes(grammarPath);return follows};Recoverable2.prototype.tryInRuleRecovery=function(expectedTokType,follows){if(this.canRecoverWithSingleTokenInsertion(expectedTokType,follows)){var tokToInsert=this.getTokenToInsert(expectedTokType);return tokToInsert}if(this.canRecoverWithSingleTokenDeletion(expectedTokType)){var nextTok=this.SKIP_TOKEN();this.consumeToken();return nextTok}throw new InRuleRecoveryException("sad sad panda")};Recoverable2.prototype.canPerformInRuleRecovery=function(expectedToken,follows){return this.canRecoverWithSingleTokenInsertion(expectedToken,follows)||this.canRecoverWithSingleTokenDeletion(expectedToken)};Recoverable2.prototype.canRecoverWithSingleTokenInsertion=function(expectedTokType,follows){var _this=this;if(!this.canTokenTypeBeInsertedInRecovery(expectedTokType)){return false}if(utils_12.isEmpty(follows)){return false}var mismatchedTok=this.LA(1);var isMisMatchedTokInFollows=utils_12.find(follows,function(possibleFollowsTokType){return _this.tokenMatcher(mismatchedTok,possibleFollowsTokType)})!==void 0;return isMisMatchedTokInFollows};Recoverable2.prototype.canRecoverWithSingleTokenDeletion=function(expectedTokType){var isNextTokenWhatIsExpected=this.tokenMatcher(this.LA(2),expectedTokType);return isNextTokenWhatIsExpected};Recoverable2.prototype.isInCurrentRuleReSyncSet=function(tokenTypeIdx){var followKey=this.getCurrFollowKey();var currentRuleReSyncSet=this.getFollowSetFromFollowKey(followKey);return utils_12.contains(currentRuleReSyncSet,tokenTypeIdx)};Recoverable2.prototype.findReSyncTokenType=function(){var allPossibleReSyncTokTypes=this.flattenFollowSet();var nextToken=this.LA(1);var k=2;while(true){var nextTokenType=nextToken.tokenType;if(utils_12.contains(allPossibleReSyncTokTypes,nextTokenType)){return nextTokenType}nextToken=this.LA(k);k++}};Recoverable2.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1){return exports3.EOF_FOLLOW_KEY}var currRuleShortName=this.getLastExplicitRuleShortName();var currRuleIdx=this.getLastExplicitRuleOccurrenceIndex();var prevRuleShortName=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(currRuleShortName),idxInCallingRule:currRuleIdx,inRule:this.shortRuleNameToFullName(prevRuleShortName)}};Recoverable2.prototype.buildFullFollowKeyStack=function(){var _this=this;var explicitRuleStack=this.RULE_STACK;var explicitOccurrenceStack=this.RULE_OCCURRENCE_STACK;return utils_12.map(explicitRuleStack,function(ruleName,idx){if(idx===0){return exports3.EOF_FOLLOW_KEY}return{ruleName:_this.shortRuleNameToFullName(ruleName),idxInCallingRule:explicitOccurrenceStack[idx],inRule:_this.shortRuleNameToFullName(explicitRuleStack[idx-1])}})};Recoverable2.prototype.flattenFollowSet=function(){var _this=this;var followStack=utils_12.map(this.buildFullFollowKeyStack(),function(currKey){return _this.getFollowSetFromFollowKey(currKey)});return utils_12.flatten(followStack)};Recoverable2.prototype.getFollowSetFromFollowKey=function(followKey){if(followKey===exports3.EOF_FOLLOW_KEY){return[tokens_public_12.EOF]}var followName=followKey.ruleName+followKey.idxInCallingRule+constants_12.IN+followKey.inRule;return this.resyncFollows[followName]};Recoverable2.prototype.addToResyncTokens=function(token,resyncTokens){if(!this.tokenMatcher(token,tokens_public_12.EOF)){resyncTokens.push(token)}return resyncTokens};Recoverable2.prototype.reSyncTo=function(tokType){var resyncedTokens=[];var nextTok=this.LA(1);while(this.tokenMatcher(nextTok,tokType)===false){nextTok=this.SKIP_TOKEN();this.addToResyncTokens(nextTok,resyncedTokens)}return utils_12.dropRight(resyncedTokens)};Recoverable2.prototype.attemptInRepetitionRecovery=function(prodFunc,args,lookaheadFunc,dslMethodIdx,prodOccurrence,nextToksWalker,notStuck){};Recoverable2.prototype.getCurrentGrammarPath=function(tokType,tokIdxInRule){var pathRuleStack=this.getHumanReadableRuleStack();var pathOccurrenceStack=utils_12.cloneArr(this.RULE_OCCURRENCE_STACK);var grammarPath={ruleStack:pathRuleStack,occurrenceStack:pathOccurrenceStack,lastTok:tokType,lastTokOccurrence:tokIdxInRule};return grammarPath};Recoverable2.prototype.getHumanReadableRuleStack=function(){var _this=this;return utils_12.map(this.RULE_STACK,function(currShortName){return _this.shortRuleNameToFullName(currShortName)})};return Recoverable2})();exports3.Recoverable=Recoverable;function attemptInRepetitionRecovery(prodFunc,args,lookaheadFunc,dslMethodIdx,prodOccurrence,nextToksWalker,notStuck){var key=this.getKeyForAutomaticLookahead(dslMethodIdx,prodOccurrence);var firstAfterRepInfo=this.firstAfterRepMap[key];if(firstAfterRepInfo===void 0){var currRuleName=this.getCurrRuleFullName();var ruleGrammar=this.getGAstProductions()[currRuleName];var walker=new nextToksWalker(ruleGrammar,prodOccurrence);firstAfterRepInfo=walker.startWalking();this.firstAfterRepMap[key]=firstAfterRepInfo}var expectTokAfterLastMatch=firstAfterRepInfo.token;var nextTokIdx=firstAfterRepInfo.occurrence;var isEndOfRule=firstAfterRepInfo.isEndOfRule;if(this.RULE_STACK.length===1&&isEndOfRule&&expectTokAfterLastMatch===void 0){expectTokAfterLastMatch=tokens_public_12.EOF;nextTokIdx=1}if(this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch,nextTokIdx,notStuck)){this.tryInRepetitionRecovery(prodFunc,args,lookaheadFunc,expectTokAfterLastMatch)}}exports3.attemptInRepetitionRecovery=attemptInRepetitionRecovery})(recoverable);var looksahead={};var keys$1={};(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.getKeyForAutomaticLookahead=exports3.AT_LEAST_ONE_SEP_IDX=exports3.MANY_SEP_IDX=exports3.AT_LEAST_ONE_IDX=exports3.MANY_IDX=exports3.OPTION_IDX=exports3.OR_IDX=exports3.BITS_FOR_ALT_IDX=exports3.BITS_FOR_RULE_IDX=exports3.BITS_FOR_OCCURRENCE_IDX=exports3.BITS_FOR_METHOD_TYPE=void 0;exports3.BITS_FOR_METHOD_TYPE=4;exports3.BITS_FOR_OCCURRENCE_IDX=8;exports3.BITS_FOR_RULE_IDX=12;exports3.BITS_FOR_ALT_IDX=8;exports3.OR_IDX=1<<exports3.BITS_FOR_OCCURRENCE_IDX;exports3.OPTION_IDX=2<<exports3.BITS_FOR_OCCURRENCE_IDX;exports3.MANY_IDX=3<<exports3.BITS_FOR_OCCURRENCE_IDX;exports3.AT_LEAST_ONE_IDX=4<<exports3.BITS_FOR_OCCURRENCE_IDX;exports3.MANY_SEP_IDX=5<<exports3.BITS_FOR_OCCURRENCE_IDX;exports3.AT_LEAST_ONE_SEP_IDX=6<<exports3.BITS_FOR_OCCURRENCE_IDX;function getKeyForAutomaticLookahead(ruleIdx,dslMethodIdx,occurrence){return occurrence|dslMethodIdx|ruleIdx}exports3.getKeyForAutomaticLookahead=getKeyForAutomaticLookahead;32-exports3.BITS_FOR_ALT_IDX})(keys$1);Object.defineProperty(looksahead,"__esModule",{value:true});looksahead.LooksAhead=void 0;var lookahead_1$2=lookahead;var utils_1$8=api;var parser_1$7=parser;var keys_1$2=keys$1;var gast_1=gast;var LooksAhead=(function(){function LooksAhead2(){}LooksAhead2.prototype.initLooksAhead=function(config){this.dynamicTokensEnabled=utils_1$8.has(config,"dynamicTokensEnabled")?config.dynamicTokensEnabled:parser_1$7.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;this.maxLookahead=utils_1$8.has(config,"maxLookahead")?config.maxLookahead:parser_1$7.DEFAULT_PARSER_CONFIG.maxLookahead;this.lookAheadFuncsCache=utils_1$8.isES2015MapSupported()?new Map:[];if(utils_1$8.isES2015MapSupported()){this.getLaFuncFromCache=this.getLaFuncFromMap;this.setLaFuncCache=this.setLaFuncCacheUsingMap}else{this.getLaFuncFromCache=this.getLaFuncFromObj;this.setLaFuncCache=this.setLaFuncUsingObj}};LooksAhead2.prototype.preComputeLookaheadFunctions=function(rules){var _this=this;utils_1$8.forEach(rules,function(currRule){_this.TRACE_INIT(currRule.name+" Rule Lookahead",function(){var _a=gast_1.collectMethods(currRule),alternation=_a.alternation,repetition=_a.repetition,option=_a.option,repetitionMandatory=_a.repetitionMandatory,repetitionMandatoryWithSeparator=_a.repetitionMandatoryWithSeparator,repetitionWithSeparator=_a.repetitionWithSeparator;utils_1$8.forEach(alternation,function(currProd){var prodIdx=currProd.idx===0?"":currProd.idx;_this.TRACE_INIT(""+gast_1.getProductionDslName(currProd)+prodIdx,function(){var laFunc=lookahead_1$2.buildLookaheadFuncForOr(currProd.idx,currRule,currProd.maxLookahead||_this.maxLookahead,currProd.hasPredicates,_this.dynamicTokensEnabled,_this.lookAheadBuilderForAlternatives);var key=keys_1$2.getKeyForAutomaticLookahead(_this.fullRuleNameToShort[currRule.name],keys_1$2.OR_IDX,currProd.idx);_this.setLaFuncCache(key,laFunc)})});utils_1$8.forEach(repetition,function(currProd){_this.computeLookaheadFunc(currRule,currProd.idx,keys_1$2.MANY_IDX,lookahead_1$2.PROD_TYPE.REPETITION,currProd.maxLookahead,gast_1.getProductionDslName(currProd))});utils_1$8.forEach(option,function(currProd){_this.computeLookaheadFunc(currRule,currProd.idx,keys_1$2.OPTION_IDX,lookahead_1$2.PROD_TYPE.OPTION,currProd.maxLookahead,gast_1.getProductionDslName(currProd))});utils_1$8.forEach(repetitionMandatory,function(currProd){_this.computeLookaheadFunc(currRule,currProd.idx,keys_1$2.AT_LEAST_ONE_IDX,lookahead_1$2.PROD_TYPE.REPETITION_MANDATORY,currProd.maxLookahead,gast_1.getProductionDslName(currProd))});utils_1$8.forEach(repetitionMandatoryWithSeparator,function(currProd){_this.computeLookaheadFunc(currRule,currProd.idx,keys_1$2.AT_LEAST_ONE_SEP_IDX,lookahead_1$2.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,currProd.maxLookahead,gast_1.getProductionDslName(currProd))});utils_1$8.forEach(repetitionWithSeparator,function(currProd){_this.computeLookaheadFunc(currRule,currProd.idx,keys_1$2.MANY_SEP_IDX,lookahead_1$2.PROD_TYPE.REPETITION_WITH_SEPARATOR,currProd.maxLookahead,gast_1.getProductionDslName(currProd))})})})};LooksAhead2.prototype.computeLookaheadFunc=function(rule,prodOccurrence,prodKey,prodType,prodMaxLookahead,dslMethodName){var _this=this;this.TRACE_INIT(""+dslMethodName+(prodOccurrence===0?"":prodOccurrence),function(){var laFunc=lookahead_1$2.buildLookaheadFuncForOptionalProd(prodOccurrence,rule,prodMaxLookahead||_this.maxLookahead,_this.dynamicTokensEnabled,prodType,_this.lookAheadBuilderForOptional);var key=keys_1$2.getKeyForAutomaticLookahead(_this.fullRuleNameToShort[rule.name],prodKey,prodOccurrence);_this.setLaFuncCache(key,laFunc)})};LooksAhead2.prototype.lookAheadBuilderForOptional=function(alt,tokenMatcher,dynamicTokensEnabled){return lookahead_1$2.buildSingleAlternativeLookaheadFunction(alt,tokenMatcher,dynamicTokensEnabled)};LooksAhead2.prototype.lookAheadBuilderForAlternatives=function(alts,hasPredicates,tokenMatcher,dynamicTokensEnabled){return lookahead_1$2.buildAlternativesLookAheadFunc(alts,hasPredicates,tokenMatcher,dynamicTokensEnabled)};LooksAhead2.prototype.getKeyForAutomaticLookahead=function(dslMethodIdx,occurrence){var currRuleShortName=this.getLastExplicitRuleShortName();return keys_1$2.getKeyForAutomaticLookahead(currRuleShortName,dslMethodIdx,occurrence)};LooksAhead2.prototype.getLaFuncFromCache=function(key){return void 0};LooksAhead2.prototype.getLaFuncFromMap=function(key){return this.lookAheadFuncsCache.get(key)};LooksAhead2.prototype.getLaFuncFromObj=function(key){return this.lookAheadFuncsCache[key]};LooksAhead2.prototype.setLaFuncCache=function(key,value){};LooksAhead2.prototype.setLaFuncCacheUsingMap=function(key,value){this.lookAheadFuncsCache.set(key,value)};LooksAhead2.prototype.setLaFuncUsingObj=function(key,value){this.lookAheadFuncsCache[key]=value};return LooksAhead2})();looksahead.LooksAhead=LooksAhead;var tree_builder={};var cst={};Object.defineProperty(cst,"__esModule",{value:true});cst.addNoneTerminalToCst=cst.addTerminalToCst=cst.setNodeLocationFull=cst.setNodeLocationOnlyOffset=void 0;function setNodeLocationOnlyOffset(currNodeLocation,newLocationInfo){if(isNaN(currNodeLocation.startOffset)===true){currNodeLocation.startOffset=newLocationInfo.startOffset;currNodeLocation.endOffset=newLocationInfo.endOffset}else if(currNodeLocation.endOffset<newLocationInfo.endOffset===true){currNodeLocation.endOffset=newLocationInfo.endOffset}}cst.setNodeLocationOnlyOffset=setNodeLocationOnlyOffset;function setNodeLocationFull(currNodeLocation,newLocationInfo){if(isNaN(currNodeLocation.startOffset)===true){currNodeLocation.startOffset=newLocationInfo.startOffset;currNodeLocation.startColumn=newLocationInfo.startColumn;currNodeLocation.startLine=newLocationInfo.startLine;currNodeLocation.endOffset=newLocationInfo.endOffset;currNodeLocation.endColumn=newLocationInfo.endColumn;currNodeLocation.endLine=newLocationInfo.endLine}else if(currNodeLocation.endOffset<newLocationInfo.endOffset===true){currNodeLocation.endOffset=newLocationInfo.endOffset;currNodeLocation.endColumn=newLocationInfo.endColumn;currNodeLocation.endLine=newLocationInfo.endLine}}cst.setNodeLocationFull=setNodeLocationFull;function addTerminalToCst(node,token,tokenTypeName){if(node.children[tokenTypeName]===void 0){node.children[tokenTypeName]=[token]}else{node.children[tokenTypeName].push(token)}}cst.addTerminalToCst=addTerminalToCst;function addNoneTerminalToCst(node,ruleName,ruleResult){if(node.children[ruleName]===void 0){node.children[ruleName]=[ruleResult]}else{node.children[ruleName].push(ruleResult)}}cst.addNoneTerminalToCst=addNoneTerminalToCst;var cst_visitor={};var lang_extensions={};Object.defineProperty(lang_extensions,"__esModule",{value:true});lang_extensions.defineNameProp=lang_extensions.functionName=lang_extensions.classNameFromInstance=void 0;var utils_1$7=api;function classNameFromInstance(instance){return functionName(instance.constructor)}lang_extensions.classNameFromInstance=classNameFromInstance;var NAME$1="name";function functionName(func){var existingNameProp=func.name;if(existingNameProp){return existingNameProp}else{return"anonymous"}}lang_extensions.functionName=functionName;function defineNameProp(obj,nameValue){var namePropDescriptor=Object.getOwnPropertyDescriptor(obj,NAME$1);if(utils_1$7.isUndefined(namePropDescriptor)||namePropDescriptor.configurable){Object.defineProperty(obj,NAME$1,{enumerable:false,configurable:true,writable:false,value:nameValue});return true}return false}lang_extensions.defineNameProp=defineNameProp;(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.validateRedundantMethods=exports3.validateMissingCstMethods=exports3.validateVisitor=exports3.CstVisitorDefinitionError=exports3.createBaseVisitorConstructorWithDefaults=exports3.createBaseSemanticVisitorConstructor=exports3.defaultVisit=void 0;var utils_12=api;var lang_extensions_12=lang_extensions;function defaultVisit(ctx,param){var childrenNames=utils_12.keys(ctx);var childrenNamesLength=childrenNames.length;for(var i=0;i<childrenNamesLength;i++){var currChildName=childrenNames[i];var currChildArray=ctx[currChildName];var currChildArrayLength=currChildArray.length;for(var j=0;j<currChildArrayLength;j++){var currChild=currChildArray[j];if(currChild.tokenTypeIdx===void 0){this[currChild.name](currChild.children,param)}}}return void 0}exports3.defaultVisit=defaultVisit;function createBaseSemanticVisitorConstructor(grammarName,ruleNames){var derivedConstructor=function(){};lang_extensions_12.defineNameProp(derivedConstructor,grammarName+"BaseSemantics");var semanticProto={visit:function(cstNode,param){if(utils_12.isArray(cstNode)){cstNode=cstNode[0]}if(utils_12.isUndefined(cstNode)){return void 0}return this[cstNode.name](cstNode.children,param)},validateVisitor:function(){var semanticDefinitionErrors=validateVisitor(this,ruleNames);if(!utils_12.isEmpty(semanticDefinitionErrors)){var errorMessages=utils_12.map(semanticDefinitionErrors,function(currDefError){return currDefError.msg});throw Error("Errors Detected in CST Visitor <"+lang_extensions_12.functionName(this.constructor)+">:\n "+(""+errorMessages.join("\n\n").replace(/\n/g,"\n ")))}}};derivedConstructor.prototype=semanticProto;derivedConstructor.prototype.constructor=derivedConstructor;derivedConstructor._RULE_NAMES=ruleNames;return derivedConstructor}exports3.createBaseSemanticVisitorConstructor=createBaseSemanticVisitorConstructor;function createBaseVisitorConstructorWithDefaults(grammarName,ruleNames,baseConstructor){var derivedConstructor=function(){};lang_extensions_12.defineNameProp(derivedConstructor,grammarName+"BaseSemanticsWithDefaults");var withDefaultsProto=Object.create(baseConstructor.prototype);utils_12.forEach(ruleNames,function(ruleName){withDefaultsProto[ruleName]=defaultVisit});derivedConstructor.prototype=withDefaultsProto;derivedConstructor.prototype.constructor=derivedConstructor;return derivedConstructor}exports3.createBaseVisitorConstructorWithDefaults=createBaseVisitorConstructorWithDefaults;var CstVisitorDefinitionError;(function(CstVisitorDefinitionError2){CstVisitorDefinitionError2[CstVisitorDefinitionError2["REDUNDANT_METHOD"]=0]="REDUNDANT_METHOD";CstVisitorDefinitionError2[CstVisitorDefinitionError2["MISSING_METHOD"]=1]="MISSING_METHOD"})(CstVisitorDefinitionError=exports3.CstVisitorDefinitionError||(exports3.CstVisitorDefinitionError={}));function validateVisitor(visitorInstance,ruleNames){var missingErrors=validateMissingCstMethods(visitorInstance,ruleNames);var redundantErrors=validateRedundantMethods(visitorInstance,ruleNames);return missingErrors.concat(redundantErrors)}exports3.validateVisitor=validateVisitor;function validateMissingCstMethods(visitorInstance,ruleNames){var errors=utils_12.map(ruleNames,function(currRuleName){if(!utils_12.isFunction(visitorInstance[currRuleName])){return{msg:"Missing visitor method: <"+currRuleName+"> on "+lang_extensions_12.functionName(visitorInstance.constructor)+" CST Visitor.",type:CstVisitorDefinitionError.MISSING_METHOD,methodName:currRuleName}}});return utils_12.compact(errors)}exports3.validateMissingCstMethods=validateMissingCstMethods;var VALID_PROP_NAMES=["constructor","visit","validateVisitor"];function validateRedundantMethods(visitorInstance,ruleNames){var errors=[];for(var prop in visitorInstance){if(utils_12.isFunction(visitorInstance[prop])&&!utils_12.contains(VALID_PROP_NAMES,prop)&&!utils_12.contains(ruleNames,prop)){errors.push({msg:"Redundant visitor method: <"+prop+"> on "+lang_extensions_12.functionName(visitorInstance.constructor)+" CST Visitor\nThere is no Grammar Rule corresponding to this method's name.\n",type:CstVisitorDefinitionError.REDUNDANT_METHOD,methodName:prop})}}return errors}exports3.validateRedundantMethods=validateRedundantMethods})(cst_visitor);Object.defineProperty(tree_builder,"__esModule",{value:true});tree_builder.TreeBuilder=void 0;var cst_1=cst;var utils_1$6=api;var cst_visitor_1=cst_visitor;var parser_1$6=parser;var TreeBuilder=(function(){function TreeBuilder2(){}TreeBuilder2.prototype.initTreeBuilder=function(config){this.CST_STACK=[];this.outputCst=config.outputCst;this.nodeLocationTracking=utils_1$6.has(config,"nodeLocationTracking")?config.nodeLocationTracking:parser_1$6.DEFAULT_PARSER_CONFIG.nodeLocationTracking;if(!this.outputCst){this.cstInvocationStateUpdate=utils_1$6.NOOP;this.cstFinallyStateUpdate=utils_1$6.NOOP;this.cstPostTerminal=utils_1$6.NOOP;this.cstPostNonTerminal=utils_1$6.NOOP;this.cstPostRule=utils_1$6.NOOP}else{if(/full/i.test(this.nodeLocationTracking)){if(this.recoveryEnabled){this.setNodeLocationFromToken=cst_1.setNodeLocationFull;this.setNodeLocationFromNode=cst_1.setNodeLocationFull;this.cstPostRule=utils_1$6.NOOP;this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery}else{this.setNodeLocationFromToken=utils_1$6.NOOP;this.setNodeLocationFromNode=utils_1$6.NOOP;this.cstPostRule=this.cstPostRuleFull;this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular}}else if(/onlyOffset/i.test(this.nodeLocationTracking)){if(this.recoveryEnabled){this.setNodeLocationFromToken=cst_1.setNodeLocationOnlyOffset;this.setNodeLocationFromNode=cst_1.setNodeLocationOnlyOffset;this.cstPostRule=utils_1$6.NOOP;this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery}else{this.setNodeLocationFromToken=utils_1$6.NOOP;this.setNodeLocationFromNode=utils_1$6.NOOP;this.cstPostRule=this.cstPostRuleOnlyOffset;this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular}}else if(/none/i.test(this.nodeLocationTracking)){this.setNodeLocationFromToken=utils_1$6.NOOP;this.setNodeLocationFromNode=utils_1$6.NOOP;this.cstPostRule=utils_1$6.NOOP;this.setInitialNodeLocation=utils_1$6.NOOP}else{throw Error('Invalid <nodeLocationTracking> config option: "'+config.nodeLocationTracking+'"')}}};TreeBuilder2.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(cstNode){cstNode.location={startOffset:NaN,endOffset:NaN}};TreeBuilder2.prototype.setInitialNodeLocationOnlyOffsetRegular=function(cstNode){cstNode.location={startOffset:this.LA(1).startOffset,endOffset:NaN}};TreeBuilder2.prototype.setInitialNodeLocationFullRecovery=function(cstNode){cstNode.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}};TreeBuilder2.prototype.setInitialNodeLocationFullRegular=function(cstNode){var nextToken=this.LA(1);cstNode.location={startOffset:nextToken.startOffset,startLine:nextToken.startLine,startColumn:nextToken.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}};TreeBuilder2.prototype.cstInvocationStateUpdate=function(fullRuleName,shortName){var cstNode={name:fullRuleName,children:{}};this.setInitialNodeLocation(cstNode);this.CST_STACK.push(cstNode)};TreeBuilder2.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()};TreeBuilder2.prototype.cstPostRuleFull=function(ruleCstNode){var prevToken=this.LA(0);var loc=ruleCstNode.location;if(loc.startOffset<=prevToken.startOffset===true){loc.endOffset=prevToken.endOffset;loc.endLine=prevToken.endLine;loc.endColumn=prevToken.endColumn}else{loc.startOffset=NaN;loc.startLine=NaN;loc.startColumn=NaN}};TreeBuilder2.prototype.cstPostRuleOnlyOffset=function(ruleCstNode){var prevToken=this.LA(0);var loc=ruleCstNode.location;if(loc.startOffset<=prevToken.startOffset===true){loc.endOffset=prevToken.endOffset}else{loc.startOffset=NaN}};TreeBuilder2.prototype.cstPostTerminal=function(key,consumedToken){var rootCst=this.CST_STACK[this.CST_STACK.length-1];cst_1.addTerminalToCst(rootCst,consumedToken,key);this.setNodeLocationFromToken(rootCst.location,consumedToken)};TreeBuilder2.prototype.cstPostNonTerminal=function(ruleCstResult,ruleName){var preCstNode=this.CST_STACK[this.CST_STACK.length-1];cst_1.addNoneTerminalToCst(preCstNode,ruleName,ruleCstResult);this.setNodeLocationFromNode(preCstNode.location,ruleCstResult.location)};TreeBuilder2.prototype.getBaseCstVisitorConstructor=function(){if(utils_1$6.isUndefined(this.baseCstVisitorConstructor)){var newBaseCstVisitorConstructor=cst_visitor_1.createBaseSemanticVisitorConstructor(this.className,utils_1$6.keys(this.gastProductionsCache));this.baseCstVisitorConstructor=newBaseCstVisitorConstructor;return newBaseCstVisitorConstructor}return this.baseCstVisitorConstructor};TreeBuilder2.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(utils_1$6.isUndefined(this.baseCstVisitorWithDefaultsConstructor)){var newConstructor=cst_visitor_1.createBaseVisitorConstructorWithDefaults(this.className,utils_1$6.keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());this.baseCstVisitorWithDefaultsConstructor=newConstructor;return newConstructor}return this.baseCstVisitorWithDefaultsConstructor};TreeBuilder2.prototype.getLastExplicitRuleShortName=function(){var ruleStack=this.RULE_STACK;return ruleStack[ruleStack.length-1]};TreeBuilder2.prototype.getPreviousExplicitRuleShortName=function(){var ruleStack=this.RULE_STACK;return ruleStack[ruleStack.length-2]};TreeBuilder2.prototype.getLastExplicitRuleOccurrenceIndex=function(){var occurrenceStack=this.RULE_OCCURRENCE_STACK;return occurrenceStack[occurrenceStack.length-1]};return TreeBuilder2})();tree_builder.TreeBuilder=TreeBuilder;var lexer_adapter={};Object.defineProperty(lexer_adapter,"__esModule",{value:true});lexer_adapter.LexerAdapter=void 0;var parser_1$5=parser;var LexerAdapter=(function(){function LexerAdapter2(){}LexerAdapter2.prototype.initLexerAdapter=function(){this.tokVector=[];this.tokVectorLength=0;this.currIdx=-1};Object.defineProperty(LexerAdapter2.prototype,"input",{get:function(){return this.tokVector},set:function(newInput){if(this.selfAnalysisDone!==true){throw Error("Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.")}this.reset();this.tokVector=newInput;this.tokVectorLength=newInput.length},enumerable:false,configurable:true});LexerAdapter2.prototype.SKIP_TOKEN=function(){if(this.currIdx<=this.tokVector.length-2){this.consumeToken();return this.LA(1)}else{return parser_1$5.END_OF_FILE}};LexerAdapter2.prototype.LA=function(howMuch){var soughtIdx=this.currIdx+howMuch;if(soughtIdx<0||this.tokVectorLength<=soughtIdx){return parser_1$5.END_OF_FILE}else{return this.tokVector[soughtIdx]}};LexerAdapter2.prototype.consumeToken=function(){this.currIdx++};LexerAdapter2.prototype.exportLexerState=function(){return this.currIdx};LexerAdapter2.prototype.importLexerState=function(newState){this.currIdx=newState};LexerAdapter2.prototype.resetLexerState=function(){this.currIdx=-1};LexerAdapter2.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1};LexerAdapter2.prototype.getLexerPosition=function(){return this.exportLexerState()};return LexerAdapter2})();lexer_adapter.LexerAdapter=LexerAdapter;var recognizer_api={};Object.defineProperty(recognizer_api,"__esModule",{value:true});recognizer_api.RecognizerApi=void 0;var utils_1$5=api;var exceptions_public_1$2=exceptions_public;var parser_1$4=parser;var errors_public_1=errors_public;var checks_1=checks;var gast_public_1$1=gast_public;var RecognizerApi=(function(){function RecognizerApi2(){}RecognizerApi2.prototype.ACTION=function(impl){return impl.call(this)};RecognizerApi2.prototype.consume=function(idx,tokType,options){return this.consumeInternal(tokType,idx,options)};RecognizerApi2.prototype.subrule=function(idx,ruleToCall,options){return this.subruleInternal(ruleToCall,idx,options)};RecognizerApi2.prototype.option=function(idx,actionORMethodDef){return this.optionInternal(actionORMethodDef,idx)};RecognizerApi2.prototype.or=function(idx,altsOrOpts){return this.orInternal(altsOrOpts,idx)};RecognizerApi2.prototype.many=function(idx,actionORMethodDef){return this.manyInternal(idx,actionORMethodDef)};RecognizerApi2.prototype.atLeastOne=function(idx,actionORMethodDef){return this.atLeastOneInternal(idx,actionORMethodDef)};RecognizerApi2.prototype.CONSUME=function(tokType,options){return this.consumeInternal(tokType,0,options)};RecognizerApi2.prototype.CONSUME1=function(tokType,options){return this.consumeInternal(tokType,1,options)};RecognizerApi2.prototype.CONSUME2=function(tokType,options){return this.consumeInternal(tokType,2,options)};RecognizerApi2.prototype.CONSUME3=function(tokType,options){return this.consumeInternal(tokType,3,options)};RecognizerApi2.prototype.CONSUME4=function(tokType,options){return this.consumeInternal(tokType,4,options)};RecognizerApi2.prototype.CONSUME5=function(tokType,options){return this.consumeInternal(tokType,5,options)};RecognizerApi2.prototype.CONSUME6=function(tokType,options){return this.consumeInternal(tokType,6,options)};RecognizerApi2.prototype.CONSUME7=function(tokType,options){return this.consumeInternal(tokType,7,options)};RecognizerApi2.prototype.CONSUME8=function(tokType,options){return this.consumeInternal(tokType,8,options)};RecognizerApi2.prototype.CONSUME9=function(tokType,options){return this.consumeInternal(tokType,9,options)};RecognizerApi2.prototype.SUBRULE=function(ruleToCall,options){return this.subruleInternal(ruleToCall,0,options)};RecognizerApi2.prototype.SUBRULE1=function(ruleToCall,options){return this.subruleInternal(ruleToCall,1,options)};RecognizerApi2.prototype.SUBRULE2=function(ruleToCall,options){return this.subruleInternal(ruleToCall,2,options)};RecognizerApi2.prototype.SUBRULE3=function(ruleToCall,options){return this.subruleInternal(ruleToCall,3,options)};RecognizerApi2.prototype.SUBRULE4=function(ruleToCall,options){return this.subruleInternal(ruleToCall,4,options)};RecognizerApi2.prototype.SUBRULE5=function(ruleToCall,options){return this.subruleInternal(ruleToCall,5,options)};RecognizerApi2.prototype.SUBRULE6=function(ruleToCall,options){return this.subruleInternal(ruleToCall,6,options)};RecognizerApi2.prototype.SUBRULE7=function(ruleToCall,options){return this.subruleInternal(ruleToCall,7,options)};RecognizerApi2.prototype.SUBRULE8=function(ruleToCall,options){return this.subruleInternal(ruleToCall,8,options)};RecognizerApi2.prototype.SUBRULE9=function(ruleToCall,options){return this.subruleInternal(ruleToCall,9,options)};RecognizerApi2.prototype.OPTION=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,0)};RecognizerApi2.prototype.OPTION1=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,1)};RecognizerApi2.prototype.OPTION2=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,2)};RecognizerApi2.prototype.OPTION3=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,3)};RecognizerApi2.prototype.OPTION4=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,4)};RecognizerApi2.prototype.OPTION5=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,5)};RecognizerApi2.prototype.OPTION6=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,6)};RecognizerApi2.prototype.OPTION7=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,7)};RecognizerApi2.prototype.OPTION8=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,8)};RecognizerApi2.prototype.OPTION9=function(actionORMethodDef){return this.optionInternal(actionORMethodDef,9)};RecognizerApi2.prototype.OR=function(altsOrOpts){return this.orInternal(altsOrOpts,0)};RecognizerApi2.prototype.OR1=function(altsOrOpts){return this.orInternal(altsOrOpts,1)};RecognizerApi2.prototype.OR2=function(altsOrOpts){return this.orInternal(altsOrOpts,2)};RecognizerApi2.prototype.OR3=function(altsOrOpts){return this.orInternal(altsOrOpts,3)};RecognizerApi2.prototype.OR4=function(altsOrOpts){return this.orInternal(altsOrOpts,4)};RecognizerApi2.prototype.OR5=function(altsOrOpts){return this.orInternal(altsOrOpts,5)};RecognizerApi2.prototype.OR6=function(altsOrOpts){return this.orInternal(altsOrOpts,6)};RecognizerApi2.prototype.OR7=function(altsOrOpts){return this.orInternal(altsOrOpts,7)};RecognizerApi2.prototype.OR8=function(altsOrOpts){return this.orInternal(altsOrOpts,8)};RecognizerApi2.prototype.OR9=function(altsOrOpts){return this.orInternal(altsOrOpts,9)};RecognizerApi2.prototype.MANY=function(actionORMethodDef){this.manyInternal(0,actionORMethodDef)};RecognizerApi2.prototype.MANY1=function(actionORMethodDef){this.manyInternal(1,actionORMethodDef)};RecognizerApi2.prototype.MANY2=function(actionORMethodDef){this.manyInternal(2,actionORMethodDef)};RecognizerApi2.prototype.MANY3=function(actionORMethodDef){this.manyInternal(3,actionORMethodDef)};RecognizerApi2.prototype.MANY4=function(actionORMethodDef){this.manyInternal(4,actionORMethodDef)};RecognizerApi2.prototype.MANY5=function(actionORMethodDef){this.manyInternal(5,actionORMethodDef)};RecognizerApi2.prototype.MANY6=function(actionORMethodDef){this.manyInternal(6,actionORMethodDef)};RecognizerApi2.prototype.MANY7=function(actionORMethodDef){this.manyInternal(7,actionORMethodDef)};RecognizerApi2.prototype.MANY8=function(actionORMethodDef){this.manyInternal(8,actionORMethodDef)};RecognizerApi2.prototype.MANY9=function(actionORMethodDef){this.manyInternal(9,actionORMethodDef)};RecognizerApi2.prototype.MANY_SEP=function(options){this.manySepFirstInternal(0,options)};RecognizerApi2.prototype.MANY_SEP1=function(options){this.manySepFirstInternal(1,options)};RecognizerApi2.prototype.MANY_SEP2=function(options){this.manySepFirstInternal(2,options)};RecognizerApi2.prototype.MANY_SEP3=function(options){this.manySepFirstInternal(3,options)};RecognizerApi2.prototype.MANY_SEP4=function(options){this.manySepFirstInternal(4,options)};RecognizerApi2.prototype.MANY_SEP5=function(options){this.manySepFirstInternal(5,options)};RecognizerApi2.prototype.MANY_SEP6=function(options){this.manySepFirstInternal(6,options)};RecognizerApi2.prototype.MANY_SEP7=function(options){this.manySepFirstInternal(7,options)};RecognizerApi2.prototype.MANY_SEP8=function(options){this.manySepFirstInternal(8,options)};RecognizerApi2.prototype.MANY_SEP9=function(options){this.manySepFirstInternal(9,options)};RecognizerApi2.prototype.AT_LEAST_ONE=function(actionORMethodDef){this.atLeastOneInternal(0,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE1=function(actionORMethodDef){return this.atLeastOneInternal(1,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE2=function(actionORMethodDef){this.atLeastOneInternal(2,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE3=function(actionORMethodDef){this.atLeastOneInternal(3,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE4=function(actionORMethodDef){this.atLeastOneInternal(4,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE5=function(actionORMethodDef){this.atLeastOneInternal(5,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE6=function(actionORMethodDef){this.atLeastOneInternal(6,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE7=function(actionORMethodDef){this.atLeastOneInternal(7,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE8=function(actionORMethodDef){this.atLeastOneInternal(8,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE9=function(actionORMethodDef){this.atLeastOneInternal(9,actionORMethodDef)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP=function(options){this.atLeastOneSepFirstInternal(0,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP1=function(options){this.atLeastOneSepFirstInternal(1,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP2=function(options){this.atLeastOneSepFirstInternal(2,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP3=function(options){this.atLeastOneSepFirstInternal(3,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP4=function(options){this.atLeastOneSepFirstInternal(4,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP5=function(options){this.atLeastOneSepFirstInternal(5,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP6=function(options){this.atLeastOneSepFirstInternal(6,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP7=function(options){this.atLeastOneSepFirstInternal(7,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP8=function(options){this.atLeastOneSepFirstInternal(8,options)};RecognizerApi2.prototype.AT_LEAST_ONE_SEP9=function(options){this.atLeastOneSepFirstInternal(9,options)};RecognizerApi2.prototype.RULE=function(name,implementation,config){if(config===void 0){config=parser_1$4.DEFAULT_RULE_CONFIG}if(utils_1$5.contains(this.definedRulesNames,name)){var errMsg=errors_public_1.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:name,grammarName:this.className});var error={message:errMsg,type:parser_1$4.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:name};this.definitionErrors.push(error)}this.definedRulesNames.push(name);var ruleImplementation=this.defineRule(name,implementation,config);this[name]=ruleImplementation;return ruleImplementation};RecognizerApi2.prototype.OVERRIDE_RULE=function(name,impl,config){if(config===void 0){config=parser_1$4.DEFAULT_RULE_CONFIG}var ruleErrors=[];ruleErrors=ruleErrors.concat(checks_1.validateRuleIsOverridden(name,this.definedRulesNames,this.className));this.definitionErrors=this.definitionErrors.concat(ruleErrors);var ruleImplementation=this.defineRule(name,impl,config);this[name]=ruleImplementation;return ruleImplementation};RecognizerApi2.prototype.BACKTRACK=function(grammarRule,args){return function(){this.isBackTrackingStack.push(1);var orgState=this.saveRecogState();try{grammarRule.apply(this,args);return true}catch(e){if(exceptions_public_1$2.isRecognitionException(e)){return false}else{throw e}}finally{this.reloadRecogState(orgState);this.isBackTrackingStack.pop()}}};RecognizerApi2.prototype.getGAstProductions=function(){return this.gastProductionsCache};RecognizerApi2.prototype.getSerializedGastProductions=function(){return gast_public_1$1.serializeGrammar(utils_1$5.values(this.gastProductionsCache))};return RecognizerApi2})();recognizer_api.RecognizerApi=RecognizerApi;var recognizer_engine={};Object.defineProperty(recognizer_engine,"__esModule",{value:true});recognizer_engine.RecognizerEngine=void 0;var utils_1$4=api;var keys_1$1=keys$1;var exceptions_public_1$1=exceptions_public;var lookahead_1$1=lookahead;var interpreter_1$1=interpreter;var parser_1$3=parser;var recoverable_1=recoverable;var tokens_public_1$1=tokens_public;var tokens_1$1=tokens;var lang_extensions_1=lang_extensions;var RecognizerEngine=(function(){function RecognizerEngine2(){}RecognizerEngine2.prototype.initRecognizerEngine=function(tokenVocabulary,config){this.className=lang_extensions_1.classNameFromInstance(this);this.shortRuleNameToFull={};this.fullRuleNameToShort={};this.ruleShortNameIdx=256;this.tokenMatcher=tokens_1$1.tokenStructuredMatcherNoCategories;this.definedRulesNames=[];this.tokensMap={};this.isBackTrackingStack=[];this.RULE_STACK=[];this.RULE_OCCURRENCE_STACK=[];this.gastProductionsCache={};if(utils_1$4.has(config,"serializedGrammar")){throw Error("The Parser's configuration can no longer contain a <serializedGrammar> property.\n See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n For Further details.")}if(utils_1$4.isArray(tokenVocabulary)){if(utils_1$4.isEmpty(tokenVocabulary)){throw Error("A Token Vocabulary cannot be empty.\n Note that the first argument for the parser constructor\n is no longer a Token vector (since v4.0).")}if(typeof tokenVocabulary[0].startOffset==="number"){throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\n For Further details.")}}if(utils_1$4.isArray(tokenVocabulary)){this.tokensMap=utils_1$4.reduce(tokenVocabulary,function(acc,tokType){acc[tokType.name]=tokType;return acc},{})}else if(utils_1$4.has(tokenVocabulary,"modes")&&utils_1$4.every(utils_1$4.flatten(utils_1$4.values(tokenVocabulary.modes)),tokens_1$1.isTokenType)){var allTokenTypes=utils_1$4.flatten(utils_1$4.values(tokenVocabulary.modes));var uniqueTokens=utils_1$4.uniq(allTokenTypes);this.tokensMap=utils_1$4.reduce(uniqueTokens,function(acc,tokType){acc[tokType.name]=tokType;return acc},{})}else if(utils_1$4.isObject(tokenVocabulary)){this.tokensMap=utils_1$4.cloneObj(tokenVocabulary)}else{throw new Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition")}this.tokensMap["EOF"]=tokens_public_1$1.EOF;var noTokenCategoriesUsed=utils_1$4.every(utils_1$4.values(tokenVocabulary),function(tokenConstructor){return utils_1$4.isEmpty(tokenConstructor.categoryMatches)});this.tokenMatcher=noTokenCategoriesUsed?tokens_1$1.tokenStructuredMatcherNoCategories:tokens_1$1.tokenStructuredMatcher;tokens_1$1.augmentTokenTypes(utils_1$4.values(this.tokensMap))};RecognizerEngine2.prototype.defineRule=function(ruleName,impl,config){if(this.selfAnalysisDone){throw Error("Grammar rule <"+ruleName+"> may not be defined after the 'performSelfAnalysis' method has been called'\nMake sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.")}var resyncEnabled=utils_1$4.has(config,"resyncEnabled")?config.resyncEnabled:parser_1$3.DEFAULT_RULE_CONFIG.resyncEnabled;var recoveryValueFunc=utils_1$4.has(config,"recoveryValueFunc")?config.recoveryValueFunc:parser_1$3.DEFAULT_RULE_CONFIG.recoveryValueFunc;var shortName=this.ruleShortNameIdx<<keys_1$1.BITS_FOR_METHOD_TYPE+keys_1$1.BITS_FOR_OCCURRENCE_IDX;this.ruleShortNameIdx++;this.shortRuleNameToFull[shortName]=ruleName;this.fullRuleNameToShort[ruleName]=shortName;function invokeRuleWithTry(args){try{if(this.outputCst===true){impl.apply(this,args);var cst2=this.CST_STACK[this.CST_STACK.length-1];this.cstPostRule(cst2);return cst2}else{return impl.apply(this,args)}}catch(e){return this.invokeRuleCatch(e,resyncEnabled,recoveryValueFunc)}finally{this.ruleFinallyStateUpdate()}}var wrappedGrammarRule=function(idxInCallingRule,args){if(idxInCallingRule===void 0){idxInCallingRule=0}this.ruleInvocationStateUpdate(shortName,ruleName,idxInCallingRule);return invokeRuleWithTry.call(this,args)};var ruleNamePropName="ruleName";wrappedGrammarRule[ruleNamePropName]=ruleName;wrappedGrammarRule["originalGrammarAction"]=impl;return wrappedGrammarRule};RecognizerEngine2.prototype.invokeRuleCatch=function(e,resyncEnabledConfig,recoveryValueFunc){var isFirstInvokedRule=this.RULE_STACK.length===1;var reSyncEnabled=resyncEnabledConfig&&!this.isBackTracking()&&this.recoveryEnabled;if(exceptions_public_1$1.isRecognitionException(e)){var recogError=e;if(reSyncEnabled){var reSyncTokType=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(reSyncTokType)){recogError.resyncedTokens=this.reSyncTo(reSyncTokType);if(this.outputCst){var partialCstResult=this.CST_STACK[this.CST_STACK.length-1];partialCstResult.recoveredNode=true;return partialCstResult}else{return recoveryValueFunc()}}else{if(this.outputCst){var partialCstResult=this.CST_STACK[this.CST_STACK.length-1];partialCstResult.recoveredNode=true;recogError.partialCstResult=partialCstResult}throw recogError}}else if(isFirstInvokedRule){this.moveToTerminatedState();return recoveryValueFunc()}else{throw recogError}}else{throw e}};RecognizerEngine2.prototype.optionInternal=function(actionORMethodDef,occurrence){var key=this.getKeyForAutomaticLookahead(keys_1$1.OPTION_IDX,occurrence);return this.optionInternalLogic(actionORMethodDef,occurrence,key)};RecognizerEngine2.prototype.optionInternalLogic=function(actionORMethodDef,occurrence,key){var _this=this;var lookAheadFunc=this.getLaFuncFromCache(key);var action;var predicate;if(actionORMethodDef.DEF!==void 0){action=actionORMethodDef.DEF;predicate=actionORMethodDef.GATE;if(predicate!==void 0){var orgLookaheadFunction_1=lookAheadFunc;lookAheadFunc=function(){return predicate.call(_this)&&orgLookaheadFunction_1.call(_this)}}}else{action=actionORMethodDef}if(lookAheadFunc.call(this)===true){return action.call(this)}return void 0};RecognizerEngine2.prototype.atLeastOneInternal=function(prodOccurrence,actionORMethodDef){var laKey=this.getKeyForAutomaticLookahead(keys_1$1.AT_LEAST_ONE_IDX,prodOccurrence);return this.atLeastOneInternalLogic(prodOccurrence,actionORMethodDef,laKey)};RecognizerEngine2.prototype.atLeastOneInternalLogic=function(prodOccurrence,actionORMethodDef,key){var _this=this;var lookAheadFunc=this.getLaFuncFromCache(key);var action;var predicate;if(actionORMethodDef.DEF!==void 0){action=actionORMethodDef.DEF;predicate=actionORMethodDef.GATE;if(predicate!==void 0){var orgLookaheadFunction_2=lookAheadFunc;lookAheadFunc=function(){return predicate.call(_this)&&orgLookaheadFunction_2.call(_this)}}}else{action=actionORMethodDef}if(lookAheadFunc.call(this)===true){var notStuck=this.doSingleRepetition(action);while(lookAheadFunc.call(this)===true&&notStuck===true){notStuck=this.doSingleRepetition(action)}}else{throw this.raiseEarlyExitException(prodOccurrence,lookahead_1$1.PROD_TYPE.REPETITION_MANDATORY,actionORMethodDef.ERR_MSG)}this.attemptInRepetitionRecovery(this.atLeastOneInternal,[prodOccurrence,actionORMethodDef],lookAheadFunc,keys_1$1.AT_LEAST_ONE_IDX,prodOccurrence,interpreter_1$1.NextTerminalAfterAtLeastOneWalker)};RecognizerEngine2.prototype.atLeastOneSepFirstInternal=function(prodOccurrence,options){var laKey=this.getKeyForAutomaticLookahead(keys_1$1.AT_LEAST_ONE_SEP_IDX,prodOccurrence);this.atLeastOneSepFirstInternalLogic(prodOccurrence,options,laKey)};RecognizerEngine2.prototype.atLeastOneSepFirstInternalLogic=function(prodOccurrence,options,key){var _this=this;var action=options.DEF;var separator=options.SEP;var firstIterationLookaheadFunc=this.getLaFuncFromCache(key);if(firstIterationLookaheadFunc.call(this)===true){action.call(this);var separatorLookAheadFunc=function(){return _this.tokenMatcher(_this.LA(1),separator)};while(this.tokenMatcher(this.LA(1),separator)===true){this.CONSUME(separator);action.call(this)}this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[prodOccurrence,separator,separatorLookAheadFunc,action,interpreter_1$1.NextTerminalAfterAtLeastOneSepWalker],separatorLookAheadFunc,keys_1$1.AT_LEAST_ONE_SEP_IDX,prodOccurrence,interpreter_1$1.NextTerminalAfterAtLeastOneSepWalker)}else{throw this.raiseEarlyExitException(prodOccurrence,lookahead_1$1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,options.ERR_MSG)}};RecognizerEngine2.prototype.manyInternal=function(prodOccurrence,actionORMethodDef){var laKey=this.getKeyForAutomaticLookahead(keys_1$1.MANY_IDX,prodOccurrence);return this.manyInternalLogic(prodOccurrence,actionORMethodDef,laKey)};RecognizerEngine2.prototype.manyInternalLogic=function(prodOccurrence,actionORMethodDef,key){var _this=this;var lookaheadFunction=this.getLaFuncFromCache(key);var action;var predicate;if(actionORMethodDef.DEF!==void 0){action=actionORMethodDef.DEF;predicate=actionORMethodDef.GATE;if(predicate!==void 0){var orgLookaheadFunction_3=lookaheadFunction;lookaheadFunction=function(){return predicate.call(_this)&&orgLookaheadFunction_3.call(_this)}}}else{action=actionORMethodDef}var notStuck=true;while(lookaheadFunction.call(this)===true&&notStuck===true){notStuck=this.doSingleRepetition(action)}this.attemptInRepetitionRecovery(this.manyInternal,[prodOccurrence,actionORMethodDef],lookaheadFunction,keys_1$1.MANY_IDX,prodOccurrence,interpreter_1$1.NextTerminalAfterManyWalker,notStuck)};RecognizerEngine2.prototype.manySepFirstInternal=function(prodOccurrence,options){var laKey=this.getKeyForAutomaticLookahead(keys_1$1.MANY_SEP_IDX,prodOccurrence);this.manySepFirstInternalLogic(prodOccurrence,options,laKey)};RecognizerEngine2.prototype.manySepFirstInternalLogic=function(prodOccurrence,options,key){var _this=this;var action=options.DEF;var separator=options.SEP;var firstIterationLaFunc=this.getLaFuncFromCache(key);if(firstIterationLaFunc.call(this)===true){action.call(this);var separatorLookAheadFunc=function(){return _this.tokenMatcher(_this.LA(1),separator)};while(this.tokenMatcher(this.LA(1),separator)===true){this.CONSUME(separator);action.call(this)}this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[prodOccurrence,separator,separatorLookAheadFunc,action,interpreter_1$1.NextTerminalAfterManySepWalker],separatorLookAheadFunc,keys_1$1.MANY_SEP_IDX,prodOccurrence,interpreter_1$1.NextTerminalAfterManySepWalker)}};RecognizerEngine2.prototype.repetitionSepSecondInternal=function(prodOccurrence,separator,separatorLookAheadFunc,action,nextTerminalAfterWalker){while(separatorLookAheadFunc()){this.CONSUME(separator);action.call(this)}this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[prodOccurrence,separator,separatorLookAheadFunc,action,nextTerminalAfterWalker],separatorLookAheadFunc,keys_1$1.AT_LEAST_ONE_SEP_IDX,prodOccurrence,nextTerminalAfterWalker)};RecognizerEngine2.prototype.doSingleRepetition=function(action){var beforeIteration=this.getLexerPosition();action.call(this);var afterIteration=this.getLexerPosition();return afterIteration>beforeIteration};RecognizerEngine2.prototype.orInternal=function(altsOrOpts,occurrence){var laKey=this.getKeyForAutomaticLookahead(keys_1$1.OR_IDX,occurrence);var alts=utils_1$4.isArray(altsOrOpts)?altsOrOpts:altsOrOpts.DEF;var laFunc=this.getLaFuncFromCache(laKey);var altIdxToTake=laFunc.call(this,alts);if(altIdxToTake!==void 0){var chosenAlternative=alts[altIdxToTake];return chosenAlternative.ALT.call(this)}this.raiseNoAltException(occurrence,altsOrOpts.ERR_MSG)};RecognizerEngine2.prototype.ruleFinallyStateUpdate=function(){this.RULE_STACK.pop();this.RULE_OCCURRENCE_STACK.pop();this.cstFinallyStateUpdate();if(this.RULE_STACK.length===0&&this.isAtEndOfInput()===false){var firstRedundantTok=this.LA(1);var errMsg=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:firstRedundantTok,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new exceptions_public_1$1.NotAllInputParsedException(errMsg,firstRedundantTok))}};RecognizerEngine2.prototype.subruleInternal=function(ruleToCall,idx,options){var ruleResult;try{var args=options!==void 0?options.ARGS:void 0;ruleResult=ruleToCall.call(this,idx,args);this.cstPostNonTerminal(ruleResult,options!==void 0&&options.LABEL!==void 0?options.LABEL:ruleToCall.ruleName);return ruleResult}catch(e){this.subruleInternalError(e,options,ruleToCall.ruleName)}};RecognizerEngine2.prototype.subruleInternalError=function(e,options,ruleName){if(exceptions_public_1$1.isRecognitionException(e)&&e.partialCstResult!==void 0){this.cstPostNonTerminal(e.partialCstResult,options!==void 0&&options.LABEL!==void 0?options.LABEL:ruleName);delete e.partialCstResult}throw e};RecognizerEngine2.prototype.consumeInternal=function(tokType,idx,options){var consumedToken;try{var nextToken=this.LA(1);if(this.tokenMatcher(nextToken,tokType)===true){this.consumeToken();consumedToken=nextToken}else{this.consumeInternalError(tokType,nextToken,options)}}catch(eFromConsumption){consumedToken=this.consumeInternalRecovery(tokType,idx,eFromConsumption)}this.cstPostTerminal(options!==void 0&&options.LABEL!==void 0?options.LABEL:tokType.name,consumedToken);return consumedToken};RecognizerEngine2.prototype.consumeInternalError=function(tokType,nextToken,options){var msg;var previousToken=this.LA(0);if(options!==void 0&&options.ERR_MSG){msg=options.ERR_MSG}else{msg=this.errorMessageProvider.buildMismatchTokenMessage({expected:tokType,actual:nextToken,previous:previousToken,ruleName:this.getCurrRuleFullName()})}throw this.SAVE_ERROR(new exceptions_public_1$1.MismatchedTokenException(msg,nextToken,previousToken))};RecognizerEngine2.prototype.consumeInternalRecovery=function(tokType,idx,eFromConsumption){if(this.recoveryEnabled&&eFromConsumption.name==="MismatchedTokenException"&&!this.isBackTracking()){var follows=this.getFollowsForInRuleRecovery(tokType,idx);try{return this.tryInRuleRecovery(tokType,follows)}catch(eFromInRuleRecovery){if(eFromInRuleRecovery.name===recoverable_1.IN_RULE_RECOVERY_EXCEPTION){throw eFromConsumption}else{throw eFromInRuleRecovery}}}else{throw eFromConsumption}};RecognizerEngine2.prototype.saveRecogState=function(){var savedErrors=this.errors;var savedRuleStack=utils_1$4.cloneArr(this.RULE_STACK);return{errors:savedErrors,lexerState:this.exportLexerState(),RULE_STACK:savedRuleStack,CST_STACK:this.CST_STACK}};RecognizerEngine2.prototype.reloadRecogState=function(newState){this.errors=newState.errors;this.importLexerState(newState.lexerState);this.RULE_STACK=newState.RULE_STACK};RecognizerEngine2.prototype.ruleInvocationStateUpdate=function(shortName,fullName,idxInCallingRule){this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);this.RULE_STACK.push(shortName);this.cstInvocationStateUpdate(fullName,shortName)};RecognizerEngine2.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0};RecognizerEngine2.prototype.getCurrRuleFullName=function(){var shortName=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[shortName]};RecognizerEngine2.prototype.shortRuleNameToFullName=function(shortName){return this.shortRuleNameToFull[shortName]};RecognizerEngine2.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),tokens_public_1$1.EOF)};RecognizerEngine2.prototype.reset=function(){this.resetLexerState();this.isBackTrackingStack=[];this.errors=[];this.RULE_STACK=[];this.CST_STACK=[];this.RULE_OCCURRENCE_STACK=[]};return RecognizerEngine2})();recognizer_engine.RecognizerEngine=RecognizerEngine;var error_handler={};Object.defineProperty(error_handler,"__esModule",{value:true});error_handler.ErrorHandler=void 0;var exceptions_public_1=exceptions_public;var utils_1$3=api;var lookahead_1=lookahead;var parser_1$2=parser;var ErrorHandler=(function(){function ErrorHandler2(){}ErrorHandler2.prototype.initErrorHandler=function(config){this._errors=[];this.errorMessageProvider=utils_1$3.has(config,"errorMessageProvider")?config.errorMessageProvider:parser_1$2.DEFAULT_PARSER_CONFIG.errorMessageProvider};ErrorHandler2.prototype.SAVE_ERROR=function(error){if(exceptions_public_1.isRecognitionException(error)){error.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:utils_1$3.cloneArr(this.RULE_OCCURRENCE_STACK)};this._errors.push(error);return error}else{throw Error("Trying to save an Error which is not a RecognitionException")}};Object.defineProperty(ErrorHandler2.prototype,"errors",{get:function(){return utils_1$3.cloneArr(this._errors)},set:function(newErrors){this._errors=newErrors},enumerable:false,configurable:true});ErrorHandler2.prototype.raiseEarlyExitException=function(occurrence,prodType,userDefinedErrMsg){var ruleName=this.getCurrRuleFullName();var ruleGrammar=this.getGAstProductions()[ruleName];var lookAheadPathsPerAlternative=lookahead_1.getLookaheadPathsForOptionalProd(occurrence,ruleGrammar,prodType,this.maxLookahead);var insideProdPaths=lookAheadPathsPerAlternative[0];var actualTokens=[];for(var i=1;i<=this.maxLookahead;i++){actualTokens.push(this.LA(i))}var msg=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:insideProdPaths,actual:actualTokens,previous:this.LA(0),customUserDescription:userDefinedErrMsg,ruleName});throw this.SAVE_ERROR(new exceptions_public_1.EarlyExitException(msg,this.LA(1),this.LA(0)))};ErrorHandler2.prototype.raiseNoAltException=function(occurrence,errMsgTypes){var ruleName=this.getCurrRuleFullName();var ruleGrammar=this.getGAstProductions()[ruleName];var lookAheadPathsPerAlternative=lookahead_1.getLookaheadPathsForOr(occurrence,ruleGrammar,this.maxLookahead);var actualTokens=[];for(var i=1;i<=this.maxLookahead;i++){actualTokens.push(this.LA(i))}var previousToken=this.LA(0);var errMsg=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:lookAheadPathsPerAlternative,actual:actualTokens,previous:previousToken,customUserDescription:errMsgTypes,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new exceptions_public_1.NoViableAltException(errMsg,this.LA(1),previousToken))};return ErrorHandler2})();error_handler.ErrorHandler=ErrorHandler;var context_assist={};Object.defineProperty(context_assist,"__esModule",{value:true});context_assist.ContentAssist=void 0;var interpreter_1=interpreter;var utils_1$2=api;var ContentAssist=(function(){function ContentAssist2(){}ContentAssist2.prototype.initContentAssist=function(){};ContentAssist2.prototype.computeContentAssist=function(startRuleName,precedingInput){var startRuleGast=this.gastProductionsCache[startRuleName];if(utils_1$2.isUndefined(startRuleGast)){throw Error("Rule ->"+startRuleName+"<- does not exist in this grammar.")}return interpreter_1.nextPossibleTokensAfter([startRuleGast],precedingInput,this.tokenMatcher,this.maxLookahead)};ContentAssist2.prototype.getNextPossibleTokenTypes=function(grammarPath){var topRuleName=utils_1$2.first(grammarPath.ruleStack);var gastProductions=this.getGAstProductions();var topProduction=gastProductions[topRuleName];var nextPossibleTokenTypes=new interpreter_1.NextAfterTokenWalker(topProduction,grammarPath).startWalking();return nextPossibleTokenTypes};return ContentAssist2})();context_assist.ContentAssist=ContentAssist;var gast_recorder={};Object.defineProperty(gast_recorder,"__esModule",{value:true});gast_recorder.GastRecorder=void 0;var utils_1$1=api;var gast_public_1=gast_public;var lexer_public_1=lexer_public;var tokens_1=tokens;var tokens_public_1=tokens_public;var parser_1$1=parser;var keys_1=keys$1;var RECORDING_NULL_OBJECT={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(RECORDING_NULL_OBJECT);var HANDLE_SEPARATOR=true;var MAX_METHOD_IDX=Math.pow(2,keys_1.BITS_FOR_OCCURRENCE_IDX)-1;var RFT=tokens_public_1.createToken({name:"RECORDING_PHASE_TOKEN",pattern:lexer_public_1.Lexer.NA});tokens_1.augmentTokenTypes([RFT]);var RECORDING_PHASE_TOKEN=tokens_public_1.createTokenInstance(RFT,"This IToken indicates the Parser is in Recording Phase\n See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",-1,-1,-1,-1,-1,-1);Object.freeze(RECORDING_PHASE_TOKEN);var RECORDING_PHASE_CSTNODE={name:"This CSTNode indicates the Parser is in Recording Phase\n See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",children:{}};var GastRecorder=(function(){function GastRecorder2(){}GastRecorder2.prototype.initGastRecorder=function(config){this.recordingProdStack=[];this.RECORDING_PHASE=false};GastRecorder2.prototype.enableRecording=function(){var _this=this;this.RECORDING_PHASE=true;this.TRACE_INIT("Enable Recording",function(){var _loop_1=function(i2){var idx=i2>0?i2:"";_this["CONSUME"+idx]=function(arg1,arg2){return this.consumeInternalRecord(arg1,i2,arg2)};_this["SUBRULE"+idx]=function(arg1,arg2){return this.subruleInternalRecord(arg1,i2,arg2)};_this["OPTION"+idx]=function(arg1){return this.optionInternalRecord(arg1,i2)};_this["OR"+idx]=function(arg1){return this.orInternalRecord(arg1,i2)};_this["MANY"+idx]=function(arg1){this.manyInternalRecord(i2,arg1)};_this["MANY_SEP"+idx]=function(arg1){this.manySepFirstInternalRecord(i2,arg1)};_this["AT_LEAST_ONE"+idx]=function(arg1){this.atLeastOneInternalRecord(i2,arg1)};_this["AT_LEAST_ONE_SEP"+idx]=function(arg1){this.atLeastOneSepFirstInternalRecord(i2,arg1)}};for(var i=0;i<10;i++){_loop_1(i)}_this["consume"]=function(idx,arg1,arg2){return this.consumeInternalRecord(arg1,idx,arg2)};_this["subrule"]=function(idx,arg1,arg2){return this.subruleInternalRecord(arg1,idx,arg2)};_this["option"]=function(idx,arg1){return this.optionInternalRecord(arg1,idx)};_this["or"]=function(idx,arg1){return this.orInternalRecord(arg1,idx)};_this["many"]=function(idx,arg1){this.manyInternalRecord(idx,arg1)};_this["atLeastOne"]=function(idx,arg1){this.atLeastOneInternalRecord(idx,arg1)};_this.ACTION=_this.ACTION_RECORD;_this.BACKTRACK=_this.BACKTRACK_RECORD;_this.LA=_this.LA_RECORD})};GastRecorder2.prototype.disableRecording=function(){var _this=this;this.RECORDING_PHASE=false;this.TRACE_INIT("Deleting Recording methods",function(){for(var i=0;i<10;i++){var idx=i>0?i:"";delete _this["CONSUME"+idx];delete _this["SUBRULE"+idx];delete _this["OPTION"+idx];delete _this["OR"+idx];delete _this["MANY"+idx];delete _this["MANY_SEP"+idx];delete _this["AT_LEAST_ONE"+idx];delete _this["AT_LEAST_ONE_SEP"+idx]}delete _this["consume"];delete _this["subrule"];delete _this["option"];delete _this["or"];delete _this["many"];delete _this["atLeastOne"];delete _this.ACTION;delete _this.BACKTRACK;delete _this.LA})};GastRecorder2.prototype.ACTION_RECORD=function(impl){return};GastRecorder2.prototype.BACKTRACK_RECORD=function(grammarRule,args){return function(){return true}};GastRecorder2.prototype.LA_RECORD=function(howMuch){return parser_1$1.END_OF_FILE};GastRecorder2.prototype.topLevelRuleRecord=function(name,def){try{var newTopLevelRule=new gast_public_1.Rule({definition:[],name});newTopLevelRule.name=name;this.recordingProdStack.push(newTopLevelRule);def.call(this);this.recordingProdStack.pop();return newTopLevelRule}catch(originalError){if(originalError.KNOWN_RECORDER_ERROR!==true){try{originalError.message=originalError.message+'\n This error was thrown during the "grammar recording phase" For more info see:\n https://chevrotain.io/docs/guide/internals.html#grammar-recording'}catch(mutabilityError){throw originalError}}throw originalError}};GastRecorder2.prototype.optionInternalRecord=function(actionORMethodDef,occurrence){return recordProd.call(this,gast_public_1.Option,actionORMethodDef,occurrence)};GastRecorder2.prototype.atLeastOneInternalRecord=function(occurrence,actionORMethodDef){recordProd.call(this,gast_public_1.RepetitionMandatory,actionORMethodDef,occurrence)};GastRecorder2.prototype.atLeastOneSepFirstInternalRecord=function(occurrence,options){recordProd.call(this,gast_public_1.RepetitionMandatoryWithSeparator,options,occurrence,HANDLE_SEPARATOR)};GastRecorder2.prototype.manyInternalRecord=function(occurrence,actionORMethodDef){recordProd.call(this,gast_public_1.Repetition,actionORMethodDef,occurrence)};GastRecorder2.prototype.manySepFirstInternalRecord=function(occurrence,options){recordProd.call(this,gast_public_1.RepetitionWithSeparator,options,occurrence,HANDLE_SEPARATOR)};GastRecorder2.prototype.orInternalRecord=function(altsOrOpts,occurrence){return recordOrProd.call(this,altsOrOpts,occurrence)};GastRecorder2.prototype.subruleInternalRecord=function(ruleToCall,occurrence,options){assertMethodIdxIsValid(occurrence);if(!ruleToCall||utils_1$1.has(ruleToCall,"ruleName")===false){var error=new Error("<SUBRULE"+getIdxSuffix(occurrence)+"> argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(ruleToCall)+">")+("\n inside top level rule: <"+this.recordingProdStack[0].name+">"));error.KNOWN_RECORDER_ERROR=true;throw error}var prevProd=utils_1$1.peek(this.recordingProdStack);var ruleName=ruleToCall["ruleName"];var newNoneTerminal=new gast_public_1.NonTerminal({idx:occurrence,nonTerminalName:ruleName,label:options===null||options===void 0?void 0:options.LABEL,referencedRule:void 0});prevProd.definition.push(newNoneTerminal);return this.outputCst?RECORDING_PHASE_CSTNODE:RECORDING_NULL_OBJECT};GastRecorder2.prototype.consumeInternalRecord=function(tokType,occurrence,options){assertMethodIdxIsValid(occurrence);if(!tokens_1.hasShortKeyProperty(tokType)){var error=new Error("<CONSUME"+getIdxSuffix(occurrence)+"> argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(tokType)+">")+("\n inside top level rule: <"+this.recordingProdStack[0].name+">"));error.KNOWN_RECORDER_ERROR=true;throw error}var prevProd=utils_1$1.peek(this.recordingProdStack);var newNoneTerminal=new gast_public_1.Terminal({idx:occurrence,terminalType:tokType,label:options===null||options===void 0?void 0:options.LABEL});prevProd.definition.push(newNoneTerminal);return RECORDING_PHASE_TOKEN};return GastRecorder2})();gast_recorder.GastRecorder=GastRecorder;function recordProd(prodConstructor,mainProdArg,occurrence,handleSep){if(handleSep===void 0){handleSep=false}assertMethodIdxIsValid(occurrence);var prevProd=utils_1$1.peek(this.recordingProdStack);var grammarAction=utils_1$1.isFunction(mainProdArg)?mainProdArg:mainProdArg.DEF;var newProd=new prodConstructor({definition:[],idx:occurrence});if(handleSep){newProd.separator=mainProdArg.SEP}if(utils_1$1.has(mainProdArg,"MAX_LOOKAHEAD")){newProd.maxLookahead=mainProdArg.MAX_LOOKAHEAD}this.recordingProdStack.push(newProd);grammarAction.call(this);prevProd.definition.push(newProd);this.recordingProdStack.pop();return RECORDING_NULL_OBJECT}function recordOrProd(mainProdArg,occurrence){var _this=this;assertMethodIdxIsValid(occurrence);var prevProd=utils_1$1.peek(this.recordingProdStack);var hasOptions=utils_1$1.isArray(mainProdArg)===false;var alts=hasOptions===false?mainProdArg:mainProdArg.DEF;var newOrProd=new gast_public_1.Alternation({definition:[],idx:occurrence,ignoreAmbiguities:hasOptions&&mainProdArg.IGNORE_AMBIGUITIES===true});if(utils_1$1.has(mainProdArg,"MAX_LOOKAHEAD")){newOrProd.maxLookahead=mainProdArg.MAX_LOOKAHEAD}var hasPredicates=utils_1$1.some(alts,function(currAlt){return utils_1$1.isFunction(currAlt.GATE)});newOrProd.hasPredicates=hasPredicates;prevProd.definition.push(newOrProd);utils_1$1.forEach(alts,function(currAlt){var currAltFlat=new gast_public_1.Alternative({definition:[]});newOrProd.definition.push(currAltFlat);if(utils_1$1.has(currAlt,"IGNORE_AMBIGUITIES")){currAltFlat.ignoreAmbiguities=currAlt.IGNORE_AMBIGUITIES}else if(utils_1$1.has(currAlt,"GATE")){currAltFlat.ignoreAmbiguities=true}_this.recordingProdStack.push(currAltFlat);currAlt.ALT.call(_this);_this.recordingProdStack.pop()});return RECORDING_NULL_OBJECT}function getIdxSuffix(idx){return idx===0?"":""+idx}function assertMethodIdxIsValid(idx){if(idx<0||idx>MAX_METHOD_IDX){var error=new Error("Invalid DSL Method idx value: <"+idx+">\n "+("Idx value must be a none negative value smaller than "+(MAX_METHOD_IDX+1)));error.KNOWN_RECORDER_ERROR=true;throw error}}var perf_tracer={};Object.defineProperty(perf_tracer,"__esModule",{value:true});perf_tracer.PerformanceTracer=void 0;var utils_1=api;var parser_1=parser;var PerformanceTracer=(function(){function PerformanceTracer2(){}PerformanceTracer2.prototype.initPerformanceTracer=function(config){if(utils_1.has(config,"traceInitPerf")){var userTraceInitPerf=config.traceInitPerf;var traceIsNumber=typeof userTraceInitPerf==="number";this.traceInitMaxIdent=traceIsNumber?userTraceInitPerf:Infinity;this.traceInitPerf=traceIsNumber?userTraceInitPerf>0:userTraceInitPerf}else{this.traceInitMaxIdent=0;this.traceInitPerf=parser_1.DEFAULT_PARSER_CONFIG.traceInitPerf}this.traceInitIndent=-1};PerformanceTracer2.prototype.TRACE_INIT=function(phaseDesc,phaseImpl){if(this.traceInitPerf===true){this.traceInitIndent++;var indent=new Array(this.traceInitIndent+1).join(" ");if(this.traceInitIndent<this.traceInitMaxIdent){console.log(indent+"--> <"+phaseDesc+">")}var _a=utils_1.timer(phaseImpl),time=_a.time,value=_a.value;var traceMethod=time>10?console.warn:console.log;if(this.traceInitIndent<this.traceInitMaxIdent){traceMethod(indent+"<-- <"+phaseDesc+"> time: "+time+"ms")}this.traceInitIndent--;return value}else{return phaseImpl()}};return PerformanceTracer2})();perf_tracer.PerformanceTracer=PerformanceTracer;var apply_mixins={};Object.defineProperty(apply_mixins,"__esModule",{value:true});apply_mixins.applyMixins=void 0;function applyMixins(derivedCtor,baseCtors){baseCtors.forEach(function(baseCtor){var baseProto=baseCtor.prototype;Object.getOwnPropertyNames(baseProto).forEach(function(propName){if(propName==="constructor"){return}var basePropDescriptor=Object.getOwnPropertyDescriptor(baseProto,propName);if(basePropDescriptor&&(basePropDescriptor.get||basePropDescriptor.set)){Object.defineProperty(derivedCtor.prototype,propName,basePropDescriptor)}else{derivedCtor.prototype[propName]=baseCtor.prototype[propName]}})})}apply_mixins.applyMixins=applyMixins;(function(exports3){var __extends2=commonjsGlobal&&commonjsGlobal.__extends||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(Object.prototype.hasOwnProperty.call(b2,p))d2[p]=b2[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(exports3,"__esModule",{value:true});exports3.EmbeddedActionsParser=exports3.CstParser=exports3.Parser=exports3.EMPTY_ALT=exports3.ParserDefinitionErrorType=exports3.DEFAULT_RULE_CONFIG=exports3.DEFAULT_PARSER_CONFIG=exports3.END_OF_FILE=void 0;var utils_12=api;var follow_1=follow;var tokens_public_12=tokens_public;var errors_public_12=errors_public;var gast_resolver_public_1=gast_resolver_public;var recoverable_12=recoverable;var looksahead_1=looksahead;var tree_builder_1=tree_builder;var lexer_adapter_1=lexer_adapter;var recognizer_api_1=recognizer_api;var recognizer_engine_1=recognizer_engine;var error_handler_1=error_handler;var context_assist_1=context_assist;var gast_recorder_1=gast_recorder;var perf_tracer_1=perf_tracer;var apply_mixins_1=apply_mixins;exports3.END_OF_FILE=tokens_public_12.createTokenInstance(tokens_public_12.EOF,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(exports3.END_OF_FILE);exports3.DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:false,maxLookahead:3,dynamicTokensEnabled:false,outputCst:true,errorMessageProvider:errors_public_12.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:false,skipValidations:false});exports3.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){return void 0},resyncEnabled:true});(function(ParserDefinitionErrorType){ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"]=0]="INVALID_RULE_NAME";ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"]=1]="DUPLICATE_RULE_NAME";ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"]=2]="INVALID_RULE_OVERRIDE";ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"]=3]="DUPLICATE_PRODUCTIONS";ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"]=4]="UNRESOLVED_SUBRULE_REF";ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"]=5]="LEFT_RECURSION";ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"]=6]="NONE_LAST_EMPTY_ALT";ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"]=7]="AMBIGUOUS_ALTS";ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"]=8]="CONFLICT_TOKENS_RULES_NAMESPACE";ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"]=9]="INVALID_TOKEN_NAME";ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"]=10]="NO_NON_EMPTY_LOOKAHEAD";ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"]=11]="AMBIGUOUS_PREFIX_ALTS";ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"]=12]="TOO_MANY_ALTS"})(exports3.ParserDefinitionErrorType||(exports3.ParserDefinitionErrorType={}));function EMPTY_ALT(value){if(value===void 0){value=void 0}return function(){return value}}exports3.EMPTY_ALT=EMPTY_ALT;var Parser2=(function(){function Parser3(tokenVocabulary,config){this.definitionErrors=[];this.selfAnalysisDone=false;var that=this;that.initErrorHandler(config);that.initLexerAdapter();that.initLooksAhead(config);that.initRecognizerEngine(tokenVocabulary,config);that.initRecoverable(config);that.initTreeBuilder(config);that.initContentAssist();that.initGastRecorder(config);that.initPerformanceTracer(config);if(utils_12.has(config,"ignoredIssues")){throw new Error("The <ignoredIssues> IParserConfig property has been deprecated.\n Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.\n See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n For further details.")}this.skipValidations=utils_12.has(config,"skipValidations")?config.skipValidations:exports3.DEFAULT_PARSER_CONFIG.skipValidations}Parser3.performSelfAnalysis=function(parserInstance){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")};Parser3.prototype.performSelfAnalysis=function(){var _this=this;this.TRACE_INIT("performSelfAnalysis",function(){var defErrorsMsgs;_this.selfAnalysisDone=true;var className=_this.className;_this.TRACE_INIT("toFastProps",function(){utils_12.toFastProperties(_this)});_this.TRACE_INIT("Grammar Recording",function(){try{_this.enableRecording();utils_12.forEach(_this.definedRulesNames,function(currRuleName){var wrappedRule=_this[currRuleName];var originalGrammarAction=wrappedRule["originalGrammarAction"];var recordedRuleGast=void 0;_this.TRACE_INIT(currRuleName+" Rule",function(){recordedRuleGast=_this.topLevelRuleRecord(currRuleName,originalGrammarAction)});_this.gastProductionsCache[currRuleName]=recordedRuleGast})}finally{_this.disableRecording()}});var resolverErrors=[];_this.TRACE_INIT("Grammar Resolving",function(){resolverErrors=gast_resolver_public_1.resolveGrammar({rules:utils_12.values(_this.gastProductionsCache)});_this.definitionErrors=_this.definitionErrors.concat(resolverErrors)});_this.TRACE_INIT("Grammar Validations",function(){if(utils_12.isEmpty(resolverErrors)&&_this.skipValidations===false){var validationErrors=gast_resolver_public_1.validateGrammar({rules:utils_12.values(_this.gastProductionsCache),maxLookahead:_this.maxLookahead,tokenTypes:utils_12.values(_this.tokensMap),errMsgProvider:errors_public_12.defaultGrammarValidatorErrorProvider,grammarName:className});_this.definitionErrors=_this.definitionErrors.concat(validationErrors)}});if(utils_12.isEmpty(_this.definitionErrors)){if(_this.recoveryEnabled){_this.TRACE_INIT("computeAllProdsFollows",function(){var allFollows=follow_1.computeAllProdsFollows(utils_12.values(_this.gastProductionsCache));_this.resyncFollows=allFollows})}_this.TRACE_INIT("ComputeLookaheadFunctions",function(){_this.preComputeLookaheadFunctions(utils_12.values(_this.gastProductionsCache))})}if(!Parser3.DEFER_DEFINITION_ERRORS_HANDLING&&!utils_12.isEmpty(_this.definitionErrors)){defErrorsMsgs=utils_12.map(_this.definitionErrors,function(defError){return defError.message});throw new Error("Parser Definition Errors detected:\n "+defErrorsMsgs.join("\n-------------------------------\n"))}})};Parser3.DEFER_DEFINITION_ERRORS_HANDLING=false;return Parser3})();exports3.Parser=Parser2;apply_mixins_1.applyMixins(Parser2,[recoverable_12.Recoverable,looksahead_1.LooksAhead,tree_builder_1.TreeBuilder,lexer_adapter_1.LexerAdapter,recognizer_engine_1.RecognizerEngine,recognizer_api_1.RecognizerApi,error_handler_1.ErrorHandler,context_assist_1.ContentAssist,gast_recorder_1.GastRecorder,perf_tracer_1.PerformanceTracer]);var CstParser2=(function(_super){__extends2(CstParser3,_super);function CstParser3(tokenVocabulary,config){if(config===void 0){config=exports3.DEFAULT_PARSER_CONFIG}var _this=this;var configClone=utils_12.cloneObj(config);configClone.outputCst=true;_this=_super.call(this,tokenVocabulary,configClone)||this;return _this}return CstParser3})(Parser2);exports3.CstParser=CstParser2;var EmbeddedActionsParser=(function(_super){__extends2(EmbeddedActionsParser2,_super);function EmbeddedActionsParser2(tokenVocabulary,config){if(config===void 0){config=exports3.DEFAULT_PARSER_CONFIG}var _this=this;var configClone=utils_12.cloneObj(config);configClone.outputCst=false;_this=_super.call(this,tokenVocabulary,configClone)||this;return _this}return EmbeddedActionsParser2})(Parser2);exports3.EmbeddedActionsParser=EmbeddedActionsParser})(parser);var render_public={};Object.defineProperty(render_public,"__esModule",{value:true});render_public.createSyntaxDiagramsCode=void 0;var version_1=version;function createSyntaxDiagramsCode(grammar,_a){var _b=_a===void 0?{}:_a,_c=_b.resourceBase,resourceBase=_c===void 0?"https://unpkg.com/chevrotain@"+version_1.VERSION+"/diagrams/":_c,_d=_b.css,css=_d===void 0?"https://unpkg.com/chevrotain@"+version_1.VERSION+"/diagrams/diagrams.css":_d;var header='\n<!-- This is a generated file -->\n<!DOCTYPE html>\n<meta charset="utf-8">\n<style>\n body {\n background-color: hsl(30, 20%, 95%)\n }\n</style>\n\n';var cssHtml="\n<link rel='stylesheet' href='"+css+"'>\n";var scripts="\n<script src='"+resourceBase+"vendor/railroad-diagrams.js'></script>\n<script src='"+resourceBase+"src/diagrams_builder.js'></script>\n<script src='"+resourceBase+"src/diagrams_behavior.js'></script>\n<script src='"+resourceBase+"src/main.js'></script>\n";var diagramsDiv='\n<div id="diagrams" align="center"></div> \n';var serializedGrammar="\n<script>\n window.serializedGrammar = "+JSON.stringify(grammar,null," ")+";\n</script>\n";var initLogic='\n<script>\n var diagramsDiv = document.getElementById("diagrams");\n main.drawDiagramsFromSerializedGrammar(serializedGrammar, diagramsDiv);\n</script>\n';return header+cssHtml+scripts+diagramsDiv+serializedGrammar+initLogic}render_public.createSyntaxDiagramsCode=createSyntaxDiagramsCode;(function(exports3){Object.defineProperty(exports3,"__esModule",{value:true});exports3.Parser=exports3.createSyntaxDiagramsCode=exports3.clearCache=exports3.GAstVisitor=exports3.serializeProduction=exports3.serializeGrammar=exports3.Terminal=exports3.Rule=exports3.RepetitionWithSeparator=exports3.RepetitionMandatoryWithSeparator=exports3.RepetitionMandatory=exports3.Repetition=exports3.Option=exports3.NonTerminal=exports3.Alternative=exports3.Alternation=exports3.defaultLexerErrorProvider=exports3.NoViableAltException=exports3.NotAllInputParsedException=exports3.MismatchedTokenException=exports3.isRecognitionException=exports3.EarlyExitException=exports3.defaultParserErrorProvider=exports3.tokenName=exports3.tokenMatcher=exports3.tokenLabel=exports3.EOF=exports3.createTokenInstance=exports3.createToken=exports3.LexerDefinitionErrorType=exports3.Lexer=exports3.EMPTY_ALT=exports3.ParserDefinitionErrorType=exports3.EmbeddedActionsParser=exports3.CstParser=exports3.VERSION=void 0;var version_12=version;Object.defineProperty(exports3,"VERSION",{enumerable:true,get:function(){return version_12.VERSION}});var parser_12=parser;Object.defineProperty(exports3,"CstParser",{enumerable:true,get:function(){return parser_12.CstParser}});Object.defineProperty(exports3,"EmbeddedActionsParser",{enumerable:true,get:function(){return parser_12.EmbeddedActionsParser}});Object.defineProperty(exports3,"ParserDefinitionErrorType",{enumerable:true,get:function(){return parser_12.ParserDefinitionErrorType}});Object.defineProperty(exports3,"EMPTY_ALT",{enumerable:true,get:function(){return parser_12.EMPTY_ALT}});var lexer_public_12=lexer_public;Object.defineProperty(exports3,"Lexer",{enumerable:true,get:function(){return lexer_public_12.Lexer}});Object.defineProperty(exports3,"LexerDefinitionErrorType",{enumerable:true,get:function(){return lexer_public_12.LexerDefinitionErrorType}});var tokens_public_12=tokens_public;Object.defineProperty(exports3,"createToken",{enumerable:true,get:function(){return tokens_public_12.createToken}});Object.defineProperty(exports3,"createTokenInstance",{enumerable:true,get:function(){return tokens_public_12.createTokenInstance}});Object.defineProperty(exports3,"EOF",{enumerable:true,get:function(){return tokens_public_12.EOF}});Object.defineProperty(exports3,"tokenLabel",{enumerable:true,get:function(){return tokens_public_12.tokenLabel}});Object.defineProperty(exports3,"tokenMatcher",{enumerable:true,get:function(){return tokens_public_12.tokenMatcher}});Object.defineProperty(exports3,"tokenName",{enumerable:true,get:function(){return tokens_public_12.tokenName}});var errors_public_12=errors_public;Object.defineProperty(exports3,"defaultParserErrorProvider",{enumerable:true,get:function(){return errors_public_12.defaultParserErrorProvider}});var exceptions_public_12=exceptions_public;Object.defineProperty(exports3,"EarlyExitException",{enumerable:true,get:function(){return exceptions_public_12.EarlyExitException}});Object.defineProperty(exports3,"isRecognitionException",{enumerable:true,get:function(){return exceptions_public_12.isRecognitionException}});Object.defineProperty(exports3,"MismatchedTokenException",{enumerable:true,get:function(){return exceptions_public_12.MismatchedTokenException}});Object.defineProperty(exports3,"NotAllInputParsedException",{enumerable:true,get:function(){return exceptions_public_12.NotAllInputParsedException}});Object.defineProperty(exports3,"NoViableAltException",{enumerable:true,get:function(){return exceptions_public_12.NoViableAltException}});var lexer_errors_public_1=lexer_errors_public;Object.defineProperty(exports3,"defaultLexerErrorProvider",{enumerable:true,get:function(){return lexer_errors_public_1.defaultLexerErrorProvider}});var gast_public_12=gast_public;Object.defineProperty(exports3,"Alternation",{enumerable:true,get:function(){return gast_public_12.Alternation}});Object.defineProperty(exports3,"Alternative",{enumerable:true,get:function(){return gast_public_12.Alternative}});Object.defineProperty(exports3,"NonTerminal",{enumerable:true,get:function(){return gast_public_12.NonTerminal}});Object.defineProperty(exports3,"Option",{enumerable:true,get:function(){return gast_public_12.Option}});Object.defineProperty(exports3,"Repetition",{enumerable:true,get:function(){return gast_public_12.Repetition}});Object.defineProperty(exports3,"RepetitionMandatory",{enumerable:true,get:function(){return gast_public_12.RepetitionMandatory}});Object.defineProperty(exports3,"RepetitionMandatoryWithSeparator",{enumerable:true,get:function(){return gast_public_12.RepetitionMandatoryWithSeparator}});Object.defineProperty(exports3,"RepetitionWithSeparator",{enumerable:true,get:function(){return gast_public_12.RepetitionWithSeparator}});Object.defineProperty(exports3,"Rule",{enumerable:true,get:function(){return gast_public_12.Rule}});Object.defineProperty(exports3,"Terminal",{enumerable:true,get:function(){return gast_public_12.Terminal}});var gast_public_2=gast_public;Object.defineProperty(exports3,"serializeGrammar",{enumerable:true,get:function(){return gast_public_2.serializeGrammar}});Object.defineProperty(exports3,"serializeProduction",{enumerable:true,get:function(){return gast_public_2.serializeProduction}});var gast_visitor_public_12=gast_visitor_public;Object.defineProperty(exports3,"GAstVisitor",{enumerable:true,get:function(){return gast_visitor_public_12.GAstVisitor}});function clearCache(){console.warn("The clearCache function was 'soft' removed from the Chevrotain API.\n It performs no action other than printing this message.\n Please avoid using it as it will be completely removed in the future")}exports3.clearCache=clearCache;var render_public_1=render_public;Object.defineProperty(exports3,"createSyntaxDiagramsCode",{enumerable:true,get:function(){return render_public_1.createSyntaxDiagramsCode}});var Parser2=(function(){function Parser3(){throw new Error("The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. \nSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0")}return Parser3})();exports3.Parser=Parser2})(api$1);var mod=getDefaultExportFromCjs(api$1);mod.Alternation;mod.Alternative;const CstParser=mod.CstParser;mod.EMPTY_ALT;mod.EOF;mod.EarlyExitException;mod.EmbeddedActionsParser;mod.GAstVisitor;const Lexer=mod.Lexer;mod.LexerDefinitionErrorType;mod.MismatchedTokenException;mod.NoViableAltException;mod.NonTerminal;mod.NotAllInputParsedException;mod.Option;mod.Parser;mod.ParserDefinitionErrorType;mod.Repetition;mod.RepetitionMandatory;mod.RepetitionMandatoryWithSeparator;mod.RepetitionWithSeparator;mod.Rule;mod.Terminal;mod.VERSION;mod.clearCache;mod.createSyntaxDiagramsCode;const createToken$1=mod.createToken;mod.createTokenInstance;mod.defaultLexerErrorProvider;mod.defaultParserErrorProvider;mod.isRecognitionException;mod.serializeGrammar;mod.serializeProduction;mod.tokenLabel;mod.tokenMatcher;mod.tokenName;const fragments={};const f=fragments;function FRAGMENT(name,def){fragments[name]=typeof def==="string"?def:def.source}function makePattern(strings,...args){let combined="";for(let i=0;i<strings.length;i++){combined+=strings[i];if(i<args.length){let pattern=args[i];combined+=`(?:${pattern})`}}return new RegExp(combined)}const tokensDictionary={};function createToken(options){const newTokenType=createToken$1(options);tokensDictionary[options.name]=newTokenType;return newTokenType}FRAGMENT("NameStartChar","(:|[a-zA-Z]|_|\\u2070-\\u218F|\\u2C00-\\u2FEF|\\u3001-\\uD7FF|\\uF900-\\uFDCF|\\uFDF0-\\uFFFD)");FRAGMENT("NameChar",makePattern`${f.NameStartChar}|-|\\.|\\d|\\u00B7||[\\u0300-\\u036F]|[\\u203F-\\u2040]`);FRAGMENT("Name",makePattern`${f.NameStartChar}(${f.NameChar})*`);const WXS_START=createToken({name:"WXS_START",pattern:/<wxs/,push_mode:"WXS_INSIDE"});const COMMENT=createToken({name:"COMMENT",pattern:/<!--(.|\r?\n)*?-->/,line_breaks:true});const SEA_WS=createToken({name:"SEA_WS",pattern:/( |\t|\n|\r\n)+/});const SLASH_OPEN=createToken({name:"SLASH_OPEN",pattern:/<\//,push_mode:"INSIDE"});const INVALID_SLASH_OPEN=createToken({name:"INVALID_SLASH_OPEN",pattern:/<\//,categories:[SLASH_OPEN]});const OPEN=createToken({name:"OPEN",pattern:/</,push_mode:"INSIDE"});const INVALID_OPEN_INSIDE=createToken({name:"INVALID_OPEN_INSIDE",pattern:/</,categories:[OPEN]});const TEXT=createToken({name:"TEXT",pattern:/((?!(<|\{\{)).)+/});const INTPN=createToken({name:"INTPN",pattern:/((?!('|"|\}\})).)+/});const WXS_REG=/([^]*?)(?=<\/(( |\t|\n|\r\n)*)wxs(( |\t|\n|\r\n)*)>)/;const WXS_END=createToken({name:"WXS_END",pattern:/(?=<\/(( |\t|\n|\r\n)*)wxs(( |\t|\n|\r\n)*))>/,pop_mode:true});const WXS_CLOSE=createToken({name:"WXS_CLOSE",pattern:/(?!<\/(( |\t|\n|\r\n)*)wxs(( |\t|\n|\r\n)*))>/,push_mode:"WXS_CONTENT",longer_alt:WXS_END});const WXS_SLASH_CLOSE=createToken({name:"WXS_SLASH_CLOSE",pattern:/<\/(( |\t|\n|\r\n)*)wxs(( |\t|\n|\r\n)*)>/,pop_mode:true});const WXS_TEXT=createToken({name:"WXS_TEXT",pattern:WXS_REG,line_breaks:true});const INLINE_WXS_TEXT=createToken({name:"INLINE_WXS_TEXT",pattern:WXS_REG,line_breaks:true,pop_mode:true});const CLOSE=createToken({name:"CLOSE",pattern:/>/,pop_mode:true});const SLASH_CLOSE=createToken({name:"SLASH_CLOSE",pattern:/\/>/,pop_mode:true});const SLASH=createToken({name:"SLASH",pattern:/\//});const STRING=createToken({name:"STRING",pattern:/"[^"]*"|'[^']*'/});const MUSTACHE_LEFT=createToken({name:"MUSTACHE_LEFT",pattern:/\{\{/,push_mode:"INTPN_INSIDE"});const MUSTACHE_LEFT_IN_QUOTE=createToken({name:"MUSTACHE_LEFT_IN_QUOTE",pattern:/\{\{/,push_mode:"INTPN_IN_QUOTE"});const MUSTACHE_RIGHT=createToken({name:"MUSTACHE_RIGHT",pattern:/\}\}/,pop_mode:true});const MUSTACHE_RIGHT_IN_QUOTE=createToken({name:"MUSTACHE_RIGHT_IN_QUOTE",pattern:/\}\}/,pop_mode:true});const EQUALS=createToken({name:"EQUALS",pattern:/=/});const NAME=createToken({name:"NAME",pattern:makePattern`${f.Name}`});const SPACE=createToken({name:"SPACE",pattern:/[ \t\r\n]/,group:Lexer.SKIPPED});const PURE_STRING=createToken({name:"PURE_STRING",pattern:/"[^"^\{\{]*"|'[^'^\{\{]*'/});const PURE_STRING_IN_DOUBLE_QUOTE=createToken({name:"PURE_STRING_IN_DOUBLE_QUOTE",pattern:/[^"^\{\{^\}\}]+/});const PURE_STRING_IN_SINGLE_QUOTE=createToken({name:"PURE_STRING_IN_SINGLE_QUOTE",pattern:/[^'^\{\{^\}\}]+/});const DOUBLE_QUOTE_START=createToken({name:"DOUBLE_QUOTE_START",pattern:/"/,push_mode:"DOUBLE_QUOTE_STR_INSIDE"});const DOUBLE_QUOTE_END=createToken({name:"DOUBLE_QUOTE_END",pattern:/"/,pop_mode:true});const SINGLE_QUOTE_START=createToken({name:"SINGLE_QUOTE_START",pattern:/'/,push_mode:"SINGLE_QUOTE_STR_INSIDE"});const SINGLE_QUOTE_END=createToken({name:"SINGLE_QUOTE_END",pattern:/'/,pop_mode:true});const wxmlLexerDefinition={defaultMode:"OUTSIDE",modes:{OUTSIDE:[WXS_START,COMMENT,SEA_WS,SLASH_OPEN,OPEN,TEXT,MUSTACHE_LEFT,WXS_TEXT],INTPN_INSIDE:[MUSTACHE_RIGHT,INTPN,SEA_WS,STRING],DOUBLE_QUOTE_STR_INSIDE:[DOUBLE_QUOTE_END,MUSTACHE_LEFT_IN_QUOTE,PURE_STRING_IN_DOUBLE_QUOTE,SEA_WS],SINGLE_QUOTE_STR_INSIDE:[SINGLE_QUOTE_END,MUSTACHE_LEFT_IN_QUOTE,PURE_STRING_IN_SINGLE_QUOTE,SEA_WS],INTPN_IN_QUOTE:[MUSTACHE_RIGHT_IN_QUOTE,INTPN,STRING,SEA_WS],INSIDE:[COMMENT,INVALID_SLASH_OPEN,INVALID_OPEN_INSIDE,CLOSE,SLASH_CLOSE,SLASH,EQUALS,PURE_STRING,DOUBLE_QUOTE_START,SINGLE_QUOTE_START,NAME,SPACE],WXS_INSIDE:[WXS_SLASH_CLOSE,WXS_CLOSE,SLASH_CLOSE,SLASH,EQUALS,PURE_STRING,DOUBLE_QUOTE_START,SINGLE_QUOTE_START,NAME,SPACE,WXS_END],WXS_CONTENT:[INLINE_WXS_TEXT]}};const wxmlLexer=new Lexer(wxmlLexerDefinition,{positionTracking:"full",ensureOptimizations:false,lineTerminatorCharacters:["\n"],lineTerminatorsPattern:/\n|\r\n/g});class Parser extends CstParser{constructor(){super(tokensDictionary,{maxLookahead:1,recoveryEnabled:true,nodeLocationTracking:"full"});const $=this;$.RULE("document",()=>{$.MANY(()=>{$.OR([{ALT:()=>$.SUBRULE($.wxs)},{ALT:()=>$.SUBRULE($.element)},{ALT:()=>$.SUBRULE($.comment)},{ALT:()=>$.SUBRULE($.chardata)},{ALT:()=>$.SUBRULE($.interpolation)}])})});$.RULE("content",()=>{$.MANY(()=>{$.OR([{ALT:()=>$.SUBRULE($.wxs)},{ALT:()=>$.SUBRULE($.element)},{ALT:()=>$.SUBRULE($.interpolation)},{ALT:()=>$.SUBRULE($.chardata)},{ALT:()=>$.SUBRULE($.comment)}])})});$.RULE("comment",()=>{$.CONSUME(tokensDictionary.COMMENT)});$.RULE("wxs",()=>{$.CONSUME(tokensDictionary.WXS_START);$.MANY(()=>{$.SUBRULE($.attribute)});$.OR([{ALT:()=>{$.CONSUME(tokensDictionary.WXS_CLOSE,{LABEL:"START_CLOSE",ERR_MSG:"wxs element missing close '>'"});$.OPTION(()=>{$.SUBRULE($.wxscontent)});$.CONSUME(tokensDictionary.WXS_SLASH_CLOSE,{ERR_MSG:"wxs element missing slash open '</wxs>'"})}},{ALT:()=>{$.CONSUME(tokensDictionary.SLASH_CLOSE,{ERR_MSG:"wxs element missing slash close '/>'"})}}])});$.RULE("interpolation",()=>{$.CONSUME(tokensDictionary.MUSTACHE_LEFT);$.MANY(()=>{$.OR([{ALT:()=>$.CONSUME(tokensDictionary.INTPN)},{ALT:()=>$.CONSUME(tokensDictionary.STRING,{ERR_MSG:"wx interpolation unexpected string"})},{ALT:()=>$.CONSUME(tokensDictionary.SEA_WS)}])});$.CONSUME(tokensDictionary.MUSTACHE_RIGHT,{ERR_MSG:"wx interpolation unexpected end"})});$.RULE("element",()=>{$.CONSUME(tokensDictionary.OPEN);$.CONSUME(tokensDictionary.NAME);$.MANY(()=>{$.SUBRULE($.attribute)});$.OR([{ALT:()=>{$.CONSUME(tokensDictionary.CLOSE,{LABEL:"START_CLOSE",ERR_MSG:"wx element missing close '>'"});$.SUBRULE($.content);$.CONSUME(tokensDictionary.SLASH_OPEN,{ERR_MSG:"wx element missing slash open '</'"});$.CONSUME2(tokensDictionary.NAME,{LABEL:"END_NAME",ERR_MSG:"wx element missing end tag name"});$.CONSUME2(tokensDictionary.CLOSE,{LABEL:"END",ERR_MSG:"wx element missing end close '>'"})}},{ALT:()=>{$.CONSUME(tokensDictionary.SLASH_CLOSE,{ERR_MSG:"wx element missing slash close '/>'"})}}])});$.RULE("attribute",()=>{$.CONSUME(tokensDictionary.NAME);$.OPTION(()=>{$.OR([{ALT:()=>{$.CONSUME(tokensDictionary.EQUALS);$.SUBRULE($.attributeValue)}}])})});$.RULE("attributeValue",()=>{$.OR([{ALT:()=>$.CONSUME(tokensDictionary.PURE_STRING,{ERR_MSG:"wx attributes missing value"})},{ALT:()=>$.SUBRULE($.doubleQuoteAttributeVal)},{ALT:()=>$.SUBRULE($.singleQuoteAttributeVal)}])});$.RULE("doubleQuoteAttributeVal",()=>{$.CONSUME(tokensDictionary.DOUBLE_QUOTE_START,{ERR_MSG:"wx attributes unexpected start"});$.MANY(()=>{$.OR([{ALT:()=>$.CONSUME(tokensDictionary.PURE_STRING_IN_DOUBLE_QUOTE,{ERR_MSG:"wx attributes missing value"})},{ALT:()=>$.SUBRULE($.attributeValInterpolation)}])});$.CONSUME(tokensDictionary.DOUBLE_QUOTE_END,{ERR_MSG:"wx attribute value unexpected end"})});$.RULE("singleQuoteAttributeVal",()=>{$.CONSUME(tokensDictionary.SINGLE_QUOTE_START,{ERR_MSG:"wx attributes unexpected start"});$.MANY(()=>{$.OR([{ALT:()=>$.CONSUME(tokensDictionary.PURE_STRING_IN_SINGLE_QUOTE,{ERR_MSG:"wx attributes missing value"})},{ALT:()=>$.SUBRULE($.attributeValInterpolation)}])});$.CONSUME(tokensDictionary.SINGLE_QUOTE_END,{ERR_MSG:"wx attribute value unexpected end"})});$.RULE("attributeValInterpolation",()=>{$.CONSUME(tokensDictionary.MUSTACHE_LEFT_IN_QUOTE,{ERR_MSG:"wx interpolation in attributes value unexpected start"});$.MANY(()=>{$.OR([{ALT:()=>$.CONSUME(tokensDictionary.INTPN,{ERR_MSG:"wx interpolation in attributes unexpected intpn"})},{ALT:()=>$.CONSUME(tokensDictionary.STRING,{ERR_MSG:"wx interpolation in attributes unexpected string"})},{ALT:()=>$.CONSUME(tokensDictionary.SEA_WS,{ERR_MSG:"wx interpolation in attributes unexpected intpn"})}])});$.CONSUME(tokensDictionary.MUSTACHE_RIGHT_IN_QUOTE,{ERR_MSG:"wx interpolation in attribute value unexpected end"})});$.RULE("chardata",()=>{$.OR([{ALT:()=>$.CONSUME(tokensDictionary.TEXT)},{ALT:()=>$.CONSUME(tokensDictionary.SEA_WS)}])});$.RULE("wxscontent",()=>{$.MANY(()=>{$.CONSUME(tokensDictionary.SEA_WS)});$.OPTION(()=>{$.CONSUME(tokensDictionary.INLINE_WXS_TEXT)})});this.performSelfAnalysis()}}const wxmlParser=new Parser;const parse$1=text=>{const lexResult=wxmlLexer.tokenize(text);wxmlParser.input=lexResult.tokens;const cst2=wxmlParser.document();return{cst:cst2,tokenVector:lexResult.tokens,lexErrors:lexResult.errors,parseErrors:wxmlParser.errors}};const BaseWxmlCstVisitor=wxmlParser.getBaseCstVisitorConstructor();var freeGlobal=typeof global=="object"&&global&&global.Object===Object&&global;var freeGlobal$1=freeGlobal;var freeSelf=typeof self=="object"&&self&&self.Object===Object&&self;var root=freeGlobal$1||freeSelf||Function("return this")();var root$1=root;var Symbol2=root$1.Symbol;var Symbol$1=Symbol2;var objectProto$c=Object.prototype;var hasOwnProperty$9=objectProto$c.hasOwnProperty;var nativeObjectToString$1=objectProto$c.toString;var symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0;function getRawTag(value){var isOwn=hasOwnProperty$9.call(value,symToStringTag$1),tag=value[symToStringTag$1];try{value[symToStringTag$1]=void 0;var unmasked=true}catch(e){}var result=nativeObjectToString$1.call(value);if(unmasked){if(isOwn){value[symToStringTag$1]=tag}else{delete value[symToStringTag$1]}}return result}var objectProto$b=Object.prototype;var nativeObjectToString=objectProto$b.toString;function objectToString(value){return nativeObjectToString.call(value)}var nullTag="[object Null]",undefinedTag="[object Undefined]";var symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0;function baseGetTag(value){if(value==null){return value===void 0?undefinedTag:nullTag}return symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value)}function isObjectLike(value){return value!=null&&typeof value=="object"}var symbolTag$1="[object Symbol]";function isSymbol(value){return typeof value=="symbol"||isObjectLike(value)&&baseGetTag(value)==symbolTag$1}function arrayMap(array,iteratee){var index=-1,length=array==null?0:array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array)}return result}var isArray=Array.isArray;var isArray$1=isArray;var INFINITY$1=1/0;var symbolProto$1=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto$1?symbolProto$1.toString:void 0;function baseToString(value){if(typeof value=="string"){return value}if(isArray$1(value)){return arrayMap(value,baseToString)+""}if(isSymbol(value)){return symbolToString?symbolToString.call(value):""}var result=value+"";return result=="0"&&1/value==-INFINITY$1?"-0":result}function isObject(value){var type=typeof value;return value!=null&&(type=="object"||type=="function")}function identity(value){return value}var asyncTag="[object AsyncFunction]",funcTag$1="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(value){if(!isObject(value)){return false}var tag=baseGetTag(value);return tag==funcTag$1||tag==genTag||tag==asyncTag||tag==proxyTag}var coreJsData=root$1["__core-js_shared__"];var coreJsData$1=coreJsData;var maskSrcKey=(function(){var uid=/[^.]+$/.exec(coreJsData$1&&coreJsData$1.keys&&coreJsData$1.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""})();function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}var funcProto$1=Function.prototype;var funcToString$1=funcProto$1.toString;function toSource(func){if(func!=null){try{return funcToString$1.call(func)}catch(e){}try{return func+""}catch(e){}}return""}var reRegExpChar=/[\\^$.*+?()[\]{}|]/g;var reIsHostCtor=/^\[object .+?Constructor\]$/;var funcProto=Function.prototype,objectProto$a=Object.prototype;var funcToString=funcProto.toString;var hasOwnProperty$8=objectProto$a.hasOwnProperty;var reIsNative=RegExp("^"+funcToString.call(hasOwnProperty$8).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(value){if(!isObject(value)||isMasked(value)){return false}var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}function getValue(object,key){return object==null?void 0:object[key]}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}var WeakMap=getNative(root$1,"WeakMap");var WeakMap$1=WeakMap;function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var HOT_COUNT=800,HOT_SPAN=16;var nativeNow=Date.now;function shortOut(func){var count=0,lastCalled=0;return function(){var stamp=nativeNow(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return arguments[0]}}else{count=0}return func.apply(void 0,arguments)}}function constant(value){return function(){return value}}var defineProperty=(function(){try{var func=getNative(Object,"defineProperty");func({},"",{});return func}catch(e){}})();var defineProperty$1=defineProperty;var baseSetToString=!defineProperty$1?identity:function(func,string){return defineProperty$1(func,"toString",{"configurable":true,"enumerable":false,"value":constant(string),"writable":true})};var baseSetToString$1=baseSetToString;var setToString=shortOut(baseSetToString$1);var setToString$1=setToString;var MAX_SAFE_INTEGER$1=9007199254740991;var reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(value,length){var type=typeof value;length=length==null?MAX_SAFE_INTEGER$1:length;return!!length&&(type=="number"||type!="symbol"&&reIsUint.test(value))&&(value>-1&&value%1==0&&value<length)}function baseAssignValue(object,key,value){if(key=="__proto__"&&defineProperty$1){defineProperty$1(object,key,{"configurable":true,"enumerable":true,"value":value,"writable":true})}else{object[key]=value}}function eq(value,other){return value===other||value!==value&&other!==other}var objectProto$9=Object.prototype;var hasOwnProperty$7=objectProto$9.hasOwnProperty;function assignValue(object,key,value){var objValue=object[key];if(!(hasOwnProperty$7.call(object,key)&&eq(objValue,value))||value===void 0&&!(key in object)){baseAssignValue(object,key,value)}}var nativeMax=Math.max;function overRest(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index<length){array[index]=args[start+index]}index=-1;var otherArgs=Array(start+1);while(++index<start){otherArgs[index]=args[index]}otherArgs[start]=transform(array);return apply(func,this,otherArgs)}}function baseRest(func,start){return setToString$1(overRest(func,start,identity),func+"")}var MAX_SAFE_INTEGER=9007199254740991;function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"?isArrayLike(object)&&isIndex(index,object.length):type=="string"&&index in object){return eq(object[index],value)}return false}var objectProto$8=Object.prototype;function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=="function"&&Ctor.prototype||objectProto$8;return value===proto}function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index)}return result}var argsTag$2="[object Arguments]";function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag$2}var objectProto$7=Object.prototype;var hasOwnProperty$6=objectProto$7.hasOwnProperty;var propertyIsEnumerable$1=objectProto$7.propertyIsEnumerable;var isArguments=baseIsArguments((function(){return arguments})())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$6.call(value,"callee")&&!propertyIsEnumerable$1.call(value,"callee")};var isArguments$1=isArguments;function stubFalse(){return false}var freeExports$1=typeof exports2=="object"&&exports2&&!exports2.nodeType&&exports2;var freeModule$1=freeExports$1&&typeof module=="object"&&module&&!module.nodeType&&module;var moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1;var Buffer2=moduleExports$1?root$1.Buffer:void 0;var nativeIsBuffer=Buffer2?Buffer2.isBuffer:void 0;var isBuffer=nativeIsBuffer||stubFalse;var isBuffer$1=isBuffer;var argsTag$1="[object Arguments]",arrayTag$1="[object Array]",boolTag$1="[object Boolean]",dateTag$1="[object Date]",errorTag$1="[object Error]",funcTag="[object Function]",mapTag$2="[object Map]",numberTag$1="[object Number]",objectTag$2="[object Object]",regexpTag$1="[object RegExp]",setTag$2="[object Set]",stringTag$1="[object String]",weakMapTag$1="[object WeakMap]";var arrayBufferTag$1="[object ArrayBuffer]",dataViewTag$2="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]";var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag$1]=typedArrayTags[arrayTag$1]=typedArrayTags[arrayBufferTag$1]=typedArrayTags[boolTag$1]=typedArrayTags[dataViewTag$2]=typedArrayTags[dateTag$1]=typedArrayTags[errorTag$1]=typedArrayTags[funcTag]=typedArrayTags[mapTag$2]=typedArrayTags[numberTag$1]=typedArrayTags[objectTag$2]=typedArrayTags[regexpTag$1]=typedArrayTags[setTag$2]=typedArrayTags[stringTag$1]=typedArrayTags[weakMapTag$1]=false;function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}function baseUnary(func){return function(value){return func(value)}}var freeExports=typeof exports2=="object"&&exports2&&!exports2.nodeType&&exports2;var freeModule=freeExports&&typeof module=="object"&&module&&!module.nodeType&&module;var moduleExports=freeModule&&freeModule.exports===freeExports;var freeProcess=moduleExports&&freeGlobal$1.process;var nodeUtil=(function(){try{var types=freeModule&&freeModule.require&&freeModule.require("util").types;if(types){return types}return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}})();var nodeUtil$1=nodeUtil;var nodeIsTypedArray=nodeUtil$1&&nodeUtil$1.isTypedArray;var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;var isTypedArray$1=isTypedArray;var objectProto$6=Object.prototype;var hasOwnProperty$5=objectProto$6.hasOwnProperty;function arrayLikeKeys(value,inherited){var isArr=isArray$1(value),isArg=!isArr&&isArguments$1(value),isBuff=!isArr&&!isArg&&isBuffer$1(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray$1(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value){if((inherited||hasOwnProperty$5.call(value,key))&&!(skipIndexes&&(key=="length"||isBuff&&(key=="offset"||key=="parent")||isType&&(key=="buffer"||key=="byteLength"||key=="byteOffset")||isIndex(key,length)))){result.push(key)}}return result}function overArg(func,transform){return function(arg){return func(transform(arg))}}var nativeKeys=overArg(Object.keys,Object);var nativeKeys$1=nativeKeys;var objectProto$5=Object.prototype;var hasOwnProperty$4=objectProto$5.hasOwnProperty;function baseKeys(object){if(!isPrototype(object)){return nativeKeys$1(object)}var result=[];for(var key in Object(object)){if(hasOwnProperty$4.call(object,key)&&key!="constructor"){result.push(key)}}return result}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/;function isKey(value,object){if(isArray$1(value)){return false}var type=typeof value;if(type=="number"||type=="symbol"||type=="boolean"||value==null||isSymbol(value)){return true}return reIsPlainProp.test(value)||!reIsDeepProp.test(value)||object!=null&&value in Object(object)}var nativeCreate=getNative(Object,"create");var nativeCreate$1=nativeCreate;function hashClear(){this.__data__=nativeCreate$1?nativeCreate$1(null):{};this.size=0}function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];this.size-=result?1:0;return result}var HASH_UNDEFINED$2="__lodash_hash_undefined__";var objectProto$4=Object.prototype;var hasOwnProperty$3=objectProto$4.hasOwnProperty;function hashGet(key){var data=this.__data__;if(nativeCreate$1){var result=data[key];return result===HASH_UNDEFINED$2?void 0:result}return hasOwnProperty$3.call(data,key)?data[key]:void 0}var objectProto$3=Object.prototype;var hasOwnProperty$2=objectProto$3.hasOwnProperty;function hashHas(key){var data=this.__data__;return nativeCreate$1?data[key]!==void 0:hasOwnProperty$2.call(data,key)}var HASH_UNDEFINED$1="__lodash_hash_undefined__";function hashSet(key,value){var data=this.__data__;this.size+=this.has(key)?0:1;data[key]=nativeCreate$1&&value===void 0?HASH_UNDEFINED$1:value;return this}function Hash(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1])}}Hash.prototype.clear=hashClear;Hash.prototype["delete"]=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;function listCacheClear(){this.__data__=[];this.size=0}function assocIndexOf(array,key){var length=array.length;while(length--){if(eq(array[length][0],key)){return length}}return-1}var arrayProto=Array.prototype;var splice=arrayProto.splice;function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){return false}var lastIndex=data.length-1;if(index==lastIndex){data.pop()}else{splice.call(data,index,1)}--this.size;return true}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value])}else{data[index][1]=value}return this}function ListCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1])}}ListCache.prototype.clear=listCacheClear;ListCache.prototype["delete"]=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;var Map$1=getNative(root$1,"Map");var Map$2=Map$1;function mapCacheClear(){this.size=0;this.__data__={"hash":new Hash,"map":new(Map$2||ListCache),"string":new Hash}}function isKeyable(value){var type=typeof value;return type=="string"||type=="number"||type=="symbol"||type=="boolean"?value!=="__proto__":value===null}function getMapData(map2,key){var data=map2.__data__;return isKeyable(key)?data[typeof key=="string"?"string":"hash"]:data.map}function mapCacheDelete(key){var result=getMapData(this,key)["delete"](key);this.size-=result?1:0;return result}function mapCacheGet(key){return getMapData(this,key).get(key)}function mapCacheHas(key){return getMapData(this,key).has(key)}function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;data.set(key,value);this.size+=data.size==size?0:1;return this}function MapCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1])}}MapCache.prototype.clear=mapCacheClear;MapCache.prototype["delete"]=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;var FUNC_ERROR_TEXT="Expected a function";function memoize(func,resolver2){if(typeof func!="function"||resolver2!=null&&typeof resolver2!="function"){throw new TypeError(FUNC_ERROR_TEXT)}var memoized=function(){var args=arguments,key=resolver2?resolver2.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key)}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result};memoized.cache=new(memoize.Cache||MapCache);return memoized}memoize.Cache=MapCache;var MAX_MEMOIZE_SIZE=500;function memoizeCapped(func){var result=memoize(func,function(key){if(cache.size===MAX_MEMOIZE_SIZE){cache.clear()}return key});var cache=result.cache;return result}var rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;var reEscapeChar=/\\(\\)?/g;var stringToPath=memoizeCapped(function(string){var result=[];if(string.charCodeAt(0)===46){result.push("")}string.replace(rePropName,function(match,number,quote2,subString){result.push(quote2?subString.replace(reEscapeChar,"$1"):number||match)});return result});var stringToPath$1=stringToPath;function toString(value){return value==null?"":baseToString(value)}function castPath(value,object){if(isArray$1(value)){return value}return isKey(value,object)?[value]:stringToPath$1(toString(value))}var INFINITY=1/0;function toKey(value){if(typeof value=="string"||isSymbol(value)){return value}var result=value+"";return result=="0"&&1/value==-INFINITY?"-0":result}function baseGet(object,path){path=castPath(path,object);var index=0,length=path.length;while(object!=null&&index<length){object=object[toKey(path[index++])]}return index&&index==length?object:void 0}function get(object,path,defaultValue){var result=object==null?void 0:baseGet(object,path);return result===void 0?defaultValue:result}function arrayPush(array,values2){var index=-1,length=values2.length,offset=array.length;while(++index<length){array[offset+index]=values2[index]}return array}var spreadableSymbol=Symbol$1?Symbol$1.isConcatSpreadable:void 0;function isFlattenable(value){return isArray$1(value)||isArguments$1(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;predicate||(predicate=isFlattenable);result||(result=[]);while(++index<length){var value=array[index];if(depth>0&&predicate(value)){if(depth>1){baseFlatten(value,depth-1,predicate,isStrict,result)}else{arrayPush(result,value)}}else if(!isStrict){result[result.length]=value}}return result}function flatten(array){var length=array==null?0:array.length;return length?baseFlatten(array,1):[]}function flatRest(func){return setToString$1(overRest(func,void 0,flatten),func+"")}function stackClear(){this.__data__=new ListCache;this.size=0}function stackDelete(key){var data=this.__data__,result=data["delete"](key);this.size=data.size;return result}function stackGet(key){return this.__data__.get(key)}function stackHas(key){return this.__data__.has(key)}var LARGE_ARRAY_SIZE=200;function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map$2||pairs.length<LARGE_ARRAY_SIZE-1){pairs.push([key,value]);this.size=++data.size;return this}data=this.__data__=new MapCache(pairs)}data.set(key,value);this.size=data.size;return this}function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size}Stack.prototype.clear=stackClear;Stack.prototype["delete"]=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;function arrayFilter(array,predicate){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[resIndex++]=value}}return result}function stubArray(){return[]}var objectProto$2=Object.prototype;var propertyIsEnumerable=objectProto$2.propertyIsEnumerable;var nativeGetSymbols=Object.getOwnPropertySymbols;var getSymbols=!nativeGetSymbols?stubArray:function(object){if(object==null){return[]}object=Object(object);return arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)})};var getSymbols$1=getSymbols;function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray$1(object)?result:arrayPush(result,symbolsFunc(object))}function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols$1)}var DataView=getNative(root$1,"DataView");var DataView$1=DataView;var Promise$1=getNative(root$1,"Promise");var Promise$2=Promise$1;var Set2=getNative(root$1,"Set");var Set$1=Set2;var mapTag$1="[object Map]",objectTag$1="[object Object]",promiseTag="[object Promise]",setTag$1="[object Set]",weakMapTag="[object WeakMap]";var dataViewTag$1="[object DataView]";var dataViewCtorString=toSource(DataView$1),mapCtorString=toSource(Map$2),promiseCtorString=toSource(Promise$2),setCtorString=toSource(Set$1),weakMapCtorString=toSource(WeakMap$1);var getTag=baseGetTag;if(DataView$1&&getTag(new DataView$1(new ArrayBuffer(1)))!=dataViewTag$1||Map$2&&getTag(new Map$2)!=mapTag$1||Promise$2&&getTag(Promise$2.resolve())!=promiseTag||Set$1&&getTag(new Set$1)!=setTag$1||WeakMap$1&&getTag(new WeakMap$1)!=weakMapTag){getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag$1?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString){switch(ctorString){case dataViewCtorString:return dataViewTag$1;case mapCtorString:return mapTag$1;case promiseCtorString:return promiseTag;case setCtorString:return setTag$1;case weakMapCtorString:return weakMapTag}}return result}}var getTag$1=getTag;var Uint8Array2=root$1.Uint8Array;var Uint8Array$1=Uint8Array2;var HASH_UNDEFINED="__lodash_hash_undefined__";function setCacheAdd(value){this.__data__.set(value,HASH_UNDEFINED);return this}function setCacheHas(value){return this.__data__.has(value)}function SetCache(values2){var index=-1,length=values2==null?0:values2.length;this.__data__=new MapCache;while(++index<length){this.add(values2[index])}}SetCache.prototype.add=SetCache.prototype.push=setCacheAdd;SetCache.prototype.has=setCacheHas;function arraySome(array,predicate){var index=-1,length=array==null?0:array.length;while(++index<length){if(predicate(array[index],index,array)){return true}}return false}function cacheHas(cache,key){return cache.has(key)}var COMPARE_PARTIAL_FLAG$5=1,COMPARE_UNORDERED_FLAG$3=2;function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG$5,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength)){return false}var arrStacked=stack.get(array);var othStacked=stack.get(other);if(arrStacked&&othStacked){return arrStacked==other&&othStacked==array}var index=-1,result=true,seen=bitmask&COMPARE_UNORDERED_FLAG$3?new SetCache:void 0;stack.set(array,other);stack.set(other,array);while(++index<arrLength){var arrValue=array[index],othValue=other[index];if(customizer){var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack)}if(compared!==void 0){if(compared){continue}result=false;break}if(seen){if(!arraySome(other,function(othValue2,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue2||equalFunc(arrValue,othValue2,bitmask,customizer,stack))){return seen.push(othIndex)}})){result=false;break}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){result=false;break}}stack["delete"](array);stack["delete"](other);return result}function mapToArray(map2){var index=-1,result=Array(map2.size);map2.forEach(function(value,key){result[++index]=[key,value]});return result}function setToArray(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=value});return result}var COMPARE_PARTIAL_FLAG$4=1,COMPARE_UNORDERED_FLAG$2=2;var boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",mapTag="[object Map]",numberTag="[object Number]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]";var arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]";var symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;function equalByTag(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case dataViewTag:if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset){return false}object=object.buffer;other=other.buffer;case arrayBufferTag:if(object.byteLength!=other.byteLength||!equalFunc(new Uint8Array$1(object),new Uint8Array$1(other))){return false}return true;case boolTag:case dateTag:case numberTag:return eq(+object,+other);case errorTag:return object.name==other.name&&object.message==other.message;case regexpTag:case stringTag:return object==other+"";case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&COMPARE_PARTIAL_FLAG$4;convert||(convert=setToArray);if(object.size!=other.size&&!isPartial){return false}var stacked=stack.get(object);if(stacked){return stacked==other}bitmask|=COMPARE_UNORDERED_FLAG$2;stack.set(object,other);var result=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);stack["delete"](object);return result;case symbolTag:if(symbolValueOf){return symbolValueOf.call(object)==symbolValueOf.call(other)}}return false}var COMPARE_PARTIAL_FLAG$3=1;var objectProto$1=Object.prototype;var hasOwnProperty$1=objectProto$1.hasOwnProperty;function equalObjects(object,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG$3,objProps=getAllKeys(object),objLength=objProps.length,othProps=getAllKeys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial){return false}var index=objLength;while(index--){var key=objProps[index];if(!(isPartial?key in other:hasOwnProperty$1.call(other,key))){return false}}var objStacked=stack.get(object);var othStacked=stack.get(other);if(objStacked&&othStacked){return objStacked==other&&othStacked==object}var result=true;stack.set(object,other);stack.set(other,object);var skipCtor=isPartial;while(++index<objLength){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer){var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack)}if(!(compared===void 0?objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack):compared)){result=false;break}skipCtor||(skipCtor=key=="constructor")}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&("constructor"in object&&"constructor"in other)&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)){result=false}}stack["delete"](object);stack["delete"](other);return result}var COMPARE_PARTIAL_FLAG$2=1;var argsTag="[object Arguments]",arrayTag="[object Array]",objectTag="[object Object]";var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function baseIsEqualDeep(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray$1(object),othIsArr=isArray$1(other),objTag=objIsArr?arrayTag:getTag$1(object),othTag=othIsArr?arrayTag:getTag$1(other);objTag=objTag==argsTag?objectTag:objTag;othTag=othTag==argsTag?objectTag:othTag;var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer$1(object)){if(!isBuffer$1(other)){return false}objIsArr=true;objIsObj=false}if(isSameTag&&!objIsObj){stack||(stack=new Stack);return objIsArr||isTypedArray$1(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack)}if(!(bitmask&COMPARE_PARTIAL_FLAG$2)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othIsWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;stack||(stack=new Stack);return equalFunc(objUnwrapped,othUnwrapped,bitmask,customizer,stack)}}if(!isSameTag){return false}stack||(stack=new Stack);return equalObjects(object,other,bitmask,customizer,equalFunc,stack)}function baseIsEqual(value,other,bitmask,customizer,stack){if(value===other){return true}if(value==null||other==null||!isObjectLike(value)&&!isObjectLike(other)){return value!==value&&other!==other}return baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack)}var COMPARE_PARTIAL_FLAG$1=1,COMPARE_UNORDERED_FLAG$1=2;function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(object==null){return!length}object=Object(object);while(index--){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object)){return false}}while(++index<length){data=matchData[index];var key=data[0],objValue=object[key],srcValue=data[1];if(noCustomizer&&data[2]){if(objValue===void 0&&!(key in object)){return false}}else{var stack=new Stack;if(customizer){var result=customizer(objValue,srcValue,key,object,source,stack)}if(!(result===void 0?baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG$1|COMPARE_UNORDERED_FLAG$1,customizer,stack):result)){return false}}}return true}function isStrictComparable(value){return value===value&&!isObject(value)}function getMatchData(object){var result=keys(object),length=result.length;while(length--){var key=result[length],value=object[key];result[length]=[key,value,isStrictComparable(value)]}return result}function matchesStrictComparable(key,srcValue){return function(object){if(object==null){return false}return object[key]===srcValue&&(srcValue!==void 0||key in Object(object))}}function baseMatches(source){var matchData=getMatchData(source);if(matchData.length==1&&matchData[0][2]){return matchesStrictComparable(matchData[0][0],matchData[0][1])}return function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseHasIn(object,key){return object!=null&&key in Object(object)}function hasPath(object,path,hasFunc){path=castPath(path,object);var index=-1,length=path.length,result=false;while(++index<length){var key=toKey(path[index]);if(!(result=object!=null&&hasFunc(object,key))){break}object=object[key]}if(result||++index!=length){return result}length=object==null?0:object.length;return!!length&&isLength(length)&&isIndex(key,length)&&(isArray$1(object)||isArguments$1(object))}function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn)}var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;function baseMatchesProperty(path,srcValue){if(isKey(path)&&isStrictComparable(srcValue)){return matchesStrictComparable(toKey(path),srcValue)}return function(object){var objValue=get(object,path);return objValue===void 0&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG)}}function baseProperty(key){return function(object){return object==null?void 0:object[key]}}function basePropertyDeep(path){return function(object){return baseGet(object,path)}}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}function baseIteratee(value){if(typeof value=="function"){return value}if(value==null){return identity}if(typeof value=="object"){return isArray$1(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value)}return property(value)}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;while(length--){var key=props[fromRight?length:++index];if(iteratee(iterable[key],key,iterable)===false){break}}return object}}var baseFor=createBaseFor();var baseFor$1=baseFor;function baseForOwn(object,iteratee){return object&&baseFor$1(object,iteratee,keys)}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){if(collection==null){return collection}if(!isArrayLike(collection)){return eachFunc(collection,iteratee)}var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);while(fromRight?index--:++index<length){if(iteratee(iterable[index],index,iterable)===false){break}}return collection}}var baseEach=createBaseEach(baseForOwn);var baseEach$1=baseEach;function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];baseEach$1(collection,function(value,key,collection2){result[++index]=iteratee(value,key,collection2)});return result}function map(collection,iteratee){var func=isArray$1(collection)?arrayMap:baseMap;return func(collection,baseIteratee(iteratee))}function baseSet(object,path,value,customizer){if(!isObject(object)){return object}path=castPath(path,object);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++index<length){var key=toKey(path[index]),newValue=value;if(key==="__proto__"||key==="constructor"||key==="prototype"){return object}if(index!=lastIndex){var objValue=nested[key];newValue=customizer?customizer(objValue,key,nested):void 0;if(newValue===void 0){newValue=isObject(objValue)?objValue:isIndex(path[index+1])?[]:{}}}assignValue(nested,key,newValue);nested=nested[key]}return object}function basePickBy(object,paths,predicate){var index=-1,length=paths.length,result={};while(++index<length){var path=paths[index],value=baseGet(object,path);if(predicate(value,path)){baseSet(result,castPath(path,object),value)}}return result}function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value}return array}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==void 0,valIsNull=value===null,valIsReflexive=value===value,valIsSymbol=isSymbol(value);var othIsDefined=other!==void 0,othIsNull=other===null,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive){return 1}if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value<other||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive){return-1}}return 0}function compareMultiple(object,other,orders){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;while(++index<length){var result=compareAscending(objCriteria[index],othCriteria[index]);if(result){if(index>=ordersLength){return result}var order=orders[index];return result*(order=="desc"?-1:1)}}return object.index-other.index}function baseOrderBy(collection,iteratees,orders){if(iteratees.length){iteratees=arrayMap(iteratees,function(iteratee){if(isArray$1(iteratee)){return function(value){return baseGet(value,iteratee.length===1?iteratee[0]:iteratee)}}return iteratee})}else{iteratees=[identity]}var index=-1;iteratees=arrayMap(iteratees,baseUnary(baseIteratee));var result=baseMap(collection,function(value,key,collection2){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{"criteria":criteria,"index":++index,"value":value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,paths){return basePickBy(object,paths,function(value,path){return hasIn(object,path)})}var pick=flatRest(function(object,paths){return object==null?{}:basePick(object,paths)});var pick$1=pick;var sortBy=baseRest(function(collection,iteratees){if(collection==null){return[]}var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[]}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees=[iteratees[0]]}return baseOrderBy(collection,baseFlatten(iteratees,1),[])});var sortBy$1=sortBy;function sortASTNode(nodes){nodes.forEach(node=>{});let sortedNodes=[];sortedNodes=nodes.sort((nodeA,nodeB)=>{if(nodeA.loc.start.line>nodeB.loc.start.line||nodeA.loc.start.line===nodeB.loc.start.line&&nodeA.loc.start.column>nodeB.loc.start.column){return 1}else{return-1}});return sortedNodes}function sortTokenChildren(tokensArr){let tokens2=[];let sortedTokens=[];Object.keys(tokensArr).forEach(key=>{tokens2.push(...tokensArr[key])});sortedTokens=tokens2.sort((nodeA,nodeB)=>{if(nodeA.startLine>nodeB.startLine||nodeA.startLine===nodeB.startLine&&nodeA.startColumn>nodeB.startColumn){return 1}else{return-1}});return sortedTokens}function sortCstChildren(ctx){let child=[];let sortedChild=[];Object.keys(ctx).forEach(key=>{child.push(...ctx[key])});sortedChild=child.filter(node=>node.location).sort((nodeA,nodeB)=>{if(nodeA.location.startLine>nodeB.location.startLine||nodeA.location.startLine===nodeB.location.startLine&&nodeA.location.startColumn>nodeB.location.startColumn){return 1}else{return-1}});return sortedChild}function mergeLocation(astNode,location){Object.assign(astNode,{start:location.startOffset,end:location.endOffset,loc:{start:{line:location.startLine,column:location.startColumn},end:{line:location.endLine,column:location.endColumn}},range:[location.startOffset,location.endOffset]})}function parseInlineJS(astNode){let espreeParser;if(!(astNode===null||astNode===void 0?void 0:astNode.value)){return}try{espreeParser=__require("espree")}catch(_){}if(espreeParser){try{const wxsOffset=astNode.startTag?astNode.startTag.loc.end:astNode.loc.start;const appendStr="\n".repeat(wxsOffset.line-1)+" ".repeat(wxsOffset.column);const espreeAst=espreeParser.parse(appendStr+astNode.value,{loc:true,range:true,comment:true,ecmaVersion:2015});espreeAst.type="WXScriptProgram";espreeAst.offset=[];astNode.body=[espreeAst]}catch(e){const error=e;astNode.error={type:"WXScriptError",value:error.message,start:astNode.start,end:astNode.end,loc:{start:{line:error.lineNumber,column:error.column},end:{line:error.lineNumber,column:error.column}},range:[astNode.start,astNode.end]}}}}function convertLexerErrorToNode(error){return{type:"WXLexerError",value:error.message,start:error.offset,end:error.offset+error.length,loc:{start:{line:error.line,column:error.column},end:{line:error.line,column:error.column}},range:[error.offset,error.length]}}function convertParseErrorToNode(error){const token=error.token.image?error.token:error.previousToken;return{type:"WXParseError",value:error.message,rawType:error.name,start:token.startOffset,end:token.endOffset,loc:{start:{line:token.startLine,column:token.startColumn},end:{line:token.endLine,column:token.endColumn}},range:[token.startOffset,token.endOffset]}}class CstToAstVisitor extends BaseWxmlCstVisitor{constructor(){super()}setState({tokenVector,eslintMode}){this.tokenVector=tokenVector;this.eslintMode=eslintMode}visit(cstNode,params={}){return super.visit(cstNode,Object.assign({location:cstNode.location},params))}document(ctx,{location,lexErrors,parseErrors}){const child=sortCstChildren(ctx);const astNode={type:"Program",body:child.map(node=>this.visit(node)),comments:[],errors:[...(lexErrors||[]).map(convertLexerErrorToNode),...(parseErrors||[]).map(convertParseErrorToNode)],tokens:[]};mergeLocation(astNode,location);return astNode}wxs(ctx,{location}){var _a,_b,_c,_d,_e,_f,_g,_h,_j;const astNode={type:"WXScript",name:"wxs",value:null,startTag:null,endTag:null};if(((_a=ctx.WXS_START)===null||_a===void 0?void 0:_a[0])&&(((_b=ctx.START_CLOSE)===null||_b===void 0?void 0:_b[0])||((_c=ctx.SLASH_CLOSE)===null||_c===void 0?void 0:_c[0]))){const startTagLocation=Object.assign(Object.assign({},pick$1((_d=ctx.WXS_START)===null||_d===void 0?void 0:_d[0],["startOffset","startLine","startColumn"])),pick$1(((_e=ctx.START_CLOSE)===null||_e===void 0?void 0:_e[0])||((_f=ctx.SLASH_CLOSE)===null||_f===void 0?void 0:_f[0]),["endOffset","endLine","endColumn"]));astNode.startTag={type:"WXStartTag",name:"wxs",attributes:ctx.attribute?map(ctx.attribute,this.visit.bind(this)):[],selfClosing:!!ctx.SLASH_CLOSE};mergeLocation(astNode.startTag,startTagLocation)}if((_g=ctx.WXS_SLASH_CLOSE)===null||_g===void 0?void 0:_g[0]){astNode.endTag={type:"WXEndTag",name:"wxs"};const endTagLocation=pick$1(ctx.WXS_SLASH_CLOSE[0],["startOffset","startLine","startColumn","endOffset","endLine","endColumn"]);mergeLocation(astNode.endTag,endTagLocation)}mergeLocation(astNode,location);if((_h=ctx.wxscontent)===null||_h===void 0?void 0:_h[0]){astNode.value=this.visit.bind(this)((_j=ctx.wxscontent)===null||_j===void 0?void 0:_j[0]);if(this.eslintMode){parseInlineJS(astNode)}}return astNode}wxscontent(ctx,{location}){let allTokens=[];if(ctx.SEA_WS!==void 0){allTokens=allTokens.concat(ctx.SEA_WS)}if(ctx.INLINE_WXS_TEXT!==void 0){allTokens=allTokens.concat(ctx.INLINE_WXS_TEXT)}const sortedTokens=sortBy$1(allTokens,["startOffset"]);const fullText=map(sortedTokens,"image").join("");return fullText}attribute(ctx,{location}){const attributeValue=ctx.attributeValue?this.visit(ctx.attributeValue[0]):null;const astNode=Object.assign({type:"WXAttribute",key:ctx.NAME[0].image,quote:null,value:null,rawValue:null},attributeValue||{});mergeLocation(astNode,location);return astNode}attributeValue(ctx,{location}){if(ctx.PURE_STRING!==void 0){const raw=ctx.PURE_STRING[0].image;const astNode={value:raw.split("").slice(1,raw.length-1).join(""),rawValue:ctx.PURE_STRING[0].image,children:[],interpolations:[],quote:(raw===null||raw===void 0?void 0:raw.length)?raw.slice(0,1):null};mergeLocation(astNode,location);return astNode}else if(ctx.doubleQuoteAttributeVal!==void 0){return this.visit(ctx.doubleQuoteAttributeVal[0])}else if(ctx.singleQuoteAttributeVal!==void 0){return this.visit(ctx.singleQuoteAttributeVal[0])}}doubleQuoteAttributeVal(ctx,{location}){const interpolationASTS=map(ctx.attributeValInterpolation,this.visit.bind(this));const quote2='"';let strASTs=map(ctx.PURE_STRING_IN_DOUBLE_QUOTE,item=>{const astNode2={value:item.image,type:"WXText"};mergeLocation(astNode2,item);return astNode2});const sortedValue=sortASTNode(interpolationASTS.concat(strASTs));const value=sortedValue.map(v=>v.rawValue||v.value).join("");const astNode={value,rawValue:quote2+value+quote2,children:sortedValue,interpolations:interpolationASTS.map(intp=>{return Object.assign(Object.assign({},intp),{type:"WXInterpolation"})}),quote:quote2};mergeLocation(astNode,location);return astNode}attributeValInterpolation(ctx,{location}){const child=sortTokenChildren(ctx);const value=(child||[]).map(token=>token.image).join("");const astNode={type:"WXAttributeInterpolation",rawValue:value,value:value.replace(/^{{/,"").replace(/}}$/,"")};mergeLocation(astNode,location);return astNode}singleQuoteAttributeVal(ctx,{location}){const interpolationASTS=map(ctx.attributeValInterpolation,this.visit.bind(this));const quote2="'";let strASTs=map(ctx.PURE_STRING_IN_SINGLE_QUOTE,item=>{const astNode2={value:item.image,type:"WXText"};mergeLocation(astNode2,item);return astNode2});const sortedValue=sortASTNode(interpolationASTS.concat(strASTs));const value=sortedValue.map(v=>v.rawValue||v.value).join("");const astNode={value,rawValue:quote2+value+quote2,children:sortedValue,interpolations:interpolationASTS.map(intp=>{return Object.assign(Object.assign({},intp),{type:"WXInterpolation"})}),quote:quote2};mergeLocation(astNode,location);return astNode}interpolation(ctx,{location}){const child=sortTokenChildren(ctx);const value=(child||[]).map(token=>token.image).join("");const astNode={type:"WXInterpolation",rawValue:value,value:value.replace(/^{{/,"").replace(/}}$/,"")};mergeLocation(astNode,location);return astNode}content(ctx){const child=sortCstChildren(ctx);return child.map(node=>this.visit(node))}comment(ctx,{location}){const astNode={type:"WXComment",value:(ctx.COMMENT[0].image||"").replace(/^<!--/,"").replace(/-->$/,"")};mergeLocation(astNode,location);return astNode}element(ctx,{location}){var _a,_b,_c,_d,_e,_f,_g,_h;const astNode={type:"WXElement",name:ctx.NAME[0].image,children:[],startTag:null,endTag:null};if(((_a=ctx.OPEN)===null||_a===void 0?void 0:_a[0])&&(((_b=ctx.START_CLOSE)===null||_b===void 0?void 0:_b[0])||((_c=ctx.SLASH_CLOSE)===null||_c===void 0?void 0:_c[0]))){astNode.startTag={type:"WXStartTag",name:astNode.name,attributes:ctx.attribute?map(ctx.attribute,this.visit.bind(this)):[],selfClosing:!!ctx.SLASH_CLOSE};const startTagLocation=Object.assign(Object.assign({},pick$1((_d=ctx.OPEN)===null||_d===void 0?void 0:_d[0],["startOffset","startLine","startColumn"])),pick$1(((_e=ctx.START_CLOSE)===null||_e===void 0?void 0:_e[0])||((_f=ctx.SLASH_CLOSE)===null||_f===void 0?void 0:_f[0]),["endOffset","endLine","endColumn"]));mergeLocation(astNode.startTag,startTagLocation)}if(((_g=ctx.SLASH_OPEN)===null||_g===void 0?void 0:_g[0])&&((_h=ctx.END)===null||_h===void 0?void 0:_h[0])){astNode.endTag={type:"WXEndTag",name:get(ctx,"END_NAME[0].image")};const endTagLocation=Object.assign(Object.assign({},pick$1(ctx.SLASH_OPEN[0],["startOffset","startLine","startColumn"])),pick$1(ctx.END[0],["endOffset","endLine","endColumn"]));mergeLocation(astNode.endTag,endTagLocation)}if(ctx.content!==void 0){astNode.children=this.visit(ctx.content[0])}mergeLocation(astNode,location);return astNode}chardata(ctx,{location}){const astNode={type:"WXText",value:null};let allTokens=[];if(ctx.SEA_WS!==void 0){allTokens=allTokens.concat(ctx.SEA_WS)}if(ctx.TEXT!==void 0){allTokens=allTokens.concat(ctx.TEXT)}const sortedTokens=sortBy$1(allTokens,["startOffset"]);const fullText=map(sortedTokens,"image").join("");astNode.value=fullText;mergeLocation(astNode,location);return astNode}}const AstBuilder=new CstToAstVisitor;function buildAst(docCst,tokenVector,lexErrors,parseErrors,eslintMode){AstBuilder.setState({tokenVector,eslintMode});const wxmlDocAst=AstBuilder.visit(docCst,{lexErrors,parseErrors});return wxmlDocAst}function parse2(code){const{cst:cst2,tokenVector,lexErrors,parseErrors}=parse$1(code);return buildAst(cst2,tokenVector,lexErrors,parseErrors)}function parseForESLint(code){const{cst:cst2,tokenVector,lexErrors,parseErrors}=parse$1(code);return{ast:buildAst(cst2,tokenVector,lexErrors,parseErrors,true),services:{},scopeManager:null,visitorKeys:{Program:["errors","body"]}}}exports2.parse=parse2;exports2.parseForESLint=parseForESLint;Object.defineProperty(exports2,"__esModule",{value:true})}))}});var import_parser=__toESM(require_lib(),1);import{createHash}from"node:crypto";import{existsSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,writeFileSync,watch}from"node:fs";import{dirname,extname,isAbsolute,join,relative,resolve,sep}from"node:path";import{fileURLToPath}from"node:url";var VERSION=JSON.parse(readFileSync(new URL("../package.json",import.meta.url),"utf8")).version;var MANIFEST="yuanze-text-manifest.json";var CONTRACT="yuanze-click-text-v1";var hash=data=>createHash("sha256").update(data).digest("hex");var attr=(node,key)=>node.startTag.attributes.find(item=>item.key===key);var elements=node=>(node.children??[]).filter(item=>item.type==="WXElement");var nativeEvents=/^(?:bind|catch|mut-bind):?(tap|longpress|longtap)$/;var clickEvent=/^(?:bind|catch):?click$/;var sensitiveKey=/^(data-(?:sensitive|no-track|yz-sensitive|yz-no-track|track-sensitive))$/;var sensitiveId=/(?:^|[-_:])(captcha\d*|verify|verification|otp|password|passwd|credential)(?:$|[-_:])/i;var opaqueTags=new Set(["input","textarea","web-view","canvas","video","camera","map","rich-text"]);var virtualTags=new Set(["block","template","include","import","wxs"]);function componentType(node,usingComponents){const path=usingComponents[node.name];if(typeof path!=="string")return void 0;return/(?:^|\/)tdesign-miniprogram\/(button|grid-item|icon)\/\1$/.exec(path)?.[1]}function isSensitive(node){return opaqueTags.has(node.name)||node.startTag.attributes.some(item=>sensitiveKey.test(item.key))||/(?:^|\s)yz-no-track(?:\s|$)/.test(attr(node,"class")?.value??"")||sensitiveId.test(attr(node,"id")?.value??"")}function matches(node,selector){if(!/^(?:[.#])?[\w-]+$/.test(selector)){throw new Error("Text rules support one tag, .class or #id selector")}if(selector.startsWith("."))return(attr(node,"class")?.value??"").split(/\s+/).includes(selector.slice(1));if(selector.startsWith("#"))return attr(node,"id")?.value===selector.slice(1);return node.name===selector}function quote(value){if(!value.includes('"'))return'"'+value+'"';if(!value.includes("'"))return"'"+value+"'";if(value.includes("{{"))return void 0;return'"'+value.replace(/"/g,"&quot;")+'"'}function labelOf(node,usingComponents,top=true){if(isSensitive(node))return void 0;if(!top&&node.startTag.attributes.some(item=>["wx:for","wx:if","wx:elif","wx:else","slot"].includes(item.key)||nativeEvents.test(item.key)||clickEvent.test(item.key)))return void 0;const type=componentType(node,usingComponents);if(type==="grid-item")return attr(node,"text")?.rawValue;if(type==="icon"||["image","icon"].includes(node.name))return"";if(["template","include","import","wxs","slot"].includes(node.name))return void 0;if(usingComponents[node.name]&&type!=="button")return void 0;const children=node.children??[];const content=attr(node,"content");if(type==="button"&&content&&children.length===0)return content.rawValue;const candidates=[];let inline="";for(const child of children){if(child.type==="WXText")inline+=child.value;else if(child.type==="WXInterpolation")inline+=child.rawValue;else if(child.type==="WXElement"){const label=labelOf(child,usingComponents,false);if(label===void 0)return void 0;if(label)candidates.push(label)}else if(child.type!=="WXComment")return void 0}if(inline.trim())candidates.push(quote(inline.trim()));return candidates.length===0?"":candidates.length===1?candidates[0]:void 0}function selectedLabel(node,usingComponents,rule){if(!rule)return labelOf(node,usingComponents);const found=[];function visit(current,top){if(!top&&(isSensitive(current)||current.startTag.attributes.some(item=>["wx:for","wx:if","wx:elif","wx:else","slot"].includes(item.key)||nativeEvents.test(item.key)||clickEvent.test(item.key))))return;if(matches(current,rule.textSelector))found.push(current);for(const child of elements(current))visit(child,false)}visit(node,true);return found.length===1?labelOf(found[0],usingComponents):void 0}function transformWxml(source,{file="page.wxml",usingComponents={},rules=[]}={}){const ast=(0,import_parser.parse)(source);if(ast.errors.length)throw new Error(file+": invalid WXML");const edits=[];const report=[];function visit(node,sensitive=false,unsupportedScope=false){if(node.type!=="WXElement")return;sensitive||=isSensitive(node);unsupportedScope||=["template","wxs"].includes(node.name);const attributes=node.startTag.attributes;const type=componentType(node,usingComponents);const events=attributes.filter(item=>nativeEvents.test(item.key)||type==="grid-item"&&clickEvent.test(item.key));const unsupportedClick=attributes.some(item=>clickEvent.test(item.key))&&type!=="grid-item";const additions=[];const add=(key,value)=>{if(!attr(node,key))additions.push(key+"="+value)};if(sensitive&&!virtualTags.has(node.name))add("mark:yzSensitive",'"1"');const named=attr(node,"data-track");if(named)add("mark:yzNamed",named.rawValue||'""');if(unsupportedClick)report.push({file,line:node.loc.start.line,tag:node.name,status:"unsupported-event"});if(events.length){let status;if(attr(node,"data-yz-capture")){status="already-marked"}else if(sensitive||unsupportedScope){status=sensitive?"sensitive":"unsupported-template"}else if(events.some(event=>!/^[A-Za-z_$][\w$]*$/.test(event.value??""))){status="dynamic-handler"}else{if(attr(node,"data-yz-owner")||attr(node,"mark:yzOwner")||attr(node,"data-yz-adapter")){throw new Error(file+": reserved text metadata conflicts with generated ownership")}const id="yz"+hash(file+":"+node.start).slice(0,16);const applicable=rules.filter(rule=>(!rule.file||rule.file===file)&&matches(node,rule.selector));if(applicable.length>1)throw new Error(file+": overlapping text rules");const label=selectedLabel(node,usingComponents,applicable[0]);add("data-yz-capture",'"1"');add("data-yz-owner",quote(id));add("mark:yzOwner",quote(id));if(type==="grid-item"&&events.some(event=>clickEvent.test(event.key))){add("data-yz-adapter",'"tdesign-grid-item"')}if(label)add("data-yz-text",label);status=attr(node,"data-yz-text")?"manual":label?applicable.length?"rule":type?"component":"automatic":"no-reliable-label"}report.push({file,line:node.loc.start.line,tag:node.name,status})}if(additions.length){edits.push({at:node.startTag.end-(node.startTag.selfClosing?1:0),text:" "+additions.join(" ")})}for(const child of elements(node))visit(child,sensitive,unsupportedScope)}for(const node of ast.body)visit(node);let output=source;for(const edit of edits.sort((a,b)=>b.at-a.at)){output=output.slice(0,edit.at)+edit.text+output.slice(edit.at)}if((0,import_parser.parse)(output).errors.length)throw new Error(file+": generated invalid WXML");return{source:output,report}}var allowedExtensions=new Set([".js",".json",".wxml",".wxss",".wxs",".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".ttf",".otf",".woff",".woff2",".mp3",".mp4",".wav",".wasm"]);function within(root,path){const rel=relative(root,path);return rel!==""&&rel!==".."&&!rel.startsWith(".."+sep)&&!isAbsolute(rel)}function readJson(path){return JSON.parse(readFileSync(path,"utf8"))}function noSymlinks(root,path){let current=root;for(const part of relative(root,path).split(sep)){current=join(current,part);if(existsSync(current)&&lstatSync(current).isSymbolicLink()){throw new Error("Symbolic source/output path is not supported")}}}function prepareProject(configFile,mode="prepare"){if(!["prepare","check","analyze"].includes(mode))throw new Error("Unknown prepare mode");const configPath=resolve(configFile);const project=dirname(configPath);const config=readJson(configPath);const root=resolve(project,config.sourceRoot??".");const output=resolve(project,config.outputRoot??".yuanze-text");if(root!==project&&!within(project,root)||!within(project,output)||root===output||within(output,root)){throw new Error("Source and output must be distinct directories inside the project")}if(lstatSync(root).isSymbolicLink())throw new Error("Symbolic source root is not supported");noSymlinks(project,root);noSymlinks(project,output);const projectConfig=readJson(join(project,"project.config.json"));if(mode!=="analyze"&&resolve(project,projectConfig.miniprogramRoot??".")!==output){throw new Error("project.config.json miniprogramRoot must point to outputRoot")}const app=readJson(join(root,"app.json"));const roots=new Set(["app.js","app.json","app.wxss","sitemap.json","pages","components","utils","assets","images","styles","behaviors","miniprogram_npm",...(app.pages??[]).map(page=>page.split("/")[0]),...(app.subPackages??app.subpackages??[]).map(pkg=>pkg.root.split("/")[0]),...config.include??[]]);const files=new Map;function scan(path){if(path===output||within(output,path))return;const rel=relative(root,path).split(sep).join("/");if(!within(root,path))throw new Error("Include paths must stay inside sourceRoot");const info=lstatSync(path);if(info.isSymbolicLink())throw new Error("Symbolic source entry: "+rel);if(info.isDirectory()){for(const name of readdirSync(path).sort()){if(!name.startsWith(".")&&name!=="node_modules"&&name!=="__tests__"){scan(join(path,name))}}}else if(info.isFile()&&allowedExtensions.has(extname(path))&&!/\.(?:test|spec)\.[^.]+$/.test(path)){files.set(rel,readFileSync(path))}}for(const entry of[...roots].sort()){if(typeof entry!=="string"||isAbsolute(entry))throw new Error("Invalid include path");const path=resolve(root,entry);if(!within(root,path))throw new Error("Include paths must stay inside sourceRoot");noSymlinks(root,path);if(existsSync(path))scan(path)}const generated=new Map(files);const report=[];for(const[file,source]of files){if(!file.endsWith(".wxml")||file.startsWith("miniprogram_npm/"))continue;const jsonFile=file.slice(0,-5)+".json";const local=files.has(jsonFile)?JSON.parse(files.get(jsonFile).toString("utf8")):{};const result=transformWxml(source.toString("utf8"),{file,usingComponents:{...app.usingComponents,...local.usingComponents},rules:config.rules??[]});generated.set(file,Buffer.from(result.source));report.push(...result.report)}const sourceHashes=Object.fromEntries([...files].map(([file,data])=>[file,hash(data)]));const outputHashes=Object.fromEntries([...generated].map(([file,data])=>[file,hash(data)]));const manifest={contract:CONTRACT,sdkVersion:VERSION,toolHash:hash(readFileSync(fileURLToPath(import.meta.url))),configHash:hash(JSON.stringify(config)),sourceHashes,outputHashes,report};if(mode==="analyze")return manifest;const marker=join(output,MANIFEST);if(existsSync(output)){if(lstatSync(output).isSymbolicLink()||!existsSync(marker)||readJson(marker).contract!==CONTRACT){throw new Error("Output is not owned by the text tool; choose an empty outputRoot")}}if(mode==="check"){let checkEntries2=function(dir){for(const entry of readdirSync(dir,{withFileTypes:true})){const path=join(dir,entry.name);const file=relative(output,path).split(sep).join("/");if(entry.isSymbolicLink())throw new Error("Generated output contains a symbolic link");if(entry.isDirectory())checkEntries2(path);else if(file!==MANIFEST&&!Object.hasOwn(outputHashes,file)){throw new Error("Unexpected generated output: "+file)}}};var checkEntries=checkEntries2;if(!existsSync(marker)||JSON.stringify(readJson(marker))!==JSON.stringify(manifest)){throw new Error("Generated output is stale; run prepare")}for(const[file,expected]of Object.entries(outputHashes)){const path=join(output,file);if(!existsSync(path)||lstatSync(path).isSymbolicLink()||hash(readFileSync(path))!==expected)throw new Error("Generated output changed: "+file)}checkEntries2(output);return manifest}mkdirSync(dirname(output),{recursive:true});const staging=mkdtempSync(join(dirname(output),".yz-text-"));let backup;try{for(const[file,data]of generated){const path=join(staging,file);mkdirSync(dirname(path),{recursive:true});writeFileSync(path,data)}writeFileSync(join(staging,MANIFEST),JSON.stringify(manifest,null,2)+"\n");if(existsSync(output)){backup=staging+"-previous";renameSync(output,backup)}try{renameSync(staging,output)}catch(error){if(backup)renameSync(backup,output);backup=void 0;throw error}if(backup)rmSync(backup,{recursive:true})}finally{if(existsSync(staging))rmSync(staging,{recursive:true})}return manifest}function summary(manifest){const counts={};for(const entry of manifest.report)counts[entry.status]=(counts[entry.status]??0)+1;return{sdkVersion:manifest.sdkVersion,files:Object.keys(manifest.outputHashes).length,counts}}function main(){const[mode="prepare",config="yuanze-text.config.json",...extra]=process.argv.slice(2);if(extra.length||!["prepare","check","analyze","watch"].includes(mode)){throw new Error("Usage: yuanze-miniprogram-text prepare|check|analyze|watch [config.json]")}const run=()=>{const manifest=prepareProject(config,mode==="watch"?"prepare":mode);console.log(JSON.stringify(summary(manifest)))};run();if(mode!=="watch")return;const configPath=resolve(config);const project=dirname(configPath);const settings=readJson(configPath);const output=resolve(project,settings.outputRoot??".yuanze-text");let timer;watch(project,{recursive:true},(_,filename)=>{if(!filename)return;const path=resolve(project,filename);if(path===output||within(output,path)||filename.split(sep).some(part=>part==="node_modules"||part.startsWith(".")&&part!=="."))return;clearTimeout(timer);timer=setTimeout(()=>{try{run()}catch(error){console.error(error.message)}},150)})}if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===fileURLToPath(import.meta.url)){try{main()}catch(error){console.error(error.message);process.exitCode=1}}export{prepareProject,transformWxml};
package/index.d.ts CHANGED
@@ -15,6 +15,7 @@ export type TrackerInstance = {
15
15
  applyIdentitySnapshot(snapshot: IdentitySnapshot): boolean;
16
16
  dispose(): void;
17
17
  readonly pending: number;
18
+ readonly droppedEvents: number;
18
19
  };
19
20
 
20
21
  export type IdentifyOptions = {
package/package.json CHANGED
@@ -1,13 +1,17 @@
1
1
  {
2
2
  "name": "@yuanze_dev/tracker-miniprogram",
3
- "version": "0.10.1",
3
+ "version": "0.11.1",
4
4
  "description": "原则数据埋点 SDK · 微信小程序",
5
5
  "license": "UNLICENSED",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./index.d.ts",
8
+ "bin": {
9
+ "yuanze-miniprogram-text": "./dist/prepare.mjs"
10
+ },
8
11
  "files": [
9
12
  "dist",
10
- "index.d.ts"
13
+ "index.d.ts",
14
+ "THIRD_PARTY_LICENSES.txt"
11
15
  ],
12
16
  "sideEffects": false,
13
17
  "publishConfig": {